]> git.sesse.net Git - vlc/blob - modules/gui/ncurses.c
ncurses: fix buffer overflow when typing in the edit box
[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]",
782                      vlc_meta_TypeToLocalizedString(i));
783         if (p_sys->b_color) color_set(C_DEFAULT, NULL);
784         MainBoxWrite(p_sys, l++, "      %s", psz_meta);
785     }
786     vlc_mutex_unlock(&p_item->lock);
787
788     return l;
789 }
790
791 static int DrawInfo(intf_thread_t *p_intf)
792 {
793     intf_sys_t *p_sys = p_intf->p_sys;
794     input_thread_t *p_input = p_sys->p_input;
795     input_item_t *p_item;
796     int l = 0;
797
798     if (!p_input)
799         return 0;
800
801     p_item = input_GetItem(p_input);
802     vlc_mutex_lock(&p_item->lock);
803     for(int i = 0; i < p_item->i_categories; i++)
804     {
805         info_category_t *p_category = p_item->pp_categories[i];
806         if (p_sys->b_color) color_set(C_CATEGORY, NULL);
807         MainBoxWrite(p_sys, l++, _("  [%s]"), p_category->psz_name);
808         if (p_sys->b_color) color_set(C_DEFAULT, NULL);
809         for(int j = 0; j < p_category->i_infos; j++)
810         {
811             info_t *p_info = p_category->pp_infos[j];
812             MainBoxWrite(p_sys, l++, _("      %s: %s"),
813                          p_info->psz_name, p_info->psz_value);
814         }
815     }
816     vlc_mutex_unlock(&p_item->lock);
817
818     return l;
819 }
820
821 static int DrawStats(intf_thread_t *p_intf)
822 {
823     intf_sys_t *p_sys = p_intf->p_sys;
824     input_thread_t *p_input = p_sys->p_input;
825     input_item_t *p_item;
826     input_stats_t *p_stats;
827     int l = 0, i_audio = 0, i_video = 0;
828
829     if (!p_input)
830         return 0;
831
832     p_item = input_GetItem(p_input);
833     assert(p_item);
834
835     vlc_mutex_lock(&p_item->lock);
836     p_stats = p_item->p_stats;
837     vlc_mutex_lock(&p_stats->lock);
838
839     for(int i = 0; i < p_item->i_es ; i++)
840     {
841         i_audio += (p_item->es[i]->i_cat == AUDIO_ES);
842         i_video += (p_item->es[i]->i_cat == VIDEO_ES);
843     }
844
845     /* Input */
846     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
847     MainBoxWrite(p_sys, l++, _("  [Incoming]"));
848     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
849     MainBoxWrite(p_sys, l++, _("      input bytes read : %8.0f KiB"),
850             (float)(p_stats->i_read_bytes)/1024);
851     MainBoxWrite(p_sys, l++, _("      input bitrate    :   %6.0f kb/s"),
852             p_stats->f_input_bitrate*8000);
853     MainBoxWrite(p_sys, l++, _("      demux bytes read : %8.0f KiB"),
854             (float)(p_stats->i_demux_read_bytes)/1024);
855     MainBoxWrite(p_sys, l++, _("      demux bitrate    :   %6.0f kb/s"),
856             p_stats->f_demux_bitrate*8000);
857
858     /* Video */
859     if (i_video)
860     {
861         if (p_sys->b_color) color_set(C_CATEGORY, NULL);
862         MainBoxWrite(p_sys, l++, _("  [Video Decoding]"));
863         if (p_sys->b_color) color_set(C_DEFAULT, NULL);
864         MainBoxWrite(p_sys, l++, _("      video decoded    :    %"PRId64),
865                 p_stats->i_decoded_video);
866         MainBoxWrite(p_sys, l++, _("      frames displayed :    %"PRId64),
867                 p_stats->i_displayed_pictures);
868         MainBoxWrite(p_sys, l++, _("      frames lost      :    %"PRId64),
869                 p_stats->i_lost_pictures);
870     }
871     /* Audio*/
872     if (i_audio)
873     {
874         if (p_sys->b_color) color_set(C_CATEGORY, NULL);
875         MainBoxWrite(p_sys, l++, _("  [Audio Decoding]"));
876         if (p_sys->b_color) color_set(C_DEFAULT, NULL);
877         MainBoxWrite(p_sys, l++, _("      audio decoded    :    %"PRId64),
878                 p_stats->i_decoded_audio);
879         MainBoxWrite(p_sys, l++, _("      buffers played   :    %"PRId64),
880                 p_stats->i_played_abuffers);
881         MainBoxWrite(p_sys, l++, _("      buffers lost     :    %"PRId64),
882                 p_stats->i_lost_abuffers);
883     }
884     /* Sout */
885     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
886     MainBoxWrite(p_sys, l++, _("  [Streaming]"));
887     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
888     MainBoxWrite(p_sys, l++, _("      packets sent     :    %5i"), p_stats->i_sent_packets);
889     MainBoxWrite(p_sys, l++, _("      bytes sent       : %8.0f KiB"),
890             (float)(p_stats->i_sent_bytes)/1025);
891     MainBoxWrite(p_sys, l++, _("      sending bitrate  :   %6.0f kb/s"),
892             p_stats->f_send_bitrate*8000);
893     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
894
895     vlc_mutex_unlock(&p_stats->lock);
896     vlc_mutex_unlock(&p_item->lock);
897
898     return l;
899 }
900
901 static int DrawHelp(intf_thread_t *p_intf)
902 {
903     intf_sys_t *p_sys = p_intf->p_sys;
904     int l = 0;
905
906 #define H(a) MainBoxWrite(p_sys, l++, a)
907
908     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
909     H(_("[Display]"));
910     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
911     H(_(" h,H                    Show/Hide help box"));
912     H(_(" i                      Show/Hide info box"));
913     H(_(" m                      Show/Hide metadata box"));
914     H(_(" L                      Show/Hide messages box"));
915     H(_(" P                      Show/Hide playlist box"));
916     H(_(" B                      Show/Hide filebrowser"));
917     H(_(" x                      Show/Hide objects box"));
918     H(_(" S                      Show/Hide statistics box"));
919     H(_(" Esc                    Close Add/Search entry"));
920     H(_(" Ctrl-l                 Refresh the screen"));
921     H("");
922
923     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
924     H(_("[Global]"));
925     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
926     H(_(" q, Q, Esc              Quit"));
927     H(_(" s                      Stop"));
928     H(_(" <space>                Pause/Play"));
929     H(_(" f                      Toggle Fullscreen"));
930     H(_(" n, p                   Next/Previous playlist item"));
931     H(_(" [, ]                   Next/Previous title"));
932     H(_(" <, >                   Next/Previous chapter"));
933     /* xgettext: You can use ← and → characters */
934     H(_(" <left>,<right>         Seek -/+ 1%%"));
935     H(_(" a, z                   Volume Up/Down"));
936     /* xgettext: You can use ↑ and ↓ characters */
937     H(_(" <up>,<down>            Navigate through the box line by line"));
938     /* xgettext: You can use ⇞ and ⇟ characters */
939     H(_(" <pageup>,<pagedown>    Navigate through the box page by page"));
940     /* xgettext: You can use ↖ and ↘ characters */
941     H(_(" <start>,<end>          Navigate to start/end of box"));
942     H("");
943
944     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
945     H(_("[Playlist]"));
946     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
947     H(_(" r                      Toggle Random playing"));
948     H(_(" l                      Toggle Loop Playlist"));
949     H(_(" R                      Toggle Repeat item"));
950     H(_(" o                      Order Playlist by title"));
951     H(_(" O                      Reverse order Playlist by title"));
952     H(_(" g                      Go to the current playing item"));
953     H(_(" /                      Look for an item"));
954     H(_(" A                      Add an entry"));
955     /* xgettext: You can use ⌫ character to translate <backspace> */
956     H(_(" D, <backspace>, <del>  Delete an entry"));
957     H(_(" e                      Eject (if stopped)"));
958     H("");
959
960     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
961     H(_("[Filebrowser]"));
962     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
963     H(_(" <enter>                Add the selected file to the playlist"));
964     H(_(" <space>                Add the selected directory to the playlist"));
965     H(_(" .                      Show/Hide hidden files"));
966     H("");
967
968     if (p_sys->b_color) color_set(C_CATEGORY, NULL);
969     H(_("[Player]"));
970     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
971     /* xgettext: You can use ↑ and ↓ characters */
972     H(_(" <up>,<down>            Seek +/-5%%"));
973
974 #undef H
975     return l;
976 }
977
978 static int DrawBrowse(intf_thread_t *p_intf)
979 {
980     intf_sys_t *p_sys = p_intf->p_sys;
981
982     for(int i = 0; i < p_sys->i_dir_entries; i++)
983     {
984         struct dir_entry_t *p_dir_entry = p_sys->pp_dir_entries[i];
985         char type = p_dir_entry->b_file ? ' ' : '+';
986
987         if (p_sys->b_color)
988             color_set(p_dir_entry->b_file ? C_DEFAULT : C_FOLDER, NULL);
989         MainBoxWrite(p_sys, i, " %c %s", type, p_dir_entry->psz_path);
990     }
991
992     return p_sys->i_dir_entries;
993 }
994
995 static int DrawPlaylist(intf_thread_t *p_intf)
996 {
997     intf_sys_t *p_sys = p_intf->p_sys;
998     playlist_t *p_playlist = pl_Get(p_intf);
999
1000     if (p_sys->b_need_update)
1001     {
1002         PlaylistRebuild(p_intf);
1003         p_sys->b_need_update = false;
1004     }
1005
1006     if (p_sys->b_plidx_follow)
1007         FindIndex(p_sys, p_playlist);
1008
1009     for(int i = 0; i < p_sys->i_plist_entries; i++)
1010     {
1011         char c;
1012         playlist_item_t *p_current_item;
1013         playlist_item_t *p_item = p_sys->pp_plist[i]->p_item;
1014         playlist_item_t *p_node = p_sys->p_node;
1015
1016         PL_LOCK;
1017         assert(p_item);
1018         p_current_item = playlist_CurrentPlayingItem(p_playlist);
1019         if ((p_node && p_item->p_input == p_node->p_input) ||
1020            (!p_node && p_current_item && p_item->p_input == p_current_item->p_input))
1021             c = '*';
1022         else if (p_item == p_node || p_current_item == p_item)
1023             c = '>';
1024         else
1025             c = ' ';
1026         PL_UNLOCK;
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
1061     vlc_mutex_unlock(&p_sys->msg_lock);
1062     if (p_sys->b_color)
1063         color_set(C_DEFAULT, NULL);
1064     return l;
1065 }
1066
1067 static int DrawStatus(intf_thread_t *p_intf)
1068 {
1069     intf_sys_t     *p_sys = p_intf->p_sys;
1070     input_thread_t *p_input = p_sys->p_input;
1071     playlist_t     *p_playlist = pl_Get(p_intf);
1072     static const char name[] = "VLC media player "PACKAGE_VERSION;
1073     const size_t name_len = sizeof name - 1; /* without \0 termination */
1074     int y = 0;
1075     const char *repeat, *loop, *random;
1076
1077
1078     /* Title */
1079     int padding = COLS - name_len; /* center title */
1080     if (padding < 0)
1081         padding = 0;
1082
1083     attrset(A_REVERSE);
1084     if (p_sys->b_color) color_set(C_TITLE, NULL);
1085     DrawEmptyLine(y, 0, COLS);
1086     mvnprintw(y++, padding / 2, COLS, "%s", name);
1087     if (p_sys->b_color) color_set(C_STATUS, NULL);
1088     attroff(A_REVERSE);
1089
1090     y++; /* leave a blank line */
1091
1092     repeat = var_GetBool(p_playlist, "repeat") ? _("[Repeat] ") : "";
1093     random = var_GetBool(p_playlist, "random") ? _("[Random] ") : "";
1094     loop   = var_GetBool(p_playlist, "loop")   ? _("[Loop]")    : "";
1095
1096     if (p_input && !p_input->b_dead)
1097     {
1098         vlc_value_t val;
1099
1100         char *psz_uri = input_item_GetURI(input_GetItem(p_input));
1101         mvnprintw(y++, 0, COLS, _(" Source   : %s"), psz_uri);
1102         free(psz_uri);
1103
1104         var_Get(p_input, "state", &val);
1105         switch(val.i_int)
1106         {
1107             static const char *input_state[] = {
1108                 [PLAYING_S] = " State    : Playing %s%s%s",
1109                 [OPENING_S] = " State    : Opening/Connecting %s%s%s",
1110                 [PAUSE_S]   = " State    : Paused %s%s%s",
1111             };
1112             char buf1[MSTRTIME_MAX_SIZE];
1113             char buf2[MSTRTIME_MAX_SIZE];
1114             audio_volume_t i_volume;
1115
1116         case INIT_S:
1117         case END_S:
1118             y += 2;
1119             break;
1120
1121         case PLAYING_S:
1122         case OPENING_S:
1123         case PAUSE_S:
1124             mvnprintw(y++, 0, COLS, _(input_state[val.i_int]),
1125                         repeat, random, loop);
1126
1127         default:
1128             var_Get(p_input, "time", &val);
1129             secstotimestr(buf1, val.i_time / CLOCK_FREQ);
1130             var_Get(p_input, "length", &val);
1131             secstotimestr(buf2, val.i_time / CLOCK_FREQ);
1132
1133             mvnprintw(y++, 0, COLS, _(" Position : %s/%s"), buf1, buf2);
1134
1135             aout_VolumeGet(p_playlist, &i_volume);
1136             mvnprintw(y++, 0, COLS, _(" Volume   : %i%%"),
1137                        i_volume*200/AOUT_VOLUME_MAX);
1138
1139             if (!var_Get(p_input, "title", &val))
1140             {
1141                 int i_title_count = var_CountChoices(p_input, "title");
1142                 if (i_title_count > 0)
1143                     mvnprintw(y++, 0, COLS, _(" Title    : %"PRId64"/%d"),
1144                                val.i_int, i_title_count);
1145             }
1146
1147             if (!var_Get(p_input, "chapter", &val))
1148             {
1149                 int i_chapter_count = var_CountChoices(p_input, "chapter");
1150                 if (i_chapter_count > 0)
1151                     mvnprintw(y++, 0, COLS, _(" Chapter  : %"PRId64"/%d"),
1152                                val.i_int, i_chapter_count);
1153             }
1154         }
1155     }
1156     else
1157     {
1158         mvnprintw(y++, 0, COLS, _(" Source: <no current item> "));
1159         mvnprintw(y++, 0, COLS, " %s%s%s", repeat, random, loop);
1160         mvnprintw(y++, 0, COLS, _(" [ h for help ]"));
1161         DrawEmptyLine(y++, 0, COLS);
1162     }
1163
1164     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
1165     DrawBox(y++, 1, p_sys->b_color, ""); /* position slider */
1166     DrawEmptyLine(y, 1, COLS-2);
1167     if (p_input)
1168         DrawLine(y, 1, (int)((COLS-2) * var_GetFloat(p_input, "position")));
1169
1170     y += 2; /* skip slider and box */
1171
1172     return y;
1173 }
1174
1175 static void FillTextBox(intf_sys_t *p_sys)
1176 {
1177     int width = COLS - 2;
1178     const char *title = p_sys->i_box_type == BOX_OPEN ? "Open: %s" : "Find: %s";
1179     char *chain = p_sys->i_box_type == BOX_OPEN ? p_sys->psz_open_chain :
1180                     p_sys->psz_old_search ?  p_sys->psz_old_search :
1181                      p_sys->psz_search_chain;
1182
1183     DrawEmptyLine(7, 1, width);
1184     mvnprintw(7, 1, width, _(title), chain);
1185 }
1186
1187 static void FillBox(intf_thread_t *p_intf)
1188 {
1189     intf_sys_t *p_sys = p_intf->p_sys;
1190     static int (* const draw[]) (intf_thread_t *) = {
1191         [BOX_HELP]      = DrawHelp,
1192         [BOX_INFO]      = DrawInfo,
1193         [BOX_META]      = DrawMeta,
1194         [BOX_OBJECTS]   = DrawObjects,
1195         [BOX_STATS]     = DrawStats,
1196         [BOX_BROWSE]    = DrawBrowse,
1197         [BOX_PLAYLIST]  = DrawPlaylist,
1198         [BOX_SEARCH]    = DrawPlaylist,
1199         [BOX_OPEN]      = DrawPlaylist,
1200         [BOX_LOG]       = DrawMessages,
1201     };
1202
1203     p_sys->i_box_lines_total = draw[p_sys->i_box_type](p_intf);
1204
1205     if (p_sys->i_box_type == BOX_SEARCH || p_sys->i_box_type == BOX_OPEN)
1206         FillTextBox(p_sys);
1207 }
1208
1209 static void Redraw(intf_thread_t *p_intf)
1210 {
1211     intf_sys_t *p_sys   = p_intf->p_sys;
1212     int         box     = p_sys->i_box_type;
1213     int         y       = DrawStatus(p_intf);
1214
1215     p_sys->i_box_height = LINES - y - 2;
1216     DrawBox(y++, p_sys->i_box_height, p_sys->b_color, _(box_title[box]));
1217
1218     p_sys->i_box_y = y;
1219
1220     if (box != BOX_NONE)
1221     {
1222         FillBox(p_intf);
1223
1224         if (p_sys->i_box_start > p_sys->i_box_lines_total - 1)
1225             p_sys->i_box_start = p_sys->i_box_lines_total - 1;
1226         y += __MIN(p_sys->i_box_lines_total - p_sys->i_box_start,
1227                    p_sys->i_box_height);
1228     }
1229
1230     while (y < LINES - 1)
1231         DrawEmptyLine(y++, 1, COLS - 2);
1232
1233     refresh();
1234 }
1235
1236 static void ChangePosition(intf_thread_t *p_intf, float increment)
1237 {
1238     intf_sys_t     *p_sys = p_intf->p_sys;
1239     input_thread_t *p_input = p_sys->p_input;
1240     float pos;
1241
1242     if (!p_input || var_GetInteger(p_input, "state") != PLAYING_S)
1243         return;
1244
1245     pos = var_GetFloat(p_input, "position") + increment;
1246
1247     if (pos > 0.99) pos = 0.99;
1248     if (pos < 0.0)  pos = 0.0;
1249
1250     var_SetFloat(p_input, "position", pos);
1251 }
1252
1253 static inline void RemoveLastUTF8Entity(char *psz, int len)
1254 {
1255     while (len && ((psz[--len] & 0xc0) == 0x80))    /* UTF8 continuation byte */
1256         ;
1257     psz[len] = '\0';
1258 }
1259
1260 static char *GetDiscDevice(intf_thread_t *p_intf, const char *name)
1261 {
1262     static const struct { const char *s; size_t n; const char *v; } devs[] =
1263     {
1264         { "cdda://", 7, "cd-audio", },
1265         { "dvd://",  6, "dvd",      },
1266         { "vcd://",  6, "vcd",      },
1267     };
1268     char *device;
1269
1270     for (unsigned i = 0; i < sizeof devs / sizeof *devs; i++)
1271     {
1272         size_t n = devs[i].n;
1273         if (!strncmp(name, devs[i].s, n))
1274             switch(name[n])
1275             {
1276             case '\0':
1277             case '@':
1278                 return config_GetPsz(p_intf, devs[i].v);
1279             default:
1280                 /* Omit the beginning MRL-selector characters */
1281                 return strdup(name + n);
1282             }
1283     }
1284
1285     device = strdup(name);
1286
1287     if (device) /* Remove what we have after @ */
1288         device[strcspn(device, "@")] = '\0';
1289
1290     return device;
1291 }
1292
1293 static void Eject(intf_thread_t *p_intf)
1294 {
1295     char *psz_device, *psz_name;
1296     playlist_t * p_playlist = pl_Get(p_intf);
1297
1298     /* If there's a stream playing, we aren't allowed to eject ! */
1299     if (p_intf->p_sys->p_input)
1300         return;
1301
1302     PL_LOCK;
1303
1304     if (!playlist_CurrentPlayingItem(p_playlist))
1305     {
1306         PL_UNLOCK;
1307         return;
1308     }
1309
1310     psz_name = playlist_CurrentPlayingItem(p_playlist)->p_input->psz_name;
1311     psz_device = psz_name ? GetDiscDevice(p_intf, psz_name) : NULL;
1312
1313     PL_UNLOCK;
1314
1315     if (psz_device)
1316     {
1317         intf_Eject(p_intf, psz_device);
1318         free(psz_device);
1319     }
1320 }
1321
1322 static void PlayPause(intf_thread_t *p_intf)
1323 {
1324     input_thread_t *p_input = p_intf->p_sys->p_input;
1325
1326     if (p_input)
1327     {
1328         int64_t state = var_GetInteger( p_input, "state" );
1329         state = (state != PLAYING_S) ? PLAYING_S : PAUSE_S;
1330         var_SetInteger( p_input, "state", state );
1331     }
1332     else
1333         playlist_Play(pl_Get(p_intf));
1334 }
1335
1336 static inline void BoxSwitch(intf_sys_t *p_sys, int box)
1337 {
1338     p_sys->i_box_type = (p_sys->i_box_type == box) ? BOX_NONE : box;
1339     p_sys->i_box_start = 0;
1340     p_sys->i_box_idx = 0;
1341 }
1342
1343 static bool HandlePlaylistKey(intf_thread_t *p_intf, int key)
1344 {
1345     intf_sys_t *p_sys = p_intf->p_sys;
1346     playlist_t *p_playlist = pl_Get(p_intf);
1347     struct pl_item_t *p_pl_item;
1348
1349     switch(key)
1350     {
1351     /* Playlist Settings */
1352     case 'r': var_ToggleBool(p_playlist, "random"); return true;
1353     case 'l': var_ToggleBool(p_playlist, "loop");   return true;
1354     case 'R': var_ToggleBool(p_playlist, "repeat"); return true;
1355
1356     /* Playlist sort */
1357     case 'o':
1358     case 'O':
1359         playlist_RecursiveNodeSort(p_playlist, p_playlist->p_root_onelevel,
1360                                     SORT_TITLE_NODES_FIRST,
1361                                     (key == 'o')? ORDER_NORMAL : ORDER_REVERSE);
1362         p_sys->b_need_update = true;
1363         return true;
1364
1365     case 'g':
1366         FindIndex(p_sys, p_playlist);
1367         return true;
1368
1369     /* Deletion */
1370     case 'D':
1371     case KEY_BACKSPACE:
1372     case 0x7f:
1373     case KEY_DC:
1374     {
1375         playlist_item_t *p_item;
1376
1377         PL_LOCK;
1378         p_item = p_sys->pp_plist[p_sys->i_box_idx]->p_item;
1379         if (p_item->i_children == -1)
1380             playlist_DeleteFromInput(p_playlist, p_item->p_input, pl_Locked);
1381         else
1382             playlist_NodeDelete(p_playlist, p_item, true , false);
1383         PL_UNLOCK;
1384         p_sys->b_need_update = true;
1385         return true;
1386     }
1387
1388     case KEY_ENTER:
1389     case '\r':
1390     case '\n':
1391         if (!(p_pl_item = p_sys->pp_plist[p_sys->i_box_idx]))
1392             return false;
1393
1394         if (p_pl_item->p_item->i_children)
1395         {
1396             playlist_item_t *p_item, *p_parent = p_pl_item->p_item;
1397             if (p_parent->i_children == -1)
1398             {
1399                 p_item = p_parent;
1400
1401                 while (p_parent->p_parent)
1402                     p_parent = p_parent->p_parent;
1403             }
1404             else
1405             {
1406                 p_sys->p_node = p_parent;
1407                 p_item = NULL;
1408             }
1409
1410             playlist_Control(p_playlist, PLAYLIST_VIEWPLAY, pl_Unlocked,
1411                               p_parent, p_item);
1412         }
1413         else
1414         {   /* We only want to set the current node */
1415             playlist_Stop(p_playlist);
1416             p_sys->p_node = p_pl_item->p_item;
1417         }
1418
1419         p_sys->b_plidx_follow = true;
1420         return true;
1421     }
1422
1423     return false;
1424 }
1425
1426 static bool HandleBrowseKey(intf_thread_t *p_intf, int key)
1427 {
1428     intf_sys_t *p_sys = p_intf->p_sys;
1429     struct dir_entry_t *dir_entry;
1430
1431     switch(key)
1432     {
1433     case '.':
1434         p_sys->b_show_hidden_files = !p_sys->b_show_hidden_files;
1435         ReadDir(p_intf);
1436         return true;
1437
1438     case KEY_ENTER:
1439     case '\r':
1440     case '\n':
1441     case ' ':
1442         dir_entry = p_sys->pp_dir_entries[p_sys->i_box_idx];
1443         char *psz_path;
1444         if (asprintf(&psz_path, "%s" DIR_SEP "%s", p_sys->psz_current_dir,
1445                      dir_entry->psz_path) == -1)
1446             return true;
1447
1448         if (!dir_entry->b_file && key != ' ')
1449         {
1450             free(p_sys->psz_current_dir);
1451             p_sys->psz_current_dir = psz_path;
1452             ReadDir(p_intf);
1453
1454             p_sys->i_box_start = 0;
1455             p_sys->i_box_idx = 0;
1456             return true;
1457         }
1458
1459         char *psz_uri = make_URI(psz_path, dir_entry->b_file ? "file"
1460                                                              : "directory");
1461         free(psz_path);
1462         if (psz_uri == NULL)
1463             return true;
1464
1465         playlist_t *p_playlist = pl_Get(p_intf);
1466         playlist_item_t *p_parent = p_sys->p_node;
1467         if (!p_parent)
1468         {
1469             playlist_item_t *p_item;
1470             PL_LOCK;
1471             p_item = playlist_CurrentPlayingItem(p_playlist);
1472             p_parent = p_item ? p_item->p_parent : NULL;
1473             PL_UNLOCK;
1474             if (!p_parent)
1475                 p_parent = p_playlist->p_local_onelevel;
1476         }
1477
1478         while (p_parent->p_parent && p_parent->p_parent->p_parent)
1479             p_parent = p_parent->p_parent;
1480
1481         input_item_t *p_input = p_playlist->p_local_onelevel->p_input;
1482         playlist_Add(p_playlist, psz_uri, NULL, PLAYLIST_APPEND,
1483                       PLAYLIST_END, p_parent->p_input == p_input, false);
1484
1485         BoxSwitch(p_sys, BOX_PLAYLIST);
1486         free(psz_uri);
1487         return true;
1488     }
1489
1490     return false;
1491 }
1492
1493 static void HandleEditBoxKey(intf_thread_t *p_intf, int key, int box)
1494 {
1495     intf_sys_t *p_sys = p_intf->p_sys;
1496     bool search = box == BOX_SEARCH;
1497     char *str = search ? p_sys->psz_search_chain: p_sys->psz_open_chain;
1498     size_t len = strlen(str);
1499
1500     assert(box == BOX_SEARCH || box == BOX_OPEN);
1501
1502     switch(key)
1503     {
1504     case 0x0c:  /* ^l */
1505     case KEY_CLEAR:     clear(); return;
1506
1507     case KEY_ENTER:
1508     case '\r':
1509     case '\n':
1510         if (search)
1511         {
1512             if (len)
1513                 p_sys->psz_old_search = strdup(p_sys->psz_search_chain);
1514             else if (p_sys->psz_old_search)
1515                 SearchPlaylist(p_sys, p_sys->psz_old_search);
1516         }
1517         else if (len)
1518         {
1519             playlist_t *p_playlist = pl_Get(p_intf);
1520             playlist_item_t *p_parent = p_sys->p_node, *p_current;
1521
1522             PL_LOCK;
1523             if (!p_parent)
1524             {
1525                 p_current = playlist_CurrentPlayingItem(p_playlist);
1526                 p_parent = p_current ? p_current->p_parent : NULL;
1527                 if (!p_parent)
1528                     p_parent = p_playlist->p_local_onelevel;
1529             }
1530
1531             while (p_parent->p_parent && p_parent->p_parent->p_parent)
1532                 p_parent = p_parent->p_parent;
1533             PL_UNLOCK;
1534
1535             playlist_Add(p_playlist, p_sys->psz_open_chain, NULL,
1536                   PLAYLIST_APPEND|PLAYLIST_GO, PLAYLIST_END,
1537                   p_parent->p_input == p_playlist->p_local_onelevel->p_input,
1538                   false);
1539
1540             p_sys->b_plidx_follow = true;
1541         }
1542         p_sys->i_box_type = BOX_PLAYLIST;
1543         return;
1544
1545     case 0x1b: /* ESC */
1546         /* Alt+key combinations return 2 keys in the terminal keyboard:
1547          * ESC, and the 2nd key.
1548          * If some other key is available immediately (where immediately
1549          * means after getch() 1 second delay), that means that the
1550          * ESC key was not pressed.
1551          *
1552          * man 3X curs_getch says:
1553          *
1554          * Use of the escape key by a programmer for a single
1555          * character function is discouraged, as it will cause a delay
1556          * of up to one second while the keypad code looks for a
1557          * following function-key sequence.
1558          *
1559          */
1560         if (getch() != ERR)
1561             return;
1562
1563         if (search) p_sys->i_box_idx = p_sys->i_before_search;
1564         p_sys->i_box_type = BOX_PLAYLIST;
1565         return;
1566
1567     case KEY_BACKSPACE:
1568     case 0x7f:
1569         RemoveLastUTF8Entity(str, len);
1570         break;
1571
1572     default:
1573         if (len + 1 < (search ? sizeof p_sys->psz_search_chain
1574                               : sizeof p_sys->psz_open_chain))
1575         {
1576             str[len + 0] = (char) key;
1577             str[len + 1] = '\0';
1578         }
1579     }
1580
1581     if (search)
1582     {
1583         free(p_sys->psz_old_search);
1584         p_sys->psz_old_search = NULL;
1585         SearchPlaylist(p_sys, str);
1586     }
1587 }
1588
1589 static void InputNavigate(input_thread_t* p_input, const char *var)
1590 {
1591     if (p_input)
1592         var_TriggerCallback(p_input, var);
1593 }
1594
1595 static void HandleCommonKey(intf_thread_t *p_intf, int key)
1596 {
1597     intf_sys_t *p_sys = p_intf->p_sys;
1598     playlist_t *p_playlist = pl_Get(p_intf);
1599     switch(key)
1600     {
1601     case 0x1b:  /* ESC */
1602         if (getch() != ERR)
1603             return;
1604
1605     case 'q':
1606     case 'Q':
1607     case KEY_EXIT:
1608         libvlc_Quit(p_intf->p_libvlc);
1609         p_sys->b_exit = true;           // terminate the main loop
1610         return;
1611
1612     case 'h':
1613     case 'H': BoxSwitch(p_sys, BOX_HELP);       return;
1614     case 'i': BoxSwitch(p_sys, BOX_INFO);       return;
1615     case 'm': BoxSwitch(p_sys, BOX_META);       return;
1616     case 'L': BoxSwitch(p_sys, BOX_LOG);        return;
1617     case 'P': BoxSwitch(p_sys, BOX_PLAYLIST);   return;
1618     case 'B': BoxSwitch(p_sys, BOX_BROWSE);     return;
1619     case 'x': BoxSwitch(p_sys, BOX_OBJECTS);    return;
1620     case 'S': BoxSwitch(p_sys, BOX_STATS);      return;
1621
1622     case '/': /* Search */
1623         p_sys->psz_search_chain[0] = '\0';
1624         p_sys->b_plidx_follow = false;
1625         if (p_sys->i_box_type == BOX_PLAYLIST)
1626         {
1627             p_sys->i_before_search = p_sys->i_box_idx;
1628             p_sys->i_box_type = BOX_SEARCH;
1629         }
1630         else
1631         {
1632             p_sys->i_before_search = 0;
1633             BoxSwitch(p_sys, BOX_SEARCH);
1634         }
1635         return;
1636
1637     case 'A': /* Open */
1638         p_sys->psz_open_chain[0] = '\0';
1639         if (p_sys->i_box_type == BOX_PLAYLIST)
1640             p_sys->i_box_type = BOX_OPEN;
1641         else
1642             BoxSwitch(p_sys, BOX_OPEN);
1643         return;
1644
1645     /* Navigation */
1646     case KEY_RIGHT: ChangePosition(p_intf, +0.01); return;
1647     case KEY_LEFT:  ChangePosition(p_intf, -0.01); return;
1648
1649     /* Common control */
1650     case 'f':
1651         if (p_sys->p_input)
1652         {
1653             vout_thread_t *p_vout = input_GetVout(p_sys->p_input);
1654             if (p_vout)
1655             {
1656                 bool fs = var_ToggleBool(p_playlist, "fullscreen");
1657                 var_SetBool(p_vout, "fullscreen", fs);
1658                 vlc_object_release(p_vout);
1659             }
1660         }
1661         return;
1662
1663     case ' ': PlayPause(p_intf);            return;
1664     case 's': playlist_Stop(p_playlist);    return;
1665     case 'e': Eject(p_intf);                return;
1666
1667     case '[': InputNavigate(p_sys->p_input, "prev-title");      return;
1668     case ']': InputNavigate(p_sys->p_input, "next-title");      return;
1669     case '<': InputNavigate(p_sys->p_input, "prev-chapter");    return;
1670     case '>': InputNavigate(p_sys->p_input, "next-chapter");    return;
1671
1672     case 'p': playlist_Prev(p_playlist);            break;
1673     case 'n': playlist_Next(p_playlist);            break;
1674     case 'a': aout_VolumeUp(p_playlist, 1, NULL);   break;
1675     case 'z': aout_VolumeDown(p_playlist, 1, NULL); break;
1676
1677     case 0x0c:  /* ^l */
1678     case KEY_CLEAR:
1679         break;
1680
1681     default:
1682         return;
1683     }
1684
1685     clear();
1686     return;
1687 }
1688
1689 static bool HandleListKey(intf_thread_t *p_intf, int key)
1690 {
1691     intf_sys_t *p_sys = p_intf->p_sys;
1692     playlist_t *p_playlist = pl_Get(p_intf);
1693
1694     switch(key)
1695     {
1696 #ifdef __FreeBSD__
1697 /* workaround for FreeBSD + xterm:
1698  * see http://www.nabble.com/curses-vs.-xterm-key-mismatch-t3574377.html */
1699     case KEY_SELECT:
1700 #endif
1701     case KEY_END:  p_sys->i_box_idx = p_sys->i_box_lines_total - 1; break;
1702     case KEY_HOME: p_sys->i_box_idx = 0;                            break;
1703     case KEY_UP:   p_sys->i_box_idx--;                              break;
1704     case KEY_DOWN: p_sys->i_box_idx++;                              break;
1705     case KEY_PPAGE:p_sys->i_box_idx -= p_sys->i_box_height;         break;
1706     case KEY_NPAGE:p_sys->i_box_idx += p_sys->i_box_height;         break;
1707     default:
1708         return false;
1709     }
1710
1711     CheckIdx(p_sys);
1712
1713     if (p_sys->i_box_type == BOX_PLAYLIST)
1714     {
1715         PL_LOCK;
1716         p_sys->b_plidx_follow = IsIndex(p_sys, p_playlist, p_sys->i_box_idx);
1717         PL_UNLOCK;
1718     }
1719
1720     return true;
1721 }
1722
1723 static void HandleKey(intf_thread_t *p_intf)
1724 {
1725     intf_sys_t *p_sys = p_intf->p_sys;
1726     int key = getch();
1727     int box = p_sys->i_box_type;
1728
1729     if (key == -1)
1730         return;
1731
1732     if (box == BOX_SEARCH || box == BOX_OPEN)
1733     {
1734         HandleEditBoxKey(p_intf, key, p_sys->i_box_type);
1735         return;
1736     }
1737
1738     if (box == BOX_NONE)
1739         switch(key)
1740         {
1741 #ifdef __FreeBSD__
1742         case KEY_SELECT:
1743 #endif
1744         case KEY_END:   ChangePosition(p_intf, +.99);   return;
1745         case KEY_HOME:  ChangePosition(p_intf, -1.0);   return;
1746         case KEY_UP:    ChangePosition(p_intf, +0.05);  return;
1747         case KEY_DOWN:  ChangePosition(p_intf, -0.05);  return;
1748         default:        HandleCommonKey(p_intf, key);   return;
1749         }
1750
1751     if (box == BOX_BROWSE   && HandleBrowseKey(p_intf, key))
1752         return;
1753
1754     if (box == BOX_PLAYLIST && HandlePlaylistKey(p_intf, key))
1755         return;
1756
1757     if (HandleListKey(p_intf, key))
1758         return;
1759
1760     HandleCommonKey(p_intf, key);
1761 }
1762
1763 /*
1764  *
1765  */
1766
1767 static void MsgCallback(msg_cb_data_t *data, msg_item_t *msg, unsigned i)
1768 {
1769     intf_sys_t *p_sys = data->p_sys;
1770     (void)i; // what is this?
1771     int canc = vlc_savecancel();
1772
1773     vlc_mutex_lock(&p_sys->msg_lock);
1774
1775     if (p_sys->msgs[p_sys->i_msgs])
1776         msg_Release(p_sys->msgs[p_sys->i_msgs]);
1777     p_sys->msgs[p_sys->i_msgs++] = msg_Hold(msg);
1778
1779     if (p_sys->i_msgs == (sizeof p_sys->msgs / sizeof *p_sys->msgs))
1780         p_sys->i_msgs = 0;
1781
1782     vlc_mutex_unlock(&p_sys->msg_lock);
1783
1784     vlc_restorecancel(canc);
1785 }
1786
1787 static inline void UpdateInput(intf_sys_t *p_sys, playlist_t *p_playlist)
1788 {
1789     if (!p_sys->p_input)
1790     {
1791         p_sys->p_input = playlist_CurrentInput(p_playlist);
1792     }
1793     else if (p_sys->p_input->b_dead)
1794     {
1795         vlc_object_release(p_sys->p_input);
1796         p_sys->p_input = NULL;
1797     }
1798 }
1799
1800 /*****************************************************************************
1801  * Run: ncurses thread
1802  *****************************************************************************/
1803 static void Run(intf_thread_t *p_intf)
1804 {
1805     intf_sys_t    *p_sys = p_intf->p_sys;
1806     playlist_t    *p_playlist = pl_Get(p_intf);
1807
1808     int canc = vlc_savecancel();
1809
1810     var_AddCallback(p_playlist, "intf-change", PlaylistChanged, p_intf);
1811     var_AddCallback(p_playlist, "playlist-item-append", PlaylistChanged, p_intf);
1812
1813     while (vlc_object_alive(p_intf) && !p_sys->b_exit)
1814     {
1815         UpdateInput(p_sys, p_playlist);
1816         Redraw(p_intf);
1817         HandleKey(p_intf);
1818     }
1819
1820     var_DelCallback(p_playlist, "intf-change", PlaylistChanged, p_intf);
1821     var_DelCallback(p_playlist, "playlist-item-append", PlaylistChanged, p_intf);
1822     vlc_restorecancel(canc);
1823 }
1824
1825 /*****************************************************************************
1826  * Open: initialize and create window
1827  *****************************************************************************/
1828 static int Open(vlc_object_t *p_this)
1829 {
1830     intf_thread_t *p_intf = (intf_thread_t *)p_this;
1831     intf_sys_t    *p_sys  = p_intf->p_sys = calloc(1, sizeof(intf_sys_t));
1832     struct msg_cb_data_t *msg_cb_data;
1833
1834     if (!p_sys)
1835         return VLC_ENOMEM;
1836
1837     msg_cb_data = malloc(sizeof *msg_cb_data);
1838     if (!msg_cb_data)
1839     {
1840         free(p_sys);
1841         return VLC_ENOMEM;
1842     }
1843
1844     msg_cb_data->p_sys = p_sys;
1845     vlc_mutex_init(&p_sys->msg_lock);
1846     p_sys->i_msgs = 0;
1847     memset(p_sys->msgs, 0, sizeof p_sys->msgs);
1848     p_sys->p_sub = msg_Subscribe(p_intf->p_libvlc, MsgCallback, msg_cb_data);
1849     msg_SubscriptionSetVerbosity(p_sys->p_sub,
1850             var_GetInteger(p_intf->p_libvlc, "verbose"));
1851
1852     p_sys->i_box_type = BOX_PLAYLIST;
1853     p_sys->b_plidx_follow = true;
1854     p_sys->b_color = var_CreateGetBool(p_intf, "color");
1855
1856     p_sys->psz_current_dir = var_CreateGetString(p_intf, "browse-dir");
1857     if (!p_sys->psz_current_dir || !*p_sys->psz_current_dir)
1858     {
1859         free(p_sys->psz_current_dir);
1860         p_sys->psz_current_dir = config_GetUserDir(VLC_HOME_DIR);
1861     }
1862
1863     initscr();   /* Initialize the curses library */
1864
1865     if (p_sys->b_color)
1866         start_color_and_pairs(p_intf);
1867
1868     keypad(stdscr, TRUE);   /* Don't do NL -> CR/NL */
1869     nonl();                 /* Take input chars one at a time */
1870     cbreak();               /* Don't echo */
1871     noecho();               /* Invisible cursor */
1872     curs_set(0);            /* Non blocking getch() */
1873     timeout(1000);
1874     clear();
1875
1876     /* Stop printing errors to the console */
1877     if(!freopen("/dev/null", "wb", stderr))
1878         msg_Err(p_intf, "Couldn't close stderr (%m)");
1879
1880     ReadDir(p_intf);
1881     PlaylistRebuild(p_intf),
1882
1883     p_intf->pf_run = Run;
1884     return VLC_SUCCESS;
1885 }
1886
1887 /*****************************************************************************
1888  * Close: destroy interface window
1889  *****************************************************************************/
1890 static void Close(vlc_object_t *p_this)
1891 {
1892     intf_sys_t *p_sys = ((intf_thread_t*)p_this)->p_sys;
1893
1894     PlaylistDestroy(p_sys);
1895     DirsDestroy(p_sys);
1896
1897     free(p_sys->psz_current_dir);
1898     free(p_sys->psz_old_search);
1899
1900     if (p_sys->p_input)
1901         vlc_object_release(p_sys->p_input);
1902
1903     endwin();   /* Close the ncurses interface */
1904
1905     msg_Unsubscribe(p_sys->p_sub);
1906     vlc_mutex_destroy(&p_sys->msg_lock);
1907     for(unsigned i = 0; i < sizeof p_sys->msgs / sizeof *p_sys->msgs; i++)
1908         if (p_sys->msgs[i])
1909             msg_Release(p_sys->msgs[i]);
1910
1911     free(p_sys);
1912 }