59ebd80e852913eb9b80ea977a38eb63aa875fa6
[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                 .beginStdCPtrList <Selectable> ("SelectionList")
601                 .endClass ()
602
603                 .beginClass <RegionSelection> ("RegionSelection")
604                 .addFunction ("start", &RegionSelection::start)
605                 .addFunction ("end_frame", &RegionSelection::end_frame)
606                 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
607                 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
608                 .endClass ()
609
610                 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
611                 .addFunction ("start", &TimeSelection::start)
612                 .addFunction ("end_frame", &TimeSelection::end_frame)
613                 .addFunction ("length", &TimeSelection::length)
614                 .endClass ()
615
616                 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
617                 .endClass ()
618
619                 .beginClass <TrackViewList> ("TrackViewList")
620                 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
621                 .endClass ()
622
623                 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
624                 .endClass ()
625
626                 .beginClass <Selection> ("Selection")
627                 .addFunction ("clear", &Selection::clear)
628                 .addFunction ("clear_all", &Selection::clear_all)
629                 .addFunction ("empty", &Selection::empty)
630                 .addData ("tracks", &Selection::tracks)
631                 .addData ("regions", &Selection::regions)
632                 .addData ("time", &Selection::time)
633                 .addData ("markers", &Selection::markers)
634 #if 0
635                 .addData ("lines", &Selection::lines)
636                 .addData ("playlists", &Selection::playlists)
637                 .addData ("points", &Selection::points)
638                 .addData ("midi_regions", &Selection::midi_regions)
639                 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
640 #endif
641                 .endClass ()
642
643                 .beginClass <PublicEditor> ("Editor")
644                 .addFunction ("snap_type", &PublicEditor::snap_type)
645                 .addFunction ("snap_mode", &PublicEditor::snap_mode)
646                 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
647                 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
648
649                 .addFunction ("undo", &PublicEditor::undo)
650                 .addFunction ("redo", &PublicEditor::redo)
651
652                 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
653                 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
654
655                 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
656
657                 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
658                 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
659                 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
660                 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
661
662                 .addFunction ("get_selection", &PublicEditor::get_selection)
663                 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
664                 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
665
666                 .addFunction ("set_selection", &PublicEditor::set_selection)
667
668                 .addFunction ("play_selection", &PublicEditor::play_selection)
669                 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
670                 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
671                 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
672
673                 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
674                 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
675
676                 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
677                 .addFunction ("show_measures", &PublicEditor::show_measures)
678                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
679
680                 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
681                 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
682
683                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
684
685                 .addRefFunction ("do_import", &PublicEditor::do_import)
686                 .addRefFunction ("do_embed", &PublicEditor::do_embed)
687
688                 .addFunction ("export_audio", &PublicEditor::export_audio)
689                 .addFunction ("stem_export", &PublicEditor::stem_export)
690                 .addFunction ("export_selection", &PublicEditor::export_selection)
691                 .addFunction ("export_range", &PublicEditor::export_range)
692
693                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
694                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
695                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
696                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
697
698 #if 0 // These need TimeAxisView* which isn't exposed, yet
699                 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
700                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
701                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
702                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
703                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
704 #endif
705
706                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
707                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
708 #if 0
709                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
710                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
711                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
712 #endif
713
714                 .addFunction ("get_regionview_from_region", &PublicEditor::get_regionview_from_region)
715                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
716                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
717                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
718                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
719
720                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
721                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
722                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
723                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
724                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
725                 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
726                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
727
728                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
729                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
730                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
731                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
732
733                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
734                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
735                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
736
737                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
738
739                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
740                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
741                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
742
743                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
744                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
745
746                 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
747                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
748                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
749                 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
750
751                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
752                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
753                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
754                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
755
756 #if 0
757                 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
758                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
759
760                 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
761                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
762                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
763                 .addFunction ("drags", &PublicEditor::drags)
764 #endif
765
766                 .addFunction ("center_screen", &PublicEditor::center_screen)
767
768                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
769                 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
770
771                 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
772                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
773                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
774 #if 0
775                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
776                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
777                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
778                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
779                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
780 #endif
781
782 #if 0
783                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
784                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
785                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
786                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
787 #endif
788
789                 .addFunction ("access_action", &PublicEditor::access_action)
790                 .endClass ()
791
792                 /* ArdourUI enums */
793                 .beginNamespace ("MarkerType")
794                 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
795                 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
796                 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
797                 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
798                 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
799                 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
800                 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
801                 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
802                 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
803                 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
804                 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
805                 .endNamespace ()
806
807                 .beginNamespace ("SelectionOp")
808                 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
809                 .addConst ("Set", Selection::Operation(Selection::Set))
810                 .addConst ("Extend", Selection::Operation(Selection::Extend))
811                 .addConst ("Add", Selection::Operation(Selection::Add))
812                 .endNamespace ()
813
814                 .endNamespace (); // end ArdourUI
815
816         // Editing Symbols
817
818 #undef ZOOMFOCUS
819 #undef SNAPTYPE
820 #undef SNAPMODE
821 #undef MOUSEMODE
822 #undef DISPLAYCONTROL
823 #undef IMPORTMODE
824 #undef IMPORTPOSITION
825 #undef IMPORTDISPOSITION
826
827 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
828 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
829 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
830 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
831 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
832 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
833 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
834 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
835         luabridge::getGlobalNamespace (L)
836                 .beginNamespace ("Editing")
837 #               include "editing_syms.h"
838                 .endNamespace ();
839 }
840
841 #undef xstr
842 #undef stringify
843
844 ////////////////////////////////////////////////////////////////////////////////
845
846 using namespace ARDOUR;
847 using namespace ARDOUR_UI_UTILS;
848 using namespace PBD;
849 using namespace std;
850
851 static void _lua_print (std::string s) {
852 #ifndef NDEBUG
853         std::cout << "LuaInstance: " << s << "\n";
854 #endif
855         PBD::info << "LuaInstance: " << s << endmsg;
856 }
857
858 LuaInstance* LuaInstance::_instance = 0;
859
860 LuaInstance*
861 LuaInstance::instance ()
862 {
863         if (!_instance) {
864                 _instance  = new LuaInstance;
865         }
866
867         return _instance;
868 }
869
870 void
871 LuaInstance::destroy_instance ()
872 {
873         delete _instance;
874         _instance = 0;
875 }
876
877 LuaInstance::LuaInstance ()
878 {
879         lua.Print.connect (&_lua_print);
880         init ();
881
882         LuaScriptParamList args;
883 }
884
885 LuaInstance::~LuaInstance ()
886 {
887         delete _lua_call_action;
888         delete _lua_render_icon;
889         delete _lua_add_action;
890         delete _lua_del_action;
891         delete _lua_get_action;
892
893         delete _lua_load;
894         delete _lua_save;
895         delete _lua_clear;
896         _callbacks.clear();
897 }
898
899 void
900 LuaInstance::init ()
901 {
902         lua.do_command (
903                         "function ScriptManager ()"
904                         "  local self = { scripts = {}, instances = {}, icons = {} }"
905                         ""
906                         "  local remove = function (id)"
907                         "   self.scripts[id] = nil"
908                         "   self.instances[id] = nil"
909                         "   self.icons[id] = nil"
910                         "  end"
911                         ""
912                         "  local addinternal = function (i, n, s, f, c, a)"
913                         "   assert(type(i) == 'number', 'id must be numeric')"
914                         "   assert(type(n) == 'string', 'Name must be string')"
915                         "   assert(type(s) == 'string', 'Script must be string')"
916                         "   assert(type(f) == 'function', 'Factory is a not a function')"
917                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
918                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
919                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
920                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
921                         "   if type(c) == 'function' then"
922                         "     self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
923                         "   else"
924                         "     self.icons[i] = nil"
925                         "   end"
926                         "  end"
927                         ""
928                         "  local call = function (id)"
929                         "   if type(self.instances[id]) == 'function' then"
930                         "     local status, err = pcall (self.instances[id])"
931                         "     if not status then"
932                         "       print ('action \"'.. id .. '\": ', err)" // error out
933                         "       remove (id)"
934                         "     end"
935                         "   end"
936                         "   collectgarbage()"
937                         "  end"
938                         ""
939                         "  local icon = function (id, ...)"
940                         "   if type(self.icons[id]) == 'function' then"
941                         "     pcall (self.icons[id], ...)"
942                         "   end"
943                         "   collectgarbage()"
944                         "  end"
945                         ""
946                         "  local add = function (i, n, s, b, c, a)"
947                         "   assert(type(b) == 'string', 'ByteCode must be string')"
948                         "   f = nil load (b)()" // assigns f
949                         "   icn = nil load (c)()" // may assign "icn"
950                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
951                         "   addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
952                         "  end"
953                         ""
954                         "  local get = function (id)"
955                         "   if type(self.scripts[id]) == 'table' then"
956                         "    return { ['name'] = self.scripts[id]['n'],"
957                         "             ['script'] = self.scripts[id]['s'],"
958                         "             ['icon'] = type(self.scripts[id]['c']) == 'function',"
959                         "             ['args'] = self.scripts[id]['a'] }"
960                         "   end"
961                         "   return nil"
962                         "  end"
963                         ""
964                         "  local function basic_serialize (o)"
965                         "    if type(o) == \"number\" then"
966                         "     return tostring(o)"
967                         "    else"
968                         "     return string.format(\"%q\", o)"
969                         "    end"
970                         "  end"
971                         ""
972                         "  local function serialize (name, value)"
973                         "   local rv = name .. ' = '"
974                         "   collectgarbage()"
975                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
976                         "    return rv .. basic_serialize(value) .. ' '"
977                         "   elseif type(value) == \"table\" then"
978                         "    rv = rv .. '{} '"
979                         "    for k,v in pairs(value) do"
980                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
981                         "     rv = rv .. serialize(fieldname, v) .. ' '"
982                         "     collectgarbage()" // string concatenation allocates a new string
983                         "    end"
984                         "    return rv;"
985                         "   elseif type(value) == \"function\" then"
986                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
987                         "   elseif type(value) == \"boolean\" then"
988                         "     return rv .. tostring (value)"
989                         "   else"
990                         "    error('cannot save a ' .. type(value))"
991                         "   end"
992                         "  end"
993                         ""
994                         ""
995                         "  local save = function ()"
996                         "   return (serialize('scripts', self.scripts))"
997                         "  end"
998                         ""
999                         "  local clear = function ()"
1000                         "   self.scripts = {}"
1001                         "   self.instances = {}"
1002                         "   self.icons = {}"
1003                         "   collectgarbage()"
1004                         "  end"
1005                         ""
1006                         "  local restore = function (state)"
1007                         "   clear()"
1008                         "   load (state)()"
1009                         "   for i, s in pairs (scripts) do"
1010                         "    addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1011                         "   end"
1012                         "   collectgarbage()"
1013                         "  end"
1014                         ""
1015                         " return { call = call, add = add, remove = remove, get = get,"
1016                         "          restore = restore, save = save, clear = clear, icon = icon}"
1017                         " end"
1018                         " "
1019                         " manager = ScriptManager ()"
1020                         " ScriptManager = nil"
1021                         );
1022
1023         lua_State* L = lua.getState();
1024
1025         try {
1026                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1027                 lua.do_command ("manager = nil"); // hide it.
1028                 lua.do_command ("collectgarbage()");
1029
1030                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1031                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1032                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1033                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1034                 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1035                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1036                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1037                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1038
1039         } catch (luabridge::LuaException const& e) {
1040                 fatal << string_compose (_("programming error: %1"),
1041                                 X_("Failed to setup Lua action interpreter"))
1042                         << endmsg;
1043                 abort(); /*NOTREACHED*/
1044         }
1045
1046         register_classes (L);
1047
1048         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1049         lua_setglobal (L, "Editor");
1050 }
1051
1052 void LuaInstance::set_session (Session* s)
1053 {
1054         SessionHandlePtr::set_session (s);
1055         if (!_session) {
1056                 return;
1057         }
1058
1059         lua_State* L = lua.getState();
1060         LuaBindings::set_session (L, _session);
1061
1062         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1063                 i->second->set_session (s);
1064         }
1065         point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1066 }
1067
1068 void
1069 LuaInstance::session_going_away ()
1070 {
1071         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1072         point_one_second_connection.disconnect ();
1073
1074         (*_lua_clear)();
1075         for (int i = 0; i < 9; ++i) {
1076                 ActionChanged (i, ""); /* EMIT SIGNAL */
1077         }
1078         SessionHandlePtr::session_going_away ();
1079         _session = 0;
1080
1081         lua_State* L = lua.getState();
1082         LuaBindings::set_session (L, _session);
1083         lua.do_command ("collectgarbage();");
1084 }
1085
1086 void
1087 LuaInstance::every_point_one_seconds ()
1088 {
1089         LuaTimerDS (); // emit signal
1090 }
1091
1092 int
1093 LuaInstance::set_state (const XMLNode& node)
1094 {
1095         LocaleGuard lg;
1096         XMLNode* child;
1097
1098         if ((child = find_named_node (node, "ActionScript"))) {
1099                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1100                         if (!(*n)->is_content ()) { continue; }
1101                         gsize size;
1102                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1103                         try {
1104                                 (*_lua_load)(std::string ((const char*)buf, size));
1105                         } catch (luabridge::LuaException const& e) {
1106                                 cerr << "LuaException:" << e.what () << endl;
1107                         }
1108                         for (int i = 0; i < 9; ++i) {
1109                                 std::string name;
1110                                 if (lua_action_name (i, name)) {
1111                                         ActionChanged (i, name); /* EMIT SIGNAL */
1112                                 }
1113                         }
1114                         g_free (buf);
1115                 }
1116         }
1117
1118         if ((child = find_named_node (node, "ActionHooks"))) {
1119                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1120                         try {
1121                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1122                                 _callbacks.insert (std::make_pair(p->id(), p));
1123                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1124                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1125                         } catch (luabridge::LuaException const& e) {
1126                                 cerr << "LuaException:" << e.what () << endl;
1127                         }
1128                 }
1129         }
1130
1131         return 0;
1132 }
1133
1134 bool
1135 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1136 {
1137         std::string title;
1138         std::string param_function = "action_params";
1139         std::vector<std::string> reg;
1140
1141         switch (type) {
1142                 case LuaScriptInfo::EditorAction:
1143                         reg = lua_action_names ();
1144                         title = _("Add Lua Action");
1145                         break;
1146                 case LuaScriptInfo::EditorHook:
1147                         reg = lua_slot_names ();
1148                         title = _("Add Lua Callback Hook");
1149                         break;
1150                 case LuaScriptInfo::Session:
1151                         if (!_session) {
1152                                 return false;
1153                         }
1154                         reg = _session->registered_lua_functions ();
1155                         title = _("Add Lua Session Script");
1156                         param_function = "sess_params";
1157                         break;
1158                 default:
1159                         return false;
1160         }
1161
1162         LuaScriptInfoPtr spi;
1163         ScriptSelector ss (title, type);
1164         switch (ss.run ()) {
1165                 case Gtk::RESPONSE_ACCEPT:
1166                         spi = ss.script();
1167                         break;
1168                 default:
1169                         return false;
1170         }
1171         ss.hide ();
1172
1173         std::string script = "";
1174
1175         try {
1176                 script = Glib::file_get_contents (spi->path);
1177         } catch (Glib::FileError e) {
1178                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1179                 Gtk::MessageDialog am (msg);
1180                 am.run ();
1181                 return false;
1182         }
1183
1184         LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1185
1186         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1187         switch (spd.run ()) {
1188                 case Gtk::RESPONSE_ACCEPT:
1189                         break;
1190                 default:
1191                         return false;
1192         }
1193
1194         switch (type) {
1195                 case LuaScriptInfo::EditorAction:
1196                         return set_lua_action (id, spd.name(), script, lsp);
1197                         break;
1198                 case LuaScriptInfo::EditorHook:
1199                         return register_lua_slot (spd.name(), script, lsp);
1200                         break;
1201                 case LuaScriptInfo::Session:
1202                         try {
1203                                 _session->register_lua_function (spd.name(), script, lsp);
1204                         } catch (luabridge::LuaException const& e) {
1205                                 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1206                                 Gtk::MessageDialog am (msg);
1207                                 am.run ();
1208                         } catch (SessionException e) {
1209                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1210                                 Gtk::MessageDialog am (msg);
1211                                 am.run ();
1212                         }
1213                 default:
1214                         break;
1215         }
1216         return false;
1217 }
1218
1219 XMLNode&
1220 LuaInstance::get_action_state ()
1221 {
1222         LocaleGuard lg;
1223         std::string saved;
1224         {
1225                 luabridge::LuaRef savedstate ((*_lua_save)());
1226                 saved = savedstate.cast<std::string>();
1227         }
1228         lua.collect_garbage ();
1229
1230         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1231         std::string b64s (b64);
1232         g_free (b64);
1233
1234         XMLNode* script_node = new XMLNode (X_("ActionScript"));
1235         script_node->add_property (X_("lua"), LUA_VERSION);
1236         script_node->add_content (b64s);
1237
1238         return *script_node;
1239 }
1240
1241 XMLNode&
1242 LuaInstance::get_hook_state ()
1243 {
1244         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1245         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1246                 script_node->add_child_nocopy (i->second->get_state ());
1247         }
1248         return *script_node;
1249 }
1250
1251 void
1252 LuaInstance::call_action (const int id)
1253 {
1254         try {
1255                 (*_lua_call_action)(id + 1);
1256                 lua.collect_garbage_step ();
1257         } catch (luabridge::LuaException const& e) {
1258                 cerr << "LuaException:" << e.what () << endl;
1259         }
1260 }
1261
1262 void
1263 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1264         int ii = reinterpret_cast<uintptr_t> (i);
1265         instance()->render_icon (ii, cr, w, h, c);
1266 }
1267
1268 void
1269 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1270 {
1271          Cairo::Context ctx (cr);
1272          try {
1273                  (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1274          } catch (luabridge::LuaException const& e) {
1275                  cerr << "LuaException:" << e.what () << endl;
1276          }
1277 }
1278
1279 bool
1280 LuaInstance::set_lua_action (
1281                 const int id,
1282                 const std::string& name,
1283                 const std::string& script,
1284                 const LuaScriptParamList& args)
1285 {
1286         try {
1287                 lua_State* L = lua.getState();
1288                 // get bytcode of factory-function in a sandbox
1289                 // (don't allow scripts to interfere)
1290                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1291                 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1292                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1293                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1294                         if ((*i)->optional && !(*i)->is_set) { continue; }
1295                         tbl_arg[(*i)->name] = (*i)->value;
1296                 }
1297                 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1298                 ActionChanged (id, name); /* EMIT SIGNAL */
1299         } catch (luabridge::LuaException const& e) {
1300                 cerr << "LuaException:" << e.what () << endl;
1301                 return false;
1302         }
1303         _session->set_dirty ();
1304         return true;
1305 }
1306
1307 bool
1308 LuaInstance::remove_lua_action (const int id)
1309 {
1310         try {
1311                 (*_lua_del_action)(id + 1);
1312         } catch (luabridge::LuaException const& e) {
1313                 cerr << "LuaException:" << e.what () << endl;
1314                 return false;
1315         }
1316         ActionChanged (id, ""); /* EMIT SIGNAL */
1317         _session->set_dirty ();
1318         return true;
1319 }
1320
1321 bool
1322 LuaInstance::lua_action_name (const int id, std::string& rv)
1323 {
1324         try {
1325                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1326                 if (ref.isNil()) {
1327                         return false;
1328                 }
1329                 if (ref["name"].isString()) {
1330                         rv = ref["name"].cast<std::string>();
1331                         return true;
1332                 }
1333                 return true;
1334         } catch (luabridge::LuaException const& e) {
1335                 cerr << "LuaException:" << e.what () << endl;
1336                 return false;
1337         }
1338         return false;
1339 }
1340
1341 std::vector<std::string>
1342 LuaInstance::lua_action_names ()
1343 {
1344         std::vector<std::string> rv;
1345         for (int i = 0; i < 9; ++i) {
1346                 std::string name;
1347                 if (lua_action_name (i, name)) {
1348                         rv.push_back (name);
1349                 }
1350         }
1351         return rv;
1352 }
1353
1354 bool
1355 LuaInstance::lua_action_has_icon (const int id)
1356 {
1357         try {
1358                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1359                 if (ref.isNil()) {
1360                         return false;
1361                 }
1362                 if (ref["icon"].isBoolean()) {
1363                         return ref["icon"].cast<bool>();
1364                 }
1365         } catch (luabridge::LuaException const& e) {
1366                 cerr << "LuaException:" << e.what () << endl;
1367         }
1368         return false;
1369 }
1370
1371 bool
1372 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1373 {
1374         try {
1375                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1376                 if (ref.isNil()) {
1377                         return false;
1378                 }
1379                 if (!ref["name"].isString()) {
1380                         return false;
1381                 }
1382                 if (!ref["script"].isString()) {
1383                         return false;
1384                 }
1385                 if (!ref["args"].isTable()) {
1386                         return false;
1387                 }
1388                 name = ref["name"].cast<std::string>();
1389                 script = ref["script"].cast<std::string>();
1390
1391                 args.clear();
1392                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1393                 if (!lsi) {
1394                         return false;
1395                 }
1396                 args = LuaScriptParams::script_params (lsi, "action_params");
1397                 luabridge::LuaRef rargs (ref["args"]);
1398                 LuaScriptParams::ref_to_params (args, &rargs);
1399                 return true;
1400         } catch (luabridge::LuaException const& e) {
1401                 cerr << "LuaException:" << e.what () << endl;
1402                 return false;
1403         }
1404         return false;
1405 }
1406
1407 bool
1408 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1409 {
1410         /* parse script, get ActionHook(s) from script */
1411         ActionHook ah;
1412         try {
1413                 LuaState l;
1414                 l.Print.connect (&_lua_print);
1415                 lua_State* L = l.getState();
1416                 register_hooks (L);
1417                 l.do_command ("function ardour () end");
1418                 l.do_command (script);
1419                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1420                 if (signals.isFunction()) {
1421                         ah = signals();
1422                 }
1423         } catch (luabridge::LuaException const& e) {
1424                 cerr << "LuaException:" << e.what () << endl;
1425         }
1426
1427         if (ah.none ()) {
1428                 cerr << "Script registered no hooks." << endl;
1429                 return false;
1430         }
1431
1432         /* register script w/args, get entry-point / ID */
1433
1434         try {
1435                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1436                 _callbacks.insert (std::make_pair(p->id(), p));
1437                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1438                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1439                 return true;
1440         } catch (luabridge::LuaException const& e) {
1441                 cerr << "LuaException:" << e.what () << endl;
1442         }
1443         _session->set_dirty ();
1444         return false;
1445 }
1446
1447 bool
1448 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1449 {
1450         LuaCallbackMap::iterator i = _callbacks.find (id);
1451         if (i != _callbacks.end()) {
1452                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1453                 _callbacks.erase (i);
1454                 return true;
1455         }
1456         _session->set_dirty ();
1457         return false;
1458 }
1459
1460 std::vector<PBD::ID>
1461 LuaInstance::lua_slots () const
1462 {
1463         std::vector<PBD::ID> rv;
1464         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1465                 rv.push_back (i->first);
1466         }
1467         return rv;
1468 }
1469
1470 bool
1471 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1472 {
1473         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1474         if (i != _callbacks.end()) {
1475                 name = i->second->name();
1476                 return true;
1477         }
1478         return false;
1479 }
1480
1481 std::vector<std::string>
1482 LuaInstance::lua_slot_names () const
1483 {
1484         std::vector<std::string> rv;
1485         std::vector<PBD::ID> ids = lua_slots();
1486         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1487                 std::string name;
1488                 if (lua_slot_name (*i, name)) {
1489                         rv.push_back (name);
1490                 }
1491         }
1492         return rv;
1493 }
1494
1495 bool
1496 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1497 {
1498         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1499         if (i == _callbacks.end()) {
1500                 return false; // error
1501         }
1502         return i->second->lua_slot (name, script, ah, args);
1503 }
1504
1505 ///////////////////////////////////////////////////////////////////////////////
1506
1507 LuaCallback::LuaCallback (Session *s,
1508                 const std::string& name,
1509                 const std::string& script,
1510                 const ActionHook& ah,
1511                 const ARDOUR::LuaScriptParamList& args)
1512         : SessionHandlePtr (s)
1513         , _id ("0")
1514         , _name (name)
1515         , _signals (ah)
1516 {
1517         // TODO: allow to reference object (e.g region)
1518         init ();
1519
1520         lua_State* L = lua.getState();
1521         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1522         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1523                 if ((*i)->optional && !(*i)->is_set) { continue; }
1524                 tbl_arg[(*i)->name] = (*i)->value;
1525         }
1526
1527         try {
1528         const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1529         (*_lua_add)(name, script, bytecode, tbl_arg);
1530         } catch (luabridge::LuaException const& e) {
1531                 cerr << "LuaException:" << e.what () << endl;
1532                 throw failed_constructor ();
1533         }
1534
1535         _id.reset ();
1536         set_session (s);
1537 }
1538
1539 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1540         : SessionHandlePtr (s)
1541 {
1542         XMLNode* child = NULL;
1543         if (node.name() != X_("LuaCallback")
1544                         || !node.property ("signals")
1545                         || !node.property ("id")
1546                         || !node.property ("name")) {
1547                 throw failed_constructor ();
1548         }
1549
1550         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1551                 if (!(*n)->is_content ()) { continue; }
1552                 child = *n;
1553         }
1554
1555         if (!child) {
1556                 throw failed_constructor ();
1557         }
1558
1559         init ();
1560
1561         _id = PBD::ID (node.property ("id")->value ());
1562         _name = node.property ("name")->value ();
1563         _signals = ActionHook (node.property ("signals")->value ());
1564
1565         gsize size;
1566         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1567         try {
1568                 (*_lua_load)(std::string ((const char*)buf, size));
1569         } catch (luabridge::LuaException const& e) {
1570                 cerr << "LuaException:" << e.what () << endl;
1571         }
1572         g_free (buf);
1573
1574         set_session (s);
1575 }
1576
1577 LuaCallback::~LuaCallback ()
1578 {
1579         delete _lua_add;
1580         delete _lua_get;
1581         delete _lua_call;
1582         delete _lua_load;
1583         delete _lua_save;
1584 }
1585
1586 XMLNode&
1587 LuaCallback::get_state (void)
1588 {
1589         std::string saved;
1590         {
1591                 luabridge::LuaRef savedstate ((*_lua_save)());
1592                 saved = savedstate.cast<std::string>();
1593         }
1594         lua.collect_garbage ();
1595
1596         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1597         std::string b64s (b64);
1598         g_free (b64);
1599
1600         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1601         script_node->add_property (X_("lua"), LUA_VERSION);
1602         script_node->add_property (X_("id"), _id.to_s ());
1603         script_node->add_property (X_("name"), _name);
1604         script_node->add_property (X_("signals"), _signals.to_string ());
1605         script_node->add_content (b64s);
1606         return *script_node;
1607 }
1608
1609 void
1610 LuaCallback::init (void)
1611 {
1612         lua.Print.connect (&_lua_print);
1613
1614         lua.do_command (
1615                         "function ScriptManager ()"
1616                         "  local self = { script = {}, instance = {} }"
1617                         ""
1618                         "  local addinternal = function (n, s, f, a)"
1619                         "   assert(type(n) == 'string', 'Name must be string')"
1620                         "   assert(type(s) == 'string', 'Script must be string')"
1621                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1622                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1623                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1624                         "   local env = _ENV;  env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1625                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1626                         "  end"
1627                         ""
1628                         "  local call = function (...)"
1629                         "   if type(self.instance) == 'function' then"
1630                         "     local status, err = pcall (self.instance, ...)"
1631                         "     if not status then"
1632                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1633                         "       self.script = nil"
1634                         "       self.instance = nil"
1635                         "       return false"
1636                         "     end"
1637                         "   end"
1638                         "   collectgarbage()"
1639                         "   return true"
1640                         "  end"
1641                         ""
1642                         "  local add = function (n, s, b, a)"
1643                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1644                         "   load (b)()" // assigns f
1645                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1646                         "   addinternal (n, s, load(f), a)"
1647                         "  end"
1648                         ""
1649                         "  local get = function ()"
1650                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1651                         "    return { ['name'] = self.script['n'],"
1652                         "             ['script'] = self.script['s'],"
1653                         "             ['args'] = self.script['a'] }"
1654                         "   end"
1655                         "   return nil"
1656                         "  end"
1657                         ""
1658                         // code dup
1659                         ""
1660                         "  local function basic_serialize (o)"
1661                         "    if type(o) == \"number\" then"
1662                         "     return tostring(o)"
1663                         "    else"
1664                         "     return string.format(\"%q\", o)"
1665                         "    end"
1666                         "  end"
1667                         ""
1668                         "  local function serialize (name, value)"
1669                         "   local rv = name .. ' = '"
1670                         "   collectgarbage()"
1671                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1672                         "    return rv .. basic_serialize(value) .. ' '"
1673                         "   elseif type(value) == \"table\" then"
1674                         "    rv = rv .. '{} '"
1675                         "    for k,v in pairs(value) do"
1676                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1677                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1678                         "     collectgarbage()" // string concatenation allocates a new string
1679                         "    end"
1680                         "    return rv;"
1681                         "   elseif type(value) == \"function\" then"
1682                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1683                         "   elseif type(value) == \"boolean\" then"
1684                         "     return rv .. tostring (value)"
1685                         "   else"
1686                         "    error('cannot save a ' .. type(value))"
1687                         "   end"
1688                         "  end"
1689                         ""
1690                         // end code dup
1691                         ""
1692                         "  local save = function ()"
1693                         "   return (serialize('s', self.script))"
1694                         "  end"
1695                         ""
1696                         "  local restore = function (state)"
1697                         "   self.script = {}"
1698                         "   load (state)()"
1699                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1700                         "  end"
1701                         ""
1702                         " return { call = call, add = add, get = get,"
1703                         "          restore = restore, save = save}"
1704                         " end"
1705                         " "
1706                         " manager = ScriptManager ()"
1707                         " ScriptManager = nil"
1708                         );
1709
1710         lua_State* L = lua.getState();
1711
1712         try {
1713                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1714                 lua.do_command ("manager = nil"); // hide it.
1715                 lua.do_command ("collectgarbage()");
1716
1717                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1718                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1719                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1720                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1721                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1722
1723         } catch (luabridge::LuaException const& e) {
1724                 fatal << string_compose (_("programming error: %1"),
1725                                 X_("Failed to setup Lua callback interpreter"))
1726                         << endmsg;
1727                 abort(); /*NOTREACHED*/
1728         }
1729
1730         LuaInstance::register_classes (L);
1731
1732         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1733         lua_setglobal (L, "Editor");
1734 }
1735
1736 bool
1737 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1738 {
1739         // TODO consolidate w/ LuaInstance::lua_action()
1740         try {
1741                 luabridge::LuaRef ref = (*_lua_get)();
1742                 if (ref.isNil()) {
1743                         return false;
1744                 }
1745                 if (!ref["name"].isString()) {
1746                         return false;
1747                 }
1748                 if (!ref["script"].isString()) {
1749                         return false;
1750                 }
1751                 if (!ref["args"].isTable()) {
1752                         return false;
1753                 }
1754
1755                 ah = _signals;
1756                 name = ref["name"].cast<std::string> ();
1757                 script = ref["script"].cast<std::string> ();
1758
1759                 args.clear();
1760                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1761                 if (!lsi) {
1762                         return false;
1763                 }
1764                 args = LuaScriptParams::script_params (lsi, "action_params");
1765                 luabridge::LuaRef rargs (ref["args"]);
1766                 LuaScriptParams::ref_to_params (args, &rargs);
1767                 return true;
1768         } catch (luabridge::LuaException const& e) {
1769                 cerr << "LuaException:" << e.what () << endl;
1770                 return false;
1771         }
1772         return false;
1773 }
1774
1775 void
1776 LuaCallback::set_session (ARDOUR::Session *s)
1777 {
1778         SessionHandlePtr::set_session (s);
1779
1780         if (!_session) {
1781                 return;
1782         }
1783
1784         lua_State* L = lua.getState();
1785         LuaBindings::set_session (L, _session);
1786
1787         reconnect();
1788 }
1789
1790 void
1791 LuaCallback::session_going_away ()
1792 {
1793         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1794         lua.do_command ("collectgarbage();");
1795
1796         SessionHandlePtr::session_going_away ();
1797         _session = 0;
1798
1799         drop_callback (); /* EMIT SIGNAL */
1800 }
1801
1802 void
1803 LuaCallback::reconnect ()
1804 {
1805         _connections.drop_connections ();
1806         if ((*_lua_get) ().isNil ()) {
1807                 drop_callback (); /* EMIT SIGNAL */
1808                 return;
1809         }
1810
1811         // TODO pass object which emits the signal (e.g region)
1812         //
1813         // save/load bound objects will be tricky.
1814         // Best idea so far is to save/lookup the PBD::ID
1815         // (either use boost::any indirection or templates for bindable
1816         // object types or a switch statement..)
1817         //
1818         // _session->route_by_id ()
1819         // _session->track_by_diskstream_id ()
1820         // _session->source_by_id ()
1821         // _session->controllable_by_id ()
1822         // _session->processor_by_id ()
1823         // RegionFactory::region_by_id ()
1824         //
1825         // TODO loop over objects (if any)
1826
1827         reconnect_object ((void*)0);
1828 }
1829
1830 template <class T> void
1831 LuaCallback::reconnect_object (T obj)
1832 {
1833         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1834                 if (_signals[i]) {
1835 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1836 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1837 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1838                         if (0) {}
1839 #                       include "luasignal_syms.h"
1840                         else {
1841                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1842                                 abort(); /*NOTREACHED*/
1843                         }
1844 #undef ENGINE
1845 #undef SESSION
1846 #undef STATIC
1847                 }
1848         }
1849 }
1850
1851 template <typename T, typename S> void
1852 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1853         signal->connect (
1854                         _connections, invalidator (*this),
1855                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1856                         gui_context());
1857 }
1858
1859 template <typename T, typename C1> void
1860 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1861         signal->connect (
1862                         _connections, invalidator (*this),
1863                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1864                         gui_context());
1865 }
1866
1867 template <typename T, typename C1, typename C2> void
1868 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1869         signal->connect (
1870                         _connections, invalidator (*this),
1871                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1872                         gui_context());
1873 }
1874
1875 template <typename T> void
1876 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1877         bool ok = true;
1878         {
1879                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1880                 if (! rv.cast<bool> ()) {
1881                         ok = false;
1882                 }
1883         }
1884         /* destroy LuaRef ^^ first before calling drop_callback() */
1885         if (!ok) {
1886                 drop_callback (); /* EMIT SIGNAL */
1887         }
1888 }
1889
1890 template <typename T, typename C1> void
1891 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1892         bool ok = true;
1893         {
1894                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1895                 if (! rv.cast<bool> ()) {
1896                         ok = false;
1897                 }
1898         }
1899         if (!ok) {
1900                 drop_callback (); /* EMIT SIGNAL */
1901         }
1902 }
1903
1904 template <typename T, typename C1, typename C2> void
1905 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1906         bool ok = true;
1907         {
1908                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1909                 if (! rv.cast<bool> ()) {
1910                         ok = false;
1911                 }
1912         }
1913         if (!ok) {
1914                 drop_callback (); /* EMIT SIGNAL */
1915         }
1916 }