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