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