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 ("snap_type", &PublicEditor::snap_type)
118 .addFunction ("snap_mode", &PublicEditor::snap_mode)
119 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
120 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
122 .addFunction ("undo", &PublicEditor::undo)
123 .addFunction ("redo", &PublicEditor::redo)
125 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
126 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
128 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
130 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
131 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
132 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
133 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
135 #if 0 // Selection is not yet exposed
136 .addFunction ("get_selection", &PublicEditor::get_selection)
137 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
138 .addFunction ("track_mixer_selection", &PublicEditor::track_mixer_selection)
139 .addFunction ("extend_selection_to_track", &PublicEditor::extend_selection_to_track)
142 .addFunction ("play_selection", &PublicEditor::play_selection)
143 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
144 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
145 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
147 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
148 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
150 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
151 .addFunction ("show_measures", &PublicEditor::show_measures)
152 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
154 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
156 .addFunction ("do_import", &PublicEditor::do_import)
157 .addFunction ("do_embed", &PublicEditor::do_embed)
159 .addFunction ("export_audio", &PublicEditor::export_audio)
160 .addFunction ("stem_export", &PublicEditor::stem_export)
161 .addFunction ("export_selection", &PublicEditor::export_selection)
162 .addFunction ("export_range", &PublicEditor::export_range)
164 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
165 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
166 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
167 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
169 #if 0 // These need TimeAxisView* which isn't exposed, yet
170 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
171 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
172 .addFunction ("new_playlists", &PublicEditor::new_playlists)
173 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
174 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
177 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
178 .addFunction ("deselect_all", &PublicEditor::deselect_all)
180 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
181 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
182 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
184 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
185 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
186 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
187 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
189 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
190 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
191 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
192 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
193 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
194 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
195 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
197 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
198 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
199 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
200 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
202 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
203 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
204 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
206 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
208 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
209 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
210 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
212 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
213 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
215 .addFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
216 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
217 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
218 .addFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
220 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
221 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
222 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
223 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
226 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
227 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
229 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
230 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
231 .addFunction ("get_track_views", &PublicEditor::get_track_views)
232 .addFunction ("drags", &PublicEditor::drags)
235 .addFunction ("center_screen", &PublicEditor::center_screen)
237 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
238 .addFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
240 .addFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
241 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
242 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
244 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
245 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
246 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
247 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
248 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
252 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
253 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
254 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
255 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
258 .addFunction ("access_action", &PublicEditor::access_action)
266 #undef DISPLAYCONTROL
268 #undef IMPORTPOSITION
269 #undef IMPORTDISPOSITION
271 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
272 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
273 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
274 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
275 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
276 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
277 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
278 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
279 luabridge::getGlobalNamespace (L)
280 .beginNamespace ("Editing")
281 # include "editing_syms.h"
288 ////////////////////////////////////////////////////////////////////////////////
290 using namespace ARDOUR;
291 using namespace ARDOUR_UI_UTILS;
296 static void _lua_print (std::string s) {
297 std::cout << "LuaInstance: " << s << "\n";
301 LuaInstance* LuaInstance::_instance = 0;
304 LuaInstance::instance ()
307 _instance = new LuaInstance;
313 LuaInstance::LuaInstance ()
316 lua.Print.connect (&_lua_print);
320 LuaScriptParamList args;
323 LuaInstance::~LuaInstance ()
325 delete _lua_call_action;
326 delete _lua_add_action;
327 delete _lua_del_action;
328 delete _lua_get_action;
340 "function ScriptManager ()"
341 " local self = { scripts = {}, instances = {} }"
343 " local remove = function (id)"
344 " self.scripts[id] = nil"
345 " self.instances[id] = nil"
348 " local addinternal = function (i, n, s, f, a)"
349 " assert(type(i) == 'number', 'id must be numeric')"
350 " assert(type(n) == 'string', 'Name must be string')"
351 " assert(type(s) == 'string', 'Script must be string')"
352 " assert(type(f) == 'function', 'Factory is a not a function')"
353 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
354 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
355 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
356 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
359 " local call = function (id)"
360 " if type(self.instances[id]) == 'function' then"
361 " local status, err = pcall (self.instances[id])"
362 " if not status then"
363 " print ('action \"'.. id .. '\": ', err)" // error out
370 " local add = function (i, n, s, b, a)"
371 " assert(type(b) == 'string', 'ByteCode must be string')"
372 " load (b)()" // assigns f
373 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
374 " addinternal (i, n, s, load(f), a)"
377 " local get = function (id)"
378 " if type(self.scripts[id]) == 'table' then"
379 " return { ['name'] = self.scripts[id]['n'],"
380 " ['script'] = self.scripts[id]['s'],"
381 " ['args'] = self.scripts[id]['a'] }"
386 " local function basic_serialize (o)"
387 " if type(o) == \"number\" then"
388 " return tostring(o)"
390 " return string.format(\"%q\", o)"
394 " local function serialize (name, value)"
395 " local rv = name .. ' = '"
397 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
398 " return rv .. basic_serialize(value) .. ' '"
399 " elseif type(value) == \"table\" then"
401 " for k,v in pairs(value) do"
402 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
403 " rv = rv .. serialize(fieldname, v) .. ' '"
404 " collectgarbage()" // string concatenation allocates a new string
407 " elseif type(value) == \"function\" then"
408 " return rv .. string.format(\"%q\", string.dump(value, true))"
410 " error('cannot save a ' .. type(value))"
415 " local save = function ()"
416 " return (serialize('scripts', self.scripts))"
419 " local clear = function ()"
421 " self.instances = {}"
425 " local restore = function (state)"
428 " for i, s in pairs (scripts) do"
429 " addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
434 " return { call = call, add = add, remove = remove, get = get,"
435 " restore = restore, save = save, clear = clear}"
438 " manager = ScriptManager ()"
439 " ScriptManager = nil"
442 lua_State* L = lua.getState();
445 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
446 lua.do_command ("manager = nil"); // hide it.
447 lua.do_command ("collectgarbage()");
449 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
450 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
451 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
452 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
453 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
454 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
455 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
457 } catch (luabridge::LuaException const& e) {
458 fatal << string_compose (_("programming error: %1"),
459 X_("Failed to setup Lua action interpreter"))
461 abort(); /*NOTREACHED*/
464 register_classes (L);
466 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
467 lua_setglobal (L, "Editor");
470 void LuaInstance::set_session (Session* s)
472 SessionHandlePtr::set_session (s);
477 lua_State* L = lua.getState();
478 LuaBindings::set_session (L, _session);
480 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
481 i->second->set_session (s);
486 LuaInstance::session_going_away ()
488 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
490 for (int i = 0; i < 9; ++i) {
491 ActionChanged (i, ""); /* EMIT SIGNAL */
493 SessionHandlePtr::session_going_away ();
496 lua_State* L = lua.getState();
497 LuaBindings::set_session (L, _session);
498 lua.do_command ("collectgarbage();");
502 LuaInstance::set_state (const XMLNode& node)
504 LocaleGuard lg (X_("C"));
507 if ((child = find_named_node (node, "ActionScript"))) {
508 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
509 if (!(*n)->is_content ()) { continue; }
511 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
513 (*_lua_load)(std::string ((const char*)buf, size));
514 } catch (luabridge::LuaException const& e) {
515 cerr << "LuaException:" << e.what () << endl;
517 for (int i = 0; i < 9; ++i) {
519 if (lua_action_name (i, name)) {
520 ActionChanged (i, name); /* EMIT SIGNAL */
527 if ((child = find_named_node (node, "ActionHooks"))) {
528 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
530 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
531 _callbacks.insert (std::make_pair(p->id(), p));
532 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
533 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
534 } catch (luabridge::LuaException const& e) {
535 cerr << "LuaException:" << e.what () << endl;
544 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
547 std::vector<std::string> reg;
550 case LuaScriptInfo::EditorAction:
551 reg = lua_action_names ();
552 title = "Add Lua Action";
554 case LuaScriptInfo::EditorHook:
555 reg = lua_slot_names ();
556 title = "Add Lua Callback Hook";
562 LuaScriptInfoPtr spi;
563 ScriptSelector ss (title, type);
565 case Gtk::RESPONSE_ACCEPT:
572 std::string script = "";
575 script = Glib::file_get_contents (spi->path);
576 } catch (Glib::FileError e) {
577 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
578 Gtk::MessageDialog am (msg);
583 LuaScriptParamList lsp = LuaScripting::script_params (spi, "action_params");
585 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
586 switch (spd.run ()) {
587 case Gtk::RESPONSE_ACCEPT:
594 case LuaScriptInfo::EditorAction:
595 return set_lua_action (id, spd.name(), script, lsp);
597 case LuaScriptInfo::EditorHook:
598 return register_lua_slot (spd.name(), script, lsp);
607 LuaInstance::get_action_state ()
609 LocaleGuard lg (X_("C"));
612 luabridge::LuaRef savedstate ((*_lua_save)());
613 saved = savedstate.cast<std::string>();
615 lua.collect_garbage ();
617 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
618 std::string b64s (b64);
621 XMLNode* script_node = new XMLNode (X_("ActionScript"));
622 script_node->add_property (X_("lua"), LUA_VERSION);
623 script_node->add_content (b64s);
629 LuaInstance::get_hook_state ()
631 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
632 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
633 script_node->add_child_nocopy (i->second->get_state ());
639 LuaInstance::call_action (const int id)
642 (*_lua_call_action)(id + 1);
643 } catch (luabridge::LuaException const& e) {
644 cerr << "LuaException:" << e.what () << endl;
649 LuaInstance::set_lua_action (
651 const std::string& name,
652 const std::string& script,
653 const LuaScriptParamList& args)
656 lua_State* L = lua.getState();
657 // get bytcode of factory-function in a sandbox
658 // (don't allow scripts to interfere)
659 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
660 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
661 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
662 if ((*i)->optional && !(*i)->is_set) { continue; }
663 tbl_arg[(*i)->name] = (*i)->value;
665 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
666 ActionChanged (id, name); /* EMIT SIGNAL */
667 } catch (luabridge::LuaException const& e) {
668 cerr << "LuaException:" << e.what () << endl;
675 LuaInstance::remove_lua_action (const int id)
678 (*_lua_del_action)(id + 1);
679 } catch (luabridge::LuaException const& e) {
680 cerr << "LuaException:" << e.what () << endl;
683 ActionChanged (id, ""); /* EMIT SIGNAL */
688 LuaInstance::lua_action_name (const int id, std::string& rv)
691 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
695 if (ref["name"].isString()) {
696 rv = ref["name"].cast<std::string>();
700 } catch (luabridge::LuaException const& e) {
701 cerr << "LuaException:" << e.what () << endl;
707 std::vector<std::string>
708 LuaInstance::lua_action_names ()
710 std::vector<std::string> rv;
711 for (int i = 0; i < 9; ++i) {
713 if (lua_action_name (i, name)) {
721 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
724 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
728 if (!ref["name"].isString()) {
731 if (!ref["script"].isString()) {
734 if (!ref["args"].isTable()) {
737 name = ref["name"].cast<std::string>();
738 script = ref["script"].cast<std::string>();
741 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
745 args = LuaScripting::script_params (lsi, "action_params");
746 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
747 if (!i.key ().isString ()) { assert(0); continue; }
748 std::string name = i.key ().cast<std::string> ();
749 std::string value = i.value ().cast<std::string> ();
750 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
751 if ((*ii)->name == name) {
752 (*ii)->value = value;
758 } catch (luabridge::LuaException const& e) {
759 cerr << "LuaException:" << e.what () << endl;
766 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
768 /* parse script, get ActionHook(s) from script */
773 l.Print.connect (&_lua_print);
775 lua_State* L = l.getState();
777 l.do_command ("function ardour () end");
778 l.do_command (script);
779 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
780 if (signals.isFunction()) {
783 } catch (luabridge::LuaException const& e) {
784 cerr << "LuaException:" << e.what () << endl;
788 cerr << "Script registered no hooks." << endl;
792 /* register script w/args, get entry-point / ID */
795 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
796 _callbacks.insert (std::make_pair(p->id(), p));
797 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
798 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
800 } catch (luabridge::LuaException const& e) {
801 cerr << "LuaException:" << e.what () << endl;
807 LuaInstance::unregister_lua_slot (const PBD::ID& id)
809 LuaCallbackMap::iterator i = _callbacks.find (id);
810 if (i != _callbacks.end()) {
811 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
812 _callbacks.erase (i);
819 LuaInstance::lua_slots () const
821 std::vector<PBD::ID> rv;
822 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
823 rv.push_back (i->first);
829 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
831 LuaCallbackMap::const_iterator i = _callbacks.find (id);
832 if (i != _callbacks.end()) {
833 name = i->second->name();
839 std::vector<std::string>
840 LuaInstance::lua_slot_names () const
842 std::vector<std::string> rv;
843 std::vector<PBD::ID> ids = lua_slots();
844 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
846 if (lua_slot_name (*i, name)) {
854 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
856 LuaCallbackMap::const_iterator i = _callbacks.find (id);
857 if (i == _callbacks.end()) {
858 return false; // error
860 return i->second->lua_slot (name, script, ah, args);
863 ///////////////////////////////////////////////////////////////////////////////
865 LuaCallback::LuaCallback (Session *s,
866 const std::string& name,
867 const std::string& script,
868 const ActionHook& ah,
869 const ARDOUR::LuaScriptParamList& args)
870 : SessionHandlePtr (s)
875 // TODO: allow to reference object (e.g region)
878 lua_State* L = lua.getState();
879 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
880 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
881 if ((*i)->optional && !(*i)->is_set) { continue; }
882 tbl_arg[(*i)->name] = (*i)->value;
886 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
887 (*_lua_add)(name, script, bytecode, tbl_arg);
888 } catch (luabridge::LuaException const& e) {
889 cerr << "LuaException:" << e.what () << endl;
890 throw failed_constructor ();
897 LuaCallback::LuaCallback (Session *s, XMLNode & node)
898 : SessionHandlePtr (s)
900 XMLNode* child = NULL;
901 if (node.name() != X_("LuaCallback")
902 || !node.property ("signals")
903 || !node.property ("id")
904 || !node.property ("name")) {
905 throw failed_constructor ();
908 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
909 if (!(*n)->is_content ()) { continue; }
914 throw failed_constructor ();
919 _id = PBD::ID (node.property ("id")->value ());
920 _name = node.property ("name")->value ();
921 _signals = ActionHook (node.property ("signals")->value ());
924 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
926 (*_lua_load)(std::string ((const char*)buf, size));
927 } catch (luabridge::LuaException const& e) {
928 cerr << "LuaException:" << e.what () << endl;
935 LuaCallback::~LuaCallback ()
945 LuaCallback::get_state (void)
949 luabridge::LuaRef savedstate ((*_lua_save)());
950 saved = savedstate.cast<std::string>();
952 lua.collect_garbage ();
954 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
955 std::string b64s (b64);
958 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
959 script_node->add_property (X_("lua"), LUA_VERSION);
960 script_node->add_property (X_("id"), _id.to_s ());
961 script_node->add_property (X_("name"), _name);
962 script_node->add_property (X_("signals"), _signals.to_string ());
963 script_node->add_content (b64s);
968 LuaCallback::init (void)
971 lua.Print.connect (&_lua_print);
975 "function ScriptManager ()"
976 " local self = { script = {}, instance = {} }"
978 " local addinternal = function (n, s, f, a)"
979 " assert(type(n) == 'string', 'Name must be string')"
980 " assert(type(s) == 'string', 'Script must be string')"
981 " assert(type(f) == 'function', 'Factory is a not a function')"
982 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
983 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
984 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
985 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
988 " local call = function (...)"
989 " if type(self.instance) == 'function' then"
990 " local status, err = pcall (self.instance, ...)"
991 " if not status then"
992 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
994 " self.instance = nil"
1002 " local add = function (n, s, b, a)"
1003 " assert(type(b) == 'string', 'ByteCode must be string')"
1004 " load (b)()" // assigns f
1005 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1006 " addinternal (n, s, load(f), a)"
1009 " local get = function ()"
1010 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1011 " return { ['name'] = self.script['n'],"
1012 " ['script'] = self.script['s'],"
1013 " ['args'] = self.script['a'] }"
1020 " local function basic_serialize (o)"
1021 " if type(o) == \"number\" then"
1022 " return tostring(o)"
1024 " return string.format(\"%q\", o)"
1028 " local function serialize (name, value)"
1029 " local rv = name .. ' = '"
1031 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1032 " return rv .. basic_serialize(value) .. ' '"
1033 " elseif type(value) == \"table\" then"
1035 " for k,v in pairs(value) do"
1036 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1037 " rv = rv .. serialize(fieldname, v) .. ' '"
1038 " collectgarbage()" // string concatenation allocates a new string
1041 " elseif type(value) == \"function\" then"
1042 " return rv .. string.format(\"%q\", string.dump(value, true))"
1044 " error('cannot save a ' .. type(value))"
1050 " local save = function ()"
1051 " return (serialize('s', self.script))"
1054 " local restore = function (state)"
1057 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1060 " return { call = call, add = add, get = get,"
1061 " restore = restore, save = save}"
1064 " manager = ScriptManager ()"
1065 " ScriptManager = nil"
1068 lua_State* L = lua.getState();
1071 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1072 lua.do_command ("manager = nil"); // hide it.
1073 lua.do_command ("collectgarbage()");
1075 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1076 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1077 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1078 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1079 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1081 } catch (luabridge::LuaException const& e) {
1082 fatal << string_compose (_("programming error: %1"),
1083 X_("Failed to setup Lua callback interpreter"))
1085 abort(); /*NOTREACHED*/
1088 LuaInstance::register_classes (L);
1090 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1091 lua_setglobal (L, "Editor");
1095 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1097 // TODO consolidate w/ LuaInstance::lua_action()
1099 luabridge::LuaRef ref = (*_lua_get)();
1103 if (!ref["name"].isString()) {
1106 if (!ref["script"].isString()) {
1109 if (!ref["args"].isTable()) {
1114 name = ref["name"].cast<std::string> ();
1115 script = ref["script"].cast<std::string> ();
1118 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1122 args = LuaScripting::script_params (lsi, "action_params");
1123 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
1124 if (!i.key ().isString ()) { assert(0); continue; }
1125 std::string name = i.key ().cast<std::string> ();
1126 std::string value = i.value ().cast<std::string> ();
1127 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
1128 if ((*ii)->name == name) {
1129 (*ii)->value = value;
1135 } catch (luabridge::LuaException const& e) {
1136 cerr << "LuaException:" << e.what () << endl;
1143 LuaCallback::set_session (ARDOUR::Session *s)
1145 SessionHandlePtr::set_session (s);
1148 lua_State* L = lua.getState();
1149 LuaBindings::set_session (L, _session);
1156 LuaCallback::session_going_away ()
1158 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1159 lua.do_command ("collectgarbage();");
1161 SessionHandlePtr::session_going_away ();
1164 drop_callback (); /* EMIT SIGNAL */
1168 LuaCallback::reconnect ()
1170 _connections.drop_connections ();
1171 if ((*_lua_get) ().isNil ()) {
1172 drop_callback (); /* EMIT SIGNAL */
1176 // TODO pass object which emits the signal (e.g region)
1178 // save/load bound objects will be tricky.
1179 // Best idea so far is to save/lookup the PBD::ID
1180 // (either use boost::any indirection or templates for bindable
1181 // object types or a switch statement..)
1183 // _session->route_by_id ()
1184 // _session->track_by_diskstream_id ()
1185 // _session->source_by_id ()
1186 // _session->controllable_by_id ()
1187 // _session->processor_by_id ()
1188 // RegionFactory::region_by_id ()
1190 // TODO loop over objects (if any)
1192 reconnect_object ((void*)0);
1195 template <class T> void
1196 LuaCallback::reconnect_object (T obj)
1198 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1200 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1201 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1202 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1204 # include "luasignal_syms.h"
1206 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1207 abort(); /*NOTREACHED*/
1216 template <typename T, typename S> void
1217 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1219 _connections, invalidator (*this),
1220 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1224 template <typename T, typename C1> void
1225 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1227 _connections, invalidator (*this),
1228 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1232 template <typename T, typename C1, typename C2> void
1233 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1235 _connections, invalidator (*this),
1236 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1240 template <typename T> void
1241 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1242 luabridge::LuaRef rv ((*_lua_call)((int)ls, ref));
1243 if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}
1246 template <typename T, typename C1> void
1247 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1248 luabridge::LuaRef rv ((*_lua_call)((int)ls, ref, a1));
1249 if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}
1252 template <typename T, typename C1, typename C2> void
1253 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1254 luabridge::LuaRef rv ((*_lua_call)((int)ls, ref, a1, a2));
1255 if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}