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