chiark / gitweb /
565902d6539f0923381aa5e4448d069f7fb82529
[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
21 #include "disobedience.h"
22
23 /* Choose track ------------------------------------------------------------ */
24
25 WT(label);
26 WT(event_box);
27 WT(menu);
28 WT(menu_item);
29 WT(layout);
30 WT(vbox);
31 WT(arrow);
32 WT(hbox);
33 WT(button);
34 WT(image);
35 WT(entry);
36
37 /* We don't use the built-in tree widgets because they require that you know
38  * the children of a node on demand, and we have to wait for the server to tell
39  * us. */
40
41 /* Types */
42
43 struct choosenode;
44
45 struct displaydata {
46   guint width;                          /* total width required */
47   guint height;                         /* total height required */
48 };
49
50 /* instantiate the node vector type */
51 VECTOR_TYPE(nodevector, struct choosenode *, xrealloc)
52
53 struct choosenode {
54   struct choosenode *parent;            /* parent node */
55   const char *path;                     /* full path or 0  */
56   const char *sort;                     /* sort key */
57   const char *display;                  /* display name */
58   int pending;                          /* pending resolve queries */
59   unsigned flags;
60 #define CN_EXPANDABLE 0x0001            /* node is expandable */
61 #define CN_EXPANDED 0x0002              /* node is expanded */
62 /* Expandable items are directories; non-expandable ones are files */
63 #define CN_DISPLAYED 0x0004             /* widget is displayed in layout */
64 #define CN_SELECTED 0x0008              /* node is selected */
65   struct nodevector children;           /* vector of children */
66   void (*fill)(struct choosenode *);    /* request child fill or 0 for leaf */
67   GtkWidget *container;                 /* the container for this row */
68   GtkWidget *hbox;                      /* the hbox for this row */
69   GtkWidget *arrow;                     /* arrow widget or 0 */
70   GtkWidget *label;                     /* text label for this node */
71   GtkWidget *marker;                    /* queued marker */
72 };
73
74 struct menuitem {
75   /* Parameters */
76   const char *name;                     /* name */
77
78   /* Callbacks */
79   void (*activate)(GtkMenuItem *menuitem, gpointer user_data);
80   /* Called to activate the menu item.  The user data is the choosenode the
81    * pointer is over. */
82
83   gboolean (*sensitive)(struct choosenode *cn);
84   /* Called to determine whether the menu item should be sensitive.  TODO */
85
86   /* State */
87   gulong handlerid;                     /* signal handler ID */
88   GtkWidget *w;                         /* menu item widget */
89 };
90
91 /* Variables */
92
93 static GtkWidget *chooselayout;
94 static GtkWidget *searchentry;          /* search terms */
95 static struct choosenode *root;
96 static struct choosenode *realroot;
97 static GtkWidget *menu;                 /* our popup menu */
98 static struct choosenode *last_click;   /* last clicked node for selection */
99 static int files_visible;               /* total files visible */
100 static int files_selected;              /* total files selected */
101 static int search_in_flight;            /* a search is underway */
102 static int search_obsolete;             /* the current search is void */
103 static char **searchresults;            /* search results */
104 static int nsearchresults;              /* number of results */
105
106 /* Forward Declarations */
107
108 static void clear_children(struct choosenode *cn);
109 static struct choosenode *newnode(struct choosenode *parent,
110                                   const char *path,
111                                   const char *display,
112                                   const char *sort,
113                                   unsigned flags,
114                                   void (*fill)(struct choosenode *));
115 static void fill_root_node(struct choosenode *cn);
116 static void fill_letter_node(struct choosenode *cn);
117 static void fill_directory_node(struct choosenode *cn);
118 static void got_files(void *v, int nvec, char **vec);
119 static void got_resolved_file(void *v, const char *track);
120 static void got_dirs(void *v, int nvec, char **vec);
121
122 static void expand_node(struct choosenode *cn);
123 static void contract_node(struct choosenode *cn);
124 static void updated_node(struct choosenode *cn, int redisplay);
125
126 static void display_selection(struct choosenode *cn);
127 static void clear_selection(struct choosenode *cn);
128
129 static void redisplay_tree(void);
130 static struct displaydata display_tree(struct choosenode *cn, int x, int y);
131 static void undisplay_tree(struct choosenode *cn);
132 static void initiate_search(void);
133 static void delete_widgets(struct choosenode *cn);
134
135 static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
136                                GdkEventButton *event,
137                                gpointer user_data);
138
139 static void activate_play(GtkMenuItem *menuitem, gpointer user_data);
140 #if 0
141 static void activate_remove(GtkMenuItem *menuitem, gpointer user_data);
142 #endif
143 static void activate_properties(GtkMenuItem *menuitem, gpointer user_data);
144
145 static gboolean sensitive_play(struct choosenode *cn);
146 #if 0
147 static gboolean sensitive_remove(struct choosenode *cn);
148 #endif
149 static gboolean sensitive_properties(struct choosenode *cn);
150
151 static struct menuitem menuitems[] = {
152   { "Play track", activate_play, sensitive_play, 0, 0 },
153 #if 0
154   /* Not implemented yet */
155   { "Remove", activate_remove, sensitive_remove, 0, 0 },
156 #endif
157   { "Track properties", activate_properties, sensitive_properties, 0, 0 },
158 };
159
160 #define NMENUITEMS (int)(sizeof menuitems / sizeof *menuitems)
161
162 /* Maintaining the data structure ------------------------------------------ */
163
164 /* Create a new node */
165 static struct choosenode *newnode(struct choosenode *parent,
166                                   const char *path,
167                                   const char *display,
168                                   const char *sort,
169                                   unsigned flags,
170                                   void (*fill)(struct choosenode *)) {
171   struct choosenode *const n = xmalloc(sizeof *n);
172
173   D(("newnode %s %s", path, display));
174   if(flags & CN_EXPANDABLE)
175     assert(fill);
176   else
177     assert(!fill);
178   n->parent = parent;
179   n->path = path;
180   n->display = display;
181   n->sort = sort;
182   n->flags = flags;
183   nodevector_init(&n->children);
184   n->fill = fill;
185   if(parent)
186     nodevector_append(&parent->children, n);
187   return n;
188 }
189
190 /* Fill the root */
191 static void fill_root_node(struct choosenode *cn) {
192   int ch;
193   char *name;
194   struct callbackdata *cbd;
195
196   D(("fill_root_node"));
197   clear_children(cn);
198   if(choosealpha) {
199     if(!cn->children.nvec) {              /* Only need to do this once */
200       for(ch = 'A'; ch <= 'Z'; ++ch) {
201         byte_xasprintf(&name, "%c", ch);
202         newnode(cn, "<letter>", name, name, CN_EXPANDABLE, fill_letter_node);
203       }
204       newnode(cn, "<letter>", "*", "~", CN_EXPANDABLE, fill_letter_node);
205     }
206     updated_node(cn, 1);
207   } else {
208     /* More de-duping possible here */
209     gtk_label_set_text(GTK_LABEL(report_label), "getting files");
210     cbd = xmalloc(sizeof *cbd);
211     cbd->u.choosenode = cn;
212     disorder_eclient_dirs(client, got_dirs, "", 0, cbd);
213     cbd = xmalloc(sizeof *cbd);
214     cbd->u.choosenode = cn;
215     disorder_eclient_files(client, got_files, "", 0, cbd);
216   }
217 }
218
219 static void delete_cn_widgets(struct choosenode *cn) {
220   if(cn->arrow) {
221     DW(arrow);
222     gtk_widget_destroy(cn->arrow);
223     cn->arrow = 0;
224   }
225   if(cn->label) {
226     DW(label);
227     gtk_widget_destroy(cn->label);
228     cn->label = 0;
229   }
230   if(cn->marker) {
231     DW(image);
232     gtk_widget_destroy(cn->marker);
233     cn->marker = 0;
234   }
235   if(cn->hbox) {
236     DW(hbox);
237     gtk_widget_destroy(cn->hbox);
238     cn->hbox = 0;
239   }
240   if(cn->container) {
241     DW(event_box);
242     gtk_widget_destroy(cn->container);
243     cn->container = 0;
244   }
245 }
246
247 /* Clear all the children of CN */
248 static void clear_children(struct choosenode *cn) {
249   int n;
250
251   D(("clear_children %s", cn->path));
252   /* Recursively clear subtrees */
253   for(n = 0; n < cn->children.nvec; ++n) {
254     clear_children(cn->children.vec[n]);
255     delete_cn_widgets(cn->children.vec[n]);
256   }
257   cn->children.nvec = 0;
258 }
259
260 /* Fill a child node */
261 static void fill_letter_node(struct choosenode *cn) {
262   const char *regexp;
263   struct callbackdata *cbd;
264
265   D(("fill_letter_node %s", cn->display));
266   switch(cn->display[0]) {
267   default:
268     byte_xasprintf((char **)&regexp, "^(the )?%c", tolower(cn->display[0]));
269     break;
270   case 'T':
271     regexp = "^(?!the [^t])t";
272     break;
273   case '*':
274     regexp = "^[^a-z]";
275     break;
276   }
277   /* TODO: caching */
278   /* TODO: de-dupe against fill_directory_node */
279   gtk_label_set_text(GTK_LABEL(report_label), "getting files");
280   clear_children(cn);
281   cbd = xmalloc(sizeof *cbd);
282   cbd->u.choosenode = cn;
283   disorder_eclient_dirs(client, got_dirs, "", regexp, cbd);
284   cbd = xmalloc(sizeof *cbd);
285   cbd->u.choosenode = cn;
286   disorder_eclient_files(client, got_files, "", regexp, cbd);
287 }
288
289 /* Called with a list of files just below some node */
290 static void got_files(void *v, int nvec, char **vec) {
291   struct callbackdata *cbd = v;
292   struct choosenode *cn = cbd->u.choosenode;
293   int n;
294
295   D(("got_files %d files for %s", nvec, cn->path));
296   /* Complicated by the need to resolve aliases.  We can save a bit of effort
297    * by re-using cbd though. */
298   cn->pending = nvec;
299   for(n = 0; n < nvec; ++n)
300     disorder_eclient_resolve(client, got_resolved_file, vec[n], cbd);
301 }
302
303 static void got_resolved_file(void *v, const char *track) {
304   struct callbackdata *cbd = v;
305   struct choosenode *cn = cbd->u.choosenode, *file_cn;
306
307   file_cn = newnode(cn, track,
308                     trackname_transform("track", track, "display"),
309                     trackname_transform("track", track, "sort"),
310                     0/*flags*/, 0/*fill*/);
311   /* Only bother updating when we've got the lot */
312   if(--cn->pending == 0)
313     updated_node(cn, 1);
314 }
315
316 /* Called with a list of directories just below some node */
317 static void got_dirs(void *v, int nvec, char **vec) {
318   struct callbackdata *cbd = v;
319   struct choosenode *cn = cbd->u.choosenode;
320   int n;
321
322   D(("got_dirs %d dirs for %s", nvec, cn->path));
323   for(n = 0; n < nvec; ++n)
324     newnode(cn, vec[n],
325             trackname_transform("dir", vec[n], "display"),
326             trackname_transform("dir", vec[n], "sort"),
327             CN_EXPANDABLE, fill_directory_node);
328   updated_node(cn, 1);
329 }
330   
331 /* Fill a child node */
332 static void fill_directory_node(struct choosenode *cn) {
333   struct callbackdata *cbd;
334
335   D(("fill_directory_node %s", cn->path));
336   /* TODO: caching */
337   /* TODO: de-dupe against fill_letter_node */
338   assert(report_label != 0);
339   gtk_label_set_text(GTK_LABEL(report_label), "getting files");
340   clear_children(cn);
341   cbd = xmalloc(sizeof *cbd);
342   cbd->u.choosenode = cn;
343   disorder_eclient_dirs(client, got_dirs, cn->path, 0, cbd);
344   cbd = xmalloc(sizeof *cbd);
345   cbd->u.choosenode = cn;
346   disorder_eclient_files(client, got_files, cn->path, 0, cbd);
347 }
348
349 /* Expand a node */
350 static void expand_node(struct choosenode *cn) {
351   D(("expand_node %s", cn->path));
352   assert(cn->flags & CN_EXPANDABLE);
353   /* If node is already expanded do nothing. */
354   if(cn->flags & CN_EXPANDED) return;
355   /* We mark the node as expanded and request that it fill itself.  When it has
356    * completed it will called updated_node() and we can redraw at that
357    * point. */
358   cn->flags |= CN_EXPANDED;
359   /* TODO: visual feedback */
360   cn->fill(cn);
361 }
362
363 /* Contract a node */
364 static void contract_node(struct choosenode *cn) {
365   D(("contract_node %s", cn->path));
366   assert(cn->flags & CN_EXPANDABLE);
367   /* If node is already contracted do nothing. */
368   if(!(cn->flags & CN_EXPANDED)) return;
369   cn->flags &= ~CN_EXPANDED;
370   /* Clear selection below this node */
371   clear_selection(cn);
372   /* Zot children.  We never used to do this but the result would be that over
373    * time you'd end up with the entire tree pulled into memory.  If the server
374    * is over a slow network it will make interactivity slightly worse; if
375    * anyone complains we can make it an option. */
376   clear_children(cn);
377   /* We can contract a node immediately. */
378   redisplay_tree();
379 }
380
381 /* qsort callback for ordering choosenodes */
382 static int compare_choosenode(const void *av, const void *bv) {
383   const struct choosenode *const *aa = av, *const *bb = bv;
384   const struct choosenode *a = *aa, *b = *bb;
385
386   return compare_tracks(a->sort, b->sort,
387                         a->display, b->display,
388                         a->path, b->path);
389 }
390
391 /* Called when an expandable node is updated.   */
392 static void updated_node(struct choosenode *cn, int redisplay) {
393   D(("updated_node %s", cn->path));
394   assert(cn->flags & CN_EXPANDABLE);
395   /* It might be that the node has been de-expanded since we requested the
396    * update.  In that case we ignore this notification. */
397   if(!(cn->flags & CN_EXPANDED)) return;
398   /* Sort children */
399   qsort(cn->children.vec, cn->children.nvec, sizeof (struct choosenode *),
400         compare_choosenode);
401   if(redisplay)
402     redisplay_tree();
403 }
404
405 /* Searching --------------------------------------------------------------- */
406
407 static int compare_track_for_qsort(const void *a, const void *b) {
408   return compare_path(*(char **)a, *(char **)b);
409 }
410
411 /* Return true iff FILE is a child of DIR */
412 static int is_child(const char *dir, const char *file) {
413   const size_t dlen = strlen(dir);
414
415   return (!strncmp(file, dir, dlen)
416           && file[dlen] == '/'
417           && strchr(file + dlen + 1, '/') == 0);
418 }
419
420 /* Return true iff FILE is a descendant of DIR */
421 static int is_descendant(const char *dir, const char *file) {
422   const size_t dlen = strlen(dir);
423
424   return !strncmp(file, dir, dlen) && file[dlen] == '/';
425 }
426
427 /* Called to fill a node in the search results tree */
428 static void fill_search_node(struct choosenode *cn) {
429   int n;
430   const size_t plen = strlen(cn->path);
431   const char *s;
432   char *dir, *last = 0;
433
434   D(("fill_search_node %s", cn->path));
435   /* We depend on the search results being sorted as by compare_path(). */
436   clear_children(cn);
437   for(n = 0; n < nsearchresults; ++n) {
438     /* We only care about descendants of CN */
439     if(!is_descendant(cn->path, searchresults[n]))
440        continue;
441     s = strchr(searchresults[n] + plen + 1, '/');
442     if(s) {
443       /* We've identified a subdirectory of CN. */
444       dir = xstrndup(searchresults[n], s - searchresults[n]);
445       if(!last || strcmp(dir, last)) {
446         /* Not a duplicate */
447         last = dir;
448         newnode(cn, dir,
449                 trackname_transform("dir", dir, "display"),
450                 trackname_transform("dir", dir, "sort"),
451                 CN_EXPANDABLE, fill_search_node);
452       }
453     } else {
454       /* We've identified a file in CN */
455       newnode(cn, searchresults[n],
456               trackname_transform("track", searchresults[n], "display"),
457               trackname_transform("track", searchresults[n], "sort"),
458               0/*flags*/, 0/*fill*/);
459     }
460   }
461   updated_node(cn, 1);
462 }
463
464 /* This is called from eclient with a (possibly empty) list of search results,
465  * and also from initiate_seatch with an always empty list to indicate that
466  * we're not searching for anything in particular. */
467 static void search_completed(void attribute((unused)) *v,
468                              int nvec, char **vec) {
469   struct choosenode *cn;
470   int n;
471   const char *dir;
472
473   search_in_flight = 0;
474   if(search_obsolete) {
475     /* This search has been obsoleted by user input since it started.
476      * Therefore we throw away the result and search again. */
477     search_obsolete = 0;
478     initiate_search();
479   } else {
480     if(nvec) {
481       /* We will replace the choose tree with a tree structured view of search
482        * results.  First we must disabled the choose tree's widgets. */
483       delete_widgets(root);
484       /* Put the tracks into order, grouped by directory.  They'll probably
485        * come back this way anyway in current versions of the server, but it's
486        * cheap not to rely on it (compared with the massive effort we expend
487        * later on) */
488       qsort(vec, nvec, sizeof(char *), compare_track_for_qsort);
489       searchresults = vec;
490       nsearchresults = nvec;
491       cn = root = newnode(0/*parent*/, "", "Search results", "",
492                   CN_EXPANDABLE|CN_EXPANDED, fill_search_node);
493       /* Construct the initial tree.  We do this in a single pass and expand
494        * everything, so you can actually see your search results. */
495       for(n = 0; n < nsearchresults; ++n) {
496         /* Firstly we might need to go up a few directories to each an ancestor
497          * of this track */
498         while(!is_descendant(cn->path, searchresults[n])) {
499           /* We report the update on each node the last time we see it (With
500            * display=0, the main purpose of this is to get the order of the
501            * children right.) */
502           updated_node(cn, 0);
503           cn = cn->parent;
504         }
505         /* Secondly we might need to insert some new directories */
506         while(!is_child(cn->path, searchresults[n])) {
507           /* Figure out the subdirectory */
508           dir = xstrndup(searchresults[n],
509                          strchr(searchresults[n] + strlen(cn->path) + 1,
510                                 '/') - searchresults[n]);
511           cn = newnode(cn, dir,
512                        trackname_transform("dir", dir, "display"),
513                        trackname_transform("dir", dir, "sort"),
514                        CN_EXPANDABLE|CN_EXPANDED, fill_search_node);
515         }
516         /* Finally we can insert the track as a child of the current
517          * directory */
518         newnode(cn, searchresults[n],
519                 trackname_transform("track", searchresults[n], "display"),
520                 trackname_transform("track", searchresults[n], "sort"),
521                 0/*flags*/, 0/*fill*/);
522       }
523       while(cn) {
524         /* Update all the nodes back up to the root */
525         updated_node(cn, 0);
526         cn = cn->parent;
527       }
528       /* Now it's worth displaying the tree */
529       redisplay_tree();
530     } else if(root != realroot) {
531       delete_widgets(root);
532       root = realroot;
533       redisplay_tree();
534     }
535   }
536 }
537
538 static void initiate_search(void) {
539   char *terms, *e;
540
541   /* Find out what the user is after */
542   terms = xstrdup(gtk_entry_get_text(GTK_ENTRY(searchentry)));
543   /* Strip leading and trailing space */
544   while(*terms == ' ') ++terms;
545   e = terms + strlen(terms);
546   while(e > terms && e[-1] == ' ') --e;
547   *e = 0;
548   /* If a search is already underway then mark it as obsolete.  We'll revisit
549    * when it returns. */
550   if(search_in_flight) {
551     search_obsolete = 1;
552     return;
553   }
554   if(*terms) {
555     /* There's still something left.  Initiate the search. */
556     if(disorder_eclient_search(client, search_completed, terms, 0)) {
557       /* The search terms are bad!  We treat this as if there were no search
558        * terms at all.  Some kind of feedback would be handy. */
559       fprintf(stderr, "bad terms [%s]\n", terms); /* TODO */
560       search_completed(0, 0, 0);
561     } else {
562       search_in_flight = 1;
563     }
564   } else {
565     /* No search terms - we want to see all tracks */
566     search_completed(0, 0, 0);
567   }
568 }
569
570 /* Called when the cancel search button is clicked */
571 static void clearsearch_clicked(GtkButton attribute((unused)) *button,
572                                 gpointer attribute((unused)) userdata) {
573   gtk_entry_set_text(GTK_ENTRY(searchentry), "");
574 }
575
576 /* Display functions ------------------------------------------------------- */
577
578 /* Delete all the widgets in the tree */
579 static void delete_widgets(struct choosenode *cn) {
580   int n;
581
582   delete_cn_widgets(cn);
583   for(n = 0; n < cn->children.nvec; ++n)
584     delete_widgets(cn->children.vec[n]);
585   cn->flags &= ~(CN_DISPLAYED|CN_SELECTED);
586   files_selected = 0;
587 }
588
589 /* Update the display */
590 static void redisplay_tree(void) {
591   struct displaydata d;
592   guint oldwidth, oldheight;
593
594   D(("redisplay_tree"));
595   /* We'll count these up empirically each time */
596   files_selected = 0;
597   files_visible = 0;
598   /* Correct the layout and find out how much space it uses */
599   d = display_tree(root, 0, 0);
600   /* We must set the total size or scrolling will not work (it wouldn't be hard
601    * for GtkLayout to figure it out for itself but presumably you're supposed
602    * to be able to have widgets off the edge of the layuot.)
603    *
604    * There is a problem: if we shrink the size then the part of the screen that
605    * is outside the new size but inside the old one is not updated.  I think
606    * this is arguably bug in GTK+ but it's easy to force a redraw if this
607    * region is nonempty.
608    */
609   gtk_layout_get_size(GTK_LAYOUT(chooselayout), &oldwidth, &oldheight);
610   if(oldwidth > d.width || oldheight > d.height)
611     gtk_widget_queue_draw(chooselayout);
612   gtk_layout_set_size(GTK_LAYOUT(chooselayout), d.width, d.height);
613   /* Notify the main menu of any recent changes */
614   menu_update(-1);
615 }
616
617 /* Make sure all displayed widgets from CN down exist and are in their proper
618  * place and return the vertical space used. */
619 static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
620   int n, aw;
621   GtkRequisition req;
622   struct displaydata d, cd;
623   GdkPixbuf *pb;
624   
625   D(("display_tree %s %d,%d", cn->path, x, y));
626
627   /* An expandable item contains an arrow and a text label.  When you press the
628    * button it flips its expand state.
629    *
630    * A non-expandable item has just a text label and no arrow.
631    */
632   if(!cn->container) {
633     /* Widgets need to be created */
634     NW(hbox);
635     cn->hbox = gtk_hbox_new(FALSE, 1);
636     if(cn->flags & CN_EXPANDABLE) {
637       NW(arrow);
638       cn->arrow = gtk_arrow_new(cn->flags & CN_EXPANDED ? GTK_ARROW_DOWN
639                                                         : GTK_ARROW_RIGHT,
640                                 GTK_SHADOW_NONE);
641       cn->marker = 0;
642     } else {
643       cn->arrow = 0;
644       if((pb = find_image("notes.png"))) {
645         NW(image);
646         cn->marker = gtk_image_new_from_pixbuf(pb);
647       }
648     }
649     NW(label);
650     cn->label = gtk_label_new(cn->display);
651     if(cn->arrow)
652       gtk_container_add(GTK_CONTAINER(cn->hbox), cn->arrow);
653     gtk_container_add(GTK_CONTAINER(cn->hbox), cn->label);
654     if(cn->marker)
655       gtk_container_add(GTK_CONTAINER(cn->hbox), cn->marker);
656     NW(event_box);
657     cn->container = gtk_event_box_new();
658     gtk_container_add(GTK_CONTAINER(cn->container), cn->hbox);
659     g_signal_connect(cn->container, "button-release-event", 
660                      G_CALLBACK(clicked_choosenode), cn);
661     g_signal_connect(cn->container, "button-press-event", 
662                      G_CALLBACK(clicked_choosenode), cn);
663     g_object_ref(cn->container);
664     gtk_widget_set_name(cn->label, "choose");
665     gtk_widget_set_name(cn->container, "choose");
666     /* Show everything by default */
667     gtk_widget_show_all(cn->container);
668   }
669   assert(cn->container);
670   /* Make sure the icon is right */
671   if(cn->flags & CN_EXPANDABLE)
672     gtk_arrow_set(GTK_ARROW(cn->arrow),
673                   cn->flags & CN_EXPANDED ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT,
674                   GTK_SHADOW_NONE);
675   else if(cn->marker)
676     /* Make sure the queued marker is right */
677     /* TODO: doesn't always work */
678     (queued(cn->path) ? gtk_widget_show : gtk_widget_hide)(cn->marker);
679   /* Put the widget in the right place */
680   if(cn->flags & CN_DISPLAYED)
681     gtk_layout_move(GTK_LAYOUT(chooselayout), cn->container, x, y);
682   else {
683     gtk_layout_put(GTK_LAYOUT(chooselayout), cn->container, x, y);
684     cn->flags |= CN_DISPLAYED;
685   }
686   /* Set the widget's selection status */
687   if(!(cn->flags & CN_EXPANDABLE))
688     display_selection(cn);
689   /* Find the size used so we can get vertical positioning right. */
690   gtk_widget_size_request(cn->container, &req);
691   d.width = x + req.width;
692   d.height = y + req.height;
693   if(cn->flags & CN_EXPANDED) {
694     /* We'll offset children by the size of the arrow whatever it might be. */
695     assert(cn->arrow);
696     gtk_widget_size_request(cn->arrow, &req);
697     aw = req.width;
698     for(n = 0; n < cn->children.nvec; ++n) {
699       cd = display_tree(cn->children.vec[n], x + aw, d.height);
700       if(cd.width > d.width)
701         d.width = cd.width;
702       d.height = cd.height;
703     }
704   } else {
705     for(n = 0; n < cn->children.nvec; ++n)
706       undisplay_tree(cn->children.vec[n]);
707   }
708   if(!(cn->flags & CN_EXPANDABLE)) {
709     ++files_visible;
710     if(cn->flags & CN_SELECTED)
711       ++files_selected;
712   }
713   /* report back how much space we used */
714   D(("display_tree %s %d,%d total size %dx%d", cn->path, x, y,
715      d.width, d.height));
716   return d;
717 }
718
719 /* Remove widgets for newly hidden nodes */
720 static void undisplay_tree(struct choosenode *cn) {
721   int n;
722
723   D(("undisplay_tree %s", cn->path));
724   /* Remove this widget from the display */
725   if(cn->flags & CN_DISPLAYED) {
726     gtk_container_remove(GTK_CONTAINER(chooselayout), cn->container);
727     cn->flags ^= CN_DISPLAYED;
728   }
729   /* Remove children too */
730   for(n = 0; n < cn->children.nvec; ++n)
731     undisplay_tree(cn->children.vec[n]);
732 }
733
734 /* Selection --------------------------------------------------------------- */
735
736 static void display_selection(struct choosenode *cn) {
737   /* Need foreground and background colors */
738   gtk_widget_set_state(cn->label, (cn->flags & CN_SELECTED
739                                    ? GTK_STATE_SELECTED : GTK_STATE_NORMAL));
740   gtk_widget_set_state(cn->container, (cn->flags & CN_SELECTED
741                                        ? GTK_STATE_SELECTED : GTK_STATE_NORMAL));
742 }
743
744 /* Set the selection state of a widget.  Directories can never be selected, we
745  * just ignore attempts to do so. */
746 static void set_selection(struct choosenode *cn, int selected) {
747   unsigned f = selected ? CN_SELECTED : 0;
748
749   D(("set_selection %d %s", selected, cn->path));
750   if(!(cn->flags & CN_EXPANDABLE) && (cn->flags & CN_SELECTED) != f) {
751     cn->flags ^= CN_SELECTED;
752     /* Maintain selection count */
753     if(selected)
754       ++files_selected;
755     else
756       --files_selected;
757     display_selection(cn);
758     /* Update main menu sensitivity */
759     menu_update(-1);
760   }
761 }
762
763 /* Recursively clear all selection bits from CN down */
764 static void clear_selection(struct choosenode *cn) {
765   int n;
766
767   set_selection(cn, 0);
768   for(n = 0; n < cn->children.nvec; ++n)
769     clear_selection(cn->children.vec[n]);
770 }
771
772 /* User actions ------------------------------------------------------------ */
773
774 /* Clicked on something */
775 static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
776                                GdkEventButton *event,
777                                gpointer user_data) {
778   struct choosenode *cn = user_data;
779   int ind, last_ind, n;
780
781   D(("clicked_choosenode %s", cn->path));
782   if(event->type == GDK_BUTTON_RELEASE
783      && event->button == 1) {
784     /* Left click */
785     if(cn->flags & CN_EXPANDABLE) {
786       /* This is a directory.  Flip its expansion status. */
787       if(cn->flags & CN_EXPANDED)
788         contract_node(cn);
789       else
790         expand_node(cn);
791       last_click = 0;
792     } else {
793       /* This is a file.  Adjust selection status */
794       /* TODO the basic logic here is essentially the same as that in queue.c.
795        * Can we share code at all? */
796       switch(event->state & (GDK_SHIFT_MASK|GDK_CONTROL_MASK)) {
797       case 0:
798         clear_selection(root);
799         set_selection(cn, 1);
800         last_click = cn;
801         break;
802       case GDK_CONTROL_MASK:
803         set_selection(cn, !(cn->flags & CN_SELECTED));
804         last_click = cn;
805         break;
806       case GDK_SHIFT_MASK:
807       case GDK_SHIFT_MASK|GDK_CONTROL_MASK:
808         if(last_click && last_click->parent == cn->parent) {
809           /* Figure out where the current and last clicks are in the list */
810           ind = last_ind = -1;
811           for(n = 0; n < cn->parent->children.nvec; ++n) {
812             if(cn->parent->children.vec[n] == cn)
813               ind = n;
814             if(cn->parent->children.vec[n] == last_click)
815               last_ind = n;
816           }
817           /* Test shouldn't ever fail, but still */
818           if(ind >= 0 && last_ind >= 0) {
819             if(!(event->state & GDK_CONTROL_MASK)) {
820               for(n = 0; n < cn->parent->children.nvec; ++n)
821                 set_selection(cn->parent->children.vec[n], 0);
822             }
823             if(ind > last_ind)
824               for(n = last_ind; n <= ind; ++n)
825                 set_selection(cn->parent->children.vec[n], 1);
826             else
827               for(n = ind; n <= last_ind; ++n)
828                 set_selection(cn->parent->children.vec[n], 1);
829             if(event->state & GDK_CONTROL_MASK)
830               last_click = cn;
831           }
832         }
833         break;
834       }
835     }
836   } else if(event->type == GDK_BUTTON_RELEASE
837      && event->button == 2) {
838     /* Middle click - play the pointed track */
839     if(!(cn->flags & CN_EXPANDABLE)) {
840       clear_selection(root);
841       set_selection(cn, 1);
842       gtk_label_set_text(GTK_LABEL(report_label), "adding track to queue");
843       disorder_eclient_play(client, cn->path, 0, 0);
844       last_click = 0;
845     }
846   } else if(event->type == GDK_BUTTON_PRESS
847      && event->button == 3) {
848     /* Right click.  Pop up a menu. */
849     /* If the current file isn't selected, switch the selection to just that.
850      * (If we're looking at a directory then leave the selection alone.) */
851     if(!(cn->flags & CN_EXPANDABLE) && !(cn->flags & CN_SELECTED)) {
852       clear_selection(root);
853       set_selection(cn, 1);
854       last_click = cn;
855     }
856     /* Set the item sensitivity and callbacks */
857     for(n = 0; n < NMENUITEMS; ++n) {
858       if(menuitems[n].handlerid)
859         g_signal_handler_disconnect(menuitems[n].w,
860                                     menuitems[n].handlerid);
861       gtk_widget_set_sensitive(menuitems[n].w,
862                                menuitems[n].sensitive(cn));
863       menuitems[n].handlerid = g_signal_connect
864         (menuitems[n].w, "activate", G_CALLBACK(menuitems[n].activate), cn);
865     }
866     /* Pop up the menu */
867     gtk_widget_show_all(menu);
868     gtk_menu_popup(GTK_MENU(menu), 0, 0, 0, 0,
869                    event->button, event->time);
870   }
871 }
872
873 static void searchentry_changed(GtkEditable attribute((unused)) *editable,
874                                 gpointer attribute((unused)) user_data) {
875   initiate_search();
876 }
877
878 /* Menu items -------------------------------------------------------------- */
879
880 static void recurse_selected(struct choosenode *cn, struct vector *v) {
881   int n;
882
883   if(cn->flags & CN_EXPANDABLE) {
884     if(cn->flags & CN_EXPANDED)
885       for(n = 0; n < cn->children.nvec; ++n)
886         recurse_selected(cn->children.vec[n], v);
887   } else {
888     if((cn->flags & CN_SELECTED) && cn->path)
889       vector_append(v, (char *)cn->path);
890   }
891 }
892
893 static char **gather_selected(int *ntracks) {
894   struct vector v;
895
896   vector_init(&v);
897   recurse_selected(root, &v);
898   vector_terminate(&v);
899   if(ntracks) *ntracks = v.nvec;
900   return v.vec;
901 }
902
903 static void activate_play(GtkMenuItem attribute((unused)) *menuitem,
904                           gpointer attribute((unused)) user_data) {
905   char **tracks = gather_selected(0);
906   int n;
907   
908   gtk_label_set_text(GTK_LABEL(report_label), "adding track to queue");
909   for(n = 0; tracks[n]; ++n)
910     disorder_eclient_play(client, tracks[n], 0, 0);
911 }
912
913 #if 0
914 static void activate_remove(GtkMenuItem attribute((unused)) *menuitem,
915                             gpointer attribute((unused)) user_data) {
916   /* TODO remove all selected tracks */
917 }
918 #endif
919
920 static void activate_properties(GtkMenuItem attribute((unused)) *menuitem,
921                                 gpointer attribute((unused)) user_data) {
922   int ntracks;
923   char **tracks = gather_selected(&ntracks);
924
925   properties(ntracks, tracks);
926 }
927
928 static gboolean sensitive_play(struct choosenode attribute((unused)) *cn) {
929   return !!files_selected;
930 }
931
932 #if 0
933 static gboolean sensitive_remove(struct choosenode attribute((unused)) *cn) {
934   return FALSE;                         /* not implemented yet */
935 }
936 #endif
937
938 static gboolean sensitive_properties(struct choosenode attribute((unused)) *cn) {
939   return !!files_selected;
940 }
941
942 /* Main menu plumbing ------------------------------------------------------ */
943
944 static int choose_properties_sensitive(GtkWidget attribute((unused)) *w) {
945   return !!files_selected;
946 }
947
948 static int choose_selectall_sensitive(GtkWidget attribute((unused)) *w) {
949   return FALSE;                         /* TODO */
950 }
951
952 static void choose_properties_activate(GtkWidget attribute((unused)) *w) {
953   activate_properties(0, 0);
954 }
955
956 static void choose_selectall_activate(GtkWidget attribute((unused)) *w) {
957   /* TODO */
958 }
959
960 static const struct tabtype tabtype_choose = {
961   choose_properties_sensitive,
962   choose_selectall_sensitive,
963   choose_properties_activate,
964   choose_selectall_activate,
965 };
966
967 /* Public entry points ----------------------------------------------------- */
968
969 /* Create a track choice widget */
970 GtkWidget *choose_widget(void) {
971   int n;
972   GtkWidget *scrolled;
973   GtkWidget *vbox, *hbox, *clearsearch;
974
975   /*
976    *   +--vbox-------------------------------------------------------+
977    *   | +-hbox----------------------------------------------------+ |
978    *   | | searchentry                               | clearsearch | |
979    *   | +---------------------------------------------------------+ |
980    *   | +-scrolled------------------------------------------------+ |
981    *   | | +-chooselayout------------------------------------++--+ | |
982    *   | | | Tree structure is manually layed out in here    ||^^| | |
983    *   | | |                                                 ||  | | |
984    *   | | |                                                 ||  | | |
985    *   | | |                                                 ||  | | |
986    *   | | |                                                 ||vv| | |
987    *   | | +-------------------------------------------------++--+ | |
988    *   | | +-------------------------------------------------+     | |
989    *   | | |<                                               >|     | |
990    *   | | +-------------------------------------------------+     | |
991    *   | +---------------------------------------------------------+ |
992    *   +-------------------------------------------------------------+
993    */
994   
995   /* Text entry box for search terms */
996   NW(entry);
997   searchentry = gtk_entry_new();
998   g_signal_connect(searchentry, "changed", G_CALLBACK(searchentry_changed), 0);
999
1000   /* Cancel button to clear the search */
1001   NW(button);
1002   clearsearch = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
1003   g_signal_connect(G_OBJECT(clearsearch), "clicked",
1004                    G_CALLBACK(clearsearch_clicked), 0);
1005
1006   /* hbox packs the search box and the cancel button together on a line */
1007   NW(hbox);
1008   hbox = gtk_hbox_new(FALSE/*homogeneous*/, 1/*spacing*/);
1009   gtk_box_pack_start(GTK_BOX(hbox), searchentry,
1010                      TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
1011   gtk_box_pack_end(GTK_BOX(hbox), clearsearch,
1012                    FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1013   
1014   /* chooselayout contains the currently visible subset of the track
1015    * namespace */
1016   NW(layout);
1017   chooselayout = gtk_layout_new(0, 0);
1018   root = newnode(0/*parent*/, "<root>", "All files", "",
1019                  CN_EXPANDABLE, fill_root_node);
1020   realroot = root;
1021   expand_node(root);                    /* will call redisplay_tree */
1022   /* Create the popup menu */
1023   NW(menu);
1024   menu = gtk_menu_new();
1025   g_signal_connect(menu, "destroy", G_CALLBACK(gtk_widget_destroyed), &menu);
1026   for(n = 0; n < NMENUITEMS; ++n) {
1027     NW(menu_item);
1028     menuitems[n].w = gtk_menu_item_new_with_label(menuitems[n].name);
1029     gtk_menu_attach(GTK_MENU(menu), menuitems[n].w, 0, 1, n, n + 1);
1030   }
1031   /* The layout is scrollable */
1032   scrolled = scroll_widget(GTK_WIDGET(chooselayout), "choose");
1033
1034   /* The scrollable layout and the search hbox go together in a vbox */
1035   NW(vbox);
1036   vbox = gtk_vbox_new(FALSE/*homogenous*/, 1/*spacing*/);
1037   gtk_box_pack_start(GTK_BOX(vbox), hbox,
1038                      FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
1039   gtk_box_pack_end(GTK_BOX(vbox), scrolled,
1040                    TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
1041
1042   g_object_set_data(G_OBJECT(vbox), "type", (void *)&tabtype_choose);
1043   return vbox;
1044 }
1045
1046 /* Called when something we care about here might have changed */
1047 void choose_update(void) {
1048   redisplay_tree();
1049 }
1050
1051 /*
1052 Local Variables:
1053 c-basic-offset:2
1054 comment-column:40
1055 fill-column:79
1056 indent-tabs-mode:nil
1057 End:
1058 */