chiark / gitweb /
corrected speaker-failed error message
[disorder] / disobedience / disobedience.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
21 #include "disobedience.h"
22
23 #include <getopt.h>
24 #include <locale.h>
25 #include <pcre.h>
26
27 /* Apologies for the numerous de-consting casts, but GLib et al do not seem to
28  * have heard of const. */
29
30 #include "style.h"                      /* generated style */
31
32 /* Functions --------------------------------------------------------------- */
33
34 static void log_connected(void *v);
35 static void log_completed(void *v, const char *track);
36 static void log_failed(void *v, const char *track, const char *status);
37 static void log_moved(void *v, const char *user);
38 static void log_playing(void *v, const char *track, const char *user);
39 static void log_queue(void *v, struct queue_entry *q);
40 static void log_recent_added(void *v, struct queue_entry *q);
41 static void log_recent_removed(void *v, const char *id);
42 static void log_removed(void *v, const char *id, const char *user);
43 static void log_scratched(void *v, const char *track, const char *user);
44 static void log_state(void *v, unsigned long state);
45 static void log_volume(void *v, int l, int r);
46
47 /* Variables --------------------------------------------------------------- */
48
49 GMainLoop *mainloop;                    /* event loop */
50 GtkWidget *toplevel;                    /* top level window */
51 GtkWidget *report_label;                /* label for progress indicator */
52 GtkWidget *tabs;                        /* main tabs */
53
54 disorder_eclient *client;               /* main client */
55
56 unsigned long last_state;               /* last reported state */
57 int playing;                            /* true if playing some track */
58 int volume_l, volume_r;                 /* volume */
59 double goesupto = 10;                   /* volume upper bound */
60 int choosealpha;                        /* break up choose by letter */
61
62 /** @brief True if a NOP is in flight */
63 static int nop_in_flight;
64
65 static const disorder_eclient_log_callbacks gdisorder_log_callbacks = {
66   log_connected,
67   log_completed,
68   log_failed,
69   log_moved,
70   log_playing,
71   log_queue,
72   log_recent_added,
73   log_recent_removed,
74   log_removed,
75   log_scratched,
76   log_state,
77   log_volume
78 };
79
80 /* Window creation --------------------------------------------------------- */
81
82 /* Note that all the client operations kicked off from here will only complete
83  * after we've entered the event loop. */
84
85 static gboolean delete_event(GtkWidget attribute((unused)) *widget,
86                              GdkEvent attribute((unused)) *event,
87                              gpointer attribute((unused)) data) {
88   D(("delete_event"));
89   exit(0);                              /* die immediately */
90 }
91
92 /* Called when the current tab is switched. */
93 static void tab_switched(GtkNotebook attribute((unused)) *notebook,
94                          GtkNotebookPage attribute((unused)) *page,
95                          guint page_num,
96                          gpointer attribute((unused)) user_data) {
97   menu_update(page_num);
98 }
99
100 static GtkWidget *report_box(void) {
101   GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
102
103   report_label = gtk_label_new("");
104   gtk_label_set_ellipsize(GTK_LABEL(report_label), PANGO_ELLIPSIZE_END);
105   gtk_misc_set_alignment(GTK_MISC(report_label), 0, 0);
106   gtk_container_add(GTK_CONTAINER(vbox), gtk_hseparator_new());
107   gtk_container_add(GTK_CONTAINER(vbox), report_label);
108   return vbox;
109 }
110
111 static GtkWidget *notebook(void) {
112   tabs = gtk_notebook_new();
113   g_signal_connect(tabs, "switch-page", G_CALLBACK(tab_switched), 0);
114   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), queue_widget(),
115                            gtk_label_new("Queue"));
116   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), recent_widget(),
117                            gtk_label_new("Recent"));
118   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), choose_widget(),
119                            gtk_label_new("Choose"));
120   return tabs;
121 }
122
123 static void make_toplevel_window(void) {
124   GtkWidget *const vbox = gtk_vbox_new(FALSE, 1);
125   GtkWidget *const rb = report_box();
126
127   D(("top_window"));
128   toplevel = gtk_window_new(GTK_WINDOW_TOPLEVEL);
129   /* default size is too small */
130   gtk_window_set_default_size(GTK_WINDOW(toplevel), 640, 480);
131   /* terminate on close */
132   g_signal_connect(G_OBJECT(toplevel), "delete_event",
133                    G_CALLBACK(delete_event), NULL);
134   /* lay out the window */
135   gtk_window_set_title(GTK_WINDOW(toplevel), "Disobedience");
136   gtk_container_add(GTK_CONTAINER(toplevel), vbox);
137   /* lay out the vbox */
138   gtk_box_pack_start(GTK_BOX(vbox),
139                      menubar(toplevel),
140                      FALSE,             /* expand */
141                      FALSE,             /* fill */
142                      0);
143   gtk_box_pack_start(GTK_BOX(vbox),
144                      control_widget(),
145                      FALSE,             /* expand */
146                      FALSE,             /* fill */
147                      0);
148   gtk_container_add(GTK_CONTAINER(vbox), notebook());
149   gtk_box_pack_end(GTK_BOX(vbox),
150                    rb,
151                    FALSE,             /* expand */
152                    FALSE,             /* fill */
153                    0);
154   gtk_widget_set_name(toplevel, "disobedience");
155 }
156
157 /* State monitoring -------------------------------------------------------- */
158
159 static void all_update(void) {
160   playing_update();
161   queue_update();
162   recent_update();
163   control_update();
164 }
165
166 static void log_connected(void attribute((unused)) *v) {
167   struct callbackdata *cbd;
168
169   /* Don't know what we might have missed while disconnected so update
170    * everything.  We get this at startup too and this is how we do the initial
171    * state fetch. */
172   all_update();
173   /* Re-get the volume */
174   cbd = xmalloc(sizeof *cbd);
175   cbd->onerror = 0;
176   disorder_eclient_volume(client, log_volume, -1, -1, cbd);
177 }
178
179 static void log_completed(void attribute((unused)) *v,
180                           const char attribute((unused)) *track) {
181   playing = 0;
182   playing_update();
183   control_update();
184 }
185
186 static void log_failed(void attribute((unused)) *v,
187                        const char attribute((unused)) *track,
188                        const char attribute((unused)) *status) {
189   playing = 0;
190   playing_update();
191   control_update();
192 }
193
194 static void log_moved(void attribute((unused)) *v,
195                       const char attribute((unused)) *user) {
196    queue_update();
197 }
198
199 static void log_playing(void attribute((unused)) *v,
200                         const char attribute((unused)) *track,
201                         const char attribute((unused)) *user) {
202   playing = 1;
203   playing_update();
204   control_update();
205   /* we get a log_removed() anyway so we don't need to update_queue() from
206    * here */
207 }
208
209 static void log_queue(void attribute((unused)) *v,
210                       struct queue_entry attribute((unused)) *q) {
211   queue_update();
212 }
213
214 static void log_recent_added(void attribute((unused)) *v,
215                              struct queue_entry attribute((unused)) *q) {
216   recent_update();
217 }
218
219 static void log_recent_removed(void attribute((unused)) *v,
220                                const char attribute((unused)) *id) {
221   /* nothing - log_recent_added() will trigger the relevant update */
222 }
223
224 static void log_removed(void attribute((unused)) *v,
225                         const char attribute((unused)) *id,
226                         const char attribute((unused)) *user) {
227   queue_update();
228 }
229
230 static void log_scratched(void attribute((unused)) *v,
231                           const char attribute((unused)) *track,
232                           const char attribute((unused)) *user) {
233   playing = 0;
234   playing_update();
235   control_update();
236 }
237
238 static void log_state(void attribute((unused)) *v,
239                       unsigned long state) {
240   last_state = state;
241   control_update();
242   /* If the track is paused or resume then the currently playing track is
243    * refetched so that we can continue to correctly calculate the played so-far
244    * field */
245   playing_update();
246 }
247
248 static void log_volume(void attribute((unused)) *v,
249                        int l, int r) {
250   if(volume_l != l || volume_r != r) {
251     volume_l = l;
252     volume_r = r;
253     control_update();
254   }
255 }
256
257 #if MDEBUG
258 static int widget_count, container_count;
259
260 static void count_callback(GtkWidget *w,
261                            gpointer attribute((unused)) data) {
262   ++widget_count;
263   if(GTK_IS_CONTAINER(w)) {
264     ++container_count;
265     gtk_container_foreach(GTK_CONTAINER(w), count_callback, 0);
266   }
267 }
268
269 static void count_widgets(void) {
270   widget_count = 0;
271   container_count = 1;
272   if(toplevel)
273     gtk_container_foreach(GTK_CONTAINER(toplevel), count_callback, 0);
274   fprintf(stderr, "widget count: %8d  container count: %8d\n",
275           widget_count, container_count);
276 }
277 #endif
278
279 #if MTRACK
280 const char *mtag = "init";
281 static hash *mtrack_hash;
282
283 static int *mthfind(const char *tag) {
284   static const int zero = 0;
285   int *cp = hash_find(mtrack_hash, tag);
286   if(!cp) {
287     hash_add(mtrack_hash, tag, &zero, HASH_INSERT);
288     cp = hash_find(mtrack_hash, tag);
289   }
290   return cp;
291 }
292
293 static void *trap_malloc(size_t n) {
294   void *ptr = malloc(n + sizeof(char *));
295
296   *(const char **)ptr = mtag;
297   ++*mthfind(mtag);
298   return (char *)ptr + sizeof(char *);
299 }
300
301 static void trap_free(void *ptr) {
302   const char *tag;
303   if(!ptr)
304     return;
305   ptr = (char *)ptr - sizeof(char *);
306   tag = *(const char **)ptr;
307   --*mthfind(tag);
308   free(ptr);
309 }
310
311 static void *trap_realloc(void *ptr, size_t n) {
312   if(!ptr)
313     return trap_malloc(n);
314   if(!n) {
315     trap_free(ptr);
316     return 0;
317   }
318   ptr = (char *)ptr - sizeof(char *);
319   ptr = realloc(ptr, n + sizeof(char *));
320   *(const char **)ptr = mtag;
321   return (char *)ptr + sizeof(char *);
322 }
323
324 static int report_tags_callback(const char *key, void *value,
325                                 void attribute((unused)) *u) {
326   fprintf(stderr, "%16s: %d\n", key, *(int *)value);
327   return 0;
328 }
329
330 static void report_tags(void) {
331   hash_foreach(mtrack_hash, report_tags_callback, 0);
332   fprintf(stderr, "\n");
333 }
334
335 static const GMemVTable glib_memvtable = {
336   trap_malloc,
337   trap_realloc,
338   trap_free,
339   0,
340   0,
341   0
342 };
343 #endif
344
345 /* Called once every 10 minutes */
346 static gboolean periodic(gpointer attribute((unused)) data) {
347   D(("periodic"));
348   /* Expire cached data */
349   cache_expire();
350   /* Update everything to be sure that the connection to the server hasn't
351    * mysteriously gone stale on us. */
352   all_update();
353 #if MDEBUG
354   count_widgets();
355   fprintf(stderr, "cache size: %zu\n", cache_count());
356 #endif
357 #if MTRACK
358   report_tags();
359 #endif
360   return TRUE;                          /* don't remove me */
361 }
362
363 static gboolean heartbeat(gpointer attribute((unused)) data) {
364   static struct timeval last;
365   struct timeval now;
366   double delta;
367
368   xgettimeofday(&now, 0);
369   if(last.tv_sec) {
370     delta = (now.tv_sec + now.tv_sec / 1.0E6) 
371       - (last.tv_sec + last.tv_sec / 1.0E6);
372     if(delta >= 1.0625)
373       fprintf(stderr, "%f: %fs between 1s heartbeats\n", 
374               now.tv_sec + now.tv_sec / 1.0E6,
375               delta);
376   }
377   last = now;
378   return TRUE;
379 }
380
381 /** @brief Called when a NOP completes */
382 static void nop_completed(void attribute((unused)) *v) {
383   nop_in_flight = 0;
384 }
385
386 /** @brief Called from time to time to arrange for a NOP to be sent
387  *
388  * At most one NOP remains in flight at any moment.  If the client is not
389  * currently connected then no NOP is sent.
390  */
391 static gboolean maybe_send_nop(gpointer attribute((unused)) data) {
392   if(!nop_in_flight && disorder_eclient_connected(client)) {
393     nop_in_flight = 1;
394     disorder_eclient_nop(client, nop_completed, 0);
395   }
396   return TRUE;                          /* keep call me please */
397 }
398
399 /* main -------------------------------------------------------------------- */
400
401 static const struct option options[] = {
402   { "help", no_argument, 0, 'h' },
403   { "version", no_argument, 0, 'V' },
404   { "config", required_argument, 0, 'c' },
405   { "tufnel", no_argument, 0, 't' },
406   { "choosealpha", no_argument, 0, 'C' },
407   { "debug", no_argument, 0, 'd' },
408   { 0, 0, 0, 0 }
409 };
410
411 /* display usage message and terminate */
412 static void help(void) {
413   xprintf("Disobedience - GUI client for DisOrder\n"
414           "\n"
415           "Usage:\n"
416           "  disobedience [OPTIONS]\n"
417           "Options:\n"
418           "  --help, -h              Display usage message\n"
419           "  --version, -V           Display version number\n"
420           "  --config PATH, -c PATH  Set configuration file\n"
421           "  --debug, -d             Turn on debugging\n"
422           "\n"
423           "Also GTK+ options will work.\n");
424   xfclose(stdout);
425   exit(0);
426 }
427
428 /* display version number and terminate */
429 static void version(void) {
430   xprintf("disorder version %s\n", disorder_version_string);
431   xfclose(stdout);
432   exit(0);
433 }
434
435 int main(int argc, char **argv) {
436   int n;
437   disorder_eclient *logclient;
438
439   mem_init();
440   /* garbage-collect PCRE's memory */
441   pcre_malloc = xmalloc;
442   pcre_free = xfree;
443 #if MTRACK
444   mtrack_hash = hash_new(sizeof (int));
445   g_mem_set_vtable((GMemVTable *)&glib_memvtable);
446 #endif
447   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
448   gtk_init(&argc, &argv);
449   gtk_rc_parse_string(style);
450   while((n = getopt_long(argc, argv, "hVc:dtH", options, 0)) >= 0) {
451     switch(n) {
452     case 'h': help();
453     case 'V': version();
454     case 'c': configfile = optarg; break;
455     case 'd': debugging = 1; break;
456     case 't': goesupto = 11; break;
457     case 'C': choosealpha = 1; break;   /* not well tested any more */
458     default: fatal(0, "invalid option");
459     }
460   }
461   signal(SIGPIPE, SIG_IGN);
462   /* create the event loop */
463   D(("create main loop"));
464   mainloop = g_main_loop_new(0, 0);
465   if(config_read()) fatal(0, "cannot read configuration");
466   /* create the clients */
467   if(!(client = gtkclient())
468      || !(logclient = gtkclient()))
469     return 1;                           /* already reported an error */
470   disorder_eclient_log(logclient, &gdisorder_log_callbacks, 0);
471   /* periodic operations (e.g. expiring the cache) */
472 #if MDEBUG || MTRACK
473   g_timeout_add(5000/*milliseconds*/, periodic, 0);
474 #else
475   g_timeout_add(600000/*milliseconds*/, periodic, 0);
476 #endif
477   /* The point of this is to try and get a handle on mysterious
478    * unresponsiveness.  It's not very useful in production use. */
479   if(0)
480     g_timeout_add(1000/*milliseconds*/, heartbeat, 0);
481   make_toplevel_window();
482   /* reset styles now everything has its name */
483   gtk_rc_reset_styles(gtk_settings_get_for_screen(gdk_screen_get_default()));
484   gtk_widget_show_all(toplevel);
485   /* set initial control button visibility/usability */
486   control_update();
487   /* issue a NOP every so often */
488   g_timeout_add_full(G_PRIORITY_LOW,
489                      1000/*interval, ms*/,
490                      maybe_send_nop,
491                      0/*data*/,
492                      0/*notify*/);
493   D(("enter main loop"));
494   MTAG("misc");
495   g_main_loop_run(mainloop);
496   return 0;
497 }
498
499 /*
500 Local Variables:
501 c-basic-offset:2
502 comment-column:40
503 fill-column:79
504 indent-tabs-mode:nil
505 End:
506 */