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