chiark / gitweb /
--without-server builds should now work again.
[disorder] / disobedience / queue-generic.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 3 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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU 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, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file disobedience/queue-generic.c
19  * @brief Disobedience queue widgets
20  *
21  * This file provides contains code shared between all the queue-like
22  * widgets - the queue, the recent list and the added tracks list.
23  *
24  * This code is in the process of being rewritten to use the native list
25  * widget.
26  *
27  * There are three @ref queuelike objects: @ref ql_queue, @ref
28  * ql_recent and @ref ql_added.  Each has an associated queue linked
29  * list and a list store containing the contents.
30  *
31  * When new contents turn up we rearrange the list store accordingly.
32  *
33  * NB that while in the server the playing track is not in the queue, in
34  * Disobedience, the playing does live in @c ql_queue.q, despite its different
35  * status to everything else found in that list.
36  *
37  * To do:
38  * - display playing row in a different color?
39  */
40 #include "disobedience.h"
41 #include "popup.h"
42 #include "queue-generic.h"
43
44 /* Track detail lookup ----------------------------------------------------- */
45
46 static void queue_lookups_completed(const char attribute((unused)) *event,
47                                    void attribute((unused)) *eventdata,
48                                    void *callbackdata) {
49   struct queuelike *ql = callbackdata;
50   ql_update_list_store(ql);
51 }
52
53 /* Column formatting -------------------------------------------------------- */
54
55 /** @brief Format the 'when' column */
56 const char *column_when(const struct queue_entry *q,
57                         const char attribute((unused)) *data) {
58   char when[64];
59   struct tm tm;
60   time_t t;
61
62   D(("column_when"));
63   switch(q->state) {
64   case playing_isscratch:
65   case playing_unplayed:
66   case playing_random:
67     t = q->expected;
68     break;
69   case playing_failed:
70   case playing_no_player:
71   case playing_ok:
72   case playing_scratched:
73   case playing_started:
74   case playing_paused:
75   case playing_quitting:
76     t = q->played;
77     break;
78   default:
79     t = 0;
80     break;
81   }
82   if(t)
83     strftime(when, sizeof when, "%H:%M", localtime_r(&t, &tm));
84   else
85     when[0] = 0;
86   return xstrdup(when);
87 }
88
89 /** @brief Format the 'who' column */
90 const char *column_who(const struct queue_entry *q,
91                        const char attribute((unused)) *data) {
92   D(("column_who"));
93   return q->submitter ? q->submitter : "";
94 }
95
96 /** @brief Format one of the track name columns */
97 const char *column_namepart(const struct queue_entry *q,
98                             const char *data) {
99   D(("column_namepart"));
100   return namepart(q->track, "display", data);
101 }
102
103 /** @brief Format the length column */
104 const char *column_length(const struct queue_entry *q,
105                           const char attribute((unused)) *data) {
106   D(("column_length"));
107   long l;
108   time_t now;
109   char *played = 0, *length = 0;
110
111   /* Work out what to say for the length */
112   l = namepart_length(q->track);
113   if(l > 0)
114     byte_xasprintf(&length, "%ld:%02ld", l / 60, l % 60);
115   else
116     byte_xasprintf(&length, "?:??");
117   /* For the currently playing track we want to report how much of the track
118    * has been played */
119   if(q == playing_track) {
120     /* log_state() arranges that we re-get the playing data whenever the
121      * pause/resume state changes */
122     if(last_state & DISORDER_TRACK_PAUSED)
123       l = playing_track->sofar;
124     else {
125       if(!last_playing)
126         return NULL;
127       xtime(&now);
128       l = playing_track->sofar + (now - last_playing);
129     }
130     byte_xasprintf(&played, "%ld:%02ld/%s", l / 60, l % 60, length);
131     return played;
132   } else
133     return length;
134 }
135
136 /* List store maintenance -------------------------------------------------- */
137
138 /** @brief Return the @ref queue_entry corresponding to @p iter
139  * @param model Model that owns @p iter
140  * @param iter Tree iterator
141  * @return Pointer to queue entry
142  */
143 struct queue_entry *ql_iter_to_q(GtkTreeModel *model,
144                                  GtkTreeIter *iter) {
145   struct queuelike *ql = g_object_get_data(G_OBJECT(model), "ql");
146   GValue v[1];
147   memset(v, 0, sizeof v);
148   gtk_tree_model_get_value(model, iter, ql->ncolumns + QUEUEPOINTER_COLUMN, v);
149   assert(G_VALUE_TYPE(v) == G_TYPE_POINTER);
150   struct queue_entry *const q = g_value_get_pointer(v);
151   g_value_unset(v);
152   return q;
153 }
154
155 /** @brief Update one row of a list store
156  * @param q Queue entry
157  * @param iter Iterator referring to row or NULL to work it out
158  */
159 void ql_update_row(struct queue_entry *q,
160                    GtkTreeIter *iter) { 
161   const struct queuelike *const ql = q->ql; 
162
163   D(("ql_update_row"));
164   /* If no iter was supplied, work it out */
165   GtkTreeIter my_iter[1];
166   if(!iter) {
167     gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store), my_iter);
168     struct queue_entry *qq;
169     for(qq = ql->q; qq && q != qq; qq = qq->next)
170       gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), my_iter);
171     if(!qq)
172       return;
173     iter = my_iter;
174   }
175   /* Update all the columns */
176   for(int col = 0; col < ql->ncolumns; ++col) {
177     const char *const v = ql->columns[col].value(q,
178                                                  ql->columns[col].data);
179     if(v)
180       gtk_list_store_set(ql->store, iter,
181                          col, v,
182                          -1);
183   }
184   gtk_list_store_set(ql->store, iter,
185                      ql->ncolumns + QUEUEPOINTER_COLUMN, q,
186                      -1);
187   if(q == playing_track)
188     gtk_list_store_set(ql->store, iter,
189                        ql->ncolumns + BACKGROUND_COLUMN, BG_PLAYING,
190                        ql->ncolumns + FOREGROUND_COLUMN, FG_PLAYING,
191                        -1);
192   else
193     gtk_list_store_set(ql->store, iter,
194                        ql->ncolumns + BACKGROUND_COLUMN, (char *)0,
195                        ql->ncolumns + FOREGROUND_COLUMN, (char *)0,
196                        -1);
197 }
198
199 /** @brief Update the list store
200  * @param ql Queuelike to update
201  *
202  * Called when new namepart data is available (and initially).  Doesn't change
203  * the rows, just updates the cell values.
204  */
205 void ql_update_list_store(struct queuelike *ql) {
206   D(("ql_update_list_store"));
207   GtkTreeIter iter[1];
208   gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store), iter);
209   for(struct queue_entry *q = ql->q; q; q = q->next) {
210     ql_update_row(q, iter);
211     gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), iter);
212   }
213 }
214
215 struct newqueue_data {
216   struct queue_entry *old, *new;
217 };
218
219 static void record_queue_map(hash *h,
220                              const char *id,
221                              struct queue_entry *old,
222                              struct queue_entry *new) {
223   struct newqueue_data *nqd;
224
225   if(!(nqd = hash_find(h, id))) {
226     static const struct newqueue_data empty[1];
227     hash_add(h, id, empty, HASH_INSERT);
228     nqd = hash_find(h, id);
229   }
230   if(old)
231     nqd->old = old;
232   if(new)
233     nqd->new = new;
234 }
235
236 #if 0
237 static void dump_queue(struct queue_entry *head, struct queue_entry *mark) {
238   for(struct queue_entry *q = head; q; q = q->next) {
239     if(q == mark)
240       fprintf(stderr, "!");
241     fprintf(stderr, "%s", q->id);
242     if(q->next)
243       fprintf(stderr, " ");
244   }
245   fprintf(stderr, "\n");
246 }
247
248 static void dump_rows(struct queuelike *ql) {
249   GtkTreeIter iter[1];
250   gboolean it = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store),
251                                               iter);
252   while(it) {
253     struct queue_entry *q = ql_iter_to_q(GTK_TREE_MODEL(ql->store), iter);
254     it = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), iter);
255     fprintf(stderr, "%s", q->id);
256     if(it)
257       fprintf(stderr, " ");
258   }
259   fprintf(stderr, "\n");
260 }
261 #endif
262
263 /** @brief Reset the list store
264  * @param ql Queuelike to reset
265  * @param newq New queue contents/ordering
266  *
267  * Updates the queue to match @p newq
268  */
269 void ql_new_queue(struct queuelike *ql,
270                   struct queue_entry *newq) {
271   D(("ql_new_queue"));
272   ++suppress_actions;
273
274   /* Tell every queue entry which queue owns it */
275   //fprintf(stderr, "%s: filling in q->ql\n", ql->name);
276   for(struct queue_entry *q = newq; q; q = q->next)
277     q->ql = ql;
278
279   //fprintf(stderr, "%s: constructing h\n", ql->name);
280   /* Construct map from id to new and old structures */
281   hash *h = hash_new(sizeof(struct newqueue_data));
282   for(struct queue_entry *q = ql->q; q; q = q->next)
283     record_queue_map(h, q->id, q, NULL);
284   for(struct queue_entry *q = newq; q; q = q->next)
285     record_queue_map(h, q->id, NULL, q);
286
287   /* The easy bit: delete rows not present any more.  In the same pass we
288    * update the secret column containing the queue_entry pointer. */
289   //fprintf(stderr, "%s: deleting rows...\n", ql->name);
290   GtkTreeIter iter[1];
291   gboolean it = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store),
292                                               iter);
293   int inserted = 0, deleted = 0, kept = 0;
294   while(it) {
295     struct queue_entry *q = ql_iter_to_q(GTK_TREE_MODEL(ql->store), iter);
296     const struct newqueue_data *nqd = hash_find(h, q->id);
297     if(nqd->new) {
298       /* Tell this row that it belongs to the new version of the queue */
299       gtk_list_store_set(ql->store, iter,
300                          ql->ncolumns + QUEUEPOINTER_COLUMN, nqd->new,
301                          -1);
302       it = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), iter);
303       ++kept;
304     } else {
305       /* Delete this row (and move iter to the next one) */
306       //fprintf(stderr, " delete %s", q->id);
307       it = gtk_list_store_remove(ql->store, iter);
308       ++deleted;
309     }
310   }
311
312   /* Now every row's secret column is right, but we might be missing new rows
313    * and they might be in the wrong order */
314
315   /* We're going to have to support arbitrary rearrangements, so we might as
316    * well add new elements at the end. */
317   //fprintf(stderr, "%s: adding rows...\n", ql->name);
318   struct queue_entry *after = 0;
319   for(struct queue_entry *q = newq; q; q = q->next) {
320     const struct newqueue_data *nqd = hash_find(h, q->id);
321     if(!nqd->old) {
322       if(after) {
323         /* Try to insert at the right sort of place */
324         GtkTreeIter where[1];
325         gboolean wit = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store),
326                                                      where);
327         while(wit && ql_iter_to_q(GTK_TREE_MODEL(ql->store), where) != after)
328           wit = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), where);
329         if(wit)
330           gtk_list_store_insert_after(ql->store, iter, where);
331         else
332           gtk_list_store_append(ql->store, iter);
333       } else
334         gtk_list_store_prepend(ql->store, iter);
335       gtk_list_store_set(ql->store, iter,
336                          ql->ncolumns + QUEUEPOINTER_COLUMN, q,
337                          -1);
338       //fprintf(stderr, " add %s", q->id);
339       ++inserted;
340     }
341     after = newq;
342   }
343
344   /* Now exactly the right set of rows are present, and they have the right
345    * queue_entry pointers in their secret column, but they may be in the wrong
346    * order.
347    *
348    * The current code is simple but amounts to a bubble-sort - we might easily
349    * called gtk_tree_model_iter_next a couple of thousand times.
350    */
351   //fprintf(stderr, "%s: rearranging rows\n", ql->name);
352   //fprintf(stderr, "%s: queue state: ", ql->name);
353   //dump_queue(newq, 0);
354   //fprintf(stderr, "%s: row state: ", ql->name);
355   //dump_rows(ql);
356   it = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ql->store),
357                                               iter);
358   struct queue_entry *rq = newq;        /* r for 'right, correct' */
359   int swaps = 0, searches = 0;
360   while(it) {
361     struct queue_entry *q = ql_iter_to_q(GTK_TREE_MODEL(ql->store), iter);
362     //fprintf(stderr, " rq = %p, q = %p\n", rq, q);
363     //fprintf(stderr, " rq->id = %s, q->id = %s\n", rq->id, q->id);
364
365     if(q != rq) {
366       //fprintf(stderr, "  mismatch\n");
367       GtkTreeIter next[1] = { *iter };
368       gboolean nit = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), next);
369       while(nit) {
370         struct queue_entry *nq = ql_iter_to_q(GTK_TREE_MODEL(ql->store), next);
371         //fprintf(stderr, "   candidate: %s\n", nq->id);
372         if(nq == rq)
373           break;
374         nit = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), next);
375         ++searches;
376       }
377       assert(nit);
378       //fprintf(stderr, "  found it\n");
379       gtk_list_store_swap(ql->store, iter, next);
380       *iter = *next;
381       //fprintf(stderr, "%s: new row state: ", ql->name);
382       //dump_rows(ql);
383       ++swaps;
384     }
385     /* ...and onto the next one */
386     it = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), iter);
387     rq = rq->next;
388   }
389 #if 0
390   fprintf(stderr, "%6s: %3d kept %3d inserted %3d deleted %3d swaps %4d searches\n", ql->name,
391           kept, inserted, deleted, swaps, searches);
392 #endif
393   //fprintf(stderr, "done\n");
394   ql->q = newq;
395   /* Set the rest of the columns in new rows */
396   ql_update_list_store(ql);
397   --suppress_actions;
398 }
399
400 /* Drag and drop has to be figured out experimentally, because it is not well
401  * documented.
402  *
403  * First you get a row-inserted.  The path argument points to the destination
404  * row but this will not yet have had its values set.  The source row is still
405  * present.  AFAICT the iter argument points to the same place.
406  *
407  * Then you get a row-deleted.  The path argument identifies the row that was
408  * deleted.  By this stage the row inserted above has acquired its values.
409  *
410  * A complication is that the deletion will move the inserted row.  For
411  * instance, if you do a drag that moves row 1 down to after the track that was
412  * formerly on row 9, in the row-inserted call it will show up as row 10, but
413  * in the row-deleted call, row 1 will have been deleted thus making the
414  * inserted row be row 9.
415  *
416  * So when we see the row-inserted we have no idea what track to move.
417  * Therefore we stash it until we see a row-deleted.
418  */
419
420 /** @brief row-inserted callback */
421 static void ql_row_inserted(GtkTreeModel attribute((unused)) *treemodel,
422                             GtkTreePath *path,
423                             GtkTreeIter attribute((unused)) *iter,
424                             gpointer user_data) {
425   struct queuelike *const ql = user_data;
426   if(!suppress_actions) {
427 #if 0
428     char *ps = gtk_tree_path_to_string(path);
429     GtkTreeIter piter[1];
430     gboolean pi = gtk_tree_model_get_iter(treemodel, piter, path);
431     struct queue_entry *pq = pi ? ql_iter_to_q(treemodel, piter) : 0;
432     struct queue_entry *iq = ql_iter_to_q(treemodel, iter);
433
434     fprintf(stderr, "row-inserted %s path=%s pi=%d pq=%p path=%s iq=%p iter=%s\n",
435             ql->name,
436             ps,
437             pi,
438             pq,
439             (pi
440              ? (pq ? pq->track : "(pq=0)")
441              : "(pi=FALSE)"),
442             iq,
443             iq ? iq->track : "(iq=0)");
444
445     GtkTreeIter j[1];
446     gboolean jt = gtk_tree_model_get_iter_first(treemodel, j);
447     int row = 0;
448     while(jt) {
449       struct queue_entry *q = ql_iter_to_q(treemodel, j);
450       fprintf(stderr, " %2d %s\n", row++, q ? q->track : "(no q)");
451       jt = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), j);
452     }
453     g_free(ps);
454 #endif
455     /* Remember an iterator pointing at the insertion target */
456     if(ql->drag_target)
457       gtk_tree_path_free(ql->drag_target);
458     ql->drag_target = gtk_tree_path_copy(path);
459   }
460 }
461
462 /** @brief row-deleted callback */
463 static void ql_row_deleted(GtkTreeModel attribute((unused)) *treemodel,
464                            GtkTreePath *path,
465                            gpointer user_data) {
466   struct queuelike *const ql = user_data;
467
468   if(!suppress_actions) {
469 #if 0
470     char *ps = gtk_tree_path_to_string(path);
471     fprintf(stderr, "row-deleted %s path=%s ql->drag_target=%s\n",
472             ql->name, ps, gtk_tree_path_to_string(ql->drag_target));
473     GtkTreeIter j[1];
474     gboolean jt = gtk_tree_model_get_iter_first(treemodel, j);
475     int row = 0;
476     while(jt) {
477       struct queue_entry *q = ql_iter_to_q(treemodel, j);
478       fprintf(stderr, " %2d %s\n", row++, q ? q->track : "(no q)");
479       jt = gtk_tree_model_iter_next(GTK_TREE_MODEL(ql->store), j);
480     }
481     g_free(ps);
482 #endif
483     if(!ql->drag_target) {
484       error(0, "%s: unsuppressed row-deleted with no row-inserted",
485             ql->name);
486       return;
487     }
488
489     /* Get the source and destination row numbers. */
490     int srcrow = gtk_tree_path_get_indices(path)[0];
491     int dstrow = gtk_tree_path_get_indices(ql->drag_target)[0];
492     //fprintf(stderr, "srcrow=%d dstrow=%d\n", srcrow, dstrow);
493
494     /* Note that the source row is computed AFTER the destination has been
495      * inserted, since GTK+ does the insert before the delete.  Therefore if
496      * the source row is south (higher row number) of the destination, it will
497      * be one higher than expected.
498      *
499      * For instance if we drag row 1 to before row 0 we will see row-inserted
500      * for row 0 but then a row-deleted for row 2.
501      */
502     if(srcrow > dstrow)
503       --srcrow;
504
505     /* Tell the queue implementation */
506     ql->drop(ql, srcrow, dstrow);
507
508     /* Dispose of stashed data */
509     gtk_tree_path_free(ql->drag_target);
510     ql->drag_target = 0;
511   }
512 }
513
514 /** @brief Initialize a @ref queuelike */
515 GtkWidget *init_queuelike(struct queuelike *ql) {
516   D(("init_queuelike"));
517   /* Create the list store.  We add an extra column to hold a pointer to the
518    * queue_entry. */
519   GType *types = xcalloc(ql->ncolumns + EXTRA_COLUMNS, sizeof (GType));
520   for(int n = 0; n < ql->ncolumns + EXTRA_COLUMNS; ++n)
521     types[n] = G_TYPE_STRING;
522   types[ql->ncolumns + QUEUEPOINTER_COLUMN] = G_TYPE_POINTER;
523   ql->store = gtk_list_store_newv(ql->ncolumns + EXTRA_COLUMNS, types);
524   g_object_set_data(G_OBJECT(ql->store), "ql", (void *)ql);
525
526   /* Create the view */
527   ql->view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(ql->store));
528   gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(ql->view), TRUE);
529
530   /* Create cell renderers and label columns */
531   for(int n = 0; n < ql->ncolumns; ++n) {
532     GtkCellRenderer *r = gtk_cell_renderer_text_new();
533     if(ql->columns[n].flags & COL_ELLIPSIZE)
534       g_object_set(r, "ellipsize", PANGO_ELLIPSIZE_END, (char *)0);
535     if(ql->columns[n].flags & COL_RIGHT)
536       g_object_set(r, "xalign", (gfloat)1.0, (char *)0);
537     GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes
538       (ql->columns[n].name,
539        r,
540        "text", n,
541        "background", ql->ncolumns + BACKGROUND_COLUMN,
542        "foreground", ql->ncolumns + FOREGROUND_COLUMN,
543        (char *)0);
544     gtk_tree_view_column_set_resizable(c, TRUE);
545     gtk_tree_view_column_set_reorderable(c, TRUE);
546     if(ql->columns[n].flags & COL_EXPAND)
547       g_object_set(c, "expand", TRUE, (char *)0);
548     gtk_tree_view_append_column(GTK_TREE_VIEW(ql->view), c);
549   }
550
551   /* The selection should support multiple things being selected */
552   ql->selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(ql->view));
553   gtk_tree_selection_set_mode(ql->selection, GTK_SELECTION_MULTIPLE);
554
555   /* Catch button presses */
556   g_signal_connect(ql->view, "button-press-event",
557                    G_CALLBACK(ql_button_release), ql);
558
559   /* Drag+drop*/
560   if(ql->drop) {
561     gtk_tree_view_set_reorderable(GTK_TREE_VIEW(ql->view), TRUE);
562     g_signal_connect(ql->store,
563                      "row-inserted",
564                      G_CALLBACK(ql_row_inserted), ql);
565     g_signal_connect(ql->store,
566                      "row-deleted",
567                      G_CALLBACK(ql_row_deleted), ql);
568   }
569   
570   /* TODO style? */
571
572   ql->init(ql);
573
574   /* Update display text when lookups complete */
575   event_register("lookups-completed", queue_lookups_completed, ql);
576   
577   GtkWidget *scrolled = scroll_widget(ql->view);
578   g_object_set_data(G_OBJECT(scrolled), "type", (void *)ql_tabtype(ql));
579   return scrolled;
580 }
581
582 /*
583 Local Variables:
584 c-basic-offset:2
585 comment-column:40
586 fill-column:79
587 indent-tabs-mode:nil
588 End:
589 */