]> git.sesse.net Git - vlc/blob - modules/lua/extension.c
79843960a9f762fe06d515230276f9e5a01547e5
[vlc] / modules / lua / extension.c
1 /*****************************************************************************
2  * extension.c: Lua Extensions (meta data, web information, ...)
3  *****************************************************************************
4  * Copyright (C) 2009-2010 VideoLAN and authors
5  * $Id$
6  *
7  * Authors: Jean-Philippe AndrĂ© < jpeg # videolan.org >
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #ifndef _GNU_SOURCE
25 # define _GNU_SOURCE
26 #endif
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include "vlc.h"
33 #include "libs.h"
34 #include "extension.h"
35 #include "assert.h"
36
37 #include <vlc_common.h>
38 #include <vlc_input.h>
39 #include <vlc_events.h>
40 #include <vlc_dialog.h>
41
42 /* Functions to register */
43 static const luaL_Reg p_reg[] =
44 {
45     { NULL, NULL }
46 };
47
48 /*
49  * Extensions capabilities
50  * Note: #define and ppsz_capabilities must be in sync
51  */
52 static const char const caps[][20] = {
53 #define EXT_HAS_MENU          (1 << 0)   ///< Hook: menu
54     "menu",
55 #define EXT_TRIGGER_ONLY      (1 << 1)   ///< Hook: trigger. Not activable
56     "trigger",
57 #define EXT_INPUT_LISTENER    (1 << 2)   ///< Hook: input_changed
58     "input-listener",
59 #define EXT_META_LISTENER     (1 << 3)   ///< Hook: meta_changed
60     "meta-listener",
61 #define EXT_PLAYING_LISTENER  (1 << 4)   ///< Hook: status_changed
62     "playing-listener",
63 };
64
65 #define WATCH_TIMER_PERIOD    (10 * CLOCK_FREQ) ///< 10s period for the timer
66
67 static int ScanExtensions( extensions_manager_t *p_this );
68 static int ScanLuaCallback( vlc_object_t *p_this, const char *psz_script,
69                             void *dummy );
70 static int Control( extensions_manager_t *, int, va_list );
71 static int GetMenuEntries( extensions_manager_t *p_mgr, extension_t *p_ext,
72                     char ***pppsz_titles, uint16_t **ppi_ids );
73 static lua_State* GetLuaState( extensions_manager_t *p_mgr,
74                                extension_t *p_ext );
75 static int TriggerMenu( extension_t *p_ext, int id );
76 static int TriggerExtension( extensions_manager_t *p_mgr,
77                              extension_t *p_ext );
78 static void WatchTimerCallback( void* );
79
80 static int vlclua_extension_deactivate( lua_State *L );
81 static int vlclua_extension_keep_alive( lua_State *L );
82
83 /* Interactions */
84 static int vlclua_extension_dialog_callback( vlc_object_t *p_this,
85                                              char const *psz_var,
86                                              vlc_value_t oldval,
87                                              vlc_value_t newval,
88                                              void *p_data );
89
90 /* Input item callback: vlc_InputItemMetaChanged */
91 static void inputItemMetaChanged( const vlc_event_t *p_event,
92                                   void *data );
93
94
95 /**
96  * Module entry-point
97  **/
98 int Open_Extension( vlc_object_t *p_this )
99 {
100     msg_Dbg( p_this, "Opening Lua Extension module" );
101
102     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
103
104     p_mgr->pf_control = Control;
105
106     extensions_manager_sys_t *p_sys = ( extensions_manager_sys_t* )
107                     calloc( 1, sizeof( extensions_manager_sys_t ) );
108     if( !p_sys ) return VLC_ENOMEM;
109
110     p_mgr->p_sys = p_sys;
111     ARRAY_INIT( p_sys->activated_extensions );
112     ARRAY_INIT( p_mgr->extensions );
113     vlc_mutex_init( &p_mgr->lock );
114     vlc_mutex_init( &p_mgr->p_sys->lock );
115
116     /* Scan available Lua Extensions */
117     if( ScanExtensions( p_mgr ) != VLC_SUCCESS )
118     {
119         msg_Err( p_mgr, "Can't load extensions modules" );
120         return VLC_EGENERIC;
121     }
122
123     // Create the dialog-event variable
124     var_Create( p_this, "dialog-event", VLC_VAR_ADDRESS );
125     var_AddCallback( p_this, "dialog-event",
126                      vlclua_extension_dialog_callback, NULL );
127
128     return VLC_SUCCESS;
129 }
130
131 /**
132  * Module unload function
133  **/
134 void Close_Extension( vlc_object_t *p_this )
135 {
136     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
137     msg_Dbg( p_mgr, "Deactivating all loaded extensions" );
138
139     vlc_mutex_lock( &p_mgr->lock );
140     p_mgr->p_sys->b_killed = true;
141     vlc_mutex_unlock( &p_mgr->lock );
142
143     var_Destroy( p_mgr, "dialog-event" );
144
145     extension_t *p_ext = NULL;
146     FOREACH_ARRAY( p_ext, p_mgr->p_sys->activated_extensions )
147     {
148         if( !p_ext ) break;
149         msg_Dbg( p_mgr, "Deactivating '%s'", p_ext->psz_title );
150         Deactivate( p_mgr, p_ext );
151         vlc_join( p_ext->p_sys->thread, NULL );
152     }
153     FOREACH_END()
154
155     msg_Dbg( p_mgr, "All extensions are now deactivated" );
156     ARRAY_RESET( p_mgr->p_sys->activated_extensions );
157
158     vlc_mutex_destroy( &p_mgr->lock );
159     vlc_mutex_destroy( &p_mgr->p_sys->lock );
160     free( p_mgr->p_sys );
161     p_mgr->p_sys = NULL;
162
163     /* Free extensions' memory */
164     FOREACH_ARRAY( p_ext, p_mgr->extensions )
165     {
166         if( !p_ext )
167             break;
168         if( p_ext->p_sys->L )
169             lua_close( p_ext->p_sys->L );
170         free( p_ext->psz_name );
171         free( p_ext->psz_title );
172         free( p_ext->psz_author );
173         free( p_ext->psz_description );
174         free( p_ext->psz_shortdescription );
175         free( p_ext->psz_url );
176         free( p_ext->psz_version );
177         free( p_ext->p_icondata );
178
179         vlc_mutex_destroy( &p_ext->p_sys->running_lock );
180         vlc_mutex_destroy( &p_ext->p_sys->command_lock );
181         vlc_cond_destroy( &p_ext->p_sys->wait );
182         vlc_timer_destroy( p_ext->p_sys->timer );
183
184         free( p_ext->p_sys );
185         free( p_ext );
186     }
187     FOREACH_END()
188
189     ARRAY_RESET( p_mgr->extensions );
190
191     var_DelCallback( p_this, "dialog-event",
192                      vlclua_extension_dialog_callback, NULL );
193 }
194
195 /**
196  * Batch scan all Lua files in folder "extensions"
197  * @param p_mgr This extensions_manager_t object
198  **/
199 static int ScanExtensions( extensions_manager_t *p_mgr )
200 {
201     int i_ret =
202         vlclua_scripts_batch_execute( VLC_OBJECT( p_mgr ),
203                                       "extensions",
204                                       &ScanLuaCallback,
205                                       NULL );
206
207     if( !i_ret )
208         return VLC_EGENERIC;
209
210     return VLC_SUCCESS;
211 }
212
213 /**
214  * Dummy Lua function: does nothing
215  * @note This function can be used to replace "require" while scanning for
216  * extensions
217  * Even the built-in libraries are not loaded when calling descriptor()
218  **/
219 static int vlclua_dummy_require( lua_State *L )
220 {
221     (void) L;
222     return 0;
223 }
224
225 /**
226  * Replacement for "require", adding support for packaged extensions
227  * @note Loads modules in the modules/ folder of a package
228  * @note Try first with .luac and then with .lua
229  **/
230 static int vlclua_extension_require( lua_State *L )
231 {
232     const char *psz_module = luaL_checkstring( L, 1 );
233     vlc_object_t *p_this = vlclua_get_this( L );
234     extension_t *p_ext = vlclua_extension_get( L );
235     msg_Dbg( p_this, "loading module '%s' from extension package",
236              psz_module );
237     char *psz_fullpath, *psz_package, *sep;
238     psz_package = strdup( p_ext->psz_name );
239     sep = strrchr( psz_package, '/' );
240     if( !sep )
241     {
242         free( psz_package );
243         return luaL_error( L, "could not find package name" );
244     }
245     *sep = '\0';
246     if( -1 == asprintf( &psz_fullpath,
247                         "%s/modules/%s.luac", psz_package, psz_module ) )
248     {
249         free( psz_package );
250         return 1;
251     }
252     int i_ret = vlclua_dofile( p_this, L, psz_fullpath );
253     if( i_ret != 0 )
254     {
255         // Remove trailing 'c' --> try with .lua script
256         psz_fullpath[ strlen( psz_fullpath ) - 1 ] = '\0';
257         i_ret = vlclua_dofile( p_this, L, psz_fullpath );
258     }
259     free( psz_fullpath );
260     free( psz_package );
261     if( i_ret != 0 )
262     {
263         return luaL_error( L, "unable to load module '%s' from package",
264                            psz_module );
265     }
266     return 0;
267 }
268
269 /**
270  * Batch scan all Lua files in folder "extensions": callback
271  * @param p_this This extensions_manager_t object
272  * @param psz_filename Name of the script to run
273  * @param L Lua State, common to all scripts here
274  * @param dummy: unused
275  **/
276 int ScanLuaCallback( vlc_object_t *p_this, const char *psz_filename,
277                      void *dummy )
278 {
279     VLC_UNUSED(dummy);
280     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
281     bool b_ok = false;
282
283     msg_Dbg( p_mgr, "Scanning Lua script %s", psz_filename );
284
285     /* Experimental: read .vle packages (Zip archives) */
286     char *psz_script = NULL;
287     int i_flen = strlen( psz_filename );
288     if( !strncasecmp( psz_filename + i_flen - 4, ".vle", 4 ) )
289     {
290         msg_Dbg( p_this, "reading Lua script in a zip archive" );
291         psz_script = calloc( 1, i_flen + 6 + 12 + 1 );
292         if( !psz_script )
293             return 0;
294         strcpy( psz_script, "zip://" );
295         strncat( psz_script, psz_filename, i_flen + 19 );
296         strncat( psz_script, "!/script.lua", i_flen + 19 );
297     }
298     else
299     {
300         psz_script = strdup( psz_filename );
301         if( !psz_script )
302             return 0;
303     }
304
305     /* Create new script descriptor */
306     extension_t *p_ext = ( extension_t* ) calloc( 1, sizeof( extension_t ) );
307     if( !p_ext )
308     {
309         free( psz_script );
310         return 0;
311     }
312
313     p_ext->psz_name = psz_script;
314     p_ext->p_sys = (extension_sys_t*) calloc( 1, sizeof( extension_sys_t ) );
315     if( !p_ext->p_sys || !p_ext->psz_name )
316     {
317         free( p_ext->psz_name );
318         free( p_ext->p_sys );
319         free( p_ext );
320         return 0;
321     }
322     p_ext->p_sys->p_mgr = p_mgr;
323
324     /* Watch timer */
325     if( vlc_timer_create( &p_ext->p_sys->timer, WatchTimerCallback, p_ext ) )
326     {
327         free( p_ext->psz_name );
328         free( p_ext->p_sys );
329         free( p_ext );
330         return 0;
331     }
332
333     /* Mutexes and conditions */
334     vlc_mutex_init( &p_ext->p_sys->command_lock );
335     vlc_mutex_init( &p_ext->p_sys->running_lock );
336     vlc_cond_init( &p_ext->p_sys->wait );
337
338     /* Prepare Lua state */
339     lua_State *L = luaL_newstate();
340     lua_register( L, "require", &vlclua_dummy_require );
341
342     /* Let's run it */
343     if( vlclua_dofile( p_this, L, psz_script ) ) // luaL_dofile
344     {
345         msg_Warn( p_mgr, "Error loading script %s: %s", psz_script,
346                   lua_tostring( L, lua_gettop( L ) ) );
347         lua_pop( L, 1 );
348         goto exit;
349     }
350
351     /* Scan script for capabilities */
352     lua_getglobal( L, "descriptor" );
353
354     if( !lua_isfunction( L, -1 ) )
355     {
356         msg_Warn( p_mgr, "Error while running script %s, "
357                   "function descriptor() not found", psz_script );
358         goto exit;
359     }
360
361     if( lua_pcall( L, 0, 1, 0 ) )
362     {
363         msg_Warn( p_mgr, "Error while running script %s, "
364                   "function descriptor(): %s", psz_script,
365                   lua_tostring( L, lua_gettop( L ) ) );
366         goto exit;
367     }
368
369     if( lua_gettop( L ) )
370     {
371         if( lua_istable( L, -1 ) )
372         {
373             /* Get caps */
374             lua_getfield( L, -1, "capabilities" );
375             if( lua_istable( L, -1 ) )
376             {
377                 lua_pushnil( L );
378                 while( lua_next( L, -2 ) != 0 )
379                 {
380                     /* Key is at index -2 and value at index -1. Discard key */
381                     const char *psz_cap = luaL_checkstring( L, -1 );
382                     bool b_ok = false;
383                     /* Find this capability's flag */
384                     for( size_t i = 0; i < sizeof(caps)/sizeof(caps[0]); i++ )
385                     {
386                         if( !strcmp( caps[i], psz_cap ) )
387                         {
388                             /* Flag it! */
389                             p_ext->p_sys->i_capabilities |= 1 << i;
390                             b_ok = true;
391                             break;
392                         }
393                     }
394                     if( !b_ok )
395                     {
396                         msg_Warn( p_mgr, "Extension capability '%s' unknown in"
397                                   " script %s", psz_cap, psz_script );
398                     }
399                     /* Removes 'value'; keeps 'key' for next iteration */
400                     lua_pop( L, 1 );
401                 }
402             }
403             else
404             {
405                 msg_Warn( p_mgr, "In script %s, function descriptor() "
406                               "did not return a table of capabilities.",
407                               psz_script );
408             }
409             lua_pop( L, 1 );
410
411             /* Get title */
412             lua_getfield( L, -1, "title" );
413             if( lua_isstring( L, -1 ) )
414             {
415                 p_ext->psz_title = strdup( luaL_checkstring( L, -1 ) );
416             }
417             else
418             {
419                 msg_Dbg( p_mgr, "In script %s, function descriptor() "
420                                 "did not return a string as title.",
421                                 psz_script );
422                 p_ext->psz_title = strdup( psz_script );
423             }
424             lua_pop( L, 1 );
425
426             /* Get author */
427             lua_getfield( L, -1, "author" );
428             p_ext->psz_author = luaL_strdupornull( L, -1 );
429             lua_pop( L, 1 );
430
431             /* Get description */
432             lua_getfield( L, -1, "description" );
433             p_ext->psz_description = luaL_strdupornull( L, -1 );
434             lua_pop( L, 1 );
435
436             /* Get short description */
437             lua_getfield( L, -1, "shortdesc" );
438             p_ext->psz_shortdescription = luaL_strdupornull( L, -1 );
439             lua_pop( L, 1 );
440
441             /* Get URL */
442             lua_getfield( L, -1, "url" );
443             p_ext->psz_url = luaL_strdupornull( L, -1 );
444             lua_pop( L, 1 );
445
446             /* Get version */
447             lua_getfield( L, -1, "version" );
448             p_ext->psz_version = luaL_strdupornull( L, -1 );
449             lua_pop( L, 1 );
450
451             /* Get icon data */
452             lua_getfield( L, -1, "icon" );
453             if( !lua_isnil( L, -1 ) && lua_isstring( L, -1 ) )
454             {
455                 int len = lua_strlen( L, -1 );
456                 p_ext->p_icondata = malloc( len );
457                 if( p_ext->p_icondata )
458                 {
459                     p_ext->i_icondata_size = len;
460                     memcpy( p_ext->p_icondata, lua_tostring( L, -1 ), len );
461                 }
462             }
463             lua_pop( L, 1 );
464         }
465         else
466         {
467             msg_Warn( p_mgr, "In script %s, function descriptor() "
468                       "did not return a table!", psz_script );
469             goto exit;
470         }
471     }
472     else
473     {
474         msg_Err( p_mgr, "Script %s went completely foobar", psz_script );
475         goto exit;
476     }
477
478     msg_Dbg( p_mgr, "Script %s has the following capability flags: 0x%x",
479              psz_script, p_ext->p_sys->i_capabilities );
480
481     b_ok = true;
482 exit:
483     lua_close( L );
484     if( !b_ok )
485     {
486         free( p_ext->psz_name );
487         free( p_ext->psz_title );
488         free( p_ext->psz_url );
489         free( p_ext->psz_author );
490         free( p_ext->psz_description );
491         free( p_ext->psz_shortdescription );
492         free( p_ext->psz_version );
493         vlc_mutex_destroy( &p_ext->p_sys->command_lock );
494         vlc_mutex_destroy( &p_ext->p_sys->running_lock );
495         vlc_cond_destroy( &p_ext->p_sys->wait );
496         free( p_ext->p_sys );
497         free( p_ext );
498     }
499     else
500     {
501         /* Add the extension to the list of known extensions */
502         ARRAY_APPEND( p_mgr->extensions, p_ext );
503     }
504
505     /* Continue batch execution */
506     return VLC_EGENERIC;
507 }
508
509 static int Control( extensions_manager_t *p_mgr, int i_control, va_list args )
510 {
511     extension_t *p_ext = NULL;
512     bool *pb = NULL;
513     uint16_t **ppus = NULL;
514     char ***pppsz = NULL;
515     int i = 0;
516
517     switch( i_control )
518     {
519         case EXTENSION_ACTIVATE:
520             p_ext = ( extension_t* ) va_arg( args, extension_t* );
521             return Activate( p_mgr, p_ext );
522
523         case EXTENSION_DEACTIVATE:
524             p_ext = ( extension_t* ) va_arg( args, extension_t* );
525             return Deactivate( p_mgr, p_ext );
526
527         case EXTENSION_IS_ACTIVATED:
528             p_ext = ( extension_t* ) va_arg( args, extension_t* );
529             pb = ( bool* ) va_arg( args, bool* );
530             *pb = IsActivated( p_mgr, p_ext );
531             break;
532
533         case EXTENSION_HAS_MENU:
534             p_ext = ( extension_t* ) va_arg( args, extension_t* );
535             pb = ( bool* ) va_arg( args, bool* );
536             *pb = ( p_ext->p_sys->i_capabilities & EXT_HAS_MENU ) ? 1 : 0;
537             break;
538
539         case EXTENSION_GET_MENU:
540             p_ext = ( extension_t* ) va_arg( args, extension_t* );
541             pppsz = ( char*** ) va_arg( args, char*** );
542             ppus = ( uint16_t** ) va_arg( args, uint16_t** );
543             return GetMenuEntries( p_mgr, p_ext, pppsz, ppus );
544
545         case EXTENSION_TRIGGER_ONLY:
546             p_ext = ( extension_t* ) va_arg( args, extension_t* );
547             pb = ( bool* ) va_arg( args, bool* );
548             *pb = ( p_ext->p_sys->i_capabilities & EXT_TRIGGER_ONLY ) ? 1 : 0;
549             break;
550
551         case EXTENSION_TRIGGER:
552             p_ext = ( extension_t* ) va_arg( args, extension_t* );
553             return TriggerExtension( p_mgr, p_ext );
554
555         case EXTENSION_TRIGGER_MENU:
556             p_ext = ( extension_t* ) va_arg( args, extension_t* );
557             // GCC: 'uint16_t' is promoted to 'int' when passed through '...'
558             i = ( int ) va_arg( args, int );
559             return TriggerMenu( p_ext, i );
560
561         case EXTENSION_SET_INPUT:
562         {
563             p_ext = ( extension_t* ) va_arg( args, extension_t* );
564             input_thread_t *p_input = va_arg( args, struct input_thread_t * );
565
566             if( !LockExtension( p_ext ) )
567                 return VLC_EGENERIC;
568
569             // Change input
570             input_thread_t *old = p_ext->p_sys->p_input;
571             input_item_t *p_item;
572             if( old )
573             {
574                 // Untrack meta fetched events
575                 if( p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
576                 {
577                     p_item = input_GetItem( old );
578                     vlc_event_detach( &p_item->event_manager,
579                                       vlc_InputItemMetaChanged,
580                                       inputItemMetaChanged,
581                                       p_ext );
582                     vlc_gc_decref( p_item );
583                 }
584                 vlc_object_release( old );
585             }
586
587             p_ext->p_sys->p_input = p_input ? vlc_object_hold( p_input )
588                                             : p_input;
589
590             // Tell the script the input changed
591             if( p_ext->p_sys->i_capabilities & EXT_INPUT_LISTENER )
592             {
593                 PushCommandUnique( p_ext, CMD_SET_INPUT );
594             }
595
596             // Track meta fetched events
597             if( p_ext->p_sys->p_input &&
598                 p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
599             {
600                 p_item = input_GetItem( p_ext->p_sys->p_input );
601                 vlc_gc_incref( p_item );
602                 vlc_event_attach( &p_item->event_manager,
603                                   vlc_InputItemMetaChanged,
604                                   inputItemMetaChanged,
605                                   p_ext );
606             }
607
608             UnlockExtension( p_ext );
609             break;
610         }
611         case EXTENSION_PLAYING_CHANGED:
612         {
613             extension_t *p_ext;
614             p_ext = ( extension_t* ) va_arg( args, extension_t* );
615             assert( p_ext->psz_name != NULL );
616             i = ( int ) va_arg( args, int );
617             if( p_ext->p_sys->i_capabilities & EXT_PLAYING_LISTENER )
618             {
619                 PushCommand( p_ext, CMD_PLAYING_CHANGED, i );
620             }
621             break;
622         }
623         case EXTENSION_META_CHANGED:
624         {
625             extension_t *p_ext;
626             p_ext = ( extension_t* ) va_arg( args, extension_t* );
627             PushCommand( p_ext, CMD_UPDATE_META );
628             break;
629         }
630         default:
631             msg_Warn( p_mgr, "Control '%d' not yet implemented in Extension",
632                       i_control );
633             return VLC_EGENERIC;
634     }
635
636     return VLC_SUCCESS;
637 }
638
639 int lua_ExtensionActivate( extensions_manager_t *p_mgr, extension_t *p_ext )
640 {
641     assert( p_mgr != NULL && p_ext != NULL );
642     return lua_ExecuteFunction( p_mgr, p_ext, "activate", LUA_END );
643 }
644
645 int lua_ExtensionDeactivate( extensions_manager_t *p_mgr, extension_t *p_ext )
646 {
647     assert( p_mgr != NULL && p_ext != NULL );
648
649     if( !p_ext->p_sys->L )
650         return VLC_SUCCESS;
651
652     // Unset and release input objects
653     if( p_ext->p_sys->p_input )
654     {
655         if( p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
656         {
657             // Release item
658             input_item_t *p_item = input_GetItem( p_ext->p_sys->p_input );
659             vlc_gc_decref( p_item );
660         }
661         vlc_object_release( p_ext->p_sys->p_input );
662         p_ext->p_sys->p_input = NULL;
663     }
664
665     int i_ret = lua_ExecuteFunction( p_mgr, p_ext, "deactivate", LUA_END );
666
667     /* Clear Lua State */
668     lua_close( p_ext->p_sys->L );
669     p_ext->p_sys->L = NULL;
670
671     return i_ret;
672 }
673
674 int lua_ExtensionWidgetClick( extensions_manager_t *p_mgr,
675                               extension_t *p_ext,
676                               extension_widget_t *p_widget )
677 {
678     if( !p_ext->p_sys->L )
679         return VLC_SUCCESS;
680
681     lua_State *L = GetLuaState( p_mgr, p_ext );
682     lua_pushlightuserdata( L, p_widget );
683     lua_gettable( L, LUA_REGISTRYINDEX );
684     return lua_ExecuteFunction( p_mgr, p_ext, NULL, LUA_END );
685 }
686
687
688 /**
689  * Get the list of menu entries from an extension script
690  * @param p_mgr
691  * @param p_ext
692  * @param pppsz_titles Pointer to NULL. All strings must be freed by the caller
693  * @param ppi_ids Pointer to NULL. Must be freed by the caller.
694  * @note This function is allowed to run in the UI thread. This means
695  *       that it MUST respond very fast.
696  * @todo Remove the menu() hook and provide a new function vlc.set_menu()
697  **/
698 static int GetMenuEntries( extensions_manager_t *p_mgr, extension_t *p_ext,
699                     char ***pppsz_titles, uint16_t **ppi_ids )
700 {
701     assert( *pppsz_titles == NULL );
702     assert( *ppi_ids == NULL );
703
704     if( !IsActivated( p_mgr, p_ext ) )
705     {
706         msg_Dbg( p_mgr, "Can't get menu before activating the extension!" );
707         return VLC_EGENERIC;
708     }
709
710     if( !LockExtension( p_ext ) )
711     {
712         /* Dying extension, fail. */
713         return VLC_EGENERIC;
714     }
715
716     int i_ret = VLC_EGENERIC;
717     lua_State *L = GetLuaState( p_mgr, p_ext );
718
719     if( ( p_ext->p_sys->i_capabilities & EXT_HAS_MENU ) == 0 )
720     {
721         msg_Dbg( p_mgr, "can't get a menu from an extension without menu!" );
722         goto exit;
723     }
724
725     lua_getglobal( L, "menu" );
726
727     if( !lua_isfunction( L, -1 ) )
728     {
729         msg_Warn( p_mgr, "Error while running script %s, "
730                   "function menu() not found", p_ext->psz_name );
731         goto exit;
732     }
733
734     if( lua_pcall( L, 0, 1, 0 ) )
735     {
736         msg_Warn( p_mgr, "Error while running script %s, "
737                   "function menu(): %s", p_ext->psz_name,
738                   lua_tostring( L, lua_gettop( L ) ) );
739         goto exit;
740     }
741
742     if( lua_gettop( L ) )
743     {
744         if( lua_istable( L, -1 ) )
745         {
746             /* Get table size */
747             size_t i_size = lua_objlen( L, -1 );
748             *pppsz_titles = ( char** ) calloc( i_size+1, sizeof( char* ) );
749             *ppi_ids = ( uint16_t* ) calloc( i_size+1, sizeof( uint16_t ) );
750
751             /* Walk table */
752             size_t i_idx = 0;
753             lua_pushnil( L );
754             while( lua_next( L, -2 ) != 0 )
755             {
756                 assert( i_idx < i_size );
757                 if( (!lua_isstring( L, -1 )) || (!lua_isnumber( L, -2 )) )
758                 {
759                     msg_Warn( p_mgr, "In script %s, an entry in "
760                               "the menu table is invalid!", p_ext->psz_name );
761                     goto exit;
762                 }
763                 (*pppsz_titles)[ i_idx ] = strdup( luaL_checkstring( L, -1 ) );
764                 (*ppi_ids)[ i_idx ] = (uint16_t) ( luaL_checkinteger( L, -2 ) & 0xFFFF );
765                 i_idx++;
766                 lua_pop( L, 1 );
767             }
768         }
769         else
770         {
771             msg_Warn( p_mgr, "Function menu() in script %s "
772                       "did not return a table", p_ext->psz_name );
773             goto exit;
774         }
775     }
776     else
777     {
778         msg_Warn( p_mgr, "Script %s went completely foobar", p_ext->psz_name );
779         goto exit;
780     }
781
782     i_ret = VLC_SUCCESS;
783
784 exit:
785     UnlockExtension( p_ext );
786     if( i_ret != VLC_SUCCESS )
787     {
788         msg_Dbg( p_mgr, "Something went wrong in %s (%s:%d)",
789                  __func__, __FILE__, __LINE__ );
790     }
791     return i_ret;
792 }
793
794 /* Must be entered with the Lock on Extension */
795 static lua_State* GetLuaState( extensions_manager_t *p_mgr,
796                                extension_t *p_ext )
797 {
798     lua_State *L = NULL;
799     if( p_ext )
800         L = p_ext->p_sys->L;
801
802     if( !L )
803     {
804         L = luaL_newstate();
805         if( !L )
806         {
807             msg_Err( p_mgr, "Could not create new Lua State" );
808             return NULL;
809         }
810         vlclua_set_this( L, p_mgr );
811         vlclua_extension_set( L, p_ext );
812
813         luaL_openlibs( L );
814         luaL_register( L, "vlc", p_reg );
815         luaopen_msg( L );
816
817         if( p_ext )
818         {
819             /* Load more libraries */
820             luaopen_config( L );
821             luaopen_dialog( L, p_ext );
822             luaopen_input( L );
823             luaopen_msg( L );
824             luaopen_net( L );
825             luaopen_object( L );
826             luaopen_osd( L );
827             luaopen_playlist( L );
828             luaopen_sd( L );
829             luaopen_stream( L );
830             luaopen_strings( L );
831             luaopen_variables( L );
832             luaopen_video( L );
833             luaopen_vlm( L );
834             luaopen_volume( L );
835             luaopen_xml( L );
836 #if defined(_WIN32) && !VLC_WINSTORE_APP
837             luaopen_win( L );
838 #endif
839
840             /* Register extension specific functions */
841             lua_getglobal( L, "vlc" );
842             lua_pushcfunction( L, vlclua_extension_deactivate );
843             lua_setfield( L, -2, "deactivate" );
844             lua_pushcfunction( L, vlclua_extension_keep_alive );
845             lua_setfield( L, -2, "keep_alive" );
846
847             /* Setup the module search path */
848             if( !strncmp( p_ext->psz_name, "zip://", 6 ) )
849             {
850                 /* Load all required modules manually */
851                 lua_register( L, "require", &vlclua_extension_require );
852             }
853             else
854             {
855                 if( vlclua_add_modules_path( L, p_ext->psz_name ) )
856                 {
857                     msg_Warn( p_mgr, "Error while setting the module "
858                               "search path for %s", p_ext->psz_name );
859                     lua_close( L );
860                     return NULL;
861                 }
862             }
863             /* Load and run the script(s) */
864             if( vlclua_dofile( VLC_OBJECT( p_mgr ), L, p_ext->psz_name ) )
865             {
866                 msg_Warn( p_mgr, "Error loading script %s: %s", p_ext->psz_name,
867                           lua_tostring( L, lua_gettop( L ) ) );
868                 lua_close( L );
869                 return NULL;
870             }
871
872             p_ext->p_sys->L = L;
873         }
874     }
875
876     return L;
877 }
878
879 int lua_ExecuteFunction( extensions_manager_t *p_mgr, extension_t *p_ext,
880                             const char *psz_function, ... )
881 {
882     va_list args;
883     va_start( args, psz_function );
884     int i_ret = lua_ExecuteFunctionVa( p_mgr, p_ext, psz_function, args );
885     va_end( args );
886     return i_ret;
887 }
888
889 /**
890  * Execute a function in a Lua script
891  * @param psz_function Name of global function to execute. If NULL, assume
892  *                     that the function object is already on top of the
893  *                     stack.
894  * @return < 0 in case of failure, >= 0 in case of success
895  * @note It's better to call this function from a dedicated thread
896  * (see extension_thread.c)
897  **/
898 int lua_ExecuteFunctionVa( extensions_manager_t *p_mgr, extension_t *p_ext,
899                            const char *psz_function, va_list args )
900 {
901     int i_ret = VLC_SUCCESS;
902     int i_args = 0;
903     assert( p_mgr != NULL );
904     assert( p_ext != NULL );
905
906     lua_State *L = GetLuaState( p_mgr, p_ext );
907     if( !L )
908         return -1;
909
910     if( psz_function )
911         lua_getglobal( L, psz_function );
912
913     if( !lua_isfunction( L, -1 ) )
914     {
915         msg_Warn( p_mgr, "Error while running script %s, "
916                   "function %s() not found", p_ext->psz_name, psz_function );
917         goto exit;
918     }
919
920     lua_datatype_e type = LUA_END;
921     while( ( type = va_arg( args, int ) ) != LUA_END )
922     {
923         if( type == LUA_NUM )
924         {
925             lua_pushnumber( L , ( int ) va_arg( args, int ) );
926         }
927         else if( type == LUA_TEXT )
928         {
929             lua_pushstring( L , ( char * ) va_arg( args, char* ) );
930         }
931         else
932         {
933             msg_Warn( p_mgr, "Undefined argument type %d to lua function %s"
934                    "from script %s", type, psz_function, p_ext->psz_name );
935             goto exit;
936         }
937         i_args ++;
938     }
939
940     // Create watch timer
941     vlc_mutex_lock( &p_ext->p_sys->command_lock );
942     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
943     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
944
945     // Start actual call to Lua
946     if( lua_pcall( L, i_args, 1, 0 ) )
947     {
948         msg_Warn( p_mgr, "Error while running script %s, "
949                   "function %s(): %s", p_ext->psz_name, psz_function,
950                   lua_tostring( L, lua_gettop( L ) ) );
951         i_ret = VLC_EGENERIC;
952     }
953
954     // Reset watch timer and timestamp
955     vlc_mutex_lock( &p_ext->p_sys->command_lock );
956     if( p_ext->p_sys->progress )
957     {
958         dialog_ProgressDestroy( p_ext->p_sys->progress );
959         p_ext->p_sys->progress = NULL;
960     }
961     vlc_timer_schedule( p_ext->p_sys->timer, false, 0, 0 );
962     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
963
964     i_ret |= lua_DialogFlush( L );
965
966 exit:
967     return i_ret;
968
969 }
970
971 static inline int TriggerMenu( extension_t *p_ext, int i_id )
972 {
973     return PushCommand( p_ext, CMD_TRIGGERMENU, i_id );
974 }
975
976 int lua_ExtensionTriggerMenu( extensions_manager_t *p_mgr,
977                               extension_t *p_ext, int id )
978 {
979     int i_ret = VLC_SUCCESS;
980     lua_State *L = GetLuaState( p_mgr, p_ext );
981
982     if( !L )
983         return VLC_EGENERIC;
984
985     luaopen_dialog( L, p_ext );
986
987     lua_getglobal( L, "trigger_menu" );
988     if( !lua_isfunction( L, -1 ) )
989     {
990         msg_Warn( p_mgr, "Error while running script %s, "
991                   "function trigger_menu() not found", p_ext->psz_name );
992         return VLC_EGENERIC;
993     }
994
995     /* Pass id as unique argument to the function */
996     lua_pushinteger( L, id );
997
998     // Create watch timer
999     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1000     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
1001     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1002
1003     if( lua_pcall( L, 1, 1, 0 ) != 0 )
1004     {
1005         msg_Warn( p_mgr, "Error while running script %s, "
1006                   "function trigger_menu(): %s", p_ext->psz_name,
1007                   lua_tostring( L, lua_gettop( L ) ) );
1008         i_ret = VLC_EGENERIC;
1009     }
1010
1011     // Reset watch timer and timestamp
1012     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1013     if( p_ext->p_sys->progress )
1014     {
1015         dialog_ProgressDestroy( p_ext->p_sys->progress );
1016         p_ext->p_sys->progress = NULL;
1017     }
1018     vlc_timer_schedule( p_ext->p_sys->timer, false, 0, 0 );
1019     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1020
1021     i_ret |= lua_DialogFlush( L );
1022     if( i_ret < VLC_SUCCESS )
1023     {
1024         msg_Dbg( p_mgr, "Something went wrong in %s (%s:%d)",
1025                  __func__, __FILE__, __LINE__ );
1026     }
1027
1028     return i_ret;
1029 }
1030
1031 /** Directly trigger an extension, without activating it
1032  * This is NOT multithreaded, and this code runs in the UI thread
1033  * @param p_mgr
1034  * @param p_ext Extension to trigger
1035  * @return Value returned by the lua function "trigger"
1036  **/
1037 static int TriggerExtension( extensions_manager_t *p_mgr,
1038                              extension_t *p_ext )
1039 {
1040     int i_ret = lua_ExecuteFunction( p_mgr, p_ext, "trigger", LUA_END );
1041
1042     /* Close lua state for trigger-only extensions */
1043     if( p_ext->p_sys->L )
1044         lua_close( p_ext->p_sys->L );
1045     p_ext->p_sys->L = NULL;
1046
1047     return i_ret;
1048 }
1049
1050 /** Set extension associated to the current script
1051  * @param L current lua_State
1052  * @param p_ext the extension
1053  */
1054 void vlclua_extension_set( lua_State *L, extension_t *p_ext )
1055 {
1056     lua_pushlightuserdata( L, vlclua_extension_set );
1057     lua_pushlightuserdata( L, p_ext );
1058     lua_rawset( L, LUA_REGISTRYINDEX );
1059 }
1060
1061 /** Retrieve extension associated to the current script
1062  * @param L current lua_State
1063  * @return Extension pointer
1064  **/
1065 extension_t *vlclua_extension_get( lua_State *L )
1066 {
1067     lua_pushlightuserdata( L, vlclua_extension_set );
1068     lua_rawget( L, LUA_REGISTRYINDEX );
1069     extension_t *p_ext = (extension_t*) lua_topointer( L, -1 );
1070     lua_pop( L, 1 );
1071     return p_ext;
1072 }
1073
1074 /** Deactivate an extension by order from the extension itself
1075  * @param L lua_State
1076  * @note This is an asynchronous call. A script calling vlc.deactivate() will
1077  * be executed to the end before the last call to deactivate() is done.
1078  **/
1079 int vlclua_extension_deactivate( lua_State *L )
1080 {
1081     extension_t *p_ext = vlclua_extension_get( L );
1082     int i_ret = Deactivate( p_ext->p_sys->p_mgr, p_ext );
1083     return ( i_ret == VLC_SUCCESS ) ? 1 : 0;
1084 }
1085
1086 /** Keep an extension alive. This resets the watch timer to 0
1087  * @param L lua_State
1088  * @note This is the "vlc.keep_alive()" function
1089  **/
1090 int vlclua_extension_keep_alive( lua_State *L )
1091 {
1092     extension_t *p_ext = vlclua_extension_get( L );
1093
1094     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1095     if( p_ext->p_sys->progress )
1096     {
1097         dialog_ProgressDestroy( p_ext->p_sys->progress );
1098         p_ext->p_sys->progress = NULL;
1099     }
1100     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
1101     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1102
1103     return 1;
1104 }
1105
1106 /** Callback for the variable "dialog-event"
1107  * @param p_this Current object owner of the extension and the dialog
1108  * @param psz_var "dialog-event"
1109  * @param oldval Unused
1110  * @param newval Address of the dialog
1111  * @param p_data Unused
1112  **/
1113 static int vlclua_extension_dialog_callback( vlc_object_t *p_this,
1114                                              char const *psz_var,
1115                                              vlc_value_t oldval,
1116                                              vlc_value_t newval,
1117                                              void *p_data )
1118 {
1119     /* psz_var == "dialog-event" */
1120     ( void ) psz_var;
1121     ( void ) oldval;
1122     ( void ) p_data;
1123
1124     extension_dialog_command_t *command = newval.p_address;
1125     assert( command != NULL );
1126     assert( command->p_dlg != NULL);
1127
1128     extension_t *p_ext = command->p_dlg->p_sys;
1129     assert( p_ext != NULL );
1130
1131     extension_widget_t *p_widget = command->p_data;
1132
1133     switch( command->event )
1134     {
1135         case EXTENSION_EVENT_CLICK:
1136             assert( p_widget != NULL );
1137             PushCommandUnique( p_ext, CMD_CLICK, p_widget );
1138             break;
1139         case EXTENSION_EVENT_CLOSE:
1140             PushCommandUnique( p_ext, CMD_CLOSE );
1141             break;
1142         default:
1143             msg_Dbg( p_this, "Received unknown UI event %d, discarded",
1144                      command->event );
1145             break;
1146     }
1147
1148     return VLC_SUCCESS;
1149 }
1150
1151 /** Callback on vlc_InputItemMetaChanged event
1152  **/
1153 static void inputItemMetaChanged( const vlc_event_t *p_event,
1154                                   void *data )
1155 {
1156     assert( p_event && p_event->type == vlc_InputItemMetaChanged );
1157
1158     extension_t *p_ext = ( extension_t* ) data;
1159     assert( p_ext != NULL );
1160
1161     PushCommandUnique( p_ext, CMD_UPDATE_META );
1162 }
1163
1164 /** Lock this extension. Can fail. */
1165 bool LockExtension( extension_t *p_ext )
1166 {
1167     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1168     if( p_ext->p_sys->b_exiting )
1169     {
1170         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1171         return false;
1172     }
1173
1174     vlc_mutex_lock( &p_ext->p_sys->running_lock );
1175     if( p_ext->p_sys->b_exiting )
1176     {
1177         vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1178         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1179         return false;
1180     }
1181
1182     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1183     return true;
1184 }
1185
1186 /** Unlock this extension. */
1187 void UnlockExtension( extension_t *p_ext )
1188 {
1189     vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1190 }
1191
1192 /** Watch timer callback
1193  * The timer expired, Lua may be stuck, ask the user what to do now
1194  **/
1195 static void WatchTimerCallback( void *data )
1196 {
1197     extension_t *p_ext = data;
1198     extensions_manager_t *p_mgr = p_ext->p_sys->p_mgr;
1199
1200     char *message;
1201     if( asprintf( &message, _( "Extension '%s' does not respond.\n"
1202                                "Do you want to kill it now? " ),
1203                   p_ext->psz_title ) == -1 )
1204     {
1205         return;
1206     }
1207
1208     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1209
1210     // Do we have a pending Deactivate command?
1211     if( ( p_ext->p_sys->command &&
1212           p_ext->p_sys->command->i_command == CMD_DEACTIVATE )
1213         || ( p_ext->p_sys->command->next
1214              && p_ext->p_sys->command->next->i_command == CMD_DEACTIVATE) )
1215     {
1216         if( p_ext->p_sys->progress )
1217         {
1218             dialog_ProgressDestroy( p_ext->p_sys->progress );
1219             p_ext->p_sys->progress = NULL;
1220         }
1221         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1222         KillExtension( p_mgr, p_ext );
1223         return;
1224     }
1225
1226     if( !p_ext->p_sys->progress )
1227     {
1228         p_ext->p_sys->progress =
1229                 dialog_ProgressCreate( p_mgr, _( "Extension not responding!" ),
1230                                        message,
1231                                        _( "Yes" ) );
1232         vlc_timer_schedule( p_ext->p_sys->timer, false, 100000, 0 );
1233     }
1234     else
1235     {
1236         if( dialog_ProgressCancelled( p_ext->p_sys->progress ) )
1237         {
1238             dialog_ProgressDestroy( p_ext->p_sys->progress );
1239             p_ext->p_sys->progress = NULL;
1240             vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1241             KillExtension( p_mgr, p_ext );
1242             return;
1243         }
1244         vlc_timer_schedule( p_ext->p_sys->timer, false, 100000, 0 );
1245     }
1246     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1247 }