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