chiark / gitweb /
merge missing file fix
[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 #include "disobedience.h"
21 #include "popup.h"
22 #include "queue-generic.h"
23
24 /** @brief The actual queue */
25 static struct queue_entry *actual_queue;
26 static struct queue_entry *actual_playing_track;
27
28 /** @brief The playing track */
29 struct queue_entry *playing_track;
30
31 /** @brief When we last got the playing track */
32 time_t last_playing;
33
34 static void queue_completed(void *v,
35                             const char *err,
36                             struct queue_entry *q);
37 static void playing_completed(void *v,
38                               const char *err,
39                               struct queue_entry *q);
40
41 /** @brief Called when either the actual queue or the playing track change */
42 static void queue_playing_changed(void) {
43   const char *old_id = playing_track ? playing_track->id : 0;
44   
45   /* Check that the playing track isn't in the queue.  There's a race here due
46    * to the fact that we issue the two commands at slightly different times.
47    * If it goes wrong we re-issue and try again, so that we never offer up an
48    * inconsistent state. */
49   if(actual_playing_track) {
50     struct queue_entry *q;
51     for(q = actual_queue; q; q = q->next)
52       if(!strcmp(q->id, actual_playing_track->id))
53         break;
54     if(q) {
55       disorder_eclient_playing(client, playing_completed, 0);
56       disorder_eclient_queue(client, queue_completed, 0);
57       return;
58     }
59   }
60   
61   struct queue_entry *q = xmalloc(sizeof *q);
62   if(actual_playing_track) {
63     *q = *actual_playing_track;
64     q->next = actual_queue;
65     playing_track = q;
66   } else {
67     playing_track = NULL;
68     q = actual_queue;
69   }
70   if(!old_id || !playing_track || strcmp(old_id, playing_track->id))
71     time(&last_playing);                /* for column_length() */
72   ql_new_queue(&ql_queue, q);
73   /* Tell anyone who cares */
74   event_raise("queue-list-changed", q);
75   event_raise("playing-track-changed", q);
76 }
77
78 /** @brief Update the queue itself */
79 static void queue_completed(void attribute((unused)) *v,
80                             const char *err,
81                             struct queue_entry *q) {
82   if(err) {
83     popup_protocol_error(0, err);
84     return;
85   }
86   actual_queue = q;
87   queue_playing_changed();
88 }
89
90 /** @brief Update the playing track */
91 static void playing_completed(void attribute((unused)) *v,
92                               const char *err,
93                               struct queue_entry *q) {
94   if(err) {
95     popup_protocol_error(0, err);
96     return;
97   }
98   actual_playing_track = q;
99   queue_playing_changed();
100 }
101
102 /** @brief Schedule an update to the queue
103  *
104  * Called whenever a track is added to it or removed from it.
105  */
106 static void queue_changed(const char attribute((unused)) *event,
107                            void  attribute((unused)) *eventdata,
108                            void  attribute((unused)) *callbackdata) {
109   D(("queue_changed"));
110   gtk_label_set_text(GTK_LABEL(report_label), "updating queue");
111   disorder_eclient_queue(client, queue_completed, 0);
112 }
113
114 /** @brief Schedule an update to the playing track
115  *
116  * Called whenever it changes
117  */
118 static void playing_changed(const char attribute((unused)) *event,
119                             void  attribute((unused)) *eventdata,
120                             void  attribute((unused)) *callbackdata) {
121   D(("playing_changed"));
122   gtk_label_set_text(GTK_LABEL(report_label), "updating playing track");
123   disorder_eclient_playing(client, playing_completed, 0);
124 }
125
126 /** @brief Called regularly
127  *
128  * Updates the played-so-far field
129  */
130 static gboolean playing_periodic(gpointer attribute((unused)) data) {
131   /* If there's a track playing, update its row */
132   if(playing_track)
133     ql_update_row(playing_track, 0);
134   return TRUE;
135 }
136
137 /** @brief Called at startup */
138 static void queue_init(void) {
139   /* Arrange a callback whenever the playing state changes */ 
140   event_register("playing-changed", playing_changed, 0);
141   /* We reget both playing track and queue at pause/resume so that start times
142    * can be computed correctly */
143   event_register("pause-changed", playing_changed, 0);
144   event_register("pause-changed", queue_changed, 0);
145   /* Reget the queue whenever it changes */
146   event_register("queue-changed", queue_changed, 0);
147   /* ...and once a second anyway */
148   g_timeout_add(1000/*ms*/, playing_periodic, 0);
149 }
150
151 /** @brief Columns for the queue */
152 static const struct queue_column queue_columns[] = {
153   { "When",   column_when,     0,        COL_RIGHT },
154   { "Who",    column_who,      0,        0 },
155   { "Artist", column_namepart, "artist", COL_EXPAND|COL_ELLIPSIZE },
156   { "Album",  column_namepart, "album",  COL_EXPAND|COL_ELLIPSIZE },
157   { "Title",  column_namepart, "title",  COL_EXPAND|COL_ELLIPSIZE },
158   { "Length", column_length,   0,        COL_RIGHT }
159 };
160
161 /** @brief Pop-up menu for queue */
162 static struct menuitem queue_menuitems[] = {
163   { "Track properties", ql_properties_activate, ql_properties_sensitive, 0, 0 },
164   { "Select all tracks", ql_selectall_activate, ql_selectall_sensitive, 0, 0 },
165   { "Deselect all tracks", ql_selectnone_activate, ql_selectnone_sensitive, 0, 0 },
166   { "Scratch playing track", ql_scratch_activate, ql_scratch_sensitive, 0, 0 },
167   { "Remove track from queue", ql_remove_activate, ql_remove_sensitive, 0, 0 },
168 };
169
170 struct queuelike ql_queue = {
171   .name = "queue",
172   .init = queue_init,
173   .columns = queue_columns,
174   .ncolumns = sizeof queue_columns / sizeof *queue_columns,
175   .menuitems = queue_menuitems,
176   .nmenuitems = sizeof queue_menuitems / sizeof *queue_menuitems
177 };
178
179 /* Drag and drop has to be figured out experimentally, because it is not well
180  * documented.
181  *
182  * First you get a row-inserted.  The path argument points to the destination
183  * row but this will not yet have had its values set.  The source row is still
184  * present.  AFAICT the iter argument points to the same place.
185  *
186  * Then you get a row-deleted.  The path argument identifies the row that was
187  * deleted.  By this stage the row inserted above has acquired its values.
188  *
189  * A complication is that the deletion will move the inserted row.  For
190  * instance, if you do a drag that moves row 1 down to after the track that was
191  * formerly on row 9, in the row-inserted call it will show up as row 10, but
192  * in the row-deleted call, row 1 will have been deleted thus making the
193  * inserted row be row 9.
194  *
195  * So when we see the row-inserted we have no idea what track to move.
196  * Therefore we stash it until we see a row-deleted.
197  */
198
199 /** @brief Target row for drag */
200 static int queue_drag_target = -1;
201
202 static void queue_move_completed(void attribute((unused)) *v,
203                                  const char *err) {
204   if(err) {
205     popup_protocol_error(0, err);
206     return;
207   }
208   /* The log should tell us the queue changed so we do no more here */
209 }
210
211 static void queue_row_deleted(GtkTreeModel *treemodel,
212                               GtkTreePath *path,
213                               gpointer attribute((unused)) user_data) {
214   if(!suppress_actions) {
215 #if 0
216     char *ps = gtk_tree_path_to_string(path);
217     fprintf(stderr, "row-deleted path=%s queue_drag_target=%d\n",
218             ps, queue_drag_target);
219     GtkTreeIter j[1];
220     gboolean jt = gtk_tree_model_get_iter_first(treemodel, j);
221     int row = 0;
222     while(jt) {
223       struct queue_entry *q = ql_iter_to_q(treemodel, j);
224       fprintf(stderr, " %2d %s\n", row++, q ? q->track : "(no q)");
225       jt = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql_queue.store), j);
226     }
227     g_free(ps);
228 #endif
229     if(queue_drag_target < 0) {
230       error(0, "unsuppressed row-deleted with no row-inserted");
231       return;
232     }
233     int drag_source = gtk_tree_path_get_indices(path)[0];
234
235     /* If the drag is downwards (=towards higher row numbers) then the target
236      * will have been moved upwards (=towards lower row numbers) by one row. */
237     if(drag_source < queue_drag_target)
238       --queue_drag_target;
239     
240     /* Find the track to move */
241     GtkTreeIter src[1];
242     gboolean srcv = gtk_tree_model_iter_nth_child(treemodel, src, NULL,
243                                                   queue_drag_target);
244     if(!srcv) {
245       error(0, "cannot get iterator to drag target %d", queue_drag_target);
246       queue_playing_changed();
247       queue_drag_target = -1;
248       return;
249     }
250     struct queue_entry *srcq = ql_iter_to_q(treemodel, src);
251     assert(srcq);
252     //fprintf(stderr, "move %s %s\n", srcq->id, srcq->track);
253     
254     /* Don't allow the currently playing track to be moved.  As above, we put
255      * the queue back into the right order straight away. */
256     if(srcq == playing_track) {
257       //fprintf(stderr, "cannot move currently playing track\n");
258       queue_playing_changed();
259       queue_drag_target = -1;
260       return;
261     }
262
263     /* Find the destination */
264     struct queue_entry *dstq;
265     if(queue_drag_target) {
266       GtkTreeIter dst[1];
267       gboolean dstv = gtk_tree_model_iter_nth_child(treemodel, dst, NULL,
268                                                     queue_drag_target - 1);
269       if(!dstv) {
270         error(0, "cannot get iterator to drag target predecessor %d",
271               queue_drag_target - 1);
272         queue_playing_changed();
273         queue_drag_target = -1;
274         return;
275       }
276       dstq = ql_iter_to_q(treemodel, dst);
277       assert(dstq);
278       if(dstq == playing_track)
279         dstq = 0;
280     } else
281       dstq = 0;
282     /* NB if the user attempts to move a queued track before the currently
283      * playing track we assume they just missed a bit, and put it after. */
284     //fprintf(stderr, " target %s %s\n", dstq ? dstq->id : "(none)", dstq ? dstq->track : "(none)");
285     /* Now we know what is to be moved.  We need to know the preceding queue
286      * entry so we can move it. */
287     disorder_eclient_moveafter(client,
288                                dstq ? dstq->id : "",
289                                1, &srcq->id,
290                                queue_move_completed, NULL);
291     queue_drag_target = -1;
292   }
293 }
294
295 static void queue_row_inserted(GtkTreeModel attribute((unused)) *treemodel,
296                                GtkTreePath *path,
297                                GtkTreeIter attribute((unused)) *iter,
298                                gpointer attribute((unused)) user_data) {
299   if(!suppress_actions) {
300 #if 0
301     char *ps = gtk_tree_path_to_string(path);
302     GtkTreeIter piter[1];
303     gboolean pi = gtk_tree_model_get_iter(treemodel, piter, path);
304     struct queue_entry *pq = pi ? ql_iter_to_q(treemodel, piter) : 0;
305     struct queue_entry *iq = ql_iter_to_q(treemodel, iter);
306
307     fprintf(stderr, "row-inserted path=%s pi=%d pq=%p path=%s iq=%p iter=%s\n",
308             ps,
309             pi,
310             pq,
311             (pi
312              ? (pq ? pq->track : "(pq=0)")
313              : "(pi=FALSE)"),
314             iq,
315             iq ? iq->track : "(iq=0)");
316
317     GtkTreeIter j[1];
318     gboolean jt = gtk_tree_model_get_iter_first(treemodel, j);
319     int row = 0;
320     while(jt) {
321       struct queue_entry *q = ql_iter_to_q(treemodel, j);
322       fprintf(stderr, " %2d %s\n", row++, q ? q->track : "(no q)");
323       jt = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql_queue.store), j);
324     }
325     g_free(ps);
326 #endif
327     queue_drag_target = gtk_tree_path_get_indices(path)[0];
328   }
329 }
330
331 /** @brief Called when a key is pressed in the queue tree view */
332 static gboolean queue_key_press(GtkWidget attribute((unused)) *widget,
333                                 GdkEventKey *event,
334                                 gpointer user_data) {
335   /*fprintf(stderr, "queue_key_press type=%d state=%#x keyval=%#x\n",
336           event->type, event->state, event->keyval);*/
337   switch(event->keyval) {
338   case GDK_BackSpace:
339   case GDK_Delete:
340     if(event->state)
341       break;                            /* Only take unmodified DEL/<-- */
342     ql_remove_activate(0, user_data);
343     return TRUE;                        /* Do not propagate */
344   }
345   return FALSE;                         /* Propagate */
346 }
347
348 GtkWidget *queue_widget(void) {
349   GtkWidget *const w = init_queuelike(&ql_queue);
350
351   /* Enable drag+drop */
352   gtk_tree_view_set_reorderable(GTK_TREE_VIEW(ql_queue.view), TRUE);
353   g_signal_connect(ql_queue.store,
354                    "row-inserted",
355                    G_CALLBACK(queue_row_inserted), &ql_queue);
356   g_signal_connect(ql_queue.store,
357                    "row-deleted",
358                    G_CALLBACK(queue_row_deleted), &ql_queue);
359   /* Catch keypresses */
360   g_signal_connect(ql_queue.view, "key-press-event",
361                    G_CALLBACK(queue_key_press), &ql_queue);
362   return w;
363 }
364
365 /** @brief Return nonzero if @p track is in the queue */
366 int queued(const char *track) {
367   struct queue_entry *q;
368
369   D(("queued %s", track));
370   /* Queue will contain resolved name */
371   track = namepart_resolve(track);
372   for(q = ql_queue.q; q; q = q->next)
373     if(!strcmp(q->track, track))
374       return 1;
375   return 0;
376 }
377
378 /*
379 Local Variables:
380 c-basic-offset:2
381 comment-column:40
382 fill-column:79
383 indent-tabs-mode:nil
384 End:
385 */