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