chiark / gitweb /
choose_populate() always raise choose-more-tracks rather than only
[disorder] / disobedience / choose.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2008 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/choose.c
21  * @brief Hierarchical track selection and search
22  *
23  * We now use an ordinary GtkTreeStore/GtkTreeView.
24  *
25  * We don't want to pull the entire tree in memory, but we want directories to
26  * show up as having children.  Therefore we give directories a placeholder
27  * child and replace their children when they are opened.  Placeholders have
28  * TRACK_COLUMN="" and ISFILE_COLUMN=FALSE (so that they don't get check boxes,
29  * lengths, etc).
30  *
31  * TODO We do a period sweep which kills contracted nodes, putting back
32  * placeholders, and updating expanded nodes to keep up with server-side
33  * changes.  (We could trigger the latter off rescan complete notifications?)
34  * 
35  * TODO:
36  * - sweep up contracted nodes
37  * - update when content may have changed (e.g. after a rescan)
38  */
39
40 #include "disobedience.h"
41 #include "choose.h"
42
43 /** @brief The current selection tree */
44 GtkTreeStore *choose_store;
45
46 /** @brief The view onto the selection tree */
47 GtkWidget *choose_view;
48
49 /** @brief The selection tree's selection */
50 GtkTreeSelection *choose_selection;
51
52 /** @brief Count of file listing operations in flight */
53 static int choose_list_in_flight;
54
55 static char *choose_get_string(GtkTreeIter *iter, int column) {
56   gchar *gs;
57   gtk_tree_model_get(GTK_TREE_MODEL(choose_store), iter,
58                      column, &gs,
59                      -1);
60   char *s = xstrdup(gs);
61   g_free(gs);
62   return s;
63 }
64
65 char *choose_get_track(GtkTreeIter *iter) {
66   char *s = choose_get_string(iter, TRACK_COLUMN);
67   return *s ? s : 0;                    /* Placeholder -> NULL */
68 }
69
70 char *choose_get_sort(GtkTreeIter *iter) {
71   return choose_get_string(iter, SORT_COLUMN);
72 }
73
74 char *choose_get_display(GtkTreeIter *iter) {
75   return choose_get_string(iter, NAME_COLUMN);
76 }
77
78 int choose_is_file(GtkTreeIter *iter) {
79   gboolean isfile;
80   gtk_tree_model_get(GTK_TREE_MODEL(choose_store), iter,
81                      ISFILE_COLUMN, &isfile,
82                      -1);
83   return isfile;
84 }
85
86 int choose_is_dir(GtkTreeIter *iter) {
87   gboolean isfile;
88   gtk_tree_model_get(GTK_TREE_MODEL(choose_store), iter,
89                      ISFILE_COLUMN, &isfile,
90                      -1);
91   if(isfile)
92     return FALSE;
93   return !choose_is_placeholder(iter);
94 }
95
96 int choose_is_placeholder(GtkTreeIter *iter) {
97   return choose_get_string(iter, TRACK_COLUMN)[0] == 0;
98 }
99
100 /** @brief Remove node @p it and all its children
101  * @param Iterator, updated to point to next
102  * @return True if iterator remains valid
103  *
104  * TODO is this necessary?  gtk_tree_store_remove() does not document what
105  * happens to children.
106  */
107 static gboolean choose_remove_node(GtkTreeIter *it) {
108   GtkTreeIter child[1];
109   gboolean childv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
110                                                  child,
111                                                  it);
112   while(childv)
113     childv = choose_remove_node(child);
114   return gtk_tree_store_remove(choose_store, it);
115 }
116
117 /** @brief Update length and state fields */
118 static gboolean choose_set_state_callback(GtkTreeModel attribute((unused)) *model,
119                                           GtkTreePath attribute((unused)) *path,
120                                           GtkTreeIter *it,
121                                           gpointer attribute((unused)) data) {
122   if(choose_is_file(it)) {
123     const char *track = choose_get_track(it);
124     const long l = namepart_length(track);
125     char length[64];
126     if(l > 0)
127       byte_snprintf(length, sizeof length, "%ld:%02ld", l / 60, l % 60);
128     else
129       length[0] = 0;
130     gtk_tree_store_set(choose_store, it,
131                        LENGTH_COLUMN, length,
132                        STATE_COLUMN, queued(track),
133                        -1);
134     if(choose_is_search_result(track))
135       gtk_tree_store_set(choose_store, it,
136                          BG_COLUMN, SEARCH_RESULT_BG,
137                          FG_COLUMN, SEARCH_RESULT_FG,
138                          -1);
139     else
140       gtk_tree_store_set(choose_store, it,
141                          BG_COLUMN, (char *)0,
142                          FG_COLUMN, (char *)0,
143                          -1);
144   }
145   return FALSE;                         /* continue walking */
146 }
147
148 /** @brief Called when the queue or playing track change */
149 static void choose_set_state(const char attribute((unused)) *event,
150                              void attribute((unused)) *eventdata,
151                              void attribute((unused)) *callbackdata) {
152   gtk_tree_model_foreach(GTK_TREE_MODEL(choose_store),
153                          choose_set_state_callback,
154                          NULL);
155 }
156
157 /** @brief (Re-)populate a node
158  * @param parent_ref Node to populate or NULL to fill root
159  * @param nvec Number of children to add
160  * @param vec Children
161  * @param files 1 if children are files, 0 if directories
162  *
163  * Adjusts the set of files (or directories) below @p parent_ref to match those
164  * listed in @p nvec and @p vec.
165  *
166  * @parent_ref will be destroyed.
167  */
168 static void choose_populate(GtkTreeRowReference *parent_ref,
169                             int nvec, char **vec,
170                             int isfile) {
171   const char *type = isfile ? "track" : "dir";
172   //fprintf(stderr, "%d new children of type %s\n", nvec, type);
173   if(!nvec)
174     goto skip;
175   /* Compute parent_* */
176   GtkTreeIter pit[1], *parent_it;
177   GtkTreePath *parent_path;
178   if(parent_ref) {
179     parent_path = gtk_tree_row_reference_get_path(parent_ref);
180     parent_it = pit;
181     gboolean pitv = gtk_tree_model_get_iter(GTK_TREE_MODEL(choose_store),
182                                             pit, parent_path);
183     assert(pitv);
184     /*fprintf(stderr, "choose_populate %s: parent path is [%s]\n",
185             type,
186             gtk_tree_path_to_string(parent_path));*/
187   } else {
188     parent_path = 0;
189     parent_it = 0;
190     /*fprintf(stderr, "choose_populate %s: populating the root\n",
191             type);*/
192   }
193   /* Both td[] and the current node set are sorted so we can do a single linear
194    * pass to insert new nodes and remove unwanted ones.  The total performance
195    * may be worse than linear depending on the performance of GTK+'s insert and
196    * delete operations. */
197   //fprintf(stderr, "sorting tracks\n");
198   struct tracksort_data *td = tracksort_init(nvec, vec, type);
199   GtkTreeIter it[1];
200   gboolean itv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
201                                               it,
202                                               parent_it);
203   int inserted = 0, deleted_placeholder = 0;
204   //fprintf(stderr, "inserting tracks type=%s\n", type);
205   while(nvec > 0 || itv) {
206     /*fprintf(stderr, "td[] = %s, it=%s [%s]\n",
207             nvec > 0 ? td->track : "(none)",
208             itv ? choose_get_track(it) : "(!itv)",
209             itv ? (choose_is_file(it) ? "file" : "dir") : "");*/
210     enum { INSERT, DELETE, SKIP_TREE, SKIP_BOTH } action;
211     const char *track = itv ? choose_get_track(it) : 0;
212     if(itv && !track) {
213       //fprintf(stderr, " placeholder\n");
214       action = DELETE;
215       ++deleted_placeholder;
216     } else if(nvec > 0 && itv) {
217       /* There's both a tree row and a td[] entry */
218       const int cmp = compare_tracks(td->sort, choose_get_sort(it),
219                                      td->display, choose_get_display(it),
220                                      td->track, track);
221       //fprintf(stderr, " cmp=%d\n", cmp);
222       if(cmp < 0)
223         /* td < it, so we insert td before it */
224         action = INSERT;
225       else if(cmp > 0) {
226         /* td > it, so we must either delete it (if the same type) or skip it */
227         if(choose_is_file(it) == isfile)
228           action = DELETE;
229         else
230           action = SKIP_TREE;
231       } else
232         /* td = it, so we step past both */
233         action = SKIP_BOTH;
234     } else if(nvec > 0) {
235       /* We've reached the end of the tree rows, but new have tracks left in
236        * td[] */
237       //fprintf(stderr, " inserting\n");
238       action = INSERT;
239     } else {
240       /* We've reached the end of the new tracks from td[], but there are
241        * further tracks in the tree */
242       //fprintf(stderr, " deleting\n");
243       if(choose_is_file(it) == isfile)
244         action = DELETE;
245       else
246         action = SKIP_TREE;
247     }
248     
249     switch(action) {
250     case INSERT: {
251       //fprintf(stderr, " INSERT %s\n", td->track);
252       /* Insert a new row from td[] before it, or at the end if it is no longer
253        * valid */
254       GtkTreeIter child[1];
255       gtk_tree_store_insert_before(choose_store,
256                                    child, /* new row */
257                                    parent_it, /* parent */
258                                    itv ? it : NULL); /* successor */
259       gtk_tree_store_set(choose_store, child,
260                          NAME_COLUMN, td->display,
261                          ISFILE_COLUMN, isfile,
262                          TRACK_COLUMN, td->track,
263                          SORT_COLUMN, td->sort,
264                          -1);
265       /* Update length and state; we expect this to kick off length lookups
266        * rather than necessarily get the right value the first time round. */
267       choose_set_state_callback(0, 0, child, 0);
268       /* If we inserted a directory, insert a placeholder too, so it appears to
269        * have children; it will be deleted when we expand the directory. */
270       if(!isfile) {
271         //fprintf(stderr, "  inserting a placeholder\n");
272         GtkTreeIter placeholder[1];
273
274         gtk_tree_store_append(choose_store, placeholder, child);
275         gtk_tree_store_set(choose_store, placeholder,
276                            NAME_COLUMN, "Waddling...",
277                            TRACK_COLUMN, "",
278                            ISFILE_COLUMN, FALSE,
279                            -1);
280       }
281       ++inserted;
282       ++td;
283       --nvec;
284       break;
285     }
286     case SKIP_BOTH:
287       //fprintf(stderr, " SKIP_BOTH\n");
288       ++td;
289       --nvec;
290       /* fall thru */
291     case SKIP_TREE:
292       //fprintf(stderr, " SKIP_TREE\n");
293       itv = gtk_tree_model_iter_next(GTK_TREE_MODEL(choose_store), it);
294       break;
295     case DELETE:
296       //fprintf(stderr, " DELETE\n");
297       itv = choose_remove_node(it);
298       break;
299     }
300   }
301   /*fprintf(stderr, "inserted=%d deleted_placeholder=%d\n\n",
302           inserted, deleted_placeholder);*/
303   if(parent_ref) {
304     /* If we deleted a placeholder then we must re-expand the row */
305     if(deleted_placeholder)
306       gtk_tree_view_expand_row(GTK_TREE_VIEW(choose_view), parent_path, FALSE);
307     gtk_tree_row_reference_free(parent_ref);
308     gtk_tree_path_free(parent_path);
309   }
310 skip:
311   /* We only notify others that we've inserted tracks when there are no more
312    * insertions pending, so that they don't have to keep track of how many
313    * requests they've made.  */
314   if(--choose_list_in_flight == 0) {
315     /* Notify interested parties that we inserted some tracks, AFTER making
316      * sure that the row is properly expanded */
317     //fprintf(stderr, "raising choose-more-tracks\n");
318     event_raise("choose-more-tracks", 0);
319   }
320   //fprintf(stderr, "choose_list_in_flight -> %d-\n", choose_list_in_flight);
321 }
322
323 static void choose_dirs_completed(void *v,
324                                   const char *error,
325                                   int nvec, char **vec) {
326   if(error) {
327     popup_protocol_error(0, error);
328     return;
329   }
330   choose_populate(v, nvec, vec, 0/*!isfile*/);
331 }
332
333 static void choose_files_completed(void *v,
334                                    const char *error,
335                                    int nvec, char **vec) {
336   if(error) {
337     popup_protocol_error(0, error);
338     return;
339   }
340   choose_populate(v, nvec, vec, 1/*isfile*/);
341 }
342
343 void choose_play_completed(void attribute((unused)) *v,
344                            const char *error) {
345   if(error)
346     popup_protocol_error(0, error);
347 }
348
349 static void choose_state_toggled
350     (GtkCellRendererToggle attribute((unused)) *cell_renderer,
351      gchar *path_str,
352      gpointer attribute((unused)) user_data) {
353   GtkTreeIter it[1];
354   /* Identify the track */
355   gboolean itv =
356     gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(choose_store),
357                                         it,
358                                         path_str);
359   if(!itv)
360     return;
361   if(!choose_is_file(it))
362     return;
363   const char *track = choose_get_track(it);
364   if(queued(track))
365     return;
366   disorder_eclient_play(client, track, choose_play_completed, 0);
367   
368 }
369
370 static void choose_row_expanded(GtkTreeView attribute((unused)) *treeview,
371                                 GtkTreeIter *iter,
372                                 GtkTreePath *path,
373                                 gpointer attribute((unused)) user_data) {
374   /*fprintf(stderr, "row-expanded path=[%s]\n\n",
375           gtk_tree_path_to_string(path));*/
376   /* We update a node's contents whenever it is expanded, even if it was
377    * already populated; the effect is that contracting and expanding a node
378    * suffices to update it to the latest state on the server. */
379   const char *track = choose_get_track(iter);
380   disorder_eclient_files(client, choose_files_completed,
381                          track,
382                          NULL,
383                          gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
384                                                     path));
385   disorder_eclient_dirs(client, choose_dirs_completed,
386                         track,
387                         NULL,
388                         gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
389                                                    path));
390   /* The row references are destroyed in the _completed handlers. */
391   choose_list_in_flight += 2;
392   //fprintf(stderr, "choose_list_in_flight -> %d+\n", choose_list_in_flight);
393 }
394
395 /** @brief Create the choose tab */
396 GtkWidget *choose_widget(void) {
397   /* Create the tree store. */
398   choose_store = gtk_tree_store_new(CHOOSE_COLUMNS,
399                                     G_TYPE_BOOLEAN,
400                                     G_TYPE_STRING,
401                                     G_TYPE_STRING,
402                                     G_TYPE_BOOLEAN,
403                                     G_TYPE_STRING,
404                                     G_TYPE_STRING,
405                                     G_TYPE_STRING,
406                                     G_TYPE_STRING);
407
408   /* Create the view */
409   choose_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(choose_store));
410   gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(choose_view), TRUE);
411
412   /* Create cell renderers and columns */
413   /* TODO use a table */
414   {
415     GtkCellRenderer *r = gtk_cell_renderer_toggle_new();
416     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
417       ("Queued",
418        r,
419        "active", STATE_COLUMN,
420        "visible", ISFILE_COLUMN,
421        (char *)0);
422     gtk_tree_view_column_set_resizable(c, TRUE);
423     gtk_tree_view_column_set_reorderable(c, TRUE);
424     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
425     g_signal_connect(r, "toggled",
426                      G_CALLBACK(choose_state_toggled), 0);
427   }
428   {
429     GtkCellRenderer *r = gtk_cell_renderer_text_new();
430     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
431       ("Length",
432        r,
433        "text", LENGTH_COLUMN,
434        (char *)0);
435     gtk_tree_view_column_set_resizable(c, TRUE);
436     gtk_tree_view_column_set_reorderable(c, TRUE);
437     g_object_set(r, "xalign", (gfloat)1.0, (char *)0);
438     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
439   }
440   {
441     GtkCellRenderer *r = gtk_cell_renderer_text_new();
442     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
443       ("Track",
444        r,
445        "text", NAME_COLUMN,
446        "background", BG_COLUMN,
447        "foreground", FG_COLUMN,
448        (char *)0);
449     gtk_tree_view_column_set_resizable(c, TRUE);
450     gtk_tree_view_column_set_reorderable(c, TRUE);
451     g_object_set(c, "expand", TRUE, (char *)0);
452     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
453     gtk_tree_view_set_expander_column(GTK_TREE_VIEW(choose_view), c);
454   }
455   
456   /* The selection should support multiple things being selected */
457   choose_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(choose_view));
458   gtk_tree_selection_set_mode(choose_selection, GTK_SELECTION_MULTIPLE);
459
460   /* Catch button presses */
461   g_signal_connect(choose_view, "button-press-event",
462                    G_CALLBACK(choose_button_event), 0);
463   g_signal_connect(choose_view, "button-release-event",
464                    G_CALLBACK(choose_button_event), 0);
465   /* Catch row expansions so we can fill in placeholders */
466   g_signal_connect(choose_view, "row-expanded",
467                    G_CALLBACK(choose_row_expanded), 0);
468
469   event_register("queue-list-changed", choose_set_state, 0);
470   event_register("playing-track-changed", choose_set_state, 0);
471   event_register("search-results-changed", choose_set_state, 0);
472   event_register("lookups-completed", choose_set_state, 0);
473
474   /* Fill the root */
475   disorder_eclient_files(client, choose_files_completed, "", NULL, NULL); 
476   disorder_eclient_dirs(client, choose_dirs_completed, "", NULL, NULL); 
477   choose_list_in_flight += 2;
478   //fprintf(stderr, "choose_list_in_flight -> %d+\n", choose_list_in_flight);
479
480   /* Make the widget scrollable */
481   GtkWidget *scrolled = scroll_widget(choose_view);
482
483   /* Pack vertically with the search widget */
484   GtkWidget *vbox = gtk_vbox_new(FALSE/*homogenous*/, 1/*spacing*/);
485   gtk_box_pack_start(GTK_BOX(vbox), scrolled,
486                      TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
487   gtk_box_pack_end(GTK_BOX(vbox), choose_search_widget(),
488                    FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
489   
490   g_object_set_data(G_OBJECT(vbox), "type", (void *)&choose_tabtype);
491   return vbox;
492 }
493
494 /*
495 Local Variables:
496 c-basic-offset:2
497 comment-column:40
498 fill-column:79
499 indent-tabs-mode:nil
500 End:
501 */