]> git.sesse.net Git - vlc/blob - modules/misc/lua/extension.c
lua_extension: factorize.
[vlc] / modules / misc / 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 #include "vlc.h"
25 #include "libs.h"
26 #include "extension.h"
27 #include "assert.h"
28
29 #include <vlc_input.h>
30 #include <vlc_events.h>
31
32 /* Functions to register */
33 static const luaL_Reg p_reg[] =
34 {
35     { NULL, NULL }
36 };
37
38 /*
39  * Extensions capabilities
40  * Note: #define and ppsz_capabilities must be in sync
41  */
42 #define EXT_HAS_MENU          (1 << 0)   ///< Hook: menu
43 #define EXT_TRIGGER_ONLY      (1 << 1)   ///< Hook: trigger. Not activable
44 #define EXT_INPUT_LISTENER    (1 << 2)   ///< Hook: input_changed
45 #define EXT_META_LISTENER     (1 << 3)   ///< Hook: meta_changed
46 #define EXT_PLAYING_LISTENER  (1 << 4)   ///< Hook: status_changed
47
48 const char* const ppsz_capabilities[] = {
49     "menu",
50     "trigger",
51     "input-listener",
52     "meta-listener",
53     "playing-listener",
54     NULL
55 };
56
57 static int ScanExtensions( extensions_manager_t *p_this );
58 static int ScanLuaCallback( vlc_object_t *p_this, const char *psz_script,
59                             void *pb_continue );
60 static int Control( extensions_manager_t *, int, va_list );
61 static int GetMenuEntries( extensions_manager_t *p_mgr, extension_t *p_ext,
62                     char ***pppsz_titles, uint16_t **ppi_ids );
63 static lua_State* GetLuaState( extensions_manager_t *p_mgr,
64                                extension_t *p_ext );
65 static int TriggerMenu( extension_t *p_ext, int id );
66 static int TriggerExtension( extensions_manager_t *p_mgr,
67                              extension_t *p_ext );
68
69 int vlclua_extension_deactivate( lua_State *L );
70
71 /* Interactions */
72 static int vlclua_extension_dialog_callback( vlc_object_t *p_this,
73                                              char const *psz_var,
74                                              vlc_value_t oldval,
75                                              vlc_value_t newval,
76                                              void *p_data );
77
78 /* Input item callback: vlc_InputItemMetaChanged */
79 static void inputItemMetaChanged( const vlc_event_t *p_event,
80                                   void *data );
81
82
83 /**
84  * Module entry-point
85  **/
86 int Open_Extension( vlc_object_t *p_this )
87 {
88     msg_Dbg( p_this, "Opening EXPERIMENTAL Lua Extension module" );
89
90     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
91
92     p_mgr->pf_control = Control;
93
94     extensions_manager_sys_t *p_sys = ( extensions_manager_sys_t* )
95                     calloc( 1, sizeof( extensions_manager_sys_t ) );
96     if( !p_sys ) return VLC_ENOMEM;
97
98     p_mgr->p_sys = p_sys;
99     ARRAY_INIT( p_sys->activated_extensions );
100     ARRAY_INIT( p_mgr->extensions );
101     vlc_mutex_init( &p_mgr->lock );
102     vlc_mutex_init( &p_mgr->p_sys->lock );
103
104     /* Scan available Lua Extensions */
105     if( ScanExtensions( p_mgr ) != VLC_SUCCESS )
106     {
107         msg_Err( p_mgr, "Can't load extensions modules" );
108         return VLC_EGENERIC;
109     }
110
111     // Create the dialog-event variable
112     var_Create( p_this, "dialog-event", VLC_VAR_ADDRESS );
113     var_AddCallback( p_this, "dialog-event",
114                      vlclua_extension_dialog_callback, NULL );
115
116     return VLC_SUCCESS;
117 }
118
119 /**
120  * Module unload function
121  **/
122 void Close_Extension( vlc_object_t *p_this )
123 {
124     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
125     msg_Dbg( p_mgr, "Deactivating all loaded extensions" );
126
127     vlc_mutex_lock( &p_mgr->lock );
128     p_mgr->p_sys->b_killed = true;
129     vlc_mutex_unlock( &p_mgr->lock );
130
131     var_Destroy( p_mgr, "dialog-event" );
132
133     extension_t *p_ext = NULL;
134     FOREACH_ARRAY( p_ext, p_mgr->p_sys->activated_extensions )
135     {
136         if( !p_ext ) break;
137         msg_Dbg( p_mgr, "Deactivating '%s'", p_ext->psz_title );
138         Deactivate( p_mgr, p_ext );
139         WaitForDeactivation( p_ext );
140     }
141     FOREACH_END()
142
143     msg_Dbg( p_mgr, "All extensions are now deactivated" );
144     ARRAY_RESET( p_mgr->p_sys->activated_extensions );
145
146     vlc_mutex_destroy( &p_mgr->lock );
147     vlc_mutex_destroy( &p_mgr->p_sys->lock );
148     free( p_mgr->p_sys );
149     p_mgr->p_sys = NULL;
150
151     /* Free extensions' memory */
152     FOREACH_ARRAY( p_ext, p_mgr->extensions )
153     {
154         if( !p_ext )
155             break;
156         if( p_ext->p_sys->L )
157             lua_close( p_ext->p_sys->L );
158         free( p_ext->psz_name );
159         free( p_ext->psz_title );
160         free( p_ext->psz_author );
161         free( p_ext->psz_description );
162         free( p_ext->psz_shortdescription );
163         free( p_ext->psz_url );
164         free( p_ext->psz_version );
165
166         vlc_mutex_destroy( &p_ext->p_sys->running_lock );
167         vlc_mutex_destroy( &p_ext->p_sys->command_lock );
168         vlc_cond_destroy( &p_ext->p_sys->wait );
169
170         free( p_ext->p_sys );
171         free( p_ext );
172     }
173     FOREACH_END()
174
175     ARRAY_RESET( p_mgr->extensions );
176 }
177
178 /**
179  * Batch scan all Lua files in folder "extensions"
180  * @param p_mgr This extensions_manager_t object
181  **/
182 static int ScanExtensions( extensions_manager_t *p_mgr )
183 {
184     bool b_true = true;
185     int i_ret =
186         vlclua_scripts_batch_execute( VLC_OBJECT( p_mgr ),
187                                       "extensions",
188                                       &ScanLuaCallback,
189                                       &b_true );
190
191     if( !i_ret )
192         return VLC_EGENERIC;
193
194     return VLC_SUCCESS;
195 }
196
197 /**
198  * Dummy Lua function: does nothing
199  * @note This function can be used to replace "require" while scanning for
200  * extensions
201  * Even the built-in libraries are not loaded when calling descriptor()
202  **/
203 static int vlclua_dummy_require( lua_State *L )
204 {
205     (void) L;
206     return 0;
207 }
208
209 /**
210  * Batch scan all Lua files in folder "extensions": callback
211  * @param p_this This extensions_manager_t object
212  * @param psz_script Name of the script to run
213  * @param L Lua State, common to all scripts here
214  * @param pb_continue bool* that indicates whether to continue batch or not
215  **/
216 int ScanLuaCallback( vlc_object_t *p_this, const char *psz_script,
217                      void *pb_continue )
218 {
219     extensions_manager_t *p_mgr = ( extensions_manager_t* ) p_this;
220     bool b_ok = false;
221
222     msg_Dbg( p_mgr, "Scanning Lua script %s", psz_script );
223
224     vlc_mutex_lock( &p_mgr->lock );
225
226     /* Create new script descriptor */
227     extension_t *p_ext = ( extension_t* ) calloc( 1, sizeof( extension_t ) );
228     if( !p_ext )
229     {
230         vlc_mutex_unlock( &p_mgr->lock );
231         return 0;
232     }
233
234     p_ext->psz_name = strdup( psz_script );
235     p_ext->p_sys = (extension_sys_t*) calloc( 1, sizeof( extension_sys_t ) );
236     if( !p_ext->p_sys || !p_ext->psz_name )
237     {
238         free( p_ext->psz_name );
239         free( p_ext->p_sys );
240         free( p_ext );
241         vlc_mutex_unlock( &p_mgr->lock );
242         return 0;
243     }
244     p_ext->p_sys->p_mgr = p_mgr;
245
246     /* Mutexes and conditions */
247     vlc_mutex_init( &p_ext->p_sys->command_lock );
248     vlc_mutex_init( &p_ext->p_sys->running_lock );
249     vlc_cond_init( &p_ext->p_sys->wait );
250
251     /* Prepare Lua state */
252     lua_State *L = luaL_newstate();
253     lua_register( L, "require", &vlclua_dummy_require );
254
255     /* Let's run it */
256     if( luaL_dofile( L, psz_script ) )
257     {
258         msg_Warn( p_mgr, "Error loading script %s: %s", psz_script,
259                   lua_tostring( L, lua_gettop( L ) ) );
260         lua_pop( L, 1 );
261         goto exit;
262     }
263
264     /* Scan script for capabilities */
265     lua_getglobal( L, "descriptor" );
266
267     if( !lua_isfunction( L, -1 ) )
268     {
269         msg_Warn( p_mgr, "Error while running script %s, "
270                   "function descriptor() not found", psz_script );
271         goto exit;
272     }
273
274     if( lua_pcall( L, 0, 1, 0 ) )
275     {
276         msg_Warn( p_mgr, "Error while running script %s, "
277                   "function descriptor(): %s", psz_script,
278                   lua_tostring( L, lua_gettop( L ) ) );
279         goto exit;
280     }
281
282     if( lua_gettop( L ) )
283     {
284         if( lua_istable( L, -1 ) )
285         {
286             /* Get caps */
287             lua_getfield( L, -1, "capabilities" );
288             if( lua_istable( L, -1 ) )
289             {
290                 lua_pushnil( L );
291                 while( lua_next( L, -2 ) != 0 )
292                 {
293                     /* Key is at index -2 and value at index -1. Discard key */
294                     const char *psz_cap = luaL_checkstring( L, -1 );
295                     int i_cap = 0;
296                     bool b_ok = false;
297                     /* Find this capability's flag */
298                     for( const char *iter = *ppsz_capabilities;
299                          iter != NULL;
300                          iter = ppsz_capabilities[ ++i_cap ])
301                     {
302                         if( !strcmp( iter, psz_cap ) )
303                         {
304                             /* Flag it! */
305                             p_ext->p_sys->i_capabilities |= 1 << i_cap;
306                             b_ok = true;
307                             break;
308                         }
309                     }
310                     if( !b_ok )
311                     {
312                         msg_Warn( p_mgr, "Extension capability '%s' unknown in"
313                                   " script %s", psz_cap, psz_script );
314                     }
315                     /* Removes 'value'; keeps 'key' for next iteration */
316                     lua_pop( L, 1 );
317                 }
318             }
319             else
320             {
321                 msg_Warn( p_mgr, "In script %s, function descriptor() "
322                               "did not return a table of capabilities.",
323                               psz_script );
324             }
325             lua_pop( L, 1 );
326
327             /* Get title */
328             lua_getfield( L, -1, "title" );
329             if( lua_isstring( L, -1 ) )
330             {
331                 p_ext->psz_title = strdup( luaL_checkstring( L, -1 ) );
332             }
333             else
334             {
335                 msg_Dbg( p_mgr, "In script %s, function descriptor() "
336                                 "did not return a string as title.",
337                                 psz_script );
338                 p_ext->psz_title = strdup( psz_script );
339             }
340             lua_pop( L, 1 );
341
342             /* Get author */
343             lua_getfield( L, -1, "author" );
344             if( lua_isstring( L, -1 ) )
345                 p_ext->psz_author = strdup( luaL_optstring( L, -1, NULL ) );
346             lua_pop( L, 1 );
347
348             /* Get description */
349             lua_getfield( L, -1, "description" );
350             if( lua_isstring( L, -1 ) )
351                 p_ext->psz_description = strdup( luaL_optstring( L, -1, NULL ) );
352             lua_pop( L, 1 );
353
354             /* Get short description */
355             lua_getfield( L, -1, "shortdesc" );
356             if( lua_isstring( L, -1 ) )
357                 p_ext->psz_shortdescription = strdup( luaL_optstring( L, -1, NULL ) );
358             lua_pop( L, 1 );
359
360             /* Get URL */
361             lua_getfield( L, -1, "url" );
362             if( lua_isstring( L, -1 ) )
363                 p_ext->psz_url = strdup( luaL_optstring( L, -1, NULL ) );
364             lua_pop( L, 1 );
365
366             /* Get version */
367             lua_getfield( L, -1, "version" );
368             if( lua_isstring( L, -1 ) )
369                 p_ext->psz_version = strdup( luaL_optstring( L, -1, NULL ) );
370             lua_pop( L, 1 );
371         }
372         else
373         {
374             msg_Warn( p_mgr, "In script %s, function descriptor() "
375                       "did not return a table!", psz_script );
376             goto exit;
377         }
378     }
379     else
380     {
381         msg_Err( p_mgr, "Script %s went completely foobar", psz_script );
382         goto exit;
383     }
384
385     msg_Dbg( p_mgr, "Script %s has the following capability flags: 0x%x",
386              psz_script, p_ext->p_sys->i_capabilities );
387
388     b_ok = true;
389 exit:
390     lua_close( L );
391     if( !b_ok )
392     {
393         free( p_ext->psz_name );
394         free( p_ext->psz_title );
395         free( p_ext->psz_url );
396         free( p_ext->psz_author );
397         free( p_ext->psz_description );
398         free( p_ext->psz_shortdescription );
399         free( p_ext->psz_version );
400         vlc_mutex_destroy( &p_ext->p_sys->command_lock );
401         vlc_mutex_destroy( &p_ext->p_sys->running_lock );
402         vlc_cond_destroy( &p_ext->p_sys->wait );
403         free( p_ext->p_sys );
404         free( p_ext );
405     }
406     else
407     {
408         /* Add the extension to the list of known extensions */
409         ARRAY_APPEND( p_mgr->extensions, p_ext );
410     }
411
412     vlc_mutex_unlock( &p_mgr->lock );
413     /* Continue batch execution */
414     return pb_continue ? ( (* (bool*)pb_continue) ? -1 : 0 ) : -1;
415 }
416
417 static int Control( extensions_manager_t *p_mgr, int i_control, va_list args )
418 {
419     extension_t *p_ext = NULL;
420     bool *pb = NULL;
421     uint16_t **ppus = NULL;
422     char ***pppsz = NULL;
423     int i = 0;
424
425     switch( i_control )
426     {
427         case EXTENSION_ACTIVATE:
428             p_ext = ( extension_t* ) va_arg( args, extension_t* );
429             return Activate( p_mgr, p_ext );
430
431         case EXTENSION_DEACTIVATE:
432             p_ext = ( extension_t* ) va_arg( args, extension_t* );
433             return Deactivate( p_mgr, p_ext );
434
435         case EXTENSION_IS_ACTIVATED:
436             p_ext = ( extension_t* ) va_arg( args, extension_t* );
437             pb = ( bool* ) va_arg( args, bool* );
438             *pb = IsActivated( p_mgr, p_ext );
439             break;
440
441         case EXTENSION_HAS_MENU:
442             p_ext = ( extension_t* ) va_arg( args, extension_t* );
443             pb = ( bool* ) va_arg( args, bool* );
444             *pb = ( p_ext->p_sys->i_capabilities & EXT_HAS_MENU ) ? 1 : 0;
445             break;
446
447         case EXTENSION_GET_MENU:
448             p_ext = ( extension_t* ) va_arg( args, extension_t* );
449             pppsz = ( char*** ) va_arg( args, char*** );
450             ppus = ( uint16_t** ) va_arg( args, uint16_t** );
451             return GetMenuEntries( p_mgr, p_ext, pppsz, ppus );
452
453         case EXTENSION_TRIGGER_ONLY:
454             p_ext = ( extension_t* ) va_arg( args, extension_t* );
455             pb = ( bool* ) va_arg( args, bool* );
456             *pb = ( p_ext->p_sys->i_capabilities & EXT_TRIGGER_ONLY ) ? 1 : 0;
457             break;
458
459         case EXTENSION_TRIGGER:
460             p_ext = ( extension_t* ) va_arg( args, extension_t* );
461             return TriggerExtension( p_mgr, p_ext );
462
463         case EXTENSION_TRIGGER_MENU:
464             p_ext = ( extension_t* ) va_arg( args, extension_t* );
465             // GCC: 'uint16_t' is promoted to 'int' when passed through '...'
466             i = ( int ) va_arg( args, int );
467             return TriggerMenu( p_ext, i );
468
469         case EXTENSION_SET_INPUT:
470         {
471             p_ext = ( extension_t* ) va_arg( args, extension_t* );
472             input_thread_t *p_input = va_arg( args, struct input_thread_t * );
473
474             if( !LockExtension( p_ext ) )
475                 return VLC_EGENERIC;
476
477             // Change input
478             input_thread_t *old = p_ext->p_sys->p_input;
479             input_item_t *p_item;
480             if( old )
481             {
482                 // Untrack meta fetched events
483                 if( p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
484                 {
485                     p_item = input_GetItem( old );
486                     vlc_event_detach( &p_item->event_manager,
487                                       vlc_InputItemMetaChanged,
488                                       inputItemMetaChanged,
489                                       p_ext );
490                     vlc_gc_decref( p_item );
491                 }
492                 vlc_object_release( old );
493             }
494
495             p_ext->p_sys->p_input = p_input ? vlc_object_hold( p_input )
496                                             : p_input;
497
498             // Tell the script the input changed
499             if( p_ext->p_sys->i_capabilities & EXT_INPUT_LISTENER )
500             {
501                 PushCommandUnique( p_ext, CMD_SET_INPUT );
502             }
503
504             // Track meta fetched events
505             if( p_ext->p_sys->p_input &&
506                 p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
507             {
508                 p_item = input_GetItem( p_ext->p_sys->p_input );
509                 vlc_gc_incref( p_item );
510                 vlc_event_attach( &p_item->event_manager,
511                                   vlc_InputItemMetaChanged,
512                                   inputItemMetaChanged,
513                                   p_ext );
514             }
515
516             UnlockExtension( p_ext );
517             break;
518         }
519         case EXTENSION_PLAYING_CHANGED:
520         {
521             extension_t *p_ext;
522             p_ext = ( extension_t* ) va_arg( args, extension_t* );
523             assert( p_ext->psz_name != NULL );
524             i = ( int ) va_arg( args, int );
525             if( p_ext->p_sys->i_capabilities & EXT_PLAYING_LISTENER )
526             {
527                 PushCommand( p_ext, CMD_PLAYING_CHANGED, i );
528             }
529             break;
530         }
531         default:
532             msg_Warn( p_mgr, "Control '%d' not yet implemented in Extension",
533                       i_control );
534             return VLC_EGENERIC;
535     }
536
537     return VLC_SUCCESS;
538 }
539
540 int lua_ExtensionActivate( extensions_manager_t *p_mgr, extension_t *p_ext )
541 {
542     assert( p_mgr != NULL && p_ext != NULL );
543     return lua_ExecuteFunction( p_mgr, p_ext, "activate", LUA_END );
544 }
545
546 int lua_ExtensionDeactivate( extensions_manager_t *p_mgr, extension_t *p_ext )
547 {
548     assert( p_mgr != NULL && p_ext != NULL );
549
550     if( !p_ext->p_sys->L )
551         return VLC_SUCCESS;
552
553     // Unset and release input objects
554     if( p_ext->p_sys->p_input )
555     {
556         if( p_ext->p_sys->i_capabilities & EXT_META_LISTENER )
557         {
558             // Release item
559             input_item_t *p_item = input_GetItem( p_ext->p_sys->p_input );
560             vlc_gc_decref( p_item );
561         }
562         vlc_object_release( p_ext->p_sys->p_input );
563     }
564
565     int i_ret = lua_ExecuteFunction( p_mgr, p_ext, "deactivate", LUA_END );
566
567     /* Clear Lua State */
568     lua_close( p_ext->p_sys->L );
569     p_ext->p_sys->L = NULL;
570
571     return i_ret;
572 }
573
574 int lua_ExtensionWidgetClick( extensions_manager_t *p_mgr,
575                               extension_t *p_ext,
576                               extension_widget_t *p_widget )
577 {
578     if( !p_ext->p_sys->L )
579         return VLC_SUCCESS;
580
581     lua_State *L = GetLuaState( p_mgr, p_ext );
582     lua_pushlightuserdata( L, p_widget );
583     lua_gettable( L, LUA_REGISTRYINDEX );
584     return lua_ExecuteFunction( p_mgr, p_ext, NULL, LUA_END );
585 }
586
587
588 /**
589  * Get the list of menu entries from an extension script
590  * @param p_mgr
591  * @param p_ext
592  * @param pppsz_titles Pointer to NULL. All strings must be freed by the caller
593  * @param ppi_ids Pointer to NULL. Must be freed by the caller.
594  * @note This function is allowed to run in the UI thread. This means
595  *       that it MUST respond very fast.
596  * @todo Remove the menu() hook and provide a new function vlc.set_menu()
597  **/
598 static int GetMenuEntries( extensions_manager_t *p_mgr, extension_t *p_ext,
599                     char ***pppsz_titles, uint16_t **ppi_ids )
600 {
601     assert( *pppsz_titles == NULL );
602     assert( *ppi_ids == NULL );
603
604     if( !IsActivated( p_mgr, p_ext ) )
605     {
606         msg_Dbg( p_mgr, "Can't get menu before activating the extension!" );
607         return VLC_EGENERIC;
608     }
609
610     if( !LockExtension( p_ext ) )
611     {
612         /* Dying extension, fail. */
613         return VLC_EGENERIC;
614     }
615
616     int i_ret = VLC_EGENERIC;
617     lua_State *L = GetLuaState( p_mgr, p_ext );
618
619     if( ( p_ext->p_sys->i_capabilities & EXT_HAS_MENU ) == 0 )
620     {
621         msg_Dbg( p_mgr, "can't get a menu from an extension without menu!" );
622         goto exit;
623     }
624
625     lua_getglobal( L, "menu" );
626
627     if( !lua_isfunction( L, -1 ) )
628     {
629         msg_Warn( p_mgr, "Error while running script %s, "
630                   "function menu() not found", p_ext->psz_name );
631         goto exit;
632     }
633
634     if( lua_pcall( L, 0, 1, 0 ) )
635     {
636         msg_Warn( p_mgr, "Error while running script %s, "
637                   "function menu(): %s", p_ext->psz_name,
638                   lua_tostring( L, lua_gettop( L ) ) );
639         goto exit;
640     }
641
642     if( lua_gettop( L ) )
643     {
644         if( lua_istable( L, -1 ) )
645         {
646             /* Get table size */
647             size_t i_size = lua_objlen( L, -1 );
648             *pppsz_titles = ( char** ) calloc( i_size+1, sizeof( char* ) );
649             *ppi_ids = ( uint16_t* ) calloc( i_size+1, sizeof( uint16_t ) );
650
651             /* Walk table */
652             size_t i_idx = 0;
653             lua_pushnil( L );
654             while( lua_next( L, -2 ) != 0 )
655             {
656                 assert( i_idx < i_size );
657                 if( (!lua_isstring( L, -1 )) || (!lua_isnumber( L, -2 )) )
658                 {
659                     msg_Warn( p_mgr, "In script %s, an entry in "
660                               "the menu table is invalid!", p_ext->psz_name );
661                     goto exit;
662                 }
663                 (*pppsz_titles)[ i_idx ] = strdup( luaL_checkstring( L, -1 ) );
664                 (*ppi_ids)[ i_idx ] = (uint16_t) ( luaL_checkinteger( L, -2 ) & 0xFFFF );
665                 i_idx++;
666                 lua_pop( L, 1 );
667             }
668         }
669         else
670         {
671             msg_Warn( p_mgr, "Function menu() in script %s "
672                       "did not return a table", p_ext->psz_name );
673             goto exit;
674         }
675     }
676     else
677     {
678         msg_Warn( p_mgr, "Script %s went completely foobar", p_ext->psz_name );
679         goto exit;
680     }
681
682     i_ret = VLC_SUCCESS;
683
684 exit:
685     UnlockExtension( p_ext );
686     if( i_ret != VLC_SUCCESS )
687     {
688         msg_Dbg( p_mgr, "Something went wrong in %s (%s:%d)",
689                  __func__, __FILE__, __LINE__ );
690     }
691     return i_ret;
692 }
693
694 /* Must be entered with the Lock on Extension */
695 static lua_State* GetLuaState( extensions_manager_t *p_mgr,
696                                extension_t *p_ext )
697 {
698     lua_State *L = NULL;
699     if( p_ext )
700         L = p_ext->p_sys->L;
701
702     if( !L )
703     {
704         L = luaL_newstate();
705         if( !L )
706         {
707             msg_Err( p_mgr, "Could not create new Lua State" );
708             return NULL;
709         }
710         vlclua_set_this( L, p_mgr );
711         vlclua_extension_set( L, p_ext );
712
713         luaL_openlibs( L );
714         luaL_register( L, "vlc", p_reg );
715         luaopen_msg( L );
716
717         if( p_ext )
718         {
719             /* Load more libraries */
720             luaopen_acl( L );
721             luaopen_config( L );
722             luaopen_dialog( L, p_ext );
723             luaopen_input( L );
724             luaopen_md5( L );
725             luaopen_msg( L );
726             luaopen_misc( L );
727             luaopen_net( L );
728             luaopen_object( L );
729             luaopen_osd( L );
730             luaopen_playlist( L );
731             luaopen_sd( L );
732             luaopen_stream( L );
733             luaopen_strings( L );
734             luaopen_variables( L );
735             luaopen_video( L );
736             luaopen_vlm( L );
737             luaopen_volume( L );
738             luaopen_xml( L );
739
740             /* Register extension specific functions */
741             lua_getglobal( L, "vlc" );
742             lua_pushcfunction( L, vlclua_extension_deactivate );
743             lua_setfield( L, -2, "deactivate" );
744
745             /* Setup the module search path */
746             if( vlclua_add_modules_path( p_mgr, L, p_ext->psz_name ) )
747             {
748                 msg_Warn( p_mgr, "Error while setting the module search path for %s", p_ext->psz_name );
749                 return NULL;
750             }
751
752             /* Load and run the script(s) */
753             if( luaL_dofile( L, p_ext->psz_name ) != 0 )
754             {
755                 msg_Warn( p_mgr, "Error loading script %s: %s", p_ext->psz_name,
756                           lua_tostring( L, lua_gettop( L ) ) );
757                 lua_pop( L, 1 );
758                 return NULL;
759             }
760
761             p_ext->p_sys->L = L;
762         }
763     }
764
765     return L;
766 }
767
768 int lua_ExecuteFunction( extensions_manager_t *p_mgr, extension_t *p_ext,
769                             const char *psz_function, ... )
770 {
771     va_list args;
772     va_start( args, psz_function );
773     int i_ret = lua_ExecuteFunctionVa( p_mgr, p_ext, psz_function, args );
774     va_end( args );
775     return i_ret;
776 }
777
778 /**
779  * Execute a function in a Lua script
780  * @param psz_function Name of global function to execute. If NULL, assume
781  *                     that the function object is already on top of the
782  *                     stack.
783  * @return < 0 in case of failure, >= 0 in case of success
784  * @note It's better to call this function from a dedicated thread
785  * (see extension_thread.c)
786  **/
787 int lua_ExecuteFunctionVa( extensions_manager_t *p_mgr, extension_t *p_ext,
788                             const char *psz_function, va_list args )
789 {
790     int i_ret = VLC_EGENERIC;
791     int i_args = 0;
792     assert( p_mgr != NULL );
793     assert( p_ext != NULL );
794
795     lua_State *L = GetLuaState( p_mgr, p_ext );
796     if( psz_function )
797         lua_getglobal( L, psz_function );
798
799     if( !lua_isfunction( L, -1 ) )
800     {
801         msg_Warn( p_mgr, "Error while running script %s, "
802                   "function %s() not found", p_ext->psz_name, psz_function );
803         goto exit;
804     }
805
806     lua_datatype_e type = LUA_END;
807     while( ( type = va_arg( args, int ) ) != LUA_END )
808     {
809         if( type == LUA_NUM )
810         {
811             lua_pushnumber( L , ( int ) va_arg( args, int ) );
812         }
813         else if( type == LUA_TEXT )
814         {
815             lua_pushstring( L , ( char * ) va_arg( args, char* ) );
816         }
817         else
818         {
819             msg_Warn( p_mgr, "Undefined argument type %d to lua function %s"
820                    "from script %s", type, psz_function, p_ext->psz_name );
821             goto exit;
822         }
823         i_args ++;
824     }
825     if( lua_pcall( L, i_args, 1, 0 ) )
826     {
827         msg_Warn( p_mgr, "Error while running script %s, "
828                   "function %s(): %s", p_ext->psz_name, psz_function,
829                   lua_tostring( L, lua_gettop( L ) ) );
830         goto exit;
831     }
832
833     i_ret = lua_DialogFlush( L );
834 exit:
835     return i_ret;
836
837 }
838
839 static inline int TriggerMenu( extension_t *p_ext, int i_id )
840 {
841     return PushCommand( p_ext, CMD_TRIGGERMENU, i_id );
842 }
843
844 int lua_ExtensionTriggerMenu( extensions_manager_t *p_mgr,
845                               extension_t *p_ext, int id )
846 {
847     int i_ret = VLC_EGENERIC;
848     lua_State *L = GetLuaState( p_mgr, p_ext );
849
850     if( !L )
851         return VLC_EGENERIC;
852
853     luaopen_dialog( L, p_ext );
854
855     lua_getglobal( L, "trigger_menu" );
856     if( !lua_isfunction( L, -1 ) )
857     {
858         msg_Warn( p_mgr, "Error while running script %s, "
859                   "function trigger_menu() not found", p_ext->psz_name );
860         return VLC_EGENERIC;
861     }
862
863     /* Pass id as unique argument to the function */
864     lua_pushinteger( L, id );
865
866     if( lua_pcall( L, 1, 1, 0 ) != 0 )
867     {
868         msg_Warn( p_mgr, "Error while running script %s, "
869                   "function trigger_menu(): %s", p_ext->psz_name,
870                   lua_tostring( L, lua_gettop( L ) ) );
871         return VLC_EGENERIC;
872     }
873
874     i_ret = lua_DialogFlush( L );
875     if( i_ret < VLC_SUCCESS )
876     {
877         msg_Dbg( p_mgr, "Something went wrong in %s (%s:%d)",
878                  __func__, __FILE__, __LINE__ );
879     }
880     return i_ret;
881 }
882
883 /** Directly trigger an extension, without activating it
884  * This is NOT multithreaded, and this code runs in the UI thread
885  * @param p_mgr
886  * @param p_ext Extension to trigger
887  * @return Value returned by the lua function "trigger"
888  **/
889 static int TriggerExtension( extensions_manager_t *p_mgr,
890                              extension_t *p_ext )
891 {
892     int i_ret = lua_ExecuteFunction( p_mgr, p_ext, "trigger", LUA_END );
893
894     /* Close lua state for trigger-only extensions */
895     if( p_ext->p_sys->L )
896         lua_close( p_ext->p_sys->L );
897     p_ext->p_sys->L = NULL;
898
899     return i_ret;
900 }
901
902 /** Set extension associated to the current script
903  * @param L current lua_State
904  * @param p_ext the extension
905  */
906 void vlclua_extension_set( lua_State *L, extension_t *p_ext )
907 {
908     lua_pushlightuserdata( L, vlclua_extension_set );
909     lua_pushlightuserdata( L, p_ext );
910     lua_rawset( L, LUA_REGISTRYINDEX );
911 }
912
913 /** Retrieve extension associated to the current script
914  * @param L current lua_State
915  * @return Extension pointer
916  **/
917 extension_t *vlclua_extension_get( lua_State *L )
918 {
919     lua_pushlightuserdata( L, vlclua_extension_set );
920     lua_rawget( L, LUA_REGISTRYINDEX );
921     extension_t *p_ext = (extension_t*) lua_topointer( L, -1 );
922     lua_pop( L, 1 );
923     return p_ext;
924 }
925
926 /** Deactivate an extension by order from the extension itself
927  * @param L lua_State
928  * @note This is an asynchronous call. A script calling vlc.deactivate() will
929  * be executed to the end before the last call to deactivate() is done.
930  **/
931 int vlclua_extension_deactivate( lua_State *L )
932 {
933     extension_t *p_ext = vlclua_extension_get( L );
934     int i_ret = Deactivate( p_ext->p_sys->p_mgr, p_ext );
935     return ( i_ret == VLC_SUCCESS ) ? 1 : 0;
936 }
937
938 /** Callback for the variable "dialog-event"
939  * @param p_this Current object owner of the extension and the dialog
940  * @param psz_var "dialog-event"
941  * @param oldval Unused
942  * @param newval Address of the dialog
943  * @param p_data Unused
944  **/
945 static int vlclua_extension_dialog_callback( vlc_object_t *p_this,
946                                              char const *psz_var,
947                                              vlc_value_t oldval,
948                                              vlc_value_t newval,
949                                              void *p_data )
950 {
951     /* psz_var == "dialog-event" */
952     ( void ) psz_var;
953     ( void ) oldval;
954     ( void ) p_data;
955
956     extension_dialog_command_t *command = newval.p_address;
957     assert( command != NULL );
958     assert( command->p_dlg != NULL);
959
960     extension_t *p_ext = command->p_dlg->p_sys;
961     assert( p_ext != NULL );
962
963     extension_widget_t *p_widget = command->p_data;
964
965     switch( command->event )
966     {
967         case EXTENSION_EVENT_CLICK:
968             assert( p_widget != NULL );
969             PushCommandUnique( p_ext, CMD_CLICK, p_widget );
970             break;
971         case EXTENSION_EVENT_CLOSE:
972             PushCommandUnique( p_ext, CMD_CLOSE );
973             break;
974         default:
975             msg_Dbg( p_this, "Received unknown UI event %d, discarded",
976                      command->event );
977             break;
978     }
979
980     return VLC_SUCCESS;
981 }
982
983 /** Callback on vlc_InputItemMetaChanged event
984  **/
985 static void inputItemMetaChanged( const vlc_event_t *p_event,
986                                   void *data )
987 {
988     assert( p_event && p_event->type == vlc_InputItemMetaChanged );
989
990     extension_t *p_ext = ( extension_t* ) data;
991     assert( p_ext != NULL );
992
993     PushCommandUnique( p_ext, CMD_UPDATE_META );
994 }
995
996 /* Lock this extension. Can fail. */
997 bool LockExtension( extension_t *p_ext )
998 {
999     if( p_ext->p_sys->b_exiting )
1000         return false;
1001
1002     vlc_mutex_lock( &p_ext->p_sys->running_lock );
1003     if( p_ext->p_sys->b_exiting )
1004     {
1005         vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1006         return false;
1007     }
1008
1009     return true;
1010 }
1011
1012 void UnlockExtension( extension_t *p_ext )
1013 {
1014     vlc_mutex_unlock( &p_ext->p_sys->running_lock );
1015 }