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