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