]> git.sesse.net Git - vlc/blob - modules/gui/ncurses.c
Update message callback
[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
1099         char *psz_uri = input_item_GetURI(input_GetItem(p_input));
1100         mvnprintw(y++, 0, COLS, _(" Source   : %s"), psz_uri);
1101         free(psz_uri);
1102
1103         var_Get(p_input, "state", &val);
1104         switch(val.i_int)
1105         {
1106             static const char *input_state[] = {
1107                 [PLAYING_S] = " State    : Playing %s%s%s",
1108                 [OPENING_S] = " State    : Opening/Connecting %s%s%s",
1109                 [PAUSE_S]   = " State    : Paused %s%s%s",
1110             };
1111             char buf1[MSTRTIME_MAX_SIZE];
1112             char buf2[MSTRTIME_MAX_SIZE];
1113             audio_volume_t i_volume;
1114
1115         case INIT_S:
1116         case END_S:
1117             y += 2;
1118             break;
1119
1120         case PLAYING_S:
1121         case OPENING_S:
1122         case PAUSE_S:
1123             mvnprintw(y++, 0, COLS, _(input_state[val.i_int]),
1124                         repeat, random, loop);
1125
1126         default:
1127             var_Get(p_input, "time", &val);
1128             secstotimestr(buf1, val.i_time / CLOCK_FREQ);
1129             var_Get(p_input, "length", &val);
1130             secstotimestr(buf2, val.i_time / CLOCK_FREQ);
1131
1132             mvnprintw(y++, 0, COLS, _(" Position : %s/%s"), buf1, buf2);
1133
1134             i_volume = aout_VolumeGet(p_playlist);
1135             mvnprintw(y++, 0, COLS, _(" Volume   : %i%%"),
1136                        i_volume*200/AOUT_VOLUME_MAX);
1137
1138             if (!var_Get(p_input, "title", &val))
1139             {
1140                 int i_title_count = var_CountChoices(p_input, "title");
1141                 if (i_title_count > 0)
1142                     mvnprintw(y++, 0, COLS, _(" Title    : %"PRId64"/%d"),
1143                                val.i_int, i_title_count);
1144             }
1145
1146             if (!var_Get(p_input, "chapter", &val))
1147             {
1148                 int i_chapter_count = var_CountChoices(p_input, "chapter");
1149                 if (i_chapter_count > 0)
1150                     mvnprintw(y++, 0, COLS, _(" Chapter  : %"PRId64"/%d"),
1151                                val.i_int, i_chapter_count);
1152             }
1153         }
1154     }
1155     else
1156     {
1157         mvnprintw(y++, 0, COLS, _(" Source: <no current item> "));
1158         mvnprintw(y++, 0, COLS, " %s%s%s", repeat, random, loop);
1159         mvnprintw(y++, 0, COLS, _(" [ h for help ]"));
1160         DrawEmptyLine(y++, 0, COLS);
1161     }
1162
1163     if (p_sys->b_color) color_set(C_DEFAULT, NULL);
1164     DrawBox(y++, 1, p_sys->b_color, ""); /* position slider */
1165     DrawEmptyLine(y, 1, COLS-2);
1166     if (p_input)
1167         DrawLine(y, 1, (int)((COLS-2) * var_GetFloat(p_input, "position")));
1168
1169     y += 2; /* skip slider and box */
1170
1171     return y;
1172 }
1173
1174 static void FillTextBox(intf_sys_t *p_sys)
1175 {
1176     int width = COLS - 2;
1177     const char *title = p_sys->i_box_type == BOX_OPEN ? "Open: %s" : "Find: %s";
1178     char *chain = p_sys->i_box_type == BOX_OPEN ? p_sys->psz_open_chain :
1179                     p_sys->psz_old_search ?  p_sys->psz_old_search :
1180                      p_sys->psz_search_chain;
1181
1182     DrawEmptyLine(7, 1, width);
1183     mvnprintw(7, 1, width, _(title), chain);
1184 }
1185
1186 static void FillBox(intf_thread_t *p_intf)
1187 {
1188     intf_sys_t *p_sys = p_intf->p_sys;
1189     static int (* const draw[]) (intf_thread_t *) = {
1190         [BOX_HELP]      = DrawHelp,
1191         [BOX_INFO]      = DrawInfo,
1192         [BOX_META]      = DrawMeta,
1193         [BOX_OBJECTS]   = DrawObjects,
1194         [BOX_STATS]     = DrawStats,
1195         [BOX_BROWSE]    = DrawBrowse,
1196         [BOX_PLAYLIST]  = DrawPlaylist,
1197         [BOX_SEARCH]    = DrawPlaylist,
1198         [BOX_OPEN]      = DrawPlaylist,
1199         [BOX_LOG]       = DrawMessages,
1200     };
1201
1202     p_sys->i_box_lines_total = draw[p_sys->i_box_type](p_intf);
1203
1204     if (p_sys->i_box_type == BOX_SEARCH || p_sys->i_box_type == BOX_OPEN)
1205         FillTextBox(p_sys);
1206 }
1207
1208 static void Redraw(intf_thread_t *p_intf)
1209 {
1210     intf_sys_t *p_sys   = p_intf->p_sys;
1211     int         box     = p_sys->i_box_type;
1212     int         y       = DrawStatus(p_intf);
1213
1214     p_sys->i_box_height = LINES - y - 2;
1215     DrawBox(y++, p_sys->i_box_height, p_sys->b_color, _(box_title[box]));
1216
1217     p_sys->i_box_y = y;
1218
1219     if (box != BOX_NONE)
1220     {
1221         FillBox(p_intf);
1222
1223         if (p_sys->i_box_lines_total == 0)
1224             p_sys->i_box_start = 0;
1225         else if (p_sys->i_box_start > p_sys->i_box_lines_total - 1)
1226             p_sys->i_box_start = p_sys->i_box_lines_total - 1;
1227         y += __MIN(p_sys->i_box_lines_total - p_sys->i_box_start,
1228                    p_sys->i_box_height);
1229     }
1230
1231     while (y < LINES - 1)
1232         DrawEmptyLine(y++, 1, COLS - 2);
1233
1234     refresh();
1235 }
1236
1237 static void ChangePosition(intf_thread_t *p_intf, float increment)
1238 {
1239     intf_sys_t     *p_sys = p_intf->p_sys;
1240     input_thread_t *p_input = p_sys->p_input;
1241     float pos;
1242
1243     if (!p_input || var_GetInteger(p_input, "state") != PLAYING_S)
1244         return;
1245
1246     pos = var_GetFloat(p_input, "position") + increment;
1247
1248     if (pos > 0.99) pos = 0.99;
1249     if (pos < 0.0)  pos = 0.0;
1250
1251     var_SetFloat(p_input, "position", pos);
1252 }
1253
1254 static inline void RemoveLastUTF8Entity(char *psz, int len)
1255 {
1256     while (len && ((psz[--len] & 0xc0) == 0x80))    /* UTF8 continuation byte */
1257         ;
1258     psz[len] = '\0';
1259 }
1260
1261 static char *GetDiscDevice(intf_thread_t *p_intf, const char *name)
1262 {
1263     static const struct { const char *s; size_t n; const char *v; } devs[] =
1264     {
1265         { "cdda://", 7, "cd-audio", },
1266         { "dvd://",  6, "dvd",      },
1267         { "vcd://",  6, "vcd",      },
1268     };
1269     char *device;
1270
1271     for (unsigned i = 0; i < sizeof devs / sizeof *devs; i++)
1272     {
1273         size_t n = devs[i].n;
1274         if (!strncmp(name, devs[i].s, n))
1275             switch(name[n])
1276             {
1277             case '\0':
1278             case '@':
1279                 return config_GetPsz(p_intf, devs[i].v);
1280             default:
1281                 /* Omit the beginning MRL-selector characters */
1282                 return strdup(name + n);
1283             }
1284     }
1285
1286     device = strdup(name);
1287
1288     if (device) /* Remove what we have after @ */
1289         device[strcspn(device, "@")] = '\0';
1290
1291     return device;
1292 }
1293
1294 static void Eject(intf_thread_t *p_intf)
1295 {
1296     char *psz_device, *psz_name;
1297     playlist_t * p_playlist = pl_Get(p_intf);
1298
1299     /* If there's a stream playing, we aren't allowed to eject ! */
1300     if (p_intf->p_sys->p_input)
1301         return;
1302
1303     PL_LOCK;
1304
1305     if (!playlist_CurrentPlayingItem(p_playlist))
1306     {
1307         PL_UNLOCK;
1308         return;
1309     }
1310
1311     psz_name = playlist_CurrentPlayingItem(p_playlist)->p_input->psz_name;
1312     psz_device = psz_name ? GetDiscDevice(p_intf, psz_name) : NULL;
1313
1314     PL_UNLOCK;
1315
1316     if (psz_device)
1317     {
1318         intf_Eject(p_intf, psz_device);
1319         free(psz_device);
1320     }
1321 }
1322
1323 static void PlayPause(intf_thread_t *p_intf)
1324 {
1325     input_thread_t *p_input = p_intf->p_sys->p_input;
1326
1327     if (p_input)
1328     {
1329         int64_t state = var_GetInteger( p_input, "state" );
1330         state = (state != PLAYING_S) ? PLAYING_S : PAUSE_S;
1331         var_SetInteger( p_input, "state", state );
1332     }
1333     else
1334         playlist_Play(pl_Get(p_intf));
1335 }
1336
1337 static inline void BoxSwitch(intf_sys_t *p_sys, int box)
1338 {
1339     p_sys->i_box_type = (p_sys->i_box_type == box) ? BOX_NONE : box;
1340     p_sys->i_box_start = 0;
1341     p_sys->i_box_idx = 0;
1342 }
1343
1344 static bool HandlePlaylistKey(intf_thread_t *p_intf, int key)
1345 {
1346     intf_sys_t *p_sys = p_intf->p_sys;
1347     playlist_t *p_playlist = pl_Get(p_intf);
1348     struct pl_item_t *p_pl_item;
1349
1350     switch(key)
1351     {
1352     /* Playlist Settings */
1353     case 'r': var_ToggleBool(p_playlist, "random"); return true;
1354     case 'l': var_ToggleBool(p_playlist, "loop");   return true;
1355     case 'R': var_ToggleBool(p_playlist, "repeat"); return true;
1356
1357     /* Playlist sort */
1358     case 'o':
1359     case 'O':
1360         playlist_RecursiveNodeSort(p_playlist, p_playlist->p_root_onelevel,
1361                                     SORT_TITLE_NODES_FIRST,
1362                                     (key == 'o')? ORDER_NORMAL : ORDER_REVERSE);
1363         p_sys->b_need_update = true;
1364         return true;
1365
1366     case 'g':
1367         FindIndex(p_sys, p_playlist);
1368         return true;
1369
1370     /* Deletion */
1371     case 'D':
1372     case KEY_BACKSPACE:
1373     case 0x7f:
1374     case KEY_DC:
1375     {
1376         playlist_item_t *p_item;
1377
1378         PL_LOCK;
1379         p_item = p_sys->pp_plist[p_sys->i_box_idx]->p_item;
1380         if (p_item->i_children == -1)
1381             playlist_DeleteFromInput(p_playlist, p_item->p_input, pl_Locked);
1382         else
1383             playlist_NodeDelete(p_playlist, p_item, true , false);
1384         PL_UNLOCK;
1385         p_sys->b_need_update = true;
1386         return true;
1387     }
1388
1389     case KEY_ENTER:
1390     case '\r':
1391     case '\n':
1392         if (!(p_pl_item = p_sys->pp_plist[p_sys->i_box_idx]))
1393             return false;
1394
1395         if (p_pl_item->p_item->i_children)
1396         {
1397             playlist_item_t *p_item, *p_parent = p_pl_item->p_item;
1398             if (p_parent->i_children == -1)
1399             {
1400                 p_item = p_parent;
1401
1402                 while (p_parent->p_parent)
1403                     p_parent = p_parent->p_parent;
1404             }
1405             else
1406             {
1407                 p_sys->p_node = p_parent;
1408                 p_item = NULL;
1409             }
1410
1411             playlist_Control(p_playlist, PLAYLIST_VIEWPLAY, pl_Unlocked,
1412                               p_parent, p_item);
1413         }
1414         else
1415         {   /* We only want to set the current node */
1416             playlist_Stop(p_playlist);
1417             p_sys->p_node = p_pl_item->p_item;
1418         }
1419
1420         p_sys->b_plidx_follow = true;
1421         return true;
1422     }
1423
1424     return false;
1425 }
1426
1427 static bool HandleBrowseKey(intf_thread_t *p_intf, int key)
1428 {
1429     intf_sys_t *p_sys = p_intf->p_sys;
1430     struct dir_entry_t *dir_entry;
1431
1432     switch(key)
1433     {
1434     case '.':
1435         p_sys->b_show_hidden_files = !p_sys->b_show_hidden_files;
1436         ReadDir(p_intf);
1437         return true;
1438
1439     case KEY_ENTER:
1440     case '\r':
1441     case '\n':
1442     case ' ':
1443         dir_entry = p_sys->pp_dir_entries[p_sys->i_box_idx];
1444         char *psz_path;
1445         if (asprintf(&psz_path, "%s" DIR_SEP "%s", p_sys->psz_current_dir,
1446                      dir_entry->psz_path) == -1)
1447             return true;
1448
1449         if (!dir_entry->b_file && key != ' ')
1450         {
1451             free(p_sys->psz_current_dir);
1452             p_sys->psz_current_dir = psz_path;
1453             ReadDir(p_intf);
1454
1455             p_sys->i_box_start = 0;
1456             p_sys->i_box_idx = 0;
1457             return true;
1458         }
1459
1460         char *psz_uri = make_URI(psz_path, dir_entry->b_file ? "file"
1461                                                              : "directory");
1462         free(psz_path);
1463         if (psz_uri == NULL)
1464             return true;
1465
1466         playlist_t *p_playlist = pl_Get(p_intf);
1467         playlist_item_t *p_parent = p_sys->p_node;
1468         if (!p_parent)
1469         {
1470             playlist_item_t *p_item;
1471             PL_LOCK;
1472             p_item = playlist_CurrentPlayingItem(p_playlist);
1473             p_parent = p_item ? p_item->p_parent : NULL;
1474             PL_UNLOCK;
1475             if (!p_parent)
1476                 p_parent = p_playlist->p_local_onelevel;
1477         }
1478
1479         while (p_parent->p_parent && p_parent->p_parent->p_parent)
1480             p_parent = p_parent->p_parent;
1481
1482         input_item_t *p_input = p_playlist->p_local_onelevel->p_input;
1483         playlist_Add(p_playlist, psz_uri, NULL, PLAYLIST_APPEND,
1484                       PLAYLIST_END, p_parent->p_input == p_input, false);
1485
1486         BoxSwitch(p_sys, BOX_PLAYLIST);
1487         free(psz_uri);
1488         return true;
1489     }
1490
1491     return false;
1492 }
1493
1494 static void HandleEditBoxKey(intf_thread_t *p_intf, int key, int box)
1495 {
1496     intf_sys_t *p_sys = p_intf->p_sys;
1497     bool search = box == BOX_SEARCH;
1498     char *str = search ? p_sys->psz_search_chain: p_sys->psz_open_chain;
1499     size_t len = strlen(str);
1500
1501     assert(box == BOX_SEARCH || box == BOX_OPEN);
1502
1503     switch(key)
1504     {
1505     case 0x0c:  /* ^l */
1506     case KEY_CLEAR:     clear(); return;
1507
1508     case KEY_ENTER:
1509     case '\r':
1510     case '\n':
1511         if (search)
1512         {
1513             if (len)
1514                 p_sys->psz_old_search = strdup(p_sys->psz_search_chain);
1515             else if (p_sys->psz_old_search)
1516                 SearchPlaylist(p_sys, p_sys->psz_old_search);
1517         }
1518         else if (len)
1519         {
1520             char *psz_uri = make_URI(p_sys->psz_open_chain, NULL);
1521             if (psz_uri == NULL)
1522             {
1523                 p_sys->i_box_type = BOX_PLAYLIST;
1524                 return;
1525             }
1526
1527             playlist_t *p_playlist = pl_Get(p_intf);
1528             playlist_item_t *p_parent = p_sys->p_node, *p_current;
1529
1530             PL_LOCK;
1531             if (!p_parent)
1532             {
1533                 p_current = playlist_CurrentPlayingItem(p_playlist);
1534                 p_parent = p_current ? p_current->p_parent : NULL;
1535                 if (!p_parent)
1536                     p_parent = p_playlist->p_local_onelevel;
1537             }
1538
1539             while (p_parent->p_parent && p_parent->p_parent->p_parent)
1540                 p_parent = p_parent->p_parent;
1541             PL_UNLOCK;
1542
1543             playlist_Add(p_playlist, psz_uri, NULL,
1544                   PLAYLIST_APPEND|PLAYLIST_GO, PLAYLIST_END,
1545                   p_parent->p_input == p_playlist->p_local_onelevel->p_input,
1546                   false);
1547
1548             free(psz_uri);
1549             p_sys->b_plidx_follow = true;
1550         }
1551         p_sys->i_box_type = BOX_PLAYLIST;
1552         return;
1553
1554     case 0x1b: /* ESC */
1555         /* Alt+key combinations return 2 keys in the terminal keyboard:
1556          * ESC, and the 2nd key.
1557          * If some other key is available immediately (where immediately
1558          * means after getch() 1 second delay), that means that the
1559          * ESC key was not pressed.
1560          *
1561          * man 3X curs_getch says:
1562          *
1563          * Use of the escape key by a programmer for a single
1564          * character function is discouraged, as it will cause a delay
1565          * of up to one second while the keypad code looks for a
1566          * following function-key sequence.
1567          *
1568          */
1569         if (getch() != ERR)
1570             return;
1571
1572         if (search) p_sys->i_box_idx = p_sys->i_before_search;
1573         p_sys->i_box_type = BOX_PLAYLIST;
1574         return;
1575
1576     case KEY_BACKSPACE:
1577     case 0x7f:
1578         RemoveLastUTF8Entity(str, len);
1579         break;
1580
1581     default:
1582         if (len + 1 < (search ? sizeof p_sys->psz_search_chain
1583                               : sizeof p_sys->psz_open_chain))
1584         {
1585             str[len + 0] = (char) key;
1586             str[len + 1] = '\0';
1587         }
1588     }
1589
1590     if (search)
1591     {
1592         free(p_sys->psz_old_search);
1593         p_sys->psz_old_search = NULL;
1594         SearchPlaylist(p_sys, str);
1595     }
1596 }
1597
1598 static void InputNavigate(input_thread_t* p_input, const char *var)
1599 {
1600     if (p_input)
1601         var_TriggerCallback(p_input, var);
1602 }
1603
1604 static void HandleCommonKey(intf_thread_t *p_intf, int key)
1605 {
1606     intf_sys_t *p_sys = p_intf->p_sys;
1607     playlist_t *p_playlist = pl_Get(p_intf);
1608     switch(key)
1609     {
1610     case 0x1b:  /* ESC */
1611         if (getch() != ERR)
1612             return;
1613
1614     case 'q':
1615     case 'Q':
1616     case KEY_EXIT:
1617         libvlc_Quit(p_intf->p_libvlc);
1618         p_sys->b_exit = true;           // terminate the main loop
1619         return;
1620
1621     case 'h':
1622     case 'H': BoxSwitch(p_sys, BOX_HELP);       return;
1623     case 'i': BoxSwitch(p_sys, BOX_INFO);       return;
1624     case 'm': BoxSwitch(p_sys, BOX_META);       return;
1625     case 'L': BoxSwitch(p_sys, BOX_LOG);        return;
1626     case 'P': BoxSwitch(p_sys, BOX_PLAYLIST);   return;
1627     case 'B': BoxSwitch(p_sys, BOX_BROWSE);     return;
1628     case 'x': BoxSwitch(p_sys, BOX_OBJECTS);    return;
1629     case 'S': BoxSwitch(p_sys, BOX_STATS);      return;
1630
1631     case '/': /* Search */
1632         p_sys->psz_search_chain[0] = '\0';
1633         p_sys->b_plidx_follow = false;
1634         if (p_sys->i_box_type == BOX_PLAYLIST)
1635         {
1636             p_sys->i_before_search = p_sys->i_box_idx;
1637             p_sys->i_box_type = BOX_SEARCH;
1638         }
1639         else
1640         {
1641             p_sys->i_before_search = 0;
1642             BoxSwitch(p_sys, BOX_SEARCH);
1643         }
1644         return;
1645
1646     case 'A': /* Open */
1647         p_sys->psz_open_chain[0] = '\0';
1648         if (p_sys->i_box_type == BOX_PLAYLIST)
1649             p_sys->i_box_type = BOX_OPEN;
1650         else
1651             BoxSwitch(p_sys, BOX_OPEN);
1652         return;
1653
1654     /* Navigation */
1655     case KEY_RIGHT: ChangePosition(p_intf, +0.01); return;
1656     case KEY_LEFT:  ChangePosition(p_intf, -0.01); return;
1657
1658     /* Common control */
1659     case 'f':
1660         if (p_sys->p_input)
1661         {
1662             vout_thread_t *p_vout = input_GetVout(p_sys->p_input);
1663             if (p_vout)
1664             {
1665                 bool fs = var_ToggleBool(p_playlist, "fullscreen");
1666                 var_SetBool(p_vout, "fullscreen", fs);
1667                 vlc_object_release(p_vout);
1668             }
1669         }
1670         return;
1671
1672     case ' ': PlayPause(p_intf);            return;
1673     case 's': playlist_Stop(p_playlist);    return;
1674     case 'e': Eject(p_intf);                return;
1675
1676     case '[': InputNavigate(p_sys->p_input, "prev-title");      return;
1677     case ']': InputNavigate(p_sys->p_input, "next-title");      return;
1678     case '<': InputNavigate(p_sys->p_input, "prev-chapter");    return;
1679     case '>': InputNavigate(p_sys->p_input, "next-chapter");    return;
1680
1681     case 'p': playlist_Prev(p_playlist);            break;
1682     case 'n': playlist_Next(p_playlist);            break;
1683     case 'a': aout_VolumeUp(p_playlist, 1, NULL);   break;
1684     case 'z': aout_VolumeDown(p_playlist, 1, NULL); break;
1685
1686     case 0x0c:  /* ^l */
1687     case KEY_CLEAR:
1688         break;
1689
1690     default:
1691         return;
1692     }
1693
1694     clear();
1695     return;
1696 }
1697
1698 static bool HandleListKey(intf_thread_t *p_intf, int key)
1699 {
1700     intf_sys_t *p_sys = p_intf->p_sys;
1701     playlist_t *p_playlist = pl_Get(p_intf);
1702
1703     switch(key)
1704     {
1705 #ifdef __FreeBSD__
1706 /* workaround for FreeBSD + xterm:
1707  * see http://www.nabble.com/curses-vs.-xterm-key-mismatch-t3574377.html */
1708     case KEY_SELECT:
1709 #endif
1710     case KEY_END:  p_sys->i_box_idx = p_sys->i_box_lines_total - 1; break;
1711     case KEY_HOME: p_sys->i_box_idx = 0;                            break;
1712     case KEY_UP:   p_sys->i_box_idx--;                              break;
1713     case KEY_DOWN: p_sys->i_box_idx++;                              break;
1714     case KEY_PPAGE:p_sys->i_box_idx -= p_sys->i_box_height;         break;
1715     case KEY_NPAGE:p_sys->i_box_idx += p_sys->i_box_height;         break;
1716     default:
1717         return false;
1718     }
1719
1720     CheckIdx(p_sys);
1721
1722     if (p_sys->i_box_type == BOX_PLAYLIST)
1723     {
1724         PL_LOCK;
1725         p_sys->b_plidx_follow = IsIndex(p_sys, p_playlist, p_sys->i_box_idx);
1726         PL_UNLOCK;
1727     }
1728
1729     return true;
1730 }
1731
1732 static void HandleKey(intf_thread_t *p_intf)
1733 {
1734     intf_sys_t *p_sys = p_intf->p_sys;
1735     int key = getch();
1736     int box = p_sys->i_box_type;
1737
1738     if (key == -1)
1739         return;
1740
1741     if (box == BOX_SEARCH || box == BOX_OPEN)
1742     {
1743         HandleEditBoxKey(p_intf, key, p_sys->i_box_type);
1744         return;
1745     }
1746
1747     if (box == BOX_NONE)
1748         switch(key)
1749         {
1750 #ifdef __FreeBSD__
1751         case KEY_SELECT:
1752 #endif
1753         case KEY_END:   ChangePosition(p_intf, +.99);   return;
1754         case KEY_HOME:  ChangePosition(p_intf, -1.0);   return;
1755         case KEY_UP:    ChangePosition(p_intf, +0.05);  return;
1756         case KEY_DOWN:  ChangePosition(p_intf, -0.05);  return;
1757         default:        HandleCommonKey(p_intf, key);   return;
1758         }
1759
1760     if (box == BOX_BROWSE   && HandleBrowseKey(p_intf, key))
1761         return;
1762
1763     if (box == BOX_PLAYLIST && HandlePlaylistKey(p_intf, key))
1764         return;
1765
1766     if (HandleListKey(p_intf, key))
1767         return;
1768
1769     HandleCommonKey(p_intf, key);
1770 }
1771
1772 /*
1773  *
1774  */
1775
1776 static void MsgCallback(msg_cb_data_t *data, const msg_item_t *msg)
1777 {
1778     intf_sys_t *p_sys = data->p_sys;
1779     int canc = vlc_savecancel();
1780
1781     vlc_mutex_lock(&p_sys->msg_lock);
1782
1783     if (p_sys->msgs[p_sys->i_msgs])
1784         msg_Free(p_sys->msgs[p_sys->i_msgs]);
1785     p_sys->msgs[p_sys->i_msgs++] = msg_Copy(msg);
1786
1787     if (p_sys->i_msgs == (sizeof p_sys->msgs / sizeof *p_sys->msgs))
1788         p_sys->i_msgs = 0;
1789
1790     vlc_mutex_unlock(&p_sys->msg_lock);
1791
1792     vlc_restorecancel(canc);
1793 }
1794
1795 static inline void UpdateInput(intf_sys_t *p_sys, playlist_t *p_playlist)
1796 {
1797     if (!p_sys->p_input)
1798     {
1799         p_sys->p_input = playlist_CurrentInput(p_playlist);
1800     }
1801     else if (p_sys->p_input->b_dead)
1802     {
1803         vlc_object_release(p_sys->p_input);
1804         p_sys->p_input = NULL;
1805     }
1806 }
1807
1808 /*****************************************************************************
1809  * Run: ncurses thread
1810  *****************************************************************************/
1811 static void Run(intf_thread_t *p_intf)
1812 {
1813     intf_sys_t    *p_sys = p_intf->p_sys;
1814     playlist_t    *p_playlist = pl_Get(p_intf);
1815
1816     int canc = vlc_savecancel();
1817
1818     var_AddCallback(p_playlist, "intf-change", PlaylistChanged, p_intf);
1819     var_AddCallback(p_playlist, "playlist-item-append", PlaylistChanged, p_intf);
1820
1821     while (vlc_object_alive(p_intf) && !p_sys->b_exit)
1822     {
1823         UpdateInput(p_sys, p_playlist);
1824         Redraw(p_intf);
1825         HandleKey(p_intf);
1826     }
1827
1828     var_DelCallback(p_playlist, "intf-change", PlaylistChanged, p_intf);
1829     var_DelCallback(p_playlist, "playlist-item-append", PlaylistChanged, p_intf);
1830     vlc_restorecancel(canc);
1831 }
1832
1833 /*****************************************************************************
1834  * Open: initialize and create window
1835  *****************************************************************************/
1836 static int Open(vlc_object_t *p_this)
1837 {
1838     intf_thread_t *p_intf = (intf_thread_t *)p_this;
1839     intf_sys_t    *p_sys  = p_intf->p_sys = calloc(1, sizeof(intf_sys_t));
1840     struct msg_cb_data_t *msg_cb_data;
1841
1842     if (!p_sys)
1843         return VLC_ENOMEM;
1844
1845     msg_cb_data = malloc(sizeof *msg_cb_data);
1846     if (!msg_cb_data)
1847     {
1848         free(p_sys);
1849         return VLC_ENOMEM;
1850     }
1851
1852     msg_cb_data->p_sys = p_sys;
1853     vlc_mutex_init(&p_sys->msg_lock);
1854     p_sys->i_msgs = 0;
1855     memset(p_sys->msgs, 0, sizeof p_sys->msgs);
1856     p_sys->p_sub = msg_Subscribe(p_intf->p_libvlc, MsgCallback, msg_cb_data);
1857     msg_SubscriptionSetVerbosity(p_sys->p_sub,
1858             var_GetInteger(p_intf->p_libvlc, "verbose"));
1859
1860     p_sys->i_box_type = BOX_PLAYLIST;
1861     p_sys->b_plidx_follow = true;
1862     p_sys->b_color = var_CreateGetBool(p_intf, "color");
1863
1864     p_sys->psz_current_dir = var_CreateGetString(p_intf, "browse-dir");
1865     if (!p_sys->psz_current_dir || !*p_sys->psz_current_dir)
1866     {
1867         free(p_sys->psz_current_dir);
1868         p_sys->psz_current_dir = config_GetUserDir(VLC_HOME_DIR);
1869     }
1870
1871     initscr();   /* Initialize the curses library */
1872
1873     if (p_sys->b_color)
1874         start_color_and_pairs(p_intf);
1875
1876     keypad(stdscr, TRUE);   /* Don't do NL -> CR/NL */
1877     nonl();                 /* Take input chars one at a time */
1878     cbreak();               /* Don't echo */
1879     noecho();               /* Invisible cursor */
1880     curs_set(0);            /* Non blocking getch() */
1881     timeout(1000);
1882     clear();
1883
1884     /* Stop printing errors to the console */
1885     if(!freopen("/dev/null", "wb", stderr))
1886         msg_Err(p_intf, "Couldn't close stderr (%m)");
1887
1888     ReadDir(p_intf);
1889     PlaylistRebuild(p_intf),
1890
1891     p_intf->pf_run = Run;
1892     return VLC_SUCCESS;
1893 }
1894
1895 /*****************************************************************************
1896  * Close: destroy interface window
1897  *****************************************************************************/
1898 static void Close(vlc_object_t *p_this)
1899 {
1900     intf_sys_t *p_sys = ((intf_thread_t*)p_this)->p_sys;
1901
1902     PlaylistDestroy(p_sys);
1903     DirsDestroy(p_sys);
1904
1905     free(p_sys->psz_current_dir);
1906     free(p_sys->psz_old_search);
1907
1908     if (p_sys->p_input)
1909         vlc_object_release(p_sys->p_input);
1910
1911     endwin();   /* Close the ncurses interface */
1912
1913     msg_Unsubscribe(p_sys->p_sub);
1914     vlc_mutex_destroy(&p_sys->msg_lock);
1915     for(unsigned i = 0; i < sizeof p_sys->msgs / sizeof *p_sys->msgs; i++)
1916         if (p_sys->msgs[i])
1917             msg_Free(p_sys->msgs[i]);
1918
1919     free(p_sys);
1920 }