chiark / gitweb /
ce5d7d860b6360cb608f323406bba018e1fa7971
[disorder] / disobedience / playlists.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2008, 2009 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file disobedience/playlists.c
21  * @brief Playlist support for Disobedience
22  *
23  * The playlists management window contains:
24  * - the playlist picker (a list of all playlists) TODO should be a tree!
25  * - an add button
26  * - a delete button
27  * - the playlist editor (a d+d-capable view of the currently picked playlist)
28  * - a close button   TODO
29  *
30  * This file also maintains the playlist menu, allowing playlists to be
31  * activated from the main window's menu.
32  *
33  * Internally we maintain the playlist list, which is just the current list of
34  * playlists.  Changes to this are reflected in the playlist menu and the
35  * playlist picker.
36  *
37  */
38 #include "disobedience.h"
39 #include "queue-generic.h"
40 #include "popup.h"
41 #include "validity.h"
42
43 #if PLAYLISTS
44
45 static void playlist_list_received_playlists(void *v,
46                                              const char *err,
47                                              int nvec, char **vec);
48 static void playlist_editor_fill(const char *event,
49                                  void *eventdata,
50                                  void *callbackdata);
51 static int playlist_playall_sensitive(void *extra);
52 static void playlist_playall_activate(GtkMenuItem *menuitem,
53                                       gpointer user_data);
54 static int playlist_remove_sensitive(void *extra) ;
55 static void playlist_remove_activate(GtkMenuItem *menuitem,
56                                      gpointer user_data);
57 static void playlist_new_locked(void *v, const char *err);
58 static void playlist_new_retrieved(void *v, const char *err,
59                                    int nvec,
60                                    char **vec);
61 static void playlist_new_created(void *v, const char *err);
62 static void playlist_new_unlocked(void *v, const char *err);
63 static void playlist_new_entry_edited(GtkEditable *editable,
64                                       gpointer user_data);
65 static void playlist_new_button_toggled(GtkToggleButton *tb,
66                                         gpointer userdata);
67 static void playlist_new_changed(const char *event,
68                                  void *eventdata,
69                                  void *callbackdata);
70 static const char *playlist_new_valid(void);
71 static void playlist_new_details(char **namep,
72                                  char **fullnamep,
73                                  gboolean *sharedp,
74                                  gboolean *publicp,
75                                  gboolean *privatep);
76 static void playlist_new_ok(GtkButton *button,
77                             gpointer userdata);
78 static void playlist_new_cancel(GtkButton *button,
79                                 gpointer userdata);
80 static void playlists_editor_received_tracks(void *v,
81                                              const char *err,
82                                              int nvec, char **vec);
83 static void playlist_window_destroyed(GtkWidget *widget,
84                                       GtkWidget **widget_pointer);
85 static gboolean playlist_window_keypress(GtkWidget *widget,
86                                          GdkEventKey *event,
87                                          gpointer user_data);
88 static int playlistcmp(const void *ap, const void *bp);
89 static void playlist_remove_locked(void *v, const char *err);
90 void playlist_remove_retrieved(void *v, const char *err,
91                                int nvec,
92                                char **vec);
93 static void playlist_remove_updated(void *v, const char *err);
94 static void playlist_remove_unlocked(void *v, const char *err);
95
96 /** @brief Playlist editing window */
97 static GtkWidget *playlist_window;
98
99 /** @brief Columns for the playlist editor */
100 static const struct queue_column playlist_columns[] = {
101   { "Artist", column_namepart, "artist", COL_EXPAND|COL_ELLIPSIZE },
102   { "Album",  column_namepart, "album",  COL_EXPAND|COL_ELLIPSIZE },
103   { "Title",  column_namepart, "title",  COL_EXPAND|COL_ELLIPSIZE },
104   { "Length", column_length,   0,        COL_RIGHT }
105 };
106
107 /** @brief Pop-up menu for playlist editor
108  *
109  * Status:
110  * - track properties works but, bizarrely, raises the main window
111  * - play track works
112  * - play playlist works
113  * - select/deselect all work
114  */
115 static struct menuitem playlist_menuitems[] = {
116   { "Track properties", ql_properties_activate, ql_properties_sensitive, 0, 0 },
117   { "Play track", ql_play_activate, ql_play_sensitive, 0, 0 },
118   { "Play playlist", playlist_playall_activate, playlist_playall_sensitive, 0, 0 },
119   { "Remove track from queue", playlist_remove_activate, playlist_remove_sensitive, 0, 0 },
120   { "Select all tracks", ql_selectall_activate, ql_selectall_sensitive, 0, 0 },
121   { "Deselect all tracks", ql_selectnone_activate, ql_selectnone_sensitive, 0, 0 },
122 };
123
124 /** @brief Queuelike for editing a playlist */
125 static struct queuelike ql_playlist = {
126   .name = "playlist",
127   .columns = playlist_columns,
128   .ncolumns = sizeof playlist_columns / sizeof *playlist_columns,
129   .menuitems = playlist_menuitems,
130   .nmenuitems = sizeof playlist_menuitems / sizeof *playlist_menuitems,
131   //.drop = playlist_drop  //TODO
132 };
133
134 /* Maintaining the list of playlists ---------------------------------------- */
135
136 /** @brief Current list of playlists or NULL */
137 char **playlists;
138
139 /** @brief Count of playlists */
140 int nplaylists;
141
142 /** @brief Schedule an update to the list of playlists
143  *
144  * Called periodically and when a playlist is created or deleted.
145  */
146 static void playlist_list_update(const char attribute((unused)) *event,
147                                  void attribute((unused)) *eventdata,
148                                  void attribute((unused)) *callbackdata) {
149   disorder_eclient_playlists(client, playlist_list_received_playlists, 0);
150 }
151
152 /** @brief Called with a new list of playlists */
153 static void playlist_list_received_playlists(void attribute((unused)) *v,
154                                              const char *err,
155                                              int nvec, char **vec) {
156   if(err) {
157     playlists = 0;
158     nplaylists = -1;
159     /* Probably means server does not support playlists */
160   } else {
161     playlists = vec;
162     nplaylists = nvec;
163     qsort(playlists, nplaylists, sizeof (char *), playlistcmp);
164   }
165   /* Tell our consumers */
166   event_raise("playlists-updated", 0);
167 }
168
169 /** @brief qsort() callback for playlist name comparison */
170 static int playlistcmp(const void *ap, const void *bp) {
171   const char *a = *(char **)ap, *b = *(char **)bp;
172   const char *ad = strchr(a, '.'), *bd = strchr(b, '.');
173   int c;
174
175   /* Group owned playlists by owner */
176   if(ad && bd) {
177     const int adn = ad - a, bdn = bd - b;
178     if((c = strncmp(a, b, adn < bdn ? adn : bdn)))
179       return c;
180     /* Lexical order within playlists of a single owner */
181     return strcmp(ad + 1, bd + 1);
182   }
183
184   /* Owned playlists after shared ones */
185   if(ad) {
186     return 1;
187   } else if(bd) {
188     return -1;
189   }
190
191   /* Lexical order of shared playlists */
192   return strcmp(a, b);
193 }
194
195 /* Playlists menu ----------------------------------------------------------- */
196
197 static void playlist_menu_playing(void attribute((unused)) *v,
198                                   const char *err) {
199   if(err)
200     popup_protocol_error(0, err);
201 }
202
203 /** @brief Play received playlist contents
204  *
205  * Passed as a completion callback by menu_activate_playlist().
206  */
207 static void playlist_menu_received_content(void attribute((unused)) *v,
208                                            const char *err,
209                                            int nvec, char **vec) {
210   if(err) {
211     popup_protocol_error(0, err);
212     return;
213   }
214   for(int n = 0; n < nvec; ++n)
215     disorder_eclient_play(client, vec[n], playlist_menu_playing, NULL);
216 }
217
218 /** @brief Called to activate a playlist
219  *
220  * Called when the menu item for a playlist is clicked.
221  */
222 static void playlist_menu_activate(GtkMenuItem *menuitem,
223                                    gpointer attribute((unused)) user_data) {
224   GtkLabel *label = GTK_LABEL(GTK_BIN(menuitem)->child);
225   const char *playlist = gtk_label_get_text(label);
226
227   disorder_eclient_playlist_get(client, playlist_menu_received_content,
228                                 playlist, NULL);
229 }
230
231 /** @brief Called when the playlists change
232  *
233  * Naively refills the menu.  The results might be unsettling if the menu is
234  * currently open, but this is hopefuly fairly rare.
235  */
236 static void playlist_menu_changed(const char attribute((unused)) *event,
237                                   void attribute((unused)) *eventdata,
238                                   void attribute((unused)) *callbackdata) {
239   if(!playlists_menu)
240     return;                             /* OMG too soon */
241   GtkMenuShell *menu = GTK_MENU_SHELL(playlists_menu);
242   while(menu->children)
243     gtk_container_remove(GTK_CONTAINER(menu), GTK_WIDGET(menu->children->data));
244   /* NB nplaylists can be -1 as well as 0 */
245   for(int n = 0; n < nplaylists; ++n) {
246     GtkWidget *w = gtk_menu_item_new_with_label(playlists[n]);
247     g_signal_connect(w, "activate", G_CALLBACK(playlist_menu_activate), 0);
248     gtk_widget_show(w);
249     gtk_menu_shell_append(menu, w);
250   }
251   gtk_widget_set_sensitive(menu_playlists_widget,
252                            nplaylists > 0);
253   gtk_widget_set_sensitive(menu_editplaylists_widget,
254                            nplaylists >= 0);
255 }
256
257 /* Popup to create a new playlist ------------------------------------------- */
258
259 /** @brief New-playlist popup */
260 static GtkWidget *playlist_new_window;
261
262 /** @brief Text entry in new-playlist popup */
263 static GtkWidget *playlist_new_entry;
264
265 /** @brief Label for displaying feedback on what's wrong */
266 static GtkWidget *playlist_new_info;
267
268 /** @brief "Shared" radio button */
269 static GtkWidget *playlist_new_shared;
270
271 /** @brief "Public" radio button */
272 static GtkWidget *playlist_new_public;
273
274 /** @brief "Private" radio button */
275 static GtkWidget *playlist_new_private;
276
277 /** @brief Buttons for new-playlist popup */
278 static struct button playlist_new_buttons[] = {
279   {
280     .stock = GTK_STOCK_OK,
281     .clicked = playlist_new_ok,
282     .tip = "Create new playlist"
283   },
284   {
285     .stock = GTK_STOCK_CANCEL,
286     .clicked = playlist_new_cancel,
287     .tip = "Do not create new playlist"
288   }
289 };
290 #define NPLAYLIST_NEW_BUTTONS (sizeof playlist_new_buttons / sizeof *playlist_new_buttons)
291
292 /** @brief Pop up a new window to enter the playlist name and details */
293 static void playlist_new_playlist(void) {
294   assert(playlist_new_window == NULL);
295   playlist_new_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
296   g_signal_connect(playlist_new_window, "destroy",
297                    G_CALLBACK(gtk_widget_destroyed), &playlist_new_window);
298   gtk_window_set_title(GTK_WINDOW(playlist_new_window), "Create new playlist");
299   /* Window will be modal, suppressing access to other windows */
300   gtk_window_set_modal(GTK_WINDOW(playlist_new_window), TRUE);
301   gtk_window_set_transient_for(GTK_WINDOW(playlist_new_window),
302                                GTK_WINDOW(playlist_window));
303
304   /* Window contents will use a table (grid) layout */
305   GtkWidget *table = gtk_table_new(3, 3, FALSE/*!homogeneous*/);
306
307   /* First row: playlist name */
308   gtk_table_attach_defaults(GTK_TABLE(table),
309                             gtk_label_new("Playlist name"),
310                             0, 1, 0, 1);
311   playlist_new_entry = gtk_entry_new();
312   g_signal_connect(playlist_new_entry, "changed",
313                    G_CALLBACK(playlist_new_entry_edited), NULL);
314   gtk_table_attach_defaults(GTK_TABLE(table),
315                             playlist_new_entry,
316                             1, 3, 0, 1);
317
318   /* Second row: radio buttons to choose type */
319   playlist_new_shared = gtk_radio_button_new_with_label(NULL, "shared");
320   playlist_new_public
321     = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(playlist_new_shared),
322                                                   "public");
323   playlist_new_private
324     = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(playlist_new_shared),
325                                                   "private");
326   g_signal_connect(playlist_new_shared, "toggled",
327                    G_CALLBACK(playlist_new_button_toggled), NULL);
328   g_signal_connect(playlist_new_public, "toggled",
329                    G_CALLBACK(playlist_new_button_toggled), NULL);
330   g_signal_connect(playlist_new_private, "toggled",
331                    G_CALLBACK(playlist_new_button_toggled), NULL);
332   gtk_table_attach_defaults(GTK_TABLE(table), playlist_new_shared, 0, 1, 1, 2);
333   gtk_table_attach_defaults(GTK_TABLE(table), playlist_new_public, 1, 2, 1, 2);
334   gtk_table_attach_defaults(GTK_TABLE(table), playlist_new_private, 2, 3, 1, 2);
335
336   /* Third row: info bar saying why not */
337   playlist_new_info = gtk_label_new("");
338   gtk_table_attach_defaults(GTK_TABLE(table), playlist_new_info,
339                             0, 3, 2, 3);
340
341   /* Fourth row: ok/cancel buttons */
342   GtkWidget *hbox = create_buttons_box(playlist_new_buttons,
343                                        NPLAYLIST_NEW_BUTTONS,
344                                        gtk_hbox_new(FALSE, 0));
345   gtk_table_attach_defaults(GTK_TABLE(table), hbox, 0, 3, 3, 4);
346
347   gtk_container_add(GTK_CONTAINER(playlist_new_window),
348                     frame_widget(table, NULL));
349
350   /* Set initial state of OK button */
351   playlist_new_changed(0,0,0);
352
353   /* TODO: return should = OK, escape should = cancel */
354   
355   /* Display the window */
356   gtk_widget_show_all(playlist_new_window);
357 }
358
359 /** @brief Called when 'ok' is clicked in new-playlist popup */
360 static void playlist_new_ok(GtkButton attribute((unused)) *button,
361                             gpointer attribute((unused)) userdata) {
362   gboolean shared, public, private;
363   char *name, *fullname;
364   playlist_new_details(&name, &fullname, &shared, &public, &private);
365
366   /* We need to:
367    * - lock the playlist
368    * - check it doesn't exist
369    * - set sharing (which will create it empty
370    * - unlock it
371    *
372    * TODO we should freeze the window while this is going on to stop a second
373    * click.
374    */
375   disorder_eclient_playlist_lock(client, playlist_new_locked, fullname,
376                                  fullname);
377 }
378
379 /** @brief Called when the proposed new playlist has been locked */
380 static void playlist_new_locked(void *v, const char *err) {
381   char *fullname = v;
382   if(err) {
383     popup_protocol_error(0, err);
384     return;
385   }
386   disorder_eclient_playlist_get(client, playlist_new_retrieved,
387                                 fullname, fullname);
388 }
389
390 /** @brief Called when the proposed new playlist's contents have been retrieved
391  *
392  * ...or rather, normally, when it's been reported that it does not exist.
393  */
394 static void playlist_new_retrieved(void *v, const char *err,
395                                    int nvec,
396                                    char attribute((unused)) **vec) {
397   char *fullname = v;
398   if(!err && nvec != -1)
399     /* A rare case but not in principle impossible */
400     err = "A playlist with that name already exists.";
401   if(err) {
402     popup_protocol_error(0, err);
403     disorder_eclient_playlist_unlock(client, playlist_new_unlocked, fullname);
404     return;
405   }
406   gboolean shared, public, private;
407   playlist_new_details(0, 0, &shared, &public, &private);
408   disorder_eclient_playlist_set_share(client, playlist_new_created, fullname,
409                                       public ? "public"
410                                       : private ? "private"
411                                       : "shared",
412                                       fullname);
413 }
414
415 /** @brief Called when the new playlist has been created */
416 static void playlist_new_created(void attribute((unused)) *v, const char *err) {
417   if(err) {
418     popup_protocol_error(0, err);
419     return;
420   }
421   disorder_eclient_playlist_unlock(client, playlist_new_unlocked, NULL);
422   // TODO arrange for the new playlist to be selected
423 }
424
425 /** @brief Called when the newly created playlist has unlocked */
426 static void playlist_new_unlocked(void attribute((unused)) *v, const char *err) {
427   if(err)
428     popup_protocol_error(0, err);
429   /* Pop down the creation window */
430   gtk_widget_destroy(playlist_new_window);
431 }
432
433 /** @brief Called when 'cancel' is clicked in new-playlist popup */
434 static void playlist_new_cancel(GtkButton attribute((unused)) *button,
435                                 gpointer attribute((unused)) userdata) {
436   gtk_widget_destroy(playlist_new_window);
437 }
438
439 /** @brief Called when some radio button in the new-playlist popup changes */
440 static void playlist_new_button_toggled(GtkToggleButton attribute((unused)) *tb,
441                                         gpointer attribute((unused)) userdata) {
442   playlist_new_changed(0,0,0);
443 }
444
445 /** @brief Called when the text entry field in the new-playlist popup changes */
446 static void playlist_new_entry_edited(GtkEditable attribute((unused)) *editable,
447                                       gpointer attribute((unused)) user_data) {
448   playlist_new_changed(0,0,0);
449 }
450
451 /** @brief Called to update new playlist window state
452  *
453  * This is called whenever one the text entry or radio buttons changed, and
454  * also when the set of known playlists changes.  It determines whether the new
455  * playlist would be creatable and sets the sensitivity of the OK button
456  * and info display accordingly.
457  */
458 static void playlist_new_changed(const char attribute((unused)) *event,
459                                  void attribute((unused)) *eventdata,
460                                  void attribute((unused)) *callbackdata) {
461   if(!playlist_new_window)
462     return;
463   const char *reason = playlist_new_valid();
464   gtk_widget_set_sensitive(playlist_new_buttons[0].widget,
465                            !reason);
466   gtk_label_set_text(GTK_LABEL(playlist_new_info), reason);
467 }
468
469 /** @brief Test whether the new-playlist window settings are valid
470  * @return NULL on success or an error string if not
471  */
472 static const char *playlist_new_valid(void) {
473   gboolean shared, public, private;
474   char *name, *fullname;
475   playlist_new_details(&name, &fullname, &shared, &public, &private);
476   if(!(shared || public || private))
477     return "No type set.";
478   if(!*name)
479     return "";
480   /* See if the result is valid */
481   if(!valid_username(name)
482      || playlist_parse_name(fullname, NULL, NULL))
483     return "Not a valid playlist name.";
484   /* See if the result clashes with an existing name.  This is not a perfect
485    * check, the playlist might be created after this point but before we get a
486    * chance to disable the "OK" button.  However when we try to create the
487    * playlist we will first try to retrieve it, with a lock held, so we
488    * shouldn't end up overwriting anything. */
489   for(int n = 0; n < nplaylists; ++n)
490     if(!strcmp(playlists[n], fullname)) {
491       if(shared)
492         return "A shared playlist with that name already exists.";
493       else
494         return "You already have a playlist with that name.";
495     }
496   /* As far as we can tell creation would work */
497   return NULL;
498 }
499
500 /** @brief Get entered new-playlist details
501  * @param namep Where to store entered name (or NULL)
502  * @param fullnamep Where to store computed full name (or NULL)
503  * @param sharep Where to store 'shared' flag (or NULL)
504  * @param publicp Where to store 'public' flag (or NULL)
505  * @param privatep Where to store 'private' flag (or NULL)
506  */
507 static void playlist_new_details(char **namep,
508                                  char **fullnamep,
509                                  gboolean *sharedp,
510                                  gboolean *publicp,
511                                  gboolean *privatep) {
512   gboolean shared, public, private;
513   g_object_get(playlist_new_shared, "active", &shared, (char *)NULL);
514   g_object_get(playlist_new_public, "active", &public, (char *)NULL);
515   g_object_get(playlist_new_private, "active", &private, (char *)NULL);
516   char *gname = gtk_editable_get_chars(GTK_EDITABLE(playlist_new_entry),
517                                        0, -1); /* name owned by calle */
518   char *name = xstrdup(gname);
519   g_free(gname);
520   if(sharedp) *sharedp = shared;
521   if(publicp) *publicp = public;
522   if(privatep) *privatep = private;
523   if(namep) *namep = name;
524   if(fullnamep) {
525     if(*sharedp) *fullnamep = *namep;
526     else byte_xasprintf(fullnamep, "%s.%s", config->username, name);
527   }
528 }
529
530 /* Playlist picker ---------------------------------------------------------- */
531
532 /** @brief Delete button */
533 static GtkWidget *playlist_picker_delete_button;
534
535 /** @brief Tree model for list of playlists */
536 static GtkListStore *playlist_picker_list;
537
538 /** @brief Selection for list of playlists */
539 static GtkTreeSelection *playlist_picker_selection;
540
541 /** @brief Currently selected playlist */
542 static const char *playlist_picker_selected;
543
544 /** @brief (Re-)populate the playlist picker tree model */
545 static void playlist_picker_fill(const char attribute((unused)) *event,
546                                  void attribute((unused)) *eventdata,
547                                  void attribute((unused)) *callbackdata) {
548   GtkTreeIter iter[1];
549
550   if(!playlist_window)
551     return;
552   if(!playlist_picker_list)
553     playlist_picker_list = gtk_list_store_new(1, G_TYPE_STRING);
554   const char *was_selected = playlist_picker_selected;
555   gtk_list_store_clear(playlist_picker_list); /* clears playlists_selected */
556   for(int n = 0; n < nplaylists; ++n) {
557     gtk_list_store_insert_with_values(playlist_picker_list, iter,
558                                       n                /*position*/,
559                                       0, playlists[n], /* column 0 */
560                                       -1);             /* no more cols */
561     /* Reselect the selected playlist */
562     if(was_selected && !strcmp(was_selected, playlists[n]))
563       gtk_tree_selection_select_iter(playlist_picker_selection, iter);
564   }
565   /* TODO deselecting then reselecting the current playlist resets the playlist
566    * editor, which trashes the user's selection. */
567 }
568
569 /** @brief Called when the selection might have changed */
570 static void playlist_picker_selection_changed(GtkTreeSelection attribute((unused)) *treeselection,
571                                               gpointer attribute((unused)) user_data) {
572   GtkTreeIter iter;
573   char *gselected, *selected;
574   
575   /* Identify the current selection */
576   if(gtk_tree_selection_get_selected(playlist_picker_selection, 0, &iter)) {
577     gtk_tree_model_get(GTK_TREE_MODEL(playlist_picker_list), &iter,
578                        0, &gselected, -1);
579     selected = xstrdup(gselected);
580     g_free(gselected);
581   } else
582     selected = 0;
583   /* Set button sensitivity according to the new state */
584   if(selected)
585     gtk_widget_set_sensitive(playlist_picker_delete_button, 1);
586   else
587     gtk_widget_set_sensitive(playlist_picker_delete_button, 0);
588   /* Eliminate no-change cases */
589   if(!selected && !playlist_picker_selected)
590     return;
591   if(selected
592      && playlist_picker_selected
593      && !strcmp(selected, playlist_picker_selected))
594     return;
595   /* Record the new state */
596   playlist_picker_selected = selected;
597   /* Re-initalize the queue */
598   ql_new_queue(&ql_playlist, NULL);
599   playlist_editor_fill(NULL, (void *)playlist_picker_selected, NULL);
600 }
601
602 /** @brief Called when the 'add' button is pressed */
603 static void playlist_picker_add(GtkButton attribute((unused)) *button,
604                                 gpointer attribute((unused)) userdata) {
605   /* Unselect whatever is selected TODO why?? */
606   gtk_tree_selection_unselect_all(playlist_picker_selection);
607   playlist_new_playlist();
608 }
609
610 /** @brief Called when playlist deletion completes */
611 static void playlists_picker_delete_completed(void attribute((unused)) *v,
612                                               const char *err) {
613   if(err)
614     popup_protocol_error(0, err);
615 }
616
617 /** @brief Called when the 'Delete' button is pressed */
618 static void playlist_picker_delete(GtkButton attribute((unused)) *button,
619                                    gpointer attribute((unused)) userdata) {
620   GtkWidget *yesno;
621   int res;
622
623   if(!playlist_picker_selected)
624     return;                             /* shouldn't happen */
625   yesno = gtk_message_dialog_new(GTK_WINDOW(playlist_window),
626                                  GTK_DIALOG_MODAL,
627                                  GTK_MESSAGE_QUESTION,
628                                  GTK_BUTTONS_YES_NO,
629                                  "Do you really want to delete playlist %s?"
630                                  " This action cannot be undone.",
631                                  playlist_picker_selected);
632   res = gtk_dialog_run(GTK_DIALOG(yesno));
633   gtk_widget_destroy(yesno);
634   if(res == GTK_RESPONSE_YES) {
635     disorder_eclient_playlist_delete(client,
636                                      playlists_picker_delete_completed,
637                                      playlist_picker_selected,
638                                      NULL);
639   }
640 }
641
642 /** @brief Table of buttons below the playlist list */
643 static struct button playlist_picker_buttons[] = {
644   {
645     GTK_STOCK_ADD,
646     playlist_picker_add,
647     "Create a new playlist",
648     0
649   },
650   {
651     GTK_STOCK_REMOVE,
652     playlist_picker_delete,
653     "Delete a playlist",
654     0
655   },
656 };
657 #define NPLAYLIST_PICKER_BUTTONS (sizeof playlist_picker_buttons / sizeof *playlist_picker_buttons)
658
659 /** @brief Create the list of playlists for the edit playlists window */
660 static GtkWidget *playlist_picker_create(void) {
661   /* Create the list of playlist and populate it */
662   playlist_picker_fill(NULL, NULL, NULL);
663   /* Create the tree view */
664   GtkWidget *tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(playlist_picker_list));
665   /* ...and the renderers for it */
666   GtkCellRenderer *cr = gtk_cell_renderer_text_new();
667   GtkTreeViewColumn *col = gtk_tree_view_column_new_with_attributes("Playlist",
668                                                                     cr,
669                                                                     "text", 0,
670                                                                     NULL);
671   gtk_tree_view_append_column(GTK_TREE_VIEW(tree), col);
672   /* Get the selection for the view; set its mode; arrange for a callback when
673    * it changes */
674   playlist_picker_selected = NULL;
675   playlist_picker_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
676   gtk_tree_selection_set_mode(playlist_picker_selection, GTK_SELECTION_BROWSE);
677   g_signal_connect(playlist_picker_selection, "changed",
678                    G_CALLBACK(playlist_picker_selection_changed), NULL);
679
680   /* Create the control buttons */
681   GtkWidget *buttons = create_buttons_box(playlist_picker_buttons,
682                                           NPLAYLIST_PICKER_BUTTONS,
683                                           gtk_hbox_new(FALSE, 1));
684   playlist_picker_delete_button = playlist_picker_buttons[1].widget;
685
686   playlist_picker_selection_changed(NULL, NULL);
687
688   /* Buttons live below the list */
689   GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
690   gtk_box_pack_start(GTK_BOX(vbox), scroll_widget(tree), TRUE/*expand*/, TRUE/*fill*/, 0);
691   gtk_box_pack_start(GTK_BOX(vbox), buttons, FALSE/*expand*/, FALSE, 0);
692
693   return vbox;
694 }
695
696 /* Playlist editor ---------------------------------------------------------- */
697
698 static GtkWidget *playlists_editor_create(void) {
699   assert(ql_playlist.view == NULL);     /* better not be set up already */
700   GtkWidget *w = init_queuelike(&ql_playlist);
701   /* Initially empty */
702   return w;
703 }
704
705 /** @brief (Re-)populate the playlist tree model */
706 static void playlist_editor_fill(const char attribute((unused)) *event,
707                                  void *eventdata,
708                                  void attribute((unused)) *callbackdata) {
709   const char *modified_playlist = eventdata;
710   if(!playlist_window)
711     return;
712   if(!playlist_picker_selected)
713     return;
714   if(!strcmp(playlist_picker_selected, modified_playlist))
715     disorder_eclient_playlist_get(client, playlists_editor_received_tracks,
716                                   playlist_picker_selected,
717                                   (void *)playlist_picker_selected);
718 }
719
720 /** @brief Called with new tracks for the playlist */
721 static void playlists_editor_received_tracks(void *v,
722                                              const char *err,
723                                              int nvec, char **vec) {
724   const char *playlist = v;
725   if(err) {
726     popup_protocol_error(0, err);
727     return;
728   }
729   if(!playlist_picker_selected
730      || strcmp(playlist, playlist_picker_selected)) {
731     /* The tracks are for the wrong playlist - something must have changed
732      * while the fetch command was in flight.  We just ignore this callback,
733      * the right answer will be requested and arrive in due course. */
734     return;
735   }
736   if(nvec == -1)
737     /* No such playlist, presumably we'll get a deleted event shortly */
738     return;
739   /* Translate the list of tracks into queue entries */
740   struct queue_entry *newq, **qq = &newq;
741   hash *h = hash_new(sizeof(int));
742   for(int n = 0; n < nvec; ++n) {
743     struct queue_entry *q = xmalloc(sizeof *q);
744     q->track = vec[n];
745     /* Synthesize a unique ID so that the selection survives updates.  Tracks
746      * can appear more than once in the queue so we can't use raw track names,
747      * so we add a serial number to the start. */
748     int *serialp = hash_find(h, vec[n]), serial = serialp ? *serialp : 0;
749     byte_xasprintf((char **)&q->id, "%d-%s", serial++, vec[n]);
750     hash_add(h, vec[0], &serial, HASH_INSERT_OR_REPLACE);
751     *qq = q;
752     qq = &q->next;
753   }
754   *qq = NULL;
755   ql_new_queue(&ql_playlist, newq);
756 }
757
758 /* Playlist editor right-click menu ---------------------------------------- */
759
760 /** @brief Called to determine whether the playlist is playable */
761 static int playlist_playall_sensitive(void attribute((unused)) *extra) {
762   /* If there's no playlist obviously we can't play it */
763   if(!playlist_picker_selected)
764     return FALSE;
765   /* If it's empty we can't play it */
766   if(!ql_playlist.q)
767     return FALSE;
768   /* Otherwise we can */
769   return TRUE;
770 }
771
772 /** @brief Called to play the selected playlist */
773 static void playlist_playall_activate(GtkMenuItem attribute((unused)) *menuitem,
774                                       gpointer attribute((unused)) user_data) {
775   if(!playlist_picker_selected)
776     return;
777   /* Re-use the menu-based activation callback */
778   disorder_eclient_playlist_get(client, playlist_menu_received_content,
779                                 playlist_picker_selected, NULL);
780 }
781
782 /** @brief Called to determine whether the playlist is playable */
783 static int playlist_remove_sensitive(void attribute((unused)) *extra) {
784   /* If there's no playlist obviously we can't remove from it */
785   if(!playlist_picker_selected)
786     return FALSE;
787   /* If no tracks are selected we cannot remove them */
788   if(!gtk_tree_selection_count_selected_rows(ql_playlist.selection))
789     return FALSE;
790   /* We're good to go */
791   return TRUE;
792 }
793
794 /** @brief Called to play the selected playlist */
795 static void playlist_remove_activate(GtkMenuItem attribute((unused)) *menuitem,
796                                      gpointer attribute((unused)) user_data) {
797   if(!playlist_picker_selected)
798     return;
799   /* To safely remove rows we must:
800    * - take a lock
801    * - fetch the playlist
802    * - verify it's not changed
803    * - delete the selected rows from the retrieved version
804    * - store the playlist
805    * - release the lock
806    *
807    * In addition we careful check that the selected playlist hasn't changed
808    * underfoot, and avoid leaving the playlist locked if we bail out at any
809    * point.
810    */
811   disorder_eclient_playlist_lock(client, playlist_remove_locked,
812                                  playlist_picker_selected,
813                                  (void *)playlist_picker_selected);
814 }
815
816 static void playlist_remove_locked(void *v, const char *err) {
817   char *playlist = v;
818   if(err) {
819     popup_protocol_error(0, err);
820     return;
821   }
822   if(!playlist_picker_selected || strcmp(playlist, playlist_picker_selected)) {
823     disorder_eclient_playlist_unlock(client, playlist_remove_unlocked, NULL);
824     return;
825   }
826   disorder_eclient_playlist_get(client, playlist_remove_retrieved,
827                                 playlist, playlist);
828 }
829
830 void playlist_remove_retrieved(void *v, const char *err,
831                                int nvec,
832                                char **vec) {
833   char *playlist = v;
834   if(err) {
835     popup_protocol_error(0, err);
836     disorder_eclient_playlist_unlock(client, playlist_remove_unlocked, NULL);
837     return;
838   }
839   if(!playlist_picker_selected || strcmp(playlist, playlist_picker_selected)) {
840     disorder_eclient_playlist_unlock(client, playlist_remove_unlocked, NULL);
841     return;
842   }
843   /* We check that the contents haven't changed.  If they have we just abandon
844    * the operation.  The user will have to try again. */
845   struct queue_entry *q;
846   int n, m;
847   for(n = 0, q = ql_playlist.q; q && n < nvec; ++n, q = q->next)
848     if(strcmp(q->track, vec[n]))
849       break;
850   if(n != nvec || q != NULL)  {
851     disorder_eclient_playlist_unlock(client, playlist_remove_unlocked, NULL);
852     return;
853   }
854   /* Edit the selected items out */
855   GtkTreeIter iter[1];
856   gboolean it = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql_playlist.store),
857                                               iter);
858   n = m = 0;
859   while(it) {
860     if(!gtk_tree_selection_iter_is_selected(ql_playlist.selection, iter))
861       vec[m++] = vec[n++];
862     else
863       n++;
864     it = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql_playlist.store), iter);
865   }
866   /* Store the new value */
867   disorder_eclient_playlist_set(client, playlist_remove_updated, playlist,
868                                 vec, m, playlist);
869 }
870
871 static void playlist_remove_updated(void attribute((unused)) *v,
872                                     const char *err) {
873   if(err) 
874     popup_protocol_error(0, err);
875   disorder_eclient_playlist_unlock(client, playlist_remove_unlocked, NULL);
876 }
877
878 static void playlist_remove_unlocked(void attribute((unused)) *v,
879                                      const char *err) {
880   if(err) 
881     popup_protocol_error(0, err);
882 }
883
884 /* Playlists window --------------------------------------------------------- */
885
886 /** @brief Pop up the playlists window
887  *
888  * Called when the playlists menu item is selected
889  */
890 void playlist_window_create(gpointer attribute((unused)) callback_data,
891                             guint attribute((unused)) callback_action,
892                             GtkWidget attribute((unused)) *menu_item) {
893   /* If the window already exists, raise it */
894   if(playlist_window) {
895     gtk_window_present(GTK_WINDOW(playlist_window));
896     return;
897   }
898   /* Create the window */
899   playlist_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
900   gtk_widget_set_style(playlist_window, tool_style);
901   g_signal_connect(playlist_window, "destroy",
902                    G_CALLBACK(playlist_window_destroyed), &playlist_window);
903   gtk_window_set_title(GTK_WINDOW(playlist_window), "Playlists Management");
904   /* TODO loads of this is very similar to (copied from!) users.c - can we
905    * de-dupe? */
906   /* Keyboard shortcuts */
907   g_signal_connect(playlist_window, "key-press-event",
908                    G_CALLBACK(playlist_window_keypress), 0);
909   /* default size is too small */
910   gtk_window_set_default_size(GTK_WINDOW(playlist_window), 512, 240);
911
912   GtkWidget *hbox = gtk_hbox_new(FALSE, 0);
913   gtk_box_pack_start(GTK_BOX(hbox), playlist_picker_create(),
914                      FALSE/*expand*/, FALSE, 0);
915   gtk_box_pack_start(GTK_BOX(hbox), gtk_event_box_new(),
916                      FALSE/*expand*/, FALSE, 2);
917   gtk_box_pack_start(GTK_BOX(hbox), playlists_editor_create(),
918                      TRUE/*expand*/, TRUE/*fill*/, 0);
919
920   gtk_container_add(GTK_CONTAINER(playlist_window), frame_widget(hbox, NULL));
921   gtk_widget_show_all(playlist_window);
922 }
923
924 /** @brief Keypress handler */
925 static gboolean playlist_window_keypress(GtkWidget attribute((unused)) *widget,
926                                          GdkEventKey *event,
927                                          gpointer attribute((unused)) user_data) {
928   if(event->state)
929     return FALSE;
930   switch(event->keyval) {
931   case GDK_Escape:
932     gtk_widget_destroy(playlist_window);
933     return TRUE;
934   default:
935     return FALSE;
936   }
937 }
938
939 /** @brief Called when the playlist window is destroyed */
940 static void playlist_window_destroyed(GtkWidget attribute((unused)) *widget,
941                                       GtkWidget **widget_pointer) {
942   destroy_queuelike(&ql_playlist);
943   *widget_pointer = NULL;
944 }
945
946 /** @brief Initialize playlist support */
947 void playlists_init(void) {
948   /* We re-get all playlists upon any change... */
949   event_register("playlist-created", playlist_list_update, 0);
950   event_register("playlist-deleted", playlist_list_update, 0);
951   /* ...and on reconnection */
952   event_register("log-connected", playlist_list_update, 0);
953   /* ...and from time to time */
954   event_register("periodic-slow", playlist_list_update, 0);
955   /* ...and at startup */
956   playlist_list_update(0, 0, 0);
957
958   /* Update the playlists menu when the set of playlists changes */
959   event_register("playlists-updated", playlist_menu_changed, 0);
960   /* Update the new-playlist OK button when the set of playlists changes */
961   event_register("playlists-updated", playlist_new_changed, 0);
962   /* Update the list of playlists in the edit window when the set changes */
963   event_register("playlists-updated", playlist_picker_fill, 0);
964   /* Update the displayed playlist when it is modified */
965   event_register("playlist-modified", playlist_editor_fill, 0);
966 }
967
968 #endif
969
970 /*
971 Local Variables:
972 c-basic-offset:2
973 comment-column:40
974 fill-column:79
975 indent-tabs-mode:nil
976 End:
977 */