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