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 <cairomm/context.h>
21 #include "gtkmm2ext/gui_thread.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/diskstream.h"
25 #include "ardour/plugin_manager.h"
26 #include "ardour/route.h"
27 #include "ardour/session.h"
29 #include "LuaBridge/LuaBridge.h"
31 #include "ardour_ui.h"
32 #include "public_editor.h"
33 #include "region_selection.h"
34 #include "luainstance.h"
35 #include "luasignal.h"
36 #include "time_axis_view.h"
37 #include "selection.h"
38 #include "script_selector.h"
44 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
45 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
46 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
49 str2luasignal (const std::string &str) {
50 const char* type = str.c_str();
52 # include "luasignal_syms.h"
54 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
55 abort(); /*NOTREACHED*/
62 #define STATIC(name,c,p) N_(#name),
63 #define SESSION(name,c,p) N_(#name),
64 #define ENGINE(name,c,p) N_(#name),
65 const char *luasignalstr[] = {
66 # include "luasignal_syms.h"
75 ////////////////////////////////////////////////////////////////////////////////
77 #define xstr(s) stringify(s)
78 #define stringify(s) #s
80 using namespace ARDOUR;
83 LuaInstance::register_hooks (lua_State* L)
86 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
87 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
88 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
89 luabridge::getGlobalNamespace (L)
90 .beginNamespace ("LuaSignal")
91 # include "luasignal_syms.h"
97 luabridge::getGlobalNamespace (L)
98 .beginNamespace ("LuaSignal")
99 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
105 LuaInstance::bind_cairo (lua_State* L)
107 /* std::vector<double> for set_dash()
108 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
110 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
111 * the address of the one in libardour.dll is mapped when loading the .dll
113 * see LuaBindings::set_session() for a detailed explanation
115 luabridge::getGlobalNamespace (L)
116 .beginNamespace ("C")
117 .beginStdVector <double> ("DoubleVector")
121 luabridge::getGlobalNamespace (L)
122 .beginNamespace ("Cairo")
123 .beginClass <Cairo::Context> ("Context")
124 .addFunction ("save", &Cairo::Context::save)
125 .addFunction ("restore", &Cairo::Context::restore)
126 .addFunction ("set_operator", &Cairo::Context::set_operator)
127 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
128 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
129 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
130 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
131 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
132 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
133 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
134 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
135 .addFunction ("translate", &Cairo::Context::translate)
136 .addFunction ("scale", &Cairo::Context::scale)
137 .addFunction ("rotate", &Cairo::Context::rotate)
138 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
139 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
140 .addFunction ("move_to", &Cairo::Context::move_to)
141 .addFunction ("line_to", &Cairo::Context::line_to)
142 .addFunction ("curve_to", &Cairo::Context::curve_to)
143 .addFunction ("arc", &Cairo::Context::arc)
144 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
145 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
146 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
147 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
148 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
149 .addFunction ("close_path", &Cairo::Context::close_path)
150 .addFunction ("paint", &Cairo::Context::paint)
151 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
152 .addFunction ("stroke", &Cairo::Context::stroke)
153 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
154 .addFunction ("fill", &Cairo::Context::fill)
155 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
156 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
157 .addFunction ("clip", &Cairo::Context::clip)
158 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
159 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
160 .addFunction ("show_text", &Cairo::Context::show_text)
163 // LineCap, LineJoin, Operator
164 .beginNamespace ("LineCap")
165 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
166 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
167 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
170 .beginNamespace ("LineJoin")
171 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
172 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
173 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
176 .beginNamespace ("Operator")
177 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
178 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
179 .addConst ("Over", CAIRO_OPERATOR_OVER)
180 .addConst ("Add", CAIRO_OPERATOR_ADD)
185 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
186 one can work around this as follows:
189 LuaInstance::register_classes (lua.getState());
191 "function render (ctx)"
192 " ctx:rectangle (0, 0, 100, 100)"
193 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
198 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
199 Cairo::Context ctx (context->cobj ());
201 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
202 lua_render ((Cairo::Context *)&ctx);
209 LuaInstance::register_classes (lua_State* L)
211 LuaBindings::stddef (L);
212 LuaBindings::common (L);
213 LuaBindings::session (L);
214 LuaBindings::osc (L);
219 luabridge::getGlobalNamespace (L)
220 .beginNamespace ("ArdourUI")
221 .beginClass <RegionSelection> ("RegionSelection")
222 .addFunction ("clear_all", &RegionSelection::clear_all)
223 .addFunction ("start", &RegionSelection::start)
224 .addFunction ("end_frame", &RegionSelection::end_frame)
225 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
228 .beginClass <AxisView> ("AxisView")
230 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
232 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
235 .beginClass <Selection> ("Selection")
236 .addFunction ("clear", &Selection::clear)
237 .addFunction ("clear_all", &Selection::clear_all)
240 .beginClass <TrackViewList> ("TrackViewList")
243 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
246 .beginClass <ArdourMarker> ("ArdourMarker")
249 .beginClass <PublicEditor> ("Editor")
250 .addFunction ("snap_type", &PublicEditor::snap_type)
251 .addFunction ("snap_mode", &PublicEditor::snap_mode)
252 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
253 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
255 .addFunction ("undo", &PublicEditor::undo)
256 .addFunction ("redo", &PublicEditor::redo)
258 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
259 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
261 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
263 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
264 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
265 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
266 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
268 .addFunction ("get_selection", &PublicEditor::get_selection)
269 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
270 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
272 .addFunction ("play_selection", &PublicEditor::play_selection)
273 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
274 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
275 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
277 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
278 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
280 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
281 .addFunction ("show_measures", &PublicEditor::show_measures)
282 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
284 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
285 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
287 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
289 .addRefFunction ("do_import", &PublicEditor::do_import)
290 .addRefFunction ("do_embed", &PublicEditor::do_embed)
292 .addFunction ("export_audio", &PublicEditor::export_audio)
293 .addFunction ("stem_export", &PublicEditor::stem_export)
294 .addFunction ("export_selection", &PublicEditor::export_selection)
295 .addFunction ("export_range", &PublicEditor::export_range)
297 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
298 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
299 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
300 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
302 #if 0 // These need TimeAxisView* which isn't exposed, yet
303 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
304 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
305 .addFunction ("new_playlists", &PublicEditor::new_playlists)
306 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
307 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
310 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
311 .addFunction ("deselect_all", &PublicEditor::deselect_all)
313 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
314 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
315 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
317 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
318 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
319 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
320 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
322 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
323 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
324 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
325 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
326 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
327 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
328 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
330 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
331 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
332 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
333 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
335 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
336 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
337 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
339 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
341 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
342 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
343 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
345 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
346 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
348 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
349 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
350 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
351 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
353 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
354 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
355 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
356 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
359 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
360 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
362 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
363 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
364 .addFunction ("get_track_views", &PublicEditor::get_track_views)
365 .addFunction ("drags", &PublicEditor::drags)
368 .addFunction ("center_screen", &PublicEditor::center_screen)
370 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
371 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
373 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
374 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
375 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
377 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
378 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
379 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
380 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
381 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
385 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
386 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
387 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
388 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
391 .addFunction ("access_action", &PublicEditor::access_action)
399 #undef DISPLAYCONTROL
401 #undef IMPORTPOSITION
402 #undef IMPORTDISPOSITION
404 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
405 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
406 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
407 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
408 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
409 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
410 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
411 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
412 luabridge::getGlobalNamespace (L)
413 .beginNamespace ("Editing")
414 # include "editing_syms.h"
421 ////////////////////////////////////////////////////////////////////////////////
423 using namespace ARDOUR;
424 using namespace ARDOUR_UI_UTILS;
429 static void _lua_print (std::string s) {
430 std::cout << "LuaInstance: " << s << "\n";
434 LuaInstance* LuaInstance::_instance = 0;
437 LuaInstance::instance ()
440 _instance = new LuaInstance;
446 LuaInstance::LuaInstance ()
449 lua.Print.connect (&_lua_print);
453 LuaScriptParamList args;
456 LuaInstance::~LuaInstance ()
458 delete _lua_call_action;
459 delete _lua_add_action;
460 delete _lua_del_action;
461 delete _lua_get_action;
473 "function ScriptManager ()"
474 " local self = { scripts = {}, instances = {} }"
476 " local remove = function (id)"
477 " self.scripts[id] = nil"
478 " self.instances[id] = nil"
481 " local addinternal = function (i, n, s, f, a)"
482 " assert(type(i) == 'number', 'id must be numeric')"
483 " assert(type(n) == 'string', 'Name must be string')"
484 " assert(type(s) == 'string', 'Script must be string')"
485 " assert(type(f) == 'function', 'Factory is a not a function')"
486 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
487 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
488 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
489 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
492 " local call = function (id)"
493 " if type(self.instances[id]) == 'function' then"
494 " local status, err = pcall (self.instances[id])"
495 " if not status then"
496 " print ('action \"'.. id .. '\": ', err)" // error out
503 " local add = function (i, n, s, b, a)"
504 " assert(type(b) == 'string', 'ByteCode must be string')"
505 " load (b)()" // assigns f
506 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
507 " addinternal (i, n, s, load(f), a)"
510 " local get = function (id)"
511 " if type(self.scripts[id]) == 'table' then"
512 " return { ['name'] = self.scripts[id]['n'],"
513 " ['script'] = self.scripts[id]['s'],"
514 " ['args'] = self.scripts[id]['a'] }"
519 " local function basic_serialize (o)"
520 " if type(o) == \"number\" then"
521 " return tostring(o)"
523 " return string.format(\"%q\", o)"
527 " local function serialize (name, value)"
528 " local rv = name .. ' = '"
530 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
531 " return rv .. basic_serialize(value) .. ' '"
532 " elseif type(value) == \"table\" then"
534 " for k,v in pairs(value) do"
535 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
536 " rv = rv .. serialize(fieldname, v) .. ' '"
537 " collectgarbage()" // string concatenation allocates a new string
540 " elseif type(value) == \"function\" then"
541 " return rv .. string.format(\"%q\", string.dump(value, true))"
543 " error('cannot save a ' .. type(value))"
548 " local save = function ()"
549 " return (serialize('scripts', self.scripts))"
552 " local clear = function ()"
554 " self.instances = {}"
558 " local restore = function (state)"
561 " for i, s in pairs (scripts) do"
562 " addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
567 " return { call = call, add = add, remove = remove, get = get,"
568 " restore = restore, save = save, clear = clear}"
571 " manager = ScriptManager ()"
572 " ScriptManager = nil"
575 lua_State* L = lua.getState();
578 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
579 lua.do_command ("manager = nil"); // hide it.
580 lua.do_command ("collectgarbage()");
582 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
583 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
584 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
585 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
586 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
587 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
588 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
590 } catch (luabridge::LuaException const& e) {
591 fatal << string_compose (_("programming error: %1"),
592 X_("Failed to setup Lua action interpreter"))
594 abort(); /*NOTREACHED*/
597 register_classes (L);
599 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
600 lua_setglobal (L, "Editor");
603 void LuaInstance::set_session (Session* s)
605 SessionHandlePtr::set_session (s);
610 lua_State* L = lua.getState();
611 LuaBindings::set_session (L, _session);
613 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
614 i->second->set_session (s);
619 LuaInstance::session_going_away ()
621 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
623 for (int i = 0; i < 9; ++i) {
624 ActionChanged (i, ""); /* EMIT SIGNAL */
626 SessionHandlePtr::session_going_away ();
629 lua_State* L = lua.getState();
630 LuaBindings::set_session (L, _session);
631 lua.do_command ("collectgarbage();");
635 LuaInstance::set_state (const XMLNode& node)
637 LocaleGuard lg (X_("C"));
640 if ((child = find_named_node (node, "ActionScript"))) {
641 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
642 if (!(*n)->is_content ()) { continue; }
644 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
646 (*_lua_load)(std::string ((const char*)buf, size));
647 } catch (luabridge::LuaException const& e) {
648 cerr << "LuaException:" << e.what () << endl;
650 for (int i = 0; i < 9; ++i) {
652 if (lua_action_name (i, name)) {
653 ActionChanged (i, name); /* EMIT SIGNAL */
660 if ((child = find_named_node (node, "ActionHooks"))) {
661 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
663 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
664 _callbacks.insert (std::make_pair(p->id(), p));
665 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
666 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
667 } catch (luabridge::LuaException const& e) {
668 cerr << "LuaException:" << e.what () << endl;
677 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
680 std::vector<std::string> reg;
683 case LuaScriptInfo::EditorAction:
684 reg = lua_action_names ();
685 title = "Add Lua Action";
687 case LuaScriptInfo::EditorHook:
688 reg = lua_slot_names ();
689 title = "Add Lua Callback Hook";
695 LuaScriptInfoPtr spi;
696 ScriptSelector ss (title, type);
698 case Gtk::RESPONSE_ACCEPT:
706 std::string script = "";
709 script = Glib::file_get_contents (spi->path);
710 } catch (Glib::FileError e) {
711 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
712 Gtk::MessageDialog am (msg);
717 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, "action_params");
719 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
720 switch (spd.run ()) {
721 case Gtk::RESPONSE_ACCEPT:
728 case LuaScriptInfo::EditorAction:
729 return set_lua_action (id, spd.name(), script, lsp);
731 case LuaScriptInfo::EditorHook:
732 return register_lua_slot (spd.name(), script, lsp);
741 LuaInstance::get_action_state ()
743 LocaleGuard lg (X_("C"));
746 luabridge::LuaRef savedstate ((*_lua_save)());
747 saved = savedstate.cast<std::string>();
749 lua.collect_garbage ();
751 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
752 std::string b64s (b64);
755 XMLNode* script_node = new XMLNode (X_("ActionScript"));
756 script_node->add_property (X_("lua"), LUA_VERSION);
757 script_node->add_content (b64s);
763 LuaInstance::get_hook_state ()
765 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
766 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
767 script_node->add_child_nocopy (i->second->get_state ());
773 LuaInstance::call_action (const int id)
776 (*_lua_call_action)(id + 1);
777 } catch (luabridge::LuaException const& e) {
778 cerr << "LuaException:" << e.what () << endl;
783 LuaInstance::set_lua_action (
785 const std::string& name,
786 const std::string& script,
787 const LuaScriptParamList& args)
790 lua_State* L = lua.getState();
791 // get bytcode of factory-function in a sandbox
792 // (don't allow scripts to interfere)
793 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
794 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
795 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
796 if ((*i)->optional && !(*i)->is_set) { continue; }
797 tbl_arg[(*i)->name] = (*i)->value;
799 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
800 ActionChanged (id, name); /* EMIT SIGNAL */
801 } catch (luabridge::LuaException const& e) {
802 cerr << "LuaException:" << e.what () << endl;
809 LuaInstance::remove_lua_action (const int id)
812 (*_lua_del_action)(id + 1);
813 } catch (luabridge::LuaException const& e) {
814 cerr << "LuaException:" << e.what () << endl;
817 ActionChanged (id, ""); /* EMIT SIGNAL */
822 LuaInstance::lua_action_name (const int id, std::string& rv)
825 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
829 if (ref["name"].isString()) {
830 rv = ref["name"].cast<std::string>();
834 } catch (luabridge::LuaException const& e) {
835 cerr << "LuaException:" << e.what () << endl;
841 std::vector<std::string>
842 LuaInstance::lua_action_names ()
844 std::vector<std::string> rv;
845 for (int i = 0; i < 9; ++i) {
847 if (lua_action_name (i, name)) {
855 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
858 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
862 if (!ref["name"].isString()) {
865 if (!ref["script"].isString()) {
868 if (!ref["args"].isTable()) {
871 name = ref["name"].cast<std::string>();
872 script = ref["script"].cast<std::string>();
875 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
879 args = LuaScriptParams::script_params (lsi, "action_params");
880 luabridge::LuaRef rargs (ref["args"]);
881 LuaScriptParams::ref_to_params (args, &rargs);
883 } catch (luabridge::LuaException const& e) {
884 cerr << "LuaException:" << e.what () << endl;
891 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
893 /* parse script, get ActionHook(s) from script */
898 l.Print.connect (&_lua_print);
900 lua_State* L = l.getState();
902 l.do_command ("function ardour () end");
903 l.do_command (script);
904 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
905 if (signals.isFunction()) {
908 } catch (luabridge::LuaException const& e) {
909 cerr << "LuaException:" << e.what () << endl;
913 cerr << "Script registered no hooks." << endl;
917 /* register script w/args, get entry-point / ID */
920 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
921 _callbacks.insert (std::make_pair(p->id(), p));
922 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
923 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
925 } catch (luabridge::LuaException const& e) {
926 cerr << "LuaException:" << e.what () << endl;
932 LuaInstance::unregister_lua_slot (const PBD::ID& id)
934 LuaCallbackMap::iterator i = _callbacks.find (id);
935 if (i != _callbacks.end()) {
936 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
937 _callbacks.erase (i);
944 LuaInstance::lua_slots () const
946 std::vector<PBD::ID> rv;
947 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
948 rv.push_back (i->first);
954 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
956 LuaCallbackMap::const_iterator i = _callbacks.find (id);
957 if (i != _callbacks.end()) {
958 name = i->second->name();
964 std::vector<std::string>
965 LuaInstance::lua_slot_names () const
967 std::vector<std::string> rv;
968 std::vector<PBD::ID> ids = lua_slots();
969 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
971 if (lua_slot_name (*i, name)) {
979 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
981 LuaCallbackMap::const_iterator i = _callbacks.find (id);
982 if (i == _callbacks.end()) {
983 return false; // error
985 return i->second->lua_slot (name, script, ah, args);
988 ///////////////////////////////////////////////////////////////////////////////
990 LuaCallback::LuaCallback (Session *s,
991 const std::string& name,
992 const std::string& script,
993 const ActionHook& ah,
994 const ARDOUR::LuaScriptParamList& args)
995 : SessionHandlePtr (s)
1000 // TODO: allow to reference object (e.g region)
1003 lua_State* L = lua.getState();
1004 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1005 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1006 if ((*i)->optional && !(*i)->is_set) { continue; }
1007 tbl_arg[(*i)->name] = (*i)->value;
1011 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1012 (*_lua_add)(name, script, bytecode, tbl_arg);
1013 } catch (luabridge::LuaException const& e) {
1014 cerr << "LuaException:" << e.what () << endl;
1015 throw failed_constructor ();
1022 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1023 : SessionHandlePtr (s)
1025 XMLNode* child = NULL;
1026 if (node.name() != X_("LuaCallback")
1027 || !node.property ("signals")
1028 || !node.property ("id")
1029 || !node.property ("name")) {
1030 throw failed_constructor ();
1033 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1034 if (!(*n)->is_content ()) { continue; }
1039 throw failed_constructor ();
1044 _id = PBD::ID (node.property ("id")->value ());
1045 _name = node.property ("name")->value ();
1046 _signals = ActionHook (node.property ("signals")->value ());
1049 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1051 (*_lua_load)(std::string ((const char*)buf, size));
1052 } catch (luabridge::LuaException const& e) {
1053 cerr << "LuaException:" << e.what () << endl;
1060 LuaCallback::~LuaCallback ()
1070 LuaCallback::get_state (void)
1074 luabridge::LuaRef savedstate ((*_lua_save)());
1075 saved = savedstate.cast<std::string>();
1077 lua.collect_garbage ();
1079 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1080 std::string b64s (b64);
1083 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1084 script_node->add_property (X_("lua"), LUA_VERSION);
1085 script_node->add_property (X_("id"), _id.to_s ());
1086 script_node->add_property (X_("name"), _name);
1087 script_node->add_property (X_("signals"), _signals.to_string ());
1088 script_node->add_content (b64s);
1089 return *script_node;
1093 LuaCallback::init (void)
1096 lua.Print.connect (&_lua_print);
1100 "function ScriptManager ()"
1101 " local self = { script = {}, instance = {} }"
1103 " local addinternal = function (n, s, f, a)"
1104 " assert(type(n) == 'string', 'Name must be string')"
1105 " assert(type(s) == 'string', 'Script must be string')"
1106 " assert(type(f) == 'function', 'Factory is a not a function')"
1107 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1108 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1109 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1110 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1113 " local call = function (...)"
1114 " if type(self.instance) == 'function' then"
1115 " local status, err = pcall (self.instance, ...)"
1116 " if not status then"
1117 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1118 " self.script = nil"
1119 " self.instance = nil"
1127 " local add = function (n, s, b, a)"
1128 " assert(type(b) == 'string', 'ByteCode must be string')"
1129 " load (b)()" // assigns f
1130 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1131 " addinternal (n, s, load(f), a)"
1134 " local get = function ()"
1135 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1136 " return { ['name'] = self.script['n'],"
1137 " ['script'] = self.script['s'],"
1138 " ['args'] = self.script['a'] }"
1145 " local function basic_serialize (o)"
1146 " if type(o) == \"number\" then"
1147 " return tostring(o)"
1149 " return string.format(\"%q\", o)"
1153 " local function serialize (name, value)"
1154 " local rv = name .. ' = '"
1156 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1157 " return rv .. basic_serialize(value) .. ' '"
1158 " elseif type(value) == \"table\" then"
1160 " for k,v in pairs(value) do"
1161 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1162 " rv = rv .. serialize(fieldname, v) .. ' '"
1163 " collectgarbage()" // string concatenation allocates a new string
1166 " elseif type(value) == \"function\" then"
1167 " return rv .. string.format(\"%q\", string.dump(value, true))"
1169 " error('cannot save a ' .. type(value))"
1175 " local save = function ()"
1176 " return (serialize('s', self.script))"
1179 " local restore = function (state)"
1182 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1185 " return { call = call, add = add, get = get,"
1186 " restore = restore, save = save}"
1189 " manager = ScriptManager ()"
1190 " ScriptManager = nil"
1193 lua_State* L = lua.getState();
1196 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1197 lua.do_command ("manager = nil"); // hide it.
1198 lua.do_command ("collectgarbage()");
1200 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1201 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1202 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1203 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1204 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1206 } catch (luabridge::LuaException const& e) {
1207 fatal << string_compose (_("programming error: %1"),
1208 X_("Failed to setup Lua callback interpreter"))
1210 abort(); /*NOTREACHED*/
1213 LuaInstance::register_classes (L);
1215 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1216 lua_setglobal (L, "Editor");
1220 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1222 // TODO consolidate w/ LuaInstance::lua_action()
1224 luabridge::LuaRef ref = (*_lua_get)();
1228 if (!ref["name"].isString()) {
1231 if (!ref["script"].isString()) {
1234 if (!ref["args"].isTable()) {
1239 name = ref["name"].cast<std::string> ();
1240 script = ref["script"].cast<std::string> ();
1243 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1247 args = LuaScriptParams::script_params (lsi, "action_params");
1248 luabridge::LuaRef rargs (ref["args"]);
1249 LuaScriptParams::ref_to_params (args, &rargs);
1251 } catch (luabridge::LuaException const& e) {
1252 cerr << "LuaException:" << e.what () << endl;
1259 LuaCallback::set_session (ARDOUR::Session *s)
1261 SessionHandlePtr::set_session (s);
1264 lua_State* L = lua.getState();
1265 LuaBindings::set_session (L, _session);
1272 LuaCallback::session_going_away ()
1274 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1275 lua.do_command ("collectgarbage();");
1277 SessionHandlePtr::session_going_away ();
1280 drop_callback (); /* EMIT SIGNAL */
1284 LuaCallback::reconnect ()
1286 _connections.drop_connections ();
1287 if ((*_lua_get) ().isNil ()) {
1288 drop_callback (); /* EMIT SIGNAL */
1292 // TODO pass object which emits the signal (e.g region)
1294 // save/load bound objects will be tricky.
1295 // Best idea so far is to save/lookup the PBD::ID
1296 // (either use boost::any indirection or templates for bindable
1297 // object types or a switch statement..)
1299 // _session->route_by_id ()
1300 // _session->track_by_diskstream_id ()
1301 // _session->source_by_id ()
1302 // _session->controllable_by_id ()
1303 // _session->processor_by_id ()
1304 // RegionFactory::region_by_id ()
1306 // TODO loop over objects (if any)
1308 reconnect_object ((void*)0);
1311 template <class T> void
1312 LuaCallback::reconnect_object (T obj)
1314 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1316 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1317 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1318 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1320 # include "luasignal_syms.h"
1322 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1323 abort(); /*NOTREACHED*/
1332 template <typename T, typename S> void
1333 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1335 _connections, invalidator (*this),
1336 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1340 template <typename T, typename C1> void
1341 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1343 _connections, invalidator (*this),
1344 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1348 template <typename T, typename C1, typename C2> void
1349 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1351 _connections, invalidator (*this),
1352 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1356 template <typename T> void
1357 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1360 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1361 if (! rv.cast<bool> ()) {
1365 /* destroy LuaRef ^^ first before calling drop_callback() */
1367 drop_callback (); /* EMIT SIGNAL */
1371 template <typename T, typename C1> void
1372 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1375 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1376 if (! rv.cast<bool> ()) {
1381 drop_callback (); /* EMIT SIGNAL */
1385 template <typename T, typename C1, typename C2> void
1386 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1389 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1390 if (! rv.cast<bool> ()) {
1395 drop_callback (); /* EMIT SIGNAL */