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