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