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