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