add Lua bindings for reference counted Cairo::ImageSurface
[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 #include <cairomm/surface.h>
21
22 #include "gtkmm2ext/gui_thread.h"
23
24 #include "ardour/audioengine.h"
25 #include "ardour/diskstream.h"
26 #include "ardour/plugin_manager.h"
27 #include "ardour/route.h"
28 #include "ardour/session.h"
29
30 #include "LuaBridge/LuaBridge.h"
31
32 #include "ardour_ui.h"
33 #include "public_editor.h"
34 #include "region_selection.h"
35 #include "luainstance.h"
36 #include "luasignal.h"
37 #include "marker.h"
38 #include "time_axis_view.h"
39 #include "selection.h"
40 #include "script_selector.h"
41
42 #include "i18n.h"
43
44 namespace LuaCairo {
45 /** wrap RefPtr< Cairo::ImageSurface >
46  *
47  * Image surfaces provide the ability to render to memory buffers either
48  * allocated by cairo or by the calling code. The supported image formats are
49  * those defined in Cairo::Format.
50  */
51 class ImageSurface {
52         public:
53                 /**
54                  * Creates an image surface of the specified format and dimensions. Initially
55                  * the surface contents are all 0. (Specifically, within each pixel, each
56                  * color or alpha channel belonging to format will be 0. The contents of bits
57                  * within a pixel, but not belonging to the given format are undefined).
58                  *
59                  * @param format        format of pixels in the surface to create
60                  * @param width         width of the surface, in pixels
61                  * @param height        height of the surface, in pixels
62                  */
63                 ImageSurface (Cairo::Format format, int width, int height)
64                         : _surface (Cairo::ImageSurface::create (format, width, height))
65                         , _ctx (Cairo::Context::create (_surface))
66                         , ctx (_ctx->cobj ()) {}
67
68                 ~ImageSurface () {}
69
70                 /**
71                  * Set this surface as source for another context.
72                  * This allows to draw this surface
73                  */
74                 void set_as_source (Cairo::Context* c, int x, int y) {
75                         _surface->flush ();
76                         c->set_source (_surface, x, y);
77                 }
78
79                 /**
80                  * Returns a context object to perform operations on the surface
81                  */
82                 Cairo::Context* context () {
83                         return (Cairo::Context *)&ctx;
84                 }
85
86                 /**
87                  * Returns the stride of the image surface in bytes (or 0 if surface is not
88                  * an image surface). The stride is the distance in bytes from the beginning
89                  * of one row of the image data to the beginning of the next row.
90                  */
91                 int get_stride () const {
92                         return _surface->get_stride ();
93                 }
94
95                 /** Gets the width of the ImageSurface in pixels */
96                 int get_width () const {
97                         return _surface->get_width ();
98                 }
99
100                 /** Gets the height of the ImageSurface in pixels */
101                 int get_height () const {
102                         return _surface->get_height ();
103                 }
104
105                 /**
106                  * Get a pointer to the data of the image surface, for direct
107                  * inspection or modification.
108                  *
109                  * Return value: a pointer to the image data of this surface or NULL
110                  * if @surface is not an image surface.
111                  *
112                  */
113                 unsigned char* get_data () {
114                         return _surface->get_data ();
115                 }
116
117                 /** Tells cairo to consider the data buffer dirty.
118                  *
119                  * In particular, if you've created an ImageSurface with a data buffer that
120                  * you've allocated yourself and you draw to that data buffer using means
121                  * other than cairo, you must call mark_dirty() before doing any additional
122                  * drawing to that surface with cairo.
123                  *
124                  * Note that if you do draw to the Surface outside of cairo, you must call
125                  * flush() before doing the drawing.
126                  */
127                 void mark_dirty () {
128                         _surface->mark_dirty ();
129                 }
130
131                 /** Marks a rectangular area of the given surface dirty.
132                  *
133                  * @param x      X coordinate of dirty rectangle
134                  * @param y     Y coordinate of dirty rectangle
135                  * @param width         width of dirty rectangle
136                  * @param height        height of dirty rectangle
137                  */
138                 void mark_dirty (int x, int y, int width, int height) {
139                         _surface->mark_dirty (x, y, width, height);
140                 }
141
142         private:
143                 Cairo::RefPtr<Cairo::ImageSurface> _surface;
144                 Cairo::RefPtr<Cairo::Context> _ctx;
145                 Cairo::Context ctx;
146 };
147 }; // namespace
148
149 ////////////////////////////////////////////////////////////////////////////////
150
151 namespace LuaSignal {
152
153 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
154 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
155 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
156
157 LuaSignal
158 str2luasignal (const std::string &str) {
159         const char* type = str.c_str();
160         if (0) { }
161 #       include "luasignal_syms.h"
162         else {
163                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
164                 abort(); /*NOTREACHED*/
165         }
166 }
167 #undef STATIC
168 #undef SESSION
169 #undef ENGINE
170
171 #define STATIC(name,c,p) N_(#name),
172 #define SESSION(name,c,p) N_(#name),
173 #define ENGINE(name,c,p) N_(#name),
174 const char *luasignalstr[] = {
175 #       include "luasignal_syms.h"
176         0
177 };
178
179 #undef STATIC
180 #undef SESSION
181 #undef ENGINE
182 }; // namespace
183
184 ////////////////////////////////////////////////////////////////////////////////
185
186 #define xstr(s) stringify(s)
187 #define stringify(s) #s
188
189 using namespace ARDOUR;
190
191 void
192 LuaInstance::register_hooks (lua_State* L)
193 {
194
195 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
196 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
197 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
198         luabridge::getGlobalNamespace (L)
199                 .beginNamespace ("LuaSignal")
200 #               include "luasignal_syms.h"
201                 .endNamespace ();
202 #undef ENGINE
203 #undef SESSION
204 #undef STATIC
205
206         luabridge::getGlobalNamespace (L)
207                 .beginNamespace ("LuaSignal")
208                 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
209                 .endClass()
210                 .endNamespace ();
211 }
212
213 void
214 LuaInstance::bind_cairo (lua_State* L)
215 {
216         /* std::vector<double> for set_dash()
217          * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
218          *
219          * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
220          * the address of the one in libardour.dll is mapped when loading the .dll
221          *
222          * see LuaBindings::set_session() for a detailed explanation
223          */
224         luabridge::getGlobalNamespace (L)
225                 .beginNamespace ("C")
226                 .beginStdVector <double> ("DoubleVector")
227                 .endClass ()
228                 .endNamespace ();
229
230         luabridge::getGlobalNamespace (L)
231                 .beginNamespace ("Cairo")
232                 .beginClass <Cairo::Context> ("Context")
233                 .addFunction ("save", &Cairo::Context::save)
234                 .addFunction ("restore", &Cairo::Context::restore)
235                 .addFunction ("set_operator", &Cairo::Context::set_operator)
236                 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
237                 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
238                 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
239                 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
240                 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
241                 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
242                 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
243                 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
244                 .addFunction ("translate", &Cairo::Context::translate)
245                 .addFunction ("scale", &Cairo::Context::scale)
246                 .addFunction ("rotate", &Cairo::Context::rotate)
247                 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
248                 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
249                 .addFunction ("move_to", &Cairo::Context::move_to)
250                 .addFunction ("line_to", &Cairo::Context::line_to)
251                 .addFunction ("curve_to", &Cairo::Context::curve_to)
252                 .addFunction ("arc", &Cairo::Context::arc)
253                 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
254                 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
255                 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
256                 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
257                 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
258                 .addFunction ("close_path", &Cairo::Context::close_path)
259                 .addFunction ("paint", &Cairo::Context::paint)
260                 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
261                 .addFunction ("stroke", &Cairo::Context::stroke)
262                 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
263                 .addFunction ("fill", &Cairo::Context::fill)
264                 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
265                 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
266                 .addFunction ("clip", &Cairo::Context::clip)
267                 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
268                 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
269                 .addFunction ("show_text", &Cairo::Context::show_text)
270                 .endClass ()
271                 /* enums */
272                 // LineCap, LineJoin, Operator
273                 .beginNamespace ("LineCap")
274                 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
275                 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
276                 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
277                 .endNamespace ()
278
279                 .beginNamespace ("LineJoin")
280                 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
281                 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
282                 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
283                 .endNamespace ()
284
285                 .beginNamespace ("Operator")
286                 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
287                 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
288                 .addConst ("Over", CAIRO_OPERATOR_OVER)
289                 .addConst ("Add", CAIRO_OPERATOR_ADD)
290                 .endNamespace ()
291
292                 .beginNamespace ("Format")
293                 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
294                 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
295                 .endNamespace ()
296
297                 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
298                 .addConstructor <void (*) (Cairo::Format, int, int)> ()
299                 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
300                 .addFunction ("context", &LuaCairo::ImageSurface::context)
301                 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
302                 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
303                 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
304                 .addFunction ("get_data", &LuaCairo::ImageSurface::get_data)
305                 .endClass ()
306
307                 .endNamespace ();
308
309 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
310   one can work around this as follows:
311
312   LuaState lua;
313   LuaInstance::register_classes (lua.getState());
314   lua.do_command (
315       "function render (ctx)"
316       "  ctx:rectangle (0, 0, 100, 100)"
317       "  ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
318       "  ctx:fill ()"
319       " end"
320       );
321   {
322                 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
323     Cairo::Context ctx (context->cobj ());
324
325     luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
326     lua_render ((Cairo::Context *)&ctx);
327   }
328 */
329
330 }
331
332 void
333 LuaInstance::register_classes (lua_State* L)
334 {
335         LuaBindings::stddef (L);
336         LuaBindings::common (L);
337         LuaBindings::session (L);
338         LuaBindings::osc (L);
339
340         bind_cairo (L);
341         register_hooks (L);
342
343         luabridge::getGlobalNamespace (L)
344                 .beginNamespace ("ArdourUI")
345
346                 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
347                 .endClass ()
348
349                 .beginClass <ArdourMarker> ("ArdourMarker")
350                 .addFunction ("name", &ArdourMarker::name)
351                 .addFunction ("position", &ArdourMarker::position)
352                 .addFunction ("_type", &ArdourMarker::type)
353                 .endClass ()
354
355 #if 0
356                 .beginClass <AxisView> ("AxisView")
357                 .endClass ()
358                 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
359                 .endClass ()
360                 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
361                 .endClass ()
362 #endif
363
364                 .beginClass <RegionSelection> ("RegionSelection")
365                 .addFunction ("clear_all", &RegionSelection::clear_all)
366                 .addFunction ("start", &RegionSelection::start)
367                 .addFunction ("end_frame", &RegionSelection::end_frame)
368                 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
369                 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
370                 .endClass ()
371
372                 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
373                 .addFunction ("start", &TimeSelection::start)
374                 .addFunction ("end_frame", &TimeSelection::end_frame)
375                 .addFunction ("length", &TimeSelection::length)
376                 .endClass ()
377
378                 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
379                 .endClass ()
380
381                 .beginClass <TrackViewList> ("TrackViewList")
382                 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
383                 .endClass ()
384
385                 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
386                 .endClass ()
387
388                 .beginClass <Selection> ("Selection")
389                 .addFunction ("clear", &Selection::clear)
390                 .addFunction ("clear_all", &Selection::clear_all)
391                 .addFunction ("empty", &Selection::empty)
392                 .addData ("tracks", &Selection::tracks)
393                 .addData ("regions", &Selection::regions)
394                 .addData ("time", &Selection::time)
395                 .addData ("markers", &Selection::markers)
396 #if 0
397                 .addData ("lines", &Selection::lines)
398                 .addData ("playlists", &Selection::playlists)
399                 .addData ("points", &Selection::points)
400                 .addData ("midi_regions", &Selection::midi_regions)
401                 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
402 #endif
403                 .endClass ()
404
405                 .beginClass <PublicEditor> ("Editor")
406                 .addFunction ("snap_type", &PublicEditor::snap_type)
407                 .addFunction ("snap_mode", &PublicEditor::snap_mode)
408                 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
409                 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
410
411                 .addFunction ("undo", &PublicEditor::undo)
412                 .addFunction ("redo", &PublicEditor::redo)
413
414                 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
415                 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
416
417                 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
418
419                 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
420                 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
421                 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
422                 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
423
424                 .addFunction ("get_selection", &PublicEditor::get_selection)
425                 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
426                 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
427
428                 .addFunction ("play_selection", &PublicEditor::play_selection)
429                 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
430                 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
431                 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
432
433                 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
434                 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
435
436                 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
437                 .addFunction ("show_measures", &PublicEditor::show_measures)
438                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
439
440                 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
441                 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
442
443                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
444
445                 .addRefFunction ("do_import", &PublicEditor::do_import)
446                 .addRefFunction ("do_embed", &PublicEditor::do_embed)
447
448                 .addFunction ("export_audio", &PublicEditor::export_audio)
449                 .addFunction ("stem_export", &PublicEditor::stem_export)
450                 .addFunction ("export_selection", &PublicEditor::export_selection)
451                 .addFunction ("export_range", &PublicEditor::export_range)
452
453                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
454                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
455                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
456                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
457
458 #if 0 // These need TimeAxisView* which isn't exposed, yet
459                 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
460                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
461                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
462                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
463                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
464 #endif
465
466                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
467                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
468 #if 0
469                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
470                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
471                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
472 #endif
473                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
474                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
475                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
476                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
477
478                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
479                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
480                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
481                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
482                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
483                 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
484                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
485
486                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
487                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
488                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
489                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
490
491                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
492                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
493                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
494
495                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
496
497                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
498                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
499                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
500
501                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
502                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
503
504                 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
505                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
506                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
507                 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
508
509                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
510                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
511                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
512                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
513
514 #if 0
515                 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
516                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
517
518                 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
519                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
520                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
521                 .addFunction ("drags", &PublicEditor::drags)
522 #endif
523
524                 .addFunction ("center_screen", &PublicEditor::center_screen)
525
526                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
527                 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
528
529                 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
530                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
531                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
532 #if 0
533                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
534                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
535                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
536                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
537                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
538 #endif
539
540 #if 0
541                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
542                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
543                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
544                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
545 #endif
546
547                 .addFunction ("access_action", &PublicEditor::access_action)
548                 .endClass ()
549
550                 /* ArdourUI enums */
551                 .beginNamespace ("MarkerType")
552                 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
553                 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
554                 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
555                 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
556                 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
557                 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
558                 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
559                 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
560                 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
561                 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
562                 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
563                 .endNamespace ()
564
565                 .endNamespace (); // end ArdourUI
566
567         // Editing Symbols
568
569 #undef ZOOMFOCUS
570 #undef SNAPTYPE
571 #undef SNAPMODE
572 #undef MOUSEMODE
573 #undef DISPLAYCONTROL
574 #undef IMPORTMODE
575 #undef IMPORTPOSITION
576 #undef IMPORTDISPOSITION
577
578 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
579 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
580 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
581 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
582 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
583 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
584 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
585 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
586         luabridge::getGlobalNamespace (L)
587                 .beginNamespace ("Editing")
588 #               include "editing_syms.h"
589                 .endNamespace ();
590 }
591
592 #undef xstr
593 #undef stringify
594
595 ////////////////////////////////////////////////////////////////////////////////
596
597 using namespace ARDOUR;
598 using namespace ARDOUR_UI_UTILS;
599 using namespace PBD;
600 using namespace std;
601
602 #ifndef NDEBUG
603 static void _lua_print (std::string s) {
604         std::cout << "LuaInstance: " << s << "\n";
605 }
606 #endif
607
608 LuaInstance* LuaInstance::_instance = 0;
609
610 LuaInstance*
611 LuaInstance::instance ()
612 {
613         if (!_instance) {
614                 _instance  = new LuaInstance;
615         }
616
617         return _instance;
618 }
619
620 LuaInstance::LuaInstance ()
621 {
622 #ifndef NDEBUG
623         lua.Print.connect (&_lua_print);
624 #endif
625         init ();
626
627         LuaScriptParamList args;
628 }
629
630 LuaInstance::~LuaInstance ()
631 {
632         delete _lua_call_action;
633         delete _lua_add_action;
634         delete _lua_del_action;
635         delete _lua_get_action;
636
637         delete _lua_load;
638         delete _lua_save;
639         delete _lua_clear;
640         _callbacks.clear();
641 }
642
643 void
644 LuaInstance::init ()
645 {
646         lua.do_command (
647                         "function ScriptManager ()"
648                         "  local self = { scripts = {}, instances = {} }"
649                         ""
650                         "  local remove = function (id)"
651                         "   self.scripts[id] = nil"
652                         "   self.instances[id] = nil"
653                         "  end"
654                         ""
655                         "  local addinternal = function (i, n, s, f, a)"
656                         "   assert(type(i) == 'number', 'id must be numeric')"
657                         "   assert(type(n) == 'string', 'Name must be string')"
658                         "   assert(type(s) == 'string', 'Script must be string')"
659                         "   assert(type(f) == 'function', 'Factory is a not a function')"
660                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
661                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
662                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
663                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
664                         "  end"
665                         ""
666                         "  local call = function (id)"
667                         "   if type(self.instances[id]) == 'function' then"
668                         "     local status, err = pcall (self.instances[id])"
669                         "     if not status then"
670                         "       print ('action \"'.. id .. '\": ', err)" // error out
671                         "       remove (id)"
672                         "     end"
673                         "   end"
674                         "   collectgarbage()"
675                         "  end"
676                         ""
677                         "  local add = function (i, n, s, b, a)"
678                         "   assert(type(b) == 'string', 'ByteCode must be string')"
679                         "   load (b)()" // assigns f
680                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
681                         "   addinternal (i, n, s, load(f), a)"
682                         "  end"
683                         ""
684                         "  local get = function (id)"
685                         "   if type(self.scripts[id]) == 'table' then"
686                         "    return { ['name'] = self.scripts[id]['n'],"
687                         "             ['script'] = self.scripts[id]['s'],"
688                         "             ['args'] = self.scripts[id]['a'] }"
689                         "   end"
690                         "   return nil"
691                         "  end"
692                         ""
693                         "  local function basic_serialize (o)"
694                         "    if type(o) == \"number\" then"
695                         "     return tostring(o)"
696                         "    else"
697                         "     return string.format(\"%q\", o)"
698                         "    end"
699                         "  end"
700                         ""
701                         "  local function serialize (name, value)"
702                         "   local rv = name .. ' = '"
703                         "   collectgarbage()"
704                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
705                         "    return rv .. basic_serialize(value) .. ' '"
706                         "   elseif type(value) == \"table\" then"
707                         "    rv = rv .. '{} '"
708                         "    for k,v in pairs(value) do"
709                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
710                         "     rv = rv .. serialize(fieldname, v) .. ' '"
711                         "     collectgarbage()" // string concatenation allocates a new string
712                         "    end"
713                         "    return rv;"
714                         "   elseif type(value) == \"function\" then"
715                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
716                         "   else"
717                         "    error('cannot save a ' .. type(value))"
718                         "   end"
719                         "  end"
720                         ""
721                         ""
722                         "  local save = function ()"
723                         "   return (serialize('scripts', self.scripts))"
724                         "  end"
725                         ""
726                         "  local clear = function ()"
727                         "   self.scripts = {}"
728                         "   self.instances = {}"
729                         "   collectgarbage()"
730                         "  end"
731                         ""
732                         "  local restore = function (state)"
733                         "   clear()"
734                         "   load (state)()"
735                         "   for i, s in pairs (scripts) do"
736                         "    addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
737                         "   end"
738                         "   collectgarbage()"
739                         "  end"
740                         ""
741                         " return { call = call, add = add, remove = remove, get = get,"
742                         "          restore = restore, save = save, clear = clear}"
743                         " end"
744                         " "
745                         " manager = ScriptManager ()"
746                         " ScriptManager = nil"
747                         );
748
749         lua_State* L = lua.getState();
750
751         try {
752                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
753                 lua.do_command ("manager = nil"); // hide it.
754                 lua.do_command ("collectgarbage()");
755
756                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
757                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
758                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
759                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
760                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
761                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
762                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
763
764         } catch (luabridge::LuaException const& e) {
765                 fatal << string_compose (_("programming error: %1"),
766                                 X_("Failed to setup Lua action interpreter"))
767                         << endmsg;
768                 abort(); /*NOTREACHED*/
769         }
770
771         register_classes (L);
772
773         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
774         lua_setglobal (L, "Editor");
775 }
776
777 void LuaInstance::set_session (Session* s)
778 {
779         SessionHandlePtr::set_session (s);
780         if (!_session) {
781                 return;
782         }
783
784         lua_State* L = lua.getState();
785         LuaBindings::set_session (L, _session);
786
787         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
788                 i->second->set_session (s);
789         }
790 }
791
792 void
793 LuaInstance::session_going_away ()
794 {
795         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
796         (*_lua_clear)();
797         for (int i = 0; i < 9; ++i) {
798                 ActionChanged (i, ""); /* EMIT SIGNAL */
799         }
800         SessionHandlePtr::session_going_away ();
801         _session = 0;
802
803         lua_State* L = lua.getState();
804         LuaBindings::set_session (L, _session);
805         lua.do_command ("collectgarbage();");
806 }
807
808 int
809 LuaInstance::set_state (const XMLNode& node)
810 {
811         LocaleGuard lg;
812         XMLNode* child;
813
814         if ((child = find_named_node (node, "ActionScript"))) {
815                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
816                         if (!(*n)->is_content ()) { continue; }
817                         gsize size;
818                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
819                         try {
820                                 (*_lua_load)(std::string ((const char*)buf, size));
821                         } catch (luabridge::LuaException const& e) {
822                                 cerr << "LuaException:" << e.what () << endl;
823                         }
824                         for (int i = 0; i < 9; ++i) {
825                                 std::string name;
826                                 if (lua_action_name (i, name)) {
827                                         ActionChanged (i, name); /* EMIT SIGNAL */
828                                 }
829                         }
830                         g_free (buf);
831                 }
832         }
833
834         if ((child = find_named_node (node, "ActionHooks"))) {
835                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
836                         try {
837                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
838                                 _callbacks.insert (std::make_pair(p->id(), p));
839                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
840                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
841                         } catch (luabridge::LuaException const& e) {
842                                 cerr << "LuaException:" << e.what () << endl;
843                         }
844                 }
845         }
846
847         return 0;
848 }
849
850 bool
851 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
852 {
853         std::string title;
854         std::vector<std::string> reg;
855
856         switch (type) {
857                 case LuaScriptInfo::EditorAction:
858                         reg = lua_action_names ();
859                         title = "Add Lua Action";
860                         break;
861                 case LuaScriptInfo::EditorHook:
862                         reg = lua_slot_names ();
863                         title = "Add Lua Callback Hook";
864                         break;
865                 default:
866                         return false;
867         }
868
869         LuaScriptInfoPtr spi;
870         ScriptSelector ss (title, type);
871         switch (ss.run ()) {
872                 case Gtk::RESPONSE_ACCEPT:
873                         spi = ss.script();
874                         break;
875                 default:
876                         return false;
877         }
878         ss.hide ();
879
880         std::string script = "";
881
882         try {
883                 script = Glib::file_get_contents (spi->path);
884         } catch (Glib::FileError e) {
885                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
886                 Gtk::MessageDialog am (msg);
887                 am.run ();
888                 return false;
889         }
890
891         LuaScriptParamList lsp = LuaScriptParams::script_params (spi, "action_params");
892
893         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
894         switch (spd.run ()) {
895                 case Gtk::RESPONSE_ACCEPT:
896                         break;
897                 default:
898                         return false;
899         }
900
901         switch (type) {
902                 case LuaScriptInfo::EditorAction:
903                         return set_lua_action (id, spd.name(), script, lsp);
904                         break;
905                 case LuaScriptInfo::EditorHook:
906                         return register_lua_slot (spd.name(), script, lsp);
907                         break;
908                 default:
909                         break;
910         }
911         return false;
912 }
913
914 XMLNode&
915 LuaInstance::get_action_state ()
916 {
917         LocaleGuard lg;
918         std::string saved;
919         {
920                 luabridge::LuaRef savedstate ((*_lua_save)());
921                 saved = savedstate.cast<std::string>();
922         }
923         lua.collect_garbage ();
924
925         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
926         std::string b64s (b64);
927         g_free (b64);
928
929         XMLNode* script_node = new XMLNode (X_("ActionScript"));
930         script_node->add_property (X_("lua"), LUA_VERSION);
931         script_node->add_content (b64s);
932
933         return *script_node;
934 }
935
936 XMLNode&
937 LuaInstance::get_hook_state ()
938 {
939         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
940         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
941                 script_node->add_child_nocopy (i->second->get_state ());
942         }
943         return *script_node;
944 }
945
946 void
947 LuaInstance::call_action (const int id)
948 {
949         try {
950                 (*_lua_call_action)(id + 1);
951         } catch (luabridge::LuaException const& e) {
952                 cerr << "LuaException:" << e.what () << endl;
953         }
954 }
955
956 bool
957 LuaInstance::set_lua_action (
958                 const int id,
959                 const std::string& name,
960                 const std::string& script,
961                 const LuaScriptParamList& args)
962 {
963         try {
964                 lua_State* L = lua.getState();
965                 // get bytcode of factory-function in a sandbox
966                 // (don't allow scripts to interfere)
967                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
968                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
969                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
970                         if ((*i)->optional && !(*i)->is_set) { continue; }
971                         tbl_arg[(*i)->name] = (*i)->value;
972                 }
973                 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
974                 ActionChanged (id, name); /* EMIT SIGNAL */
975         } catch (luabridge::LuaException const& e) {
976                 cerr << "LuaException:" << e.what () << endl;
977                 return false;
978         }
979         return true;
980 }
981
982 bool
983 LuaInstance::remove_lua_action (const int id)
984 {
985         try {
986                 (*_lua_del_action)(id + 1);
987         } catch (luabridge::LuaException const& e) {
988                 cerr << "LuaException:" << e.what () << endl;
989                 return false;
990         }
991         ActionChanged (id, ""); /* EMIT SIGNAL */
992         return true;
993 }
994
995 bool
996 LuaInstance::lua_action_name (const int id, std::string& rv)
997 {
998         try {
999                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1000                 if (ref.isNil()) {
1001                         return false;
1002                 }
1003                 if (ref["name"].isString()) {
1004                         rv = ref["name"].cast<std::string>();
1005                         return true;
1006                 }
1007                 return true;
1008         } catch (luabridge::LuaException const& e) {
1009                 cerr << "LuaException:" << e.what () << endl;
1010                 return false;
1011         }
1012         return false;
1013 }
1014
1015 std::vector<std::string>
1016 LuaInstance::lua_action_names ()
1017 {
1018         std::vector<std::string> rv;
1019         for (int i = 0; i < 9; ++i) {
1020                 std::string name;
1021                 if (lua_action_name (i, name)) {
1022                         rv.push_back (name);
1023                 }
1024         }
1025         return rv;
1026 }
1027
1028 bool
1029 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1030 {
1031         try {
1032                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1033                 if (ref.isNil()) {
1034                         return false;
1035                 }
1036                 if (!ref["name"].isString()) {
1037                         return false;
1038                 }
1039                 if (!ref["script"].isString()) {
1040                         return false;
1041                 }
1042                 if (!ref["args"].isTable()) {
1043                         return false;
1044                 }
1045                 name = ref["name"].cast<std::string>();
1046                 script = ref["script"].cast<std::string>();
1047
1048                 args.clear();
1049                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1050                 if (!lsi) {
1051                         return false;
1052                 }
1053                 args = LuaScriptParams::script_params (lsi, "action_params");
1054                 luabridge::LuaRef rargs (ref["args"]);
1055                 LuaScriptParams::ref_to_params (args, &rargs);
1056                 return true;
1057         } catch (luabridge::LuaException const& e) {
1058                 cerr << "LuaException:" << e.what () << endl;
1059                 return false;
1060         }
1061         return false;
1062 }
1063
1064 bool
1065 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1066 {
1067         /* parse script, get ActionHook(s) from script */
1068         ActionHook ah;
1069         try {
1070                 LuaState l;
1071 #ifndef NDEBUG
1072                 l.Print.connect (&_lua_print);
1073 #endif
1074                 lua_State* L = l.getState();
1075                 register_hooks (L);
1076                 l.do_command ("function ardour () end");
1077                 l.do_command (script);
1078                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1079                 if (signals.isFunction()) {
1080                         ah = signals();
1081                 }
1082         } catch (luabridge::LuaException const& e) {
1083                 cerr << "LuaException:" << e.what () << endl;
1084         }
1085
1086         if (ah.none ()) {
1087                 cerr << "Script registered no hooks." << endl;
1088                 return false;
1089         }
1090
1091         /* register script w/args, get entry-point / ID */
1092
1093         try {
1094                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1095                 _callbacks.insert (std::make_pair(p->id(), p));
1096                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1097                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1098                 return true;
1099         } catch (luabridge::LuaException const& e) {
1100                 cerr << "LuaException:" << e.what () << endl;
1101         }
1102         return false;
1103 }
1104
1105 bool
1106 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1107 {
1108         LuaCallbackMap::iterator i = _callbacks.find (id);
1109         if (i != _callbacks.end()) {
1110                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1111                 _callbacks.erase (i);
1112                 return true;
1113         }
1114         return false;
1115 }
1116
1117 std::vector<PBD::ID>
1118 LuaInstance::lua_slots () const
1119 {
1120         std::vector<PBD::ID> rv;
1121         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1122                 rv.push_back (i->first);
1123         }
1124         return rv;
1125 }
1126
1127 bool
1128 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1129 {
1130         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1131         if (i != _callbacks.end()) {
1132                 name = i->second->name();
1133                 return true;
1134         }
1135         return false;
1136 }
1137
1138 std::vector<std::string>
1139 LuaInstance::lua_slot_names () const
1140 {
1141         std::vector<std::string> rv;
1142         std::vector<PBD::ID> ids = lua_slots();
1143         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1144                 std::string name;
1145                 if (lua_slot_name (*i, name)) {
1146                         rv.push_back (name);
1147                 }
1148         }
1149         return rv;
1150 }
1151
1152 bool
1153 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1154 {
1155         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1156         if (i == _callbacks.end()) {
1157                 return false; // error
1158         }
1159         return i->second->lua_slot (name, script, ah, args);
1160 }
1161
1162 ///////////////////////////////////////////////////////////////////////////////
1163
1164 LuaCallback::LuaCallback (Session *s,
1165                 const std::string& name,
1166                 const std::string& script,
1167                 const ActionHook& ah,
1168                 const ARDOUR::LuaScriptParamList& args)
1169         : SessionHandlePtr (s)
1170         , _id ("0")
1171         , _name (name)
1172         , _signals (ah)
1173 {
1174         // TODO: allow to reference object (e.g region)
1175         init ();
1176
1177         lua_State* L = lua.getState();
1178         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1179         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1180                 if ((*i)->optional && !(*i)->is_set) { continue; }
1181                 tbl_arg[(*i)->name] = (*i)->value;
1182         }
1183
1184         try {
1185         const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1186         (*_lua_add)(name, script, bytecode, tbl_arg);
1187         } catch (luabridge::LuaException const& e) {
1188                 cerr << "LuaException:" << e.what () << endl;
1189                 throw failed_constructor ();
1190         }
1191
1192         _id.reset ();
1193         set_session (s);
1194 }
1195
1196 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1197         : SessionHandlePtr (s)
1198 {
1199         XMLNode* child = NULL;
1200         if (node.name() != X_("LuaCallback")
1201                         || !node.property ("signals")
1202                         || !node.property ("id")
1203                         || !node.property ("name")) {
1204                 throw failed_constructor ();
1205         }
1206
1207         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1208                 if (!(*n)->is_content ()) { continue; }
1209                 child = *n;
1210         }
1211
1212         if (!child) {
1213                 throw failed_constructor ();
1214         }
1215
1216         init ();
1217
1218         _id = PBD::ID (node.property ("id")->value ());
1219         _name = node.property ("name")->value ();
1220         _signals = ActionHook (node.property ("signals")->value ());
1221
1222         gsize size;
1223         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1224         try {
1225                 (*_lua_load)(std::string ((const char*)buf, size));
1226         } catch (luabridge::LuaException const& e) {
1227                 cerr << "LuaException:" << e.what () << endl;
1228         }
1229         g_free (buf);
1230
1231         set_session (s);
1232 }
1233
1234 LuaCallback::~LuaCallback ()
1235 {
1236         delete _lua_add;
1237         delete _lua_get;
1238         delete _lua_call;
1239         delete _lua_load;
1240         delete _lua_save;
1241 }
1242
1243 XMLNode&
1244 LuaCallback::get_state (void)
1245 {
1246         std::string saved;
1247         {
1248                 luabridge::LuaRef savedstate ((*_lua_save)());
1249                 saved = savedstate.cast<std::string>();
1250         }
1251         lua.collect_garbage ();
1252
1253         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1254         std::string b64s (b64);
1255         g_free (b64);
1256
1257         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1258         script_node->add_property (X_("lua"), LUA_VERSION);
1259         script_node->add_property (X_("id"), _id.to_s ());
1260         script_node->add_property (X_("name"), _name);
1261         script_node->add_property (X_("signals"), _signals.to_string ());
1262         script_node->add_content (b64s);
1263         return *script_node;
1264 }
1265
1266 void
1267 LuaCallback::init (void)
1268 {
1269 #ifndef NDEBUG
1270         lua.Print.connect (&_lua_print);
1271 #endif
1272
1273         lua.do_command (
1274                         "function ScriptManager ()"
1275                         "  local self = { script = {}, instance = {} }"
1276                         ""
1277                         "  local addinternal = function (n, s, f, a)"
1278                         "   assert(type(n) == 'string', 'Name must be string')"
1279                         "   assert(type(s) == 'string', 'Script must be string')"
1280                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1281                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1282                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1283                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1284                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1285                         "  end"
1286                         ""
1287                         "  local call = function (...)"
1288                         "   if type(self.instance) == 'function' then"
1289                         "     local status, err = pcall (self.instance, ...)"
1290                         "     if not status then"
1291                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1292                         "       self.script = nil"
1293                         "       self.instance = nil"
1294                         "       return false"
1295                         "     end"
1296                         "   end"
1297                         "   collectgarbage()"
1298                         "   return true"
1299                         "  end"
1300                         ""
1301                         "  local add = function (n, s, b, a)"
1302                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1303                         "   load (b)()" // assigns f
1304                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1305                         "   addinternal (n, s, load(f), a)"
1306                         "  end"
1307                         ""
1308                         "  local get = function ()"
1309                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1310                         "    return { ['name'] = self.script['n'],"
1311                         "             ['script'] = self.script['s'],"
1312                         "             ['args'] = self.script['a'] }"
1313                         "   end"
1314                         "   return nil"
1315                         "  end"
1316                         ""
1317                         // code dup
1318                         ""
1319                         "  local function basic_serialize (o)"
1320                         "    if type(o) == \"number\" then"
1321                         "     return tostring(o)"
1322                         "    else"
1323                         "     return string.format(\"%q\", o)"
1324                         "    end"
1325                         "  end"
1326                         ""
1327                         "  local function serialize (name, value)"
1328                         "   local rv = name .. ' = '"
1329                         "   collectgarbage()"
1330                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1331                         "    return rv .. basic_serialize(value) .. ' '"
1332                         "   elseif type(value) == \"table\" then"
1333                         "    rv = rv .. '{} '"
1334                         "    for k,v in pairs(value) do"
1335                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1336                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1337                         "     collectgarbage()" // string concatenation allocates a new string
1338                         "    end"
1339                         "    return rv;"
1340                         "   elseif type(value) == \"function\" then"
1341                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1342                         "   else"
1343                         "    error('cannot save a ' .. type(value))"
1344                         "   end"
1345                         "  end"
1346                         ""
1347                         // end code dup
1348                         ""
1349                         "  local save = function ()"
1350                         "   return (serialize('s', self.script))"
1351                         "  end"
1352                         ""
1353                         "  local restore = function (state)"
1354                         "   self.script = {}"
1355                         "   load (state)()"
1356                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1357                         "  end"
1358                         ""
1359                         " return { call = call, add = add, get = get,"
1360                         "          restore = restore, save = save}"
1361                         " end"
1362                         " "
1363                         " manager = ScriptManager ()"
1364                         " ScriptManager = nil"
1365                         );
1366
1367         lua_State* L = lua.getState();
1368
1369         try {
1370                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1371                 lua.do_command ("manager = nil"); // hide it.
1372                 lua.do_command ("collectgarbage()");
1373
1374                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1375                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1376                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1377                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1378                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1379
1380         } catch (luabridge::LuaException const& e) {
1381                 fatal << string_compose (_("programming error: %1"),
1382                                 X_("Failed to setup Lua callback interpreter"))
1383                         << endmsg;
1384                 abort(); /*NOTREACHED*/
1385         }
1386
1387         LuaInstance::register_classes (L);
1388
1389         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1390         lua_setglobal (L, "Editor");
1391 }
1392
1393 bool
1394 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1395 {
1396         // TODO consolidate w/ LuaInstance::lua_action()
1397         try {
1398                 luabridge::LuaRef ref = (*_lua_get)();
1399                 if (ref.isNil()) {
1400                         return false;
1401                 }
1402                 if (!ref["name"].isString()) {
1403                         return false;
1404                 }
1405                 if (!ref["script"].isString()) {
1406                         return false;
1407                 }
1408                 if (!ref["args"].isTable()) {
1409                         return false;
1410                 }
1411
1412                 ah = _signals;
1413                 name = ref["name"].cast<std::string> ();
1414                 script = ref["script"].cast<std::string> ();
1415
1416                 args.clear();
1417                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1418                 if (!lsi) {
1419                         return false;
1420                 }
1421                 args = LuaScriptParams::script_params (lsi, "action_params");
1422                 luabridge::LuaRef rargs (ref["args"]);
1423                 LuaScriptParams::ref_to_params (args, &rargs);
1424                 return true;
1425         } catch (luabridge::LuaException const& e) {
1426                 cerr << "LuaException:" << e.what () << endl;
1427                 return false;
1428         }
1429         return false;
1430 }
1431
1432 void
1433 LuaCallback::set_session (ARDOUR::Session *s)
1434 {
1435         SessionHandlePtr::set_session (s);
1436
1437         if (_session) {
1438                 lua_State* L = lua.getState();
1439                 LuaBindings::set_session (L, _session);
1440         }
1441
1442         reconnect();
1443 }
1444
1445 void
1446 LuaCallback::session_going_away ()
1447 {
1448         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1449         lua.do_command ("collectgarbage();");
1450
1451         SessionHandlePtr::session_going_away ();
1452         _session = 0;
1453
1454         drop_callback (); /* EMIT SIGNAL */
1455 }
1456
1457 void
1458 LuaCallback::reconnect ()
1459 {
1460         _connections.drop_connections ();
1461         if ((*_lua_get) ().isNil ()) {
1462                 drop_callback (); /* EMIT SIGNAL */
1463                 return;
1464         }
1465
1466         // TODO pass object which emits the signal (e.g region)
1467         //
1468         // save/load bound objects will be tricky.
1469         // Best idea so far is to save/lookup the PBD::ID
1470         // (either use boost::any indirection or templates for bindable
1471         // object types or a switch statement..)
1472         //
1473         // _session->route_by_id ()
1474         // _session->track_by_diskstream_id ()
1475         // _session->source_by_id ()
1476         // _session->controllable_by_id ()
1477         // _session->processor_by_id ()
1478         // RegionFactory::region_by_id ()
1479         //
1480         // TODO loop over objects (if any)
1481
1482         reconnect_object ((void*)0);
1483 }
1484
1485 template <class T> void
1486 LuaCallback::reconnect_object (T obj)
1487 {
1488         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1489                 if (_signals[i]) {
1490 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1491 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1492 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1493                         if (0) {}
1494 #                       include "luasignal_syms.h"
1495                         else {
1496                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1497                                 abort(); /*NOTREACHED*/
1498                         }
1499 #undef ENGINE
1500 #undef SESSION
1501 #undef STATIC
1502                 }
1503         }
1504 }
1505
1506 template <typename T, typename S> void
1507 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1508         signal->connect (
1509                         _connections, invalidator (*this),
1510                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1511                         gui_context());
1512 }
1513
1514 template <typename T, typename C1> void
1515 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1516         signal->connect (
1517                         _connections, invalidator (*this),
1518                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1519                         gui_context());
1520 }
1521
1522 template <typename T, typename C1, typename C2> void
1523 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1524         signal->connect (
1525                         _connections, invalidator (*this),
1526                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1527                         gui_context());
1528 }
1529
1530 template <typename T> void
1531 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1532         bool ok = true;
1533         {
1534                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1535                 if (! rv.cast<bool> ()) {
1536                         ok = false;
1537                 }
1538         }
1539         /* destroy LuaRef ^^ first before calling drop_callback() */
1540         if (!ok) {
1541                 drop_callback (); /* EMIT SIGNAL */
1542         }
1543 }
1544
1545 template <typename T, typename C1> void
1546 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1547         bool ok = true;
1548         {
1549                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1550                 if (! rv.cast<bool> ()) {
1551                         ok = false;
1552                 }
1553         }
1554         if (!ok) {
1555                 drop_callback (); /* EMIT SIGNAL */
1556         }
1557 }
1558
1559 template <typename T, typename C1, typename C2> void
1560 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1561         bool ok = true;
1562         {
1563                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1564                 if (! rv.cast<bool> ()) {
1565                         ok = false;
1566                 }
1567         }
1568         if (!ok) {
1569                 drop_callback (); /* EMIT SIGNAL */
1570         }
1571 }