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