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