Code

341fb1733e121988f89d8bc1b5a8893c0da21f5b
[ncmpc.git] / src / main.c
1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2010 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         static char title[BUFSIZE];
78         struct mpd_status *status = NULL;
79         const struct mpd_song *song = NULL;
81         if (mpd) {
82                 status = mpd->status;
83                 song = mpd->song;
84         }
86         char tmp[BUFSIZE];
87         if (options.xterm_title_format && status && song &&
88             mpd_status_get_state(status) == MPD_STATE_PLAY)
89                 strfsong(tmp, BUFSIZE, options.xterm_title_format, song);
90         else
91                 g_strlcpy(tmp, PACKAGE " version " VERSION, BUFSIZE);
93         if (strncmp(title, tmp, BUFSIZE)) {
94                 g_strlcpy(title, tmp, BUFSIZE);
95                 set_xterm_title("%s", title);
96         }
97 }
98 #endif
100 static void
101 exit_and_cleanup(void)
103         screen_exit();
104 #ifndef NCMPC_MINI
105         set_xterm_title("");
106 #endif
107         printf("\n");
109         if (mpd) {
110                 mpdclient_disconnect(mpd);
111                 mpdclient_free(mpd);
112         }
115 #ifndef WIN32
116 static void
117 catch_sigint(gcc_unused int sig)
119         g_main_loop_quit(main_loop);
123 static void
124 catch_sigcont(gcc_unused int sig)
126         char irrelevant = 'a';
127         if (1 != write(sigwinch_pipes[1], &irrelevant, 1))
128                 exit(EXIT_FAILURE);
131 void
132 sigstop(void)
134         def_prog_mode();  /* save the tty modes */
135         endwin();         /* end curses mode temporarily */
136         kill(0, SIGSTOP); /* issue SIGSTOP */
139 static gboolean
140 sigwinch_event(gcc_unused GIOChannel *source,
141                gcc_unused GIOCondition condition, gcc_unused gpointer data)
143         char ignoreme[64];
144         if (1 > read(sigwinch_pipes[0], ignoreme, 64))
145                 exit(EXIT_FAILURE);
147         endwin();
148         refresh();
149         screen_resize(mpd);
151         return TRUE;
154 static void
155 catch_sigwinch(gcc_unused int sig)
157         char irrelevant = 'a';
158         if (1 != write(sigwinch_pipes[1], &irrelevant, 1))
159                 exit(EXIT_FAILURE);
161 #endif /* WIN32 */
163 static void
164 idle_callback(enum mpd_error error,
165               gcc_unused enum mpd_server_error server_error,
166               const char *message, enum mpd_idle events,
167               gcc_unused void *ctx);
169 static gboolean
170 timer_mpd_update(gpointer data);
172 static void
173 enable_update_timer(void)
175         if (update_source_id != 0)
176                 return;
178         update_source_id = g_timeout_add(update_interval,
179                                          timer_mpd_update, NULL);
182 static void
183 disable_update_timer(void)
185         if (update_source_id == 0)
186                 return;
188         g_source_remove(update_source_id);
189         update_source_id = 0;
192 static bool
193 should_enable_update_timer(void)
195         return (mpdclient_is_connected(mpd) &&
196                 (mpd->source == NULL || /* "idle" not supported */
197                  (mpd->status != NULL &&
198                   mpd_status_get_state(mpd->status) == MPD_STATE_PLAY)))
199 #ifndef NCMPC_MINI
200                 || options.display_time
201 #endif
202                 ;
205 static void
206 auto_update_timer(void)
208         if (should_enable_update_timer())
209                 enable_update_timer();
210         else
211                 disable_update_timer();
214 static void
215 check_reconnect(void);
217 static void
218 do_mpd_update(void)
220         if (mpdclient_is_connected(mpd) &&
221             (mpd->source == NULL || mpd->events != 0 ||
222              (mpd->status != NULL &&
223               mpd_status_get_state(mpd->status) == MPD_STATE_PLAY)))
224                 mpdclient_update(mpd);
226 #ifndef NCMPC_MINI
227         if (options.enable_xterm_title)
228                 update_xterm_title();
229 #endif
231         screen_update(mpd);
232         mpd->events = 0;
234         mpdclient_put_connection(mpd);
235         check_reconnect();
238 #if LIBMPDCLIENT_CHECK_VERSION(2,4,0)
240 static char *
241 settings_name(const struct mpd_settings *settings)
243         const char *host = mpd_settings_get_host(settings);
244         if (host == NULL)
245                 host = _("unknown");
247         if (host[0] == '/')
248                 return g_strdup(host);
250         unsigned port = mpd_settings_get_port(settings);
251         if (port == 0 || port == 6600)
252                 return g_strdup(host);
254         return g_strdup_printf("%s:%u", host, port);
257 #endif
259 static char *
260 default_settings_name(void)
262 #if LIBMPDCLIENT_CHECK_VERSION(2,4,0)
263         struct mpd_settings *settings =
264                 mpd_settings_new(options.host, options.port, 0,
265                                  NULL, options.password);
266         if (settings == NULL)
267                 return g_strdup(_("unknown"));
269         char *name = settings_name(settings);
270         mpd_settings_free(settings);
272         return name;
273 #else
274         /*
275          * localhost is actually not correct, we only know that
276          * mpd_connection_new() has connected to the "default host".
277          */
278         const char *name = options.host ?: "localhost";
279         return g_strdup(name);
280 #endif
283 /**
284  * This timer is installed when the connection to the MPD server is
285  * broken.  It tries to recover by reconnecting periodically.
286  */
287 static gboolean
288 timer_reconnect(gcc_unused gpointer data)
290         assert(!mpdclient_is_connected(mpd));
292         reconnect_source_id = 0;
294         char *name = default_settings_name();
295         screen_status_printf(_("Connecting to %s...  [Press %s to abort]"),
296                              name, get_key_names(CMD_QUIT, false));
297         g_free(name);
298         doupdate();
300         mpdclient_disconnect(mpd);
301         if (!mpdclient_connect(mpd, options.host, options.port,
302                                options.timeout_ms,
303                                options.password)) {
304                 /* try again in 5 seconds */
305                 reconnect_source_id = g_timeout_add(5000,
306                                                     timer_reconnect, NULL);
307                 return FALSE;
308         }
310         struct mpd_connection *connection = mpdclient_get_connection(mpd);
312 #ifndef NCMPC_MINI
313         /* quit if mpd is pre 0.14 - song id not supported by mpd */
314         if (mpd_connection_cmp_server_version(connection, 0, 16, 0) < 0) {
315                 const unsigned *version =
316                         mpd_connection_get_server_version(connection);
317                 screen_status_printf(_("Error: MPD version %d.%d.%d is too old (%s needed)"),
318                                      version[0], version[1], version[2],
319                                      "0.16.0");
320                 mpdclient_disconnect(mpd);
321                 doupdate();
323                 /* try again after 30 seconds */
324                 reconnect_source_id = g_timeout_add(30000,
325                                                     timer_reconnect, NULL);
326                 return FALSE;
327         }
328 #endif
330         mpd->source = mpd_glib_new(connection,
331                                    idle_callback, mpd);
333         screen_status_clear_message();
334         doupdate();
336         /* update immediately */
337         mpd->events = MPD_IDLE_ALL;
339         do_mpd_update();
341         auto_update_timer();
343         return FALSE;
346 static void
347 check_reconnect(void)
349         if (!mpdclient_is_connected(mpd) && reconnect_source_id == 0)
350                 /* reconnect when the connection is lost */
351                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
352                                                     NULL);
355 /**
356  * This function is called by the gidle.c library when MPD sends us an
357  * idle event (or when the connection dies).
358  */
359 static void
360 idle_callback(enum mpd_error error, enum mpd_server_error server_error,
361               const char *message, enum mpd_idle events,
362               void *ctx)
364         struct mpdclient *c = ctx;
366         c->idle = false;
368         assert(mpdclient_is_connected(c));
370         if (error != MPD_ERROR_SUCCESS) {
371                 char *allocated;
373                 if (error == MPD_ERROR_SERVER &&
374                     server_error == MPD_SERVER_ERROR_UNKNOWN_CMD) {
375                         /* the "idle" command is not supported - fall
376                            back to timer based polling */
377                         mpd_glib_free(c->source);
378                         c->source = NULL;
379                         auto_update_timer();
380                         return;
381                 }
383                 if (error == MPD_ERROR_SERVER)
384                         message = allocated = utf8_to_locale(message);
385                 else
386                         allocated = NULL;
387                 screen_status_message(message);
388                 g_free(allocated);
389                 screen_bell();
390                 doupdate();
392                 mpdclient_disconnect(c);
393                 screen_update(mpd);
394                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
395                                                     NULL);
396                 return;
397         }
399         c->events |= events;
400         mpdclient_update(c);
402 #ifndef NCMPC_MINI
403         if (options.enable_xterm_title)
404                 update_xterm_title();
405 #endif
407         screen_update(mpd);
408         c->events = 0;
410         mpdclient_put_connection(c);
411         check_reconnect();
412         auto_update_timer();
415 static gboolean
416 timer_mpd_update(gcc_unused gpointer data)
418         do_mpd_update();
420         if (should_enable_update_timer())
421                 return true;
422         else {
423                 update_source_id = 0;
424                 return false;
425         }
428 void begin_input_event(void)
432 void end_input_event(void)
434         screen_update(mpd);
435         mpd->events = 0;
437         mpdclient_put_connection(mpd);
438         check_reconnect();
439         auto_update_timer();
442 int do_input_event(command_t cmd)
444         if (cmd == CMD_QUIT) {
445                 g_main_loop_quit(main_loop);
446                 return -1;
447         }
449         screen_cmd(mpd, cmd);
451         if (cmd == CMD_VOLUME_UP || cmd == CMD_VOLUME_DOWN)
452                 /* make sure we don't update the volume yet */
453                 disable_update_timer();
455         return 0;
458 static gboolean
459 keyboard_event(gcc_unused GIOChannel *source,
460                gcc_unused GIOCondition condition,
461                gcc_unused gpointer data)
463         begin_input_event();
465         command_t cmd = get_keyboard_command();
466         if (cmd != CMD_NONE)
467                 if (do_input_event(cmd) != 0)
468                         return FALSE;
470         end_input_event();
471         return TRUE;
474 #ifndef NCMPC_MINI
475 /**
476  * Check the configured key bindings for errors, and display a status
477  * message every 10 seconds.
478  */
479 static gboolean
480 timer_check_key_bindings(gcc_unused gpointer data)
482         char buf[256];
483 #ifdef ENABLE_KEYDEF_SCREEN
484         char comment[64];
485 #endif
487         if (check_key_bindings(NULL, buf, sizeof(buf))) {
488                 /* no error: disable this timer for the rest of this
489                    process */
490                 check_key_bindings_source_id = 0;
491                 return FALSE;
492         }
494 #ifdef ENABLE_KEYDEF_SCREEN
495         g_strchomp(buf);
496         g_strlcat(buf, " (", sizeof(buf));
497         /* to translators: a key was bound twice in the key editor,
498            and this is a hint for the user what to press to correct
499            that */
500         g_snprintf(comment, sizeof(comment), _("press %s for the key editor"),
501                    get_key_names(CMD_SCREEN_KEYDEF, false));
502         g_strlcat(buf, comment, sizeof(buf));
503         g_strlcat(buf, ")", sizeof(buf));
504 #endif
506         screen_status_printf("%s", buf);
508         doupdate();
509         return TRUE;
511 #endif
513 int
514 main(int argc, const char *argv[])
516 #ifdef ENABLE_LOCALE
517 #ifndef ENABLE_NLS
518         gcc_unused
519 #endif
520         const char *charset = NULL;
521         /* time and date formatting */
522         setlocale(LC_TIME,"");
523         /* care about sorting order etc */
524         setlocale(LC_COLLATE,"");
525         /* charset */
526         setlocale(LC_CTYPE,"");
527         /* initialize charset conversions */
528         charset = charset_init();
530         /* initialize i18n support */
531 #endif
533 #ifdef ENABLE_NLS
534         setlocale(LC_MESSAGES, "");
535         bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
536 #ifdef ENABLE_LOCALE
537         bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
538 #endif
539         textdomain(GETTEXT_PACKAGE);
540 #endif
542         /* initialize options */
543         options_init();
545         /* parse command line options - 1 pass get configuration files */
546         options_parse(argc, argv);
548 #ifndef NCMPC_MINI
549         /* read configuration */
550         read_configuration();
552         /* check key bindings */
553         check_key_bindings(NULL, NULL, 0);
554 #endif
556         /* parse command line options - 2 pass */
557         options_parse(argc, argv);
559 #ifndef WIN32
560         /* setup signal behavior - SIGINT */
561         struct sigaction act;
562         sigemptyset(&act.sa_mask);
563         act.sa_flags = 0;
564         act.sa_handler = catch_sigint;
565         if (sigaction(SIGINT, &act, NULL) < 0) {
566                 perror("signal");
567                 exit(EXIT_FAILURE);
568         }
570         /* setup signal behavior - SIGTERM */
572         act.sa_handler = catch_sigint;
573         if (sigaction(SIGTERM, &act, NULL) < 0) {
574                 perror("sigaction()");
575                 exit(EXIT_FAILURE);
576         }
578         /* setup signal behavior - SIGCONT */
580         act.sa_handler = catch_sigcont;
581         if (sigaction(SIGCONT, &act, NULL) < 0) {
582                 perror("sigaction(SIGCONT)");
583                 exit(EXIT_FAILURE);
584         }
586         /* setup signal behaviour - SIGHUP*/
588         act.sa_handler = catch_sigint;
589         if (sigaction(SIGHUP, &act, NULL) < 0) {
590                 perror("sigaction(SIGHUP)");
591                 exit(EXIT_FAILURE);
592         }
594         /* setup SIGWINCH */
596         act.sa_flags = SA_RESTART;
597         act.sa_handler = catch_sigwinch;
598         if (sigaction(SIGWINCH, &act, NULL) < 0) {
599                 perror("sigaction(SIGWINCH)");
600                 exit(EXIT_FAILURE);
601         }
603         /* ignore SIGPIPE */
605         act.sa_handler = SIG_IGN;
606         if (sigaction(SIGPIPE, &act, NULL) < 0) {
607                 perror("sigaction(SIGPIPE)");
608                 exit(EXIT_FAILURE);
609         }
610 #endif
612         ncu_init();
614 #ifdef ENABLE_LYRICS_SCREEN
615         lyrics_init();
616 #endif
618         /* create mpdclient instance */
619         mpd = mpdclient_new();
621         /* initialize curses */
622         screen_init(mpd);
624         /* the main loop */
625         main_loop = g_main_loop_new(NULL, FALSE);
627         /* watch out for keyboard input */
628         GIOChannel *keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
629         g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);
631 #ifdef ENABLE_LIRC
632         /* watch out for lirc input */
633         int lirc_socket = ncmpc_lirc_open();
634         GIOChannel *lirc_channel = NULL;
635         if (lirc_socket >= 0) {
636                 lirc_channel = g_io_channel_unix_new(lirc_socket);
637                 g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
638         }
639 #endif
641 #ifndef WIN32
642         GIOChannel *sigwinch_channel = NULL;
643         if (!pipe(sigwinch_pipes) &&
644                 !fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
645                 sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
646                 g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
647         }
648         else {
649                 perror("sigwinch pipe creation failed");
650                 exit(EXIT_FAILURE);
651         }
652 #endif
654         /* attempt to connect */
655         reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);
657         auto_update_timer();
659 #ifndef NCMPC_MINI
660         check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
661 #endif
663         screen_paint(mpd);
665         g_main_loop_run(main_loop);
667         /* cleanup */
669         cancel_seek_timer();
671         disable_update_timer();
673         if (reconnect_source_id != 0)
674                 g_source_remove(reconnect_source_id);
676 #ifndef NCMPC_MINI
677         if (check_key_bindings_source_id != 0)
678                 g_source_remove(check_key_bindings_source_id);
679 #endif
681         g_main_loop_unref(main_loop);
682         g_io_channel_unref(keyboard_channel);
683         g_io_channel_unref(sigwinch_channel);
684         close(sigwinch_pipes[0]);
685         close(sigwinch_pipes[1]);
687 #ifdef ENABLE_LIRC
688         if (lirc_socket >= 0)
689                 g_io_channel_unref(lirc_channel);
690         ncmpc_lirc_close();
691 #endif
693         exit_and_cleanup();
695 #ifdef ENABLE_LYRICS_SCREEN
696         lyrics_deinit();
697 #endif
699         ncu_deinit();
700         options_deinit();
702         return 0;