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