Code

1459df4baee3bf68c51e29dbfa043f63c83acad7
[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 "gidle.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         struct mpd_status *status = NULL;
78         const struct mpd_song *song = NULL;
79         if (mpd) {
80                 status = mpd->status;
81                 song = mpd->song;
82         }
84         char tmp[BUFSIZE];
85         if (options.xterm_title_format && status && song &&
86             mpd_status_get_state(status) == MPD_STATE_PLAY)
87                 strfsong(tmp, BUFSIZE, options.xterm_title_format, song);
88         else
89                 g_strlcpy(tmp, PACKAGE " version " VERSION, BUFSIZE);
91         static char title[BUFSIZE];
92         if (strncmp(title, tmp, BUFSIZE)) {
93                 g_strlcpy(title, tmp, BUFSIZE);
94                 set_xterm_title("%s", title);
95         }
96 }
97 #endif
99 static void
100 exit_and_cleanup(void)
102         screen_exit();
103 #ifndef NCMPC_MINI
104         set_xterm_title("");
105 #endif
106         printf("\n");
108         if (mpd) {
109                 mpdclient_free(mpd);
110         }
113 #ifndef WIN32
114 static void
115 catch_sigint(gcc_unused int sig)
117         g_main_loop_quit(main_loop);
121 static void
122 catch_sigcont(gcc_unused int sig)
124         char irrelevant = 'a';
125         if (1 != write(sigwinch_pipes[1], &irrelevant, 1))
126                 exit(EXIT_FAILURE);
129 void
130 sigstop(void)
132         def_prog_mode();  /* save the tty modes */
133         endwin();         /* end curses mode temporarily */
134         kill(0, SIGSTOP); /* issue SIGSTOP */
137 static gboolean
138 sigwinch_event(gcc_unused GIOChannel *source,
139                gcc_unused GIOCondition condition, gcc_unused gpointer data)
141         char ignoreme[64];
142         if (1 > read(sigwinch_pipes[0], ignoreme, 64))
143                 exit(EXIT_FAILURE);
145         endwin();
146         refresh();
147         screen_resize(mpd);
149         return TRUE;
152 static void
153 catch_sigwinch(gcc_unused int sig)
155         if (1 != write(sigwinch_pipes[1], "", 1))
156                 exit(EXIT_FAILURE);
158 #endif /* WIN32 */
160 static void
161 idle_callback(enum mpd_error error,
162               gcc_unused enum mpd_server_error server_error,
163               const char *message, enum mpd_idle events,
164               gcc_unused void *ctx);
166 static gboolean
167 timer_mpd_update(gpointer data);
169 static void
170 enable_update_timer(void)
172         if (update_source_id != 0)
173                 return;
175         update_source_id = g_timeout_add(update_interval,
176                                          timer_mpd_update, NULL);
179 static void
180 disable_update_timer(void)
182         if (update_source_id == 0)
183                 return;
185         g_source_remove(update_source_id);
186         update_source_id = 0;
189 static bool
190 should_enable_update_timer(void)
192         return (mpdclient_is_connected(mpd) &&
193                 mpd->status != NULL &&
194                 mpd_status_get_state(mpd->status) == MPD_STATE_PLAY)
195 #ifndef NCMPC_MINI
196                 || options.display_time
197 #endif
198                 ;
201 static void
202 auto_update_timer(void)
204         if (should_enable_update_timer())
205                 enable_update_timer();
206         else
207                 disable_update_timer();
210 static void
211 check_reconnect(void);
213 static void
214 do_mpd_update(void)
216         if (mpdclient_is_connected(mpd) &&
217             (mpd->events != 0 ||
218              (mpd->status != NULL &&
219               mpd_status_get_state(mpd->status) == MPD_STATE_PLAY)))
220                 mpdclient_update(mpd);
222 #ifndef NCMPC_MINI
223         if (options.enable_xterm_title)
224                 update_xterm_title();
225 #endif
227         screen_update(mpd);
228         mpd->events = 0;
230         mpdclient_put_connection(mpd);
231         check_reconnect();
234 static char *
235 settings_name(const struct mpd_settings *settings)
237         const char *host = mpd_settings_get_host(settings);
238         if (host == NULL)
239                 host = _("unknown");
241         if (host[0] == '/')
242                 return g_strdup(host);
244         unsigned port = mpd_settings_get_port(settings);
245         if (port == 0 || port == 6600)
246                 return g_strdup(host);
248         return g_strdup_printf("%s:%u", host, port);
251 static char *
252 default_settings_name(void)
254         struct mpd_settings *settings =
255                 mpd_settings_new(options.host, options.port, 0,
256                                  NULL, options.password);
257         if (settings == NULL)
258                 return g_strdup(_("unknown"));
260         char *name = settings_name(settings);
261         mpd_settings_free(settings);
263         return name;
266 /**
267  * This timer is installed when the connection to the MPD server is
268  * broken.  It tries to recover by reconnecting periodically.
269  */
270 static gboolean
271 timer_reconnect(gcc_unused gpointer data)
273         assert(!mpdclient_is_connected(mpd));
275         reconnect_source_id = 0;
277         char *name = default_settings_name();
278         screen_status_printf(_("Connecting to %s...  [Press %s to abort]"),
279                              name, get_key_names(CMD_QUIT, false));
280         g_free(name);
281         doupdate();
283         mpdclient_disconnect(mpd);
284         if (!mpdclient_connect(mpd, options.host, options.port,
285                                options.timeout_ms,
286                                options.password)) {
287                 /* try again in 5 seconds */
288                 reconnect_source_id = g_timeout_add(5000,
289                                                     timer_reconnect, NULL);
290                 return FALSE;
291         }
293         struct mpd_connection *connection = mpdclient_get_connection(mpd);
295 #ifndef NCMPC_MINI
296         /* quit if mpd is pre 0.14 - song id not supported by mpd */
297         if (mpd_connection_cmp_server_version(connection, 0, 16, 0) < 0) {
298                 const unsigned *version =
299                         mpd_connection_get_server_version(connection);
300                 screen_status_printf(_("Error: MPD version %d.%d.%d is too old (%s needed)"),
301                                      version[0], version[1], version[2],
302                                      "0.16.0");
303                 mpdclient_disconnect(mpd);
304                 doupdate();
306                 /* try again after 30 seconds */
307                 reconnect_source_id = g_timeout_add(30000,
308                                                     timer_reconnect, NULL);
309                 return FALSE;
310         }
311 #endif
313         mpd->source = mpd_glib_new(connection,
314                                    idle_callback, mpd);
316         screen_status_clear_message();
317         doupdate();
319         /* update immediately */
320         mpd->events = MPD_IDLE_ALL;
322         do_mpd_update();
324         auto_update_timer();
326         return FALSE;
329 static void
330 check_reconnect(void)
332         if (!mpdclient_is_connected(mpd) && reconnect_source_id == 0)
333                 /* reconnect when the connection is lost */
334                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
335                                                     NULL);
338 /**
339  * This function is called by the gidle.c library when MPD sends us an
340  * idle event (or when the connection dies).
341  */
342 static void
343 idle_callback(enum mpd_error error,
344               gcc_unused enum mpd_server_error server_error,
345               const char *message, enum mpd_idle events,
346               void *ctx)
348         struct mpdclient *c = ctx;
350         c->idle = false;
352         assert(mpdclient_is_connected(c));
354         if (error != MPD_ERROR_SUCCESS) {
355                 char *allocated;
356                 if (error == MPD_ERROR_SERVER)
357                         message = allocated = utf8_to_locale(message);
358                 else
359                         allocated = NULL;
360                 screen_status_message(message);
361                 g_free(allocated);
362                 screen_bell();
363                 doupdate();
365                 mpdclient_disconnect(c);
366                 screen_update(mpd);
367                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
368                                                     NULL);
369                 return;
370         }
372         c->events |= events;
373         mpdclient_update(c);
375 #ifndef NCMPC_MINI
376         if (options.enable_xterm_title)
377                 update_xterm_title();
378 #endif
380         screen_update(mpd);
381         c->events = 0;
383         mpdclient_put_connection(c);
384         check_reconnect();
385         auto_update_timer();
388 static gboolean
389 timer_mpd_update(gcc_unused gpointer data)
391         do_mpd_update();
393         if (should_enable_update_timer())
394                 return true;
395         else {
396                 update_source_id = 0;
397                 return false;
398         }
401 void begin_input_event(void)
405 void end_input_event(void)
407         screen_update(mpd);
408         mpd->events = 0;
410         mpdclient_put_connection(mpd);
411         check_reconnect();
412         auto_update_timer();
415 int do_input_event(command_t cmd)
417         if (cmd == CMD_QUIT) {
418                 g_main_loop_quit(main_loop);
419                 return -1;
420         }
422         screen_cmd(mpd, cmd);
424         if (cmd == CMD_VOLUME_UP || cmd == CMD_VOLUME_DOWN)
425                 /* make sure we don't update the volume yet */
426                 disable_update_timer();
428         return 0;
431 static gboolean
432 keyboard_event(gcc_unused GIOChannel *source,
433                gcc_unused GIOCondition condition,
434                gcc_unused gpointer data)
436         begin_input_event();
438         command_t cmd = get_keyboard_command();
439         if (cmd != CMD_NONE)
440                 if (do_input_event(cmd) != 0)
441                         return FALSE;
443         end_input_event();
444         return TRUE;
447 #ifndef NCMPC_MINI
448 /**
449  * Check the configured key bindings for errors, and display a status
450  * message every 10 seconds.
451  */
452 static gboolean
453 timer_check_key_bindings(gcc_unused gpointer data)
455         char buf[256];
457         if (check_key_bindings(NULL, buf, sizeof(buf))) {
458                 /* no error: disable this timer for the rest of this
459                    process */
460                 check_key_bindings_source_id = 0;
461                 return FALSE;
462         }
464 #ifdef ENABLE_KEYDEF_SCREEN
465         g_strchomp(buf);
466         g_strlcat(buf, " (", sizeof(buf));
467         /* to translators: a key was bound twice in the key editor,
468            and this is a hint for the user what to press to correct
469            that */
470         char comment[64];
471         g_snprintf(comment, sizeof(comment), _("press %s for the key editor"),
472                    get_key_names(CMD_SCREEN_KEYDEF, false));
473         g_strlcat(buf, comment, sizeof(buf));
474         g_strlcat(buf, ")", sizeof(buf));
475 #endif
477         screen_status_printf("%s", buf);
479         doupdate();
480         return TRUE;
482 #endif
484 int
485 main(int argc, const char *argv[])
487 #ifdef ENABLE_LOCALE
488 #ifndef ENABLE_NLS
489         gcc_unused
490 #endif
491         const char *charset = NULL;
492         /* time and date formatting */
493         setlocale(LC_TIME,"");
494         /* care about sorting order etc */
495         setlocale(LC_COLLATE,"");
496         /* charset */
497         setlocale(LC_CTYPE,"");
498         /* initialize charset conversions */
499         charset = charset_init();
501         /* initialize i18n support */
502 #endif
504 #ifdef ENABLE_NLS
505         setlocale(LC_MESSAGES, "");
506         bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
507 #ifdef ENABLE_LOCALE
508         bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
509 #endif
510         textdomain(GETTEXT_PACKAGE);
511 #endif
513         /* initialize options */
514         options_init();
516         /* parse command line options - 1 pass get configuration files */
517         options_parse(argc, argv);
519 #ifndef NCMPC_MINI
520         /* read configuration */
521         read_configuration();
523         /* check key bindings */
524         check_key_bindings(NULL, NULL, 0);
525 #endif
527         /* parse command line options - 2 pass */
528         options_parse(argc, argv);
530 #ifndef WIN32
531         /* setup signal behavior - SIGINT */
532         struct sigaction act;
533         sigemptyset(&act.sa_mask);
534         act.sa_flags = 0;
535         act.sa_handler = catch_sigint;
536         if (sigaction(SIGINT, &act, NULL) < 0) {
537                 perror("signal");
538                 exit(EXIT_FAILURE);
539         }
541         /* setup signal behavior - SIGTERM */
543         act.sa_handler = catch_sigint;
544         if (sigaction(SIGTERM, &act, NULL) < 0) {
545                 perror("sigaction()");
546                 exit(EXIT_FAILURE);
547         }
549         /* setup signal behavior - SIGCONT */
551         act.sa_handler = catch_sigcont;
552         if (sigaction(SIGCONT, &act, NULL) < 0) {
553                 perror("sigaction(SIGCONT)");
554                 exit(EXIT_FAILURE);
555         }
557         /* setup signal behaviour - SIGHUP*/
559         act.sa_handler = catch_sigint;
560         if (sigaction(SIGHUP, &act, NULL) < 0) {
561                 perror("sigaction(SIGHUP)");
562                 exit(EXIT_FAILURE);
563         }
565         /* setup SIGWINCH */
567         act.sa_flags = SA_RESTART;
568         act.sa_handler = catch_sigwinch;
569         if (sigaction(SIGWINCH, &act, NULL) < 0) {
570                 perror("sigaction(SIGWINCH)");
571                 exit(EXIT_FAILURE);
572         }
574         /* ignore SIGPIPE */
576         act.sa_handler = SIG_IGN;
577         if (sigaction(SIGPIPE, &act, NULL) < 0) {
578                 perror("sigaction(SIGPIPE)");
579                 exit(EXIT_FAILURE);
580         }
581 #endif
583         ncu_init();
585 #ifdef ENABLE_LYRICS_SCREEN
586         lyrics_init();
587 #endif
589         /* create mpdclient instance */
590         mpd = mpdclient_new();
592         /* initialize curses */
593         screen_init(mpd);
595         /* the main loop */
596         main_loop = g_main_loop_new(NULL, FALSE);
598         /* watch out for keyboard input */
599         GIOChannel *keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
600         g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);
602 #ifdef ENABLE_LIRC
603         /* watch out for lirc input */
604         int lirc_socket = ncmpc_lirc_open();
605         GIOChannel *lirc_channel = NULL;
606         if (lirc_socket >= 0) {
607                 lirc_channel = g_io_channel_unix_new(lirc_socket);
608                 g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
609         }
610 #endif
612 #ifndef WIN32
613         GIOChannel *sigwinch_channel = NULL;
614         if (!pipe(sigwinch_pipes) &&
615                 !fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
616                 sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
617                 g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
618         }
619         else {
620                 perror("sigwinch pipe creation failed");
621                 exit(EXIT_FAILURE);
622         }
623 #endif
625         /* attempt to connect */
626         reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);
628         auto_update_timer();
630 #ifndef NCMPC_MINI
631         check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
632 #endif
634         screen_paint(mpd);
636         g_main_loop_run(main_loop);
638         /* cleanup */
640         cancel_seek_timer();
642         disable_update_timer();
644         if (reconnect_source_id != 0)
645                 g_source_remove(reconnect_source_id);
647 #ifndef NCMPC_MINI
648         if (check_key_bindings_source_id != 0)
649                 g_source_remove(check_key_bindings_source_id);
650 #endif
652         g_main_loop_unref(main_loop);
653         g_io_channel_unref(keyboard_channel);
654         g_io_channel_unref(sigwinch_channel);
655         close(sigwinch_pipes[0]);
656         close(sigwinch_pipes[1]);
658 #ifdef ENABLE_LIRC
659         if (lirc_socket >= 0)
660                 g_io_channel_unref(lirc_channel);
661         ncmpc_lirc_close();
662 #endif
664         exit_and_cleanup();
666 #ifdef ENABLE_LYRICS_SCREEN
667         lyrics_deinit();
668 #endif
670         ncu_deinit();
671         options_deinit();
673         return 0;