chiark / gitweb /
add a TODO
[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 have an extra column with per-row data.  This isn't referenced from
26  * anywhere the GC can see so explicit memory management is required.
27  * (TODO perhaps we could fix this using a gobject?)
28  *
29  * We don't want to pull the entire tree in memory, but we want directories to
30  * show up as having children.  Therefore we give directories a placeholder
31  * child and replace their children when they are opened.  Placeholders have a
32  * null choosedata pointer.
33  *
34  * TODO We do a period sweep which kills contracted nodes, putting back
35  * placeholders, and updating expanded nodes to keep up with server-side
36  * changes.  (We could trigger the latter off rescan complete notifications?)
37  * 
38  * TODO:
39  * - sweep up contracted nodes
40  * - update when content may have changed (e.g. after a rescan)
41  * - searching!
42  */
43
44 #include "disobedience.h"
45 #include "choose.h"
46
47 /** @brief The current selection tree */
48 GtkTreeStore *choose_store;
49
50 /** @brief The view onto the selection tree */
51 GtkWidget *choose_view;
52
53 /** @brief The selection tree's selection */
54 GtkTreeSelection *choose_selection;
55
56 /** @brief Map choosedata types to names */
57 static const char *const choose_type_map[] = { "track", "dir" };
58
59 /** @brief Return the choosedata given an interator */
60 struct choosedata *choose_iter_to_data(GtkTreeIter *iter) {
61   GValue v[1];
62   memset(v, 0, sizeof v);
63   gtk_tree_model_get_value(GTK_TREE_MODEL(choose_store), iter, CHOOSEDATA_COLUMN, v);
64   assert(G_VALUE_TYPE(v) == G_TYPE_POINTER);
65   struct choosedata *const cd = g_value_get_pointer(v);
66   g_value_unset(v);
67   return cd;
68 }
69
70 struct choosedata *choose_path_to_data(GtkTreePath *path) {
71   GtkTreeIter it[1];
72   gboolean itv = gtk_tree_model_get_iter(GTK_TREE_MODEL(choose_store),
73                                          it, path);
74   assert(itv);
75   return choose_iter_to_data(it);
76 }
77
78 /** @brief Remove node @p it and all its children
79  * @param Iterator, updated to point to next
80  * @return True if iterator remains valid
81  */
82 static gboolean choose_remove_node(GtkTreeIter *it) {
83   GtkTreeIter child[1];
84   gboolean childv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
85                                                  child,
86                                                  it);
87   while(childv)
88     childv = choose_remove_node(child);
89   struct choosedata *cd = choose_iter_to_data(it);
90   if(cd) {
91     g_free(cd->track);
92     g_free(cd->sort);
93     g_free(cd);
94   }
95   return gtk_tree_store_remove(choose_store, it);
96 }
97
98 /** @brief Update length and state fields */
99 static gboolean choose_set_state_callback(GtkTreeModel attribute((unused)) *model,
100                                           GtkTreePath attribute((unused)) *path,
101                                           GtkTreeIter *it,
102                                           gpointer attribute((unused)) data) {
103   struct choosedata *cd = choose_iter_to_data(it);
104   if(!cd)
105     return FALSE;                       /* Skip placeholders*/
106   if(cd->type == CHOOSE_FILE) {
107     const long l = namepart_length(cd->track);
108     char length[64];
109     if(l > 0)
110       byte_snprintf(length, sizeof length, "%ld:%02ld", l / 60, l % 60);
111     else
112       length[0] = 0;
113     gtk_tree_store_set(choose_store, it,
114                        LENGTH_COLUMN, length,
115                        STATE_COLUMN, queued(cd->track),
116                        -1);
117   }
118   return FALSE;                         /* continue walking */
119 }
120
121 /** @brief Called when the queue or playing track change */
122 static void choose_set_state(const char attribute((unused)) *event,
123                              void attribute((unused)) *eventdata,
124                              void attribute((unused)) *callbackdata) {
125   gtk_tree_model_foreach(GTK_TREE_MODEL(choose_store),
126                          choose_set_state_callback,
127                          NULL);
128 }
129
130 /** @brief (Re-)populate a node
131  * @param parent_ref Node to populate or NULL to fill root
132  * @param nvec Number of children to add
133  * @param vec Children
134  * @param dirs True if children are directories
135  *
136  * Adjusts the set of files (or directories) below @p parent_ref to match those
137  * listed in @p nvec and @p vec.
138  *
139  * @parent_ref will be destroyed.
140  */
141 static void choose_populate(GtkTreeRowReference *parent_ref,
142                             int nvec, char **vec,
143                             int type) {
144   /* Compute parent_* */
145   GtkTreeIter pit[1], *parent_it;
146   GtkTreePath *parent_path;
147   if(parent_ref) {
148     parent_path = gtk_tree_row_reference_get_path(parent_ref);
149     parent_it = pit;
150     gboolean pitv = gtk_tree_model_get_iter(GTK_TREE_MODEL(choose_store),
151                                             pit, parent_path);
152     assert(pitv);
153     /*fprintf(stderr, "choose_populate %s: parent path is [%s]\n",
154             choose_type_map[type],
155             gtk_tree_path_to_string(parent_path));*/
156   } else {
157     parent_path = 0;
158     parent_it = 0;
159     /*fprintf(stderr, "choose_populate %s: populating the root\n",
160             choose_type_map[type]);*/
161   }
162   /* Remove unwanted nodes and find out which we must add */
163   //fprintf(stderr, " trimming unwanted %s nodes\n", choose_type_map[type]);
164   char *found = xmalloc(nvec);
165   GtkTreeIter it[1];
166   gboolean itv = gtk_tree_model_iter_children(GTK_TREE_MODEL(choose_store),
167                                               it,
168                                               parent_it);
169   while(itv) {
170     struct choosedata *cd = choose_iter_to_data(it);
171     int keep;
172
173     if(!cd)  {
174       /* Always kill placeholders */
175       //fprintf(stderr, "  kill a placeholder\n");
176       keep = 0;
177     } else if(cd->type == type) {
178       /* This is the type we care about */
179       //fprintf(stderr, "  %s is a %s\n", cd->track, choose_type_map[cd->type]);
180       int n;
181       for(n = 0; n < nvec && strcmp(vec[n], cd->track); ++n)
182         ;
183       if(n < nvec) {
184         //fprintf(stderr, "   ... and survives\n");
185         found[n] = 1;
186         keep = 1;
187       } else {
188         //fprintf(stderr, "   ... and is to be removed\n");
189         keep = 0;
190       }
191     } else {
192       /* Keep wrong-type entries */
193       //fprintf(stderr, "  %s is a %s\n", cd->track, choose_type_map[cd->type]);
194       keep = 1;
195     }
196     if(keep)
197       itv = gtk_tree_model_iter_next(GTK_TREE_MODEL(choose_store), it);
198     else
199       itv = choose_remove_node(it);
200   }
201   /* Add nodes we don't have */
202   int inserted = 0;
203   //fprintf(stderr, " inserting new %s nodes\n", choose_type_map[type]);
204   for(int n = 0; n < nvec; ++n) {
205     if(!found[n]) {
206       //fprintf(stderr, "  %s was not found\n", vec[n]);
207       struct choosedata *cd = g_malloc0(sizeof *cd);
208       cd->type = type;
209       cd->track = g_strdup(vec[n]);
210       cd->sort = g_strdup(trackname_transform(choose_type_map[type],
211                                               vec[n],
212                                               "sort"));
213       gtk_tree_store_append(choose_store, it, parent_it);
214       gtk_tree_store_set(choose_store, it,
215                          NAME_COLUMN, trackname_transform(choose_type_map[type],
216                                                           vec[n],
217                                                           "display"),
218                          CHOOSEDATA_COLUMN, cd,
219                          ISFILE_COLUMN, type == CHOOSE_FILE,
220                          -1);
221       /* Update length and state; we expect this to kick off length lookups
222        * rather than necessarily get the right value the first time round. */
223       choose_set_state_callback(0, 0, it, 0);
224       ++inserted;
225       /* If we inserted a directory, insert a placeholder too, so it appears to
226        * have children; it will be deleted when we expand the directory. */
227       if(type == CHOOSE_DIRECTORY) {
228         //fprintf(stderr, "  inserting a placeholder\n");
229         GtkTreeIter placeholder[1];
230
231         gtk_tree_store_append(choose_store, placeholder, it);
232         gtk_tree_store_set(choose_store, placeholder,
233                            NAME_COLUMN, "Waddling...",
234                            CHOOSEDATA_COLUMN, (void *)0,
235                            -1);
236       }
237     }
238   }
239   //fprintf(stderr, " %d nodes inserted\n", inserted);
240   if(inserted) {
241     /* TODO sort the children */
242   }
243   if(parent_ref) {
244     /* If we deleted a placeholder then we must re-expand the row */
245     gtk_tree_view_expand_row(GTK_TREE_VIEW(choose_view), parent_path, FALSE);
246     gtk_tree_row_reference_free(parent_ref);
247     gtk_tree_path_free(parent_path);
248   }
249 }
250
251 static void choose_dirs_completed(void *v,
252                                   const char *error,
253                                   int nvec, char **vec) {
254   if(error) {
255     popup_protocol_error(0, error);
256     return;
257   }
258   choose_populate(v, nvec, vec, CHOOSE_DIRECTORY);
259 }
260
261 static void choose_files_completed(void *v,
262                                    const char *error,
263                                    int nvec, char **vec) {
264   if(error) {
265     popup_protocol_error(0, error);
266     return;
267   }
268   choose_populate(v, nvec, vec, CHOOSE_FILE);
269 }
270
271 void choose_play_completed(void attribute((unused)) *v,
272                            const char *error) {
273   if(error)
274     popup_protocol_error(0, error);
275 }
276
277 static void choose_state_toggled
278     (GtkCellRendererToggle attribute((unused)) *cell_renderer,
279      gchar *path_str,
280      gpointer attribute((unused)) user_data) {
281   GtkTreeIter it[1];
282   /* Identify the track */
283   gboolean itv =
284     gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(choose_store),
285                                         it,
286                                         path_str);
287   if(!itv)
288     return;
289   struct choosedata *cd = choose_iter_to_data(it);
290   if(!cd)
291     return;
292   if(cd->type != CHOOSE_FILE)
293     return;
294   if(queued(cd->track))
295     return;
296   disorder_eclient_play(client, xstrdup(cd->track),
297                         choose_play_completed, 0);
298   
299 }
300
301 static void choose_row_expanded(GtkTreeView attribute((unused)) *treeview,
302                                 GtkTreeIter *iter,
303                                 GtkTreePath *path,
304                                 gpointer attribute((unused)) user_data) {
305   /*fprintf(stderr, "row-expanded path=[%s]\n",
306           gtk_tree_path_to_string(path));*/
307   /* We update a node's contents whenever it is expanded, even if it was
308    * already populated; the effect is that contracting and expanding a node
309    * suffices to update it to the latest state on the server. */
310   struct choosedata *cd = choose_iter_to_data(iter);
311   disorder_eclient_files(client, choose_files_completed,
312                          xstrdup(cd->track),
313                          NULL,
314                          gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
315                                                     path));
316   disorder_eclient_dirs(client, choose_dirs_completed,
317                         xstrdup(cd->track),
318                         NULL,
319                         gtk_tree_row_reference_new(GTK_TREE_MODEL(choose_store),
320                                                    path));
321   /* The row references are destroyed in the _completed handlers. */
322 }
323
324 /** @brief Create the choose tab */
325 GtkWidget *choose_widget(void) {
326   /* Create the tree store. */
327   choose_store = gtk_tree_store_new(1 + CHOOSEDATA_COLUMN,
328                                     G_TYPE_BOOLEAN,
329                                     G_TYPE_STRING,
330                                     G_TYPE_STRING,
331                                     G_TYPE_BOOLEAN,
332                                     G_TYPE_POINTER);
333
334   /* Create the view */
335   choose_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(choose_store));
336   gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(choose_view), TRUE);
337
338   /* Create cell renderers and columns */
339   /* TODO use a table */
340   {
341     GtkCellRenderer *r = gtk_cell_renderer_text_new();
342     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
343       ("Track",
344        r,
345        "text", NAME_COLUMN,
346        (char *)0);
347     gtk_tree_view_column_set_resizable(c, TRUE);
348     gtk_tree_view_column_set_reorderable(c, TRUE);
349     g_object_set(c, "expand", TRUE, (char *)0);
350     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
351   }
352   {
353     GtkCellRenderer *r = gtk_cell_renderer_text_new();
354     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
355       ("Length",
356        r,
357        "text", LENGTH_COLUMN,
358        (char *)0);
359     gtk_tree_view_column_set_resizable(c, TRUE);
360     gtk_tree_view_column_set_reorderable(c, TRUE);
361     g_object_set(r, "xalign", (gfloat)1.0, (char *)0);
362     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
363   }
364   {
365     GtkCellRenderer *r = gtk_cell_renderer_toggle_new();
366     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
367       ("Queued",
368        r,
369        "active", STATE_COLUMN,
370        "visible", ISFILE_COLUMN,
371        (char *)0);
372     gtk_tree_view_column_set_resizable(c, TRUE);
373     gtk_tree_view_column_set_reorderable(c, TRUE);
374     gtk_tree_view_append_column(GTK_TREE_VIEW(choose_view), c);
375     g_signal_connect(r, "toggled",
376                      G_CALLBACK(choose_state_toggled), 0);
377   }
378   
379   /* The selection should support multiple things being selected */
380   choose_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(choose_view));
381   gtk_tree_selection_set_mode(choose_selection, GTK_SELECTION_MULTIPLE);
382
383   /* Catch button presses */
384   g_signal_connect(choose_view, "button-press-event",
385                    G_CALLBACK(choose_button_event), 0);
386   g_signal_connect(choose_view, "button-release-event",
387                    G_CALLBACK(choose_button_event), 0);
388   /* Catch row expansions so we can fill in placeholders */
389   g_signal_connect(choose_view, "row-expanded",
390                    G_CALLBACK(choose_row_expanded), 0);
391
392   event_register("queue-list-changed", choose_set_state, 0);
393   event_register("playing-track-changed", choose_set_state, 0);
394   
395   /* Fill the root */
396   disorder_eclient_files(client, choose_files_completed, "", NULL, NULL); 
397   disorder_eclient_dirs(client, choose_dirs_completed, "", NULL, NULL); 
398   
399   /* Make the widget scrollable */
400   GtkWidget *scrolled = scroll_widget(choose_view);
401   g_object_set_data(G_OBJECT(scrolled), "type", (void *)&choose_tabtype);
402   return scrolled;
403 }
404
405 /*
406 Local Variables:
407 c-basic-offset:2
408 comment-column:40
409 fill-column:79
410 indent-tabs-mode:nil
411 End:
412 */