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