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