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