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