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