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