Code

callbacks: add "connected" and "failed" callback
[ncmpc.git] / src / main.c
1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2017 The Music Player Daemon Project
3  * Project homepage: http://musicpd.org
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,
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 along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
20 #include "config.h"
21 #include "ncmpc.h"
22 #include "mpdclient.h"
23 #include "callbacks.h"
24 #include "charset.h"
25 #include "options.h"
26 #include "command.h"
27 #include "ncu.h"
28 #include "screen.h"
29 #include "screen_utils.h"
30 #include "screen_status.h"
31 #include "strfsong.h"
32 #include "i18n.h"
33 #include "player_command.h"
35 #ifndef NCMPC_MINI
36 #include "conf.h"
37 #endif
39 #ifdef ENABLE_LYRICS_SCREEN
40 #include "lyrics.h"
41 #endif
43 #ifdef ENABLE_LIRC
44 #include "lirc.h"
45 #endif
47 #include <mpd/client.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <signal.h>
53 #include <string.h>
55 #ifdef ENABLE_LOCALE
56 #include <locale.h>
57 #endif
59 /* time between mpd updates [ms] */
60 static const guint update_interval = 500;
62 #define BUFSIZE 1024
64 static struct mpdclient *mpd = NULL;
65 static GMainLoop *main_loop;
66 static guint reconnect_source_id, update_source_id;
67 static int sigwinch_pipes[2];
69 #ifndef NCMPC_MINI
70 static guint check_key_bindings_source_id;
71 #endif
73 #ifndef NCMPC_MINI
74 static void
75 update_xterm_title(void)
76 {
77         const struct mpd_song *song = mpd->song;
79         char tmp[BUFSIZE];
80         if (options.xterm_title_format && mpd->playing && song)
81                 strfsong(tmp, BUFSIZE, options.xterm_title_format, song);
82         else
83                 g_strlcpy(tmp, PACKAGE " version " VERSION, BUFSIZE);
85         static char title[BUFSIZE];
86         if (strncmp(title, tmp, BUFSIZE)) {
87                 g_strlcpy(title, tmp, BUFSIZE);
88                 set_xterm_title("%s", title);
89         }
90 }
91 #endif
93 static void
94 exit_and_cleanup(void)
95 {
96         screen_exit();
97 #ifndef NCMPC_MINI
98         set_xterm_title("");
99 #endif
100         printf("\n");
102         mpdclient_free(mpd);
105 #ifndef WIN32
106 static void
107 catch_sigint(gcc_unused int sig)
109         g_main_loop_quit(main_loop);
113 static void
114 catch_sigcont(gcc_unused int sig)
116         char irrelevant = 'a';
117         if (1 != write(sigwinch_pipes[1], &irrelevant, 1))
118                 exit(EXIT_FAILURE);
121 void
122 sigstop(void)
124         def_prog_mode();  /* save the tty modes */
125         endwin();         /* end curses mode temporarily */
126         kill(0, SIGSTOP); /* issue SIGSTOP */
129 static gboolean
130 sigwinch_event(gcc_unused GIOChannel *source,
131                gcc_unused GIOCondition condition, gcc_unused gpointer data)
133         char ignoreme[64];
134         if (1 > read(sigwinch_pipes[0], ignoreme, 64))
135                 exit(EXIT_FAILURE);
137         endwin();
138         refresh();
139         screen_resize(mpd);
141         return TRUE;
144 static void
145 catch_sigwinch(gcc_unused int sig)
147         if (1 != write(sigwinch_pipes[1], "", 1))
148                 exit(EXIT_FAILURE);
150 #endif /* WIN32 */
152 static gboolean
153 timer_mpd_update(gpointer data);
155 static void
156 enable_update_timer(void)
158         if (update_source_id != 0)
159                 return;
161         update_source_id = g_timeout_add(update_interval,
162                                          timer_mpd_update, NULL);
165 static void
166 disable_update_timer(void)
168         if (update_source_id == 0)
169                 return;
171         g_source_remove(update_source_id);
172         update_source_id = 0;
175 static bool
176 should_enable_update_timer(void)
178         return mpd->playing
179 #ifndef NCMPC_MINI
180                 || options.display_time
181 #endif
182                 ;
185 static void
186 auto_update_timer(void)
188         if (should_enable_update_timer())
189                 enable_update_timer();
190         else
191                 disable_update_timer();
194 static void
195 check_reconnect(void);
197 static void
198 do_mpd_update(void)
200         if (mpdclient_is_connected(mpd) &&
201             (mpd->events != 0 || mpd->playing))
202                 mpdclient_update(mpd);
204 #ifndef NCMPC_MINI
205         if (options.enable_xterm_title)
206                 update_xterm_title();
207 #endif
209         screen_update(mpd);
210         mpd->events = 0;
212         mpdclient_put_connection(mpd);
213         check_reconnect();
216 static char *
217 settings_name(const struct mpd_settings *settings)
219         const char *host = mpd_settings_get_host(settings);
220         if (host == NULL)
221                 host = _("unknown");
223         if (host[0] == '/')
224                 return g_strdup(host);
226         unsigned port = mpd_settings_get_port(settings);
227         if (port == 0 || port == 6600)
228                 return g_strdup(host);
230         return g_strdup_printf("%s:%u", host, port);
233 static char *
234 default_settings_name(void)
236         struct mpd_settings *settings =
237                 mpd_settings_new(options.host, options.port, 0,
238                                  NULL, options.password);
239         if (settings == NULL)
240                 return g_strdup(_("unknown"));
242         char *name = settings_name(settings);
243         mpd_settings_free(settings);
245         return name;
248 /**
249  * This timer is installed when the connection to the MPD server is
250  * broken.  It tries to recover by reconnecting periodically.
251  */
252 static gboolean
253 timer_reconnect(gcc_unused gpointer data)
255         assert(mpdclient_is_dead(mpd));
257         reconnect_source_id = 0;
259         char *name = default_settings_name();
260         screen_status_printf(_("Connecting to %s...  [Press %s to abort]"),
261                              name, get_key_names(CMD_QUIT, false));
262         g_free(name);
263         doupdate();
265         mpdclient_disconnect(mpd);
266         mpdclient_connect(mpd, options.host, options.port,
267                           options.timeout_ms,
268                           options.password);
270         return FALSE;
273 static void
274 check_reconnect(void)
276         if (mpdclient_is_dead(mpd) && reconnect_source_id == 0)
277                 /* reconnect when the connection is lost */
278                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
279                                                     NULL);
282 void
283 mpdclient_connected_callback(void)
285         assert(reconnect_source_id == 0);
287 #ifndef NCMPC_MINI
288         /* quit if mpd is pre 0.14 - song id not supported by mpd */
289         struct mpd_connection *connection = mpdclient_get_connection(mpd);
290         if (mpd_connection_cmp_server_version(connection, 0, 16, 0) < 0) {
291                 const unsigned *version =
292                         mpd_connection_get_server_version(connection);
293                 screen_status_printf(_("Error: MPD version %d.%d.%d is too old (%s needed)"),
294                                      version[0], version[1], version[2],
295                                      "0.16.0");
296                 mpdclient_disconnect(mpd);
297                 doupdate();
299                 /* try again after 30 seconds */
300                 reconnect_source_id = g_timeout_add(30000,
301                                                     timer_reconnect, NULL);
302                 return;
303         }
304 #endif
306         screen_status_clear_message();
307         doupdate();
309         /* update immediately */
310         mpd->events = MPD_IDLE_ALL;
312         do_mpd_update();
314         auto_update_timer();
317 void
318 mpdclient_failed_callback(void)
320         assert(reconnect_source_id == 0);
322         /* try again in 5 seconds */
323         reconnect_source_id = g_timeout_add(5000,
324                                             timer_reconnect, NULL);
327 void
328 mpdclient_lost_callback(void)
330         assert(reconnect_source_id == 0);
332         screen_update(mpd);
334         reconnect_source_id = g_timeout_add(1000, timer_reconnect, NULL);
337 /**
338  * This function is called by the gidle.c library when MPD sends us an
339  * idle event (or when the connection dies).
340  */
341 void
342 mpdclient_idle_callback(gcc_unused enum mpd_idle events)
344 #ifndef NCMPC_MINI
345         if (options.enable_xterm_title)
346                 update_xterm_title();
347 #endif
349         screen_update(mpd);
350         auto_update_timer();
353 static gboolean
354 timer_mpd_update(gcc_unused gpointer data)
356         do_mpd_update();
358         if (should_enable_update_timer())
359                 return true;
360         else {
361                 update_source_id = 0;
362                 return false;
363         }
366 void begin_input_event(void)
370 void end_input_event(void)
372         screen_update(mpd);
373         mpd->events = 0;
375         mpdclient_put_connection(mpd);
376         check_reconnect();
377         auto_update_timer();
380 int do_input_event(command_t cmd)
382         if (cmd == CMD_QUIT) {
383                 g_main_loop_quit(main_loop);
384                 return -1;
385         }
387         screen_cmd(mpd, cmd);
389         if (cmd == CMD_VOLUME_UP || cmd == CMD_VOLUME_DOWN)
390                 /* make sure we don't update the volume yet */
391                 disable_update_timer();
393         return 0;
396 static gboolean
397 keyboard_event(gcc_unused GIOChannel *source,
398                gcc_unused GIOCondition condition,
399                gcc_unused gpointer data)
401         begin_input_event();
403         command_t cmd = get_keyboard_command();
404         if (cmd != CMD_NONE)
405                 if (do_input_event(cmd) != 0)
406                         return FALSE;
408         end_input_event();
409         return TRUE;
412 #ifndef NCMPC_MINI
413 /**
414  * Check the configured key bindings for errors, and display a status
415  * message every 10 seconds.
416  */
417 static gboolean
418 timer_check_key_bindings(gcc_unused gpointer data)
420         char buf[256];
422         if (check_key_bindings(NULL, buf, sizeof(buf))) {
423                 /* no error: disable this timer for the rest of this
424                    process */
425                 check_key_bindings_source_id = 0;
426                 return FALSE;
427         }
429 #ifdef ENABLE_KEYDEF_SCREEN
430         g_strchomp(buf);
431         g_strlcat(buf, " (", sizeof(buf));
432         /* to translators: a key was bound twice in the key editor,
433            and this is a hint for the user what to press to correct
434            that */
435         char comment[64];
436         g_snprintf(comment, sizeof(comment), _("press %s for the key editor"),
437                    get_key_names(CMD_SCREEN_KEYDEF, false));
438         g_strlcat(buf, comment, sizeof(buf));
439         g_strlcat(buf, ")", sizeof(buf));
440 #endif
442         screen_status_printf("%s", buf);
444         doupdate();
445         return TRUE;
447 #endif
449 int
450 main(int argc, const char *argv[])
452 #ifdef ENABLE_LOCALE
453 #ifndef ENABLE_NLS
454         gcc_unused
455 #endif
456         const char *charset = NULL;
457         /* time and date formatting */
458         setlocale(LC_TIME,"");
459         /* care about sorting order etc */
460         setlocale(LC_COLLATE,"");
461         /* charset */
462         setlocale(LC_CTYPE,"");
463         /* initialize charset conversions */
464         charset = charset_init();
466         /* initialize i18n support */
467 #endif
469 #ifdef ENABLE_NLS
470         setlocale(LC_MESSAGES, "");
471         bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
472 #ifdef ENABLE_LOCALE
473         bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
474 #endif
475         textdomain(GETTEXT_PACKAGE);
476 #endif
478         /* initialize options */
479         options_init();
481         /* parse command line options - 1 pass get configuration files */
482         options_parse(argc, argv);
484 #ifndef NCMPC_MINI
485         /* read configuration */
486         read_configuration();
488         /* check key bindings */
489         check_key_bindings(NULL, NULL, 0);
490 #endif
492         /* parse command line options - 2 pass */
493         options_parse(argc, argv);
495 #ifndef WIN32
496         /* setup signal behavior - SIGINT */
497         struct sigaction act;
498         sigemptyset(&act.sa_mask);
499         act.sa_flags = 0;
500         act.sa_handler = catch_sigint;
501         if (sigaction(SIGINT, &act, NULL) < 0) {
502                 perror("signal");
503                 exit(EXIT_FAILURE);
504         }
506         /* setup signal behavior - SIGTERM */
508         act.sa_handler = catch_sigint;
509         if (sigaction(SIGTERM, &act, NULL) < 0) {
510                 perror("sigaction()");
511                 exit(EXIT_FAILURE);
512         }
514         /* setup signal behavior - SIGCONT */
516         act.sa_handler = catch_sigcont;
517         if (sigaction(SIGCONT, &act, NULL) < 0) {
518                 perror("sigaction(SIGCONT)");
519                 exit(EXIT_FAILURE);
520         }
522         /* setup signal behaviour - SIGHUP*/
524         act.sa_handler = catch_sigint;
525         if (sigaction(SIGHUP, &act, NULL) < 0) {
526                 perror("sigaction(SIGHUP)");
527                 exit(EXIT_FAILURE);
528         }
530         /* setup SIGWINCH */
532         act.sa_flags = SA_RESTART;
533         act.sa_handler = catch_sigwinch;
534         if (sigaction(SIGWINCH, &act, NULL) < 0) {
535                 perror("sigaction(SIGWINCH)");
536                 exit(EXIT_FAILURE);
537         }
539         /* ignore SIGPIPE */
541         act.sa_handler = SIG_IGN;
542         if (sigaction(SIGPIPE, &act, NULL) < 0) {
543                 perror("sigaction(SIGPIPE)");
544                 exit(EXIT_FAILURE);
545         }
546 #endif
548         ncu_init();
550 #ifdef ENABLE_LYRICS_SCREEN
551         lyrics_init();
552 #endif
554         /* create mpdclient instance */
555         mpd = mpdclient_new();
557         /* initialize curses */
558         screen_init(mpd);
560         /* the main loop */
561         main_loop = g_main_loop_new(NULL, FALSE);
563         /* watch out for keyboard input */
564         GIOChannel *keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
565         g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);
567 #ifdef ENABLE_LIRC
568         /* watch out for lirc input */
569         int lirc_socket = ncmpc_lirc_open();
570         GIOChannel *lirc_channel = NULL;
571         if (lirc_socket >= 0) {
572                 lirc_channel = g_io_channel_unix_new(lirc_socket);
573                 g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
574         }
575 #endif
577 #ifndef WIN32
578         GIOChannel *sigwinch_channel = NULL;
579         if (!pipe(sigwinch_pipes) &&
580                 !fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
581                 sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
582                 g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
583         }
584         else {
585                 perror("sigwinch pipe creation failed");
586                 exit(EXIT_FAILURE);
587         }
588 #endif
590         /* attempt to connect */
591         reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);
593         auto_update_timer();
595 #ifndef NCMPC_MINI
596         check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
597 #endif
599         screen_paint(mpd);
601         g_main_loop_run(main_loop);
603         /* cleanup */
605         cancel_seek_timer();
607         disable_update_timer();
609         if (reconnect_source_id != 0)
610                 g_source_remove(reconnect_source_id);
612 #ifndef NCMPC_MINI
613         if (check_key_bindings_source_id != 0)
614                 g_source_remove(check_key_bindings_source_id);
615 #endif
617         g_main_loop_unref(main_loop);
618         g_io_channel_unref(keyboard_channel);
619         g_io_channel_unref(sigwinch_channel);
620         close(sigwinch_pipes[0]);
621         close(sigwinch_pipes[1]);
623 #ifdef ENABLE_LIRC
624         if (lirc_socket >= 0)
625                 g_io_channel_unref(lirc_channel);
626         ncmpc_lirc_close();
627 #endif
629         exit_and_cleanup();
631 #ifdef ENABLE_LYRICS_SCREEN
632         lyrics_deinit();
633 #endif
635         ncu_deinit();
636         options_deinit();
638         return 0;