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