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