remove Track::hidden(); replace with Stripable::is_private_route()
[ardour.git] / libs / ardour / luascripting.cc
1 /*
2  * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19 #include <cstring>
20 #include <glibmm.h>
21
22 #include "pbd/error.h"
23 #include "pbd/file_utils.h"
24 #include "pbd/compose.h"
25
26 #include "ardour/directory_names.h"
27 #include "ardour/filesystem_paths.h"
28 #include "ardour/luascripting.h"
29 #include "ardour/lua_script_params.h"
30 #include "ardour/search_paths.h"
31
32 #include "lua/luastate.h"
33 #include "LuaBridge/LuaBridge.h"
34
35 #include "pbd/i18n.h"
36 #include "sha1.c"
37
38 using namespace ARDOUR;
39 using namespace PBD;
40 using namespace std;
41
42 LuaScripting* LuaScripting::_instance = 0;
43
44 LuaScripting&
45 LuaScripting::instance ()
46 {
47         if (!_instance) {
48                 _instance = new LuaScripting;
49         }
50         return *_instance;
51 }
52
53 LuaScripting::LuaScripting ()
54         : _sl_dsp (0)
55         , _sl_session (0)
56         , _sl_hook (0)
57         , _sl_action (0)
58         , _sl_snippet (0)
59         , _sl_setup (0)
60         , _sl_tracks (0)
61 {
62         ;
63 }
64
65 LuaScripting::~LuaScripting ()
66 {
67         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
68                 // don't bother, just exit quickly.
69                 delete _sl_dsp;
70                 delete _sl_session;
71                 delete _sl_hook;
72                 delete _sl_action;
73                 delete _sl_snippet;
74                 delete _sl_setup;
75                 delete _sl_tracks;
76         }
77 }
78
79
80 void
81 LuaScripting::refresh (bool run_scan)
82 {
83         Glib::Threads::Mutex::Lock lm (_lock);
84
85         delete _sl_dsp;
86         delete _sl_session;
87         delete _sl_hook;
88         delete _sl_action;
89         delete _sl_snippet;
90         delete _sl_setup;
91         delete _sl_tracks;
92
93         _sl_dsp = 0;
94         _sl_session = 0;
95         _sl_hook = 0;
96         _sl_action = 0;
97         _sl_snippet = 0;
98         _sl_setup = 0;
99         _sl_tracks = 0;
100
101         if (run_scan) {
102                 lm.release ();
103                 scan ();
104         }
105 }
106
107 struct ScriptSorter {
108         bool operator () (LuaScriptInfoPtr a, LuaScriptInfoPtr b) {
109                 return a->name < b->name;
110         }
111 };
112
113 LuaScriptInfoPtr
114 LuaScripting::script_info (const std::string &script) {
115         return scan_script ("", script);
116 }
117
118 void
119 LuaScripting::scan ()
120 {
121         Glib::Threads::Mutex::Lock lm (_lock);
122
123 #define CLEAR_OR_NEW(LIST) \
124         if (LIST) { LIST->clear (); } else { LIST = new LuaScriptList (); }
125
126         CLEAR_OR_NEW (_sl_dsp)
127         CLEAR_OR_NEW (_sl_session)
128         CLEAR_OR_NEW (_sl_hook)
129         CLEAR_OR_NEW (_sl_action)
130         CLEAR_OR_NEW (_sl_snippet)
131         CLEAR_OR_NEW (_sl_setup)
132         CLEAR_OR_NEW (_sl_tracks)
133
134 #undef CLEAR_OR_NEW
135
136         vector<string> luascripts;
137         find_files_matching_pattern (luascripts, lua_search_path (), "*.lua");
138
139         for (vector<string>::iterator i = luascripts.begin(); i != luascripts.end (); ++i) {
140                 LuaScriptInfoPtr lsi = scan_script (*i);
141                 if (!lsi) {
142                         PBD::info << string_compose (_("Script '%1' has no valid descriptor."), *i) << endmsg;
143                         continue;
144                 }
145                 switch (lsi->type) {
146                         case LuaScriptInfo::DSP:
147                                 _sl_dsp->push_back(lsi);
148                                 break;
149                         case LuaScriptInfo::Session:
150                                 _sl_session->push_back(lsi);
151                                 break;
152                         case LuaScriptInfo::EditorHook:
153                                 _sl_hook->push_back(lsi);
154                                 break;
155                         case LuaScriptInfo::EditorAction:
156                                 _sl_action->push_back(lsi);
157                                 break;
158                         case LuaScriptInfo::Snippet:
159                                 _sl_snippet->push_back(lsi);
160                                 break;
161                         case LuaScriptInfo::SessionInit:
162                                 _sl_setup->push_back(lsi);
163                                 break;
164                         default:
165                                 break;
166                 }
167         }
168
169         std::sort (_sl_dsp->begin(), _sl_dsp->end(), ScriptSorter());
170         std::sort (_sl_session->begin(), _sl_session->end(), ScriptSorter());
171         std::sort (_sl_hook->begin(), _sl_hook->end(), ScriptSorter());
172         std::sort (_sl_action->begin(), _sl_action->end(), ScriptSorter());
173         std::sort (_sl_snippet->begin(), _sl_snippet->end(), ScriptSorter());
174         std::sort (_sl_setup->begin(), _sl_setup->end(), ScriptSorter());
175         std::sort (_sl_tracks->begin(), _sl_tracks->end(), ScriptSorter());
176
177         scripts_changed (); /* EMIT SIGNAL */
178 }
179
180 void
181 LuaScripting::lua_print (std::string s) {
182         PBD::info << "Lua: " << s << "\n";
183 }
184
185 LuaScriptInfoPtr
186 LuaScripting::scan_script (const std::string &fn, const std::string &sc)
187 {
188         LuaState lua;
189         if (!(fn.empty() ^ sc.empty())){
190                 // give either file OR script
191                 assert (0);
192                 return LuaScriptInfoPtr();
193         }
194
195         lua_State* L = lua.getState();
196         lua.Print.connect (&LuaScripting::lua_print);
197         lua.sandbox (true);
198
199         lua.do_command (
200                         "ardourluainfo = {}"
201                         "function ardour (entry)"
202                         "  ardourluainfo['type'] = assert(entry['type'])"
203                         "  ardourluainfo['name'] = assert(entry['name'])"
204                         "  ardourluainfo['category'] = entry['category'] or 'Unknown'"
205                         "  ardourluainfo['author'] = entry['author'] or 'Unknown'"
206                         "  ardourluainfo['license'] = entry['license'] or ''"
207                         "  ardourluainfo['description'] = entry['description'] or ''"
208                         " end"
209                         );
210
211         try {
212                 int err;
213                 if (fn.empty()) {
214                         err = lua.do_command (sc);
215                 } else {
216                         err = lua.do_file (fn);
217                 }
218                 if (err) {
219 #ifndef NDEBUG
220                 cerr << "failed to load lua script\n";
221 #endif
222                         return LuaScriptInfoPtr();
223                 }
224         } catch (...) { // luabridge::LuaException
225 #ifndef NDEBUG
226                 cerr << "failed to parse lua script\n";
227 #endif
228                 return LuaScriptInfoPtr();
229         }
230         luabridge::LuaRef nfo = luabridge::getGlobal (L, "ardourluainfo");
231         if (nfo.type() != LUA_TTABLE) {
232 #ifndef NDEBUG
233                 cerr << "failed to get ardour{} table from script\n";
234 #endif
235                 return LuaScriptInfoPtr();
236         }
237
238         if (nfo["name"].type() != LUA_TSTRING || nfo["type"].type() != LUA_TSTRING) {
239 #ifndef NDEBUG
240                 cerr << "script-type or script-name is not a string\n";
241 #endif
242                 return LuaScriptInfoPtr();
243         }
244
245         std::string name = nfo["name"].cast<std::string>();
246         LuaScriptInfo::ScriptType type = LuaScriptInfo::str2type (nfo["type"].cast<std::string>());
247
248         if (name.empty() || type == LuaScriptInfo::Invalid) {
249 #ifndef NDEBUG
250                 cerr << "invalid script-type or missing script name\n";
251 #endif
252                 return LuaScriptInfoPtr();
253         }
254
255         char hash[41];
256         Sha1Digest s;
257         sha1_init (&s);
258
259         if (fn.empty()) {
260                 sha1_write (&s, (const uint8_t *) sc.c_str(), sc.size ());
261         } else {
262                 try {
263                         std::string script = Glib::file_get_contents (fn);
264                         sha1_write (&s, (const uint8_t *) script.c_str(), script.size ());
265                 } catch (Glib::FileError err) {
266                         return LuaScriptInfoPtr();
267                 }
268         }
269         sha1_result_hash (&s, hash);
270
271
272         LuaScriptInfoPtr lsi (new LuaScriptInfo (type, name, fn, hash));
273
274         for (luabridge::Iterator i(nfo); !i.isNil (); ++i) {
275                 if (!i.key().isString() || !i.value().isString()) {
276                         return LuaScriptInfoPtr();
277                 }
278                 std::string key = i.key().tostring();
279                 std::string val = i.value().tostring();
280
281                 if (key == "author") { lsi->author = val; }
282                 if (key == "license") { lsi->license = val; }
283                 if (key == "description") { lsi->description = val; }
284                 if (key == "category") { lsi->category = val; }
285         }
286
287
288         if (type == LuaScriptInfo::EditorAction) {
289
290                 luabridge::LuaRef lua_rs = luabridge::getGlobal (L, "route_setup");
291                 if (lua_rs.isFunction ()) {
292                         lsi->subtype |= LuaScriptInfo::RouteSetup;
293                 }
294
295                 luabridge::LuaRef lua_ss = luabridge::getGlobal (L, "session_setup");
296                 if (lua_ss.isFunction ()) {
297                         try {
298                                 if (lua_ss () == true) {
299                                         lsi->subtype |= LuaScriptInfo::SessionSetup;
300                                 }
301                         } catch (...) { }
302                 }
303
304         }
305
306         return lsi;
307 }
308
309 LuaScriptList &
310 LuaScripting::scripts (LuaScriptInfo::ScriptType type) {
311
312         if (!_sl_dsp || !_sl_session || !_sl_hook || !_sl_action || !_sl_snippet || ! _sl_setup || ! _sl_tracks) {
313                 scan ();
314         }
315
316         switch (type) {
317                 case LuaScriptInfo::DSP:
318                         return *_sl_dsp;
319                         break;
320                 case LuaScriptInfo::Session:
321                         return *_sl_session;
322                         break;
323                 case LuaScriptInfo::EditorHook:
324                         return *_sl_hook;
325                         break;
326                 case LuaScriptInfo::EditorAction:
327                         return *_sl_action;
328                         break;
329                 case LuaScriptInfo::Snippet:
330                         return *_sl_snippet;
331                         break;
332                 case LuaScriptInfo::SessionInit:
333                         return *_sl_setup;
334                         break;
335                 default:
336                         break;
337         }
338         return _empty_script_info; // make some compilers happy
339 }
340
341
342 std::string
343 LuaScriptInfo::type2str (const ScriptType t) {
344         switch (t) {
345                 case LuaScriptInfo::DSP: return "DSP";
346                 case LuaScriptInfo::Session: return "Session";
347                 case LuaScriptInfo::EditorHook: return "EditorHook";
348                 case LuaScriptInfo::EditorAction: return "EditorAction";
349                 case LuaScriptInfo::Snippet: return "Snippet";
350                 case LuaScriptInfo::SessionInit: return "SessionInit";
351                 default: return "Invalid";
352         }
353 }
354
355 LuaScriptInfo::ScriptType
356 LuaScriptInfo::str2type (const std::string& str) {
357         const char* type = str.c_str();
358         if (!strcasecmp (type, "DSP")) {return LuaScriptInfo::DSP;}
359         if (!strcasecmp (type, "Session")) {return LuaScriptInfo::Session;}
360         if (!strcasecmp (type, "EditorHook")) {return LuaScriptInfo::EditorHook;}
361         if (!strcasecmp (type, "EditorAction")) {return LuaScriptInfo::EditorAction;}
362         if (!strcasecmp (type, "Snippet")) {return LuaScriptInfo::Snippet;}
363         if (!strcasecmp (type, "SessionInit")) {return LuaScriptInfo::SessionInit;}
364         return LuaScriptInfo::Invalid;
365 }
366
367 LuaScriptParamList
368 LuaScriptParams::script_params (const LuaScriptInfoPtr& lsi, const std::string &pname)
369 {
370         assert (lsi);
371         return LuaScriptParams::script_params (lsi->path, pname);
372 }
373
374 LuaScriptParamList
375 LuaScriptParams::script_params (const std::string& s, const std::string &pname, bool file)
376 {
377         LuaScriptParamList rv;
378
379         LuaState lua;
380         lua_State* L = lua.getState();
381         lua.sandbox (true);
382         lua.do_command ("function ardour () end");
383
384         try {
385                 if (file) {
386                         lua.do_file (s);
387                 } else {
388                         lua.do_command (s);
389                 }
390         } catch (...) {
391                 return rv;
392         }
393
394         luabridge::LuaRef lua_params = luabridge::getGlobal (L, pname.c_str());
395         if (lua_params.isFunction ()) {
396                 luabridge::LuaRef params = lua_params ();
397                 if (params.isTable ()) {
398                         for (luabridge::Iterator i (params); !i.isNil (); ++i) {
399                                 if (!i.key ().isString ())            { continue; }
400                                 if (!i.value ().isTable ())           { continue; }
401                                 if (!i.value ()["title"].isString ()) { continue; }
402
403                                 std::string name = i.key ().cast<std::string> ();
404                                 std::string title = i.value ()["title"].cast<std::string> ();
405                                 std::string dflt;
406                                 bool optional = false;
407
408                                 if (i.value ()["default"].isString ()) {
409                                         dflt = i.value ()["default"].cast<std::string> ();
410                                 }
411                                 if (i.value ()["optional"].isBoolean ()) {
412                                         optional = i.value ()["optional"].cast<bool> ();
413                                 }
414                                 LuaScriptParamPtr lsspp (new LuaScriptParam(name, title, dflt, optional));
415                                 rv.push_back (lsspp);
416                         }
417                 }
418         }
419         return rv;
420 }
421
422 void
423 LuaScriptParams::params_to_ref (luabridge::LuaRef *tbl_args, const LuaScriptParamList& args)
424 {
425         assert (tbl_args &&  (*tbl_args).isTable ());
426         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
427                 if ((*i)->optional && !(*i)->is_set) { continue; }
428                 (*tbl_args)[(*i)->name] = (*i)->value;
429         }
430 }
431
432 void
433 LuaScriptParams::ref_to_params (LuaScriptParamList& args, luabridge::LuaRef *tbl_ref)
434 {
435         assert (tbl_ref &&  (*tbl_ref).isTable ());
436         for (luabridge::Iterator i (*tbl_ref); !i.isNil (); ++i) {
437                 if (!i.key ().isString ()) { assert(0); continue; }
438                 std::string name = i.key ().cast<std::string> ();
439                 std::string value = i.value ().cast<std::string> ();
440                 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
441                         if ((*ii)->name == name) {
442                                 (*ii)->value = value;
443                                 break;
444                         }
445                 }
446         }
447 }
448
449 bool
450 LuaScripting::try_compile (const std::string& script, const LuaScriptParamList& args)
451 {
452         const std::string& bytecode = get_factory_bytecode (script);
453         if (bytecode.empty()) {
454                 return false;
455         }
456         LuaState l;
457         l.Print.connect (&LuaScripting::lua_print);
458         l.sandbox (true);
459         lua_State* L = l.getState();
460
461         l.do_command (""
462                         " function checkfactory (b, a)"
463                         "  assert(type(b) == 'string', 'ByteCode must be string')"
464                         "  load(b)()" // assigns f
465                         "  assert(type(f) == 'string', 'Assigned ByteCode must be string')"
466                         "  local factory = load(f)"
467                         "  assert(type(factory) == 'function', 'Factory is a not a function')"
468                         "  local env = _ENV; env.f = nil env.os = nil env.io = nil"
469                         "  load (string.dump(factory, true), nil, nil, env)(a)"
470                         " end"
471                         );
472
473         try {
474                 luabridge::LuaRef lua_test = luabridge::getGlobal (L, "checkfactory");
475                 l.do_command ("checkfactory = nil"); // hide it.
476                 l.do_command ("collectgarbage()");
477
478                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
479                 LuaScriptParams::params_to_ref (&tbl_arg, args);
480                 lua_test (bytecode, tbl_arg);
481                 return true; // OK
482         } catch (luabridge::LuaException const& e) {
483 #ifndef NDEBUG
484                 cerr << e.what() << "\n";
485 #endif
486                 lua_print (e.what());
487         } catch (...) { }
488
489         return false;
490 }
491
492 std::string
493 LuaScripting::get_factory_bytecode (const std::string& script, const std::string& ffn, const std::string& fp)
494 {
495         LuaState l;
496         l.Print.connect (&LuaScripting::lua_print);
497         l.sandbox (true);
498         lua_State* L = l.getState();
499
500         l.do_command (
501                         " function ardour () end"
502                         ""
503                         " function dump_function (f)"
504                         "  assert(type(f) == 'function', 'Factory is a not a function')"
505                         "  return string.format(\"" + fp + " = %q\", string.dump(f, true))"
506                         " end"
507                         );
508
509         try {
510                 luabridge::LuaRef lua_dump = luabridge::getGlobal (L, "dump_function");
511                 l.do_command ("dump_function = nil"); // hide it
512                 l.do_command (script); // register "factory"
513                 luabridge::LuaRef lua_factory = luabridge::getGlobal (L, ffn.c_str());
514
515                 if (lua_factory.isFunction()) {
516                         return (lua_dump(lua_factory)).cast<std::string> ();
517                 }
518         } catch (...) { }
519         return "";
520 }
521
522 std::string
523 LuaScripting::user_script_dir ()
524 {
525         std::string dir = Glib::build_filename (user_config_directory(), lua_dir_name);
526         g_mkdir_with_parents (dir.c_str(), 0744);
527         return dir;
528 }