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