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