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