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