Use a const char to store the static string.
[herrie-working.git] / herrie / src / gui_input.c
blobc679afef0e443a85aa857f4148870f9fd780f897
1 /*
2 * Copyright (c) 2006-2009 Ed Schouten <ed@80386.nl>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
26 /**
27 * @file gui_input.c
28 * @brief Keyboard and signal input for user interface.
31 #include "stdinc.h"
33 #include "audio_output.h"
34 #include "config.h"
35 #include "dbus.h"
36 #include "gui.h"
37 #include "gui_internal.h"
38 #include "playq.h"
39 #include "scrobbler.h"
40 #include "vfs.h"
42 /**
43 * @brief The focus is on the browser.
45 #define GUI_FOCUS_BROWSER 0
46 /**
47 * @brief The focus is on the playlist.
49 #define GUI_FOCUS_PLAYQ 1
50 /**
51 * @brief The number of focusable windows.
53 #define GUI_FOCUS_COUNT 2
54 /**
55 * @brief Window that is currently focused.
57 static int gui_input_curfocus = GUI_FOCUS_BROWSER;
58 /**
59 * @brief Indicator of the current search string.
61 static struct vfsmatch *cursearch = NULL;
62 /**
63 * @brief The last seek string that has been entered.
65 static char *curseek = NULL;
66 /**
67 * @brief Determine if we're already trying to shut down, to prevent
68 * multiple signals being handled while quitting.
70 static int shutting_down = 0;
71 /**
72 * @brief Add the Ctrl modifier to a character.
74 #define CTRL(x) (((x) - 'A' + 1) & 0x7f)
76 /**
77 * @brief Properly shutdown the application by stopping playback and
78 * destroying the GUI.
80 static void
81 gui_input_quit(void)
83 shutting_down = 1;
85 playq_shutdown();
86 #ifdef BUILD_SCROBBLER
87 scrobbler_shutdown();
88 #endif /* BUILD_SCROBBLER */
89 audio_output_close();
90 gui_draw_destroy();
91 exit(0);
94 /**
95 * @brief Prompt the user with a message to confirm termination of the
96 * application.
98 static void
99 gui_input_askquit(void)
101 int ret;
102 char *msg;
104 if (!config_getopt_bool("gui.input.may_quit")) {
105 gui_msgbar_warn(_("Use kill(1) to quit."));
106 return;
109 msg = g_strdup_printf(_("Quit %s?"), APP_NAME);
110 ret = gui_input_askyesno(msg);
111 g_free(msg);
113 if (ret == 0)
114 gui_input_quit();
118 * @brief Fetch a character from the keyboard, already processing
119 * terminal resizes and awkward bugs.
121 static int
122 gui_input_getch(void)
124 int ch;
126 for (;;) {
127 ch = getch();
129 switch (ch) {
130 /* Redraw everything when resizing */
131 case KEY_RESIZE:
132 case CTRL('L'):
133 gui_draw_resize();
134 continue;
136 /* Catch backspace button */
137 case CTRL('H'):
138 case CTRL('?'):
139 return (KEY_BACKSPACE);
141 /* FreeBSD returns KEY_SELECT instead of KEY_END */
142 case KEY_SELECT:
143 return (KEY_END);
145 /* Error condition */
146 case ERR:
147 switch (errno) {
148 case 0:
149 case EINTR:
150 /* Signal delivery */
151 continue;
152 default:
153 /* We've lost stdin */
154 gui_input_quit();
158 break;
161 return (ch);
165 * @brief Switch the focus to the next window.
167 static void
168 gui_input_switchfocus(void)
170 gui_input_curfocus++;
171 gui_input_curfocus %= GUI_FOCUS_COUNT;
173 /* Update the selection colors */
174 gui_playq_setfocus(gui_input_curfocus == GUI_FOCUS_PLAYQ);
175 gui_browser_setfocus(gui_input_curfocus == GUI_FOCUS_BROWSER);
179 * @brief Ask the user to enter a new search string.
181 static int
182 gui_input_asksearch(void)
184 char *str;
185 const char *old = NULL;
186 struct vfsmatch *vm;
188 /* Show the previous value if we have one */
189 if (cursearch != NULL)
190 old = vfs_match_value(cursearch);
192 /* Allow the user to enter a search string */
193 str = gui_input_askstring(_("Search for"), old, NULL);
194 if (str == NULL)
195 return (-1);
197 vm = vfs_match_new(str);
198 if (vm == NULL) {
199 gui_msgbar_warn(_("Bad pattern."));
200 g_free(str);
201 return (-1);
204 /* Replace our search string */
205 if (cursearch != NULL)
206 vfs_match_free(cursearch);
207 cursearch = vm;
209 str = g_strdup_printf(_("Searching for \"%s\"..."),
210 vfs_match_value(vm));
211 gui_msgbar_warn(str);
212 g_free(str);
214 return (0);
218 * @brief Ask the user to enter a search string when none was given and
219 * search for the next item matching the search string.
221 static void
222 gui_input_searchnext(void)
224 int nfocus = GUI_FOCUS_PLAYQ;
226 if (cursearch == NULL) {
227 /* No search string yet */
228 if (gui_input_asksearch() != 0)
229 return;
233 * We want to change our search order depending on which dialog
234 * is currently focused. This code is quite awful, but does the
235 * thing. When the playq is focused, it only performs the first
236 * two searches. If the browser is focused, it only performs the
237 * last two.
239 if (gui_input_curfocus == GUI_FOCUS_PLAYQ &&
240 gui_playq_searchnext(cursearch) == 0) {
241 goto found;
242 } else if (gui_browser_searchnext(cursearch) == 0) {
243 nfocus = GUI_FOCUS_BROWSER;
244 goto found;
245 } else if (gui_input_curfocus != GUI_FOCUS_PLAYQ &&
246 gui_playq_searchnext(cursearch) == 0) {
247 goto found;
250 /* Bad luck. */
251 gui_msgbar_warn(_("Not found."));
252 return;
254 found: /* Focus the window with the match and redraw them. */
255 gui_input_curfocus = nfocus;
256 gui_playq_setfocus(gui_input_curfocus == GUI_FOCUS_PLAYQ);
257 gui_browser_setfocus(gui_input_curfocus == GUI_FOCUS_BROWSER);
258 gui_msgbar_flush();
262 * @brief Ask the user to enter a new search string and perform the
263 * first search.
265 static void
266 gui_input_search(void)
268 /* Always ask for a search string */
269 if (gui_input_asksearch() != 0)
270 return;
272 /* Just simulate a 'n' button */
273 gui_input_searchnext();
277 * @brief Ask for a search string and filter matching files in the file
278 * browser.
280 static void
281 gui_input_locate(void)
283 /* Always ask for a search string */
284 if (gui_input_asksearch() != 0)
285 return;
287 /* Perform the serach */
288 if (gui_browser_locate(cursearch) != 0)
289 gui_msgbar_warn(_("Not found."));
290 else
291 gui_msgbar_flush();
295 * @brief Instruct the playlist to seek the current song 5 seconds
296 * backward.
298 static void
299 gui_input_cursong_seek_backward(void)
301 playq_cursong_seek(-5, 1);
305 * @brief Instruct the playlist to seek the current song 5 seconds
306 * forward.
308 static void
309 gui_input_cursong_seek_forward(void)
311 playq_cursong_seek(5, 1);
315 * @brief Approve input string format for the seeking option.
317 static int
318 gui_input_cursong_seek_validator(const char *str, char c)
320 const char *s;
322 if (c == '+' || c == '-') {
323 /* Only allow + and - at the beginning of the statement */
324 if (str[0] != '\0')
325 return (-1);
326 } else if (c == ':') {
327 /* Don't allow : before a digit has been inserted */
328 if (strpbrk(str, "0123456789") == NULL)
329 return (-1);
331 s = strrchr(str, ':');
332 if (s != NULL) {
333 /* Only allow colon after two decimals */
334 if (strlen(s + 1) != 2)
335 return (-1);
336 /* Only allow two : characters in the string */
337 if (s - strchr(str, ':') == 3)
338 return (-1);
340 } else if (g_ascii_isdigit(c)) {
341 s = strrchr(str, ':');
342 if (s != NULL) {
343 /* Only allow up to two decimals after a colon */
344 if (strlen(s + 1) == 2)
345 return (-1);
346 /* Only allow '0' to '5' as the first digit */
347 if (s[1] == '\0' && c > '5')
348 return (-1);
350 } else {
351 /* Don't allow any other characters */
352 return (-1);
355 return (0);
359 * @brief Ask the user to specify a position to seek the current song to.
361 static void
362 gui_input_cursong_seek_jump(void)
364 char *str, *t;
365 int total = 0, split = 0, digit = 0, value, relative = 0;
367 str = gui_input_askstring(_("Jump to position"), curseek,
368 gui_input_cursong_seek_validator);
369 if (str == NULL)
370 return;
372 for (t = str; *t != '\0'; t++) {
373 switch (*t) {
374 case ':':
376 * Only allow two :'s, not without a prepending
377 * digit. :'s must be interleaved with two
378 * digits.
380 g_assert(split <= 1 && digit != 0);
381 g_assert(split == 0 || digit == 2);
382 split++;
383 digit = 0;
384 break;
385 case '+':
386 /* Must be at the beginning */
387 g_assert(t == str);
388 relative = 1;
389 break;
390 case '-':
391 /* Must be at the beginning */
392 g_assert(t == str);
393 relative = -1;
394 break;
395 default:
396 /* Regular digit */
397 value = g_ascii_digit_value(*t);
398 g_assert(value != -1);
399 g_assert(split == 0 || digit != 0 || value <= 5);
401 total *= (digit == 0) ? 6 : 10;
402 total += value;
403 digit++;
407 /* Not enough trailing digits */
408 if (split > 0 && digit != 2)
409 goto bad;
411 if (relative != 0) {
412 total *= relative;
413 if (total == 0)
414 goto bad;
416 playq_cursong_seek(total, relative);
418 /* Show the string the next time as well */
419 g_free(curseek);
420 curseek = str;
421 return;
423 bad: gui_msgbar_warn(_("Bad time format."));
424 g_free(str);
428 * @brief A simple binding from a keyboard character input to a function.
430 struct gui_binding {
432 * @brief The window that should be focussed.
434 int focus;
436 * @brief The character that should be pressed.
438 int input;
440 * @brief The function that will be run.
442 void (*func)(void);
446 * @brief List of keybindings available in the GUI.
448 static struct gui_binding kbdbindings[] = {
449 /* Application-wide keyboard bindings */
450 #ifdef BUILD_VOLUME
451 { -1, '(', gui_playq_volume_down },
452 { -1, ')', gui_playq_volume_up },
453 #endif /* BUILD_VOLUME */
454 { -1, '<', gui_input_cursong_seek_backward },
455 { -1, '>', gui_input_cursong_seek_forward },
456 { -1, 'a', gui_browser_playq_add_after },
457 { -1, 'A', gui_browser_playq_add_tail },
458 { -1, 'b', playq_cursong_next },
459 { -1, 'c', playq_cursong_pause },
460 { -1, 'C', gui_browser_chdir },
461 { -1, 'd', gui_playq_song_remove },
462 { -1, 'D', gui_playq_song_remove_all },
463 { -1, 'h', gui_browser_dir_parent },
464 { -1, 'i', gui_browser_playq_add_before },
465 { -1, 'I', gui_browser_playq_add_head },
466 { -1, 'J', gui_input_cursong_seek_jump },
467 { -1, 'l', gui_browser_dir_enter },
468 { -1, 'L', gui_input_locate },
469 { -1, 'q', gui_input_askquit },
470 { -1, 'r', playq_repeat_toggle },
471 { -1, 'R', gui_playq_song_randomize },
472 { -1, 'v', playq_cursong_stop },
473 { -1, 'w', gui_browser_write_playlist },
474 { -1, 'x', gui_playq_song_select },
475 { -1, 'z', playq_cursong_prev },
476 { -1, '[', gui_playq_song_move_up },
477 { -1, ']', gui_playq_song_move_down },
478 { -1, '{', gui_playq_song_move_head },
479 { -1, '}', gui_playq_song_move_tail },
480 { -1, '\t', gui_input_switchfocus },
481 { -1, CTRL('W'), gui_input_switchfocus },
482 { -1, '/', gui_input_search },
483 { -1, 'n', gui_input_searchnext },
484 { -1, KEY_LEFT, gui_browser_dir_parent },
485 { -1, KEY_RIGHT, gui_browser_dir_enter },
487 /* Keyboard bindings for the file browser */
488 { GUI_FOCUS_BROWSER, ' ', gui_browser_cursor_pagedown },
489 { GUI_FOCUS_BROWSER, 'F', gui_browser_gotofolder },
490 { GUI_FOCUS_BROWSER, 'f', gui_browser_fullpath },
491 { GUI_FOCUS_BROWSER, 'G', gui_browser_cursor_tail },
492 { GUI_FOCUS_BROWSER, 'g', gui_browser_cursor_head },
493 { GUI_FOCUS_BROWSER, 'j', gui_browser_cursor_down },
494 { GUI_FOCUS_BROWSER, 'k', gui_browser_cursor_up },
495 { GUI_FOCUS_BROWSER, CTRL('B'), gui_browser_cursor_pageup },
496 { GUI_FOCUS_BROWSER, CTRL('F'), gui_browser_cursor_pagedown },
497 { GUI_FOCUS_BROWSER, KEY_DOWN, gui_browser_cursor_down },
498 { GUI_FOCUS_BROWSER, KEY_END, gui_browser_cursor_tail },
499 { GUI_FOCUS_BROWSER, KEY_HOME, gui_browser_cursor_head },
500 { GUI_FOCUS_BROWSER, KEY_NPAGE, gui_browser_cursor_pagedown },
501 { GUI_FOCUS_BROWSER, KEY_PPAGE, gui_browser_cursor_pageup },
502 { GUI_FOCUS_BROWSER, KEY_UP, gui_browser_cursor_up },
504 /* Keyboard bindings for the playlist */
505 { GUI_FOCUS_PLAYQ, ' ', gui_playq_cursor_pagedown },
506 { GUI_FOCUS_PLAYQ, 'F', gui_playq_gotofolder },
507 { GUI_FOCUS_PLAYQ, 'f', gui_playq_fullpath },
508 { GUI_FOCUS_PLAYQ, 'G', gui_playq_cursor_tail },
509 { GUI_FOCUS_PLAYQ, 'g', gui_playq_cursor_head },
510 { GUI_FOCUS_PLAYQ, 'j', gui_playq_cursor_down },
511 { GUI_FOCUS_PLAYQ, 'k', gui_playq_cursor_up },
512 { GUI_FOCUS_PLAYQ, CTRL('B'), gui_playq_cursor_pageup },
513 { GUI_FOCUS_PLAYQ, CTRL('F'), gui_playq_cursor_pagedown },
514 { GUI_FOCUS_PLAYQ, KEY_DOWN, gui_playq_cursor_down },
515 { GUI_FOCUS_PLAYQ, KEY_END, gui_playq_cursor_tail },
516 { GUI_FOCUS_PLAYQ, KEY_HOME, gui_playq_cursor_head },
517 { GUI_FOCUS_PLAYQ, KEY_NPAGE, gui_playq_cursor_pagedown },
518 { GUI_FOCUS_PLAYQ, KEY_PPAGE, gui_playq_cursor_pageup },
519 { GUI_FOCUS_PLAYQ, KEY_UP, gui_playq_cursor_up },
522 * @brief Amount of keybindings.
524 #define NUM_BINDINGS (sizeof kbdbindings / sizeof(struct gui_binding))
526 void
527 gui_input_sigmask(void)
529 #ifdef G_THREADS_IMPL_POSIX
530 sigset_t sset;
532 sigemptyset(&sset);
533 sigaddset(&sset, SIGHUP);
534 sigaddset(&sset, SIGINT);
535 sigaddset(&sset, SIGPIPE);
536 sigaddset(&sset, SIGQUIT);
537 sigaddset(&sset, SIGTERM);
538 #ifdef SIGWINCH
539 sigaddset(&sset, SIGWINCH);
540 #endif /* SIGWINCH */
541 pthread_sigmask(SIG_BLOCK, &sset, NULL);
542 #endif /* G_THREADS_IMPL_POSIX */
545 #ifdef G_OS_UNIX
547 * @brief Handler of all incoming signals with a custom action.
549 static void
550 gui_input_sighandler(int signal)
552 if (shutting_down)
553 return;
555 switch (signal) {
556 case SIGHUP:
557 case SIGINT:
558 case SIGPIPE:
559 case SIGQUIT:
560 case SIGTERM:
561 gui_input_quit();
562 g_assert_not_reached();
565 #endif /* G_OS_UNIX */
567 void
568 gui_input_loop(void)
570 int ch;
571 unsigned int i;
573 #ifdef G_OS_UNIX
574 signal(SIGHUP, gui_input_sighandler);
575 signal(SIGINT, gui_input_sighandler);
576 signal(SIGPIPE, gui_input_sighandler);
577 signal(SIGQUIT, gui_input_sighandler);
578 signal(SIGTERM, gui_input_sighandler);
579 #endif /* G_OS_UNIX */
581 for (;;) {
582 ch = gui_input_getch();
583 gui_msgbar_flush();
585 for (i = 0; i < NUM_BINDINGS; i++) {
586 /* Let's see if the button matches */
587 if (kbdbindings[i].input != ch ||
588 (kbdbindings[i].focus != -1 &&
589 kbdbindings[i].focus != gui_input_curfocus))
590 continue;
592 #ifdef BUILD_DBUS
593 dbus_lock();
594 kbdbindings[i].func();
595 dbus_unlock();
596 #else /* !BUILD_DBUS */
597 kbdbindings[i].func();
598 #endif /* BUILD_DBUS */
599 break;
602 gui_draw_done();
607 gui_input_askyesno(const char *question)
609 char *msg, input;
610 const char *yes, *no;
611 int ret;
613 /* Skip the question if the user really wants so */
614 if (!config_getopt_bool("gui.input.confirm"))
615 return (0);
617 yes = _("yes");
618 no = _("no");
620 /* Print the question on screen */
621 msg = g_strdup_printf("%s ([%s]/%s): ", question, yes, no);
622 gui_msgbar_ask(msg);
623 g_free(msg);
625 for (;;) {
626 input = gui_input_getch();
628 #ifdef BUILD_NLS
629 /* Localized yes/no buttons */
630 if (input == yes[0]) {
631 ret = 0;
632 goto done;
633 } else if (input == no[0]) {
634 ret = -1;
635 goto done;
637 #endif /* BUILD_NLS */
639 /* Default y/n behaviour */
640 switch (input) {
641 case 'y':
642 case 'Y':
643 case '\r':
644 ret = 0;
645 goto done;
646 case CTRL('['):
647 case 'n':
648 case 'N':
649 case CTRL('C'):
650 ret = -1;
651 goto done;
654 done:
655 gui_msgbar_flush();
656 return (ret);
660 * @brief Find the offset to where a string should be trimmed to remove
661 * one word or special character sequence, including trailing
662 * whitespace.
664 static int
665 gui_input_trimword(GString *gs)
667 const char *end;
669 /* Last character */
670 end = (gs->str + gs->len) - 1;
672 /* Trim as much trailing whitespace as possible */
673 for (;;) {
674 if (end < gs->str) return (0);
675 if (!isspace(*end)) break;
676 end--;
679 if (isalnum(*end)) {
680 /* Trim alphanumerics */
681 do {
682 if (--end < gs->str) return (0);
683 } while (isalnum(*end));
684 } else {
685 /* Trim special characters */
686 do {
687 if (--end < gs->str) return (0);
688 } while (!isalnum(*end) && !isspace(*end));
691 return (end - gs->str) + 1;
694 char *
695 gui_input_askstring(const char *question, const char *defstr,
696 int (*validator)(const char *str, char c))
698 GString *msg;
699 unsigned int origlen, newlen;
700 int c, clearfirst = 0;
701 char *ret = NULL;
702 const char *vstr;
704 msg = g_string_new(question);
705 g_string_append(msg, ": ");
706 origlen = msg->len;
707 if (defstr != NULL) {
708 g_string_append(msg, defstr);
709 clearfirst = 1;
712 for(;;) {
713 gui_msgbar_ask(msg->str);
715 switch (c = gui_input_getch()) {
716 case '\r':
717 goto done;
718 case KEY_BACKSPACE:
719 clearfirst = 0;
720 if (msg->len > origlen) {
721 /* Prompt has contents */
722 g_string_truncate(msg, msg->len - 1);
724 break;
725 case CTRL('C'):
726 case CTRL('['):
727 /* Just empty the return */
728 g_string_truncate(msg, origlen);
729 goto done;
730 case CTRL('U'):
731 g_string_truncate(msg, origlen);
732 break;
733 case CTRL('W'):
734 clearfirst = 0;
735 newlen = gui_input_trimword(msg);
736 g_string_truncate(msg, MAX(newlen, origlen));
737 break;
738 default:
739 /* Control characters are not allowed */
740 if (g_ascii_iscntrl(c))
741 break;
743 if (validator != NULL) {
744 vstr = clearfirst ? "" : msg->str + origlen;
745 if (validator(vstr, c) != 0)
746 break;
748 if (clearfirst) {
749 g_string_truncate(msg, origlen);
750 clearfirst = 0;
752 g_string_append_c(msg, c);
756 done:
757 gui_msgbar_flush();
759 /* Only return a string when there are contents */
760 if (msg->len > origlen)
761 ret = g_strdup(msg->str + origlen);
763 g_string_free(msg, TRUE);
764 return ret;