chiark / gitweb /
eclient string response calls now get errors reported to the completed
[disorder] / disobedience / queue.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/queue.c
21  * @brief Queue widgets
22  *
23  * This file provides both the queue widget and the recently-played widget.
24  *
25  * A queue layout is structured as follows:
26  *
27  * <pre>
28  *  vbox
29  *   titlescroll
30  *    titlelayout
31  *     titlecells[col]                 eventbox (made by wrap_queue_cell)
32  *      titlecells[col]->child         label (from columns[])
33  *   mainscroll
34  *    mainlayout
35  *     cells[row * N + c]              eventbox (made by wrap_queue_cell)
36  *      cells[row * N + c]->child      label (from column constructors)
37  * </pre>
38  *
39  * titlescroll never has any scrollbars.  Instead whenever mainscroll's
40  * horizontal adjustment is changed, queue_scrolled adjusts titlescroll to
41  * match, forcing the title and the queue to pan in sync but allowing the queue
42  * to scroll independently.
43  *
44  * Whenever the queue changes everything below mainlayout is thrown away and
45  * reconstructed from scratch.  Name lookups are cached, so this doesn't imply
46  * lots of disorder protocol traffic.
47  *
48  * The last cell on each row is the padding cell, and this extends ridiculously
49  * far to the right.  (Can we do better?)
50  *
51  * When drag and drop is active we create extra eventboxes to act as dropzones.
52  * These only exist while the drag proceeds, as otherwise they steal events
53  * from more deserving widgets.  (It might work to hide them when not in use
54  * too but this way around the d+d code is a bit more self-contained.)
55  *
56  * NB that while in the server the playing track is not in the queue, in
57  * Disobedience, the playing does live in @c ql_queue.q, despite its different
58  * status to everything else found in that list.
59  */
60
61 #include "disobedience.h"
62 #include "charset.h"
63
64 /** @brief Horizontal padding for queue cells */
65 #define HCELLPADDING 4
66
67 /** @brief Vertical padding for queue cells */
68 #define VCELLPADDING 2
69
70 /* Queue management -------------------------------------------------------- */
71
72 WT(label);
73 WT(event_box);
74 WT(menu);
75 WT(menu_item);
76 WT(layout);
77 WT(vbox);
78
79 struct queuelike;
80
81 static void add_drag_targets(struct queuelike *ql);
82 static void remove_drag_targets(struct queuelike *ql);
83 static void redisplay_queue(struct queuelike *ql);
84 static GtkWidget *column_when(const struct queuelike *ql,
85                               const struct queue_entry *q,
86                               const char *data);
87 static GtkWidget *column_who(const struct queuelike *ql,
88                              const struct queue_entry *q,
89                              const char *data);
90 static GtkWidget *column_namepart(const struct queuelike *ql,
91                                   const struct queue_entry *q,
92                                   const char *data);
93 static GtkWidget *column_length(const struct queuelike *ql,
94                                 const struct queue_entry *q,
95                                 const char *data);
96 static int draggable_row(const struct queue_entry *q);
97
98 static const struct tabtype tabtype_queue; /* forward */
99
100 static const GtkTargetEntry dragtargets[] = {
101   { (char *)"disobedience-queue", GTK_TARGET_SAME_APP, 0 }
102 };
103 #define NDRAGTARGETS (int)(sizeof dragtargets / sizeof *dragtargets)
104
105 /** @brief Definition of a column */
106 struct column {
107   const char *name;                     /* Column name */
108   GtkWidget *(*widget)(const struct queuelike *ql,
109                        const struct queue_entry *q,
110                        const char *data); /* Make a label for this column */
111   const char *data;                     /* Data to pass to widget() */
112   gfloat xalign;                        /* Alignment of the label */
113 };
114
115 /** @brief Table of columns for queue and recently played list */
116 static const struct column maincolumns[] = {
117   { "When",   column_when,     0,        1 },
118   { "Who",    column_who,      0,        0 },
119   { "Artist", column_namepart, "artist", 0 },
120   { "Album",  column_namepart, "album",  0 },
121   { "Title",  column_namepart, "title",  0 },
122   { "Length", column_length,   0,        1 }
123 };
124
125 /** @brief Number of columns in queue and recnetly played list */
126 #define NMAINCOLUMNS (int)(sizeof maincolumns / sizeof *maincolumns)
127
128 /** @brief Table of columns for recently added tracks */
129 static const struct column addedcolumns[] = {
130   { "Artist", column_namepart, "artist", 0 },
131   { "Album",  column_namepart, "album",  0 },
132   { "Title",  column_namepart, "title",  0 },
133   { "Length", column_length,   0,        1 }
134 };
135
136 /** @brief Number of columns in recently added list */
137 #define NADDEDCOLUMNS (int)(sizeof addedcolumns / sizeof *addedcolumns)
138
139 /** @brief Maximum number of column in any @ref queuelike */
140 #define MAXCOLUMNS (NMAINCOLUMNS > NADDEDCOLUMNS ? NMAINCOLUMNS : NADDEDCOLUMNS)
141
142 /** @brief Data passed to menu item activation handlers */
143 struct menuiteminfo {
144   struct queuelike *ql;                 /**< @brief which queue we're dealing with */
145   struct queue_entry *q;                /**< @brief hovered entry or 0 */
146 };
147
148 /** @brief An item in the queue's popup menu */
149 struct queue_menuitem {
150   /** @brief Menu item name */
151   const char *name;
152
153   /** @brief Called to activate the menu item
154    *
155    * The user data is the queue entry that the pointer was over when the menu
156    * popped up. */
157   void (*activate)(GtkMenuItem *menuitem,
158                    gpointer user_data);
159   
160   /** @brief Called to determine whether the menu item is usable.
161    *
162    * Returns @c TRUE if it should be sensitive and @c FALSE otherwise.  @p q
163    * points to the queue entry the pointer is over.
164    */
165   int (*sensitive)(struct queuelike *ql,
166                    struct queue_menuitem *m,
167                    struct queue_entry *q);
168
169   /** @brief Signal handler ID */
170   gulong handlerid;
171
172   /** @brief Widget for menu item */
173   GtkWidget *w;
174 };
175
176 /** @brief A queue-like object
177  *
178  * There are (currently) three of these: @ref ql_queue, @ref ql_recent and @ref
179  * ql_added.
180  */
181 struct queuelike {
182   /** @brief Called when an update completes */
183   void (*notify)(void);
184
185   /** @brief Called to fix up the queue after update
186    * @param q The list passed back from the server
187    * @return Assigned to @c ql->q
188    */
189   struct queue_entry *(*fixup)(struct queue_entry *q);
190
191   /* Widgets */
192   GtkWidget *mainlayout;                /**< @brief main layout */
193   GtkWidget *mainscroll;                /**< @brief scroller for main layout */
194   GtkWidget *titlelayout;               /**< @brief title layout */
195   GtkWidget *titlecells[MAXCOLUMNS + 1]; /**< @brief title cells */
196   GtkWidget **cells;                    /**< @brief all the cells */
197   GtkWidget *menu;                      /**< @brief popup menu */
198   struct queue_menuitem *menuitems;     /**< @brief menu items */
199   GtkWidget *dragmark;                  /**< @brief drag destination marker */
200   GtkWidget **dropzones;                /**< @brief drag targets */
201   int ndropzones;                       /**< @brief number of drag targets */
202
203   /* State */
204   struct queue_entry *q;                /**< @brief head of queue */
205   struct queue_entry *last_click;       /**< @brief last click */
206   int nrows;                            /**< @brief number of rows */
207   int mainrowheight;                    /**< @brief height of one row */
208   hash *selection;                      /**< @brief currently selected items */
209   int swallow_release;                  /**< @brief swallow button release from drag */
210
211   const struct column *columns;         /**< @brief Table of columns */
212   int ncolumns;                         /**< @brief Number of columns */
213 };
214
215 static struct queuelike ql_queue; /**< @brief The main queue */
216 static struct queuelike ql_recent; /*< @brief Recently-played tracks */
217 static struct queuelike ql_added; /*< @brief Newly added tracks */
218 static struct queue_entry *actual_queue; /**< @brief actual queue */
219 static struct queue_entry *playing_track;     /**< @brief currenty playing */
220 static time_t last_playing = (time_t)-1; /**< @brief when last got playing */
221 static int namepart_lookups_outstanding;
222 static int  namepart_completions_deferred; /* # of completions not processed */
223 static const struct cache_type cachetype_string = { 3600 };
224 static const struct cache_type cachetype_integer = { 3600 };
225 static GtkWidget *playing_length_label;
226
227 /* Debugging --------------------------------------------------------------- */
228
229 #if 0
230 static void describe_widget(const char *name, GtkWidget *w, int indent) {
231   int ww, wh, wx, wy;
232
233   if(name)
234     fprintf(stderr, "%*s[%s]: '%s'\n", indent, "",
235             name, gtk_widget_get_name(w));
236   gdk_window_get_position(w->window, &wx, &wy);
237   gdk_drawable_get_size(GDK_DRAWABLE(w->window), &ww, &wh);
238   fprintf(stderr, "%*s window %p: %dx%d at %dx%d\n",
239           indent, "", w->window, ww, wh, wx, wy);
240 }
241
242 static void dump_layout(const struct queuelike *ql) {
243   GtkWidget *w;
244   char s[20];
245   int row, col;
246   const struct queue_entry *q;
247   
248   describe_widget("mainscroll", ql->mainscroll, 0);
249   describe_widget("mainlayout", ql->mainlayout, 1);
250   for(q = ql->q, row = 0; q; q = q->next, ++row)
251     for(col = 0; col < ql->ncolumns + 1; ++col)
252       if((w = ql->cells[row * (ql->ncolumns + 1) + col])) {
253         sprintf(s, "%dx%d", row, col);
254         describe_widget(s, w, 2);
255         if(GTK_BIN(w)->child)
256           describe_widget(0, w, 3);
257       }
258 }
259 #endif
260
261 /* Track detail lookup ----------------------------------------------------- */
262
263 /** @brief Called when a namepart lookup has completed or failed */
264 static void namepart_completed_or_failed(void) {
265   D(("namepart_completed_or_failed"));
266   --namepart_lookups_outstanding;
267   if(!namepart_lookups_outstanding) {
268     redisplay_queue(&ql_queue);
269     redisplay_queue(&ql_recent);
270     redisplay_queue(&ql_added);
271     namepart_completions_deferred = 0;
272   }
273 }
274
275 /** @brief Called when A namepart lookup has completed */
276 static void namepart_completed(void *v, const char *error, const char *value) {
277   if(error) {
278     gtk_label_set_text(GTK_LABEL(report_label), error);
279   } else {
280     cache_put(&cachetype_string, v, value);
281     ++namepart_completions_deferred;
282   }
283   namepart_completed_or_failed();
284 }
285
286 /** @brief Called when a length lookup has completed */
287 static void length_completed(void *v, long l) {
288   struct callbackdata *cbd = v;
289   long *value;
290
291   D(("namepart_completed"));
292   value = xmalloc(sizeof *value);
293   *value = l;
294   cache_put(&cachetype_integer, cbd->u.key, value);
295   ++namepart_completions_deferred;
296   namepart_completed_or_failed();
297 }
298
299 /** @brief Called when a length or namepart lookup has failed */
300 static void namepart_protocol_error(
301   struct callbackdata attribute((unused)) *cbd,
302   int attribute((unused)) code,
303   const char *msg) {
304   D(("namepart_protocol_error"));
305   gtk_label_set_text(GTK_LABEL(report_label), msg);
306   namepart_completed_or_failed();
307 }
308
309 /** @brief Arrange to fill in a namepart cache entry */
310 static void namepart_fill(const char *track,
311                           const char *context,
312                           const char *part,
313                           const char *key) {
314   ++namepart_lookups_outstanding;
315   disorder_eclient_namepart(client, namepart_completed,
316                             track, context, part, (void *)key);
317 }
318
319 /** @brief Look up a namepart
320  *
321  * If it is in the cache then just return its value.  If not then look it up
322  * and arrange for the queues to be updated when its value is available. */
323 static const char *namepart(const char *track,
324                             const char *context,
325                             const char *part) {
326   char *key;
327   const char *value;
328
329   D(("namepart %s %s %s", track, context, part));
330   byte_xasprintf(&key, "namepart context=%s part=%s track=%s",
331                  context, part, track);
332   value = cache_get(&cachetype_string, key);
333   if(!value) {
334     D(("deferring..."));
335     /* stick a value in the cache so we don't issue another lookup if we
336      * revisit */
337     cache_put(&cachetype_string, key, value = "?");
338     namepart_fill(track, context, part, key);
339   }
340   return value;
341 }
342
343 /** @brief Called from @ref disobedience/properties.c when we know a name part has changed */
344 void namepart_update(const char *track,
345                      const char *context,
346                      const char *part) {
347   char *key;
348
349   byte_xasprintf(&key, "namepart context=%s part=%s track=%s",
350                  context, part, track);
351   /* Only refetch if it's actually in the cache */
352   if(cache_get(&cachetype_string, key))
353     namepart_fill(track, context, part, key);
354 }
355
356 /** @brief Look up a track length
357  *
358  * If it is in the cache then just return its value.  If not then look it up
359  * and arrange for the queues to be updated when its value is available. */
360 static long getlength(const char *track) {
361   char *key;
362   const long *value;
363   struct callbackdata *cbd;
364   static const long bogus = -1;
365
366   D(("getlength %s", track));
367   byte_xasprintf(&key, "length track=%s", track);
368   value = cache_get(&cachetype_integer, key);
369   if(!value) {
370     D(("deferring..."));;
371     cache_put(&cachetype_integer, key, value = &bogus);
372     ++namepart_lookups_outstanding;
373     cbd = xmalloc(sizeof *cbd);
374     cbd->onerror = namepart_protocol_error;
375     cbd->u.key = key;
376     disorder_eclient_length(client, length_completed, track, cbd);
377   }
378   return *value;
379 }
380
381 /* Column constructors ----------------------------------------------------- */
382
383 /** @brief Format the 'when' column */
384 static GtkWidget *column_when(const struct queuelike attribute((unused)) *ql,
385                               const struct queue_entry *q,
386                               const char attribute((unused)) *data) {
387   char when[64];
388   struct tm tm;
389   time_t t;
390
391   D(("column_when"));
392   switch(q->state) {
393   case playing_isscratch:
394   case playing_unplayed:
395   case playing_random:
396     t = q->expected;
397     break;
398   case playing_failed:
399   case playing_no_player:
400   case playing_ok:
401   case playing_scratched:
402   case playing_started:
403   case playing_paused:
404   case playing_quitting:
405     t = q->played;
406     break;
407   default:
408     t = 0;
409     break;
410   }
411   if(t)
412     strftime(when, sizeof when, "%H:%M", localtime_r(&t, &tm));
413   else
414     when[0] = 0;
415   NW(label);
416   return gtk_label_new(when);
417 }
418
419 /** @brief Format the 'who' column */
420 static GtkWidget *column_who(const struct queuelike attribute((unused)) *ql,
421                              const struct queue_entry *q,
422                              const char attribute((unused)) *data) {
423   D(("column_who"));
424   NW(label);
425   return gtk_label_new(q->submitter ? q->submitter : "");
426 }
427
428 /** @brief Format one of the track name columns */
429 static GtkWidget *column_namepart(const struct queuelike
430                                                attribute((unused)) *ql,
431                                   const struct queue_entry *q,
432                                   const char *data) {
433   D(("column_namepart"));
434   NW(label);
435   return gtk_label_new(truncate_for_display(namepart(q->track, "display", data),
436                                             config->short_display));
437 }
438
439 /** @brief Compute the length field */
440 static const char *text_length(const struct queue_entry *q) {
441   long l;
442   time_t now;
443   char *played = 0, *length = 0;
444
445   /* Work out what to say for the length */
446   l = getlength(q->track);
447   if(l > 0)
448     byte_xasprintf(&length, "%ld:%02ld", l / 60, l % 60);
449   else
450     byte_xasprintf(&length, "?:??");
451   /* For the currently playing track we want to report how much of the track
452    * has been played */
453   if(q == playing_track) {
454     /* log_state() arranges that we re-get the playing data whenever the
455      * pause/resume state changes */
456     if(last_state & DISORDER_TRACK_PAUSED)
457       l = playing_track->sofar;
458     else {
459       time(&now);
460       l = playing_track->sofar + (now - last_playing);
461     }
462     byte_xasprintf(&played, "%ld:%02ld/%s", l / 60, l % 60, length);
463     return played;
464   } else
465     return length;
466 }
467
468 /** @brief Format the length column */
469 static GtkWidget *column_length(const struct queuelike attribute((unused)) *ql,
470                                 const struct queue_entry *q,
471                                 const char attribute((unused)) *data) {
472   D(("column_length"));
473   if(q == playing_track) {
474     assert(!playing_length_label);
475     NW(label);
476     playing_length_label = gtk_label_new(text_length(q));
477     /* Zot playing_length_label when it is destroyed */
478     g_signal_connect(playing_length_label, "destroy",
479                      G_CALLBACK(gtk_widget_destroyed), &playing_length_label);
480     return playing_length_label;
481   } else {
482     NW(label);
483     return gtk_label_new(text_length(q));
484   }
485   
486 }
487
488 /** @brief Apply a new queue contents, transferring the selection from the old value */
489 static void update_queue(struct queuelike *ql, struct queue_entry *newq) {
490   struct queue_entry *q;
491
492   D(("update_queue"));
493   /* Propagate last_click across the change */
494   if(ql->last_click) {
495     for(q = newq; q; q = q->next) {
496       if(!strcmp(q->id, ql->last_click->id)) 
497         break;
498       ql->last_click = q;
499     }
500   }
501   /* Tell every queue entry which queue owns it */
502   for(q = newq; q; q = q->next)
503     q->ql = ql;
504   /* Switch to the new queue */
505   ql->q = newq;
506   /* Clean up any selected items that have fallen off */
507   for(q = ql->q; q; q = q->next)
508     selection_live(ql->selection, q->id);
509   selection_cleanup(ql->selection);
510 }
511
512 /** @brief Wrap up a widget for putting into the queue or title
513  * @param label Label to contain
514  * @param style Pointer to style to use
515  * @param wp Updated with maximum width (or NULL)
516  * @return New widget
517  */
518 static GtkWidget *wrap_queue_cell(GtkWidget *label,
519                                   GtkStyle *style,
520                                   int *wp) {
521   GtkRequisition req;
522   GtkWidget *bg;
523
524   D(("wrap_queue_cell"));
525   /* Padding should be in the label so there are no gaps in the
526    * background */
527   gtk_misc_set_padding(GTK_MISC(label), HCELLPADDING, VCELLPADDING);
528   /* Event box is just to hold a background color */
529   NW(event_box);
530   bg = gtk_event_box_new();
531   gtk_container_add(GTK_CONTAINER(bg), label);
532   if(wp) {
533     /* Update maximum width */
534     gtk_widget_size_request(label, &req);
535     if(req.width > *wp) *wp = req.width;
536   }
537   /* Set colors */
538   gtk_widget_set_style(bg, style);
539   gtk_widget_set_style(label, style);
540   return bg;
541 }
542
543 /** @brief Create the wrapped widget for a cell in the queue display */
544 static GtkWidget *get_queue_cell(struct queuelike *ql,
545                                  const struct queue_entry *q,
546                                  int row,
547                                  int col,
548                                  GtkStyle *style,
549                                  int *wp) {
550   GtkWidget *label;
551   D(("get_queue_cell %d %d", row, col));
552   label = ql->columns[col].widget(ql, q, ql->columns[col].data);
553   gtk_misc_set_alignment(GTK_MISC(label), ql->columns[col].xalign, 0);
554   return wrap_queue_cell(label, style, wp);
555 }
556
557 /** @brief Add a padding cell to the end of a row */
558 static GtkWidget *get_padding_cell(GtkStyle *style) {
559   D(("get_padding_cell"));
560   NW(label);
561   return wrap_queue_cell(gtk_label_new(""), style, 0);
562 }
563
564 /* User button press and menu ---------------------------------------------- */
565
566 /** @brief Update widget states in order to reflect the selection status */
567 static void set_widget_states(struct queuelike *ql) {
568   struct queue_entry *q;
569   int row, col;
570
571   for(q = ql->q, row = 0; q; q = q->next, ++row) {
572     for(col = 0; col < ql->ncolumns + 1; ++col)
573       gtk_widget_set_state(ql->cells[row * (ql->ncolumns + 1) + col],
574                            selection_selected(ql->selection, q->id) ?
575                            GTK_STATE_SELECTED : GTK_STATE_NORMAL);
576   }
577   /* Might need to change sensitivity of 'Properties' in main menu */
578   menu_update(-1);
579 }
580
581 /** @brief Ordering function for queue entries */
582 static int queue_before(const struct queue_entry *a,
583                         const struct queue_entry *b) {
584   while(a && a != b)
585     a = a->next;
586   return !!a;
587 }
588
589 /** @brief A button was pressed and released */
590 static gboolean queuelike_button_released(GtkWidget attribute((unused)) *widget,
591                                           GdkEventButton *event,
592                                           gpointer user_data) {
593   struct queue_entry *q = user_data, *qq;
594   struct queuelike *ql = q->ql;
595   struct menuiteminfo *mii;
596   int n;
597   
598   /* Might be a release left over from a drag */
599   if(ql->swallow_release) {
600     ql->swallow_release = 0;
601     return FALSE;                       /* propagate */
602   }
603
604   if(event->type == GDK_BUTTON_PRESS
605      && event->button == 3) {
606     /* Right button click.
607      * If the current item is not selected then switch the selection to just
608      * this item */
609     if(q && !selection_selected(ql->selection, q->id)) {
610       selection_empty(ql->selection);
611       selection_set(ql->selection, q->id, 1);
612       ql->last_click = q;
613       set_widget_states(ql);
614     }
615     /* Set the sensitivity of each menu item and (re-)establish the signal
616      * handlers */
617     for(n = 0; ql->menuitems[n].name; ++n) {
618       if(ql->menuitems[n].handlerid)
619         g_signal_handler_disconnect(ql->menuitems[n].w,
620                                     ql->menuitems[n].handlerid);
621       gtk_widget_set_sensitive(ql->menuitems[n].w,
622                                ql->menuitems[n].sensitive(ql,
623                                                           &ql->menuitems[n],
624                                                           q));
625       mii = xmalloc(sizeof *mii);
626       mii->ql = ql;
627       mii->q = q;
628       ql->menuitems[n].handlerid = g_signal_connect
629         (ql->menuitems[n].w, "activate",
630          G_CALLBACK(ql->menuitems[n].activate), mii);
631     }
632     /* Update the menu according to context */
633     gtk_widget_show_all(ql->menu);
634     gtk_menu_popup(GTK_MENU(ql->menu), 0, 0, 0, 0,
635                    event->button, event->time);
636     return TRUE;                        /* hide the click from other widgets */
637   }
638   if(event->type == GDK_BUTTON_RELEASE
639      && event->button == 1) {
640     /* no modifiers: select this, unselect everything else, set last click
641      * +ctrl: flip selection of this, set last click
642      * +shift: select from last click to here, don't set last click
643      * +ctrl+shift: select from last click to here, set last click
644      */
645     switch(event->state & (GDK_SHIFT_MASK|GDK_CONTROL_MASK)) {
646     case 0:
647       selection_empty(ql->selection);
648       selection_set(ql->selection, q->id, 1);
649       ql->last_click = q;
650       break;
651     case GDK_CONTROL_MASK:
652       selection_flip(ql->selection, q->id);
653       ql->last_click = q;
654       break;
655     case GDK_SHIFT_MASK:
656     case GDK_SHIFT_MASK|GDK_CONTROL_MASK:
657       if(ql->last_click) {
658         if(!(event->state & GDK_CONTROL_MASK))
659           selection_empty(ql->selection);
660         selection_set(ql->selection, q->id, 1);
661         qq = q;
662         if(queue_before(ql->last_click, q))
663           while(qq != ql->last_click) {
664             qq = qq->prev;
665             selection_set(ql->selection, qq->id, 1);
666           }
667         else
668           while(qq != ql->last_click) {
669             qq = qq->next;
670             selection_set(ql->selection, qq->id, 1);
671           }
672         if(event->state & GDK_CONTROL_MASK)
673           ql->last_click = q;
674       }
675       break;
676     }
677     set_widget_states(ql);
678     gtk_widget_queue_draw(ql->mainlayout);
679   }
680   return FALSE;                         /* propagate */
681 }
682
683 /** @brief A button was pressed or released on the mainlayout
684  *
685  * For debugging only at the moment. */
686 static gboolean mainlayout_button(GtkWidget attribute((unused)) *widget,
687                                   GdkEventButton attribute((unused)) *event,
688                                   gpointer attribute((unused)) user_data) {
689   return FALSE;                         /* propagate */
690 }
691
692 /** @brief Select all entries in a queue */
693 void queue_select_all(struct queuelike *ql) {
694   struct queue_entry *qq;
695
696   for(qq = ql->q; qq; qq = qq->next)
697     selection_set(ql->selection, qq->id, 1);
698   ql->last_click = 0;
699   set_widget_states(ql);
700 }
701
702 /** @brief Deselect all entries in a queue */
703 void queue_select_none(struct queuelike *ql) {
704   struct queue_entry *qq;
705
706   for(qq = ql->q; qq; qq = qq->next)
707     selection_set(ql->selection, qq->id, 0);
708   ql->last_click = 0;
709   set_widget_states(ql);
710 }
711
712 /** @brief Pop up properties for selected tracks */
713 void queue_properties(struct queuelike *ql) {
714   struct vector v;
715   const struct queue_entry *qq;
716
717   vector_init(&v);
718   for(qq = ql->q; qq; qq = qq->next)
719     if(selection_selected(ql->selection, qq->id))
720       vector_append(&v, (char *)qq->track);
721   if(v.nvec)
722     properties(v.nvec, (const char **)v.vec);
723 }
724
725 /* Drag and drop rearrangement --------------------------------------------- */
726
727 /** @brief Return nonzero if @p is a draggable row
728  *
729  * Only tracks in the main queue are draggable (and the currently playing track
730  * is not draggable).
731  */
732 static int draggable_row(const struct queue_entry *q) {
733   return q->ql == &ql_queue && q != playing_track;
734 }
735
736 /** @brief Called when a drag begings */
737 static void queue_drag_begin(GtkWidget attribute((unused)) *widget, 
738                              GdkDragContext attribute((unused)) *dc,
739                              gpointer data) {
740   struct queue_entry *q = data;
741   struct queuelike *ql = q->ql;
742
743   /* Make sure the playing track is not selected, since it cannot be dragged */
744   if(playing_track)
745     selection_set(ql->selection, playing_track->id, 0);
746   /* If the dragged item is not in the selection then change the selection to
747    * just that */
748   if(!selection_selected(ql->selection, q->id)) {
749     selection_empty(ql->selection);
750     selection_set(ql->selection, q->id, 1);
751     set_widget_states(ql);
752   }
753   /* Ignore the eventual button release */
754   ql->swallow_release = 1;
755   /* Create dropzones */
756   add_drag_targets(ql);
757 }
758
759 /** @brief Convert @p id back into a queue entry and a screen row number */
760 static struct queue_entry *findentry(struct queuelike *ql,
761                                      const char *id,
762                                      int *rowp) {
763   int row;
764   struct queue_entry *q;
765
766   if(id) {
767     for(q = ql->q, row = 0; q && strcmp(q->id, id); q = q->next, ++row)
768       ;
769   } else {
770     q = 0;
771     row = playing_track ? 0 : -1;
772   }
773   if(rowp) *rowp = row;
774   return q;
775 }
776
777 /** @brief Called when data is dropped */
778 static gboolean queue_drag_drop(GtkWidget attribute((unused)) *widget,
779                                 GdkDragContext *drag_context,
780                                 gint attribute((unused)) x,
781                                 gint attribute((unused)) y,
782                                 guint when,
783                                 gpointer user_data) {
784   struct queuelike *ql = &ql_queue;
785   const char *id = user_data;
786   struct vector vec;
787   struct queue_entry *q;
788
789   if(!id || (playing_track && !strcmp(id, playing_track->id)))
790     id = "";
791   vector_init(&vec);
792   for(q = ql->q; q; q = q->next)
793     if(q != playing_track && selection_selected(ql->selection, q->id))
794       vector_append(&vec, (char *)q->id);
795   disorder_eclient_moveafter(client, id, vec.nvec, (const char **)vec.vec,
796                              0/*completed*/, 0/*v*/);
797   gtk_drag_finish(drag_context, TRUE, TRUE, when);
798   /* Destroy dropzones */
799   remove_drag_targets(ql);
800   return TRUE;
801 }
802
803 /** @brief Called when we enter, or move within, a drop zone */
804 static gboolean queue_drag_motion(GtkWidget attribute((unused)) *widget,
805                                   GdkDragContext *drag_context,
806                                   gint attribute((unused)) x,
807                                   gint attribute((unused)) y,
808                                   guint when,
809                                   gpointer user_data) {
810   struct queuelike *ql = &ql_queue;
811   const char *id = user_data;
812   int row;
813   struct queue_entry *q = findentry(ql, id, &row);
814
815   if(!id || q) {
816     if(!ql->dragmark) {
817       NW(event_box);
818       ql->dragmark = gtk_event_box_new();
819       g_signal_connect(ql->dragmark, "destroy",
820                        G_CALLBACK(gtk_widget_destroyed), &ql->dragmark);
821       gtk_widget_set_size_request(ql->dragmark, 10240, row ? 4 : 2);
822       gtk_widget_set_style(ql->dragmark, drag_style);
823       gtk_layout_put(GTK_LAYOUT(ql->mainlayout), ql->dragmark, 0, 
824                      (row + 1) * ql->mainrowheight - !!row);
825     } else
826       gtk_layout_move(GTK_LAYOUT(ql->mainlayout), ql->dragmark, 0, 
827                       (row + 1) * ql->mainrowheight - !!row);
828     gtk_widget_show(ql->dragmark);
829     gdk_drag_status(drag_context, GDK_ACTION_MOVE, when);
830     return TRUE;
831   } else
832     /* ID has gone AWOL */
833     return FALSE;
834 }                              
835
836 /** @brief Called when we leave a drop zone */
837 static void queue_drag_leave(GtkWidget attribute((unused)) *widget,
838                              GdkDragContext attribute((unused)) *drag_context,
839                              guint attribute((unused)) when,
840                              gpointer attribute((unused)) user_data) {
841   struct queuelike *ql = &ql_queue;
842   
843   if(ql->dragmark)
844     gtk_widget_hide(ql->dragmark);
845 }
846
847 /** @brief Add a drag target
848  * @param ql The queue-like (in practice this is always @ref ql_queue)
849  * @param y The Y coordinate to place the drag target
850  * @param id Track to insert moved tracks after, or NULL
851  *
852  * Adds a drop zone at Y coordinate @p y, which is assumed to lie between two
853  * tracks (or before the start of the queue or after the end of the queue).  If
854  * tracks are dragged into this dropzone then they will be moved @em after
855  * track @p id, or to the start of the queue if @p id is NULL.
856  *
857  * We remember all the dropzones in @c ql->dropzones so they can be destroyed
858  * later.
859  */
860 static void add_drag_target(struct queuelike *ql, int y,
861                             const char *id) {
862   GtkWidget *eventbox;
863
864   NW(event_box);
865   eventbox = gtk_event_box_new();
866   /* Make the target zone invisible */
867   gtk_event_box_set_visible_window(GTK_EVENT_BOX(eventbox), FALSE);
868   /* Make it large enough */
869   gtk_widget_set_size_request(eventbox, 10240, 
870                               y ? ql->mainrowheight : ql->mainrowheight / 2);
871   /* Position it */
872   gtk_layout_put(GTK_LAYOUT(ql->mainlayout), eventbox, 0,
873                  y ? y - ql->mainrowheight / 2 : 0);
874   /* Mark it as capable of receiving drops */
875   gtk_drag_dest_set(eventbox,
876                     0,
877                     dragtargets, NDRAGTARGETS, GDK_ACTION_MOVE);
878   g_signal_connect(eventbox, "drag-drop",
879                    G_CALLBACK(queue_drag_drop), (char *)id);
880   /* Monitor drag motion */
881   g_signal_connect(eventbox, "drag-motion",
882                    G_CALLBACK(queue_drag_motion), (char *)id);
883   g_signal_connect(eventbox, "drag-leave",
884                    G_CALLBACK(queue_drag_leave), (char *)id);
885   /* The widget needs to be shown to receive drags */
886   gtk_widget_show(eventbox);
887   /* Remember the drag targets */
888   ql->dropzones[ql->ndropzones] = eventbox;
889   g_signal_connect(eventbox, "destroy",
890                    G_CALLBACK(gtk_widget_destroyed),
891                    &ql->dropzones[ql->ndropzones]);
892   ++ql->ndropzones;
893 }
894
895 /** @brief Create dropzones for dragging into */
896 static void add_drag_targets(struct queuelike *ql) {
897   int y;
898   struct queue_entry *q;
899
900   /* Create an array to store the widgets */
901   ql->dropzones = xcalloc(ql->nrows, sizeof (GtkWidget *));
902   ql->ndropzones = 0;
903   y = 0;
904   /* Add a drag target before the first row provided it's not the playing
905    * track */
906   if(!playing_track || ql->q != playing_track)
907     add_drag_target(ql, 0, 0);
908   /* Put a drag target at the bottom of every row */
909   for(q = ql->q; q; q = q->next) {
910     y += ql->mainrowheight;
911     add_drag_target(ql, y, q->id);
912   }
913 }
914
915 /** @brief Remove the dropzones */
916 static void remove_drag_targets(struct queuelike *ql) {
917   int n;
918
919   for(n = 0; n < ql->ndropzones; ++n) {
920     if(ql->dropzones[n]) {
921       DW(event_box);
922       gtk_widget_destroy(ql->dropzones[n]);
923     }
924     assert(ql->dropzones[n] == 0);
925   }
926 }
927
928 /* Layout ------------------------------------------------------------------ */
929
930 /** @brief Redisplay a queue */
931 static void redisplay_queue(struct queuelike *ql) {
932   struct queue_entry *q;
933   int row, col;
934   GList *c, *children;
935   GtkStyle *style;
936   GtkRequisition req;  
937   GtkWidget *w;
938   int maxwidths[MAXCOLUMNS], x, y, titlerowheight;
939   int totalwidth = 10240;               /* TODO: can we be less blunt */
940
941   D(("redisplay_queue"));
942   /* Eliminate all the existing widgets and start from scratch */
943   for(c = children = gtk_container_get_children(GTK_CONTAINER(ql->mainlayout));
944       c;
945       c = c->next) {
946     /* Destroy both the label and the eventbox */
947     if(GTK_BIN(c->data)->child) {
948       DW(label);
949       gtk_widget_destroy(GTK_BIN(c->data)->child);
950     }
951     DW(event_box);
952     gtk_widget_destroy(GTK_WIDGET(c->data));
953   }
954   g_list_free(children);
955   /* Adjust the row count */
956   for(q = ql->q, ql->nrows = 0; q; q = q->next)
957     ++ql->nrows;
958   /* We need to create all the widgets before we can position them */
959   ql->cells = xcalloc(ql->nrows * (ql->ncolumns + 1), sizeof *ql->cells);
960   /* Minimum width is given by the column headings */
961   for(col = 0; col < ql->ncolumns; ++col) {
962     /* Reset size so we don't inherit last iteration's maximum size */
963     gtk_widget_set_size_request(GTK_BIN(ql->titlecells[col])->child, -1, -1);
964     gtk_widget_size_request(GTK_BIN(ql->titlecells[col])->child, &req);
965     maxwidths[col] = req.width;
966   }
967   /* Find the vertical size of the title bar */
968   gtk_widget_size_request(GTK_BIN(ql->titlecells[0])->child, &req);
969   titlerowheight = req.height;
970   y = 0;
971   if(ql->nrows) {
972     /* Construct the widgets */
973     for(q = ql->q, row = 0; q; q = q->next, ++row) {
974       /* Figure out the widget name for this row */
975       if(q == playing_track) style = active_style;
976       else style = row % 2 ? even_style : odd_style;
977       /* Make the widget for each column */
978       for(col = 0; col <= ql->ncolumns; ++col) {
979         /* Create and store the widget */
980         if(col < ql->ncolumns)
981           w = get_queue_cell(ql, q, row, col, style, &maxwidths[col]);
982         else
983           w = get_padding_cell(style);
984         ql->cells[row * (ql->ncolumns + 1) + col] = w;
985         /* Maybe mark it draggable */
986         if(draggable_row(q)) {
987           gtk_drag_source_set(w, GDK_BUTTON1_MASK,
988                               dragtargets, NDRAGTARGETS, GDK_ACTION_MOVE);
989           g_signal_connect(w, "drag-begin", G_CALLBACK(queue_drag_begin), q);
990         }
991         /* Catch button presses */
992         g_signal_connect(w, "button-release-event",
993                          G_CALLBACK(queuelike_button_released), q);
994         g_signal_connect(w, "button-press-event",
995                          G_CALLBACK(queuelike_button_released), q);
996       }
997     }
998     /* ...and of each row in the main layout */
999     gtk_widget_size_request(GTK_BIN(ql->cells[0])->child, &req);
1000     ql->mainrowheight = req.height;
1001     /* Now we know the maximum width of each column we can set the size of
1002      * everything and position it */
1003     for(row = 0, q = ql->q; row < ql->nrows; ++row, q = q->next) {
1004       x = 0;
1005       for(col = 0; col < ql->ncolumns; ++col) {
1006         w = ql->cells[row * (ql->ncolumns + 1) + col];
1007         gtk_widget_set_size_request(GTK_BIN(w)->child,
1008                                     maxwidths[col], -1);
1009         gtk_layout_put(GTK_LAYOUT(ql->mainlayout), w, x, y);
1010         x += maxwidths[col];
1011       }
1012       w = ql->cells[row * (ql->ncolumns + 1) + col];
1013       gtk_widget_set_size_request(GTK_BIN(w)->child,
1014                                   totalwidth - x, -1);
1015       gtk_layout_put(GTK_LAYOUT(ql->mainlayout), w, x, y);
1016       y += ql->mainrowheight;
1017     }
1018   }
1019   /* Titles */
1020   x = 0;
1021   for(col = 0; col < ql->ncolumns; ++col) {
1022     gtk_widget_set_size_request(GTK_BIN(ql->titlecells[col])->child,
1023                                 maxwidths[col], -1);
1024     gtk_layout_move(GTK_LAYOUT(ql->titlelayout), ql->titlecells[col], x, 0);
1025     x += maxwidths[col];
1026   }
1027   gtk_widget_set_size_request(GTK_BIN(ql->titlecells[col])->child,
1028                               totalwidth - x, -1);
1029   gtk_layout_move(GTK_LAYOUT(ql->titlelayout), ql->titlecells[col], x, 0);
1030   /* Set the states */
1031   set_widget_states(ql);
1032   /* Make sure it's all visible */
1033   gtk_widget_show_all(ql->mainlayout);
1034   gtk_widget_show_all(ql->titlelayout);
1035   /* Layouts might shrink to arrange for the area they shrink out of to be
1036    * redrawn */
1037   gtk_widget_queue_draw(ql->mainlayout);
1038   gtk_widget_queue_draw(ql->titlelayout);
1039   /* Adjust the size of the layout */
1040   gtk_layout_set_size(GTK_LAYOUT(ql->mainlayout), x, y);
1041   gtk_layout_set_size(GTK_LAYOUT(ql->titlelayout), x, titlerowheight);
1042   gtk_widget_set_size_request(ql->titlelayout, -1, titlerowheight);
1043 }
1044
1045 /** @brief Called with new queue/recent contents */ 
1046 static void queuelike_completed(void *v, struct queue_entry *q) {
1047   struct callbackdata *cbd = v;
1048   struct queuelike *ql = cbd->u.ql;
1049
1050   D(("queuelike_complete"));
1051   /* Install the new queue */
1052   update_queue(ql, ql->fixup ? ql->fixup(q) : q);
1053   /* Update the display */
1054   redisplay_queue(ql);
1055   if(ql->notify)
1056     ql->notify();
1057   /* Update sensitivity of main menu items */
1058   menu_update(-1);
1059 }
1060
1061 /** @brief Called with a new currently playing track */
1062 static void playing_completed(void attribute((unused)) *v,
1063                               struct queue_entry *q) {
1064   struct callbackdata cbd;
1065   D(("playing_completed"));
1066   playing_track = q;
1067   /* Record when we got the playing track data so we know how old the 'sofar'
1068    * field is */
1069   time(&last_playing);
1070   cbd.u.ql = &ql_queue;
1071   queuelike_completed(&cbd, actual_queue);
1072 }
1073
1074 /** @brief Called when the queue is scrolled */
1075 static void queue_scrolled(GtkAdjustment *adjustment,
1076                            gpointer user_data) {
1077   GtkAdjustment *titleadj = user_data;
1078
1079   D(("queue_scrolled"));
1080   gtk_adjustment_set_value(titleadj, adjustment->value);
1081 }
1082
1083 /** @brief Create a queuelike thing (queue/recent) */
1084 static GtkWidget *queuelike(struct queuelike *ql,
1085                             struct queue_entry *(*fixup)(struct queue_entry *),
1086                             void (*notify)(void),
1087                             struct queue_menuitem *menuitems,
1088                             const struct column *columns,
1089                             int ncolumns) {
1090   GtkWidget *vbox, *mainscroll, *titlescroll, *label;
1091   GtkAdjustment *mainadj, *titleadj;
1092   int col, n;
1093
1094   D(("queuelike"));
1095   ql->fixup = fixup;
1096   ql->notify = notify;
1097   ql->menuitems = menuitems;
1098   ql->mainrowheight = !0;                /* else division by 0 */
1099   ql->selection = selection_new();
1100   ql->columns = columns;
1101   ql->ncolumns = ncolumns;
1102   /* Create the layouts */
1103   NW(layout);
1104   ql->mainlayout = gtk_layout_new(0, 0);
1105   gtk_widget_set_style(ql->mainlayout, layout_style);
1106   NW(layout);
1107   ql->titlelayout = gtk_layout_new(0, 0);
1108   gtk_widget_set_style(ql->titlelayout, title_style);
1109   /* Scroll the layouts */
1110   ql->mainscroll = mainscroll = scroll_widget(ql->mainlayout);
1111   titlescroll = scroll_widget(ql->titlelayout);
1112   gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(titlescroll),
1113                                  GTK_POLICY_NEVER, GTK_POLICY_NEVER);
1114   mainadj = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(mainscroll));
1115   titleadj = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(titlescroll));
1116   g_signal_connect(mainadj, "changed", G_CALLBACK(queue_scrolled), titleadj);
1117   g_signal_connect(mainadj, "value-changed", G_CALLBACK(queue_scrolled), titleadj);
1118   /* Fill the titles and put them anywhere */
1119   for(col = 0; col < ql->ncolumns; ++col) {
1120     NW(label);
1121     label = gtk_label_new(ql->columns[col].name);
1122     gtk_misc_set_alignment(GTK_MISC(label), ql->columns[col].xalign, 0);
1123     ql->titlecells[col] = wrap_queue_cell(label, title_style, 0);
1124     gtk_layout_put(GTK_LAYOUT(ql->titlelayout), ql->titlecells[col], 0, 0);
1125   }
1126   ql->titlecells[col] = get_padding_cell(title_style);
1127   gtk_layout_put(GTK_LAYOUT(ql->titlelayout), ql->titlecells[col], 0, 0);
1128   /* Pack the lot together in a vbox */
1129   NW(vbox);
1130   vbox = gtk_vbox_new(0, 0);
1131   gtk_box_pack_start(GTK_BOX(vbox), titlescroll, 0, 0, 0);
1132   gtk_box_pack_start(GTK_BOX(vbox), mainscroll, 1, 1, 0);
1133   /* Create the popup menu */
1134   NW(menu);
1135   ql->menu = gtk_menu_new();
1136   g_signal_connect(ql->menu, "destroy",
1137                    G_CALLBACK(gtk_widget_destroyed), &ql->menu);
1138   for(n = 0; menuitems[n].name; ++n) {
1139     NW(menu_item);
1140     menuitems[n].w = gtk_menu_item_new_with_label(menuitems[n].name);
1141     gtk_menu_attach(GTK_MENU(ql->menu), menuitems[n].w, 0, 1, n, n + 1);
1142   }
1143   g_object_set_data(G_OBJECT(vbox), "type", (void *)&tabtype_queue);
1144   g_object_set_data(G_OBJECT(vbox), "queue", ql);
1145   /* Catch button presses */
1146   g_signal_connect(ql->mainlayout, "button-release-event",
1147                    G_CALLBACK(mainlayout_button), ql);
1148 #if 0
1149   g_signal_connect(ql->mainlayout, "button-press-event",
1150                    G_CALLBACK(mainlayout_button), ql);
1151 #endif
1152   set_tool_colors(ql->menu);
1153   return vbox;
1154 }
1155
1156 /* Popup menu items -------------------------------------------------------- */
1157
1158 /** @brief Count the number of items selected */
1159 static int queue_count_selected(const struct queuelike *ql) {
1160   return hash_count(ql->selection);
1161 }
1162
1163 /** @brief Count the number of items selected */
1164 static int queue_count_entries(const struct queuelike *ql) {
1165   int nitems = 0;
1166   const struct queue_entry *q;
1167
1168   for(q = ql->q; q; q = q->next)
1169     ++nitems;
1170   return nitems;
1171 }
1172
1173 /** @brief Count the number of items selected, excluding the playing track if
1174  * there is one */
1175 static int count_selected_nonplaying(const struct queuelike *ql) {
1176   int nselected = queue_count_selected(ql);
1177
1178   if(ql->q == playing_track && selection_selected(ql->selection, ql->q->id))
1179     --nselected;
1180   return nselected;
1181 }
1182
1183 /** @brief Determine whether the scratch option should be sensitive */
1184 static int scratch_sensitive(struct queuelike attribute((unused)) *ql,
1185                              struct queue_menuitem attribute((unused)) *m,
1186                              struct queue_entry attribute((unused)) *q) {
1187   /* We can scratch if the playing track is selected */
1188   return (playing_track
1189           && (disorder_eclient_state(client) & DISORDER_CONNECTED)
1190           && selection_selected(ql->selection, playing_track->id));
1191 }
1192
1193 /** @brief Scratch the playing track */
1194 static void scratch_activate(GtkMenuItem attribute((unused)) *menuitem,
1195                              gpointer attribute((unused)) user_data) {
1196   if(playing_track)
1197     disorder_eclient_scratch(client, playing_track->id, 0, 0);
1198 }
1199
1200 /** @brief Determine whether the remove option should be sensitive */
1201 static int remove_sensitive(struct queuelike *ql,
1202                             struct queue_menuitem attribute((unused)) *m,
1203                             struct queue_entry *q) {
1204   /* We can remove if we're hovering over a particular track or any non-playing
1205    * tracks are selected */
1206   return ((disorder_eclient_state(client) & DISORDER_CONNECTED)
1207           && ((q
1208                && q != playing_track)
1209               || count_selected_nonplaying(ql)));
1210 }
1211
1212 /** @brief Remove selected track(s) */
1213 static void remove_activate(GtkMenuItem attribute((unused)) *menuitem,
1214                             gpointer user_data) {
1215   const struct menuiteminfo *mii = user_data;
1216   struct queue_entry *q = mii->q;
1217   struct queuelike *ql = mii->ql;
1218
1219   if(count_selected_nonplaying(mii->ql)) {
1220     /* Remove selected tracks */
1221     for(q = ql->q; q; q = q->next)
1222       if(selection_selected(ql->selection, q->id) && q != playing_track)
1223         disorder_eclient_remove(client, q->id, 0, 0);
1224   } else if(q)
1225     /* Remove just the hovered track */
1226     disorder_eclient_remove(client, q->id, 0, 0);
1227 }
1228
1229 /** @brief Determine whether the properties menu option should be sensitive */
1230 static int properties_sensitive(struct queuelike *ql,
1231                                 struct queue_menuitem attribute((unused)) *m,
1232                                 struct queue_entry attribute((unused)) *q) {
1233   /* "Properties" is sensitive if at least something is selected */
1234   return (hash_count(ql->selection) > 0
1235           && (disorder_eclient_state(client) & DISORDER_CONNECTED));
1236 }
1237
1238 /** @brief Pop up properties for the selected tracks */
1239 static void properties_activate(GtkMenuItem attribute((unused)) *menuitem,
1240                                 gpointer user_data) {
1241   const struct menuiteminfo *mii = user_data;
1242   
1243   queue_properties(mii->ql);
1244 }
1245
1246 /** @brief Determine whether the select all menu option should be sensitive */
1247 static int selectall_sensitive(struct queuelike *ql,
1248                                struct queue_menuitem attribute((unused)) *m,
1249                                struct queue_entry attribute((unused)) *q) {
1250   /* Sensitive if there is anything to select */
1251   return !!ql->q;
1252 }
1253
1254 /** @brief Select all tracks */
1255 static void selectall_activate(GtkMenuItem attribute((unused)) *menuitem,
1256                                gpointer user_data) {
1257   const struct menuiteminfo *mii = user_data;
1258   queue_select_all(mii->ql);
1259 }
1260
1261 /** @brief Determine whether the select none menu option should be sensitive */
1262 static int selectnone_sensitive(struct queuelike *ql,
1263                                 struct queue_menuitem attribute((unused)) *m,
1264                                 struct queue_entry attribute((unused)) *q) {
1265   /* Sensitive if there is anything selected */
1266   return hash_count(ql->selection) != 0;
1267 }
1268
1269 /** @brief Select no tracks */
1270 static void selectnone_activate(GtkMenuItem attribute((unused)) *menuitem,
1271                                gpointer user_data) {
1272   const struct menuiteminfo *mii = user_data;
1273   queue_select_none(mii->ql);
1274 }
1275
1276 /** @brief Determine whether the play menu option should be sensitive */
1277 static int play_sensitive(struct queuelike *ql,
1278                           struct queue_menuitem attribute((unused)) *m,
1279                           struct queue_entry attribute((unused)) *q) {
1280   /* "Play" is sensitive if at least something is selected */
1281   return (hash_count(ql->selection) > 0
1282           && (disorder_eclient_state(client) & DISORDER_CONNECTED));
1283 }
1284
1285 /** @brief Play the selected tracks */
1286 static void play_activate(GtkMenuItem attribute((unused)) *menuitem,
1287                           gpointer user_data) {
1288   const struct menuiteminfo *mii = user_data;
1289   struct queue_entry *q = mii->q;
1290   struct queuelike *ql = mii->ql;
1291
1292   if(queue_count_selected(ql)) {
1293     /* Play selected tracks */
1294     for(q = ql->q; q; q = q->next)
1295       if(selection_selected(ql->selection, q->id))
1296         disorder_eclient_play(client, q->track, 0, 0);
1297   } else if(q)
1298     /* Nothing is selected, so play the hovered track */
1299     disorder_eclient_play(client, q->track, 0, 0);
1300 }
1301
1302 /* The queue --------------------------------------------------------------- */
1303
1304 /** @brief Fix up the queue by sticking the currently playing track on the front */
1305 static struct queue_entry *fixup_queue(struct queue_entry *q) {
1306   D(("fixup_queue"));
1307   actual_queue = q;
1308   if(playing_track) {
1309     if(actual_queue)
1310       actual_queue->prev = playing_track;
1311     playing_track->next = actual_queue;
1312     return playing_track;
1313   } else
1314     return actual_queue;
1315 }
1316
1317 /** @brief Adjust track played label
1318  *
1319  *  Called regularly to adjust the so-far played label (redrawing the whole
1320  * queue once a second makes disobedience occupy >10% of the CPU on my Athlon
1321  * which is ureasonable expensive) */
1322 static gboolean adjust_sofar(gpointer attribute((unused)) data) {
1323   if(playing_length_label && playing_track)
1324     gtk_label_set_text(GTK_LABEL(playing_length_label),
1325                        text_length(playing_track));
1326   return TRUE;
1327 }
1328
1329 /** @brief Popup menu for the queue
1330  *
1331  * Properties first so that finger trouble is less dangerous. */
1332 static struct queue_menuitem queue_menu[] = {
1333   { "Track properties", properties_activate, properties_sensitive, 0, 0 },
1334   { "Select all tracks", selectall_activate, selectall_sensitive, 0, 0 },
1335   { "Deselect all tracks", selectnone_activate, selectnone_sensitive, 0, 0 },
1336   { "Scratch track", scratch_activate, scratch_sensitive, 0, 0 },
1337   { "Remove track from queue", remove_activate, remove_sensitive, 0, 0 },
1338   { 0, 0, 0, 0, 0 }
1339 };
1340
1341 /** @brief Called whenever @ref DISORDER_PLAYING or @ref DISORDER_TRACK_PAUSED changes
1342  *
1343  * We monitor pause/resume as well as whether the track is playing in order to
1344  * keep the time played so far up to date correctly.  See playing_completed().
1345  */
1346 static void playing_update(void attribute((unused)) *v) {
1347   D(("playing_update"));
1348   gtk_label_set_text(GTK_LABEL(report_label), "updating playing track");
1349   disorder_eclient_playing(client, playing_completed, 0);
1350 }
1351
1352 /** @brief Create the queue widget */
1353 GtkWidget *queue_widget(void) {
1354   D(("queue_widget"));
1355   /* Arrange periodic update of the so-far played field */
1356   g_timeout_add(1000/*ms*/, adjust_sofar, 0);
1357   /* Arrange a callback whenever the playing state changes */ 
1358   register_monitor(playing_update, 0, DISORDER_PLAYING|DISORDER_TRACK_PAUSED);
1359   register_reset(queue_update);
1360   /* We pass choose_update() as our notify function since the choose screen
1361    * marks tracks that are playing/in the queue. */
1362   return queuelike(&ql_queue, fixup_queue, choose_update, queue_menu,
1363                    maincolumns, NMAINCOLUMNS);
1364 }
1365
1366 /** @brief Arrange an update of the queue widget
1367  *
1368  * Called when a track is added to the queue, removed from the queue (by user
1369  * cmmand or because it is to be played) or moved within the queue
1370  */
1371 void queue_update(void) {
1372   struct callbackdata *cbd;
1373
1374   D(("queue_update"));
1375   cbd = xmalloc(sizeof *cbd);
1376   cbd->onerror = 0;
1377   cbd->u.ql = &ql_queue;
1378   gtk_label_set_text(GTK_LABEL(report_label), "updating queue");
1379   disorder_eclient_queue(client, queuelike_completed, cbd);
1380 }
1381
1382 /* Recently played tracks -------------------------------------------------- */
1383
1384 /** @brief Fix up the recently played list
1385  *
1386  * It's in the wrong order!  TODO fix this globally */
1387 static struct queue_entry *fixup_recent(struct queue_entry *q) {
1388   struct queue_entry *qr = 0,  *qn;
1389
1390   D(("fixup_recent"));
1391   while(q) {
1392     qn = q->next;
1393     /* Swap next/prev pointers */
1394     q->next = q->prev;
1395     q->prev = qn;
1396     /* Remember last node for new head */
1397     qr = q;
1398     /* Next node */
1399     q = qn;
1400   }
1401   return qr;
1402 }
1403
1404 /** @brief Pop-up menu for recently played list */
1405 static struct queue_menuitem recent_menu[] = {
1406   { "Track properties", properties_activate, properties_sensitive,0, 0 },
1407   { "Select all tracks", selectall_activate, selectall_sensitive, 0, 0 },
1408   { "Deselect all tracks", selectnone_activate, selectnone_sensitive, 0, 0 },
1409   { 0, 0, 0, 0, 0 }
1410 };
1411
1412 /** @brief Create the recently-played list */
1413 GtkWidget *recent_widget(void) {
1414   D(("recent_widget"));
1415   register_reset(recent_update);
1416   return queuelike(&ql_recent, fixup_recent, 0, recent_menu,
1417                    maincolumns, NMAINCOLUMNS);
1418 }
1419
1420 /** @brief Update the recently played list
1421  *
1422  * Called whenever a track is added to it or removed from it.
1423  */
1424 void recent_update(void) {
1425   struct callbackdata *cbd;
1426
1427   D(("recent_update"));
1428   cbd = xmalloc(sizeof *cbd);
1429   cbd->onerror = 0;
1430   cbd->u.ql = &ql_recent;
1431   gtk_label_set_text(GTK_LABEL(report_label), "updating recently played list");
1432   disorder_eclient_recent(client, queuelike_completed, cbd);
1433 }
1434
1435 /* Newly added tracks ------------------------------------------------------ */
1436
1437 /** @brief Pop-up menu for recently played list */
1438 static struct queue_menuitem added_menu[] = {
1439   { "Track properties", properties_activate, properties_sensitive, 0, 0 },
1440   { "Play track", play_activate, play_sensitive, 0, 0 },
1441   { "Select all tracks", selectall_activate, selectall_sensitive, 0, 0 },
1442   { "Deselect all tracks", selectnone_activate, selectnone_sensitive, 0, 0 },
1443   { 0, 0, 0, 0, 0 }
1444 };
1445
1446 /** @brief Create the newly-added list */
1447 GtkWidget *added_widget(void) {
1448   D(("added_widget"));
1449   register_reset(added_update);
1450   return queuelike(&ql_added, 0/*fixup*/, 0/*notify*/, added_menu,
1451                    addedcolumns, NADDEDCOLUMNS);
1452 }
1453
1454 /** @brief Called with an updated list of newly-added tracks
1455  *
1456  * This is called with a raw list of track names but the rest of @ref
1457  * disobedience/queue.c requires @ref queue_entry structures with a valid and
1458  * unique @c id field.  This function fakes it.
1459  */
1460 static void new_completed(void *v, int nvec, char **vec) {
1461   struct queue_entry *q, *qh, *qlast = 0, **qq = &qh;
1462   int n;
1463
1464   for(n = 0; n < nvec; ++n) {
1465     q = xmalloc(sizeof *q);
1466     q->prev = qlast;
1467     q->track = vec[n];
1468     q->id = vec[n];
1469     *qq = q;
1470     qq = &q->next;
1471     qlast = q;
1472   }
1473   *qq = 0;
1474   queuelike_completed(v, qh);
1475 }
1476
1477 /** @brief Update the newly-added list */
1478 void added_update(void) {
1479   struct callbackdata *cbd;
1480   D(("added_updae"));
1481
1482   cbd = xmalloc(sizeof *cbd);
1483   cbd->onerror = 0;
1484   cbd->u.ql = &ql_added;
1485   gtk_label_set_text(GTK_LABEL(report_label),
1486                      "updating newly added track list");
1487   disorder_eclient_new_tracks(client, new_completed, 0/*all*/, cbd);
1488 }
1489
1490 /* Main menu plumbing ------------------------------------------------------ */
1491
1492 static int queue_properties_sensitive(GtkWidget *w) {
1493   return (!!queue_count_selected(g_object_get_data(G_OBJECT(w), "queue"))
1494           && (disorder_eclient_state(client) & DISORDER_CONNECTED));
1495 }
1496
1497 static int queue_selectall_sensitive(GtkWidget *w) {
1498   return !!queue_count_entries(g_object_get_data(G_OBJECT(w), "queue"));
1499 }
1500
1501 static int queue_selectnone_sensitive(GtkWidget *w) {
1502   struct queuelike *const ql = g_object_get_data(G_OBJECT(w), "queue");
1503
1504   return hash_count(ql->selection) != 0;
1505 }
1506
1507 static void queue_properties_activate(GtkWidget *w) {
1508   queue_properties(g_object_get_data(G_OBJECT(w), "queue"));
1509 }
1510
1511 static void queue_selectall_activate(GtkWidget *w) {
1512   queue_select_all(g_object_get_data(G_OBJECT(w), "queue"));
1513 }
1514
1515 static void queue_selectnone_activate(GtkWidget *w) {
1516   queue_select_none(g_object_get_data(G_OBJECT(w), "queue"));
1517 }
1518
1519 static const struct tabtype tabtype_queue = {
1520   queue_properties_sensitive,
1521   queue_selectall_sensitive,
1522   queue_selectnone_sensitive,
1523   queue_properties_activate,
1524   queue_selectall_activate,
1525   queue_selectnone_activate,
1526 };
1527
1528 /* Other entry points ------------------------------------------------------ */
1529
1530 /** @brief Return nonzero if @p track is in the queue */
1531 int queued(const char *track) {
1532   struct queue_entry *q;
1533
1534   D(("queued %s", track));
1535   for(q = ql_queue.q; q; q = q->next)
1536     if(!strcmp(q->track, track))
1537       return 1;
1538   return 0;
1539 }
1540
1541 /*
1542 Local Variables:
1543 c-basic-offset:2
1544 comment-column:40
1545 fill-column:79
1546 indent-tabs-mode:nil
1547 End:
1548 */