2 * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
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.
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.
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.
19 #include "gtkmm2ext/gui_thread.h"
21 #include "ardour/audioengine.h"
22 #include "ardour/diskstream.h"
23 #include "ardour/plugin_manager.h"
24 #include "ardour/route.h"
25 #include "ardour/session.h"
27 #include "ardour_ui.h"
28 #include "public_editor.h"
29 #include "region_selection.h"
30 #include "luainstance.h"
31 #include "luasignal.h"
32 #include "script_selector.h"
38 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
39 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
40 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
43 str2luasignal (const std::string &str) {
44 const char* type = str.c_str();
46 # include "luasignal_syms.h"
48 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
49 abort(); /*NOTREACHED*/
56 #define STATIC(name,c,p) N_(#name),
57 #define SESSION(name,c,p) N_(#name),
58 #define ENGINE(name,c,p) N_(#name),
59 const char *luasignalstr[] = {
60 # include "luasignal_syms.h"
69 ////////////////////////////////////////////////////////////////////////////////
71 #define xstr(s) stringify(s)
72 #define stringify(s) #s
74 using namespace ARDOUR;
77 LuaInstance::register_hooks (lua_State* L)
80 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
81 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
82 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
83 luabridge::getGlobalNamespace (L)
84 .beginNamespace ("LuaSignal")
85 # include "luasignal_syms.h"
91 luabridge::getGlobalNamespace (L)
92 .beginNamespace ("LuaSignal")
93 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
99 LuaInstance::register_classes (lua_State* L)
101 LuaBindings::stddef (L);
102 LuaBindings::common (L);
103 LuaBindings::session (L);
107 luabridge::getGlobalNamespace (L)
108 .beginNamespace ("ARDOUR")
109 .beginClass <RegionSelection> ("RegionSelection")
110 .addFunction ("clear_all", &RegionSelection::clear_all)
111 .addFunction ("start", &RegionSelection::start)
112 .addFunction ("end_frame", &RegionSelection::end_frame)
113 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
116 .beginClass <PublicEditor> ("Editor")
117 .addFunction ("undo", &PublicEditor::undo)
118 .addFunction ("redo", &PublicEditor::redo)
119 .addFunction ("play_selection", &PublicEditor::play_selection)
120 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
121 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
122 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
123 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
124 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
125 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
126 .addFunction ("split_regions_at", &PublicEditor::split_regions_at)
127 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
128 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
129 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
130 .addFunction ("show_measures", &PublicEditor::show_measures)
131 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
132 .addFunction ("do_import", &PublicEditor::do_import)
133 .addFunction ("do_embed", &PublicEditor::do_embed)
141 #undef DISPLAYCONTROL
143 #undef IMPORTPOSITION
144 #undef IMPORTDISPOSITION
146 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
147 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
148 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
149 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
150 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
151 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
152 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
153 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
154 luabridge::getGlobalNamespace (L)
155 .beginNamespace ("Editing")
156 # include "editing_syms.h"
163 ////////////////////////////////////////////////////////////////////////////////
165 using namespace ARDOUR;
166 using namespace ARDOUR_UI_UTILS;
171 static void _lua_print (std::string s) {
172 std::cout << "LuaInstance: " << s << "\n";
176 LuaInstance* LuaInstance::_instance = 0;
179 LuaInstance::instance ()
182 _instance = new LuaInstance;
188 LuaInstance::LuaInstance ()
191 lua.Print.connect (&_lua_print);
195 LuaScriptParamList args;
198 LuaInstance::~LuaInstance ()
200 delete _lua_call_action;
201 delete _lua_add_action;
202 delete _lua_del_action;
203 delete _lua_get_action;
215 "function ScriptManager ()"
216 " local self = { scripts = {}, instances = {} }"
218 " local remove = function (id)"
219 " self.scripts[id] = nil"
220 " self.instances[id] = nil"
223 " local addinternal = function (i, n, s, f, a)"
224 " assert(type(i) == 'number', 'id must be numeric')"
225 " assert(type(n) == 'string', 'Name must be string')"
226 " assert(type(s) == 'string', 'Script must be string')"
227 " assert(type(f) == 'function', 'Factory is a not a function')"
228 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
229 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
230 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
231 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
234 " local call = function (id)"
235 " if type(self.instances[id]) == 'function' then"
236 " local status, err = pcall (self.instances[id])"
237 " if not status then"
238 " print ('action \"'.. id .. '\": ', err)" // error out
245 " local add = function (i, n, s, b, a)"
246 " assert(type(b) == 'string', 'ByteCode must be string')"
247 " load (b)()" // assigns f
248 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
249 " addinternal (i, n, s, load(f), a)"
252 " local get = function (id)"
253 " if type(self.scripts[id]) == 'table' then"
254 " return { ['name'] = self.scripts[id]['n'],"
255 " ['script'] = self.scripts[id]['s'],"
256 " ['args'] = self.scripts[id]['a'] }"
261 " local function basic_serialize (o)"
262 " if type(o) == \"number\" then"
263 " return tostring(o)"
265 " return string.format(\"%q\", o)"
269 " local function serialize (name, value)"
270 " local rv = name .. ' = '"
272 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
273 " return rv .. basic_serialize(value) .. ' '"
274 " elseif type(value) == \"table\" then"
276 " for k,v in pairs(value) do"
277 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
278 " rv = rv .. serialize(fieldname, v) .. ' '"
279 " collectgarbage()" // string concatenation allocates a new string
282 " elseif type(value) == \"function\" then"
283 " return rv .. string.format(\"%q\", string.dump(value, true))"
285 " error('cannot save a ' .. type(value))"
290 " local save = function ()"
291 " return (serialize('scripts', self.scripts))"
294 " local clear = function ()"
296 " self.instances = {}"
300 " local restore = function (state)"
303 " for i, s in pairs (scripts) do"
304 " addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
309 " return { call = call, add = add, remove = remove, get = get,"
310 " restore = restore, save = save, clear = clear}"
313 " manager = ScriptManager ()"
314 " ScriptManager = nil"
317 lua_State* L = lua.getState();
320 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
321 lua.do_command ("manager = nil"); // hide it.
322 lua.do_command ("collectgarbage()");
324 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
325 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
326 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
327 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
328 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
329 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
330 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
332 } catch (luabridge::LuaException const& e) {
333 fatal << string_compose (_("programming error: %1"),
334 X_("Failed to setup Lua action interpreter"))
336 abort(); /*NOTREACHED*/
339 register_classes (L);
341 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
342 lua_setglobal (L, "Editor");
345 void LuaInstance::set_session (Session* s)
347 SessionHandlePtr::set_session (s);
352 lua_State* L = lua.getState();
353 LuaBindings::set_session (L, _session);
355 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
356 i->second->set_session (s);
361 LuaInstance::session_going_away ()
363 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
365 for (int i = 0; i < 9; ++i) {
366 ActionChanged (i, ""); /* EMIT SIGNAL */
368 SessionHandlePtr::session_going_away ();
371 lua_State* L = lua.getState();
372 LuaBindings::set_session (L, _session);
373 lua.do_command ("collectgarbage();");
377 LuaInstance::set_state (const XMLNode& node)
379 LocaleGuard lg (X_("C"));
382 if ((child = find_named_node (node, "ActionScript"))) {
383 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
384 if (!(*n)->is_content ()) { continue; }
386 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
388 (*_lua_load)(std::string ((const char*)buf, size));
389 } catch (luabridge::LuaException const& e) {
390 cerr << "LuaException:" << e.what () << endl;
392 for (int i = 0; i < 9; ++i) {
394 if (lua_action_name (i, name)) {
395 ActionChanged (i, name); /* EMIT SIGNAL */
402 if ((child = find_named_node (node, "ActionHooks"))) {
403 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
405 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
406 _callbacks.insert (std::make_pair(p->id(), p));
407 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
408 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
409 } catch (luabridge::LuaException const& e) {
410 cerr << "LuaException:" << e.what () << endl;
419 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
422 std::vector<std::string> reg;
425 case LuaScriptInfo::EditorAction:
426 reg = lua_action_names ();
427 title = "Add Lua Action";
429 case LuaScriptInfo::EditorHook:
430 reg = lua_slot_names ();
431 title = "Add Lua Callback Hook";
437 LuaScriptInfoPtr spi;
438 ScriptSelector ss (title, type);
440 case Gtk::RESPONSE_ACCEPT:
447 std::string script = "";
450 script = Glib::file_get_contents (spi->path);
451 } catch (Glib::FileError e) {
452 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
453 Gtk::MessageDialog am (msg);
458 LuaScriptParamList lsp = LuaScripting::script_params (spi, "action_params");
460 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
461 switch (spd.run ()) {
462 case Gtk::RESPONSE_ACCEPT:
469 case LuaScriptInfo::EditorAction:
470 return set_lua_action (id, spd.name(), script, lsp);
472 case LuaScriptInfo::EditorHook:
473 return register_lua_slot (spd.name(), script, lsp);
482 LuaInstance::get_action_state ()
484 LocaleGuard lg (X_("C"));
487 luabridge::LuaRef savedstate ((*_lua_save)());
488 saved = savedstate.cast<std::string>();
490 lua.collect_garbage ();
492 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
493 std::string b64s (b64);
496 XMLNode* script_node = new XMLNode (X_("ActionScript"));
497 script_node->add_property (X_("lua"), LUA_VERSION);
498 script_node->add_content (b64s);
504 LuaInstance::get_hook_state ()
506 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
507 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
508 script_node->add_child_nocopy (i->second->get_state ());
514 LuaInstance::call_action (const int id)
517 (*_lua_call_action)(id + 1);
518 } catch (luabridge::LuaException const& e) {
519 cerr << "LuaException:" << e.what () << endl;
524 LuaInstance::set_lua_action (
526 const std::string& name,
527 const std::string& script,
528 const LuaScriptParamList& args)
531 lua_State* L = lua.getState();
532 // get bytcode of factory-function in a sandbox
533 // (don't allow scripts to interfere)
534 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
535 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
536 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
537 if ((*i)->optional && !(*i)->is_set) { continue; }
538 tbl_arg[(*i)->name] = (*i)->value;
540 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
541 ActionChanged (id, name); /* EMIT SIGNAL */
542 } catch (luabridge::LuaException const& e) {
543 cerr << "LuaException:" << e.what () << endl;
550 LuaInstance::remove_lua_action (const int id)
553 (*_lua_del_action)(id + 1);
554 } catch (luabridge::LuaException const& e) {
555 cerr << "LuaException:" << e.what () << endl;
558 ActionChanged (id, ""); /* EMIT SIGNAL */
563 LuaInstance::lua_action_name (const int id, std::string& rv)
566 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
570 if (ref["name"].isString()) {
571 rv = ref["name"].cast<std::string>();
575 } catch (luabridge::LuaException const& e) {
576 cerr << "LuaException:" << e.what () << endl;
582 std::vector<std::string>
583 LuaInstance::lua_action_names ()
585 std::vector<std::string> rv;
586 for (int i = 0; i < 9; ++i) {
588 if (lua_action_name (i, name)) {
596 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
599 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
603 if (!ref["name"].isString()) {
606 if (!ref["script"].isString()) {
609 if (!ref["args"].isTable()) {
612 name = ref["name"].cast<std::string>();
613 script = ref["script"].cast<std::string>();
616 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
620 args = LuaScripting::script_params (lsi, "action_params");
621 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
622 if (!i.key ().isString ()) { assert(0); continue; }
623 std::string name = i.key ().cast<std::string> ();
624 std::string value = i.value ().cast<std::string> ();
625 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
626 if ((*ii)->name == name) {
627 (*ii)->value = value;
633 } catch (luabridge::LuaException const& e) {
634 cerr << "LuaException:" << e.what () << endl;
641 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
643 /* parse script, get ActionHook(s) from script */
647 l.Print.connect (&_lua_print);
648 lua_State* L = l.getState();
650 l.do_command ("function ardour () end");
651 l.do_command (script);
652 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
653 if (signals.isFunction()) {
656 } catch (luabridge::LuaException const& e) {
657 cerr << "LuaException:" << e.what () << endl;
661 cerr << "Script registered no hooks." << endl;
665 /* register script w/args, get entry-point / ID */
668 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
669 _callbacks.insert (std::make_pair(p->id(), p));
670 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
671 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
673 } catch (luabridge::LuaException const& e) {
674 cerr << "LuaException:" << e.what () << endl;
680 LuaInstance::unregister_lua_slot (const PBD::ID& id)
682 LuaCallbackMap::const_iterator i = _callbacks.find (id);
683 if (i != _callbacks.end()) {
684 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
685 _callbacks.erase (i);
692 LuaInstance::lua_slots () const
694 std::vector<PBD::ID> rv;
695 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
696 rv.push_back (i->first);
702 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
704 LuaCallbackMap::const_iterator i = _callbacks.find (id);
705 if (i != _callbacks.end()) {
706 name = i->second->name();
712 std::vector<std::string>
713 LuaInstance::lua_slot_names () const
715 std::vector<std::string> rv;
716 std::vector<PBD::ID> ids = lua_slots();
717 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
719 if (lua_slot_name (*i, name)) {
727 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
729 LuaCallbackMap::const_iterator i = _callbacks.find (id);
730 if (i == _callbacks.end()) {
731 return false; // error
733 return i->second->lua_slot (name, script, ah, args);
736 ///////////////////////////////////////////////////////////////////////////////
738 LuaCallback::LuaCallback (Session *s,
739 const std::string& name,
740 const std::string& script,
741 const ActionHook& ah,
742 const ARDOUR::LuaScriptParamList& args)
743 : SessionHandlePtr (s)
748 // TODO: allow to reference object (e.g region)
751 lua_State* L = lua.getState();
752 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
753 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
754 if ((*i)->optional && !(*i)->is_set) { continue; }
755 tbl_arg[(*i)->name] = (*i)->value;
759 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
760 (*_lua_add)(name, script, bytecode, tbl_arg);
761 } catch (luabridge::LuaException const& e) {
762 cerr << "LuaException:" << e.what () << endl;
763 throw failed_constructor ();
770 LuaCallback::LuaCallback (Session *s, XMLNode & node)
771 : SessionHandlePtr (s)
773 XMLNode* child = NULL;
774 if (node.name() != X_("LuaCallback")
775 || !node.property ("signals")
776 || !node.property ("id")
777 || !node.property ("name")) {
778 throw failed_constructor ();
781 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
782 if (!(*n)->is_content ()) { continue; }
787 throw failed_constructor ();
792 _id = PBD::ID (node.property ("id")->value ());
793 _name = node.property ("name")->value ();
794 _signals = ActionHook (node.property ("signals")->value ());
797 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
799 (*_lua_load)(std::string ((const char*)buf, size));
800 } catch (luabridge::LuaException const& e) {
801 cerr << "LuaException:" << e.what () << endl;
808 LuaCallback::~LuaCallback ()
818 LuaCallback::get_state (void)
822 luabridge::LuaRef savedstate ((*_lua_save)());
823 saved = savedstate.cast<std::string>();
825 lua.collect_garbage ();
827 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
828 std::string b64s (b64);
831 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
832 script_node->add_property (X_("lua"), LUA_VERSION);
833 script_node->add_property (X_("id"), _id.to_s ());
834 script_node->add_property (X_("name"), _name);
835 script_node->add_property (X_("signals"), _signals.to_string ());
836 script_node->add_content (b64s);
841 LuaCallback::init (void)
843 lua.Print.connect (&_lua_print);
846 "function ScriptManager ()"
847 " local self = { script = {}, instance = {} }"
849 " local addinternal = function (n, s, f, a)"
850 " assert(type(n) == 'string', 'Name must be string')"
851 " assert(type(s) == 'string', 'Script must be string')"
852 " assert(type(f) == 'function', 'Factory is a not a function')"
853 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
854 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
855 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
856 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
859 " local call = function (...)"
860 " if type(self.instance) == 'function' then"
861 " local status, err = pcall (self.instance, ...)"
862 " if not status then"
863 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
865 " self.instance = nil"
873 " local add = function (n, s, b, a)"
874 " assert(type(b) == 'string', 'ByteCode must be string')"
875 " load (b)()" // assigns f
876 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
877 " addinternal (n, s, load(f), a)"
880 " local get = function ()"
881 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
882 " return { ['name'] = self.script['n'],"
883 " ['script'] = self.script['s'],"
884 " ['args'] = self.script['a'] }"
891 " local function basic_serialize (o)"
892 " if type(o) == \"number\" then"
893 " return tostring(o)"
895 " return string.format(\"%q\", o)"
899 " local function serialize (name, value)"
900 " local rv = name .. ' = '"
902 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
903 " return rv .. basic_serialize(value) .. ' '"
904 " elseif type(value) == \"table\" then"
906 " for k,v in pairs(value) do"
907 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
908 " rv = rv .. serialize(fieldname, v) .. ' '"
909 " collectgarbage()" // string concatenation allocates a new string
912 " elseif type(value) == \"function\" then"
913 " return rv .. string.format(\"%q\", string.dump(value, true))"
915 " error('cannot save a ' .. type(value))"
921 " local save = function ()"
922 " return (serialize('s', self.script))"
925 " local restore = function (state)"
928 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
931 " return { call = call, add = add, get = get,"
932 " restore = restore, save = save}"
935 " manager = ScriptManager ()"
936 " ScriptManager = nil"
939 lua_State* L = lua.getState();
942 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
943 lua.do_command ("manager = nil"); // hide it.
944 lua.do_command ("collectgarbage()");
946 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
947 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
948 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
949 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
950 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
952 } catch (luabridge::LuaException const& e) {
953 fatal << string_compose (_("programming error: %1"),
954 X_("Failed to setup Lua callback interpreter"))
956 abort(); /*NOTREACHED*/
959 LuaInstance::register_classes (L);
961 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
962 lua_setglobal (L, "Editor");
966 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
968 // TODO consolidate w/ LuaInstance::lua_action()
970 luabridge::LuaRef ref = (*_lua_get)();
974 if (!ref["name"].isString()) {
977 if (!ref["script"].isString()) {
980 if (!ref["args"].isTable()) {
985 name = ref["name"].cast<std::string> ();
986 script = ref["script"].cast<std::string> ();
989 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
993 args = LuaScripting::script_params (lsi, "action_params");
994 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
995 if (!i.key ().isString ()) { assert(0); continue; }
996 std::string name = i.key ().cast<std::string> ();
997 std::string value = i.value ().cast<std::string> ();
998 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
999 if ((*ii)->name == name) {
1000 (*ii)->value = value;
1006 } catch (luabridge::LuaException const& e) {
1007 cerr << "LuaException:" << e.what () << endl;
1014 LuaCallback::set_session (ARDOUR::Session *s)
1016 SessionHandlePtr::set_session (s);
1019 lua_State* L = lua.getState();
1020 LuaBindings::set_session (L, _session);
1027 LuaCallback::session_going_away ()
1029 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1030 lua.do_command ("collectgarbage();");
1032 SessionHandlePtr::session_going_away ();
1035 drop_callback (); /* EMIT SIGNAL */
1039 LuaCallback::reconnect ()
1041 _connections.drop_connections ();
1042 if ((*_lua_get) ().isNil ()) {
1043 drop_callback (); /* EMIT SIGNAL */
1047 // TODO pass object which emits the signal (e.g region)
1049 // save/load bound objects will be tricky.
1050 // Best idea so far is to save/lookup the PBD::ID
1051 // (either use boost::any indirection or templates for bindable
1052 // object types or a switch statement..)
1054 // _session->route_by_id ()
1055 // _session->track_by_diskstream_id ()
1056 // _session->source_by_id ()
1057 // _session->controllable_by_id ()
1058 // _session->processor_by_id ()
1059 // RegionFactory::region_by_id ()
1061 // TODO loop over objects (if any)
1063 reconnect_object ((void*)0);
1066 template <class T> void
1067 LuaCallback::reconnect_object (T obj)
1069 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1071 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1072 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1073 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1075 # include "luasignal_syms.h"
1077 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1078 abort(); /*NOTREACHED*/
1087 template <typename T, typename S> void
1088 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1090 _connections, invalidator (*this),
1091 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1095 template <typename T, typename C1> void
1096 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1098 _connections, invalidator (*this),
1099 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1103 template <typename T, typename C1, typename C2> void
1104 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1106 _connections, invalidator (*this),
1107 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1111 template <typename T> void
1112 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1113 if (!(*_lua_call)((int)ls, ref)) { drop_callback (); /* EMIT SIGNAL */}
1116 template <typename T, typename C1> void
1117 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1118 if (!(*_lua_call)((int)ls, ref, a1)) { drop_callback (); /* EMIT SIGNAL */}
1121 template <typename T, typename C1, typename C2> void
1122 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1123 if (!(*_lua_call)((int)ls, ref, a1, a2)) { drop_callback (); /* EMIT SIGNAL */}