]> git.sesse.net Git - vlc/blob - modules/lua/extension.c
lua: remove MD5 functions before someone uses them
[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_msg( L );
830             luaopen_net( L );
831             luaopen_object( L );
832             luaopen_osd( L );
833             luaopen_playlist( L );
834             luaopen_sd( L );
835             luaopen_stream( L );
836             luaopen_strings( L );
837             luaopen_variables( L );
838             luaopen_video( L );
839             luaopen_vlm( L );
840             luaopen_volume( L );
841             luaopen_xml( L );
842
843             /* Register extension specific functions */
844             lua_getglobal( L, "vlc" );
845             lua_pushcfunction( L, vlclua_extension_deactivate );
846             lua_setfield( L, -2, "deactivate" );
847             lua_pushcfunction( L, vlclua_extension_keep_alive );
848             lua_setfield( L, -2, "keep_alive" );
849
850             /* Setup the module search path */
851             if( !strncmp( p_ext->psz_name, "zip://", 6 ) )
852             {
853                 /* Load all required modules manually */
854                 lua_register( L, "require", &vlclua_extension_require );
855             }
856             else
857             {
858                 if( vlclua_add_modules_path( p_mgr, L, p_ext->psz_name ) )
859                 {
860                     msg_Warn( p_mgr, "Error while setting the module "
861                               "search path for %s", p_ext->psz_name );
862                     lua_close( L );
863                     return NULL;
864                 }
865             }
866             /* Load and run the script(s) */
867             if( vlclua_dofile( VLC_OBJECT( p_mgr ), L, p_ext->psz_name ) )
868             {
869                 msg_Warn( p_mgr, "Error loading script %s: %s", p_ext->psz_name,
870                           lua_tostring( L, lua_gettop( L ) ) );
871                 lua_close( L );
872                 return NULL;
873             }
874
875             p_ext->p_sys->L = L;
876         }
877     }
878
879     return L;
880 }
881
882 int lua_ExecuteFunction( extensions_manager_t *p_mgr, extension_t *p_ext,
883                             const char *psz_function, ... )
884 {
885     va_list args;
886     va_start( args, psz_function );
887     int i_ret = lua_ExecuteFunctionVa( p_mgr, p_ext, psz_function, args );
888     va_end( args );
889     return i_ret;
890 }
891
892 /**
893  * Execute a function in a Lua script
894  * @param psz_function Name of global function to execute. If NULL, assume
895  *                     that the function object is already on top of the
896  *                     stack.
897  * @return < 0 in case of failure, >= 0 in case of success
898  * @note It's better to call this function from a dedicated thread
899  * (see extension_thread.c)
900  **/
901 int lua_ExecuteFunctionVa( extensions_manager_t *p_mgr, extension_t *p_ext,
902                            const char *psz_function, va_list args )
903 {
904     int i_ret = VLC_SUCCESS;
905     int i_args = 0;
906     assert( p_mgr != NULL );
907     assert( p_ext != NULL );
908
909     lua_State *L = GetLuaState( p_mgr, p_ext );
910     if( !L )
911         return -1;
912
913     if( psz_function )
914         lua_getglobal( L, psz_function );
915
916     if( !lua_isfunction( L, -1 ) )
917     {
918         msg_Warn( p_mgr, "Error while running script %s, "
919                   "function %s() not found", p_ext->psz_name, psz_function );
920         goto exit;
921     }
922
923     lua_datatype_e type = LUA_END;
924     while( ( type = va_arg( args, int ) ) != LUA_END )
925     {
926         if( type == LUA_NUM )
927         {
928             lua_pushnumber( L , ( int ) va_arg( args, int ) );
929         }
930         else if( type == LUA_TEXT )
931         {
932             lua_pushstring( L , ( char * ) va_arg( args, char* ) );
933         }
934         else
935         {
936             msg_Warn( p_mgr, "Undefined argument type %d to lua function %s"
937                    "from script %s", type, psz_function, p_ext->psz_name );
938             goto exit;
939         }
940         i_args ++;
941     }
942
943     // Create watch timer
944     vlc_mutex_lock( &p_ext->p_sys->command_lock );
945     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
946     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
947
948     // Start actual call to Lua
949     if( lua_pcall( L, i_args, 1, 0 ) )
950     {
951         msg_Warn( p_mgr, "Error while running script %s, "
952                   "function %s(): %s", p_ext->psz_name, psz_function,
953                   lua_tostring( L, lua_gettop( L ) ) );
954         i_ret = VLC_EGENERIC;
955     }
956
957     // Reset watch timer and timestamp
958     vlc_mutex_lock( &p_ext->p_sys->command_lock );
959     if( p_ext->p_sys->progress )
960     {
961         dialog_ProgressDestroy( p_ext->p_sys->progress );
962         p_ext->p_sys->progress = NULL;
963     }
964     vlc_timer_schedule( p_ext->p_sys->timer, false, 0, 0 );
965     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
966
967     i_ret |= lua_DialogFlush( L );
968
969 exit:
970     return i_ret;
971
972 }
973
974 static inline int TriggerMenu( extension_t *p_ext, int i_id )
975 {
976     return PushCommand( p_ext, CMD_TRIGGERMENU, i_id );
977 }
978
979 int lua_ExtensionTriggerMenu( extensions_manager_t *p_mgr,
980                               extension_t *p_ext, int id )
981 {
982     int i_ret = VLC_SUCCESS;
983     lua_State *L = GetLuaState( p_mgr, p_ext );
984
985     if( !L )
986         return VLC_EGENERIC;
987
988     luaopen_dialog( L, p_ext );
989
990     lua_getglobal( L, "trigger_menu" );
991     if( !lua_isfunction( L, -1 ) )
992     {
993         msg_Warn( p_mgr, "Error while running script %s, "
994                   "function trigger_menu() not found", p_ext->psz_name );
995         return VLC_EGENERIC;
996     }
997
998     /* Pass id as unique argument to the function */
999     lua_pushinteger( L, id );
1000
1001     // Create watch timer
1002     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1003     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
1004     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1005
1006     if( lua_pcall( L, 1, 1, 0 ) != 0 )
1007     {
1008         msg_Warn( p_mgr, "Error while running script %s, "
1009                   "function trigger_menu(): %s", p_ext->psz_name,
1010                   lua_tostring( L, lua_gettop( L ) ) );
1011         i_ret = VLC_EGENERIC;
1012     }
1013
1014     // Reset watch timer and timestamp
1015     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1016     if( p_ext->p_sys->progress )
1017     {
1018         dialog_ProgressDestroy( p_ext->p_sys->progress );
1019         p_ext->p_sys->progress = NULL;
1020     }
1021     vlc_timer_schedule( p_ext->p_sys->timer, false, 0, 0 );
1022     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1023
1024     i_ret |= lua_DialogFlush( L );
1025     if( i_ret < VLC_SUCCESS )
1026     {
1027         msg_Dbg( p_mgr, "Something went wrong in %s (%s:%d)",
1028                  __func__, __FILE__, __LINE__ );
1029     }
1030
1031     return i_ret;
1032 }
1033
1034 /** Directly trigger an extension, without activating it
1035  * This is NOT multithreaded, and this code runs in the UI thread
1036  * @param p_mgr
1037  * @param p_ext Extension to trigger
1038  * @return Value returned by the lua function "trigger"
1039  **/
1040 static int TriggerExtension( extensions_manager_t *p_mgr,
1041                              extension_t *p_ext )
1042 {
1043     int i_ret = lua_ExecuteFunction( p_mgr, p_ext, "trigger", LUA_END );
1044
1045     /* Close lua state for trigger-only extensions */
1046     if( p_ext->p_sys->L )
1047         lua_close( p_ext->p_sys->L );
1048     p_ext->p_sys->L = NULL;
1049
1050     return i_ret;
1051 }
1052
1053 /** Set extension associated to the current script
1054  * @param L current lua_State
1055  * @param p_ext the extension
1056  */
1057 void vlclua_extension_set( lua_State *L, extension_t *p_ext )
1058 {
1059     lua_pushlightuserdata( L, vlclua_extension_set );
1060     lua_pushlightuserdata( L, p_ext );
1061     lua_rawset( L, LUA_REGISTRYINDEX );
1062 }
1063
1064 /** Retrieve extension associated to the current script
1065  * @param L current lua_State
1066  * @return Extension pointer
1067  **/
1068 extension_t *vlclua_extension_get( lua_State *L )
1069 {
1070     lua_pushlightuserdata( L, vlclua_extension_set );
1071     lua_rawget( L, LUA_REGISTRYINDEX );
1072     extension_t *p_ext = (extension_t*) lua_topointer( L, -1 );
1073     lua_pop( L, 1 );
1074     return p_ext;
1075 }
1076
1077 /** Deactivate an extension by order from the extension itself
1078  * @param L lua_State
1079  * @note This is an asynchronous call. A script calling vlc.deactivate() will
1080  * be executed to the end before the last call to deactivate() is done.
1081  **/
1082 int vlclua_extension_deactivate( lua_State *L )
1083 {
1084     extension_t *p_ext = vlclua_extension_get( L );
1085     int i_ret = Deactivate( p_ext->p_sys->p_mgr, p_ext );
1086     return ( i_ret == VLC_SUCCESS ) ? 1 : 0;
1087 }
1088
1089 /** Keep an extension alive. This resets the watch timer to 0
1090  * @param L lua_State
1091  * @note This is the "vlc.keep_alive()" function
1092  **/
1093 int vlclua_extension_keep_alive( lua_State *L )
1094 {
1095     extension_t *p_ext = vlclua_extension_get( L );
1096
1097     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1098     if( p_ext->p_sys->progress )
1099     {
1100         dialog_ProgressDestroy( p_ext->p_sys->progress );
1101         p_ext->p_sys->progress = NULL;
1102     }
1103     vlc_timer_schedule( p_ext->p_sys->timer, false, WATCH_TIMER_PERIOD, 0 );
1104     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1105
1106     return 1;
1107 }
1108
1109 /** Callback for the variable "dialog-event"
1110  * @param p_this Current object owner of the extension and the dialog
1111  * @param psz_var "dialog-event"
1112  * @param oldval Unused
1113  * @param newval Address of the dialog
1114  * @param p_data Unused
1115  **/
1116 static int vlclua_extension_dialog_callback( vlc_object_t *p_this,
1117                                              char const *psz_var,
1118                                              vlc_value_t oldval,
1119                                              vlc_value_t newval,
1120                                              void *p_data )
1121 {
1122     /* psz_var == "dialog-event" */
1123     ( void ) psz_var;
1124     ( void ) oldval;
1125     ( void ) p_data;
1126
1127     extension_dialog_command_t *command = newval.p_address;
1128     assert( command != NULL );
1129     assert( command->p_dlg != NULL);
1130
1131     extension_t *p_ext = command->p_dlg->p_sys;
1132     assert( p_ext != NULL );
1133
1134     extension_widget_t *p_widget = command->p_data;
1135
1136     switch( command->event )
1137     {
1138         case EXTENSION_EVENT_CLICK:
1139             assert( p_widget != NULL );
1140             PushCommandUnique( p_ext, CMD_CLICK, p_widget );
1141             break;
1142         case EXTENSION_EVENT_CLOSE:
1143             PushCommandUnique( p_ext, CMD_CLOSE );
1144             break;
1145         default:
1146             msg_Dbg( p_this, "Received unknown UI event %d, discarded",
1147                      command->event );
1148             break;
1149     }
1150
1151     return VLC_SUCCESS;
1152 }
1153
1154 /** Callback on vlc_InputItemMetaChanged event
1155  **/
1156 static void inputItemMetaChanged( const vlc_event_t *p_event,
1157                                   void *data )
1158 {
1159     assert( p_event && p_event->type == vlc_InputItemMetaChanged );
1160
1161     extension_t *p_ext = ( extension_t* ) data;
1162     assert( p_ext != NULL );
1163
1164     PushCommandUnique( p_ext, CMD_UPDATE_META );
1165 }
1166
1167 /** Lock this extension. Can fail. */
1168 bool LockExtension( extension_t *p_ext )
1169 {
1170     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1171     if( p_ext->p_sys->b_exiting )
1172     {
1173         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1174         return false;
1175     }
1176
1177     vlc_mutex_lock( &p_ext->p_sys->running_lock );
1178     if( p_ext->p_sys->b_exiting )
1179     {
1180         vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1181         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1182         return false;
1183     }
1184
1185     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1186     return true;
1187 }
1188
1189 /** Unlock this extension. */
1190 void UnlockExtension( extension_t *p_ext )
1191 {
1192     vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1193 }
1194
1195 /** Watch timer callback
1196  * The timer expired, Lua may be stuck, ask the user what to do now
1197  **/
1198 static void WatchTimerCallback( void *data )
1199 {
1200     extension_t *p_ext = data;
1201     extensions_manager_t *p_mgr = p_ext->p_sys->p_mgr;
1202
1203     char *message;
1204     if( asprintf( &message, _( "Extension '%s' does not respond.\n"
1205                                "Do you want to kill it now? " ),
1206                   p_ext->psz_title ) == -1 )
1207     {
1208         return;
1209     }
1210
1211     vlc_mutex_lock( &p_ext->p_sys->command_lock );
1212
1213     // Do we have a pending Deactivate command?
1214     if( ( p_ext->p_sys->command &&
1215           p_ext->p_sys->command->i_command == CMD_DEACTIVATE )
1216         || ( p_ext->p_sys->command->next
1217              && p_ext->p_sys->command->next->i_command == CMD_DEACTIVATE) )
1218     {
1219         if( p_ext->p_sys->progress )
1220         {
1221             dialog_ProgressDestroy( p_ext->p_sys->progress );
1222             p_ext->p_sys->progress = NULL;
1223         }
1224         vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1225         KillExtension( p_mgr, p_ext );
1226         return;
1227     }
1228
1229     if( !p_ext->p_sys->progress )
1230     {
1231         p_ext->p_sys->progress =
1232                 dialog_ProgressCreate( p_mgr, _( "Extension not responding!" ),
1233                                        message,
1234                                        _( "Yes" ) );
1235         vlc_timer_schedule( p_ext->p_sys->timer, false, 100000, 0 );
1236     }
1237     else
1238     {
1239         if( dialog_ProgressCancelled( p_ext->p_sys->progress ) )
1240         {
1241             dialog_ProgressDestroy( p_ext->p_sys->progress );
1242             p_ext->p_sys->progress = NULL;
1243             vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1244             KillExtension( p_mgr, p_ext );
1245             return;
1246         }
1247         vlc_timer_schedule( p_ext->p_sys->timer, false, 100000, 0 );
1248     }
1249     vlc_mutex_unlock( &p_ext->p_sys->command_lock );
1250 }