expose Lua OSC transmitter
[ardour.git] / gtk2_ardour / luainstance.cc
1 /*
2  * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  */
18
19 #include <cairomm/context.h>
20
21 #include "gtkmm2ext/gui_thread.h"
22
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"
28
29 #include "ardour_ui.h"
30 #include "public_editor.h"
31 #include "region_selection.h"
32 #include "luainstance.h"
33 #include "luasignal.h"
34 #include "script_selector.h"
35
36 #include "i18n.h"
37
38 namespace LuaSignal {
39
40 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
41 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
42 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
43
44 LuaSignal
45 str2luasignal (const std::string &str) {
46         const char* type = str.c_str();
47         if (0) { }
48 #       include "luasignal_syms.h"
49         else {
50                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
51                 abort(); /*NOTREACHED*/
52         }
53 }
54 #undef STATIC
55 #undef SESSION
56 #undef ENGINE
57
58 #define STATIC(name,c,p) N_(#name),
59 #define SESSION(name,c,p) N_(#name),
60 #define ENGINE(name,c,p) N_(#name),
61 const char *luasignalstr[] = {
62 #       include "luasignal_syms.h"
63         0
64 };
65
66 #undef STATIC
67 #undef SESSION
68 #undef ENGINE
69 }; // namespace
70
71 ////////////////////////////////////////////////////////////////////////////////
72
73 #define xstr(s) stringify(s)
74 #define stringify(s) #s
75
76 using namespace ARDOUR;
77
78 void
79 LuaInstance::register_hooks (lua_State* L)
80 {
81
82 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
83 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
84 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
85         luabridge::getGlobalNamespace (L)
86                 .beginNamespace ("LuaSignal")
87 #               include "luasignal_syms.h"
88                 .endNamespace ();
89 #undef ENGINE
90 #undef SESSION
91 #undef STATIC
92
93         luabridge::getGlobalNamespace (L)
94                 .beginNamespace ("LuaSignal")
95                 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
96                 .endClass()
97                 .endNamespace ();
98 }
99
100 void
101 LuaInstance::bind_cairo (lua_State* L)
102 {
103         luabridge::getGlobalNamespace (L)
104                 .beginNamespace ("Cairo")
105                 .beginClass <Cairo::Context> ("Context")
106                 .addFunction ("save", &Cairo::Context::save)
107                 .addFunction ("restore", &Cairo::Context::restore)
108                 .addFunction ("set_operator", &Cairo::Context::set_operator)
109                 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
110                 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
111                 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
112                 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
113                 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
114                 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
115                 .addFunction ("set_dash", (void (Cairo::Context::*)(std::vector<double>&, double))&Cairo::Context::set_dash)
116                 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
117                 .addFunction ("translate", &Cairo::Context::translate)
118                 .addFunction ("scale", &Cairo::Context::scale)
119                 .addFunction ("rotate", &Cairo::Context::rotate)
120                 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
121                 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
122                 .addFunction ("move_to", &Cairo::Context::move_to)
123                 .addFunction ("line_to", &Cairo::Context::line_to)
124                 .addFunction ("curve_to", &Cairo::Context::curve_to)
125                 .addFunction ("arc", &Cairo::Context::arc)
126                 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
127                 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
128                 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
129                 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
130                 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
131                 .addFunction ("close_path", &Cairo::Context::close_path)
132                 .addFunction ("paint", &Cairo::Context::paint)
133                 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
134                 .addFunction ("stroke", &Cairo::Context::stroke)
135                 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
136                 .addFunction ("fill", &Cairo::Context::fill)
137                 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
138                 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
139                 .addFunction ("clip", &Cairo::Context::clip)
140                 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
141                 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
142                 .addFunction ("show_text", &Cairo::Context::show_text)
143                 .endClass ()
144                 /* enums */
145                 // LineCap, LineJoin, Operator
146                 .beginNamespace ("LineCap")
147                 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
148                 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
149                 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
150                 .endNamespace ()
151
152                 .beginNamespace ("LineJoin")
153                 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
154                 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
155                 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
156                 .endNamespace ()
157
158                 .beginNamespace ("Operator")
159                 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
160                 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
161                 .addConst ("Over", CAIRO_OPERATOR_OVER)
162                 .addConst ("Add", CAIRO_OPERATOR_ADD)
163                 .endNamespace ()
164
165                 .endNamespace ();
166
167 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
168   one can work around this as follows:
169
170   LuaState lua;
171   LuaInstance::register_classes (lua.getState());
172   lua.do_command (
173       "function render (ctx)"
174       "  ctx:rectangle (0, 0, 100, 100)"
175       "  ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
176       "  ctx:fill ()"
177       " end"
178       );
179   {
180                 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
181     Cairo::Context ctx (context->cobj ());
182
183     luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
184     lua_render ((Cairo::Context *)&ctx);
185   }
186 */
187
188 }
189
190 void
191 LuaInstance::register_classes (lua_State* L)
192 {
193         LuaBindings::stddef (L);
194         LuaBindings::common (L);
195         LuaBindings::session (L);
196         LuaBindings::osc (L);
197
198         bind_cairo (L);
199         register_hooks (L);
200
201         luabridge::getGlobalNamespace (L)
202                 .beginNamespace ("ARDOUR")
203                 .beginClass <RegionSelection> ("RegionSelection")
204                 .addFunction ("clear_all", &RegionSelection::clear_all)
205                 .addFunction ("start", &RegionSelection::start)
206                 .addFunction ("end_frame", &RegionSelection::end_frame)
207                 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
208                 .endClass ()
209
210                 .beginClass <PublicEditor> ("Editor")
211                 .addFunction ("snap_type", &PublicEditor::snap_type)
212                 .addFunction ("snap_mode", &PublicEditor::snap_mode)
213                 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
214                 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
215
216                 .addFunction ("undo", &PublicEditor::undo)
217                 .addFunction ("redo", &PublicEditor::redo)
218
219                 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
220                 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
221
222                 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
223
224                 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
225                 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
226                 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
227                 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
228
229 #if 0 // Selection is not yet exposed
230                 .addFunction ("get_selection", &PublicEditor::get_selection)
231                 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
232                 .addFunction ("track_mixer_selection", &PublicEditor::track_mixer_selection)
233                 .addFunction ("extend_selection_to_track", &PublicEditor::extend_selection_to_track)
234 #endif
235
236                 .addFunction ("play_selection", &PublicEditor::play_selection)
237                 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
238                 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
239                 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
240
241                 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
242                 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
243
244                 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
245                 .addFunction ("show_measures", &PublicEditor::show_measures)
246                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
247
248                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
249
250                 .addFunction ("do_import", &PublicEditor::do_import)
251                 .addFunction ("do_embed", &PublicEditor::do_embed)
252
253                 .addFunction ("export_audio", &PublicEditor::export_audio)
254                 .addFunction ("stem_export", &PublicEditor::stem_export)
255                 .addFunction ("export_selection", &PublicEditor::export_selection)
256                 .addFunction ("export_range", &PublicEditor::export_range)
257
258                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
259                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
260                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
261                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
262
263 #if 0 // These need TimeAxisView* which isn't exposed, yet
264                 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
265                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
266                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
267                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
268                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
269 #endif
270
271                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
272                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
273 #if 0
274                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
275                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
276                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
277 #endif
278                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
279                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
280                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
281                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
282
283                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
284                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
285                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
286                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
287                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
288                 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
289                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
290
291                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
292                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
293                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
294                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
295
296                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
297                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
298                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
299
300                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
301
302                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
303                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
304                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
305
306                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
307                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
308
309                 .addFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
310                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
311                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
312                 .addFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
313
314                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
315                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
316                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
317                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
318
319 #if 0
320                 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
321                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
322
323                 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
324                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
325                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
326                 .addFunction ("drags", &PublicEditor::drags)
327 #endif
328
329                 .addFunction ("center_screen", &PublicEditor::center_screen)
330
331                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
332                 .addFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
333
334                 .addFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
335                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
336                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
337 #if 0
338                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
339                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
340                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
341                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
342                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
343 #endif
344
345 #if 0
346                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
347                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
348                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
349                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
350 #endif
351
352                 .addFunction ("access_action", &PublicEditor::access_action)
353                 .endClass ()
354                 .endNamespace ();
355
356 #undef ZOOMFOCUS
357 #undef SNAPTYPE
358 #undef SNAPMODE
359 #undef MOUSEMODE
360 #undef DISPLAYCONTROL
361 #undef IMPORTMODE
362 #undef IMPORTPOSITION
363 #undef IMPORTDISPOSITION
364
365 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
366 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
367 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
368 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
369 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
370 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
371 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
372 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
373         luabridge::getGlobalNamespace (L)
374                 .beginNamespace ("Editing")
375 #               include "editing_syms.h"
376                 .endNamespace ();
377 }
378
379 #undef xstr
380 #undef stringify
381
382 ////////////////////////////////////////////////////////////////////////////////
383
384 using namespace ARDOUR;
385 using namespace ARDOUR_UI_UTILS;
386 using namespace PBD;
387 using namespace std;
388
389 #ifndef NDEBUG
390 static void _lua_print (std::string s) {
391         std::cout << "LuaInstance: " << s << "\n";
392 }
393 #endif
394
395 LuaInstance* LuaInstance::_instance = 0;
396
397 LuaInstance*
398 LuaInstance::instance ()
399 {
400         if (!_instance) {
401                 _instance  = new LuaInstance;
402         }
403
404         return _instance;
405 }
406
407 LuaInstance::LuaInstance ()
408 {
409 #ifndef NDEBUG
410         lua.Print.connect (&_lua_print);
411 #endif
412         init ();
413
414         LuaScriptParamList args;
415 }
416
417 LuaInstance::~LuaInstance ()
418 {
419         delete _lua_call_action;
420         delete _lua_add_action;
421         delete _lua_del_action;
422         delete _lua_get_action;
423
424         delete _lua_load;
425         delete _lua_save;
426         delete _lua_clear;
427         _callbacks.clear();
428 }
429
430 void
431 LuaInstance::init ()
432 {
433         lua.do_command (
434                         "function ScriptManager ()"
435                         "  local self = { scripts = {}, instances = {} }"
436                         ""
437                         "  local remove = function (id)"
438                         "   self.scripts[id] = nil"
439                         "   self.instances[id] = nil"
440                         "  end"
441                         ""
442                         "  local addinternal = function (i, n, s, f, a)"
443                         "   assert(type(i) == 'number', 'id must be numeric')"
444                         "   assert(type(n) == 'string', 'Name must be string')"
445                         "   assert(type(s) == 'string', 'Script must be string')"
446                         "   assert(type(f) == 'function', 'Factory is a not a function')"
447                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
448                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
449                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
450                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
451                         "  end"
452                         ""
453                         "  local call = function (id)"
454                         "   if type(self.instances[id]) == 'function' then"
455                         "     local status, err = pcall (self.instances[id])"
456                         "     if not status then"
457                         "       print ('action \"'.. id .. '\": ', err)" // error out
458                         "       remove (id)"
459                         "     end"
460                         "   end"
461                         "   collectgarbage()"
462                         "  end"
463                         ""
464                         "  local add = function (i, n, s, b, a)"
465                         "   assert(type(b) == 'string', 'ByteCode must be string')"
466                         "   load (b)()" // assigns f
467                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
468                         "   addinternal (i, n, s, load(f), a)"
469                         "  end"
470                         ""
471                         "  local get = function (id)"
472                         "   if type(self.scripts[id]) == 'table' then"
473                         "    return { ['name'] = self.scripts[id]['n'],"
474                         "             ['script'] = self.scripts[id]['s'],"
475                         "             ['args'] = self.scripts[id]['a'] }"
476                         "   end"
477                         "   return nil"
478                         "  end"
479                         ""
480                         "  local function basic_serialize (o)"
481                         "    if type(o) == \"number\" then"
482                         "     return tostring(o)"
483                         "    else"
484                         "     return string.format(\"%q\", o)"
485                         "    end"
486                         "  end"
487                         ""
488                         "  local function serialize (name, value)"
489                         "   local rv = name .. ' = '"
490                         "   collectgarbage()"
491                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
492                         "    return rv .. basic_serialize(value) .. ' '"
493                         "   elseif type(value) == \"table\" then"
494                         "    rv = rv .. '{} '"
495                         "    for k,v in pairs(value) do"
496                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
497                         "     rv = rv .. serialize(fieldname, v) .. ' '"
498                         "     collectgarbage()" // string concatenation allocates a new string
499                         "    end"
500                         "    return rv;"
501                         "   elseif type(value) == \"function\" then"
502                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
503                         "   else"
504                         "    error('cannot save a ' .. type(value))"
505                         "   end"
506                         "  end"
507                         ""
508                         ""
509                         "  local save = function ()"
510                         "   return (serialize('scripts', self.scripts))"
511                         "  end"
512                         ""
513                         "  local clear = function ()"
514                         "   self.scripts = {}"
515                         "   self.instances = {}"
516                         "   collectgarbage()"
517                         "  end"
518                         ""
519                         "  local restore = function (state)"
520                         "   clear()"
521                         "   load (state)()"
522                         "   for i, s in pairs (scripts) do"
523                         "    addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
524                         "   end"
525                         "   collectgarbage()"
526                         "  end"
527                         ""
528                         " return { call = call, add = add, remove = remove, get = get,"
529                         "          restore = restore, save = save, clear = clear}"
530                         " end"
531                         " "
532                         " manager = ScriptManager ()"
533                         " ScriptManager = nil"
534                         );
535
536         lua_State* L = lua.getState();
537
538         try {
539                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
540                 lua.do_command ("manager = nil"); // hide it.
541                 lua.do_command ("collectgarbage()");
542
543                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
544                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
545                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
546                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
547                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
548                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
549                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
550
551         } catch (luabridge::LuaException const& e) {
552                 fatal << string_compose (_("programming error: %1"),
553                                 X_("Failed to setup Lua action interpreter"))
554                         << endmsg;
555                 abort(); /*NOTREACHED*/
556         }
557
558         register_classes (L);
559
560         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
561         lua_setglobal (L, "Editor");
562 }
563
564 void LuaInstance::set_session (Session* s)
565 {
566         SessionHandlePtr::set_session (s);
567         if (!_session) {
568                 return;
569         }
570
571         lua_State* L = lua.getState();
572         LuaBindings::set_session (L, _session);
573
574         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
575                 i->second->set_session (s);
576         }
577 }
578
579 void
580 LuaInstance::session_going_away ()
581 {
582         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
583         (*_lua_clear)();
584         for (int i = 0; i < 9; ++i) {
585                 ActionChanged (i, ""); /* EMIT SIGNAL */
586         }
587         SessionHandlePtr::session_going_away ();
588         _session = 0;
589
590         lua_State* L = lua.getState();
591         LuaBindings::set_session (L, _session);
592         lua.do_command ("collectgarbage();");
593 }
594
595 int
596 LuaInstance::set_state (const XMLNode& node)
597 {
598         LocaleGuard lg (X_("C"));
599         XMLNode* child;
600
601         if ((child = find_named_node (node, "ActionScript"))) {
602                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
603                         if (!(*n)->is_content ()) { continue; }
604                         gsize size;
605                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
606                         try {
607                                 (*_lua_load)(std::string ((const char*)buf, size));
608                         } catch (luabridge::LuaException const& e) {
609                                 cerr << "LuaException:" << e.what () << endl;
610                         }
611                         for (int i = 0; i < 9; ++i) {
612                                 std::string name;
613                                 if (lua_action_name (i, name)) {
614                                         ActionChanged (i, name); /* EMIT SIGNAL */
615                                 }
616                         }
617                         g_free (buf);
618                 }
619         }
620
621         if ((child = find_named_node (node, "ActionHooks"))) {
622                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
623                         try {
624                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
625                                 _callbacks.insert (std::make_pair(p->id(), p));
626                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
627                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
628                         } catch (luabridge::LuaException const& e) {
629                                 cerr << "LuaException:" << e.what () << endl;
630                         }
631                 }
632         }
633
634         return 0;
635 }
636
637 bool
638 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
639 {
640         std::string title;
641         std::vector<std::string> reg;
642
643         switch (type) {
644                 case LuaScriptInfo::EditorAction:
645                         reg = lua_action_names ();
646                         title = "Add Lua Action";
647                         break;
648                 case LuaScriptInfo::EditorHook:
649                         reg = lua_slot_names ();
650                         title = "Add Lua Callback Hook";
651                         break;
652                 default:
653                         return false;
654         }
655
656         LuaScriptInfoPtr spi;
657         ScriptSelector ss (title, type);
658         switch (ss.run ()) {
659                 case Gtk::RESPONSE_ACCEPT:
660                         spi = ss.script();
661                         break;
662                 default:
663                         return false;
664         }
665
666         std::string script = "";
667
668         try {
669                 script = Glib::file_get_contents (spi->path);
670         } catch (Glib::FileError e) {
671                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
672                 Gtk::MessageDialog am (msg);
673                 am.run ();
674                 return false;
675         }
676
677         LuaScriptParamList lsp = LuaScripting::script_params (spi, "action_params");
678
679         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
680         switch (spd.run ()) {
681                 case Gtk::RESPONSE_ACCEPT:
682                         break;
683                 default:
684                         return false;
685         }
686
687         switch (type) {
688                 case LuaScriptInfo::EditorAction:
689                         return set_lua_action (id, spd.name(), script, lsp);
690                         break;
691                 case LuaScriptInfo::EditorHook:
692                         return register_lua_slot (spd.name(), script, lsp);
693                         break;
694                 default:
695                         break;
696         }
697         return false;
698 }
699
700 XMLNode&
701 LuaInstance::get_action_state ()
702 {
703         LocaleGuard lg (X_("C"));
704         std::string saved;
705         {
706                 luabridge::LuaRef savedstate ((*_lua_save)());
707                 saved = savedstate.cast<std::string>();
708         }
709         lua.collect_garbage ();
710
711         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
712         std::string b64s (b64);
713         g_free (b64);
714
715         XMLNode* script_node = new XMLNode (X_("ActionScript"));
716         script_node->add_property (X_("lua"), LUA_VERSION);
717         script_node->add_content (b64s);
718
719         return *script_node;
720 }
721
722 XMLNode&
723 LuaInstance::get_hook_state ()
724 {
725         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
726         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
727                 script_node->add_child_nocopy (i->second->get_state ());
728         }
729         return *script_node;
730 }
731
732 void
733 LuaInstance::call_action (const int id)
734 {
735         try {
736                 (*_lua_call_action)(id + 1);
737         } catch (luabridge::LuaException const& e) {
738                 cerr << "LuaException:" << e.what () << endl;
739         }
740 }
741
742 bool
743 LuaInstance::set_lua_action (
744                 const int id,
745                 const std::string& name,
746                 const std::string& script,
747                 const LuaScriptParamList& args)
748 {
749         try {
750                 lua_State* L = lua.getState();
751                 // get bytcode of factory-function in a sandbox
752                 // (don't allow scripts to interfere)
753                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
754                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
755                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
756                         if ((*i)->optional && !(*i)->is_set) { continue; }
757                         tbl_arg[(*i)->name] = (*i)->value;
758                 }
759                 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
760                 ActionChanged (id, name); /* EMIT SIGNAL */
761         } catch (luabridge::LuaException const& e) {
762                 cerr << "LuaException:" << e.what () << endl;
763                 return false;
764         }
765         return true;
766 }
767
768 bool
769 LuaInstance::remove_lua_action (const int id)
770 {
771         try {
772                 (*_lua_del_action)(id + 1);
773         } catch (luabridge::LuaException const& e) {
774                 cerr << "LuaException:" << e.what () << endl;
775                 return false;
776         }
777         ActionChanged (id, ""); /* EMIT SIGNAL */
778         return true;
779 }
780
781 bool
782 LuaInstance::lua_action_name (const int id, std::string& rv)
783 {
784         try {
785                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
786                 if (ref.isNil()) {
787                         return false;
788                 }
789                 if (ref["name"].isString()) {
790                         rv = ref["name"].cast<std::string>();
791                         return true;
792                 }
793                 return true;
794         } catch (luabridge::LuaException const& e) {
795                 cerr << "LuaException:" << e.what () << endl;
796                 return false;
797         }
798         return false;
799 }
800
801 std::vector<std::string>
802 LuaInstance::lua_action_names ()
803 {
804         std::vector<std::string> rv;
805         for (int i = 0; i < 9; ++i) {
806                 std::string name;
807                 if (lua_action_name (i, name)) {
808                         rv.push_back (name);
809                 }
810         }
811         return rv;
812 }
813
814 bool
815 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
816 {
817         try {
818                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
819                 if (ref.isNil()) {
820                         return false;
821                 }
822                 if (!ref["name"].isString()) {
823                         return false;
824                 }
825                 if (!ref["script"].isString()) {
826                         return false;
827                 }
828                 if (!ref["args"].isTable()) {
829                         return false;
830                 }
831                 name = ref["name"].cast<std::string>();
832                 script = ref["script"].cast<std::string>();
833
834                 args.clear();
835                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
836                 if (!lsi) {
837                         return false;
838                 }
839                 args = LuaScripting::script_params (lsi, "action_params");
840                 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
841                         if (!i.key ().isString ()) { assert(0); continue; }
842                         std::string name = i.key ().cast<std::string> ();
843                         std::string value = i.value ().cast<std::string> ();
844                         for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
845                                 if ((*ii)->name == name) {
846                                         (*ii)->value = value;
847                                         break;
848                                 }
849                         }
850                 }
851                 return true;
852         } catch (luabridge::LuaException const& e) {
853                 cerr << "LuaException:" << e.what () << endl;
854                 return false;
855         }
856         return false;
857 }
858
859 bool
860 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
861 {
862         /* parse script, get ActionHook(s) from script */
863         ActionHook ah;
864         try {
865                 LuaState l;
866 #ifndef NDEBUG
867                 l.Print.connect (&_lua_print);
868 #endif
869                 lua_State* L = l.getState();
870                 register_hooks (L);
871                 l.do_command ("function ardour () end");
872                 l.do_command (script);
873                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
874                 if (signals.isFunction()) {
875                         ah = signals();
876                 }
877         } catch (luabridge::LuaException const& e) {
878                 cerr << "LuaException:" << e.what () << endl;
879         }
880
881         if (ah.none ()) {
882                 cerr << "Script registered no hooks." << endl;
883                 return false;
884         }
885
886         /* register script w/args, get entry-point / ID */
887
888         try {
889                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
890                 _callbacks.insert (std::make_pair(p->id(), p));
891                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
892                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
893                 return true;
894         } catch (luabridge::LuaException const& e) {
895                 cerr << "LuaException:" << e.what () << endl;
896         }
897         return false;
898 }
899
900 bool
901 LuaInstance::unregister_lua_slot (const PBD::ID& id)
902 {
903         LuaCallbackMap::iterator i = _callbacks.find (id);
904         if (i != _callbacks.end()) {
905                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
906                 _callbacks.erase (i);
907                 return true;
908         }
909         return false;
910 }
911
912 std::vector<PBD::ID>
913 LuaInstance::lua_slots () const
914 {
915         std::vector<PBD::ID> rv;
916         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
917                 rv.push_back (i->first);
918         }
919         return rv;
920 }
921
922 bool
923 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
924 {
925         LuaCallbackMap::const_iterator i = _callbacks.find (id);
926         if (i != _callbacks.end()) {
927                 name = i->second->name();
928                 return true;
929         }
930         return false;
931 }
932
933 std::vector<std::string>
934 LuaInstance::lua_slot_names () const
935 {
936         std::vector<std::string> rv;
937         std::vector<PBD::ID> ids = lua_slots();
938         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
939                 std::string name;
940                 if (lua_slot_name (*i, name)) {
941                         rv.push_back (name);
942                 }
943         }
944         return rv;
945 }
946
947 bool
948 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
949 {
950         LuaCallbackMap::const_iterator i = _callbacks.find (id);
951         if (i == _callbacks.end()) {
952                 return false; // error
953         }
954         return i->second->lua_slot (name, script, ah, args);
955 }
956
957 ///////////////////////////////////////////////////////////////////////////////
958
959 LuaCallback::LuaCallback (Session *s,
960                 const std::string& name,
961                 const std::string& script,
962                 const ActionHook& ah,
963                 const ARDOUR::LuaScriptParamList& args)
964         : SessionHandlePtr (s)
965         , _id ("0")
966         , _name (name)
967         , _signals (ah)
968 {
969         // TODO: allow to reference object (e.g region)
970         init ();
971
972         lua_State* L = lua.getState();
973         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
974         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
975                 if ((*i)->optional && !(*i)->is_set) { continue; }
976                 tbl_arg[(*i)->name] = (*i)->value;
977         }
978
979         try {
980         const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
981         (*_lua_add)(name, script, bytecode, tbl_arg);
982         } catch (luabridge::LuaException const& e) {
983                 cerr << "LuaException:" << e.what () << endl;
984                 throw failed_constructor ();
985         }
986
987         _id.reset ();
988         set_session (s);
989 }
990
991 LuaCallback::LuaCallback (Session *s, XMLNode & node)
992         : SessionHandlePtr (s)
993 {
994         XMLNode* child = NULL;
995         if (node.name() != X_("LuaCallback")
996                         || !node.property ("signals")
997                         || !node.property ("id")
998                         || !node.property ("name")) {
999                 throw failed_constructor ();
1000         }
1001
1002         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1003                 if (!(*n)->is_content ()) { continue; }
1004                 child = *n;
1005         }
1006
1007         if (!child) {
1008                 throw failed_constructor ();
1009         }
1010
1011         init ();
1012
1013         _id = PBD::ID (node.property ("id")->value ());
1014         _name = node.property ("name")->value ();
1015         _signals = ActionHook (node.property ("signals")->value ());
1016
1017         gsize size;
1018         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1019         try {
1020                 (*_lua_load)(std::string ((const char*)buf, size));
1021         } catch (luabridge::LuaException const& e) {
1022                 cerr << "LuaException:" << e.what () << endl;
1023         }
1024         g_free (buf);
1025
1026         set_session (s);
1027 }
1028
1029 LuaCallback::~LuaCallback ()
1030 {
1031         delete _lua_add;
1032         delete _lua_get;
1033         delete _lua_call;
1034         delete _lua_load;
1035         delete _lua_save;
1036 }
1037
1038 XMLNode&
1039 LuaCallback::get_state (void)
1040 {
1041         std::string saved;
1042         {
1043                 luabridge::LuaRef savedstate ((*_lua_save)());
1044                 saved = savedstate.cast<std::string>();
1045         }
1046         lua.collect_garbage ();
1047
1048         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1049         std::string b64s (b64);
1050         g_free (b64);
1051
1052         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1053         script_node->add_property (X_("lua"), LUA_VERSION);
1054         script_node->add_property (X_("id"), _id.to_s ());
1055         script_node->add_property (X_("name"), _name);
1056         script_node->add_property (X_("signals"), _signals.to_string ());
1057         script_node->add_content (b64s);
1058         return *script_node;
1059 }
1060
1061 void
1062 LuaCallback::init (void)
1063 {
1064 #ifndef NDEBUG
1065         lua.Print.connect (&_lua_print);
1066 #endif
1067
1068         lua.do_command (
1069                         "function ScriptManager ()"
1070                         "  local self = { script = {}, instance = {} }"
1071                         ""
1072                         "  local addinternal = function (n, s, f, a)"
1073                         "   assert(type(n) == 'string', 'Name must be string')"
1074                         "   assert(type(s) == 'string', 'Script must be string')"
1075                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1076                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1077                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1078                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1079                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1080                         "  end"
1081                         ""
1082                         "  local call = function (...)"
1083                         "   if type(self.instance) == 'function' then"
1084                         "     local status, err = pcall (self.instance, ...)"
1085                         "     if not status then"
1086                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1087                         "       self.script = nil"
1088                         "       self.instance = nil"
1089                         "       return false"
1090                         "     end"
1091                         "   end"
1092                         "   collectgarbage()"
1093                         "   return true"
1094                         "  end"
1095                         ""
1096                         "  local add = function (n, s, b, a)"
1097                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1098                         "   load (b)()" // assigns f
1099                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1100                         "   addinternal (n, s, load(f), a)"
1101                         "  end"
1102                         ""
1103                         "  local get = function ()"
1104                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1105                         "    return { ['name'] = self.script['n'],"
1106                         "             ['script'] = self.script['s'],"
1107                         "             ['args'] = self.script['a'] }"
1108                         "   end"
1109                         "   return nil"
1110                         "  end"
1111                         ""
1112                         // code dup
1113                         ""
1114                         "  local function basic_serialize (o)"
1115                         "    if type(o) == \"number\" then"
1116                         "     return tostring(o)"
1117                         "    else"
1118                         "     return string.format(\"%q\", o)"
1119                         "    end"
1120                         "  end"
1121                         ""
1122                         "  local function serialize (name, value)"
1123                         "   local rv = name .. ' = '"
1124                         "   collectgarbage()"
1125                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1126                         "    return rv .. basic_serialize(value) .. ' '"
1127                         "   elseif type(value) == \"table\" then"
1128                         "    rv = rv .. '{} '"
1129                         "    for k,v in pairs(value) do"
1130                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1131                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1132                         "     collectgarbage()" // string concatenation allocates a new string
1133                         "    end"
1134                         "    return rv;"
1135                         "   elseif type(value) == \"function\" then"
1136                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1137                         "   else"
1138                         "    error('cannot save a ' .. type(value))"
1139                         "   end"
1140                         "  end"
1141                         ""
1142                         // end code dup
1143                         ""
1144                         "  local save = function ()"
1145                         "   return (serialize('s', self.script))"
1146                         "  end"
1147                         ""
1148                         "  local restore = function (state)"
1149                         "   self.script = {}"
1150                         "   load (state)()"
1151                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1152                         "  end"
1153                         ""
1154                         " return { call = call, add = add, get = get,"
1155                         "          restore = restore, save = save}"
1156                         " end"
1157                         " "
1158                         " manager = ScriptManager ()"
1159                         " ScriptManager = nil"
1160                         );
1161
1162         lua_State* L = lua.getState();
1163
1164         try {
1165                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1166                 lua.do_command ("manager = nil"); // hide it.
1167                 lua.do_command ("collectgarbage()");
1168
1169                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1170                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1171                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1172                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1173                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1174
1175         } catch (luabridge::LuaException const& e) {
1176                 fatal << string_compose (_("programming error: %1"),
1177                                 X_("Failed to setup Lua callback interpreter"))
1178                         << endmsg;
1179                 abort(); /*NOTREACHED*/
1180         }
1181
1182         LuaInstance::register_classes (L);
1183
1184         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1185         lua_setglobal (L, "Editor");
1186 }
1187
1188 bool
1189 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1190 {
1191         // TODO consolidate w/ LuaInstance::lua_action()
1192         try {
1193                 luabridge::LuaRef ref = (*_lua_get)();
1194                 if (ref.isNil()) {
1195                         return false;
1196                 }
1197                 if (!ref["name"].isString()) {
1198                         return false;
1199                 }
1200                 if (!ref["script"].isString()) {
1201                         return false;
1202                 }
1203                 if (!ref["args"].isTable()) {
1204                         return false;
1205                 }
1206
1207                 ah = _signals;
1208                 name = ref["name"].cast<std::string> ();
1209                 script = ref["script"].cast<std::string> ();
1210
1211                 args.clear();
1212                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1213                 if (!lsi) {
1214                         return false;
1215                 }
1216                 args = LuaScripting::script_params (lsi, "action_params");
1217                 for (luabridge::Iterator i (static_cast<luabridge::LuaRef>(ref["args"])); !i.isNil (); ++i) {
1218                         if (!i.key ().isString ()) { assert(0); continue; }
1219                         std::string name = i.key ().cast<std::string> ();
1220                         std::string value = i.value ().cast<std::string> ();
1221                         for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
1222                                 if ((*ii)->name == name) {
1223                                         (*ii)->value = value;
1224                                         break;
1225                                 }
1226                         }
1227                 }
1228                 return true;
1229         } catch (luabridge::LuaException const& e) {
1230                 cerr << "LuaException:" << e.what () << endl;
1231                 return false;
1232         }
1233         return false;
1234 }
1235
1236 void
1237 LuaCallback::set_session (ARDOUR::Session *s)
1238 {
1239         SessionHandlePtr::set_session (s);
1240
1241         if (_session) {
1242                 lua_State* L = lua.getState();
1243                 LuaBindings::set_session (L, _session);
1244         }
1245
1246         reconnect();
1247 }
1248
1249 void
1250 LuaCallback::session_going_away ()
1251 {
1252         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1253         lua.do_command ("collectgarbage();");
1254
1255         SessionHandlePtr::session_going_away ();
1256         _session = 0;
1257
1258         drop_callback (); /* EMIT SIGNAL */
1259 }
1260
1261 void
1262 LuaCallback::reconnect ()
1263 {
1264         _connections.drop_connections ();
1265         if ((*_lua_get) ().isNil ()) {
1266                 drop_callback (); /* EMIT SIGNAL */
1267                 return;
1268         }
1269
1270         // TODO pass object which emits the signal (e.g region)
1271         //
1272         // save/load bound objects will be tricky.
1273         // Best idea so far is to save/lookup the PBD::ID
1274         // (either use boost::any indirection or templates for bindable
1275         // object types or a switch statement..)
1276         //
1277         // _session->route_by_id ()
1278         // _session->track_by_diskstream_id ()
1279         // _session->source_by_id ()
1280         // _session->controllable_by_id ()
1281         // _session->processor_by_id ()
1282         // RegionFactory::region_by_id ()
1283         //
1284         // TODO loop over objects (if any)
1285
1286         reconnect_object ((void*)0);
1287 }
1288
1289 template <class T> void
1290 LuaCallback::reconnect_object (T obj)
1291 {
1292         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1293                 if (_signals[i]) {
1294 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1295 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1296 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1297                         if (0) {}
1298 #                       include "luasignal_syms.h"
1299                         else {
1300                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1301                                 abort(); /*NOTREACHED*/
1302                         }
1303 #undef ENGINE
1304 #undef SESSION
1305 #undef STATIC
1306                 }
1307         }
1308 }
1309
1310 template <typename T, typename S> void
1311 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1312         signal->connect (
1313                         _connections, invalidator (*this),
1314                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1315                         gui_context());
1316 }
1317
1318 template <typename T, typename C1> void
1319 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1320         signal->connect (
1321                         _connections, invalidator (*this),
1322                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1323                         gui_context());
1324 }
1325
1326 template <typename T, typename C1, typename C2> void
1327 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1328         signal->connect (
1329                         _connections, invalidator (*this),
1330                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1331                         gui_context());
1332 }
1333
1334 template <typename T> void
1335 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1336         luabridge::LuaRef rv ((*_lua_call)((int)ls, ref));
1337         if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}
1338 }
1339
1340 template <typename T, typename C1> void
1341 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1342         luabridge::LuaRef rv ((*_lua_call)((int)ls, ref, a1));
1343         if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}
1344 }
1345
1346 template <typename T, typename C1, typename C2> void
1347 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1348         luabridge::LuaRef rv ((*_lua_call)((int)ls, ref, a1, a2));
1349         if (! rv.cast<bool> ()) { drop_callback (); /* EMIT SIGNAL */}
1350 }