]> git.sesse.net Git - vlc/blob - modules/gui/ncurses.c
bd59a60d933af572abb86b4f1091f837ba68d49d
[vlc] / modules / gui / ncurses.c
1 /*****************************************************************************
2  * ncurses.c : NCurses interface for vlc
3  *****************************************************************************
4  * Copyright © 2001-2011 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Laurent Aimar <fenrir@via.ecp.fr>
9  *          Yoann Peronneau <yoann@videolan.org>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          Rafaël Carré <funman@videolanorg>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 /* UTF8 locale is required */
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #define _XOPEN_SOURCE_EXTENDED 1
38
39 #include <assert.h>
40 #include <wchar.h>
41 #include <sys/stat.h>
42 #include <math.h>
43 #include <errno.h>
44
45 #include <vlc_common.h>
46 #include <vlc_plugin.h>
47
48 #include <ncurses.h>
49
50 #include <vlc_interface.h>
51 #include <vlc_vout.h>
52 #include <vlc_charset.h>
53 #include <vlc_input.h>
54 #include <vlc_es.h>
55 #include <vlc_playlist.h>
56 #include <vlc_meta.h>
57 #include <vlc_fs.h>
58 #include <vlc_url.h>
59
60 /*****************************************************************************
61  * Local prototypes.
62  *****************************************************************************/
63 static int  Open           (vlc_object_t *);
64 static void Close          (vlc_object_t *);
65
66 /*****************************************************************************
67  * Module descriptor
68  *****************************************************************************/
69
70 #define BROWSE_TEXT N_("Filebrowser starting point")
71 #define BROWSE_LONGTEXT N_(\
72     "This option allows you to specify the directory the ncurses filebrowser " \
73     "will show you initially.")
74
75 vlc_module_begin ()
76     set_shortname("Ncurses")
77     set_description(N_("Ncurses interface"))
78     set_capability("interface", 10)
79     set_category(CAT_INTERFACE)
80     set_subcategory(SUBCAT_INTERFACE_MAIN)
81     set_callbacks(Open, Close)
82     add_shortcut("curses")
83     add_directory("browse-dir", NULL, BROWSE_TEXT, BROWSE_LONGTEXT, false)
84 vlc_module_end ()
85
86 #include "eject.c"
87
88 /*****************************************************************************
89  * intf_sys_t: description and status of ncurses interface
90  *****************************************************************************/
91 enum
92 {
93     BOX_NONE,
94     BOX_HELP,
95     BOX_INFO,
96     BOX_LOG,
97     BOX_PLAYLIST,
98     BOX_SEARCH,
99     BOX_OPEN,
100     BOX_BROWSE,
101     BOX_META,
102     BOX_OBJECTS,
103     BOX_STATS
104 };
105
106 static const char box_title[][19] = {
107     [BOX_NONE]      = "",
108     [BOX_HELP]      = " Help ",
109     [BOX_INFO]      = " Information ",
110     [BOX_LOG]       = " Messages ",
111     [BOX_PLAYLIST]  = " Playlist ",
112     [BOX_SEARCH]    = " Playlist ",
113     [BOX_OPEN]      = " Playlist ",
114     [BOX_BROWSE]    = " Browse ",
115     [BOX_META]      = " Meta-information ",
116     [BOX_OBJECTS]   = " Objects ",
117     [BOX_STATS]     = " Stats ",
118 };
119
120 enum
121 {
122     C_DEFAULT = 0,
123     C_TITLE,
124     C_PLAYLIST_1,
125     C_PLAYLIST_2,
126     C_PLAYLIST_3,
127     C_BOX,
128     C_STATUS,
129     C_INFO,
130     C_ERROR,
131     C_WARNING,
132     C_DEBUG,
133     C_CATEGORY,
134     C_FOLDER,
135     /* XXX: new elements here ! */
136
137     C_MAX
138 };
139
140 /* Available colors: BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE */
141 static const struct { short f; short b; } color_pairs[] =
142 {
143     /* element */       /* foreground*/ /* background*/
144     [C_TITLE]       = { COLOR_YELLOW,   COLOR_BLACK },
145
146     /* jamaican playlist, for rastafari sisters & brothers! */
147     [C_PLAYLIST_1]  = { COLOR_GREEN,    COLOR_BLACK },
148     [C_PLAYLIST_2]  = { COLOR_YELLOW,   COLOR_BLACK },
149     [C_PLAYLIST_3]  = { COLOR_RED,      COLOR_BLACK },
150
151     /* used in DrawBox() */
152     [C_BOX]         = { COLOR_CYAN,     COLOR_BLACK },
153     /* Source: State, Position, Volume, Chapters, etc...*/
154     [C_STATUS]      = { COLOR_BLUE,     COLOR_BLACK },
155
156     /* VLC messages, keep the order from highest priority to lowest */
157     [C_INFO]        = { COLOR_BLACK,    COLOR_WHITE },
158     [C_ERROR]       = { COLOR_RED,      COLOR_BLACK },
159     [C_WARNING]     = { COLOR_YELLOW,   COLOR_BLACK },
160     [C_DEBUG]       = { COLOR_WHITE,    COLOR_BLACK },
161
162     /* Category title: help, info, metadata */
163     [C_CATEGORY]    = { COLOR_MAGENTA,  COLOR_BLACK },
164     /* Folder (BOX_BROWSE) */
165     [C_FOLDER]      = { COLOR_RED,      COLOR_BLACK },
166 };
167
168 struct dir_entry_t
169 {
170     bool        file;
171     char        *path;
172 };
173
174 struct pl_item_t
175 {
176     playlist_item_t *item;
177     char            *display;
178 };
179
180 struct intf_sys_t
181 {
182     vlc_thread_t    thread;
183     input_thread_t *p_input;
184
185     bool            color;
186     bool            exit;
187
188     int             box_type;
189     int             box_y;            // start of box content
190     int             box_height;
191     int             box_lines_total;  // number of lines in the box
192     int             box_start;        // first line of box displayed
193     int             box_idx;          // selected line
194
195     struct
196     {
197         int              type;
198         vlc_log_t       *item;
199         char            *msg;
200     } msgs[50];      // ring buffer
201     int                 i_msgs;
202     int                 verbosity;
203     vlc_mutex_t         msg_lock;
204
205     /* Search Box context */
206     char            search_chain[20];
207
208     /* Open Box Context */
209     char            open_chain[50];
210
211     /* File Browser context */
212     char            *current_dir;
213     int             n_dir_entries;
214     struct dir_entry_t  **dir_entries;
215     bool            show_hidden_files;
216
217     /* Playlist context */
218     struct pl_item_t    **plist;
219     int             plist_entries;
220     bool            need_update;
221     vlc_mutex_t     pl_lock;
222     bool            plidx_follow;
223     playlist_item_t *node;        /* current node */
224
225 };
226
227 /*****************************************************************************
228  * Directories
229  *****************************************************************************/
230
231 static void DirsDestroy(intf_sys_t *sys)
232 {
233     while (sys->n_dir_entries) {
234         struct dir_entry_t *dir_entry = sys->dir_entries[--sys->n_dir_entries];
235         free(dir_entry->path);
236         free(dir_entry);
237     }
238     free(sys->dir_entries);
239     sys->dir_entries = NULL;
240 }
241
242 static int comdir_entries(const void *a, const void *b)
243 {
244     struct dir_entry_t *dir_entry1 = *(struct dir_entry_t**)a;
245     struct dir_entry_t *dir_entry2 = *(struct dir_entry_t**)b;
246
247     if (dir_entry1->file == dir_entry2->file)
248         return strcasecmp(dir_entry1->path, dir_entry2->path);
249
250     return dir_entry1->file ? 1 : -1;
251 }
252
253 static bool IsFile(const char *current_dir, const char *entry)
254 {
255     bool ret = true;
256 #ifdef S_ISDIR
257     char *uri;
258     if (asprintf(&uri, "%s" DIR_SEP "%s", current_dir, entry) != -1) {
259         struct stat st;
260         ret = vlc_stat(uri, &st) || !S_ISDIR(st.st_mode);
261         free(uri);
262     }
263 #endif
264     return ret;
265 }
266
267 static void ReadDir(intf_thread_t *intf)
268 {
269     intf_sys_t *sys = intf->p_sys;
270
271     if (!sys->current_dir || !*sys->current_dir) {
272         msg_Dbg(intf, "no current dir set");
273         return;
274     }
275
276     DIR *current_dir = vlc_opendir(sys->current_dir);
277     if (!current_dir) {
278         msg_Warn(intf, "cannot open directory `%s' (%s)", sys->current_dir,
279                  vlc_strerror_c(errno));
280         return;
281     }
282
283     DirsDestroy(sys);
284
285     char *entry;
286     while ((entry = vlc_readdir(current_dir))) {
287         if (!sys->show_hidden_files && *entry == '.' && strcmp(entry, ".."))
288             goto next;
289
290         struct dir_entry_t *dir_entry = malloc(sizeof *dir_entry);
291         if (!dir_entry)
292             goto next;
293
294         dir_entry->file = IsFile(sys->current_dir, entry);
295         dir_entry->path = entry;
296         INSERT_ELEM(sys->dir_entries, sys->n_dir_entries,
297              sys->n_dir_entries, dir_entry);
298         continue;
299
300 next:
301         free(entry);
302     }
303
304     qsort(sys->dir_entries, sys->n_dir_entries,
305            sizeof(struct dir_entry_t*), &comdir_entries);
306
307     closedir(current_dir);
308 }
309
310 /*****************************************************************************
311  * Adjust index position after a change (list navigation or item switching)
312  *****************************************************************************/
313 static void CheckIdx(intf_sys_t *sys)
314 {
315     int lines = sys->box_lines_total;
316     int height = LINES - sys->box_y - 2;
317     if (height > lines - 1)
318         height = lines - 1;
319
320     /* make sure the new index is within the box */
321     if (sys->box_idx <= 0) {
322         sys->box_idx = 0;
323         sys->box_start = 0;
324     } else if (sys->box_idx >= lines - 1 && lines > 0) {
325         sys->box_idx = lines - 1;
326         sys->box_start = sys->box_idx - height;
327     }
328
329     /* Fix box start (1st line of the box displayed) */
330     if (sys->box_idx < sys->box_start ||
331         sys->box_idx > height + sys->box_start + 1) {
332         sys->box_start = sys->box_idx - height/2;
333         if (sys->box_start < 0)
334             sys->box_start = 0;
335     } else if (sys->box_idx == sys->box_start - 1) {
336         sys->box_start--;
337     } else if (sys->box_idx == height + sys->box_start + 1) {
338         sys->box_start++;
339     }
340 }
341
342 /*****************************************************************************
343  * Playlist
344  *****************************************************************************/
345 static void PlaylistDestroy(intf_sys_t *sys)
346 {
347     while (sys->plist_entries) {
348         struct pl_item_t *p_pl_item = sys->plist[--sys->plist_entries];
349         free(p_pl_item->display);
350         free(p_pl_item);
351     }
352     free(sys->plist);
353     sys->plist = NULL;
354 }
355
356 static bool PlaylistAddChild(intf_sys_t *sys, playlist_item_t *p_child,
357                              const char *c, const char d)
358 {
359     int ret;
360     char *name = input_item_GetTitleFbName(p_child->p_input);
361     struct pl_item_t *p_pl_item = malloc(sizeof *p_pl_item);
362
363     if (!name || !p_pl_item)
364         goto error;
365
366     p_pl_item->item = p_child;
367
368     if (c && *c)
369         ret = asprintf(&p_pl_item->display, "%s%c-%s", c, d, name);
370     else
371         ret = asprintf(&p_pl_item->display, " %s", name);
372
373     free(name);
374     name = NULL;
375
376     if (ret == -1)
377         goto error;
378
379     INSERT_ELEM(sys->plist, sys->plist_entries,
380                  sys->plist_entries, p_pl_item);
381
382     return true;
383
384 error:
385     free(name);
386     free(p_pl_item);
387     return false;
388 }
389
390 static void PlaylistAddNode(intf_sys_t *sys, playlist_item_t *node,
391                             const char *c)
392 {
393     for (int k = 0; k < node->i_children; k++) {
394         bool last = k == node->i_children - 1;
395         playlist_item_t *p_child = node->pp_children[k];
396         if (!PlaylistAddChild(sys, p_child, c, last ? '`' : '|'))
397             return;
398
399         if (p_child->i_children <= 0)
400             continue;
401
402         if (*c) {
403             char *tmp;
404             if (asprintf(&tmp, "%s%c ", c, last ? ' ' : '|') == -1)
405                 return;
406             PlaylistAddNode(sys, p_child, tmp);
407             free(tmp);
408         } else {
409             PlaylistAddNode(sys, p_child, " ");
410         }
411     }
412 }
413
414 static void PlaylistRebuild(intf_thread_t *intf)
415 {
416     intf_sys_t *sys = intf->p_sys;
417     playlist_t *p_playlist = pl_Get(intf);
418
419     PlaylistDestroy(sys);
420     PlaylistAddNode(sys, p_playlist->p_root_onelevel, "");
421 }
422
423 static int ItemChanged(vlc_object_t *p_this, const char *variable,
424                             vlc_value_t oval, vlc_value_t nval, void *param)
425 {
426     VLC_UNUSED(p_this); VLC_UNUSED(variable);
427     VLC_UNUSED(oval); VLC_UNUSED(nval);
428
429     intf_sys_t *sys = ((intf_thread_t *)param)->p_sys;
430
431     vlc_mutex_lock(&sys->pl_lock);
432     sys->need_update = true;
433     vlc_mutex_unlock(&sys->pl_lock);
434
435     return VLC_SUCCESS;
436 }
437
438 static int PlaylistChanged(vlc_object_t *p_this, const char *variable,
439                             vlc_value_t oval, vlc_value_t nval, void *param)
440 {
441     VLC_UNUSED(p_this); VLC_UNUSED(variable);
442     VLC_UNUSED(oval); VLC_UNUSED(nval);
443     intf_thread_t *intf   = (intf_thread_t *)param;
444     intf_sys_t *sys       = intf->p_sys;
445     playlist_item_t *node = playlist_CurrentPlayingItem(pl_Get(intf));
446
447     vlc_mutex_lock(&sys->pl_lock);
448     sys->need_update = true;
449     sys->node = node ? node->p_parent : NULL;
450     vlc_mutex_unlock(&sys->pl_lock);
451
452     return VLC_SUCCESS;
453 }
454
455 /* Playlist suxx */
456 static int SubSearchPlaylist(intf_sys_t *sys, char *searchstring,
457                               int i_start, int i_stop)
458 {
459     for (int i = i_start + 1; i < i_stop; i++)
460         if (strcasestr(sys->plist[i]->display, searchstring))
461             return i;
462
463     return -1;
464 }
465
466 static void SearchPlaylist(intf_sys_t *sys)
467 {
468     char *str = sys->search_chain;
469     int i_first = sys->box_idx;
470     if (i_first < 0)
471         i_first = 0;
472
473     if (!str || !*str)
474         return;
475
476     int i_item = SubSearchPlaylist(sys, str, i_first + 1, sys->plist_entries);
477     if (i_item < 0)
478         i_item = SubSearchPlaylist(sys, str, 0, i_first);
479
480     if (i_item > 0) {
481         sys->box_idx = i_item;
482         CheckIdx(sys);
483     }
484 }
485
486 static inline bool IsIndex(intf_sys_t *sys, playlist_t *p_playlist, int i)
487 {
488     playlist_item_t *item = sys->plist[i]->item;
489
490     PL_ASSERT_LOCKED;
491
492     vlc_mutex_lock(&sys->pl_lock);
493     if (item->i_children == 0 && item == sys->node) {
494         vlc_mutex_unlock(&sys->pl_lock);
495         return true;
496     }
497     vlc_mutex_unlock(&sys->pl_lock);
498
499     playlist_item_t *p_played_item = playlist_CurrentPlayingItem(p_playlist);
500     if (p_played_item && item->p_input && p_played_item->p_input)
501         return item->p_input->i_id == p_played_item->p_input->i_id;
502
503     return false;
504 }
505
506 static void FindIndex(intf_sys_t *sys, playlist_t *p_playlist)
507 {
508     int plidx = sys->box_idx;
509     int max = sys->plist_entries;
510
511     PL_LOCK;
512
513     if (!IsIndex(sys, p_playlist, plidx))
514         for (int i = 0; i < max; i++)
515             if (IsIndex(sys, p_playlist, i)) {
516                 sys->box_idx = i;
517                 CheckIdx(sys);
518                 break;
519             }
520
521     PL_UNLOCK;
522
523     sys->plidx_follow = true;
524 }
525
526 /****************************************************************************
527  * Drawing
528  ****************************************************************************/
529
530 static void start_color_and_pairs(intf_thread_t *intf)
531 {
532     if (!has_colors()) {
533         intf->p_sys->color = false;
534         msg_Warn(intf, "Terminal doesn't support colors");
535         return;
536     }
537
538     start_color();
539     for (int i = C_DEFAULT + 1; i < C_MAX; i++)
540         init_pair(i, color_pairs[i].f, color_pairs[i].b);
541
542     /* untested, in all my terminals, !can_change_color() --funman */
543     if (can_change_color())
544         init_color(COLOR_YELLOW, 960, 500, 0); /* YELLOW -> ORANGE */
545 }
546
547 static void DrawBox(int y, int h, bool color, const char *title)
548 {
549     int w = COLS;
550     if (w <= 3 || h <= 0)
551         return;
552
553     if (color) color_set(C_BOX, NULL);
554
555     if (!title) title = "";
556     int len = strlen(title);
557
558     if (len > w - 2)
559         len = w - 2;
560
561     mvaddch(y, 0,    ACS_ULCORNER);
562     mvhline(y, 1,  ACS_HLINE, (w-len-2)/2);
563     mvprintw(y, 1+(w-len-2)/2, "%s", title);
564     mvhline(y, (w-len)/2+len,  ACS_HLINE, w - 1 - ((w-len)/2+len));
565     mvaddch(y, w-1,ACS_URCORNER);
566
567     for (int i = 0; i < h; i++) {
568         mvaddch(++y, 0,   ACS_VLINE);
569         mvaddch(y, w-1, ACS_VLINE);
570     }
571
572     mvaddch(++y, 0,   ACS_LLCORNER);
573     mvhline(y,   1,   ACS_HLINE, w - 2);
574     mvaddch(y,   w-1, ACS_LRCORNER);
575     if (color) color_set(C_DEFAULT, NULL);
576 }
577
578 static void DrawEmptyLine(int y, int x, int w)
579 {
580     if (w <= 0) return;
581
582     mvhline(y, x, ' ', w);
583 }
584
585 static void DrawLine(int y, int x, int w)
586 {
587     if (w <= 0) return;
588
589     attrset(A_REVERSE);
590     mvhline(y, x, ' ', w);
591     attroff(A_REVERSE);
592 }
593
594 static void mvnprintw(int y, int x, int w, const char *p_fmt, ...)
595 {
596     va_list  vl_args;
597     char    *p_buf;
598     int      len;
599
600     if (w <= 0)
601         return;
602
603     va_start(vl_args, p_fmt);
604     int i_ret = vasprintf(&p_buf, p_fmt, vl_args);
605     va_end(vl_args);
606
607     if (i_ret == -1)
608         return;
609
610     len = strlen(p_buf);
611
612     wchar_t wide[len + 1];
613
614     EnsureUTF8(p_buf);
615     size_t i_char_len = mbstowcs(wide, p_buf, len);
616
617     size_t i_width; /* number of columns */
618
619     if (i_char_len == (size_t)-1) /* an invalid character was encountered */ {
620         free(p_buf);
621         return;
622     }
623
624     i_width = wcswidth(wide, i_char_len);
625     if (i_width == (size_t)-1) {
626         /* a non printable character was encountered */
627         i_width = 0;
628         for (unsigned i = 0 ; i < i_char_len ; i++) {
629             int i_cwidth = wcwidth(wide[i]);
630             if (i_cwidth != -1)
631                 i_width += i_cwidth;
632         }
633     }
634
635     if (i_width <= (size_t)w) {
636         mvprintw(y, x, "%s", p_buf);
637         mvhline(y, x + i_width, ' ', w - i_width);
638         free(p_buf);
639         return;
640     }
641
642     int i_total_width = 0;
643     int i = 0;
644     while (i_total_width < w) {
645         i_total_width += wcwidth(wide[i]);
646         if (w > 7 && i_total_width >= w/2) {
647             wide[i  ] = '.';
648             wide[i+1] = '.';
649             i_total_width -= wcwidth(wide[i]) - 2;
650             if (i > 0) {
651                 /* we require this check only if at least one character
652                  * 4 or more columns wide exists (which i doubt) */
653                 wide[i-1] = '.';
654                 i_total_width -= wcwidth(wide[i-1]) - 1;
655             }
656
657             /* find the widest string */
658             int j, i_2nd_width = 0;
659             for (j = i_char_len - 1; i_2nd_width < w - i_total_width; j--)
660                 i_2nd_width += wcwidth(wide[j]);
661
662             /* we already have i_total_width columns filled, and we can't
663              * have more than w columns */
664             if (i_2nd_width > w - i_total_width)
665                 j++;
666
667             wmemmove(&wide[i+2], &wide[j+1], i_char_len - j - 1);
668             wide[i + 2 + i_char_len - j - 1] = '\0';
669             break;
670         }
671         i++;
672     }
673     if (w <= 7) /* we don't add the '...' else we lose too much chars */
674         wide[i] = '\0';
675
676     size_t i_wlen = wcslen(wide) * 6 + 1; /* worst case */
677     char ellipsized[i_wlen];
678     wcstombs(ellipsized, wide, i_wlen);
679     mvprintw(y, x, "%s", ellipsized);
680
681     free(p_buf);
682 }
683
684 static void MainBoxWrite(intf_sys_t *sys, int l, const char *p_fmt, ...)
685 {
686     va_list     vl_args;
687     char        *p_buf;
688     bool        b_selected = l == sys->box_idx;
689
690     if (l < sys->box_start || l - sys->box_start >= sys->box_height)
691         return;
692
693     va_start(vl_args, p_fmt);
694     int i_ret = vasprintf(&p_buf, p_fmt, vl_args);
695     va_end(vl_args);
696     if (i_ret == -1)
697         return;
698
699     if (b_selected) attron(A_REVERSE);
700     mvnprintw(sys->box_y + l - sys->box_start, 1, COLS - 2, "%s", p_buf);
701     if (b_selected) attroff(A_REVERSE);
702
703     free(p_buf);
704 }
705
706 static int SubDrawObject(intf_sys_t *sys, int l, vlc_object_t *p_obj, int i_level, const char *prefix)
707 {
708     char *name = vlc_object_get_name(p_obj);
709     MainBoxWrite(sys, l++, "%*s%s%s \"%s\" (%p)", 2 * i_level++, "", prefix,
710                   p_obj->psz_object_type, name ? name : "", p_obj);
711     free(name);
712
713     vlc_list_t *list = vlc_list_children(p_obj);
714     for (int i = 0; i < list->i_count ; i++) {
715         l = SubDrawObject(sys, l, list->p_values[i].p_object, i_level,
716             (i == list->i_count - 1) ? "`-" : "|-" );
717     }
718     vlc_list_release(list);
719     return l;
720 }
721
722 static int DrawObjects(intf_thread_t *intf)
723 {
724     return SubDrawObject(intf->p_sys, 0, VLC_OBJECT(intf->p_libvlc), 0, "");
725 }
726
727 static int DrawMeta(intf_thread_t *intf)
728 {
729     intf_sys_t *sys = intf->p_sys;
730     input_thread_t *p_input = sys->p_input;
731     input_item_t *item;
732     int l = 0;
733
734     if (!p_input)
735         return 0;
736
737     item = input_GetItem(p_input);
738     vlc_mutex_lock(&item->lock);
739     for (int i=0; i<VLC_META_TYPE_COUNT; i++) {
740         const char *meta = vlc_meta_Get(item->p_meta, i);
741         if (!meta || !*meta)
742             continue;
743
744         if (sys->color) color_set(C_CATEGORY, NULL);
745         MainBoxWrite(sys, l++, "  [%s]", vlc_meta_TypeToLocalizedString(i));
746         if (sys->color) color_set(C_DEFAULT, NULL);
747         MainBoxWrite(sys, l++, "      %s", meta);
748     }
749     vlc_mutex_unlock(&item->lock);
750
751     return l;
752 }
753
754 static int DrawInfo(intf_thread_t *intf)
755 {
756     intf_sys_t *sys = intf->p_sys;
757     input_thread_t *p_input = sys->p_input;
758     input_item_t *item;
759     int l = 0;
760
761     if (!p_input)
762         return 0;
763
764     item = input_GetItem(p_input);
765     vlc_mutex_lock(&item->lock);
766     for (int i = 0; i < item->i_categories; i++) {
767         info_category_t *p_category = item->pp_categories[i];
768         if (sys->color) color_set(C_CATEGORY, NULL);
769         MainBoxWrite(sys, l++, _("  [%s]"), p_category->psz_name);
770         if (sys->color) color_set(C_DEFAULT, NULL);
771         for (int j = 0; j < p_category->i_infos; j++) {
772             info_t *p_info = p_category->pp_infos[j];
773             MainBoxWrite(sys, l++, _("      %s: %s"),
774                          p_info->psz_name, p_info->psz_value);
775         }
776     }
777     vlc_mutex_unlock(&item->lock);
778
779     return l;
780 }
781
782 static int DrawStats(intf_thread_t *intf)
783 {
784     intf_sys_t *sys = intf->p_sys;
785     input_thread_t *p_input = sys->p_input;
786     input_item_t *item;
787     input_stats_t *p_stats;
788     int l = 0, i_audio = 0, i_video = 0;
789
790     if (!p_input)
791         return 0;
792
793     item = input_GetItem(p_input);
794     assert(item);
795
796     vlc_mutex_lock(&item->lock);
797     p_stats = item->p_stats;
798     vlc_mutex_lock(&p_stats->lock);
799
800     for (int i = 0; i < item->i_es ; i++) {
801         i_audio += (item->es[i]->i_cat == AUDIO_ES);
802         i_video += (item->es[i]->i_cat == VIDEO_ES);
803     }
804
805     /* Input */
806     if (sys->color) color_set(C_CATEGORY, NULL);
807     MainBoxWrite(sys, l++, _("+-[Incoming]"));
808     if (sys->color) color_set(C_DEFAULT, NULL);
809     MainBoxWrite(sys, l++, _("| input bytes read : %8.0f KiB"),
810             (float)(p_stats->i_read_bytes)/1024);
811     MainBoxWrite(sys, l++, _("| input bitrate    :   %6.0f kb/s"),
812             p_stats->f_input_bitrate*8000);
813     MainBoxWrite(sys, l++, _("| demux bytes read : %8.0f KiB"),
814             (float)(p_stats->i_demux_read_bytes)/1024);
815     MainBoxWrite(sys, l++, _("| demux bitrate    :   %6.0f kb/s"),
816             p_stats->f_demux_bitrate*8000);
817
818     /* Video */
819     if (i_video) {
820         if (sys->color) color_set(C_CATEGORY, NULL);
821         MainBoxWrite(sys, l++, _("+-[Video Decoding]"));
822         if (sys->color) color_set(C_DEFAULT, NULL);
823         MainBoxWrite(sys, l++, _("| video decoded    :    %5"PRIi64),
824                 p_stats->i_decoded_video);
825         MainBoxWrite(sys, l++, _("| frames displayed :    %5"PRIi64),
826                 p_stats->i_displayed_pictures);
827         MainBoxWrite(sys, l++, _("| frames lost      :    %5"PRIi64),
828                 p_stats->i_lost_pictures);
829     }
830     /* Audio*/
831     if (i_audio) {
832         if (sys->color) color_set(C_CATEGORY, NULL);
833         MainBoxWrite(sys, l++, _("+-[Audio Decoding]"));
834         if (sys->color) color_set(C_DEFAULT, NULL);
835         MainBoxWrite(sys, l++, _("| audio decoded    :    %5"PRIi64),
836                 p_stats->i_decoded_audio);
837         MainBoxWrite(sys, l++, _("| buffers played   :    %5"PRIi64),
838                 p_stats->i_played_abuffers);
839         MainBoxWrite(sys, l++, _("| buffers lost     :    %5"PRIi64),
840                 p_stats->i_lost_abuffers);
841     }
842     /* Sout */
843     if (sys->color) color_set(C_CATEGORY, NULL);
844     MainBoxWrite(sys, l++, _("+-[Streaming]"));
845     if (sys->color) color_set(C_DEFAULT, NULL);
846     MainBoxWrite(sys, l++, _("| packets sent     :    %5"PRIi64), p_stats->i_sent_packets);
847     MainBoxWrite(sys, l++, _("| bytes sent       : %8.0f KiB"),
848             (float)(p_stats->i_sent_bytes)/1025);
849     MainBoxWrite(sys, l++, _("| sending bitrate  :   %6.0f kb/s"),
850             p_stats->f_send_bitrate*8000);
851     if (sys->color) color_set(C_DEFAULT, NULL);
852
853     vlc_mutex_unlock(&p_stats->lock);
854     vlc_mutex_unlock(&item->lock);
855
856     return l;
857 }
858
859 static int DrawHelp(intf_thread_t *intf)
860 {
861     intf_sys_t *sys = intf->p_sys;
862     int l = 0;
863
864 #define H(a) MainBoxWrite(sys, l++, a)
865
866     if (sys->color) color_set(C_CATEGORY, NULL);
867     H(_("[Display]"));
868     if (sys->color) color_set(C_DEFAULT, NULL);
869     H(_(" h,H                    Show/Hide help box"));
870     H(_(" i                      Show/Hide info box"));
871     H(_(" M                      Show/Hide metadata box"));
872     H(_(" L                      Show/Hide messages box"));
873     H(_(" P                      Show/Hide playlist box"));
874     H(_(" B                      Show/Hide filebrowser"));
875     H(_(" x                      Show/Hide objects box"));
876     H(_(" S                      Show/Hide statistics box"));
877     H(_(" Esc                    Close Add/Search entry"));
878     H(_(" Ctrl-l                 Refresh the screen"));
879     H("");
880
881     if (sys->color) color_set(C_CATEGORY, NULL);
882     H(_("[Global]"));
883     if (sys->color) color_set(C_DEFAULT, NULL);
884     H(_(" q, Q, Esc              Quit"));
885     H(_(" s                      Stop"));
886     H(_(" <space>                Pause/Play"));
887     H(_(" f                      Toggle Fullscreen"));
888     H(_(" c                      Cycle through audio tracks"));
889     H(_(" v                      Cycle through subtitles tracks"));
890     H(_(" b                      Cycle through video tracks"));
891     H(_(" n, p                   Next/Previous playlist item"));
892     H(_(" [, ]                   Next/Previous title"));
893     H(_(" <, >                   Next/Previous chapter"));
894     /* xgettext: You can use ← and → characters */
895     H(_(" <left>,<right>         Seek -/+ 1%%"));
896     H(_(" a, z                   Volume Up/Down"));
897     H(_(" m                      Mute"));
898     /* xgettext: You can use ↑ and ↓ characters */
899     H(_(" <up>,<down>            Navigate through the box line by line"));
900     /* xgettext: You can use ⇞ and ⇟ characters */
901     H(_(" <pageup>,<pagedown>    Navigate through the box page by page"));
902     /* xgettext: You can use ↖ and ↘ characters */
903     H(_(" <start>,<end>          Navigate to start/end of box"));
904     H("");
905
906     if (sys->color) color_set(C_CATEGORY, NULL);
907     H(_("[Playlist]"));
908     if (sys->color) color_set(C_DEFAULT, NULL);
909     H(_(" r                      Toggle Random playing"));
910     H(_(" l                      Toggle Loop Playlist"));
911     H(_(" R                      Toggle Repeat item"));
912     H(_(" o                      Order Playlist by title"));
913     H(_(" O                      Reverse order Playlist by title"));
914     H(_(" g                      Go to the current playing item"));
915     H(_(" /                      Look for an item"));
916     H(_(" ;                      Look for the next item"));
917     H(_(" A                      Add an entry"));
918     /* xgettext: You can use ⌫ character to translate <backspace> */
919     H(_(" D, <backspace>, <del>  Delete an entry"));
920     H(_(" e                      Eject (if stopped)"));
921     H("");
922
923     if (sys->color) color_set(C_CATEGORY, NULL);
924     H(_("[Filebrowser]"));
925     if (sys->color) color_set(C_DEFAULT, NULL);
926     H(_(" <enter>                Add the selected file to the playlist"));
927     H(_(" <space>                Add the selected directory to the playlist"));
928     H(_(" .                      Show/Hide hidden files"));
929     H("");
930
931     if (sys->color) color_set(C_CATEGORY, NULL);
932     H(_("[Player]"));
933     if (sys->color) color_set(C_DEFAULT, NULL);
934     /* xgettext: You can use ↑ and ↓ characters */
935     H(_(" <up>,<down>            Seek +/-5%%"));
936
937 #undef H
938     return l;
939 }
940
941 static int DrawBrowse(intf_thread_t *intf)
942 {
943     intf_sys_t *sys = intf->p_sys;
944
945     for (int i = 0; i < sys->n_dir_entries; i++) {
946         struct dir_entry_t *dir_entry = sys->dir_entries[i];
947         char type = dir_entry->file ? ' ' : '+';
948
949         if (sys->color)
950             color_set(dir_entry->file ? C_DEFAULT : C_FOLDER, NULL);
951         MainBoxWrite(sys, i, " %c %s", type, dir_entry->path);
952     }
953
954     return sys->n_dir_entries;
955 }
956
957 static int DrawPlaylist(intf_thread_t *intf)
958 {
959     intf_sys_t *sys = intf->p_sys;
960     playlist_t *p_playlist = pl_Get(intf);
961
962     PL_LOCK;
963     vlc_mutex_lock(&sys->pl_lock);
964     if (sys->need_update) {
965         PlaylistRebuild(intf);
966         sys->need_update = false;
967     }
968     vlc_mutex_unlock(&sys->pl_lock);
969     PL_UNLOCK;
970
971     if (sys->plidx_follow)
972         FindIndex(sys, p_playlist);
973
974     for (int i = 0; i < sys->plist_entries; i++) {
975         char c;
976         playlist_item_t *current_item;
977         playlist_item_t *item = sys->plist[i]->item;
978         vlc_mutex_lock(&sys->pl_lock);
979         playlist_item_t *node = sys->node;
980         vlc_mutex_unlock(&sys->pl_lock);
981
982         PL_LOCK;
983         assert(item);
984         current_item = playlist_CurrentPlayingItem(p_playlist);
985         if ((node && item->p_input == node->p_input) ||
986            (!node && current_item && item->p_input == current_item->p_input))
987             c = '*';
988         else if (item == node || current_item == item)
989             c = '>';
990         else
991             c = ' ';
992         PL_UNLOCK;
993
994         if (sys->color) color_set(i%3 + C_PLAYLIST_1, NULL);
995         MainBoxWrite(sys, i, "%c%s", c, sys->plist[i]->display);
996         if (sys->color) color_set(C_DEFAULT, NULL);
997     }
998
999     return sys->plist_entries;
1000 }
1001
1002 static int DrawMessages(intf_thread_t *intf)
1003 {
1004     intf_sys_t *sys = intf->p_sys;
1005     int l = 0;
1006
1007     vlc_mutex_lock(&sys->msg_lock);
1008     int i = sys->i_msgs;
1009     for(;;) {
1010         vlc_log_t *msg = sys->msgs[i].item;
1011         if (msg) {
1012             if (sys->color)
1013                 color_set(sys->msgs[i].type + C_INFO, NULL);
1014             MainBoxWrite(sys, l++, "[%s] %s", msg->psz_module, sys->msgs[i].msg);
1015         }
1016
1017         if (++i == sizeof sys->msgs / sizeof *sys->msgs)
1018             i = 0;
1019
1020         if (i == sys->i_msgs) /* did we loop around the ring buffer ? */
1021             break;
1022     }
1023
1024     vlc_mutex_unlock(&sys->msg_lock);
1025     if (sys->color)
1026         color_set(C_DEFAULT, NULL);
1027     return l;
1028 }
1029
1030 static int DrawStatus(intf_thread_t *intf)
1031 {
1032     intf_sys_t     *sys = intf->p_sys;
1033     input_thread_t *p_input = sys->p_input;
1034     playlist_t     *p_playlist = pl_Get(intf);
1035     char *name = _("VLC media player");
1036     const size_t name_len = strlen(name) + sizeof(PACKAGE_VERSION);
1037     int y = 0;
1038     const char *repeat, *loop, *random;
1039
1040
1041     /* Title */
1042     int padding = COLS - name_len; /* center title */
1043     if (padding < 0)
1044         padding = 0;
1045
1046     attrset(A_REVERSE);
1047     if (sys->color) color_set(C_TITLE, NULL);
1048     DrawEmptyLine(y, 0, COLS);
1049     mvnprintw(y++, padding / 2, COLS, "%s %s", name, PACKAGE_VERSION);
1050     if (sys->color) color_set(C_STATUS, NULL);
1051     attroff(A_REVERSE);
1052
1053     y++; /* leave a blank line */
1054
1055     repeat = var_GetBool(p_playlist, "repeat") ? _("[Repeat] ") : "";
1056     random = var_GetBool(p_playlist, "random") ? _("[Random] ") : "";
1057     loop   = var_GetBool(p_playlist, "loop")   ? _("[Loop]")    : "";
1058
1059     if (p_input && !p_input->b_dead) {
1060         vlc_value_t val;
1061         char *path, *uri;
1062
1063         uri = input_item_GetURI(input_GetItem(p_input));
1064         path = make_path(uri);
1065
1066         mvnprintw(y++, 0, COLS, _(" Source   : %s"), path?path:uri);
1067         free(uri);
1068         free(path);
1069
1070         var_Get(p_input, "state", &val);
1071         switch(val.i_int)
1072         {
1073             static const char *input_state[] = {
1074                 [PLAYING_S] = " State    : Playing %s%s%s",
1075                 [OPENING_S] = " State    : Opening/Connecting %s%s%s",
1076                 [PAUSE_S]   = " State    : Paused %s%s%s",
1077             };
1078             char buf1[MSTRTIME_MAX_SIZE];
1079             char buf2[MSTRTIME_MAX_SIZE];
1080             float volume;
1081
1082         case INIT_S:
1083         case END_S:
1084             y += 2;
1085             break;
1086
1087         case PLAYING_S:
1088         case OPENING_S:
1089         case PAUSE_S:
1090             mvnprintw(y++, 0, COLS, _(input_state[val.i_int]),
1091                         repeat, random, loop);
1092
1093         default:
1094             var_Get(p_input, "time", &val);
1095             secstotimestr(buf1, val.i_time / CLOCK_FREQ);
1096             var_Get(p_input, "length", &val);
1097             secstotimestr(buf2, val.i_time / CLOCK_FREQ);
1098
1099             mvnprintw(y++, 0, COLS, _(" Position : %s/%s"), buf1, buf2);
1100
1101             volume = playlist_VolumeGet(p_playlist);
1102             int mute = playlist_MuteGet(p_playlist);
1103             mvnprintw(y++, 0, COLS,
1104                       mute ? _(" Volume   : Mute") :
1105                       volume >= 0.f ? _(" Volume   : %3ld%%") : _(" Volume   : ----"),
1106                       lroundf(volume * 100.f));
1107
1108             if (!var_Get(p_input, "title", &val)) {
1109                 int i_title_count = var_CountChoices(p_input, "title");
1110                 if (i_title_count > 0)
1111                     mvnprintw(y++, 0, COLS, _(" Title    : %"PRId64"/%d"),
1112                                val.i_int, i_title_count);
1113             }
1114
1115             if (!var_Get(p_input, "chapter", &val)) {
1116                 int i_chapter_count = var_CountChoices(p_input, "chapter");
1117                 if (i_chapter_count > 0) mvnprintw(y++, 0, COLS, _(" Chapter  : %"PRId64"/%d"),
1118                                val.i_int, i_chapter_count);
1119             }
1120         }
1121     } else {
1122         mvnprintw(y++, 0, COLS, _(" Source: <no current item> "));
1123         mvnprintw(y++, 0, COLS, " %s%s%s", repeat, random, loop);
1124         mvnprintw(y++, 0, COLS, _(" [ h for help ]"));
1125         DrawEmptyLine(y++, 0, COLS);
1126     }
1127
1128     if (sys->color) color_set(C_DEFAULT, NULL);
1129     DrawBox(y++, 1, sys->color, ""); /* position slider */
1130     DrawEmptyLine(y, 1, COLS-2);
1131     if (p_input)
1132         DrawLine(y, 1, (int)((COLS-2) * var_GetFloat(p_input, "position")));
1133
1134     y += 2; /* skip slider and box */
1135
1136     return y;
1137 }
1138
1139 static void FillTextBox(intf_sys_t *sys)
1140 {
1141     int width = COLS - 2;
1142
1143     DrawEmptyLine(7, 1, width);
1144     if (sys->box_type == BOX_OPEN)
1145         mvnprintw(7, 1, width, _("Open: %s"), sys->open_chain);
1146     else
1147         mvnprintw(7, 1, width, _("Find: %s"), sys->search_chain);
1148 }
1149
1150 static void FillBox(intf_thread_t *intf)
1151 {
1152     intf_sys_t *sys = intf->p_sys;
1153     static int (* const draw[]) (intf_thread_t *) = {
1154         [BOX_HELP]      = DrawHelp,
1155         [BOX_INFO]      = DrawInfo,
1156         [BOX_META]      = DrawMeta,
1157         [BOX_OBJECTS]   = DrawObjects,
1158         [BOX_STATS]     = DrawStats,
1159         [BOX_BROWSE]    = DrawBrowse,
1160         [BOX_PLAYLIST]  = DrawPlaylist,
1161         [BOX_SEARCH]    = DrawPlaylist,
1162         [BOX_OPEN]      = DrawPlaylist,
1163         [BOX_LOG]       = DrawMessages,
1164     };
1165
1166     sys->box_lines_total = draw[sys->box_type](intf);
1167
1168     if (sys->box_type == BOX_SEARCH || sys->box_type == BOX_OPEN)
1169         FillTextBox(sys);
1170 }
1171
1172 static void Redraw(intf_thread_t *intf)
1173 {
1174     intf_sys_t *sys   = intf->p_sys;
1175     int         box     = sys->box_type;
1176     int         y       = DrawStatus(intf);
1177
1178     sys->box_height = LINES - y - 2;
1179     DrawBox(y++, sys->box_height, sys->color, _(box_title[box]));
1180
1181     sys->box_y = y;
1182
1183     if (box != BOX_NONE) {
1184         FillBox(intf);
1185
1186         if (sys->box_lines_total == 0)
1187             sys->box_start = 0;
1188         else if (sys->box_start > sys->box_lines_total - 1)
1189             sys->box_start = sys->box_lines_total - 1;
1190         y += __MIN(sys->box_lines_total - sys->box_start,
1191                    sys->box_height);
1192     }
1193
1194     while (y < LINES - 1)
1195         DrawEmptyLine(y++, 1, COLS - 2);
1196
1197     refresh();
1198 }
1199
1200 static void ChangePosition(intf_thread_t *intf, float increment)
1201 {
1202     intf_sys_t     *sys = intf->p_sys;
1203     input_thread_t *p_input = sys->p_input;
1204     float pos;
1205
1206     if (!p_input || var_GetInteger(p_input, "state") != PLAYING_S)
1207         return;
1208
1209     pos = var_GetFloat(p_input, "position") + increment;
1210
1211     if (pos > 0.99) pos = 0.99;
1212     if (pos < 0.0)  pos = 0.0;
1213
1214     var_SetFloat(p_input, "position", pos);
1215 }
1216
1217 static inline void RemoveLastUTF8Entity(char *psz, int len)
1218 {
1219     while (len && ((psz[--len] & 0xc0) == 0x80))    /* UTF8 continuation byte */
1220         ;
1221     psz[len] = '\0';
1222 }
1223
1224 static char *GetDiscDevice(intf_thread_t *intf, const char *name)
1225 {
1226     static const struct { const char *s; size_t n; const char *v; } devs[] =
1227     {
1228         { "cdda://", 7, "cd-audio", },
1229         { "dvd://",  6, "dvd",      },
1230         { "vcd://",  6, "vcd",      },
1231     };
1232     char *device;
1233
1234     for (unsigned i = 0; i < sizeof devs / sizeof *devs; i++) {
1235         size_t n = devs[i].n;
1236         if (!strncmp(name, devs[i].s, n)) {
1237             if (name[n] == '@' || name[n] == '\0')
1238                 return config_GetPsz(intf, devs[i].v);
1239             /* Omit the beginning MRL-selector characters */
1240             return strdup(name + n);
1241         }
1242     }
1243
1244     device = strdup(name);
1245
1246     if (device) /* Remove what we have after @ */
1247         device[strcspn(device, "@")] = '\0';
1248
1249     return device;
1250 }
1251
1252 static void Eject(intf_thread_t *intf)
1253 {
1254     char *device, *name;
1255     playlist_t * p_playlist = pl_Get(intf);
1256
1257     /* If there's a stream playing, we aren't allowed to eject ! */
1258     if (intf->p_sys->p_input)
1259         return;
1260
1261     PL_LOCK;
1262
1263     if (!playlist_CurrentPlayingItem(p_playlist)) {
1264         PL_UNLOCK;
1265         return;
1266     }
1267
1268     name = playlist_CurrentPlayingItem(p_playlist)->p_input->psz_name;
1269     device = name ? GetDiscDevice(intf, name) : NULL;
1270
1271     PL_UNLOCK;
1272
1273     if (device) {
1274         intf_Eject(intf, device);
1275         free(device);
1276     }
1277 }
1278
1279 static void PlayPause(intf_thread_t *intf)
1280 {
1281     input_thread_t *p_input = intf->p_sys->p_input;
1282
1283     if (p_input) {
1284         int64_t state = var_GetInteger( p_input, "state" );
1285         state = (state != PLAYING_S) ? PLAYING_S : PAUSE_S;
1286         var_SetInteger( p_input, "state", state );
1287     } else
1288         playlist_Play(pl_Get(intf));
1289 }
1290
1291 static inline void BoxSwitch(intf_sys_t *sys, int box)
1292 {
1293     sys->box_type = (sys->box_type == box) ? BOX_NONE : box;
1294     sys->box_start = 0;
1295     sys->box_idx = 0;
1296 }
1297
1298 static bool HandlePlaylistKey(intf_thread_t *intf, int key)
1299 {
1300     intf_sys_t *sys = intf->p_sys;
1301     playlist_t *p_playlist = pl_Get(intf);
1302     struct pl_item_t *p_pl_item;
1303
1304     switch(key)
1305     {
1306     /* Playlist Settings */
1307     case 'r': var_ToggleBool(p_playlist, "random"); return true;
1308     case 'l': var_ToggleBool(p_playlist, "loop");   return true;
1309     case 'R': var_ToggleBool(p_playlist, "repeat"); return true;
1310
1311     /* Playlist sort */
1312     case 'o':
1313     case 'O':
1314         playlist_RecursiveNodeSort(p_playlist, p_playlist->p_root_onelevel,
1315                                     SORT_TITLE_NODES_FIRST,
1316                                     (key == 'o')? ORDER_NORMAL : ORDER_REVERSE);
1317         vlc_mutex_lock(&sys->pl_lock);
1318         sys->need_update = true;
1319         vlc_mutex_unlock(&sys->pl_lock);
1320         return true;
1321
1322     case ';':
1323         SearchPlaylist(sys);
1324         return true;
1325
1326     case 'g':
1327         FindIndex(sys, p_playlist);
1328         return true;
1329
1330     /* Deletion */
1331     case 'D':
1332     case KEY_BACKSPACE:
1333     case 0x7f:
1334     case KEY_DC:
1335     {
1336         playlist_item_t *item;
1337
1338         PL_LOCK;
1339         item = sys->plist[sys->box_idx]->item;
1340         if (item->i_children == -1)
1341             playlist_DeleteFromInput(p_playlist, item->p_input, pl_Locked);
1342         else
1343             playlist_NodeDelete(p_playlist, item, true , false);
1344         PL_UNLOCK;
1345         vlc_mutex_lock(&sys->pl_lock);
1346         if (sys->box_idx >= sys->box_lines_total - 1)
1347             sys->box_idx = sys->box_lines_total - 2;
1348         sys->need_update = true;
1349         vlc_mutex_unlock(&sys->pl_lock);
1350         return true;
1351     }
1352
1353     case KEY_ENTER:
1354     case '\r':
1355     case '\n':
1356         if (!(p_pl_item = sys->plist[sys->box_idx]))
1357             return false;
1358
1359         if (p_pl_item->item->i_children) {
1360             playlist_item_t *item, *p_parent = p_pl_item->item;
1361             if (p_parent->i_children == -1) {
1362                 item = p_parent;
1363
1364                 while (p_parent->p_parent)
1365                     p_parent = p_parent->p_parent;
1366             } else {
1367                 vlc_mutex_lock(&sys->pl_lock);
1368                 sys->node = p_parent;
1369                 vlc_mutex_unlock(&sys->pl_lock);
1370                 item = NULL;
1371             }
1372
1373             playlist_Control(p_playlist, PLAYLIST_VIEWPLAY, pl_Unlocked,
1374                               p_parent, item);
1375         } else {   /* We only want to set the current node */
1376             playlist_Stop(p_playlist);
1377             vlc_mutex_lock(&sys->pl_lock);
1378             sys->node = p_pl_item->item;
1379             vlc_mutex_unlock(&sys->pl_lock);
1380         }
1381
1382         sys->plidx_follow = true;
1383         return true;
1384     }
1385
1386     return false;
1387 }
1388
1389 static bool HandleBrowseKey(intf_thread_t *intf, int key)
1390 {
1391     intf_sys_t *sys = intf->p_sys;
1392     struct dir_entry_t *dir_entry;
1393
1394     switch(key)
1395     {
1396     case '.':
1397         sys->show_hidden_files = !sys->show_hidden_files;
1398         ReadDir(intf);
1399         return true;
1400
1401     case KEY_ENTER:
1402     case '\r':
1403     case '\n':
1404     case ' ':
1405         dir_entry = sys->dir_entries[sys->box_idx];
1406         char *path;
1407         if (asprintf(&path, "%s" DIR_SEP "%s", sys->current_dir,
1408                      dir_entry->path) == -1)
1409             return true;
1410
1411         if (!dir_entry->file && key != ' ') {
1412             free(sys->current_dir);
1413             sys->current_dir = path;
1414             ReadDir(intf);
1415
1416             sys->box_start = 0;
1417             sys->box_idx = 0;
1418             return true;
1419         }
1420
1421         char *uri = vlc_path2uri(path, "file");
1422         free(path);
1423         if (uri == NULL)
1424             return true;
1425
1426         playlist_t *p_playlist = pl_Get(intf);
1427         vlc_mutex_lock(&sys->pl_lock);
1428         playlist_item_t *p_parent = sys->node;
1429         vlc_mutex_unlock(&sys->pl_lock);
1430         if (!p_parent) {
1431             playlist_item_t *item;
1432             PL_LOCK;
1433             item = playlist_CurrentPlayingItem(p_playlist);
1434             p_parent = item ? item->p_parent : NULL;
1435             PL_UNLOCK;
1436             if (!p_parent)
1437                 p_parent = p_playlist->p_local_onelevel;
1438         }
1439
1440         while (p_parent->p_parent && p_parent->p_parent->p_parent)
1441             p_parent = p_parent->p_parent;
1442
1443         input_item_t *p_input = p_playlist->p_local_onelevel->p_input;
1444         playlist_Add(p_playlist, uri, NULL, PLAYLIST_APPEND,
1445                       PLAYLIST_END, p_parent->p_input == p_input, false);
1446
1447         BoxSwitch(sys, BOX_PLAYLIST);
1448         free(uri);
1449         return true;
1450     }
1451
1452     return false;
1453 }
1454
1455 static void OpenSelection(intf_thread_t *intf)
1456 {
1457     intf_sys_t *sys = intf->p_sys;
1458     char *uri = vlc_path2uri(sys->open_chain, NULL);
1459     if (uri == NULL)
1460         return;
1461
1462     playlist_t *p_playlist = pl_Get(intf);
1463     vlc_mutex_lock(&sys->pl_lock);
1464     playlist_item_t *p_parent = sys->node;
1465     vlc_mutex_unlock(&sys->pl_lock);
1466
1467     PL_LOCK;
1468     if (!p_parent) {
1469         playlist_item_t *current;
1470         current= playlist_CurrentPlayingItem(p_playlist);
1471         p_parent = current ? current->p_parent : NULL;
1472         if (!p_parent)
1473             p_parent = p_playlist->p_local_onelevel;
1474     }
1475
1476     while (p_parent->p_parent && p_parent->p_parent->p_parent)
1477         p_parent = p_parent->p_parent;
1478     PL_UNLOCK;
1479
1480     playlist_Add(p_playlist, uri, NULL,
1481             PLAYLIST_APPEND|PLAYLIST_GO, PLAYLIST_END,
1482             p_parent->p_input == p_playlist->p_local_onelevel->p_input,
1483             false);
1484
1485     sys->plidx_follow = true;
1486     free(uri);
1487 }
1488
1489 static void HandleEditBoxKey(intf_thread_t *intf, int key, int box)
1490 {
1491     intf_sys_t *sys = intf->p_sys;
1492     bool search = box == BOX_SEARCH;
1493     char *str = search ? sys->search_chain: sys->open_chain;
1494     size_t len = strlen(str);
1495
1496     assert(box == BOX_SEARCH || box == BOX_OPEN);
1497
1498     switch(key)
1499     {
1500     case 0x0c:  /* ^l */
1501     case KEY_CLEAR:     clear(); return;
1502
1503     case KEY_ENTER:
1504     case '\r':
1505     case '\n':
1506         if (search)
1507             SearchPlaylist(sys);
1508         else
1509             OpenSelection(intf);
1510
1511         sys->box_type = BOX_PLAYLIST;
1512         return;
1513
1514     case 0x1b: /* ESC */
1515         /* Alt+key combinations return 2 keys in the terminal keyboard:
1516          * ESC, and the 2nd key.
1517          * If some other key is available immediately (where immediately
1518          * means after getch() 1 second delay), that means that the
1519          * ESC key was not pressed.
1520          *
1521          * man 3X curs_getch says:
1522          *
1523          * Use of the escape key by a programmer for a single
1524          * character function is discouraged, as it will cause a delay
1525          * of up to one second while the keypad code looks for a
1526          * following function-key sequence.
1527          *
1528          */
1529         if (getch() == ERR)
1530             sys->box_type = BOX_PLAYLIST;
1531         return;
1532
1533     case KEY_BACKSPACE:
1534     case 0x7f:
1535         RemoveLastUTF8Entity(str, len);
1536         break;
1537
1538     default:
1539         if (len + 1 < (search ? sizeof sys->search_chain
1540                               : sizeof sys->open_chain)) {
1541             str[len + 0] = key;
1542             str[len + 1] = '\0';
1543         }
1544     }
1545
1546     if (search)
1547         SearchPlaylist(sys);
1548 }
1549
1550 static void InputNavigate(input_thread_t* p_input, const char *var)
1551 {
1552     if (p_input)
1553         var_TriggerCallback(p_input, var);
1554 }
1555
1556 static void CycleESTrack(intf_sys_t *sys, const char *var)
1557 {
1558     input_thread_t *input = sys->p_input;
1559
1560     if (!input)
1561         return;
1562
1563     vlc_value_t val;
1564     if (var_Change(input, var, VLC_VAR_GETLIST, &val, NULL) < 0)
1565         return;
1566
1567     vlc_list_t *list = val.p_list;
1568     int64_t current = var_GetInteger(input, var);
1569
1570     int i;
1571     for (i = 0; i < list->i_count; i++)
1572         if (list->p_values[i].i_int == current)
1573             break;
1574
1575     if (++i >= list->i_count)
1576         i = 0;
1577     var_SetInteger(input, var, list->p_values[i].i_int);
1578 }
1579
1580 static void HandleCommonKey(intf_thread_t *intf, int key)
1581 {
1582     intf_sys_t *sys = intf->p_sys;
1583     playlist_t *p_playlist = pl_Get(intf);
1584     switch(key)
1585     {
1586     case 0x1b:  /* ESC */
1587         if (getch() != ERR)
1588             return;
1589
1590     case 'q':
1591     case 'Q':
1592     case KEY_EXIT:
1593         libvlc_Quit(intf->p_libvlc);
1594         sys->exit = true;           // terminate the main loop
1595         return;
1596
1597     case 'h':
1598     case 'H': BoxSwitch(sys, BOX_HELP);       return;
1599     case 'i': BoxSwitch(sys, BOX_INFO);       return;
1600     case 'M': BoxSwitch(sys, BOX_META);       return;
1601     case 'L': BoxSwitch(sys, BOX_LOG);        return;
1602     case 'P': BoxSwitch(sys, BOX_PLAYLIST);   return;
1603     case 'B': BoxSwitch(sys, BOX_BROWSE);     return;
1604     case 'x': BoxSwitch(sys, BOX_OBJECTS);    return;
1605     case 'S': BoxSwitch(sys, BOX_STATS);      return;
1606
1607     case '/': /* Search */
1608         sys->plidx_follow = false;
1609         BoxSwitch(sys, BOX_SEARCH);
1610         return;
1611
1612     case 'A': /* Open */
1613         sys->open_chain[0] = '\0';
1614         BoxSwitch(sys, BOX_OPEN);
1615         return;
1616
1617     /* Navigation */
1618     case KEY_RIGHT: ChangePosition(intf, +0.01); return;
1619     case KEY_LEFT:  ChangePosition(intf, -0.01); return;
1620
1621     /* Common control */
1622     case 'f':
1623         if (sys->p_input) {
1624             vout_thread_t *p_vout = input_GetVout(sys->p_input);
1625             if (p_vout) {
1626                 bool fs = var_ToggleBool(p_playlist, "fullscreen");
1627                 var_SetBool(p_vout, "fullscreen", fs);
1628                 vlc_object_release(p_vout);
1629             }
1630         }
1631         return;
1632
1633     case ' ': PlayPause(intf);            return;
1634     case 's': playlist_Stop(p_playlist);    return;
1635     case 'e': Eject(intf);                return;
1636
1637     case '[': InputNavigate(sys->p_input, "prev-title");      return;
1638     case ']': InputNavigate(sys->p_input, "next-title");      return;
1639     case '<': InputNavigate(sys->p_input, "prev-chapter");    return;
1640     case '>': InputNavigate(sys->p_input, "next-chapter");    return;
1641
1642     case 'p': playlist_Prev(p_playlist);            break;
1643     case 'n': playlist_Next(p_playlist);            break;
1644     case 'a': playlist_VolumeUp(p_playlist, 1, NULL);   break;
1645     case 'z': playlist_VolumeDown(p_playlist, 1, NULL); break;
1646     case 'm': playlist_MuteToggle(p_playlist); break;
1647
1648     case 'c': CycleESTrack(sys, "audio-es"); break;
1649     case 'v': CycleESTrack(sys, "spu-es");   break;
1650     case 'b': CycleESTrack(sys, "video-es"); break;
1651
1652     case 0x0c:  /* ^l */
1653     case KEY_CLEAR:
1654         break;
1655
1656     default:
1657         return;
1658     }
1659
1660     clear();
1661     return;
1662 }
1663
1664 static bool HandleListKey(intf_thread_t *intf, int key)
1665 {
1666     intf_sys_t *sys = intf->p_sys;
1667     playlist_t *p_playlist = pl_Get(intf);
1668
1669     switch(key)
1670     {
1671 #ifdef __FreeBSD__
1672 /* workaround for FreeBSD + xterm:
1673  * see http://www.nabble.com/curses-vs.-xterm-key-mismatch-t3574377.html */
1674     case KEY_SELECT:
1675 #endif
1676     case KEY_END:  sys->box_idx = sys->box_lines_total - 1; break;
1677     case KEY_HOME: sys->box_idx = 0;                            break;
1678     case KEY_UP:   sys->box_idx--;                              break;
1679     case KEY_DOWN: sys->box_idx++;                              break;
1680     case KEY_PPAGE:sys->box_idx -= sys->box_height;         break;
1681     case KEY_NPAGE:sys->box_idx += sys->box_height;         break;
1682     default:
1683         return false;
1684     }
1685
1686     CheckIdx(sys);
1687
1688     if (sys->box_type == BOX_PLAYLIST) {
1689         PL_LOCK;
1690         sys->plidx_follow = IsIndex(sys, p_playlist, sys->box_idx);
1691         PL_UNLOCK;
1692     }
1693
1694     return true;
1695 }
1696
1697 static void HandleKey(intf_thread_t *intf)
1698 {
1699     intf_sys_t *sys = intf->p_sys;
1700     int key = getch();
1701     int box = sys->box_type;
1702
1703     if (key == -1)
1704         return;
1705
1706     if (box == BOX_SEARCH || box == BOX_OPEN) {
1707         HandleEditBoxKey(intf, key, sys->box_type);
1708         return;
1709     }
1710
1711     if (box == BOX_NONE)
1712         switch(key)
1713         {
1714 #ifdef __FreeBSD__
1715         case KEY_SELECT:
1716 #endif
1717         case KEY_END:   ChangePosition(intf, +.99);   return;
1718         case KEY_HOME:  ChangePosition(intf, -1.0);   return;
1719         case KEY_UP:    ChangePosition(intf, +0.05);  return;
1720         case KEY_DOWN:  ChangePosition(intf, -0.05);  return;
1721         default:        HandleCommonKey(intf, key);   return;
1722         }
1723
1724     if (box == BOX_BROWSE   && HandleBrowseKey(intf, key))
1725         return;
1726
1727     if (box == BOX_PLAYLIST && HandlePlaylistKey(intf, key))
1728         return;
1729
1730     if (HandleListKey(intf, key))
1731         return;
1732
1733     HandleCommonKey(intf, key);
1734 }
1735
1736 /*
1737  *
1738  */
1739 static vlc_log_t *msg_Copy (const vlc_log_t *msg)
1740 {
1741     vlc_log_t *copy = (vlc_log_t *)xmalloc (sizeof (*copy));
1742     copy->i_object_id = msg->i_object_id;
1743     copy->psz_object_type = msg->psz_object_type;
1744     copy->psz_module = strdup (msg->psz_module);
1745     copy->psz_header = msg->psz_header ? strdup (msg->psz_header) : NULL;
1746     return copy;
1747 }
1748
1749 static void msg_Free (vlc_log_t *msg)
1750 {
1751     free ((char *)msg->psz_module);
1752     free ((char *)msg->psz_header);
1753     free (msg);
1754 }
1755
1756 static void MsgCallback(void *data, int type, const vlc_log_t *msg,
1757                         const char *format, va_list ap)
1758 {
1759     intf_sys_t *sys = data;
1760     char *text;
1761
1762     if (sys->verbosity < 0
1763      || sys->verbosity < (type - VLC_MSG_ERR)
1764      || vasprintf(&text, format, ap) == -1)
1765         return;
1766
1767     vlc_mutex_lock(&sys->msg_lock);
1768
1769     sys->msgs[sys->i_msgs].type = type;
1770     if (sys->msgs[sys->i_msgs].item != NULL)
1771         msg_Free(sys->msgs[sys->i_msgs].item);
1772     sys->msgs[sys->i_msgs].item = msg_Copy(msg);
1773     free(sys->msgs[sys->i_msgs].msg);
1774     sys->msgs[sys->i_msgs].msg = text;
1775
1776     if (++sys->i_msgs == (sizeof sys->msgs / sizeof *sys->msgs))
1777         sys->i_msgs = 0;
1778
1779     vlc_mutex_unlock(&sys->msg_lock);
1780 }
1781
1782 static inline void UpdateInput(intf_sys_t *sys, playlist_t *p_playlist)
1783 {
1784     if (!sys->p_input) {
1785         sys->p_input = playlist_CurrentInput(p_playlist);
1786     } else if (sys->p_input->b_dead) {
1787         vlc_object_release(sys->p_input);
1788         sys->p_input = NULL;
1789     }
1790 }
1791
1792 /*****************************************************************************
1793  * Run: ncurses thread
1794  *****************************************************************************/
1795 static void *Run(void *data)
1796 {
1797     intf_thread_t *intf = data;
1798     intf_sys_t    *sys = intf->p_sys;
1799     playlist_t    *p_playlist = pl_Get(intf);
1800
1801     var_AddCallback(p_playlist, "intf-change", PlaylistChanged, intf);
1802     var_AddCallback(p_playlist, "item-change", ItemChanged, intf);
1803     var_AddCallback(p_playlist, "playlist-item-append", PlaylistChanged, intf);
1804
1805     while (!sys->exit) {
1806         UpdateInput(sys, p_playlist);
1807         Redraw(intf);
1808         HandleKey(intf);
1809     }
1810
1811     var_DelCallback(p_playlist, "intf-change", PlaylistChanged, intf);
1812     var_DelCallback(p_playlist, "item-change", ItemChanged, intf);
1813     var_DelCallback(p_playlist, "playlist-item-append", PlaylistChanged, intf);
1814     return NULL;
1815 }
1816
1817 /*****************************************************************************
1818  * Open: initialize and create window
1819  *****************************************************************************/
1820 static int Open(vlc_object_t *p_this)
1821 {
1822     intf_thread_t *intf = (intf_thread_t *)p_this;
1823     intf_sys_t    *sys  = intf->p_sys = calloc(1, sizeof(intf_sys_t));
1824     playlist_t    *p_playlist = pl_Get(p_this);
1825
1826     if (!sys)
1827         return VLC_ENOMEM;
1828
1829     vlc_mutex_init(&sys->msg_lock);
1830     vlc_mutex_init(&sys->pl_lock);
1831
1832     sys->verbosity = var_InheritInteger(intf, "verbose");
1833     vlc_LogSet(intf->p_libvlc, MsgCallback, sys);
1834
1835     sys->box_type = BOX_PLAYLIST;
1836     sys->plidx_follow = true;
1837     sys->color = var_CreateGetBool(intf, "color");
1838
1839     sys->current_dir = var_CreateGetNonEmptyString(intf, "browse-dir");
1840     if (!sys->current_dir)
1841         sys->current_dir = config_GetUserDir(VLC_HOME_DIR);
1842
1843     initscr();   /* Initialize the curses library */
1844
1845     if (sys->color)
1846         start_color_and_pairs(intf);
1847
1848     keypad(stdscr, TRUE);
1849     nonl();                 /* Don't do NL -> CR/NL */
1850     cbreak();               /* Take input chars one at a time */
1851     noecho();               /* Don't echo */
1852     curs_set(0);            /* Invisible cursor */
1853     timeout(1000);          /* blocking getch() */
1854     clear();
1855
1856     /* Stop printing errors to the console */
1857     if (!freopen("/dev/null", "wb", stderr))
1858         msg_Err(intf, "Couldn't close stderr (%s)", vlc_strerror_c(errno));
1859
1860     ReadDir(intf);
1861     PL_LOCK;
1862     PlaylistRebuild(intf),
1863     PL_UNLOCK;
1864
1865     if (vlc_clone(&sys->thread, Run, intf, VLC_THREAD_PRIORITY_LOW))
1866         abort(); /* TODO */
1867
1868     return VLC_SUCCESS;
1869 }
1870
1871 /*****************************************************************************
1872  * Close: destroy interface window
1873  *****************************************************************************/
1874 static void Close(vlc_object_t *p_this)
1875 {
1876     intf_sys_t *sys = ((intf_thread_t*)p_this)->p_sys;
1877
1878     vlc_join(sys->thread, NULL);
1879
1880     PlaylistDestroy(sys);
1881     DirsDestroy(sys);
1882
1883     free(sys->current_dir);
1884
1885     if (sys->p_input)
1886         vlc_object_release(sys->p_input);
1887
1888     endwin();   /* Close the ncurses interface */
1889
1890     vlc_LogSet(p_this->p_libvlc, NULL, NULL);
1891     vlc_mutex_destroy(&sys->msg_lock);
1892     vlc_mutex_destroy(&sys->pl_lock);
1893     for(unsigned i = 0; i < sizeof sys->msgs / sizeof *sys->msgs; i++) {
1894         if (sys->msgs[i].item)
1895             msg_Free(sys->msgs[i].item);
1896         free(sys->msgs[i].msg);
1897     }
1898     free(sys);
1899 }