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