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