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