chiark / gitweb /
Move RTP check. This seems to improve matters - formerly the RTP
[disorder] / disobedience / disobedience.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2006, 2007, 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/disobedience.c
21  * @brief Main Disobedience program
22  */
23
24 #include "disobedience.h"
25 #include "mixer.h"
26 #include "version.h"
27
28 #include <getopt.h>
29 #include <locale.h>
30 #include <pcre.h>
31
32 /* Apologies for the numerous de-consting casts, but GLib et al do not seem to
33  * have heard of const. */
34
35 /* Variables --------------------------------------------------------------- */
36
37 /** @brief Event loop */
38 GMainLoop *mainloop;
39
40 /** @brief Top-level window */
41 GtkWidget *toplevel;
42
43 /** @brief Label for progress indicator */
44 GtkWidget *report_label;
45
46 /** @brief Main tab group */
47 GtkWidget *tabs;
48
49 /** @brief Main client */
50 disorder_eclient *client;
51
52 /** @brief Log client */
53 disorder_eclient *logclient;
54
55 /** @brief Last reported state
56  *
57  * This is updated by log_state().
58  */
59 unsigned long last_state;
60
61 /** @brief True if some track is playing
62  *
63  * This ought to be removed in favour of last_state & DISORDER_PLAYING
64  */
65 int playing;
66
67 /** @brief Left channel volume */
68 int volume_l;
69
70 /** @brief Right channel volume */
71 int volume_r;
72
73 double goesupto = 10;                   /* volume upper bound */
74
75 /** @brief True if a NOP is in flight */
76 static int nop_in_flight;
77
78 /** @brief True if an rtp-address command is in flight */
79 static int rtp_address_in_flight;
80
81 /** @brief True if a rights lookup is in flight */
82 static int rights_lookup_in_flight;
83
84 /** @brief Current rights bitmap */
85 rights_type last_rights;
86
87 /** @brief Global tooltip group */
88 GtkTooltips *tips;
89
90 /** @brief True if RTP play is available
91  *
92  * This is a bit of a bodge...
93  */
94 int rtp_supported;
95
96 /** @brief True if RTP play is enabled */
97 int rtp_is_running;
98
99 static void check_rtp_address(void);
100
101 /* Window creation --------------------------------------------------------- */
102
103 /* Note that all the client operations kicked off from here will only complete
104  * after we've entered the event loop. */
105
106 /** @brief Called when main window is deleted
107  *
108  * Terminates the program.
109  */
110 static gboolean delete_event(GtkWidget attribute((unused)) *widget,
111                              GdkEvent attribute((unused)) *event,
112                              gpointer attribute((unused)) data) {
113   D(("delete_event"));
114   exit(0);                              /* die immediately */
115 }
116
117 /** @brief Called when the current tab is switched
118  *
119  * Updates the menu settings to correspond to the new page.
120  */
121 static void tab_switched(GtkNotebook *notebook,
122                          GtkNotebookPage attribute((unused)) *page,
123                          guint page_num,
124                          gpointer attribute((unused)) user_data) {
125   menu_update(page_num);
126   GtkWidget *const tab = gtk_notebook_get_nth_page(notebook, page_num);
127   const struct tabtype *const t = g_object_get_data(G_OBJECT(tab), "type");
128   if(t->selected)
129     t->selected();
130 }
131
132 /** @brief Create the report box */
133 static GtkWidget *report_box(void) {
134   GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
135
136   report_label = gtk_label_new("");
137   gtk_label_set_ellipsize(GTK_LABEL(report_label), PANGO_ELLIPSIZE_END);
138   gtk_misc_set_alignment(GTK_MISC(report_label), 0, 0);
139   gtk_container_add(GTK_CONTAINER(vbox), gtk_hseparator_new());
140   gtk_container_add(GTK_CONTAINER(vbox), report_label);
141   return vbox;
142 }
143
144 /** @brief Create and populate the main tab group */
145 static GtkWidget *notebook(void) {
146   tabs = gtk_notebook_new();
147   /* The current tab is _NORMAL, the rest are _ACTIVE, which is bizarre but
148    * produces not too dreadful appearance */
149   gtk_widget_set_style(tabs, tool_style);
150   g_signal_connect(tabs, "switch-page", G_CALLBACK(tab_switched), 0);
151   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), queue_widget(),
152                            gtk_label_new("Queue"));
153   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), recent_widget(),
154                            gtk_label_new("Recent"));
155   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), choose_widget(),
156                            gtk_label_new("Choose"));
157   gtk_notebook_append_page(GTK_NOTEBOOK(tabs), added_widget(),
158                            gtk_label_new("Added"));
159   return tabs;
160 }
161
162 /** @brief Create and populate the main window */
163 static void make_toplevel_window(void) {
164   GtkWidget *const vbox = gtk_vbox_new(FALSE, 1);
165   GtkWidget *const rb = report_box();
166
167   D(("top_window"));
168   toplevel = gtk_window_new(GTK_WINDOW_TOPLEVEL);
169   /* default size is too small */
170   gtk_window_set_default_size(GTK_WINDOW(toplevel), 640, 480);
171   /* terminate on close */
172   g_signal_connect(G_OBJECT(toplevel), "delete_event",
173                    G_CALLBACK(delete_event), NULL);
174   /* lay out the window */
175   gtk_window_set_title(GTK_WINDOW(toplevel), "Disobedience");
176   gtk_container_add(GTK_CONTAINER(toplevel), vbox);
177   /* lay out the vbox */
178   gtk_box_pack_start(GTK_BOX(vbox),
179                      menubar(toplevel),
180                      FALSE,             /* expand */
181                      FALSE,             /* fill */
182                      0);
183   gtk_box_pack_start(GTK_BOX(vbox),
184                      control_widget(),
185                      FALSE,             /* expand */
186                      FALSE,             /* fill */
187                      0);
188   gtk_container_add(GTK_CONTAINER(vbox), notebook());
189   gtk_box_pack_end(GTK_BOX(vbox),
190                    rb,
191                    FALSE,             /* expand */
192                    FALSE,             /* fill */
193                    0);
194   gtk_widget_set_style(toplevel, tool_style);
195 }
196
197 #if MDEBUG
198 static int widget_count, container_count;
199
200 static void count_callback(GtkWidget *w,
201                            gpointer attribute((unused)) data) {
202   ++widget_count;
203   if(GTK_IS_CONTAINER(w)) {
204     ++container_count;
205     gtk_container_foreach(GTK_CONTAINER(w), count_callback, 0);
206   }
207 }
208
209 static void count_widgets(void) {
210   widget_count = 0;
211   container_count = 1;
212   if(toplevel)
213     gtk_container_foreach(GTK_CONTAINER(toplevel), count_callback, 0);
214   fprintf(stderr, "widget count: %8d  container count: %8d\n",
215           widget_count, container_count);
216 }
217 #endif
218
219 #if MTRACK
220 const char *mtag = "init";
221 static hash *mtrack_hash;
222
223 static int *mthfind(const char *tag) {
224   static const int zero = 0;
225   int *cp = hash_find(mtrack_hash, tag);
226   if(!cp) {
227     hash_add(mtrack_hash, tag, &zero, HASH_INSERT);
228     cp = hash_find(mtrack_hash, tag);
229   }
230   return cp;
231 }
232
233 static void *trap_malloc(size_t n) {
234   void *ptr = malloc(n + sizeof(char *));
235
236   *(const char **)ptr = mtag;
237   ++*mthfind(mtag);
238   return (char *)ptr + sizeof(char *);
239 }
240
241 static void trap_free(void *ptr) {
242   const char *tag;
243   if(!ptr)
244     return;
245   ptr = (char *)ptr - sizeof(char *);
246   tag = *(const char **)ptr;
247   --*mthfind(tag);
248   free(ptr);
249 }
250
251 static void *trap_realloc(void *ptr, size_t n) {
252   if(!ptr)
253     return trap_malloc(n);
254   if(!n) {
255     trap_free(ptr);
256     return 0;
257   }
258   ptr = (char *)ptr - sizeof(char *);
259   ptr = realloc(ptr, n + sizeof(char *));
260   *(const char **)ptr = mtag;
261   return (char *)ptr + sizeof(char *);
262 }
263
264 static int report_tags_callback(const char *key, void *value,
265                                 void attribute((unused)) *u) {
266   fprintf(stderr, "%16s: %d\n", key, *(int *)value);
267   return 0;
268 }
269
270 static void report_tags(void) {
271   hash_foreach(mtrack_hash, report_tags_callback, 0);
272   fprintf(stderr, "\n");
273 }
274
275 static const GMemVTable glib_memvtable = {
276   trap_malloc,
277   trap_realloc,
278   trap_free,
279   0,
280   0,
281   0
282 };
283 #endif
284
285 static void userinfo_rights_completed(void attribute((unused)) *v,
286                                       const char *error,
287                                       const char *value) {
288   rights_type r;
289
290   if(error) {
291     popup_protocol_error(0, error);
292     r = 0;
293   } else {
294     if(parse_rights(value, &r, 0))
295       r = 0;
296   }
297   /* If rights have changed, signal everything that cares */
298   if(r != last_rights) {
299     last_rights = r;
300     ++suppress_actions;
301     event_raise("rights-changed", 0);
302     --suppress_actions;
303   }
304   rights_lookup_in_flight = 0;
305 }
306
307 /** @brief Called occasionally */
308 static gboolean periodic_slow(gpointer attribute((unused)) data) {
309   D(("periodic_slow"));
310   /* Expire cached data */
311   cache_expire();
312   /* Update everything to be sure that the connection to the server hasn't
313    * mysteriously gone stale on us. */
314   all_update();
315 #if MDEBUG
316   count_widgets();
317   fprintf(stderr, "cache size: %zu\n", cache_count());
318 #endif
319 #if MTRACK
320   report_tags();
321 #endif
322   /* Periodically check what our rights are */
323   if(!rights_lookup_in_flight) {
324     rights_lookup_in_flight = 1;
325     disorder_eclient_userinfo(client,
326                               userinfo_rights_completed,
327                               config->username, "rights",
328                               0);
329   }
330   /* Recheck RTP status too */
331   check_rtp_address();
332   return TRUE;                          /* don't remove me */
333 }
334
335 /** @brief Called frequently */
336 static gboolean periodic_fast(gpointer attribute((unused)) data) {
337 #if 0                                   /* debugging hack */
338   static struct timeval last;
339   struct timeval now;
340   double delta;
341
342   xgettimeofday(&now, 0);
343   if(last.tv_sec) {
344     delta = (now.tv_sec + now.tv_sec / 1.0E6) 
345       - (last.tv_sec + last.tv_sec / 1.0E6);
346     if(delta >= 1.0625)
347       fprintf(stderr, "%f: %fs between 1s heartbeats\n", 
348               now.tv_sec + now.tv_sec / 1.0E6,
349               delta);
350   }
351   last = now;
352 #endif
353   if(rtp_supported && mixer_supported(DEFAULT_BACKEND)) {
354     int nl, nr;
355     if(!mixer_control(DEFAULT_BACKEND, &nl, &nr, 0)
356        && (nl != volume_l || nr != volume_r)) {
357       volume_l = nl;
358       volume_r = nr;
359       event_raise("volume-changed", 0);
360     }
361   }
362   return TRUE;
363 }
364
365 /** @brief Called when a NOP completes */
366 static void nop_completed(void attribute((unused)) *v,
367                           const char attribute((unused)) *error) {
368   /* TODO report the error somewhere */
369   nop_in_flight = 0;
370 }
371
372 /** @brief Called from time to time to arrange for a NOP to be sent
373  *
374  * At most one NOP remains in flight at any moment.  If the client is not
375  * currently connected then no NOP is sent.
376  */
377 static gboolean maybe_send_nop(gpointer attribute((unused)) data) {
378   if(!nop_in_flight && (disorder_eclient_state(client) & DISORDER_CONNECTED)) {
379     nop_in_flight = 1;
380     disorder_eclient_nop(client, nop_completed, 0);
381   }
382   if(rtp_supported) {
383     const int rtp_was_running = rtp_is_running;
384     rtp_is_running = rtp_running();
385     if(rtp_was_running != rtp_is_running)
386       event_raise("rtp-changed", 0);
387   }
388   return TRUE;                          /* keep call me please */
389 }
390
391 /** @brief Called when a rtp-address command succeeds */
392 static void got_rtp_address(void attribute((unused)) *v,
393                             const char *error,
394                             int attribute((unused)) nvec,
395                             char attribute((unused)) **vec) {
396   const int rtp_was_supported = rtp_supported;
397   const int rtp_was_running = rtp_is_running;
398
399   ++suppress_actions;
400   rtp_address_in_flight = 0;
401   if(error) {
402     /* An error just means that we're not using network play */
403     rtp_supported = 0;
404     rtp_is_running = 0;
405   } else {
406     rtp_supported = 1;
407     rtp_is_running = rtp_running();
408   }
409   if(rtp_supported != rtp_was_supported
410      || rtp_is_running != rtp_was_running)
411     event_raise("rtp-changed", 0);
412   --suppress_actions;
413 }
414
415 /** @brief Called to check whether RTP play is available */
416 static void check_rtp_address(void) {
417   if(!rtp_address_in_flight)
418     disorder_eclient_rtp_address(client, got_rtp_address, NULL);
419 }
420
421 /* main -------------------------------------------------------------------- */
422
423 static const struct option options[] = {
424   { "help", no_argument, 0, 'h' },
425   { "version", no_argument, 0, 'V' },
426   { "config", required_argument, 0, 'c' },
427   { "tufnel", no_argument, 0, 't' },
428   { "debug", no_argument, 0, 'd' },
429   { 0, 0, 0, 0 }
430 };
431
432 /* display usage message and terminate */
433 static void help(void) {
434   xprintf("Disobedience - GUI client for DisOrder\n"
435           "\n"
436           "Usage:\n"
437           "  disobedience [OPTIONS]\n"
438           "Options:\n"
439           "  --help, -h              Display usage message\n"
440           "  --version, -V           Display version number\n"
441           "  --config PATH, -c PATH  Set configuration file\n"
442           "  --debug, -d             Turn on debugging\n"
443           "\n"
444           "Also GTK+ options will work.\n");
445   xfclose(stdout);
446   exit(0);
447 }
448
449 void logged_in(void) {
450   /* reset the clients */
451   disorder_eclient_close(client);
452   disorder_eclient_close(logclient);
453   rtp_supported = 0;
454   event_raise("logged-in", 0);
455   /* Force the periodic checks */
456   periodic_slow(0);
457   periodic_fast(0);
458 }
459
460 int main(int argc, char **argv) {
461   int n;
462   gboolean gtkok;
463
464   mem_init();
465   /* garbage-collect PCRE's memory */
466   pcre_malloc = xmalloc;
467   pcre_free = xfree;
468 #if MTRACK
469   mtrack_hash = hash_new(sizeof (int));
470   g_mem_set_vtable((GMemVTable *)&glib_memvtable);
471 #endif
472   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
473   gtkok = gtk_init_check(&argc, &argv);
474   while((n = getopt_long(argc, argv, "hVc:dtHC", options, 0)) >= 0) {
475     switch(n) {
476     case 'h': help();
477     case 'V': version("disobedience");
478     case 'c': configfile = optarg; break;
479     case 'd': debugging = 1; break;
480     case 't': goesupto = 11; break;
481     default: fatal(0, "invalid option");
482     }
483   }
484   if(!gtkok)
485     fatal(0, "failed to initialize GTK+");
486   signal(SIGPIPE, SIG_IGN);
487   init_styles();
488   load_settings();
489   /* create the event loop */
490   D(("create main loop"));
491   mainloop = g_main_loop_new(0, 0);
492   if(config_read(0)) fatal(0, "cannot read configuration");
493   /* create the clients */
494   if(!(client = gtkclient())
495      || !(logclient = gtkclient()))
496     return 1;                           /* already reported an error */
497   /* periodic operations (e.g. expiring the cache, checking local volume) */
498   g_timeout_add(10000/*milliseconds*/, periodic_slow, 0);
499   g_timeout_add(1000/*milliseconds*/, periodic_fast, 0);
500   /* global tooltips */
501   tips = gtk_tooltips_new();
502   make_toplevel_window();
503   /* reset styles now everything has its name */
504   gtk_rc_reset_styles(gtk_settings_get_for_screen(gdk_screen_get_default()));
505   gtk_widget_show_all(toplevel);
506   /* issue a NOP every so often */
507   g_timeout_add_full(G_PRIORITY_LOW,
508                      2000/*interval, ms*/,
509                      maybe_send_nop,
510                      0/*data*/,
511                      0/*notify*/);
512   /* Start monitoring the log */
513   disorder_eclient_log(logclient, &log_callbacks, 0);
514   /* Initiate all the checks */
515   periodic_slow(0);
516   periodic_fast(0);
517   suppress_actions = 0;
518   /* If no password is set yet pop up a login box */
519   if(!config->password)
520     login_box();
521   D(("enter main loop"));
522   MTAG("misc");
523   g_main_loop_run(mainloop);
524   return 0;
525 }
526
527 /*
528 Local Variables:
529 c-basic-offset:2
530 comment-column:40
531 fill-column:79
532 indent-tabs-mode:nil
533 End:
534 */