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