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