Code

Merge remote branches 'avuton/master' and 'jn/dev'
[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_message.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         char tmp[BUFSIZE];
79         struct mpd_status *status = NULL;
80         const struct mpd_song *song = NULL;
82         if (mpd) {
83                 status = mpd->status;
84                 song = mpd->song;
85         }
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(G_GNUC_UNUSED int sig)
119         g_main_loop_quit(main_loop);
123 static void
124 catch_sigcont(G_GNUC_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(G_GNUC_UNUSED GIOChannel *source,
141                G_GNUC_UNUSED GIOCondition condition, G_GNUC_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(G_GNUC_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               G_GNUC_UNUSED enum mpd_server_error server_error,
166               const char *message, enum mpd_idle events,
167               G_GNUC_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         return g_strdup(options.host);
275 #endif
278 static char *
279 connection_settings_name(const struct mpd_connection *connection)
281 #if LIBMPDCLIENT_CHECK_VERSION(2,4,0)
282         const struct mpd_settings *settings =
283                 mpd_connection_get_settings(connection);
284         if (settings == NULL)
285                 return g_strdup(_("unknown"));
287         return settings_name(settings);
288 #else
289         (void)connection;
291         /*
292          * localhost is actually not correct, we only know that
293          * mpd_connection_new() has connected to the "default host".
294          */
295         const char *name = options.host ?: "localhost";
296         return g_strdup(name);
297 #endif
300 /**
301  * This timer is installed when the connection to the MPD server is
302  * broken.  It tries to recover by reconnecting periodically.
303  */
304 static gboolean
305 timer_reconnect(G_GNUC_UNUSED gpointer data)
307         bool success;
308         struct mpd_connection *connection;
310         assert(!mpdclient_is_connected(mpd));
312         reconnect_source_id = 0;
314         char *name = default_settings_name();
315         screen_status_printf(_("Connecting to %s...  [Press %s to abort]"),
316                              name, get_key_names(CMD_QUIT,0) );
317         g_free(name);
318         doupdate();
320         mpdclient_disconnect(mpd);
321         success = mpdclient_connect(mpd,
322                                     options.host, options.port,
323                                     5000,
324                                     options.password);
325         if (!success) {
326                 /* try again in 5 seconds */
327                 reconnect_source_id = g_timeout_add(5000,
328                                                     timer_reconnect, NULL);
329                 return FALSE;
330         }
332         connection = mpdclient_get_connection(mpd);
334 #ifndef NCMPC_MINI
335         /* quit if mpd is pre 0.11.0 - song id not supported by mpd */
336         if (mpd_connection_cmp_server_version(connection, 0, 12, 0) < 0) {
337                 const unsigned *version =
338                         mpd_connection_get_server_version(connection);
339                 screen_status_printf(_("Error: MPD version %d.%d.%d is to old (%s needed)"),
340                                      version[0], version[1], version[2],
341                                      "0.12.0");
342                 mpdclient_disconnect(mpd);
343                 doupdate();
345                 /* try again after 30 seconds */
346                 reconnect_source_id = g_timeout_add(30000,
347                                                     timer_reconnect, NULL);
348                 return FALSE;
349         }
350 #endif
352         if (mpd_connection_cmp_server_version(connection,
353                                               0, 14, 0) >= 0)
354                 mpd->source = mpd_glib_new(connection,
355                                            idle_callback, mpd);
357         name = connection_settings_name(connection);
358         screen_status_printf(_("Connected to %s"), name);
359         g_free(name);
360         doupdate();
362         /* update immediately */
363         mpd->events = MPD_IDLE_DATABASE|MPD_IDLE_STORED_PLAYLIST|
364                 MPD_IDLE_QUEUE|MPD_IDLE_PLAYER|MPD_IDLE_MIXER|MPD_IDLE_OUTPUT|
365                 MPD_IDLE_OPTIONS|MPD_IDLE_UPDATE;
367         do_mpd_update();
369         auto_update_timer();
371         return FALSE;
374 static void
375 check_reconnect(void)
377         if (!mpdclient_is_connected(mpd) && reconnect_source_id == 0)
378                 /* reconnect when the connection is lost */
379                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
380                                                     NULL);
383 /**
384  * This function is called by the gidle.c library when MPD sends us an
385  * idle event (or when the connection dies).
386  */
387 static void
388 idle_callback(enum mpd_error error, enum mpd_server_error server_error,
389               const char *message, enum mpd_idle events,
390               void *ctx)
392         struct mpdclient *c = ctx;
394         c->idle = false;
396         assert(mpdclient_is_connected(c));
398         if (error != MPD_ERROR_SUCCESS) {
399                 char *allocated;
401                 if (error == MPD_ERROR_SERVER &&
402                     server_error == MPD_SERVER_ERROR_UNKNOWN_CMD) {
403                         /* the "idle" command is not supported - fall
404                            back to timer based polling */
405                         mpd_glib_free(c->source);
406                         c->source = NULL;
407                         auto_update_timer();
408                         return;
409                 }
411                 if (error == MPD_ERROR_SERVER)
412                         message = allocated = utf8_to_locale(message);
413                 else
414                         allocated = NULL;
415                 screen_status_message(message);
416                 g_free(allocated);
417                 screen_bell();
418                 doupdate();
420                 mpdclient_disconnect(c);
421                 screen_update(mpd);
422                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
423                                                     NULL);
424                 return;
425         }
427         c->events |= events;
428         mpdclient_update(c);
430 #ifndef NCMPC_MINI
431         if (options.enable_xterm_title)
432                 update_xterm_title();
433 #endif
435         screen_update(mpd);
436         c->events = 0;
438         mpdclient_put_connection(c);
439         check_reconnect();
440         auto_update_timer();
443 static gboolean
444 timer_mpd_update(G_GNUC_UNUSED gpointer data)
446         do_mpd_update();
448         if (should_enable_update_timer())
449                 return true;
450         else {
451                 update_source_id = 0;
452                 return false;
453         }
456 void begin_input_event(void)
460 void end_input_event(void)
462         screen_update(mpd);
463         mpd->events = 0;
465         mpdclient_put_connection(mpd);
466         check_reconnect();
467         auto_update_timer();
470 int do_input_event(command_t cmd)
472         if (cmd == CMD_QUIT) {
473                 g_main_loop_quit(main_loop);
474                 return -1;
475         }
477         screen_cmd(mpd, cmd);
479         if (cmd == CMD_VOLUME_UP || cmd == CMD_VOLUME_DOWN)
480                 /* make sure we don't update the volume yet */
481                 disable_update_timer();
483         return 0;
486 static gboolean
487 keyboard_event(G_GNUC_UNUSED GIOChannel *source,
488                G_GNUC_UNUSED GIOCondition condition,
489                G_GNUC_UNUSED gpointer data)
491         command_t cmd;
493         begin_input_event();
495         if ((cmd=get_keyboard_command()) != CMD_NONE)
496                 if (do_input_event(cmd) != 0)
497                         return FALSE;
499         end_input_event();
500         return TRUE;
503 #ifndef NCMPC_MINI
504 /**
505  * Check the configured key bindings for errors, and display a status
506  * message every 10 seconds.
507  */
508 static gboolean
509 timer_check_key_bindings(G_GNUC_UNUSED gpointer data)
511         char buf[256];
512 #ifdef ENABLE_KEYDEF_SCREEN
513         char comment[64];
514 #endif
515         gboolean key_error;
517         key_error = check_key_bindings(NULL, buf, sizeof(buf));
518         if (!key_error) {
519                 /* no error: disable this timer for the rest of this
520                    process */
521                 check_key_bindings_source_id = 0;
522                 return FALSE;
523         }
525 #ifdef ENABLE_KEYDEF_SCREEN
526         g_strchomp(buf);
527         g_strlcat(buf, " (", sizeof(buf));
528         /* to translators: a key was bound twice in the key editor,
529            and this is a hint for the user what to press to correct
530            that */
531         g_snprintf(comment, sizeof(comment), _("press %s for the key editor"),
532                    get_key_names(CMD_SCREEN_KEYDEF, 0));
533         g_strlcat(buf, comment, sizeof(buf));
534         g_strlcat(buf, ")", sizeof(buf));
535 #endif
537         screen_status_printf("%s", buf);
539         doupdate();
540         return TRUE;
542 #endif
544 int
545 main(int argc, const char *argv[])
547 #ifndef WIN32
548         struct sigaction act;
549 #endif
550 #ifdef ENABLE_LOCALE
551 #ifndef ENABLE_NLS
552         G_GNUC_UNUSED
553 #endif
554         const char *charset = NULL;
555 #endif
556         GIOChannel *keyboard_channel;
557 #ifdef ENABLE_LIRC
558         int lirc_socket;
559         GIOChannel *lirc_channel = NULL;
560 #endif
561         GIOChannel *sigwinch_channel = NULL;
563 #ifdef ENABLE_LOCALE
564         /* time and date formatting */
565         setlocale(LC_TIME,"");
566         /* care about sorting order etc */
567         setlocale(LC_COLLATE,"");
568         /* charset */
569         setlocale(LC_CTYPE,"");
570         /* initialize charset conversions */
571         charset = charset_init();
573         /* initialize i18n support */
574 #endif
576 #ifdef ENABLE_NLS
577         setlocale(LC_MESSAGES, "");
578         bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
579 #ifdef ENABLE_LOCALE
580         bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
581 #endif
582         textdomain(GETTEXT_PACKAGE);
583 #endif
585         /* initialize options */
586         options_init();
588         /* parse command line options - 1 pass get configuration files */
589         options_parse(argc, argv);
591 #ifndef NCMPC_MINI
592         /* read configuration */
593         read_configuration();
595         /* check key bindings */
596         check_key_bindings(NULL, NULL, 0);
597 #endif
599         /* parse command line options - 2 pass */
600         options_parse(argc, argv);
602 #ifndef WIN32
603         /* setup signal behavior - SIGINT */
604         sigemptyset(&act.sa_mask);
605         act.sa_flags = 0;
606         act.sa_handler = catch_sigint;
607         if (sigaction(SIGINT, &act, NULL) < 0) {
608                 perror("signal");
609                 exit(EXIT_FAILURE);
610         }
612         /* setup signal behavior - SIGTERM */
614         act.sa_handler = catch_sigint;
615         if (sigaction(SIGTERM, &act, NULL) < 0) {
616                 perror("sigaction()");
617                 exit(EXIT_FAILURE);
618         }
620         /* setup signal behavior - SIGCONT */
622         act.sa_handler = catch_sigcont;
623         if (sigaction(SIGCONT, &act, NULL) < 0) {
624                 perror("sigaction(SIGCONT)");
625                 exit(EXIT_FAILURE);
626         }
628         /* setup signal behaviour - SIGHUP*/
630         act.sa_handler = catch_sigint;
631         if (sigaction(SIGHUP, &act, NULL) < 0) {
632                 perror("sigaction(SIGHUP)");
633                 exit(EXIT_FAILURE);
634         }
636         /* setup SIGWINCH */
638         act.sa_flags = SA_RESTART;
639         act.sa_handler = catch_sigwinch;
640         if (sigaction(SIGWINCH, &act, NULL) < 0) {
641                 perror("sigaction(SIGWINCH)");
642                 exit(EXIT_FAILURE);
643         }
645         /* ignore SIGPIPE */
647         act.sa_handler = SIG_IGN;
648         if (sigaction(SIGPIPE, &act, NULL) < 0) {
649                 perror("sigaction(SIGPIPE)");
650                 exit(EXIT_FAILURE);
651         }
652 #endif
654         ncu_init();
656 #ifdef ENABLE_LYRICS_SCREEN
657         lyrics_init();
658 #endif
660         /* create mpdclient instance */
661         mpd = mpdclient_new();
663         /* initialize curses */
664         screen_init(mpd);
666         /* the main loop */
667         main_loop = g_main_loop_new(NULL, FALSE);
669         /* watch out for keyboard input */
670         keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
671         g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);
673 #ifdef ENABLE_LIRC
674         /* watch out for lirc input */
675         lirc_socket = ncmpc_lirc_open();
676         if (lirc_socket >= 0) {
677                 lirc_channel = g_io_channel_unix_new(lirc_socket);
678                 g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
679         }
680 #endif
682 #ifndef WIN32
683         if (!pipe(sigwinch_pipes) &&
684                 !fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
685                 sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
686                 g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
687         }
688         else {
689                 perror("sigwinch pipe creation failed");
690                 exit(EXIT_FAILURE);
691         }
692 #endif
694         /* attempt to connect */
695         reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);
697         auto_update_timer();
699 #ifndef NCMPC_MINI
700         check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
701 #endif
703         screen_paint(mpd);
705         g_main_loop_run(main_loop);
707         /* cleanup */
709         cancel_seek_timer();
711         disable_update_timer();
713         if (reconnect_source_id != 0)
714                 g_source_remove(reconnect_source_id);
716 #ifndef NCMPC_MINI
717         if (check_key_bindings_source_id != 0)
718                 g_source_remove(check_key_bindings_source_id);
719 #endif
721         g_main_loop_unref(main_loop);
722         g_io_channel_unref(keyboard_channel);
723         g_io_channel_unref(sigwinch_channel);
724         close(sigwinch_pipes[0]);
725         close(sigwinch_pipes[1]);
727 #ifdef ENABLE_LIRC
728         if (lirc_socket >= 0)
729                 g_io_channel_unref(lirc_channel);
730         ncmpc_lirc_close();
731 #endif
733         exit_and_cleanup();
735 #ifdef ENABLE_LYRICS_SCREEN
736         lyrics_deinit();
737 #endif
739         ncu_deinit();
740         options_deinit();
742         return 0;