chiark / gitweb /
TODOs for choose-search.c
[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  * - proper sorting
39  */
40
41 #include "disobedience.h"
42 #include "choose.h"
43
44 /** @brief The current selection tree */
45 GtkTreeStore *choose_store;
46
47 /** @brief The view onto the selection tree */
48 GtkWidget *choose_view;
49
50 /** @brief The selection tree's selection */
51 GtkTreeSelection *choose_selection;
52
53 /** @brief Count of file listing operations in flight */
54 static int choose_list_in_flight;
55
56 /** @brief Count of files inserted in current batch of listing operations */
57 static int choose_inserted;
58
59 static char *choose_get_string(GtkTreeIter *iter, int column) {
60   gchar *gs;
61   gtk_tree_model_get(GTK_TREE_MODEL(choose_store), iter,
62                      column, &gs,
63                      -1);
64   char *s = xstrdup(gs);
65   g_free(gs);
66   return s;
67 }
68
69 char *choose_get_track(GtkTreeIter *iter) {
70   char *s = choose_get_string(iter, TRACK_COLUMN);
71   return *s ? s : 0;                    /* Placeholder -> NULL */
72 }
73
74 char *choose_get_sort(GtkTreeIter *iter) {
75   return choose_get_string(iter, SORT_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 static gboolean choose_remove_node(GtkTreeIter *it) {
105   GtkTreeIter child[1];
106   gboolean childv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
107                                                  child,
108                                                  it);
109   while(childv)
110     childv = choose_remove_node(child);
111   return gtk_tree_store_remove(choose_store, it);
112 }
113
114 /** @brief Update length and state fields */
115 static gboolean choose_set_state_callback(GtkTreeModel attribute((unused)) *model,
116                                           GtkTreePath attribute((unused)) *path,
117                                           GtkTreeIter *it,
118                                           gpointer attribute((unused)) data) {
119   if(choose_is_file(it)) {
120     const char *track = choose_get_track(it);
121     const long l = namepart_length(track);
122     char length[64];
123     if(l > 0)
124       byte_snprintf(length, sizeof length, "%ld:%02ld", l / 60, l % 60);
125     else
126       length[0] = 0;
127     gtk_tree_store_set(choose_store, it,
128                        LENGTH_COLUMN, length,
129                        STATE_COLUMN, queued(track),
130                        -1);
131     if(choose_is_search_result(track))
132       gtk_tree_store_set(choose_store, it,
133                          BG_COLUMN, "yellow",
134                          FG_COLUMN, "black",
135                          -1);
136     else
137       gtk_tree_store_set(choose_store, it,
138                          BG_COLUMN, (char *)0,
139                          FG_COLUMN, (char *)0,
140                          -1);
141   }
142   return FALSE;                         /* continue walking */
143 }
144
145 /** @brief Called when the queue or playing track change */
146 static void choose_set_state(const char attribute((unused)) *event,
147                              void attribute((unused)) *eventdata,
148                              void attribute((unused)) *callbackdata) {
149   gtk_tree_model_foreach(GTK_TREE_MODEL(choose_store),
150                          choose_set_state_callback,
151                          NULL);
152 }
153
154 /** @brief (Re-)populate a node
155  * @param parent_ref Node to populate or NULL to fill root
156  * @param nvec Number of children to add
157  * @param vec Children
158  * @param files 1 if children are files, 0 if directories
159  *
160  * Adjusts the set of files (or directories) below @p parent_ref to match those
161  * listed in @p nvec and @p vec.
162  *
163  * @parent_ref will be destroyed.
164  */
165 static void choose_populate(GtkTreeRowReference *parent_ref,
166                             int nvec, char **vec,
167                             int isfile) {
168   /* Compute parent_* */
169   GtkTreeIter pit[1], *parent_it;
170   GtkTreePath *parent_path;
171   if(parent_ref) {
172     parent_path = gtk_tree_row_reference_get_path(parent_ref);
173     parent_it = pit;
174     gboolean pitv = gtk_tree_model_get_iter(GTK_TREE_MODEL(choose_store),
175                                             pit, parent_path);
176     assert(pitv);
177     /*fprintf(stderr, "choose_populate %s: parent path is [%s]\n",
178             choose_type_map[type],
179             gtk_tree_path_to_string(parent_path));*/
180   } else {
181     parent_path = 0;
182     parent_it = 0;
183     /*fprintf(stderr, "choose_populate %s: populating the root\n",
184             choose_type_map[type]);*/
185   }
186   /* Remove unwanted nodes and find out which we must add */
187   //fprintf(stderr, " trimming unwanted %s nodes\n", choose_type_map[type]);
188   char *found = xmalloc(nvec);
189   GtkTreeIter it[1];
190   gboolean itv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
191                                               it,
192                                               parent_it);
193   while(itv) {
194     const char *track = choose_get_track(it);
195     int keep;
196
197     if(!track)  {
198       /* Always kill placeholders */
199       //fprintf(stderr, "  kill a placeholder\n");
200       keep = 0;
201     } else if(choose_is_file(it) == isfile) {
202       /* This is the type we care about */
203       //fprintf(stderr, "  %s is a %s\n", track, isfile ? "file" : "dir");
204       int n;
205       for(n = 0; n < nvec && strcmp(vec[n], track); ++n)
206         ;
207       if(n < nvec) {
208         //fprintf(stderr, "   ... and survives\n");
209         found[n] = 1;
210         keep = 1;
211       } else {
212         //fprintf(stderr, "   ... and is to be removed\n");
213         keep = 0;
214       }
215     } else {
216       /* Keep wrong-type entries */
217       //fprintf(stderr, "  %s has wrong type\n", track);
218       keep = 1;
219     }
220     if(keep)
221       itv = gtk_tree_model_iter_next(GTK_TREE_MODEL(choose_store), it);
222     else
223       itv = choose_remove_node(it);
224   }
225   /* Add nodes we don't have */
226   int inserted = 0;
227   //fprintf(stderr, " inserting new %s nodes\n", isfile ? "track" : "dir");
228   const char *typename = isfile ? "track" : "dir";
229   for(int n = 0; n < nvec; ++n) {
230     if(!found[n]) {
231       //fprintf(stderr, "  %s was not found\n", vec[n]);
232       gtk_tree_store_append(choose_store, it, parent_it);
233       gtk_tree_store_set(choose_store, it,
234                          NAME_COLUMN, trackname_transform(typename,
235                                                           vec[n],
236                                                           "display"),
237                          ISFILE_COLUMN, isfile,
238                          TRACK_COLUMN, vec[n],
239                          SORT_COLUMN, trackname_transform(typename,
240                                                           vec[n],
241                                                           "sort"),
242                          -1);
243       /* Update length and state; we expect this to kick off length lookups
244        * rather than necessarily get the right value the first time round. */
245       choose_set_state_callback(0, 0, it, 0);
246       ++inserted;
247       /* If we inserted a directory, insert a placeholder too, so it appears to
248        * have children; it will be deleted when we expand the directory. */
249       if(!isfile) {
250         //fprintf(stderr, "  inserting a placeholder\n");
251         GtkTreeIter placeholder[1];
252
253         gtk_tree_store_append(choose_store, placeholder, it);
254         gtk_tree_store_set(choose_store, placeholder,
255                            NAME_COLUMN, "Waddling...",
256                            TRACK_COLUMN, "",
257                            ISFILE_COLUMN, FALSE,
258                            -1);
259       }
260     }
261   }
262   //fprintf(stderr, " %d nodes inserted\n", inserted);
263   if(inserted) {
264     /* TODO sort the children */
265   }
266   if(parent_ref) {
267     /* If we deleted a placeholder then we must re-expand the row */
268     gtk_tree_view_expand_row(GTK_TREE_VIEW(choose_view), parent_path, FALSE);
269     gtk_tree_row_reference_free(parent_ref);
270     gtk_tree_path_free(parent_path);
271   }
272   /* We only notify others that we've inserted tracks when there are no more
273    * insertions pending, so that they don't have to keep track of how many
274    * requests they've made.  */
275   choose_inserted += inserted;
276   if(--choose_list_in_flight == 0) {
277     /* Notify interested parties that we inserted some tracks, AFTER making
278      * sure that the row is properly expanded */
279     if(choose_inserted) {
280       event_raise("choose-inserted-tracks", parent_it);
281       choose_inserted = 0;
282     }
283   }
284 }
285
286 static void choose_dirs_completed(void *v,
287                                   const char *error,
288                                   int nvec, char **vec) {
289   if(error) {
290     popup_protocol_error(0, error);
291     return;
292   }
293   choose_populate(v, nvec, vec, 0/*!isfile*/);
294 }
295
296 static void choose_files_completed(void *v,
297                                    const char *error,
298                                    int nvec, char **vec) {
299   if(error) {
300     popup_protocol_error(0, error);
301     return;
302   }
303   choose_populate(v, nvec, vec, 1/*isfile*/);
304 }
305
306 void choose_play_completed(void attribute((unused)) *v,
307                            const char *error) {
308   if(error)
309     popup_protocol_error(0, error);
310 }
311
312 static void choose_state_toggled
313     (GtkCellRendererToggle attribute((unused)) *cell_renderer,
314      gchar *path_str,
315      gpointer attribute((unused)) user_data) {
316   GtkTreeIter it[1];
317   /* Identify the track */
318   gboolean itv =
319     gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(choose_store),
320                                         it,
321                                         path_str);
322   if(!itv)
323     return;
324   if(!choose_is_file(it))
325     return;
326   const char *track = choose_get_track(it);
327   if(queued(track))
328     return;
329   disorder_eclient_play(client, track, choose_play_completed, 0);
330   
331 }
332
333 static void choose_row_expanded(GtkTreeView attribute((unused)) *treeview,
334                                 GtkTreeIter *iter,
335                                 GtkTreePath *path,
336                                 gpointer attribute((unused)) user_data) {
337   /*fprintf(stderr, "row-expanded path=[%s]\n",
338           gtk_tree_path_to_string(path));*/
339   /* We update a node's contents whenever it is expanded, even if it was
340    * already populated; the effect is that contracting and expanding a node
341    * suffices to update it to the latest state on the server. */
342   const char *track = choose_get_track(iter);
343   disorder_eclient_files(client, choose_files_completed,
344                          track,
345                          NULL,
346                          gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
347                                                     path));
348   disorder_eclient_dirs(client, choose_dirs_completed,
349                         track,
350                         NULL,
351                         gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
352                                                    path));
353   /* The row references are destroyed in the _completed handlers. */
354   choose_list_in_flight += 2;
355 }
356
357 /** @brief Create the choose tab */
358 GtkWidget *choose_widget(void) {
359   /* Create the tree store. */
360   choose_store = gtk_tree_store_new(CHOOSE_COLUMNS,
361                                     G_TYPE_BOOLEAN,
362                                     G_TYPE_STRING,
363                                     G_TYPE_STRING,
364                                     G_TYPE_BOOLEAN,
365                                     G_TYPE_STRING,
366                                     G_TYPE_STRING,
367                                     G_TYPE_STRING,
368                                     G_TYPE_STRING);
369
370   /* Create the view */
371   choose_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(choose_store));
372   gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(choose_view), TRUE);
373
374   /* Create cell renderers and columns */
375   /* TODO use a table */
376   {
377     GtkCellRenderer *r = gtk_cell_renderer_text_new();
378     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
379       ("Track",
380        r,
381        "text", NAME_COLUMN,
382        "background", BG_COLUMN,
383        "foreground", FG_COLUMN,
384        (char *)0);
385     gtk_tree_view_column_set_resizable(c, TRUE);
386     gtk_tree_view_column_set_reorderable(c, TRUE);
387     g_object_set(c, "expand", TRUE, (char *)0);
388     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
389   }
390   {
391     GtkCellRenderer *r = gtk_cell_renderer_text_new();
392     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
393       ("Length",
394        r,
395        "text", LENGTH_COLUMN,
396        (char *)0);
397     gtk_tree_view_column_set_resizable(c, TRUE);
398     gtk_tree_view_column_set_reorderable(c, TRUE);
399     g_object_set(r, "xalign", (gfloat)1.0, (char *)0);
400     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
401   }
402   {
403     GtkCellRenderer *r = gtk_cell_renderer_toggle_new();
404     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
405       ("Queued",
406        r,
407        "active", STATE_COLUMN,
408        "visible", ISFILE_COLUMN,
409        (char *)0);
410     gtk_tree_view_column_set_resizable(c, TRUE);
411     gtk_tree_view_column_set_reorderable(c, TRUE);
412     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
413     g_signal_connect(r, "toggled",
414                      G_CALLBACK(choose_state_toggled), 0);
415   }
416   
417   /* The selection should support multiple things being selected */
418   choose_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(choose_view));
419   gtk_tree_selection_set_mode(choose_selection, GTK_SELECTION_MULTIPLE);
420
421   /* Catch button presses */
422   g_signal_connect(choose_view, "button-press-event",
423                    G_CALLBACK(choose_button_event), 0);
424   g_signal_connect(choose_view, "button-release-event",
425                    G_CALLBACK(choose_button_event), 0);
426   /* Catch row expansions so we can fill in placeholders */
427   g_signal_connect(choose_view, "row-expanded",
428                    G_CALLBACK(choose_row_expanded), 0);
429
430   event_register("queue-list-changed", choose_set_state, 0);
431   event_register("playing-track-changed", choose_set_state, 0);
432   event_register("search-results-changed", choose_set_state, 0);
433   
434   /* Fill the root */
435   disorder_eclient_files(client, choose_files_completed, "", NULL, NULL); 
436   disorder_eclient_dirs(client, choose_dirs_completed, "", NULL, NULL); 
437
438   /* Make the widget scrollable */
439   GtkWidget *scrolled = scroll_widget(choose_view);
440
441   /* Pack vertically with the search widget */
442   GtkWidget *vbox = gtk_vbox_new(FALSE/*homogenous*/, 1/*spacing*/);
443   gtk_box_pack_start(GTK_BOX(vbox), scrolled,
444                      TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
445   gtk_box_pack_end(GTK_BOX(vbox), choose_search_widget(),
446                    FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
447   
448   g_object_set_data(G_OBJECT(vbox), "type", (void *)&choose_tabtype);
449   return vbox;
450 }
451
452 /*
453 Local Variables:
454 c-basic-offset:2
455 comment-column:40
456 fill-column:79
457 indent-tabs-mode:nil
458 End:
459 */