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