Code

*: use Compiler.h macros instead of glib.h
[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         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(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         bool success;
291         struct mpd_connection *connection;
293         assert(!mpdclient_is_connected(mpd));
295         reconnect_source_id = 0;
297         char *name = default_settings_name();
298         screen_status_printf(_("Connecting to %s...  [Press %s to abort]"),
299                              name, get_key_names(CMD_QUIT, false));
300         g_free(name);
301         doupdate();
303         mpdclient_disconnect(mpd);
304         success = mpdclient_connect(mpd,
305                                     options.host, options.port,
306                                     options.timeout_ms,
307                                     options.password);
308         if (!success) {
309                 /* try again in 5 seconds */
310                 reconnect_source_id = g_timeout_add(5000,
311                                                     timer_reconnect, NULL);
312                 return FALSE;
313         }
315         connection = mpdclient_get_connection(mpd);
317 #ifndef NCMPC_MINI
318         /* quit if mpd is pre 0.14 - song id not supported by mpd */
319         if (mpd_connection_cmp_server_version(connection, 0, 16, 0) < 0) {
320                 const unsigned *version =
321                         mpd_connection_get_server_version(connection);
322                 screen_status_printf(_("Error: MPD version %d.%d.%d is to old (%s needed)"),
323                                      version[0], version[1], version[2],
324                                      "0.16.0");
325                 mpdclient_disconnect(mpd);
326                 doupdate();
328                 /* try again after 30 seconds */
329                 reconnect_source_id = g_timeout_add(30000,
330                                                     timer_reconnect, NULL);
331                 return FALSE;
332         }
333 #endif
335         mpd->source = mpd_glib_new(connection,
336                                    idle_callback, mpd);
338         screen_status_clear_message();
339         doupdate();
341         /* update immediately */
342         mpd->events = MPD_IDLE_ALL;
344         do_mpd_update();
346         auto_update_timer();
348         return FALSE;
351 static void
352 check_reconnect(void)
354         if (!mpdclient_is_connected(mpd) && reconnect_source_id == 0)
355                 /* reconnect when the connection is lost */
356                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
357                                                     NULL);
360 /**
361  * This function is called by the gidle.c library when MPD sends us an
362  * idle event (or when the connection dies).
363  */
364 static void
365 idle_callback(enum mpd_error error, enum mpd_server_error server_error,
366               const char *message, enum mpd_idle events,
367               void *ctx)
369         struct mpdclient *c = ctx;
371         c->idle = false;
373         assert(mpdclient_is_connected(c));
375         if (error != MPD_ERROR_SUCCESS) {
376                 char *allocated;
378                 if (error == MPD_ERROR_SERVER &&
379                     server_error == MPD_SERVER_ERROR_UNKNOWN_CMD) {
380                         /* the "idle" command is not supported - fall
381                            back to timer based polling */
382                         mpd_glib_free(c->source);
383                         c->source = NULL;
384                         auto_update_timer();
385                         return;
386                 }
388                 if (error == MPD_ERROR_SERVER)
389                         message = allocated = utf8_to_locale(message);
390                 else
391                         allocated = NULL;
392                 screen_status_message(message);
393                 g_free(allocated);
394                 screen_bell();
395                 doupdate();
397                 mpdclient_disconnect(c);
398                 screen_update(mpd);
399                 reconnect_source_id = g_timeout_add(1000, timer_reconnect,
400                                                     NULL);
401                 return;
402         }
404         c->events |= events;
405         mpdclient_update(c);
407 #ifndef NCMPC_MINI
408         if (options.enable_xterm_title)
409                 update_xterm_title();
410 #endif
412         screen_update(mpd);
413         c->events = 0;
415         mpdclient_put_connection(c);
416         check_reconnect();
417         auto_update_timer();
420 static gboolean
421 timer_mpd_update(gcc_unused gpointer data)
423         do_mpd_update();
425         if (should_enable_update_timer())
426                 return true;
427         else {
428                 update_source_id = 0;
429                 return false;
430         }
433 void begin_input_event(void)
437 void end_input_event(void)
439         screen_update(mpd);
440         mpd->events = 0;
442         mpdclient_put_connection(mpd);
443         check_reconnect();
444         auto_update_timer();
447 int do_input_event(command_t cmd)
449         if (cmd == CMD_QUIT) {
450                 g_main_loop_quit(main_loop);
451                 return -1;
452         }
454         screen_cmd(mpd, cmd);
456         if (cmd == CMD_VOLUME_UP || cmd == CMD_VOLUME_DOWN)
457                 /* make sure we don't update the volume yet */
458                 disable_update_timer();
460         return 0;
463 static gboolean
464 keyboard_event(gcc_unused GIOChannel *source,
465                gcc_unused GIOCondition condition,
466                gcc_unused gpointer data)
468         command_t cmd;
470         begin_input_event();
472         if ((cmd=get_keyboard_command()) != CMD_NONE)
473                 if (do_input_event(cmd) != 0)
474                         return FALSE;
476         end_input_event();
477         return TRUE;
480 #ifndef NCMPC_MINI
481 /**
482  * Check the configured key bindings for errors, and display a status
483  * message every 10 seconds.
484  */
485 static gboolean
486 timer_check_key_bindings(gcc_unused gpointer data)
488         char buf[256];
489 #ifdef ENABLE_KEYDEF_SCREEN
490         char comment[64];
491 #endif
492         gboolean key_error;
494         key_error = check_key_bindings(NULL, buf, sizeof(buf));
495         if (!key_error) {
496                 /* no error: disable this timer for the rest of this
497                    process */
498                 check_key_bindings_source_id = 0;
499                 return FALSE;
500         }
502 #ifdef ENABLE_KEYDEF_SCREEN
503         g_strchomp(buf);
504         g_strlcat(buf, " (", sizeof(buf));
505         /* to translators: a key was bound twice in the key editor,
506            and this is a hint for the user what to press to correct
507            that */
508         g_snprintf(comment, sizeof(comment), _("press %s for the key editor"),
509                    get_key_names(CMD_SCREEN_KEYDEF, false));
510         g_strlcat(buf, comment, sizeof(buf));
511         g_strlcat(buf, ")", sizeof(buf));
512 #endif
514         screen_status_printf("%s", buf);
516         doupdate();
517         return TRUE;
519 #endif
521 int
522 main(int argc, const char *argv[])
524 #ifndef WIN32
525         struct sigaction act;
526 #endif
527 #ifdef ENABLE_LOCALE
528 #ifndef ENABLE_NLS
529         gcc_unused
530 #endif
531         const char *charset = NULL;
532 #endif
533         GIOChannel *keyboard_channel;
534 #ifdef ENABLE_LIRC
535         int lirc_socket;
536         GIOChannel *lirc_channel = NULL;
537 #endif
538         GIOChannel *sigwinch_channel = NULL;
540 #ifdef ENABLE_LOCALE
541         /* time and date formatting */
542         setlocale(LC_TIME,"");
543         /* care about sorting order etc */
544         setlocale(LC_COLLATE,"");
545         /* charset */
546         setlocale(LC_CTYPE,"");
547         /* initialize charset conversions */
548         charset = charset_init();
550         /* initialize i18n support */
551 #endif
553 #ifdef ENABLE_NLS
554         setlocale(LC_MESSAGES, "");
555         bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
556 #ifdef ENABLE_LOCALE
557         bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
558 #endif
559         textdomain(GETTEXT_PACKAGE);
560 #endif
562         /* initialize options */
563         options_init();
565         /* parse command line options - 1 pass get configuration files */
566         options_parse(argc, argv);
568 #ifndef NCMPC_MINI
569         /* read configuration */
570         read_configuration();
572         /* check key bindings */
573         check_key_bindings(NULL, NULL, 0);
574 #endif
576         /* parse command line options - 2 pass */
577         options_parse(argc, argv);
579 #ifndef WIN32
580         /* setup signal behavior - SIGINT */
581         sigemptyset(&act.sa_mask);
582         act.sa_flags = 0;
583         act.sa_handler = catch_sigint;
584         if (sigaction(SIGINT, &act, NULL) < 0) {
585                 perror("signal");
586                 exit(EXIT_FAILURE);
587         }
589         /* setup signal behavior - SIGTERM */
591         act.sa_handler = catch_sigint;
592         if (sigaction(SIGTERM, &act, NULL) < 0) {
593                 perror("sigaction()");
594                 exit(EXIT_FAILURE);
595         }
597         /* setup signal behavior - SIGCONT */
599         act.sa_handler = catch_sigcont;
600         if (sigaction(SIGCONT, &act, NULL) < 0) {
601                 perror("sigaction(SIGCONT)");
602                 exit(EXIT_FAILURE);
603         }
605         /* setup signal behaviour - SIGHUP*/
607         act.sa_handler = catch_sigint;
608         if (sigaction(SIGHUP, &act, NULL) < 0) {
609                 perror("sigaction(SIGHUP)");
610                 exit(EXIT_FAILURE);
611         }
613         /* setup SIGWINCH */
615         act.sa_flags = SA_RESTART;
616         act.sa_handler = catch_sigwinch;
617         if (sigaction(SIGWINCH, &act, NULL) < 0) {
618                 perror("sigaction(SIGWINCH)");
619                 exit(EXIT_FAILURE);
620         }
622         /* ignore SIGPIPE */
624         act.sa_handler = SIG_IGN;
625         if (sigaction(SIGPIPE, &act, NULL) < 0) {
626                 perror("sigaction(SIGPIPE)");
627                 exit(EXIT_FAILURE);
628         }
629 #endif
631         ncu_init();
633 #ifdef ENABLE_LYRICS_SCREEN
634         lyrics_init();
635 #endif
637         /* create mpdclient instance */
638         mpd = mpdclient_new();
640         /* initialize curses */
641         screen_init(mpd);
643         /* the main loop */
644         main_loop = g_main_loop_new(NULL, FALSE);
646         /* watch out for keyboard input */
647         keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
648         g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);
650 #ifdef ENABLE_LIRC
651         /* watch out for lirc input */
652         lirc_socket = ncmpc_lirc_open();
653         if (lirc_socket >= 0) {
654                 lirc_channel = g_io_channel_unix_new(lirc_socket);
655                 g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
656         }
657 #endif
659 #ifndef WIN32
660         if (!pipe(sigwinch_pipes) &&
661                 !fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
662                 sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
663                 g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
664         }
665         else {
666                 perror("sigwinch pipe creation failed");
667                 exit(EXIT_FAILURE);
668         }
669 #endif
671         /* attempt to connect */
672         reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);
674         auto_update_timer();
676 #ifndef NCMPC_MINI
677         check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
678 #endif
680         screen_paint(mpd);
682         g_main_loop_run(main_loop);
684         /* cleanup */
686         cancel_seek_timer();
688         disable_update_timer();
690         if (reconnect_source_id != 0)
691                 g_source_remove(reconnect_source_id);
693 #ifndef NCMPC_MINI
694         if (check_key_bindings_source_id != 0)
695                 g_source_remove(check_key_bindings_source_id);
696 #endif
698         g_main_loop_unref(main_loop);
699         g_io_channel_unref(keyboard_channel);
700         g_io_channel_unref(sigwinch_channel);
701         close(sigwinch_pipes[0]);
702         close(sigwinch_pipes[1]);
704 #ifdef ENABLE_LIRC
705         if (lirc_socket >= 0)
706                 g_io_channel_unref(lirc_channel);
707         ncmpc_lirc_close();
708 #endif
710         exit_and_cleanup();
712 #ifdef ENABLE_LYRICS_SCREEN
713         lyrics_deinit();
714 #endif
716         ncu_deinit();
717         options_deinit();
719         return 0;