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