chiark / gitweb /
Columns are now resizable and wide columns are ellipsized. Columns
[disorder] / disobedience / choose.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2006-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 don't use the built-in tree widgets because they require that you know
24  * the children of a node on demand, and we have to wait for the server to tell
25  * us.
26  */
27
28 #include "disobedience.h"
29 #include "timeval.h"
30
31 /* Choose track ------------------------------------------------------------ */
32
33 #if TDEBUG
34 /* Timing */
35 static struct {
36   struct timeval total;
37   struct timeval gtkbits;
38   struct timeval menuupdate;
39   struct timeval new_widgets;
40   struct timeval undisplay;
41   struct timeval colors;
42   struct timeval markers;
43   struct timeval location;
44   struct timeval selection;
45 } times;
46
47 #define BEGIN(WHAT) do {                        \
48   struct timeval started##WHAT, finished##WHAT; \
49   xgettimeofday(&started##WHAT, 0)
50
51 #define END(WHAT)                                                       \
52   xgettimeofday(&finished##WHAT, 0);                                    \
53   times.WHAT = tvadd(times.WHAT, tvsub(finished##WHAT, started##WHAT)); \
54 } while(0)
55
56 #define INIT() memset(&times, 0, sizeof times)
57
58 #define REPORT() do {                           \
59   fprintf(stderr, "total=%g\n"                  \
60           "gtkbits=%g\n"                        \
61           "menuupdate=%g\n"                     \
62           "new_widgets=%g\n"                    \
63           "undisplay=%g\n"                      \
64           "colors=%g\n"                         \
65           "markers=%g\n"                        \
66           "location=%g\n"                       \
67           "selection=%g\n"                      \
68           "accumulation=%g\n"                   \
69           "\n",                                 \
70           tvdouble(times.total),                \
71           tvdouble(times.gtkbits),              \
72           tvdouble(times.menuupdate),           \
73           tvdouble(times.new_widgets),          \
74           tvdouble(times.undisplay),            \
75           tvdouble(times.colors),               \
76           tvdouble(times.markers),              \
77           tvdouble(times.location),             \
78           tvdouble(times.selection),            \
79           (tvdouble(times.gtkbits)              \
80            + tvdouble(times.menuupdate)         \
81            + tvdouble(times.new_widgets)        \
82            + tvdouble(times.undisplay)          \
83            + tvdouble(times.colors)             \
84            + tvdouble(times.markers)            \
85            + tvdouble(times.location)           \
86            + tvdouble(times.selection)));       \
87 } while(0)
88 #else
89 #define BEGIN(WHAT) do {
90 #define END(WHAT) } while(0)
91 #define INIT() ((void)0)
92 #define REPORT() ((void)0)
93 #endif
94
95 WT(label);
96 WT(event_box);
97 WT(menu);
98 WT(menu_item);
99 WT(layout);
100 WT(vbox);
101 WT(arrow);
102 WT(hbox);
103 WT(button);
104 WT(image);
105 WT(entry);
106
107 /* Types */
108
109 struct choosenode;
110
111 /** @brief Accumulated information about the tree widget */
112 struct displaydata {
113   /** @brief Maximum width required */
114   guint width;
115   /** @brief Maximum height required */
116   guint height;
117 };
118
119 /* instantiate the node vector type */
120
121 VECTOR_TYPE(nodevector, struct choosenode *, xrealloc);
122
123 /** @brief Signature of function called when a choosenode is filled */
124 typedef void (when_filled_callback)(struct choosenode *cn,
125                                     void *wfu);
126
127 /** @brief One node in the virtual filesystem */
128 struct choosenode {
129   struct choosenode *parent;            /**< @brief parent node */
130   const char *path;                     /**< @brief full path or 0  */
131   const char *sort;                     /**< @brief sort key */
132   const char *display;                  /**< @brief display name */
133   int pending;                          /**< @brief pending resolve queries */
134   unsigned flags;
135 #define CN_EXPANDABLE 0x0001            /**< @brief node is expandable */
136 #define CN_EXPANDED 0x0002              /**< @brief node is expanded
137                                          *
138                                          * Expandable items are directories;
139                                          * non-expandable ones are files. */
140 #define CN_DISPLAYED 0x0004             /**< @brief widget is displayed in layout */
141 #define CN_SELECTED 0x0008              /**< @brief node is selected */
142 #define CN_GETTING_FILES 0x0010         /**< @brief files inbound */
143 #define CN_RESOLVING_FILES 0x0020       /**< @brief resolved files inbound */
144 #define CN_GETTING_DIRS 0x0040          /**< @brief directories inbound */
145 #define CN_GETTING_ANY 0x0070           /**< @brief getting something */
146 #define CN_CONTINGENT 0x0080            /**< @brief expansion contingent on search */
147   struct nodevector children;           /**< @brief vector of children */
148   void (*fill)(struct choosenode *);    /**< @brief request child fill or 0 for leaf */
149   GtkWidget *container;                 /**< @brief the container for this row */
150   GtkWidget *hbox;                      /**< @brief the hbox for this row */
151   GtkWidget *arrow;                     /**< @brief arrow widget or 0 */
152   GtkWidget *label;                     /**< @brief text label for this node */
153   GtkWidget *marker;                    /**< @brief queued marker */
154
155   when_filled_callback *whenfilled;     /**< @brief called when filled or 0 */
156   void *wfu;                            /**< @brief passed to @c whenfilled */
157   int ymin;                             /**< @brief least Y value */
158   int ymax;                             /**< @brief greatest Y value */
159 };
160
161 /** @brief One item in the popup menu */
162 struct choose_menuitem {
163   /* Parameters */
164   const char *name;                     /**< @brief name */
165
166   /* Callbacks */
167   void (*activate)(GtkMenuItem *menuitem, gpointer user_data);
168   /**< @brief Called to activate the menu item.
169    *
170    * @p user_data is the choosenode the mouse pointer is over. */
171
172   gboolean (*sensitive)(struct choosenode *cn);
173   /* @brief Called to determine whether the menu item should be sensitive.
174    *
175    * TODO? */
176
177   /* State */
178   gulong handlerid;                     /**< @brief signal handler ID */
179   GtkWidget *w;                         /**< @brief menu item widget */
180 };
181
182 /* Variables */
183
184 static GtkWidget *chooselayout;
185 static GtkAdjustment *vadjust;
186 static GtkWidget *searchentry;          /**< @brief search terms */
187 static GtkWidget *nextsearch;           /**< @brief next search result */
188 static GtkWidget *prevsearch;           /**< @brief previous search result */
189 static struct choosenode *root;
190 static GtkWidget *track_menu;           /**< @brief track popup menu */
191 static GtkWidget *dir_menu;             /**< @brief directory popup menu */
192 static struct choosenode *last_click;   /**< @brief last clicked node for selection */
193 static int files_visible;               /**< @brief total files visible */
194 static int files_selected;              /**< @brief total files selected */
195 static int gets_in_flight;              /**< @brief total gets in flight */
196 static int search_in_flight;            /**< @brief a search is underway */
197 static int search_obsolete;             /**< @brief the current search is void */
198 static char **searchresults;            /**< @brief search results */
199 static int nsearchresults;              /**< @brief number of results */
200 static int nsearchvisible;      /**< @brief number of search results visible */
201 static struct hash *searchhash;         /**< @brief hash of search results */
202 static struct progress_window *spw;     /**< @brief progress window */
203 static struct choosenode **searchnodes; /**< @brief choosenodes of search results */
204 static int suppress_redisplay;          /**< @brief suppress redisplay */
205
206 /* Forward Declarations */
207
208 static void clear_children(struct choosenode *cn);
209 static struct choosenode *newnode(struct choosenode *parent,
210                                   const char *path,
211                                   const char *display,
212                                   const char *sort,
213                                   unsigned flags,
214                                   void (*fill)(struct choosenode *));
215 static void fill_root_node(struct choosenode *cn);
216 static void fill_directory_node(struct choosenode *cn);
217 static void got_files(void *v, const char *error, int nvec, char **vec);
218 static void got_resolved_file(void *v, const char *error, const char *track);
219 static void got_dirs(void *v, const char *error, int nvec, char **vec);
220
221 static void expand_node(struct choosenode *cn, int contingent);
222 static void contract_node(struct choosenode *cn);
223 static void updated_node(struct choosenode *cn, int redisplay,
224                          const char *why);
225
226 static void display_selection(struct choosenode *cn);
227 static void clear_selection(struct choosenode *cn);
228
229 static void redisplay_tree(const char *why);
230 static struct displaydata display_tree(struct choosenode *cn, int x, int y);
231 static void undisplay_tree(struct choosenode *cn);
232 static void initiate_search(void);
233 static void delete_widgets(struct choosenode *cn);
234 static void expand_from(struct choosenode *cn);
235 static struct choosenode *first_search_result(struct choosenode *cn);
236
237 static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
238                                GdkEventButton *event,
239                                gpointer user_data);
240
241 static void activate_track_play(GtkMenuItem *menuitem, gpointer user_data);
242 static void activate_track_properties(GtkMenuItem *menuitem, gpointer user_data);
243
244 static gboolean sensitive_track_play(struct choosenode *cn);
245 static gboolean sensitive_track_properties(struct choosenode *cn);
246
247 static void activate_dir_play(GtkMenuItem *menuitem, gpointer user_data);
248 static void activate_dir_properties(GtkMenuItem *menuitem, gpointer user_data);
249 static void activate_dir_select(GtkMenuItem *menuitem, gpointer user_data);
250
251 static gboolean sensitive_dir_play(struct choosenode *cn);
252 static gboolean sensitive_dir_properties(struct choosenode *cn);
253 static gboolean sensitive_dir_select(struct choosenode *cn);
254
255 /** @brief Track menu items */
256 static struct choose_menuitem track_menuitems[] = {
257   { "Play track", activate_track_play, sensitive_track_play, 0, 0 },
258   { "Track properties", activate_track_properties, sensitive_track_properties, 0, 0 },
259   { 0, 0, 0, 0, 0 }
260 };
261
262 /** @brief Directory menu items */
263 static struct choose_menuitem dir_menuitems[] = {
264   { "Play all tracks", activate_dir_play, sensitive_dir_play, 0, 0 },
265   { "Track properties", activate_dir_properties, sensitive_dir_properties, 0, 0 },
266   { "Select all tracks", activate_dir_select, sensitive_dir_select, 0, 0 },
267   { 0, 0, 0, 0, 0 }
268 };
269
270 /* Maintaining the data structure ------------------------------------------ */
271
272 static char *cnflags(const struct choosenode *cn) {
273   unsigned f = cn->flags, n;
274   struct dynstr d[1];
275   
276   static const char *bits[] = {
277     "expandable",
278     "expanded",
279     "displayed",
280     "selected",
281     "getting_files",
282     "resolving_files",
283     "getting_dirs",
284     "contingent"
285   };
286 #define NBITS (sizeof bits / sizeof *bits)
287
288   dynstr_init(d);
289   if(!f)
290     dynstr_append(d, '0');
291   else {
292     for(n = 0; n < NBITS; ++n) {
293       const unsigned bit = 1 << n;
294       if(f & bit) {
295         if(d->nvec)
296           dynstr_append(d, '|');
297         dynstr_append_string(d, bits[n]);
298         f ^= bit;
299       }
300     }
301     if(f) {
302       char buf[32];
303       if(d->nvec)
304         dynstr_append(d, '|');
305       sprintf(buf, "%#x", f);
306       dynstr_append_string(d, buf);
307     }
308   }
309   dynstr_terminate(d);
310   return d->vec;
311 }
312
313 /** @brief Create a new node */
314 static struct choosenode *newnode(struct choosenode *parent,
315                                   const char *path,
316                                   const char *display,
317                                   const char *sort,
318                                   unsigned flags,
319                                   void (*fill)(struct choosenode *)) {
320   struct choosenode *const n = xmalloc(sizeof *n);
321
322   D(("newnode %s %s", path, display));
323   if(flags & CN_EXPANDABLE)
324     assert(fill);
325   else
326     assert(!fill);
327   n->parent = parent;
328   n->path = path;
329   n->display = display;
330   n->sort = sort;
331   n->flags = flags;
332   nodevector_init(&n->children);
333   n->fill = fill;
334   if(parent)
335     nodevector_append(&parent->children, n);
336   return n;
337 }
338
339 /** @brief Called when a node has been filled
340  *
341  * Response for calling @c whenfilled.
342  */
343 static void filled(struct choosenode *cn) {
344   when_filled_callback *const whenfilled = cn->whenfilled;
345
346   if(whenfilled) {
347     cn->whenfilled = 0;
348     whenfilled(cn, cn->wfu);
349   }
350   if(nsearchvisible < nsearchresults) {
351     /* There is still search expansion work to do */
352     D(("filled %s %d/%d", cn->path, nsearchvisible, nsearchresults));
353     expand_from(cn);
354   }
355   if(gets_in_flight == 0 && nsearchvisible < nsearchresults)
356     expand_from(root);
357 }
358
359 /** @brief Fill the root */
360 static void fill_root_node(struct choosenode *cn) {
361   D(("fill_root_node"));
362   clear_children(cn);
363   /* More de-duping possible here */
364   if(cn->flags & CN_GETTING_ANY)
365     return;
366   gtk_label_set_text(GTK_LABEL(report_label), "getting files");
367   disorder_eclient_dirs(client, got_dirs, "", 0, cn);
368   disorder_eclient_files(client, got_files, "", 0, cn);
369   cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
370   gets_in_flight += 2;
371 }
372
373 /** @brief Delete all the widgets owned by @p cn */
374 static void delete_cn_widgets(struct choosenode *cn) {
375   if(cn->arrow) {
376     DW(arrow);
377     gtk_widget_destroy(cn->arrow);
378     cn->arrow = 0;
379   }
380   if(cn->label) {
381     DW(label);
382     gtk_widget_destroy(cn->label);
383     cn->label = 0;
384   }
385   if(cn->marker) {
386     DW(image);
387     gtk_widget_destroy(cn->marker);
388     cn->marker = 0;
389   }
390   if(cn->hbox) {
391     DW(hbox);
392     gtk_widget_destroy(cn->hbox);
393     cn->hbox = 0;
394   }
395   if(cn->container) {
396     DW(event_box);
397     gtk_widget_destroy(cn->container);
398     cn->container = 0;
399   }
400 }
401
402 /** @brief Recursively clear all the children of @p cn
403  *
404  * All the widgets at or below @p cn are deleted.  All choosenodes below
405  * it are emptied. i.e. we prune the tree at @p cn.
406  */
407 static void clear_children(struct choosenode *cn) {
408   int n;
409
410   D(("clear_children %s", cn->path));
411   /* Recursively clear subtrees */
412   for(n = 0; n < cn->children.nvec; ++n) {
413     clear_children(cn->children.vec[n]);
414     delete_cn_widgets(cn->children.vec[n]);
415   }
416   cn->children.nvec = 0;
417 }
418
419 /** @brief Called with a list of files just below some node */
420 static void got_files(void *v, const char *error, int nvec, char **vec) {
421   struct choosenode *cn = v;
422   int n;
423
424   if(error) {
425     popup_protocol_error(0, error);
426     return;
427   }
428
429   D(("got_files %d files for %s %s", nvec, cn->path, cnflags(cn)));
430   /* Complicated by the need to resolve aliases. */
431   cn->flags &= ~CN_GETTING_FILES;
432   --gets_in_flight;
433   if((cn->pending = nvec)) {
434     cn->flags |= CN_RESOLVING_FILES;
435     for(n = 0; n < nvec; ++n) {
436       disorder_eclient_resolve(client, got_resolved_file, vec[n], cn);
437       ++gets_in_flight;
438     }
439   }
440   /* If there are no files and the directories are all read by now, we're
441    * done */
442   if(!(cn->flags & CN_GETTING_ANY))
443     filled(cn);
444   if(!gets_in_flight)
445     redisplay_tree("got_files");
446 }
447
448 /** @brief Called with an alias resolved filename */
449 static void got_resolved_file(void *v, const char *error, const char *track) {
450   struct choosenode *const cn = v, *file_cn;
451
452   if(error) {
453     popup_protocol_error(0, error);
454   } else {
455     D(("resolved %s %s %d left", cn->path, cnflags(cn), cn->pending - 1));
456     /* TODO as below */
457     file_cn = newnode(cn, track,
458                       trackname_transform("track", track, "display"),
459                       trackname_transform("track", track, "sort"),
460                       0/*flags*/, 0/*fill*/);
461     --gets_in_flight;
462     /* Only bother updating when we've got the lot */
463     if(--cn->pending == 0) {
464       cn->flags &= ~CN_RESOLVING_FILES;
465       updated_node(cn, gets_in_flight == 0, "got_resolved_file");
466       if(!(cn->flags & CN_GETTING_ANY))
467         filled(cn);
468     }
469   }
470 }
471
472 /** @brief Called with a list of directories just below some node */
473 static void got_dirs(void *v, const char *error, int nvec, char **vec) {
474   struct choosenode *cn = v;
475   int n;
476   
477   if(error) {
478     popup_protocol_error(0, error);
479     return;
480   }
481
482   D(("got_dirs %d dirs for %s %s", nvec, cn->path, cnflags(cn)));
483   /* TODO this depends on local configuration for trackname_transform().
484    * This will work, since the defaults are now built-in, but it'll be
485    * (potentially) different to the server's configured settings.
486    *
487    * Really we want a variant of files/dirs that produces both the
488    * raw filename and the transformed name for a chosen context.
489    */
490   --gets_in_flight;
491   for(n = 0; n < nvec; ++n)
492     newnode(cn, vec[n],
493             trackname_transform("dir", vec[n], "display"),
494             trackname_transform("dir", vec[n], "sort"),
495             CN_EXPANDABLE, fill_directory_node);
496   updated_node(cn, gets_in_flight == 0, "got_dirs");
497   cn->flags &= ~CN_GETTING_DIRS;
498   if(!(cn->flags & CN_GETTING_ANY))
499     filled(cn);
500 }
501   
502 /** @brief Fill a child node */
503 static void fill_directory_node(struct choosenode *cn) {
504   D(("fill_directory_node %s", cn->path));
505   /* TODO: caching */
506   if(cn->flags & CN_GETTING_ANY)
507     return;
508   assert(report_label != 0);
509   gtk_label_set_text(GTK_LABEL(report_label), "getting files");
510   clear_children(cn);
511   disorder_eclient_dirs(client, got_dirs, cn->path, 0, cn);
512   disorder_eclient_files(client, got_files, cn->path, 0, cn);
513   cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
514   gets_in_flight += 2;
515 }
516
517 /** @brief Expand a node */
518 static void expand_node(struct choosenode *cn, int contingent) {
519   D(("expand_node %s %d %s", cn->path, contingent, cnflags(cn)));
520   assert(cn->flags & CN_EXPANDABLE);
521   /* If node is already expanded do nothing. */
522   if(cn->flags & CN_EXPANDED) return;
523   /* We mark the node as expanded and request that it fill itself.  When it has
524    * completed it will called updated_node() and we can redraw at that
525    * point. */
526   cn->flags |= CN_EXPANDED;
527   if(contingent)
528     cn->flags |= CN_CONTINGENT;
529   else
530     cn->flags &= ~CN_CONTINGENT;
531   /* If this node is not contingently expanded, mark all its parents back to
532    * the root as not contingent either, so they won't be contracted when the
533    * search results change */
534   if(!contingent) {
535     struct choosenode *cnp;
536
537     for(cnp = cn->parent; cnp; cnp = cnp->parent)
538       cnp->flags &= ~CN_CONTINGENT;
539   }
540   /* TODO: visual feedback */
541   cn->fill(cn);
542 }
543
544 /** @brief Make sure all the search results below @p cn are expanded
545  * @param cn Node to start at
546  */
547 static void expand_from(struct choosenode *cn) {
548   int n;
549
550   if(nsearchvisible == nsearchresults)
551     /* We're done */
552     return;
553   /* Are any of the search tracks at/below this point? */
554   if(!(cn == root || hash_find(searchhash, cn->path)))
555     return;
556   D(("expand_from %d/%d visible %s", 
557      nsearchvisible, nsearchresults, cn->path));
558   if(cn->flags & CN_EXPANDABLE) {
559     if(cn->flags & CN_EXPANDED)
560       /* This node is marked as expanded already.  children.nvec might be 0,
561        * indicating that expansion is still underway.  We should get another
562        * callback when it is expanded. */
563       for(n = 0; n < cn->children.nvec && gets_in_flight < 10; ++n)
564         expand_from(cn->children.vec[n]);
565     else {
566       /* This node is not expanded yet */
567       expand_node(cn, 1);
568     }
569   } else {
570     /* This is an actual search result */
571     ++nsearchvisible;
572     progress_window_progress(spw, nsearchvisible, nsearchresults);
573     if(nsearchvisible == nsearchresults) {
574       if(suppress_redisplay) {
575         suppress_redisplay = 0;
576         redisplay_tree("all search results visible");
577       }
578       /* We've got the lot.  We make sure the first result is visible. */
579       cn = first_search_result(root);
580       gtk_adjustment_clamp_page(vadjust, cn->ymin, cn->ymax);
581     }
582   }
583 }
584
585 /** @brief Contract all contingently expanded nodes below @p cn */
586 static void contract_contingent(struct choosenode *cn) {
587   int n;
588
589   if(cn->flags & CN_CONTINGENT)
590     contract_node(cn);
591   else
592     for(n = 0; n < cn->children.nvec; ++n)
593       contract_contingent(cn->children.vec[n]);
594 }
595
596 /** @brief Contract a node */
597 static void contract_node(struct choosenode *cn) {
598   D(("contract_node %s", cn->path));
599   assert(cn->flags & CN_EXPANDABLE);
600   /* If node is already contracted do nothing. */
601   if(!(cn->flags & CN_EXPANDED)) return;
602   cn->flags &= ~(CN_EXPANDED|CN_CONTINGENT);
603   /* Clear selection below this node */
604   clear_selection(cn);
605   /* Zot children.  We never used to do this but the result would be that over
606    * time you'd end up with the entire tree pulled into memory.  If the server
607    * is over a slow network it will make interactivity slightly worse; if
608    * anyone complains we can make it an option. */
609   clear_children(cn);
610   /* We can contract a node immediately. */
611   redisplay_tree("contract_node");
612 }
613
614 /** @brief qsort() callback for ordering choosenodes */
615 static int compare_choosenode(const void *av, const void *bv) {
616   const struct choosenode *const *aa = av, *const *bb = bv;
617   const struct choosenode *a = *aa, *b = *bb;
618
619   return compare_tracks(a->sort, b->sort,
620                         a->display, b->display,
621                         a->path, b->path);
622 }
623
624 /** @brief Called when an expandable node is updated.   */
625 static void updated_node(struct choosenode *cn, int redisplay,
626                          const char *why) {
627   D(("updated_node %s", cn->path));
628   assert(cn->flags & CN_EXPANDABLE);
629   /* It might be that the node has been de-expanded since we requested the
630    * update.  In that case we ignore this notification. */
631   if(!(cn->flags & CN_EXPANDED)) return;
632   /* Sort children */
633   qsort(cn->children.vec, cn->children.nvec, sizeof (struct choosenode *),
634         compare_choosenode);
635   if(redisplay) {
636     char whywhy[1024];
637
638     snprintf(whywhy, sizeof whywhy, "updated_node %s", why);
639     redisplay_tree(whywhy);
640   }
641 }
642
643 /* Searching --------------------------------------------------------------- */
644
645 /** @brief Return true if @p track is a search result
646  *
647  * In particular the return value is one more than the index of the track
648  * @p searchresults.
649  */
650 static int is_search_result(const char *track) {
651   void *r;
652
653   if(searchhash && (r = hash_find(searchhash, track)))
654     return 1 + *(int *)r;
655   else
656     return 0;
657 }
658
659 /** @brief Return the first search result at or below @p cn */
660 static struct choosenode *first_search_result(struct choosenode *cn) {
661   int n;
662   struct choosenode *r;
663
664   if(cn->flags & CN_EXPANDABLE) {
665     for(n = 0; n < cn->children.nvec; ++n)
666       if((r = first_search_result(cn->children.vec[n])))
667         return r;
668   } else if(is_search_result(cn->path))
669     return cn;
670   return 0;
671 }
672
673 /** @brief Called with a list of search results
674  *
675  * This is called from eclient with a (possibly empty) list of search results,
676  * and also from initiate_seatch with an always empty list to indicate that
677  * we're not searching for anything in particular. */
678 static void search_completed(void attribute((unused)) *v,
679                              const char *error,
680                              int nvec, char **vec) {
681   int n;
682   char *s;
683
684   if(error) {
685     popup_protocol_error(0, error);
686     return;
687   }
688   
689   search_in_flight = 0;
690   /* Contract any choosenodes that were only expanded to show search
691    * results */
692   suppress_redisplay = 1;
693   contract_contingent(root);
694   suppress_redisplay = 0;
695   if(search_obsolete) {
696     /* This search has been obsoleted by user input since it started.
697      * Therefore we throw away the result and search again. */
698     search_obsolete = 0;
699     initiate_search();
700   } else {
701     /* Stash the search results */
702     searchresults = vec;
703     nsearchresults = nvec;
704     if(nvec) {
705       /* Create a new search hash for fast identification of results */
706       searchhash = hash_new(sizeof(int));
707       for(n = 0; n < nvec; ++n) {
708         int *const ip = xmalloc(sizeof (int *));
709         static const int minus_1 = -1;
710         *ip = n;
711         /* The filename itself lives in the hash */
712         hash_add(searchhash, vec[n], ip, HASH_INSERT_OR_REPLACE);
713         /* So do its ancestor directories */
714         for(s = vec[n] + 1; *s; ++s) {
715           if(*s == '/') {
716             *s = 0;
717             hash_add(searchhash, vec[n], &minus_1, HASH_INSERT_OR_REPLACE);
718             *s = '/';
719           }
720         }
721       }
722       /* We don't yet know that the results are visible */
723       nsearchvisible = 0;
724       if(spw) {
725         progress_window_progress(spw, 0, 0);
726         spw = 0;
727       }
728       if(nsearchresults > 50)
729         spw = progress_window_new("Fetching search results");
730       /* Initiate expansion */
731       expand_from(root);
732       /* The search results buttons are usable */
733       gtk_widget_set_sensitive(nextsearch, 1);
734       gtk_widget_set_sensitive(prevsearch, 1);
735       suppress_redisplay = 1;           /* avoid lots of redisplays */
736     } else {
737       searchhash = 0;                   /* for the gc */
738       redisplay_tree("no search results"); /* remove search markers */
739       /* The search results buttons are not usable */
740       gtk_widget_set_sensitive(nextsearch, 0);
741       gtk_widget_set_sensitive(prevsearch, 0);
742     }
743   }
744 }
745
746 /** @brief Initiate a search 
747  *
748  * If a search is underway we set @ref search_obsolete and restart the search
749  * in search_completed() above.
750  */
751 static void initiate_search(void) {
752   char *terms, *e;
753
754   /* Find out what the user is after */
755   terms = xstrdup(gtk_entry_get_text(GTK_ENTRY(searchentry)));
756   /* Strip leading and trailing space */
757   while(*terms == ' ') ++terms;
758   e = terms + strlen(terms);
759   while(e > terms && e[-1] == ' ') --e;
760   *e = 0;
761   /* If a search is already underway then mark it as obsolete.  We'll revisit
762    * when it returns. */
763   if(search_in_flight) {
764     search_obsolete = 1;
765     return;
766   }
767   if(*terms) {
768     /* There's still something left.  Initiate the search. */
769     if(disorder_eclient_search(client, search_completed, terms, 0)) {
770       /* The search terms are bad!  We treat this as if there were no search
771        * terms at all.  Some kind of feedback would be handy. */
772       fprintf(stderr, "bad terms [%s]\n", terms); /* TODO */
773       search_completed(0, 0, 0, 0);
774     } else {
775       search_in_flight = 1;
776     }
777   } else {
778     /* No search terms - we want to see all tracks */
779     search_completed(0, 0, 0, 0);
780   }
781 }
782
783 /** @brief Called when the cancel search button is clicked */
784 static void clearsearch_clicked(GtkButton attribute((unused)) *button,
785                                 gpointer attribute((unused)) userdata) {
786   gtk_entry_set_text(GTK_ENTRY(searchentry), "");
787   /* Put the input focus back */
788   gtk_widget_grab_focus(searchentry);
789 }
790
791 /** @brief Called when the 'next search result' button is clicked */
792 static void next_clicked(GtkButton attribute((unused)) *button,
793                          gpointer attribute((unused)) userdata) {
794   /* We want to find the highest (lowest ymax) track that is below the current
795    * visible range */
796   int n;
797   const gdouble bottom = gtk_adjustment_get_value(vadjust) + vadjust->page_size;
798   const struct choosenode *candidate = 0;
799
800   for(n = 0; n < nsearchresults; ++n) {
801     const struct choosenode *const cn = searchnodes[n];
802
803     if(cn
804        && cn->ymax > bottom
805        && (candidate == 0
806            || cn->ymax < candidate->ymax))
807       candidate = cn;
808   }
809   if(candidate)
810     gtk_adjustment_clamp_page(vadjust, candidate->ymin, candidate->ymax);
811 }
812
813 /** @brief Called when the 'previous search result' button is clicked */
814 static void prev_clicked(GtkButton attribute((unused)) *button,
815                          gpointer attribute((unused)) userdata) {
816   /* We want to find the lowest (greated ymax) track that is above the current
817    * visible range */
818   int n;
819   const gdouble top = gtk_adjustment_get_value(vadjust);
820   const struct choosenode *candidate = 0;
821
822   for(n = 0; n < nsearchresults; ++n) {
823     const struct choosenode *const cn = searchnodes[n];
824
825     if(cn
826        && cn->ymin  < top
827        && (candidate == 0
828            || cn->ymax > candidate->ymax))
829       candidate = cn;
830   }
831   if(candidate)
832     gtk_adjustment_clamp_page(vadjust, candidate->ymin, candidate->ymax);
833 }
834
835 /* Display functions ------------------------------------------------------- */
836
837 /** @brief Delete all the widgets in the tree */
838 static void delete_widgets(struct choosenode *cn) {
839   int n;
840
841   delete_cn_widgets(cn);
842   for(n = 0; n < cn->children.nvec; ++n)
843     delete_widgets(cn->children.vec[n]);
844   cn->flags &= ~(CN_DISPLAYED|CN_SELECTED);
845   files_selected = 0;
846 }
847
848 /** @brief Update the display */
849 static void redisplay_tree(const char *why) {
850   struct displaydata d;
851   guint oldwidth, oldheight;
852
853   D(("redisplay_tree %s", why));
854   if(suppress_redisplay) {
855     /*fprintf(stderr, "redisplay_tree %s suppressed\n", why);*/
856     return;
857   }
858   if(gets_in_flight) {
859     /*fprintf(stderr, "redisplay_tree %s suppressed (gets_in_flight)\n", why);*/
860     return;
861   }
862   INIT();
863   BEGIN(total);
864   /*fprintf(stderr, "redisplay_tree %s   *** NOT SUPPRESSED ***\n", why);*/
865   /* We'll count these up empirically each time */
866   files_selected = 0;
867   files_visible = 0;
868   /* Correct the layout and find out how much space it uses */
869   MTAG_PUSH("display_tree");
870   searchnodes = nsearchresults ? xcalloc(nsearchresults, 
871                                          sizeof (struct choosenode *)) : 0;
872   d = display_tree(root, 0, 0);
873   MTAG_POP();
874
875   BEGIN(gtkbits);
876   /* We must set the total size or scrolling will not work (it wouldn't be hard
877    * for GtkLayout to figure it out for itself but presumably you're supposed
878    * to be able to have widgets off the edge of the layuot.)
879    *
880    * There is a problem: if we shrink the size then the part of the screen that
881    * is outside the new size but inside the old one is not updated.  I think
882    * this is arguably bug in GTK+ but it's easy to force a redraw if this
883    * region is nonempty.
884    */
885   gtk_layout_get_size(GTK_LAYOUT(chooselayout), &oldwidth, &oldheight);
886   if(oldwidth > d.width || oldheight > d.height)
887     gtk_widget_queue_draw(chooselayout);
888   gtk_layout_set_size(GTK_LAYOUT(chooselayout), d.width, d.height);
889   END(gtkbits);
890   /* Notify the main menu of any recent changes */
891   BEGIN(menuupdate);
892   menu_update(-1);
893   END(menuupdate);
894   END(total);
895   REPORT();
896 }
897
898 /** @brief Recursive step for redisplay_tree()
899  * @param cn Node to display
900  * @param x X coordinate for @p cn
901  * @param y Y coordinate for @p cn
902  *
903  * Makes sure all displayed widgets from CN down exist and are in their proper
904  * place and return the maximum space used.
905  */
906 static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
907   int n, aw;
908   GtkRequisition req;
909   struct displaydata d, cd;
910   GdkPixbuf *pb;
911   const int search_result = is_search_result(cn->path);
912   
913   D(("display_tree %s %d,%d", cn->path, x, y));
914
915   /* An expandable item contains an arrow and a text label.  When you press the
916    * button it flips its expand state.
917    *
918    * A non-expandable item has just a text label and no arrow.
919    */
920   if(!cn->container) {
921     BEGIN(new_widgets);
922     MTAG_PUSH("make_widgets_1");
923     /* Widgets need to be created */
924     NW(hbox);
925     cn->hbox = gtk_hbox_new(FALSE, 1);
926     if(cn->flags & CN_EXPANDABLE) {
927       NW(arrow);
928       cn->arrow = gtk_arrow_new(cn->flags & CN_EXPANDED ? GTK_ARROW_DOWN
929                                                         : GTK_ARROW_RIGHT,
930                                 GTK_SHADOW_NONE);
931       cn->marker = 0;
932     } else {
933       cn->arrow = 0;
934       if((pb = find_image("notes.png"))) {
935         NW(image);
936         cn->marker = gtk_image_new_from_pixbuf(pb);
937       }
938     }
939     MTAG_POP();
940     MTAG_PUSH("make_widgets_2");
941     NW(label);
942     cn->label = gtk_label_new(cn->display);
943     if(cn->arrow)
944       gtk_container_add(GTK_CONTAINER(cn->hbox), cn->arrow);
945     gtk_container_add(GTK_CONTAINER(cn->hbox), cn->label);
946     if(cn->marker)
947       gtk_container_add(GTK_CONTAINER(cn->hbox), cn->marker);
948     MTAG_POP();
949     MTAG_PUSH("make_widgets_3");
950     NW(event_box);
951     cn->container = gtk_event_box_new();
952     gtk_container_add(GTK_CONTAINER(cn->container), cn->hbox);
953     g_signal_connect(cn->container, "button-release-event", 
954                      G_CALLBACK(clicked_choosenode), cn);
955     g_signal_connect(cn->container, "button-press-event", 
956                      G_CALLBACK(clicked_choosenode), cn);
957     g_object_ref(cn->container);
958     /* Show everything by default */
959     gtk_widget_show_all(cn->container);
960     MTAG_POP();
961     END(new_widgets);
962   }
963   assert(cn->container);
964   /* Set colors */
965   BEGIN(colors);
966   if(search_result) {
967     gtk_widget_set_style(cn->container, search_style);
968     gtk_widget_set_style(cn->label, search_style);
969   } else {
970     gtk_widget_set_style(cn->container, layout_style);
971     gtk_widget_set_style(cn->label, layout_style);
972   }
973   END(colors);
974   /* Make sure the icon is right */
975   BEGIN(markers);
976   if(cn->flags & CN_EXPANDABLE)
977     gtk_arrow_set(GTK_ARROW(cn->arrow),
978                   cn->flags & CN_EXPANDED ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT,
979                   GTK_SHADOW_NONE);
980   else if(cn->marker)
981     /* Make sure the queued marker is right */
982     /* TODO: doesn't always work */
983     (queued(cn->path) ? gtk_widget_show : gtk_widget_hide)(cn->marker);
984   END(markers);
985   /* Put the widget in the right place */
986   BEGIN(location);
987   if(cn->flags & CN_DISPLAYED)
988     gtk_layout_move(GTK_LAYOUT(chooselayout), cn->container, x, y);
989   else {
990     gtk_layout_put(GTK_LAYOUT(chooselayout), cn->container, x, y);
991     cn->flags |= CN_DISPLAYED;
992     /* Now chooselayout has a ref to the container */
993     g_object_unref(cn->container);
994   }
995   END(location);
996   /* Set the widget's selection status */
997   BEGIN(selection);
998   if(!(cn->flags & CN_EXPANDABLE))
999     display_selection(cn);
1000   END(selection);
1001   /* Find the size used so we can get vertical positioning right. */
1002   gtk_widget_size_request(cn->container, &req);
1003   d.width = x + req.width;
1004   d.height = y + req.height;
1005   cn->ymin = y;
1006   cn->ymax = d.height;
1007   if(cn->flags & CN_EXPANDED) {
1008     /* We'll offset children by the size of the arrow whatever it might be. */
1009     assert(cn->arrow);
1010     gtk_widget_size_request(cn->arrow, &req);
1011     aw = req.width;
1012     for(n = 0; n < cn->children.nvec; ++n) {
1013       cd = display_tree(cn->children.vec[n], x + aw, d.height);
1014       if(cd.width > d.width)
1015         d.width = cd.width;
1016       d.height = cd.height;
1017     }
1018   } else {
1019     BEGIN(undisplay);
1020     for(n = 0; n < cn->children.nvec; ++n)
1021       undisplay_tree(cn->children.vec[n]);
1022     END(undisplay);
1023   }
1024   if(!(cn->flags & CN_EXPANDABLE)) {
1025     ++files_visible;
1026     if(cn->flags & CN_SELECTED)
1027       ++files_selected;
1028   }
1029   /* update the search results array */
1030   if(search_result)
1031     searchnodes[search_result - 1] = cn;
1032   /* report back how much space we used */
1033   D(("display_tree %s %d,%d total size %dx%d", cn->path, x, y,
1034      d.width, d.height));
1035   return d;
1036 }
1037
1038 /** @brief Remove widgets for newly hidden nodes */
1039 static void undisplay_tree(struct choosenode *cn) {
1040   int n;
1041
1042   D(("undisplay_tree %s", cn->path));
1043   /* Remove this widget from the display */
1044   if(cn->flags & CN_DISPLAYED) {
1045     gtk_container_remove(GTK_CONTAINER(chooselayout), cn->container);
1046     cn->flags ^= CN_DISPLAYED;
1047   }
1048   /* Remove children too */
1049   for(n = 0; n < cn->children.nvec; ++n)
1050     undisplay_tree(cn->children.vec[n]);
1051 }
1052
1053 /* Selection --------------------------------------------------------------- */
1054
1055 /** @brief Mark the widget @p cn according to its selection state */
1056 static void display_selection(struct choosenode *cn) {
1057   /* Need foreground and background colors */
1058   gtk_widget_set_state(cn->label, (cn->flags & CN_SELECTED
1059                                    ? GTK_STATE_SELECTED : GTK_STATE_NORMAL));
1060   gtk_widget_set_state(cn->container, (cn->flags & CN_SELECTED
1061                                        ? GTK_STATE_SELECTED : GTK_STATE_NORMAL));
1062 }
1063
1064 /** @brief Set the selection state of a widget
1065  *
1066  * Directories can never be selected, we just ignore attempts to do so. */
1067 static void set_selection(struct choosenode *cn, int selected) {
1068   unsigned f = selected ? CN_SELECTED : 0;
1069
1070   D(("set_selection %d %s", selected, cn->path));
1071   if(!(cn->flags & CN_EXPANDABLE) && (cn->flags & CN_SELECTED) != f) {
1072     cn->flags ^= CN_SELECTED;
1073     /* Maintain selection count */
1074     if(selected)
1075       ++files_selected;
1076     else
1077       --files_selected;
1078     display_selection(cn);
1079     /* Update main menu sensitivity */
1080     menu_update(-1);
1081   }
1082 }
1083
1084 /** @brief Recursively clear all selection bits from CN down */
1085 static void clear_selection(struct choosenode *cn) {
1086   int n;
1087
1088   set_selection(cn, 0);
1089   for(n = 0; n < cn->children.nvec; ++n)
1090     clear_selection(cn->children.vec[n]);
1091 }
1092
1093 /* User actions ------------------------------------------------------------ */
1094
1095 /** @brief Called when disorder_eclient_play completes */
1096 void play_completed(void attribute((unused)) *v,
1097                     const char *error) {
1098   if(error)
1099     popup_protocol_error(0, error);
1100 }
1101
1102 /** @brief Clicked on something
1103  *
1104  * This implements playing, all the modifiers for selection, etc.
1105  */
1106 static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
1107                                GdkEventButton *event,
1108                                gpointer user_data) {
1109   struct choosenode *cn = user_data;
1110   int ind, last_ind, n;
1111
1112   D(("clicked_choosenode %s", cn->path));
1113   if(event->type == GDK_BUTTON_RELEASE
1114      && event->button == 1) {
1115     /* Left click */
1116     if(cn->flags & CN_EXPANDABLE) {
1117       /* This is a directory.  Flip its expansion status. */
1118       if(cn->flags & CN_EXPANDED)
1119         contract_node(cn);
1120       else
1121         expand_node(cn, 0/*!contingent*/);
1122       last_click = 0;
1123     } else {
1124       /* This is a file.  Adjust selection status */
1125       /* TODO the basic logic here is essentially the same as that in queue.c.
1126        * Can we share code at all? */
1127       switch(event->state & (GDK_SHIFT_MASK|GDK_CONTROL_MASK)) {
1128       case 0:
1129         clear_selection(root);
1130         set_selection(cn, 1);
1131         last_click = cn;
1132         break;
1133       case GDK_CONTROL_MASK:
1134         set_selection(cn, !(cn->flags & CN_SELECTED));
1135         last_click = cn;
1136         break;
1137       case GDK_SHIFT_MASK:
1138       case GDK_SHIFT_MASK|GDK_CONTROL_MASK:
1139         if(last_click && last_click->parent == cn->parent) {
1140           /* Figure out where the current and last clicks are in the list */
1141           ind = last_ind = -1;
1142           for(n = 0; n < cn->parent->children.nvec; ++n) {
1143             if(cn->parent->children.vec[n] == cn)
1144               ind = n;
1145             if(cn->parent->children.vec[n] == last_click)
1146               last_ind = n;
1147           }
1148           /* Test shouldn't ever fail, but still */
1149           if(ind >= 0 && last_ind >= 0) {
1150             if(!(event->state & GDK_CONTROL_MASK)) {
1151               for(n = 0; n < cn->parent->children.nvec; ++n)
1152                 set_selection(cn->parent->children.vec[n], 0);
1153             }
1154             if(ind > last_ind)
1155               for(n = last_ind; n <= ind; ++n)
1156                 set_selection(cn->parent->children.vec[n], 1);
1157             else
1158               for(n = ind; n <= last_ind; ++n)
1159                 set_selection(cn->parent->children.vec[n], 1);
1160             if(event->state & GDK_CONTROL_MASK)
1161               last_click = cn;
1162           }
1163         }
1164         /* TODO trying to select a range that doesn't share a single parent
1165          * currently does not work, but it ought to. */
1166         break;
1167       }
1168     }
1169   } else if(event->type == GDK_BUTTON_RELEASE
1170      && event->button == 2) {
1171     /* Middle click - play the pointed track */
1172     if(!(cn->flags & CN_EXPANDABLE)) {
1173       clear_selection(root);
1174       set_selection(cn, 1);
1175       gtk_label_set_text(GTK_LABEL(report_label), "adding track to queue");
1176       disorder_eclient_play(client, cn->path, play_completed, 0);
1177       last_click = 0;
1178     }
1179   } else if(event->type == GDK_BUTTON_PRESS
1180      && event->button == 3) {
1181     struct choose_menuitem *const menuitems =
1182       (cn->flags & CN_EXPANDABLE ? dir_menuitems : track_menuitems);
1183     GtkWidget *const menu =
1184       (cn->flags & CN_EXPANDABLE ? dir_menu : track_menu);
1185     /* Right click.  Pop up a menu. */
1186     /* If the current file isn't selected, switch the selection to just that.
1187      * (If we're looking at a directory then leave the selection alone.) */
1188     if(!(cn->flags & CN_EXPANDABLE) && !(cn->flags & CN_SELECTED)) {
1189       clear_selection(root);
1190       set_selection(cn, 1);
1191       last_click = cn;
1192     }
1193     /* Set the item sensitivity and callbacks */
1194     for(n = 0; menuitems[n].name; ++n) {
1195       if(menuitems[n].handlerid)
1196         g_signal_handler_disconnect(menuitems[n].w,
1197                                     menuitems[n].handlerid);
1198       gtk_widget_set_sensitive(menuitems[n].w,
1199                                menuitems[n].sensitive(cn));
1200       menuitems[n].handlerid = g_signal_connect
1201         (menuitems[n].w, "activate", G_CALLBACK(menuitems[n].activate), cn);
1202     }
1203     set_tool_colors(menu);
1204     /* Pop up the menu */
1205     gtk_widget_show_all(menu);
1206     gtk_menu_popup(GTK_MENU(menu), 0, 0, 0, 0,
1207                    event->button, event->time);
1208   }
1209 }
1210
1211 /** @brief Called BY GTK+ to tell us the search entry box has changed */
1212 static void searchentry_changed(GtkEditable attribute((unused)) *editable,
1213                                 gpointer attribute((unused)) user_data) {
1214   initiate_search();
1215 }
1216
1217 /* Track menu items -------------------------------------------------------- */
1218
1219 /** @brief Recursive step for gather_selected() */
1220 static void recurse_selected(struct choosenode *cn, struct vector *v) {
1221   int n;
1222
1223   if(cn->flags & CN_EXPANDABLE) {
1224     if(cn->flags & CN_EXPANDED)
1225       for(n = 0; n < cn->children.nvec; ++n)
1226         recurse_selected(cn->children.vec[n], v);
1227   } else {
1228     if((cn->flags & CN_SELECTED) && cn->path)
1229       vector_append(v, (char *)cn->path);
1230   }
1231 }
1232
1233 /*** @brief Get a list of all the selected tracks */
1234 static const char **gather_selected(int *ntracks) {
1235   struct vector v;
1236
1237   vector_init(&v);
1238   recurse_selected(root, &v);
1239   vector_terminate(&v);
1240   if(ntracks) *ntracks = v.nvec;
1241   return (const char **)v.vec;
1242 }
1243
1244 /** @brief Called when the track menu's play option is activated */
1245 static void activate_track_play(GtkMenuItem attribute((unused)) *menuitem,
1246                                 gpointer attribute((unused)) user_data) {
1247   const char **tracks = gather_selected(0);
1248   int n;
1249   
1250   gtk_label_set_text(GTK_LABEL(report_label), "adding track to queue");
1251   for(n = 0; tracks[n]; ++n)
1252     disorder_eclient_play(client, tracks[n], play_completed, 0);
1253 }
1254
1255 /** @brief Called when the menu's properties option is activated */
1256 static void activate_track_properties(GtkMenuItem attribute((unused)) *menuitem,
1257                                       gpointer attribute((unused)) user_data) {
1258   int ntracks;
1259   const char **tracks = gather_selected(&ntracks);
1260
1261   properties(ntracks, tracks);
1262 }
1263
1264 /** @brief Determine whether the menu's play option should be sensitive */
1265 static gboolean sensitive_track_play(struct choosenode attribute((unused)) *cn) {
1266   return (!!files_selected
1267           && (disorder_eclient_state(client) & DISORDER_CONNECTED)
1268           && (last_rights & RIGHT_PLAY));
1269 }
1270
1271 /** @brief Determine whether the menu's properties option should be sensitive */
1272 static gboolean sensitive_track_properties(struct choosenode attribute((unused)) *cn) {
1273   return (!!files_selected
1274           && (disorder_eclient_state(client) & DISORDER_CONNECTED)
1275           && (last_rights & RIGHT_PREFS));
1276 }
1277
1278 /* Directory menu items ---------------------------------------------------- */
1279
1280 /** @brief Return the file children of @p cn
1281  *
1282  * The list is terminated by a null pointer.
1283  */
1284 static const char **dir_files(struct choosenode *cn, int *nfiles) {
1285   const char **files = xcalloc(cn->children.nvec + 1, sizeof (char *));
1286   int n, m;
1287
1288   for(n = m = 0; n < cn->children.nvec; ++n) 
1289     if(!(cn->children.vec[n]->flags & CN_EXPANDABLE))
1290       files[m++] = cn->children.vec[n]->path;
1291   files[m] = 0;
1292   if(nfiles) *nfiles = m;
1293   return files;
1294 }
1295
1296 static void play_dir(struct choosenode *cn,
1297                      void attribute((unused)) *wfu) {
1298   int ntracks, n;
1299   const char **tracks = dir_files(cn, &ntracks);
1300   
1301   gtk_label_set_text(GTK_LABEL(report_label), "adding track to queue");
1302   for(n = 0; n < ntracks; ++n)
1303     disorder_eclient_play(client, tracks[n], play_completed, 0);
1304 }
1305
1306 static void properties_dir(struct choosenode *cn,
1307                            void attribute((unused)) *wfu) {
1308   int ntracks;
1309   const char **tracks = dir_files(cn, &ntracks);
1310   
1311   properties(ntracks, tracks);
1312 }
1313
1314 static void select_dir(struct choosenode *cn,
1315                        void attribute((unused)) *wfu) {
1316   int n;
1317
1318   clear_selection(root);
1319   for(n = 0; n < cn->children.nvec; ++n) 
1320     set_selection(cn->children.vec[n], 1);
1321 }
1322
1323 /** @brief Ensure @p cn is expanded and then call @p callback */
1324 static void call_with_dir(struct choosenode *cn,
1325                           when_filled_callback *whenfilled,
1326                           void *wfu) {
1327   if(!(cn->flags & CN_EXPANDABLE))
1328     return;                             /* something went wrong */
1329   if(cn->flags & CN_EXPANDED)
1330     /* @p cn is already open */
1331     whenfilled(cn, wfu);
1332   else {
1333     /* @p cn is not open, arrange for the callback to go off when it is
1334      * opened */
1335     cn->whenfilled = whenfilled;
1336     cn->wfu = wfu;
1337     expand_node(cn, 0/*not contingnet upon search*/);
1338   }
1339 }
1340
1341 /** @brief Called when the directory menu's play option is activated */
1342 static void activate_dir_play(GtkMenuItem attribute((unused)) *menuitem,
1343                               gpointer user_data) {
1344   struct choosenode *const cn = (struct choosenode *)user_data;
1345
1346   call_with_dir(cn, play_dir, 0);
1347 }
1348
1349 /** @brief Called when the directory menu's properties option is activated */
1350 static void activate_dir_properties(GtkMenuItem attribute((unused)) *menuitem,
1351                                     gpointer user_data) {
1352   struct choosenode *const cn = (struct choosenode *)user_data;
1353
1354   call_with_dir(cn, properties_dir, 0);
1355 }
1356
1357 /** @brief Called when the directory menu's select option is activated */
1358 static void activate_dir_select(GtkMenuItem attribute((unused)) *menuitem,
1359                                 gpointer user_data) {
1360   struct choosenode *const cn = (struct choosenode *)user_data;
1361
1362   call_with_dir(cn, select_dir,  0);
1363 }
1364
1365 /** @brief Determine whether the directory menu's play option should be sensitive */
1366 static gboolean sensitive_dir_play(struct choosenode attribute((unused)) *cn) {
1367   return !!(disorder_eclient_state(client) & DISORDER_CONNECTED);
1368 }
1369
1370 /** @brief Determine whether the directory menu's properties option should be sensitive */
1371 static gboolean sensitive_dir_properties(struct choosenode attribute((unused)) *cn) {
1372   return !!(disorder_eclient_state(client) & DISORDER_CONNECTED);
1373 }
1374
1375 /** @brief Determine whether the directory menu's select option should be sensitive */
1376 static gboolean sensitive_dir_select(struct choosenode attribute((unused)) *cn) {
1377   return TRUE;
1378 }
1379
1380
1381
1382 /* Main menu plumbing ------------------------------------------------------ */
1383
1384 /** @brief Determine whether the edit menu's properties option should be sensitive */
1385 static int choose_properties_sensitive(GtkWidget attribute((unused)) *w) {
1386   return !!files_selected && (disorder_eclient_state(client) & DISORDER_CONNECTED);
1387 }
1388
1389 /** @brief Determine whether the edit menu's select all option should be sensitive
1390  *
1391  * TODO not implemented,  see also choose_selectall_activate()
1392  */
1393 static int choose_selectall_sensitive(GtkWidget attribute((unused)) *w) {
1394   return FALSE;
1395 }
1396
1397 /** @brief Determine whether the edit menu's select none option should be sensitive
1398  *
1399  * TODO not implemented,  see also choose_selectnone_activate()
1400  */
1401 static int choose_selectnone_sensitive(GtkWidget attribute((unused)) *w) {
1402   return FALSE;
1403 }
1404
1405 /** @brief Called when the edit menu's properties option is activated */
1406 static void choose_properties_activate(GtkWidget attribute((unused)) *w) {
1407   activate_track_properties(0, 0);
1408 }
1409
1410 /** @brief Called when the edit menu's select all option is activated
1411  *
1412  * TODO not implemented, see choose_selectall_sensitive() */
1413 static void choose_selectall_activate(GtkWidget attribute((unused)) *w) {
1414 }
1415
1416 /** @brief Called when the edit menu's select none option is activated
1417  *
1418  * TODO not implemented, see choose_selectnone_sensitive() */
1419 static void choose_selectnone_activate(GtkWidget attribute((unused)) *w) {
1420 }
1421
1422 /** @brief Called when the choose tab is selected */
1423 static void choose_tab_selected(void) {
1424   gtk_widget_grab_focus(searchentry);
1425 }
1426
1427 /** @brief Main menu callbacks for Choose screen */
1428 static const struct tabtype tabtype_choose = {
1429   choose_properties_sensitive,
1430   choose_selectall_sensitive,
1431   choose_selectnone_sensitive,
1432   choose_properties_activate,
1433   choose_selectall_activate,
1434   choose_selectnone_activate,
1435   choose_tab_selected,
1436 };
1437
1438 /* Public entry points ----------------------------------------------------- */
1439
1440 /** @brief Called when we have just logged in
1441  *
1442  * Entirely resets the choose tab.
1443  */
1444 static void choose_logged_in(const char attribute((unused)) *event,
1445                              void attribute((unused)) *eventdata,
1446                              void attribute((unused)) *callbackdata) {
1447   if(root)
1448     undisplay_tree(root);
1449   root = newnode(0/*parent*/, "<root>", "All files", "",
1450                  CN_EXPANDABLE, fill_root_node);
1451   expand_node(root, 0);                 /* will call redisplay_tree */
1452 }
1453
1454 /** @brief Create a track choice widget */
1455 GtkWidget *choose_widget(void) {
1456   int n;
1457   GtkWidget *scrolled;
1458   GtkWidget *vbox, *hbox, *clearsearch;
1459
1460   /*
1461    *   +--vbox-------------------------------------------------------+
1462    *   | +-hbox----------------------------------------------------+ |
1463    *   | | searchentry                               | clearsearch | |
1464    *   | +---------------------------------------------------------+ |
1465    *   | +-scrolled------------------------------------------------+ |
1466    *   | | +-chooselayout------------------------------------++--+ | |
1467    *   | | | Tree structure is manually layed out in here    ||^^| | |
1468    *   | | |                                                 ||  | | |
1469    *   | | |                                                 ||  | | |
1470    *   | | |                                                 ||  | | |
1471    *   | | |                                                 ||vv| | |
1472    *   | | +-------------------------------------------------++--+ | |
1473    *   | | +-------------------------------------------------+     | |
1474    *   | | |<                                               >|     | |
1475    *   | | +-------------------------------------------------+     | |
1476    *   | +---------------------------------------------------------+ |
1477    *   +-------------------------------------------------------------+
1478    */
1479   
1480   /* Text entry box for search terms */
1481   NW(entry);
1482   searchentry = gtk_entry_new();
1483   gtk_widget_set_style(searchentry, tool_style);
1484   g_signal_connect(searchentry, "changed", G_CALLBACK(searchentry_changed), 0);
1485   gtk_tooltips_set_tip(tips, searchentry, "Enter search terms here; search is automatic", "");
1486
1487   /* Cancel button to clear the search */
1488   NW(button);
1489   clearsearch = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
1490   gtk_widget_set_style(clearsearch, tool_style);
1491   g_signal_connect(G_OBJECT(clearsearch), "clicked",
1492                    G_CALLBACK(clearsearch_clicked), 0);
1493   gtk_tooltips_set_tip(tips, clearsearch, "Clear search terms", "");
1494
1495   /* Up and down buttons to find previous/next results; initially they are not
1496    * usable as there are no search results. */
1497   prevsearch = iconbutton("up.png", "Previous search result");
1498   g_signal_connect(G_OBJECT(prevsearch), "clicked",
1499                    G_CALLBACK(prev_clicked), 0);
1500   gtk_widget_set_style(prevsearch, tool_style);
1501   gtk_widget_set_sensitive(prevsearch, 0);
1502   nextsearch = iconbutton("down.png", "Next search result");
1503   g_signal_connect(G_OBJECT(nextsearch), "clicked",
1504                    G_CALLBACK(next_clicked), 0);
1505   gtk_widget_set_style(nextsearch, tool_style);
1506   gtk_widget_set_sensitive(nextsearch, 0);
1507
1508   /* hbox packs the search tools button together on a line */
1509   NW(hbox);
1510   hbox = gtk_hbox_new(FALSE/*homogeneous*/, 1/*spacing*/);
1511   gtk_box_pack_start(GTK_BOX(hbox), searchentry,
1512                      TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
1513   gtk_box_pack_start(GTK_BOX(hbox), prevsearch,
1514                      FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1515   gtk_box_pack_start(GTK_BOX(hbox), nextsearch,
1516                      FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1517   gtk_box_pack_start(GTK_BOX(hbox), clearsearch,
1518                      FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1519   
1520   /* chooselayout contains the currently visible subset of the track
1521    * namespace */
1522   NW(layout);
1523   chooselayout = gtk_layout_new(0, 0);
1524   gtk_widget_set_style(chooselayout, layout_style);
1525   choose_logged_in(0, 0, 0);
1526   event_register("logged-in", choose_logged_in, 0);
1527   /* Create the popup menus */
1528   NW(menu);
1529   track_menu = gtk_menu_new();
1530   g_signal_connect(track_menu, "destroy", G_CALLBACK(gtk_widget_destroyed),
1531                    &track_menu);
1532   for(n = 0; track_menuitems[n].name; ++n) {
1533     NW(menu_item);
1534     track_menuitems[n].w = 
1535       gtk_menu_item_new_with_label(track_menuitems[n].name);
1536     gtk_menu_attach(GTK_MENU(track_menu), track_menuitems[n].w,
1537                     0, 1, n, n + 1);
1538   }
1539   NW(menu);
1540   dir_menu = gtk_menu_new();
1541   g_signal_connect(dir_menu, "destroy", G_CALLBACK(gtk_widget_destroyed),
1542                    &dir_menu);
1543   for(n = 0; dir_menuitems[n].name; ++n) {
1544     NW(menu_item);
1545     dir_menuitems[n].w = 
1546       gtk_menu_item_new_with_label(dir_menuitems[n].name);
1547     gtk_menu_attach(GTK_MENU(dir_menu), dir_menuitems[n].w,
1548                     0, 1, n, n + 1);
1549   }
1550   /* The layout is scrollable */
1551   scrolled = scroll_widget(chooselayout);
1552   vadjust = gtk_layout_get_vadjustment(GTK_LAYOUT(chooselayout));
1553
1554   /* The scrollable layout and the search hbox go together in a vbox */
1555   NW(vbox);
1556   vbox = gtk_vbox_new(FALSE/*homogenous*/, 1/*spacing*/);
1557   gtk_box_pack_start(GTK_BOX(vbox), hbox,
1558                      FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1559   gtk_box_pack_end(GTK_BOX(vbox), scrolled,
1560                    TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
1561
1562   g_object_set_data(G_OBJECT(vbox), "type", (void *)&tabtype_choose);
1563   return vbox;
1564 }
1565
1566 /** @brief Called when something we care about here might have changed */
1567 void choose_update(void) {
1568   redisplay_tree("choose_update");
1569 }
1570
1571 /*
1572 Local Variables:
1573 c-basic-offset:2
1574 comment-column:40
1575 fill-column:79
1576 indent-tabs-mode:nil
1577 End:
1578 */