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