Convert album_artist tag to albumartist
[cmus.git] / ui_curses.c
blob031196ef7ed3d97140d5d0309f2cf7915f554b4c
1 /*
2 * Copyright 2004-2005 Timo Hirvonen
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17 * 02111-1307, USA.
20 #include "ui_curses.h"
21 #include "cmdline.h"
22 #include "search_mode.h"
23 #include "command_mode.h"
24 #include "options.h"
25 #include "play_queue.h"
26 #include "browser.h"
27 #include "filters.h"
28 #include "cmus.h"
29 #include "player.h"
30 #include "utils.h"
31 #include "lib.h"
32 #include "pl.h"
33 #include "xmalloc.h"
34 #include "xstrjoin.h"
35 #include "window.h"
36 #include "format_print.h"
37 #include "misc.h"
38 #include "prog.h"
39 #include "uchar.h"
40 #include "spawn.h"
41 #include "server.h"
42 #include "keys.h"
43 #include "debug.h"
44 #include "help.h"
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <stdio.h>
49 #include <errno.h>
50 #include <sys/ioctl.h>
51 #include <ctype.h>
52 #include <dirent.h>
53 #include <locale.h>
54 #include <langinfo.h>
55 #include <iconv.h>
56 #include <signal.h>
57 #include <stdarg.h>
59 #if defined(__sun__) || defined(__CYGWIN__)
60 /* TIOCGWINSZ */
61 #include <termios.h>
62 #include <ncurses.h>
63 #else
64 #include <curses.h>
65 #endif
67 /* defined in <term.h> but without const */
68 char *tgetstr(const char *id, char **area);
69 char *tgoto(const char *cap, int col, int row);
71 /* globals. documented in ui_curses.h */
73 int ui_initialized = 0;
74 enum ui_input_mode input_mode = NORMAL_MODE;
75 int cur_view = TREE_VIEW;
76 struct searchable *searchable;
78 /* display parse errors? (command line) */
79 int display_errors = 0;
81 char *lib_filename = NULL;
82 char *pl_filename = NULL;
84 /* ------------------------------------------------------------------------- */
86 /* currently playing file */
87 static struct track_info *cur_track_info = NULL;
89 static int running = 1;
90 static char *lib_autosave_filename;
91 static char *pl_autosave_filename;
93 /* shown error message and time stamp
94 * error is cleared if it is older than 3s and key was pressed
96 static char error_buf[512];
97 static time_t error_time = 0;
98 /* info messages are displayed in different color */
99 static int msg_is_error;
100 static int error_count = 0;
102 static char *server_address = NULL;
104 static char *charset = NULL;
105 static char print_buffer[512];
107 /* destination buffer for utf8_encode and utf8_decode */
108 static char conv_buffer[512];
110 #define print_buffer_size (sizeof(print_buffer) - 1)
111 static int using_utf8;
113 static const char *t_ts;
114 static const char *t_fs;
116 static int tree_win_x = 0;
117 static int tree_win_y = 0;
118 static int tree_win_w = 0;
120 static int track_win_x = 0;
121 static int track_win_y = 0;
122 static int track_win_w = 0;
124 static int cursor_x;
125 static int cursor_y;
127 enum {
128 CURSED_WIN,
129 CURSED_WIN_CUR,
130 CURSED_WIN_SEL,
131 CURSED_WIN_SEL_CUR,
133 CURSED_WIN_ACTIVE,
134 CURSED_WIN_ACTIVE_CUR,
135 CURSED_WIN_ACTIVE_SEL,
136 CURSED_WIN_ACTIVE_SEL_CUR,
138 CURSED_SEPARATOR,
139 CURSED_WIN_TITLE,
140 CURSED_COMMANDLINE,
141 CURSED_STATUSLINE,
143 CURSED_TITLELINE,
144 CURSED_DIR,
145 CURSED_ERROR,
146 CURSED_INFO,
148 NR_CURSED
151 static unsigned char cursed_to_bg_idx[NR_CURSED] = {
152 COLOR_WIN_BG,
153 COLOR_WIN_BG,
154 COLOR_WIN_INACTIVE_SEL_BG,
155 COLOR_WIN_INACTIVE_CUR_SEL_BG,
157 COLOR_WIN_BG,
158 COLOR_WIN_BG,
159 COLOR_WIN_SEL_BG,
160 COLOR_WIN_CUR_SEL_BG,
162 COLOR_WIN_BG,
163 COLOR_WIN_TITLE_BG,
164 COLOR_CMDLINE_BG,
165 COLOR_STATUSLINE_BG,
167 COLOR_TITLELINE_BG,
168 COLOR_WIN_BG,
169 COLOR_CMDLINE_BG,
170 COLOR_CMDLINE_BG
173 static unsigned char cursed_to_fg_idx[NR_CURSED] = {
174 COLOR_WIN_FG,
175 COLOR_WIN_CUR,
176 COLOR_WIN_INACTIVE_SEL_FG,
177 COLOR_WIN_INACTIVE_CUR_SEL_FG,
179 COLOR_WIN_FG,
180 COLOR_WIN_CUR,
181 COLOR_WIN_SEL_FG,
182 COLOR_WIN_CUR_SEL_FG,
184 COLOR_SEPARATOR,
185 COLOR_WIN_TITLE_FG,
186 COLOR_CMDLINE_FG,
187 COLOR_STATUSLINE_FG,
189 COLOR_TITLELINE_FG,
190 COLOR_WIN_DIR,
191 COLOR_ERROR,
192 COLOR_INFO
195 /* index is CURSED_*, value is fucking color pair */
196 static int pairs[NR_CURSED];
198 enum {
199 TF_ARTIST,
200 TF_ALBUM,
201 TF_DISC,
202 TF_TRACK,
203 TF_TITLE,
204 TF_YEAR,
205 TF_GENRE,
206 TF_DURATION,
207 TF_PATHFILE,
208 TF_FILE,
209 NR_TFS
212 static struct format_option track_fopts[NR_TFS + 1] = {
213 DEF_FO_STR('a'),
214 DEF_FO_STR('l'),
215 DEF_FO_INT('D'),
216 DEF_FO_INT('n'),
217 DEF_FO_STR('t'),
218 DEF_FO_STR('y'),
219 DEF_FO_STR('g'),
220 DEF_FO_TIME('d'),
221 DEF_FO_STR('f'),
222 DEF_FO_STR('F'),
223 DEF_FO_END
226 enum {
227 SF_STATUS,
228 SF_POSITION,
229 SF_DURATION,
230 SF_TOTAL,
231 SF_VOLUME,
232 SF_LVOLUME,
233 SF_RVOLUME,
234 SF_BUFFER,
235 SF_REPEAT,
236 SF_CONTINUE,
237 SF_SHUFFLE,
238 SF_PLAYLISTMODE,
239 NR_SFS
242 static struct format_option status_fopts[NR_SFS + 1] = {
243 DEF_FO_STR('s'),
244 DEF_FO_TIME('p'),
245 DEF_FO_TIME('d'),
246 DEF_FO_TIME('t'),
247 DEF_FO_INT('v'),
248 DEF_FO_INT('l'),
249 DEF_FO_INT('r'),
250 DEF_FO_INT('b'),
251 DEF_FO_STR('R'),
252 DEF_FO_STR('C'),
253 DEF_FO_STR('S'),
254 DEF_FO_STR('L'),
255 DEF_FO_END
258 static void utf8_encode(const char *buffer)
260 static iconv_t cd = (iconv_t)-1;
261 size_t is, os;
262 const char *i;
263 char *o;
264 int rc;
266 if (cd == (iconv_t)-1) {
267 d_print("iconv_open(UTF-8, %s)\n", charset);
268 cd = iconv_open("UTF-8", charset);
269 if (cd == (iconv_t)-1) {
270 d_print("iconv_open failed: %s\n", strerror(errno));
271 return;
274 i = buffer;
275 o = conv_buffer;
276 is = strlen(i);
277 os = sizeof(conv_buffer) - 1;
278 rc = iconv(cd, (void *)&i, &is, &o, &os);
279 *o = 0;
280 if (rc == -1) {
281 d_print("iconv failed: %s\n", strerror(errno));
282 return;
286 static void utf8_decode(const char *buffer)
288 static iconv_t cd = (iconv_t)-1;
289 size_t is, os;
290 const char *i;
291 char *o;
292 int rc;
294 if (cd == (iconv_t)-1) {
295 d_print("iconv_open(%s, UTF-8)\n", charset);
296 cd = iconv_open(charset, "UTF-8");
297 if (cd == (iconv_t)-1) {
298 d_print("iconv_open failed: %s\n", strerror(errno));
299 return;
302 i = buffer;
303 o = conv_buffer;
304 is = strlen(i);
305 os = sizeof(conv_buffer) - 1;
306 rc = iconv(cd, (void *)&i, &is, &o, &os);
307 *o = 0;
308 if (rc == -1) {
309 d_print("iconv failed: %s\n", strerror(errno));
310 return;
314 /* screen updates {{{ */
316 static void dump_print_buffer(int row, int col)
318 if (using_utf8) {
319 mvaddstr(row, col, print_buffer);
320 } else {
321 utf8_decode(print_buffer);
322 mvaddstr(row, col, conv_buffer);
326 /* print @str into @buf
328 * if @str is shorter than @width pad with spaces
329 * if @str is wider than @width truncate and add "..."
331 static int format_str(char *buf, const char *str, int width)
333 int s = 0, d = 0, ellipsis_pos = 0, cut_double_width = 0;
335 while (1) {
336 uchar u;
337 int w;
339 u_get_char(str, &s, &u);
340 if (u == 0) {
341 memset(buf + d, ' ', width);
342 d += width;
343 break;
346 w = u_char_width(u);
347 if (width == 3)
348 ellipsis_pos = d;
349 if (width == 4 && w == 2) {
350 /* can't cut double-width char */
351 ellipsis_pos = d + 1;
352 cut_double_width = 1;
355 width -= w;
356 if (width < 0) {
357 /* does not fit */
358 d = ellipsis_pos;
359 if (cut_double_width) {
360 /* first half of the double-width char */
361 buf[d - 1] = ' ';
363 buf[d++] = '.';
364 buf[d++] = '.';
365 buf[d++] = '.';
366 break;
368 u_set_char(buf, &d, u);
370 return d;
373 static void sprint(int row, int col, const char *str, int width)
375 int pos = 0;
377 print_buffer[pos++] = ' ';
378 pos += format_str(print_buffer + pos, str, width - 2);
379 print_buffer[pos++] = ' ';
380 print_buffer[pos] = 0;
381 dump_print_buffer(row, col);
384 static void sprint_ascii(int row, int col, const char *str, int len)
386 int l;
388 l = strlen(str);
389 len -= 2;
391 print_buffer[0] = ' ';
392 if (l > len) {
393 memcpy(print_buffer + 1, str, len - 3);
394 print_buffer[len - 2] = '.';
395 print_buffer[len - 1] = '.';
396 print_buffer[len - 0] = '.';
397 } else {
398 memcpy(print_buffer + 1, str, l);
399 memset(print_buffer + 1 + l, ' ', len - l);
401 print_buffer[len + 1] = ' ';
402 print_buffer[len + 2] = 0;
403 mvaddstr(row, col, print_buffer);
406 static void print_tree(struct window *win, int row, struct iter *iter)
408 const char *str;
409 struct artist *artist;
410 struct album *album;
411 struct iter sel;
412 int current, selected, active, pos;
414 artist = iter_to_artist(iter);
415 album = iter_to_album(iter);
416 current = 0;
417 if (lib_cur_track) {
418 if (album) {
419 current = CUR_ALBUM == album;
420 } else {
421 current = CUR_ARTIST == artist;
424 window_get_sel(win, &sel);
425 selected = iters_equal(iter, &sel);
426 active = lib_cur_win == lib_tree_win;
427 bkgdset(pairs[(active << 2) | (selected << 1) | current]);
429 if (active && selected) {
430 cursor_x = 0;
431 cursor_y = 1 + row;
434 pos = 0;
435 print_buffer[pos++] = ' ';
436 str = artist->name;
437 if (album) {
438 print_buffer[pos++] = ' ';
439 print_buffer[pos++] = ' ';
440 str = album->name;
442 pos += format_str(print_buffer + pos, str, tree_win_w - pos - 1);
443 print_buffer[pos++] = ' ';
444 print_buffer[pos++] = 0;
445 dump_print_buffer(tree_win_y + row + 1, tree_win_x);
448 static inline void fopt_set_str(struct format_option *fopt, const char *str)
450 BUG_ON(fopt->type != FO_STR);
451 if (str) {
452 fopt->fo_str = str;
453 fopt->empty = 0;
454 } else {
455 fopt->empty = 1;
459 static inline void fopt_set_int(struct format_option *fopt, int value, int empty)
461 BUG_ON(fopt->type != FO_INT);
462 fopt->fo_int = value;
463 fopt->empty = empty;
466 static inline void fopt_set_time(struct format_option *fopt, int value, int empty)
468 BUG_ON(fopt->type != FO_TIME);
469 fopt->fo_time = value;
470 fopt->empty = empty;
473 static void fill_track_fopts_track_info(struct track_info *info)
475 char *filename;
476 int num, disc;
478 if (using_utf8) {
479 filename = info->filename;
480 } else {
481 utf8_encode(info->filename);
482 filename = conv_buffer;
484 disc = comments_get_int(info->comments, "discnumber");
485 num = comments_get_int(info->comments, "tracknumber");
487 fopt_set_str(&track_fopts[TF_ARTIST], comments_get_val(info->comments, "artist"));
488 fopt_set_str(&track_fopts[TF_ALBUM], comments_get_val(info->comments, "album"));
489 fopt_set_int(&track_fopts[TF_DISC], disc, disc == -1);
490 fopt_set_int(&track_fopts[TF_TRACK], num, num == -1);
491 fopt_set_str(&track_fopts[TF_TITLE], comments_get_val(info->comments, "title"));
492 fopt_set_str(&track_fopts[TF_YEAR], comments_get_val(info->comments, "date"));
493 fopt_set_str(&track_fopts[TF_GENRE], comments_get_val(info->comments, "genre"));
494 fopt_set_time(&track_fopts[TF_DURATION], info->duration, info->duration == -1);
495 fopt_set_str(&track_fopts[TF_PATHFILE], filename);
496 if (is_url(info->filename)) {
497 fopt_set_str(&track_fopts[TF_FILE], filename);
498 } else {
499 const char *f;
501 f = strrchr(filename, '/');
502 if (f) {
503 fopt_set_str(&track_fopts[TF_FILE], f + 1);
504 } else {
505 fopt_set_str(&track_fopts[TF_FILE], filename);
510 static void print_track(struct window *win, int row, struct iter *iter)
512 struct tree_track *track;
513 struct iter sel;
514 int current, selected, active;
516 track = iter_to_tree_track(iter);
517 current = lib_cur_track == track;
518 window_get_sel(win, &sel);
519 selected = iters_equal(iter, &sel);
520 active = lib_cur_win == lib_track_win;
521 bkgdset(pairs[(active << 2) | (selected << 1) | current]);
523 if (active && selected) {
524 cursor_x = track_win_x;
525 cursor_y = 1 + row;
528 fill_track_fopts_track_info(tree_track_info(track));
530 if (track_info_has_tag(tree_track_info(track))) {
531 format_print(print_buffer, track_win_w, track_win_format, track_fopts);
532 } else {
533 format_print(print_buffer, track_win_w, track_win_alt_format, track_fopts);
535 dump_print_buffer(track_win_y + row + 1, track_win_x);
538 /* used by print_editable only */
539 static struct simple_track *current_track;
541 static void print_editable(struct window *win, int row, struct iter *iter)
543 struct simple_track *track;
544 struct iter sel;
545 int current, selected, active;
547 track = iter_to_simple_track(iter);
548 current = current_track == track;
549 window_get_sel(win, &sel);
550 selected = iters_equal(iter, &sel);
552 if (selected) {
553 cursor_x = 0;
554 cursor_y = 1 + row;
557 active = 1;
558 if (!selected && track->marked) {
559 selected = 1;
560 active = 0;
563 bkgdset(pairs[(active << 2) | (selected << 1) | current]);
565 fill_track_fopts_track_info(track->info);
567 if (track_info_has_tag(track->info)) {
568 format_print(print_buffer, COLS, list_win_format, track_fopts);
569 } else {
570 format_print(print_buffer, COLS, list_win_alt_format, track_fopts);
572 dump_print_buffer(row + 1, 0);
575 static void print_browser(struct window *win, int row, struct iter *iter)
577 struct browser_entry *e;
578 struct iter sel;
579 int selected;
581 e = iter_to_browser_entry(iter);
582 window_get_sel(win, &sel);
583 selected = iters_equal(iter, &sel);
584 if (selected) {
585 int active = 1;
586 int current = 0;
588 bkgdset(pairs[(active << 2) | (selected << 1) | current]);
589 } else {
590 if (e->type == BROWSER_ENTRY_DIR) {
591 bkgdset(pairs[CURSED_DIR]);
592 } else {
593 bkgdset(pairs[CURSED_WIN]);
597 if (selected) {
598 cursor_x = 0;
599 cursor_y = 1 + row;
602 /* file name encoding == terminal encoding. no need to convert */
603 if (using_utf8) {
604 sprint(row + 1, 0, e->name, COLS);
605 } else {
606 sprint_ascii(row + 1, 0, e->name, COLS);
610 static void print_filter(struct window *win, int row, struct iter *iter)
612 char buf[256];
613 struct filter_entry *e = iter_to_filter_entry(iter);
614 struct iter sel;
615 /* window active? */
616 int active = 1;
617 /* row selected? */
618 int selected;
619 /* is the filter currently active? */
620 int current = !!e->act_stat;
621 const char stat_chars[3] = " *!";
622 int ch1, ch2, ch3, pos;
624 window_get_sel(win, &sel);
625 selected = iters_equal(iter, &sel);
626 bkgdset(pairs[(active << 2) | (selected << 1) | current]);
628 if (selected) {
629 cursor_x = 0;
630 cursor_y = 1 + row;
633 ch1 = ' ';
634 ch3 = ' ';
635 if (e->sel_stat != e->act_stat) {
636 ch1 = '[';
637 ch3 = ']';
639 ch2 = stat_chars[e->sel_stat];
640 snprintf(buf, sizeof(buf), "%c%c%c%-15s %s", ch1, ch2, ch3, e->name, e->filter);
641 pos = format_str(print_buffer, buf, COLS - 1);
642 print_buffer[pos++] = ' ';
643 print_buffer[pos] = 0;
644 dump_print_buffer(row + 1, 0);
647 static void print_help(struct window *win, int row, struct iter *iter)
649 struct iter sel;
650 int selected;
651 int pos;
652 char buf[512];
653 const struct help_entry *e = iter_to_help_entry(iter);
654 const struct cmus_opt *opt;
656 window_get_sel(win, &sel);
657 selected = iters_equal(iter, &sel);
658 bkgdset(pairs[selected << 1]);
660 if (selected) {
661 cursor_x = 0;
662 cursor_y = 1 + row;
665 switch (e->type) {
666 case HE_TEXT:
667 snprintf(buf, sizeof(buf), " %s", e->text);
668 break;
669 case HE_BOUND:
670 snprintf(buf, sizeof(buf), " %-8s %-14s %s",
671 key_context_names[e->binding->ctx],
672 e->binding->key->name,
673 e->binding->cmd);
674 break;
675 case HE_UNBOUND:
676 snprintf(buf, sizeof(buf), " %s", e->command->name);
677 break;
678 case HE_OPTION:
679 opt = e->option;
680 snprintf(buf, sizeof(buf), " %-29s ", opt->name);
681 opt->get(opt->id, buf + strlen(buf));
682 break;
684 pos = format_str(print_buffer, buf, COLS - 1);
685 print_buffer[pos++] = ' ';
686 print_buffer[pos] = 0;
687 dump_print_buffer(row + 1, 0);
690 static void update_window(struct window *win, int x, int y, int w, const char *title,
691 void (*print)(struct window *, int, struct iter *))
693 struct iter iter;
694 int nr_rows;
695 int c, i;
697 win->changed = 0;
699 bkgdset(pairs[CURSED_WIN_TITLE]);
700 c = snprintf(print_buffer, w + 1, " %s", title);
701 if (c > w)
702 c = w;
703 memset(print_buffer + c, ' ', w - c + 1);
704 print_buffer[w] = 0;
705 dump_print_buffer(y, x);
706 nr_rows = window_get_nr_rows(win);
707 i = 0;
708 if (window_get_top(win, &iter)) {
709 while (i < nr_rows) {
710 print(win, i, &iter);
711 i++;
712 if (!window_get_next(win, &iter))
713 break;
717 bkgdset(pairs[0]);
718 memset(print_buffer, ' ', w);
719 print_buffer[w] = 0;
720 while (i < nr_rows) {
721 dump_print_buffer(y + i + 1, x);
722 i++;
726 static void update_tree_window(void)
728 update_window(lib_tree_win, tree_win_x, tree_win_y,
729 tree_win_w, "Artist / Album", print_tree);
732 static void update_track_window(void)
734 char title[512];
736 /* it doesn't matter what format options we use because the format
737 * string does not contain any format charaters */
738 format_print(title, track_win_w - 2, "Track%=Library", track_fopts);
739 update_window(lib_track_win, track_win_x, track_win_y,
740 track_win_w, title, print_track);
743 static const char *pretty(const char *path)
745 static int home_len = -1;
746 static char buf[256];
748 if (home_len == -1)
749 home_len = strlen(home_dir);
751 if (strncmp(path, home_dir, home_len) || path[home_len] != '/')
752 return path;
754 buf[0] = '~';
755 strcpy(buf + 1, path + home_len);
756 return buf;
759 static const char * const sorted_names[2] = { "", "sorted by " };
761 static void update_editable_window(struct editable *e, const char *title, const char *filename)
763 char buf[512];
764 int pos;
766 if (filename) {
767 if (using_utf8) {
768 /* already UTF-8 */
769 } else {
770 utf8_encode(filename);
771 filename = conv_buffer;
773 snprintf(buf, sizeof(buf), "%s %s - %d tracks", title,
774 pretty(filename), e->nr_tracks);
775 } else {
776 snprintf(buf, sizeof(buf), "%s - %d tracks", title, e->nr_tracks);
779 if (e->nr_marked) {
780 pos = strlen(buf);
781 snprintf(buf + pos, sizeof(buf) - pos, " (%d marked)", e->nr_marked);
783 pos = strlen(buf);
784 snprintf(buf + pos, sizeof(buf) - pos, " %s%s",
785 sorted_names[e->sort_str[0] != 0], e->sort_str);
787 update_window(e->win, 0, 0, COLS, buf, &print_editable);
790 static void update_sorted_window(void)
792 current_track = (struct simple_track *)lib_cur_track;
793 update_editable_window(&lib_editable, "Library", lib_filename);
796 static void update_pl_window(void)
798 current_track = pl_cur_track;
799 update_editable_window(&pl_editable, "Playlist", pl_filename);
802 static void update_play_queue_window(void)
804 current_track = NULL;
805 update_editable_window(&pq_editable, "Play Queue", NULL);
808 static void update_browser_window(void)
810 char title[512];
811 char *dirname;
813 if (using_utf8) {
814 /* already UTF-8 */
815 dirname = browser_dir;
816 } else {
817 utf8_encode(browser_dir);
818 dirname = conv_buffer;
820 snprintf(title, sizeof(title), "Browser - %s", dirname);
821 update_window(browser_win, 0, 0, COLS, title, print_browser);
824 static void update_filters_window(void)
826 update_window(filters_win, 0, 0, COLS, "Library Filters", print_filter);
829 static void update_help_window(void)
831 update_window(help_win, 0, 0, COLS, "Settings", print_help);
834 static void draw_separator(void)
836 int row;
838 bkgdset(pairs[CURSED_WIN_TITLE]);
839 mvaddch(0, tree_win_w, ' ');
840 bkgdset(pairs[CURSED_SEPARATOR]);
841 for (row = 1; row < LINES - 3; row++)
842 mvaddch(row, tree_win_w, ACS_VLINE);
845 static void do_update_view(int full)
847 cursor_x = -1;
848 cursor_y = -1;
850 switch (cur_view) {
851 case TREE_VIEW:
852 editable_lock();
853 if (full || lib_tree_win->changed)
854 update_tree_window();
855 if (full || lib_track_win->changed)
856 update_track_window();
857 editable_unlock();
858 draw_separator();
859 break;
860 case SORTED_VIEW:
861 editable_lock();
862 update_sorted_window();
863 editable_unlock();
864 break;
865 case PLAYLIST_VIEW:
866 editable_lock();
867 update_pl_window();
868 editable_unlock();
869 break;
870 case QUEUE_VIEW:
871 editable_lock();
872 update_play_queue_window();
873 editable_unlock();
874 break;
875 case BROWSER_VIEW:
876 update_browser_window();
877 break;
878 case FILTERS_VIEW:
879 update_filters_window();
880 break;
881 case HELP_VIEW:
882 update_help_window();
883 break;
887 static void do_update_statusline(void)
889 static const char *status_strs[] = { ".", ">", "|" };
890 static const char *cont_strs[] = { " ", "C" };
891 static const char *repeat_strs[] = { " ", "R" };
892 static const char *shuffle_strs[] = { " ", "S" };
893 int buffer_fill, vol, vol_left, vol_right;
894 int duration = -1;
895 char *msg;
896 char format[80];
898 editable_lock();
899 fopt_set_time(&status_fopts[SF_TOTAL], play_library ? lib_editable.total_time :
900 pl_editable.total_time, 0);
901 editable_unlock();
903 fopt_set_str(&status_fopts[SF_REPEAT], repeat_strs[repeat]);
904 fopt_set_str(&status_fopts[SF_SHUFFLE], shuffle_strs[shuffle]);
905 fopt_set_str(&status_fopts[SF_PLAYLISTMODE], aaa_mode_names[aaa_mode]);
907 if (cur_track_info)
908 duration = cur_track_info->duration;
910 player_info_lock();
912 if (volume_max == 0) {
913 vol_left = vol_right = vol = -1;
914 } else {
915 vol_left = scale_to_percentage(player_info.vol_left, volume_max);
916 vol_right = scale_to_percentage(player_info.vol_right, volume_max);
917 vol = (vol_left + vol_right + 1) / 2;
919 buffer_fill = scale_to_percentage(player_info.buffer_fill, player_info.buffer_size);
921 fopt_set_str(&status_fopts[SF_STATUS], status_strs[player_info.status]);
923 if (show_remaining_time && duration != -1) {
924 fopt_set_time(&status_fopts[SF_POSITION], player_info.pos - duration, 0);
925 } else {
926 fopt_set_time(&status_fopts[SF_POSITION], player_info.pos, 0);
929 fopt_set_time(&status_fopts[SF_DURATION], duration, 0);
930 fopt_set_int(&status_fopts[SF_VOLUME], vol, 0);
931 fopt_set_int(&status_fopts[SF_LVOLUME], vol_left, 0);
932 fopt_set_int(&status_fopts[SF_RVOLUME], vol_right, 0);
933 fopt_set_int(&status_fopts[SF_BUFFER], buffer_fill, 0);
934 fopt_set_str(&status_fopts[SF_CONTINUE], cont_strs[player_cont]);
936 strcpy(format, " %s %p ");
937 if (duration != -1)
938 strcat(format, "/ %d ");
939 strcat(format, "- %t ");
940 if (volume_max != 0) {
941 if (player_info.vol_left != player_info.vol_right) {
942 strcat(format, "vol: %l,%r ");
943 } else {
944 strcat(format, "vol: %v ");
947 if (cur_track_info && is_url(cur_track_info->filename))
948 strcat(format, "buf: %b ");
949 strcat(format, "%=");
950 if (play_library) {
951 /* artist/album modes work only in lib */
952 if (shuffle) {
953 /* shuffle overrides sorted mode */
954 strcat(format, "%L from library");
955 } else if (play_sorted) {
956 strcat(format, "%L from sorted library");
957 } else {
958 strcat(format, "%L from library");
960 } else {
961 strcat(format, "playlist");
963 strcat(format, " | %1C%1R%1S ");
964 format_print(print_buffer, COLS, format, status_fopts);
966 msg = player_info.error_msg;
967 player_info.error_msg = NULL;
969 player_info_unlock();
971 bkgdset(pairs[CURSED_STATUSLINE]);
972 dump_print_buffer(LINES - 2, 0);
974 if (msg) {
975 error_msg("%s", msg);
976 free(msg);
980 static void dump_buffer(const char *buffer)
982 if (using_utf8) {
983 addstr(buffer);
984 } else {
985 utf8_decode(buffer);
986 addstr(conv_buffer);
990 static void do_update_commandline(void)
992 char *str;
993 int w, idx;
994 char ch;
996 move(LINES - 1, 0);
997 if (error_buf[0]) {
998 if (msg_is_error) {
999 bkgdset(pairs[CURSED_ERROR]);
1000 } else {
1001 bkgdset(pairs[CURSED_INFO]);
1003 addstr(error_buf);
1004 clrtoeol();
1005 return;
1007 bkgdset(pairs[CURSED_COMMANDLINE]);
1008 if (input_mode == NORMAL_MODE) {
1009 clrtoeol();
1010 return;
1013 str = cmdline.line;
1014 if (!using_utf8) {
1015 /* cmdline.line actually pretends to be UTF-8 but all non-ASCII
1016 * characters are invalid UTF-8 so it really is in locale's
1017 * encoding.
1019 * This code should be safe because cmdline.bpos ==
1020 * cmdline.cpos as every non-ASCII character is counted as one
1021 * invalid UTF-8 byte.
1023 * NOTE: This has nothing to do with widths of printed
1024 * characters. I.e. even if there were control characters
1025 * (displayed as <xx>) there would be no problem because bpos
1026 * still equals to cpos, I think.
1028 utf8_encode(cmdline.line);
1029 str = conv_buffer;
1032 /* COMMAND_MODE or SEARCH_MODE */
1033 w = u_str_width(str);
1034 ch = ':';
1035 if (input_mode == SEARCH_MODE)
1036 ch = search_direction == SEARCH_FORWARD ? '/' : '?';
1038 if (w <= COLS - 2) {
1039 addch(ch);
1040 idx = u_copy_chars(print_buffer, str, &w);
1041 print_buffer[idx] = 0;
1042 dump_buffer(print_buffer);
1043 clrtoeol();
1044 } else {
1045 /* keep cursor as far right as possible */
1046 int skip, width, cw;
1048 /* cursor pos (width, not chars. doesn't count the ':') */
1049 cw = u_str_nwidth(str, cmdline.cpos);
1051 skip = cw + 2 - COLS;
1052 if (skip > 0) {
1053 /* skip the ':' */
1054 skip--;
1056 /* skip rest (if any) */
1057 idx = u_skip_chars(str, &skip);
1059 width = COLS;
1060 idx = u_copy_chars(print_buffer, str + idx, &width);
1061 while (width < COLS) {
1062 /* cursor is at end of the buffer
1063 * print 1, 2 or 3 spaces
1065 * To clarify:
1067 * If the last _skipped_ character was double-width we may need
1068 * to print 2 spaces.
1070 * If the last _skipped_ character was invalid UTF-8 we may need
1071 * to print 3 spaces.
1073 print_buffer[idx++] = ' ';
1074 width++;
1076 print_buffer[idx] = 0;
1077 dump_buffer(print_buffer);
1078 } else {
1079 /* print ':' + COLS - 1 chars */
1080 addch(ch);
1081 width = COLS - 1;
1082 idx = u_copy_chars(print_buffer, str, &width);
1083 print_buffer[idx] = 0;
1084 dump_buffer(print_buffer);
1089 /* lock player_info! */
1090 static const char *get_stream_title(void)
1092 static char stream_title[255 * 16 + 1];
1093 char *ptr, *title;
1095 ptr = strstr(player_info.metadata, "StreamTitle='");
1096 if (ptr == NULL)
1097 return NULL;
1098 ptr += 13;
1099 title = ptr;
1100 while (*ptr) {
1101 if (*ptr == '\'' && *(ptr + 1) == ';') {
1102 memcpy(stream_title, title, ptr - title);
1103 stream_title[ptr - title] = 0;
1104 return stream_title;
1106 ptr++;
1108 return NULL;
1111 static void set_title(const char *title)
1113 if (!set_term_title)
1114 return;
1116 if (t_ts) {
1117 printf("%s%s%s", tgoto(t_ts, 0, 0), title, t_fs);
1118 fflush(stdout);
1122 static void do_update_titleline(void)
1124 bkgdset(pairs[CURSED_TITLELINE]);
1125 player_info_lock();
1126 if (cur_track_info) {
1127 int i, use_alt_format = 0;
1128 char *wtitle;
1130 fill_track_fopts_track_info(cur_track_info);
1131 if (is_url(cur_track_info->filename)) {
1132 const char *title = get_stream_title();
1134 if (title == NULL)
1135 use_alt_format = 1;
1136 fopt_set_str(&track_fopts[TF_TITLE], title);
1137 } else {
1138 use_alt_format = !track_info_has_tag(cur_track_info);
1141 if (use_alt_format) {
1142 format_print(print_buffer, COLS, current_alt_format, track_fopts);
1143 } else {
1144 format_print(print_buffer, COLS, current_format, track_fopts);
1146 dump_print_buffer(LINES - 3, 0);
1148 /* set window title */
1149 if (use_alt_format) {
1150 format_print(print_buffer, sizeof(print_buffer) - 1,
1151 window_title_alt_format, track_fopts);
1152 } else {
1153 format_print(print_buffer, sizeof(print_buffer) - 1,
1154 window_title_format, track_fopts);
1157 /* remove whitespace */
1158 i = strlen(print_buffer) - 1;
1159 while (i > 0 && print_buffer[i] == ' ')
1160 i--;
1161 print_buffer[i + 1] = 0;
1163 if (using_utf8) {
1164 wtitle = print_buffer;
1165 } else {
1166 utf8_decode(print_buffer);
1167 wtitle = conv_buffer;
1170 set_title(wtitle);
1171 } else {
1172 move(LINES - 3, 0);
1173 clrtoeol();
1175 set_title("cmus " VERSION);
1177 player_info_unlock();
1180 static int cmdline_cursor_column(void)
1182 char *str;
1183 int cw, skip, s;
1185 str = cmdline.line;
1186 if (!using_utf8) {
1187 /* see do_update_commandline */
1188 utf8_encode(cmdline.line);
1189 str = conv_buffer;
1192 /* width of the text in the buffer before cursor */
1193 cw = u_str_nwidth(str, cmdline.cpos);
1195 if (1 + cw < COLS) {
1196 /* whole line is visible */
1197 return 1 + cw;
1200 /* beginning of cmdline is not visible */
1202 /* check if the first visible char in cmdline would be halved
1203 * double-width character (or invalid byte <xx>) which is not possible.
1204 * we need to skip the whole character and move cursor to COLS - 2
1205 * column. */
1206 skip = cw + 2 - COLS;
1208 /* skip the ':' */
1209 skip--;
1211 /* skip rest */
1212 s = skip;
1213 u_skip_chars(str, &s);
1214 if (s > skip) {
1215 /* the last skipped char was double-width or <xx> */
1216 return COLS - 1 - (s - skip);
1218 return COLS - 1;
1221 static void post_update(void)
1223 /* refresh makes cursor visible at least for urxvt */
1224 if (input_mode == COMMAND_MODE || input_mode == SEARCH_MODE) {
1225 move(LINES - 1, cmdline_cursor_column());
1226 refresh();
1227 curs_set(1);
1228 } else {
1229 if (cursor_x >= 0) {
1230 move(cursor_y, cursor_x);
1231 } else {
1232 move(LINES - 1, 0);
1234 refresh();
1235 curs_set(0);
1239 void update_titleline(void)
1241 curs_set(0);
1242 do_update_titleline();
1243 post_update();
1246 void update_full(void)
1248 if (!ui_initialized)
1249 return;
1251 curs_set(0);
1253 do_update_view(1);
1254 do_update_titleline();
1255 do_update_statusline();
1256 do_update_commandline();
1258 post_update();
1261 static void update_commandline(void)
1263 curs_set(0);
1264 do_update_commandline();
1265 post_update();
1268 void update_statusline(void)
1270 if (!ui_initialized)
1271 return;
1273 curs_set(0);
1274 do_update_statusline();
1275 post_update();
1278 void info_msg(const char *format, ...)
1280 va_list ap;
1282 va_start(ap, format);
1283 vsnprintf(error_buf, sizeof(error_buf), format, ap);
1284 va_end(ap);
1286 msg_is_error = 0;
1288 update_commandline();
1291 void error_msg(const char *format, ...)
1293 va_list ap;
1295 if (!display_errors)
1296 return;
1298 strcpy(error_buf, "Error: ");
1299 va_start(ap, format);
1300 vsnprintf(error_buf + 7, sizeof(error_buf) - 7, format, ap);
1301 va_end(ap);
1303 msg_is_error = 1;
1304 error_count++;
1306 if (ui_initialized) {
1307 error_time = time(NULL);
1308 update_commandline();
1309 } else {
1310 warn("%s\n", error_buf);
1311 error_buf[0] = 0;
1315 int yes_no_query(const char *format, ...)
1317 char buffer[512];
1318 va_list ap;
1319 int ret = 0;
1321 va_start(ap, format);
1322 vsnprintf(buffer, sizeof(buffer), format, ap);
1323 va_end(ap);
1325 move(LINES - 1, 0);
1326 bkgdset(pairs[CURSED_INFO]);
1328 /* no need to convert buffer.
1329 * it is always encoded in the right charset (assuming filenames are
1330 * encoded in same charset as LC_CTYPE).
1333 addstr(buffer);
1334 clrtoeol();
1335 refresh();
1337 while (1) {
1338 int ch = getch();
1340 if (ch == ERR || ch == 0)
1341 continue;
1342 if (ch == 'y')
1343 ret = 1;
1344 break;
1346 update_commandline();
1347 return ret;
1350 void search_not_found(void)
1352 const char *what = "Track";
1354 if (search_restricted) {
1355 switch (cur_view) {
1356 case TREE_VIEW:
1357 what = "Artist/album";
1358 break;
1359 case SORTED_VIEW:
1360 case PLAYLIST_VIEW:
1361 case QUEUE_VIEW:
1362 what = "Title";
1363 break;
1364 case BROWSER_VIEW:
1365 what = "File/Directory";
1366 break;
1367 case FILTERS_VIEW:
1368 what = "Filter";
1369 break;
1370 case HELP_VIEW:
1371 what = "Binding/command/option";
1372 break;
1374 } else {
1375 switch (cur_view) {
1376 case TREE_VIEW:
1377 case SORTED_VIEW:
1378 case PLAYLIST_VIEW:
1379 case QUEUE_VIEW:
1380 what = "Track";
1381 break;
1382 case BROWSER_VIEW:
1383 what = "File/Directory";
1384 break;
1385 case FILTERS_VIEW:
1386 what = "Filter";
1387 break;
1388 case HELP_VIEW:
1389 what = "Binding/command/option";
1390 break;
1393 info_msg("%s not found: %s", what, search_str ? : "");
1396 void set_view(int view)
1398 if (view == cur_view)
1399 return;
1401 cur_view = view;
1402 switch (cur_view) {
1403 case TREE_VIEW:
1404 searchable = tree_searchable;
1405 break;
1406 case SORTED_VIEW:
1407 searchable = lib_editable.searchable;
1408 break;
1409 case PLAYLIST_VIEW:
1410 searchable = pl_editable.searchable;
1411 break;
1412 case QUEUE_VIEW:
1413 searchable = pq_editable.searchable;
1414 break;
1415 case BROWSER_VIEW:
1416 searchable = browser_searchable;
1417 break;
1418 case FILTERS_VIEW:
1419 searchable = filters_searchable;
1420 break;
1421 case HELP_VIEW:
1422 searchable = help_searchable;
1423 update_help_window();
1424 break;
1427 curs_set(0);
1428 do_update_view(1);
1429 post_update();
1432 void enter_command_mode(void)
1434 error_buf[0] = 0;
1435 error_time = 0;
1436 input_mode = COMMAND_MODE;
1437 update_commandline();
1440 void enter_search_mode(void)
1442 error_buf[0] = 0;
1443 error_time = 0;
1444 input_mode = SEARCH_MODE;
1445 search_direction = SEARCH_FORWARD;
1446 update_commandline();
1449 void enter_search_backward_mode(void)
1451 error_buf[0] = 0;
1452 error_time = 0;
1453 input_mode = SEARCH_MODE;
1454 search_direction = SEARCH_BACKWARD;
1455 update_commandline();
1458 void quit(void)
1460 running = 0;
1463 void update_colors(void)
1465 int i;
1467 if (!ui_initialized)
1468 return;
1470 for (i = 0; i < NR_CURSED; i++) {
1471 int bg = colors[cursed_to_bg_idx[i]];
1472 int fg = colors[cursed_to_fg_idx[i]];
1473 int pair = i + 1;
1475 if (fg >= 8 && fg <= 15) {
1476 /* fg colors 8..15 are special (0..7 + bold) */
1477 init_pair(pair, fg & 7, bg);
1478 pairs[i] = COLOR_PAIR(pair) | (fg & BRIGHT ? A_BOLD : 0);
1479 } else {
1480 init_pair(pair, fg, bg);
1481 pairs[i] = COLOR_PAIR(pair);
1486 static void clear_error(void)
1488 time_t t = time(NULL);
1490 /* error msg is visible at least 3s */
1491 if (t - error_time < 3)
1492 return;
1494 if (error_buf[0]) {
1495 error_time = 0;
1496 error_buf[0] = 0;
1497 update_commandline();
1501 /* screen updates }}} */
1503 static void spawn_status_program(void)
1505 static const char *status_strs[] = { "stopped", "playing", "paused" };
1506 const char *stream_title = NULL;
1507 char *argv[32];
1508 int i, status;
1510 if (status_display_program == NULL || status_display_program[0] == 0)
1511 return;
1513 player_info_lock();
1514 status = player_info.status;
1515 if (status == 1)
1516 stream_title = get_stream_title();
1517 player_info_unlock();
1519 i = 0;
1520 argv[i++] = xstrdup(status_display_program);
1522 argv[i++] = xstrdup("status");
1523 argv[i++] = xstrdup(status_strs[status]);
1524 if (cur_track_info) {
1525 static const char *keys[] = {
1526 "artist", "album", "discnumber", "tracknumber", "title", "date", NULL
1528 int j;
1530 if (is_url(cur_track_info->filename)) {
1531 argv[i++] = xstrdup("url");
1532 argv[i++] = xstrdup(cur_track_info->filename);
1533 if (stream_title) {
1534 argv[i++] = xstrdup("title");
1535 argv[i++] = xstrdup(stream_title);
1537 } else {
1538 char buf[32];
1540 argv[i++] = xstrdup("file");
1541 argv[i++] = xstrdup(cur_track_info->filename);
1542 for (j = 0; keys[j]; j++) {
1543 const char *key = keys[j];
1544 const char *val;
1546 val = comments_get_val(cur_track_info->comments, key);
1547 if (val) {
1548 argv[i++] = xstrdup(key);
1549 argv[i++] = xstrdup(val);
1552 snprintf(buf, sizeof(buf), "%d", cur_track_info->duration);
1553 argv[i++] = xstrdup("duration");
1554 argv[i++] = xstrdup(buf);
1557 argv[i++] = NULL;
1558 if (spawn(argv, &status) == -1)
1559 error_msg("couldn't run `%s': %s", status_display_program, strerror(errno));
1560 for (i = 0; argv[i]; i++)
1561 free(argv[i]);
1564 static int ctrl_c_pressed = 0;
1566 static void sig_int(int sig)
1568 ctrl_c_pressed = 1;
1571 static int needs_to_resize = 1;
1573 static void sig_winch(int sig)
1575 needs_to_resize = 1;
1578 static int get_window_size(int *lines, int *columns)
1580 struct winsize ws;
1582 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
1583 return -1;
1584 *columns = ws.ws_col;
1585 *lines = ws.ws_row;
1586 return 0;
1589 static void resize_tree_view(int w, int h)
1591 tree_win_w = w / 3;
1592 track_win_w = w - tree_win_w - 1;
1593 if (tree_win_w < 8)
1594 tree_win_w = 8;
1595 if (track_win_w < 8)
1596 track_win_w = 8;
1597 tree_win_x = 0;
1598 tree_win_y = 0;
1599 track_win_x = tree_win_w + 1;
1600 track_win_y = 0;
1602 h--;
1603 window_set_nr_rows(lib_tree_win, h);
1604 window_set_nr_rows(lib_track_win, h);
1607 static void update(void)
1609 int needs_view_update = 0;
1610 int needs_title_update = 0;
1611 int needs_status_update = 0;
1612 int needs_command_update = 0;
1613 int needs_spawn = 0;
1615 if (needs_to_resize) {
1616 int w, h;
1617 int columns, lines;
1619 if (get_window_size(&lines, &columns) == 0) {
1620 needs_to_resize = 0;
1621 resizeterm(lines, columns);
1622 w = COLS;
1623 h = LINES - 3;
1624 if (w < 16)
1625 w = 16;
1626 if (h < 8)
1627 h = 8;
1628 editable_lock();
1629 resize_tree_view(w, h);
1630 window_set_nr_rows(lib_editable.win, h - 1);
1631 window_set_nr_rows(pl_editable.win, h - 1);
1632 window_set_nr_rows(pq_editable.win, h - 1);
1633 window_set_nr_rows(filters_win, h - 1);
1634 window_set_nr_rows(help_win, h - 1);
1635 window_set_nr_rows(browser_win, h - 1);
1636 editable_unlock();
1637 needs_title_update = 1;
1638 needs_status_update = 1;
1639 needs_command_update = 1;
1643 player_info_lock();
1644 editable_lock();
1646 needs_spawn = player_info.status_changed || player_info.file_changed ||
1647 player_info.metadata_changed;
1649 if (player_info.file_changed) {
1650 if (cur_track_info)
1651 track_info_unref(cur_track_info);
1652 if (player_info.filename[0] == 0) {
1653 cur_track_info = NULL;
1654 } else {
1655 cur_track_info = cmus_get_track_info(player_info.filename);
1657 player_info.file_changed = 0;
1658 needs_title_update = 1;
1659 needs_status_update = 1;
1661 if (player_info.metadata_changed) {
1662 player_info.metadata_changed = 0;
1663 needs_title_update = 1;
1665 if (player_info.position_changed || player_info.status_changed || player_info.vol_changed) {
1666 player_info.position_changed = 0;
1667 player_info.status_changed = 0;
1668 player_info.vol_changed = 0;
1670 needs_status_update = 1;
1672 switch (cur_view) {
1673 case TREE_VIEW:
1674 needs_view_update += lib_tree_win->changed || lib_track_win->changed;
1675 break;
1676 case SORTED_VIEW:
1677 needs_view_update += lib_editable.win->changed;
1678 break;
1679 case PLAYLIST_VIEW:
1680 needs_view_update += pl_editable.win->changed;
1681 break;
1682 case QUEUE_VIEW:
1683 needs_view_update += pq_editable.win->changed;
1684 break;
1685 case BROWSER_VIEW:
1686 needs_view_update += browser_win->changed;
1687 break;
1688 case FILTERS_VIEW:
1689 needs_view_update += filters_win->changed;
1690 break;
1691 case HELP_VIEW:
1692 needs_view_update += help_win->changed;
1693 break;
1696 /* total time changed? */
1697 if (play_library) {
1698 needs_status_update += lib_editable.win->changed;
1699 lib_editable.win->changed = 0;
1700 } else {
1701 needs_status_update += pl_editable.win->changed;
1702 lib_editable.win->changed = 0;
1705 editable_unlock();
1706 player_info_unlock();
1708 if (needs_spawn)
1709 spawn_status_program();
1711 if (needs_view_update || needs_title_update || needs_status_update || needs_command_update) {
1712 curs_set(0);
1714 if (needs_view_update)
1715 do_update_view(0);
1716 if (needs_title_update)
1717 do_update_titleline();
1718 if (needs_status_update)
1719 do_update_statusline();
1720 if (needs_command_update)
1721 do_update_commandline();
1722 post_update();
1726 static void handle_ch(uchar ch)
1728 clear_error();
1729 if (input_mode == NORMAL_MODE) {
1730 normal_mode_ch(ch);
1731 } else if (input_mode == COMMAND_MODE) {
1732 command_mode_ch(ch);
1733 update_commandline();
1734 } else if (input_mode == SEARCH_MODE) {
1735 search_mode_ch(ch);
1736 update_commandline();
1740 static void handle_key(int key)
1742 clear_error();
1743 if (input_mode == NORMAL_MODE) {
1744 normal_mode_key(key);
1745 } else if (input_mode == COMMAND_MODE) {
1746 command_mode_key(key);
1747 update_commandline();
1748 } else if (input_mode == SEARCH_MODE) {
1749 search_mode_key(key);
1750 update_commandline();
1754 static void u_getch(void)
1756 int key;
1757 int bit = 7;
1758 int mask = (1 << 7);
1759 uchar u, ch;
1761 key = getch();
1762 if (key == ERR || key == 0)
1763 return;
1765 if (key > 255) {
1766 handle_key(key);
1767 return;
1770 ch = (unsigned char)key;
1771 while (bit > 0 && ch & mask) {
1772 mask >>= 1;
1773 bit--;
1775 if (bit == 7) {
1776 /* ascii */
1777 u = ch;
1778 } else {
1779 int count;
1781 u = ch & ((1 << bit) - 1);
1782 count = 6 - bit;
1783 while (count) {
1784 key = getch();
1785 if (key == ERR || key == 0)
1786 return;
1788 ch = (unsigned char)key;
1789 u = (u << 6) | (ch & 63);
1790 count--;
1793 handle_ch(u);
1796 static void main_loop(void)
1798 int rc, fd_high;
1800 fd_high = server_socket;
1801 while (running) {
1802 fd_set set;
1803 struct timeval tv;
1805 update();
1807 FD_ZERO(&set);
1808 FD_SET(0, &set);
1809 FD_SET(server_socket, &set);
1811 /* Timeout must be so small that screen updates seem instant.
1812 * Only affects changes done in other threads (worker, player).
1814 * Too small timeout makes window updates too fast (wastes CPU).
1816 * Too large timeout makes status line (position) updates too slow.
1817 * The timeout is accuracy of player position.
1819 tv.tv_sec = 0;
1820 tv.tv_usec = 100e3;
1821 rc = select(fd_high + 1, &set, NULL, NULL, &tv);
1822 if (rc <= 0) {
1823 if (ctrl_c_pressed) {
1824 handle_ch(0x03);
1825 ctrl_c_pressed = 0;
1827 continue;
1830 if (FD_ISSET(server_socket, &set)) {
1831 /* no error msgs for cmus-remote */
1832 display_errors = 0;
1834 server_serve();
1836 if (FD_ISSET(0, &set)) {
1837 /* diplay errors for interactive commands */
1838 display_errors = 1;
1840 if (using_utf8) {
1841 u_getch();
1842 } else {
1843 int key = getch();
1845 if (key != ERR && key != 0) {
1846 if (key > 255) {
1847 handle_key(key);
1848 } else {
1849 uchar ch = key;
1851 if (ch > 0x7f)
1852 ch |= U_INVALID_MASK;
1853 handle_ch(ch);
1861 static int get_next(char **filename)
1863 struct track_info *info;
1865 editable_lock();
1866 info = play_queue_remove();
1867 if (info == NULL) {
1868 if (play_library) {
1869 info = lib_set_next();
1870 } else {
1871 info = pl_set_next();
1874 editable_unlock();
1876 if (info == NULL)
1877 return -1;
1879 *filename = xstrdup(info->filename);
1880 track_info_unref(info);
1881 return 0;
1884 static const struct player_callbacks player_callbacks = {
1885 .get_next = get_next
1888 static void init_curses(void)
1890 struct sigaction act;
1891 char *ptr, *term;
1893 sigemptyset(&act.sa_mask);
1894 act.sa_flags = 0;
1895 act.sa_handler = sig_int;
1896 sigaction(SIGINT, &act, NULL);
1898 sigemptyset(&act.sa_mask);
1899 act.sa_flags = 0;
1900 act.sa_handler = sig_winch;
1901 sigaction(SIGWINCH, &act, NULL);
1903 initscr();
1905 /* turn off kb buffering */
1906 cbreak();
1908 keypad(stdscr, TRUE);
1910 /* wait max 5 * 0.1 s if there are no keys available
1911 * doesn't really matter because we use select()
1913 halfdelay(5);
1915 noecho();
1916 if (has_colors()) {
1917 start_color();
1918 use_default_colors();
1920 d_print("Number of supported colors: %d\n", COLORS);
1921 ui_initialized = 1;
1923 /* this was disabled while initializing because it needs to be
1924 * called only once after all colors have been set
1926 update_colors();
1928 ptr = print_buffer;
1929 t_ts = tgetstr("ts", &ptr);
1930 t_fs = tgetstr("fs", &ptr);
1931 d_print("ts: %d fs: %d\n", !!t_ts, !!t_fs);
1933 if (!t_fs)
1934 t_ts = NULL;
1936 if (!t_ts && (term = getenv("TERM"))) {
1938 * Eterm: Eterm
1939 * aterm: rxvt
1940 * mlterm: xterm
1941 * terminal (xfce): xterm
1942 * urxvt: rxvt-unicode
1943 * xterm: xterm, xterm-{,16,88,256}color
1945 if (!strcmp(term, "screen")) {
1946 t_ts = "\033_";
1947 t_fs = "\033\\";
1948 } else if (!strncmp(term, "xterm", 5) ||
1949 !strncmp(term, "rxvt", 4) ||
1950 !strcmp(term, "Eterm")) {
1951 /* \033]1; change icon
1952 * \033]2; change title
1953 * \033]0; change both
1955 t_ts = "\033]0;";
1956 t_fs = "\007";
1961 static void init_all(void)
1963 server_init(server_address);
1965 /* does not select output plugin */
1966 player_init(&player_callbacks);
1968 /* plugins have been loaded so we know what plugin options are available */
1969 options_add();
1971 lib_init();
1972 searchable = tree_searchable;
1973 pl_init();
1974 cmus_init();
1975 browser_init();
1976 filters_init();
1977 help_init();
1978 cmdline_init();
1979 commands_init();
1980 search_mode_init();
1982 /* almost everything must be initialized now */
1983 options_load();
1985 /* finally we can set the output plugin */
1986 player_set_op(output_plugin);
1988 player_get_volume(&player_info.vol_left, &player_info.vol_right);
1990 lib_autosave_filename = xstrjoin(cmus_config_dir, "/lib.pl");
1991 pl_autosave_filename = xstrjoin(cmus_config_dir, "/playlist.pl");
1992 pl_filename = xstrdup(pl_autosave_filename);
1993 lib_filename = xstrdup(lib_autosave_filename);
1995 cmus_add(lib_add_track, lib_autosave_filename, FILE_TYPE_PL, JOB_TYPE_LIB);
1996 cmus_add(pl_add_track, pl_autosave_filename, FILE_TYPE_PL, JOB_TYPE_PL);
1998 if (error_count) {
1999 char buf[16];
2001 warn("Press <enter> to continue.");
2002 fgets(buf, sizeof(buf), stdin);
2004 help_add_all_unbound();
2006 init_curses();
2009 static void exit_all(void)
2011 endwin();
2013 options_exit();
2015 server_exit();
2016 cmus_exit();
2017 cmus_save(lib_for_each, lib_autosave_filename);
2018 cmus_save(pl_for_each, pl_autosave_filename);
2020 player_exit();
2021 commands_exit();
2022 search_mode_exit();
2023 filters_exit();
2024 help_exit();
2025 browser_exit();
2028 enum {
2029 FLAG_LISTEN,
2030 FLAG_PLUGINS,
2031 FLAG_HELP,
2032 FLAG_VERSION,
2033 NR_FLAGS
2036 static struct option options[NR_FLAGS + 1] = {
2037 { 0, "listen", 1 },
2038 { 0, "plugins", 0 },
2039 { 0, "help", 0 },
2040 { 0, "version", 0 },
2041 { 0, NULL, 0 }
2044 static const char *usage =
2045 "Usage: %s [OPTION]...\n"
2046 "Curses based music player.\n"
2047 "\n"
2048 " --listen ADDR listen on ADDR instead of ~/.cmus/socket\n"
2049 " ADDR is either a UNIX socket or host[:port]\n"
2050 " --plugins list available plugins and exit\n"
2051 " --help display this help and exit\n"
2052 " --version " VERSION "\n"
2053 "\n"
2054 "Use cmus-remote to control cmus from command line.\n"
2055 "Report bugs to <cmus-devel@lists.sourceforge.net>.\n";
2057 int main(int argc, char *argv[])
2059 int list_plugins = 0;
2061 program_name = argv[0];
2062 argv++;
2063 while (1) {
2064 int idx;
2065 char *arg;
2067 idx = get_option(&argv, options, &arg);
2068 if (idx < 0)
2069 break;
2071 switch (idx) {
2072 case FLAG_HELP:
2073 printf(usage, program_name);
2074 return 0;
2075 case FLAG_VERSION:
2076 printf("cmus " VERSION "\nCopyright 2004-2006 Timo Hirvonen\n");
2077 return 0;
2078 case FLAG_PLUGINS:
2079 list_plugins = 1;
2080 break;
2081 case FLAG_LISTEN:
2082 server_address = xstrdup(arg);
2083 break;
2087 setlocale(LC_CTYPE, "");
2088 #ifdef CODESET
2089 charset = nl_langinfo(CODESET);
2090 #else
2091 charset = "ISO-8859-1";
2092 #endif
2093 if (strcmp(charset, "UTF-8") == 0) {
2094 using_utf8 = 1;
2095 } else {
2096 using_utf8 = 0;
2098 misc_init();
2099 if (server_address == NULL)
2100 server_address = xstrjoin(cmus_config_dir, "/socket");
2101 debug_init();
2102 d_print("charset = '%s'\n", charset);
2104 player_load_plugins();
2105 if (list_plugins) {
2106 player_dump_plugins();
2107 return 0;
2109 init_all();
2110 main_loop();
2111 exit_all();
2112 return 0;