Lua may call C++ functions with throw. Catch them
[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 static PBD::ScopedConnectionList _luaexecs;
374
375 static void reaper (ARDOUR::SystemExec* x)
376 {
377         delete x;
378 }
379
380 static int
381 lua_forkexec (lua_State *L)
382 {
383         int argc = lua_gettop (L);
384         if (argc == 0) {
385                 return luaL_argerror (L, 1, "invalid number of arguments, forkexec (command, ...)");
386         }
387         // args are free()ed in ~SystemExec
388         char** args = (char**) malloc ((argc + 1) * sizeof(char*));
389         for (int i = 0; i < argc; ++i) {
390                 args[i] = strdup (luaL_checkstring (L, i + 1));
391         }
392         args[argc] = 0;
393
394         ARDOUR::SystemExec* x = new ARDOUR::SystemExec (args[0], args);
395         x->Terminated.connect (_luaexecs, MISSING_INVALIDATOR, boost::bind (&reaper, x), gui_context());
396
397         if (x->start()) {
398                 reaper (x);
399                 luabridge::Stack<bool>::push (L, false);
400                 return -1;
401         } else {
402                 luabridge::Stack<bool>::push (L, false);
403         }
404         return 1;
405 }
406
407 #ifndef PLATFORM_WINDOWS
408 static int
409 lua_exec (std::string cmd)
410 {
411         // args are free()ed in ~SystemExec
412         char** args = (char**) malloc (4 * sizeof(char*));
413         args[0] = strdup ("/bin/sh");
414         args[1] = strdup ("-c");
415         args[2] = strdup (cmd.c_str());
416         args[3] = 0;
417         ARDOUR::SystemExec x ("/bin/sh", args);
418         if (x.start()) {
419                 return -1;
420         }
421         x.wait ();
422         return 0;
423 }
424 #endif
425
426 ////////////////////////////////////////////////////////////////////////////////
427
428 #define xstr(s) stringify(s)
429 #define stringify(s) #s
430
431 using namespace ARDOUR;
432
433 PBD::Signal0<void> LuaInstance::LuaTimerDS;
434 PBD::Signal0<void> LuaInstance::SetSession;
435
436 void
437 LuaInstance::register_hooks (lua_State* L)
438 {
439
440 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
441 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
442 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
443         luabridge::getGlobalNamespace (L)
444                 .beginNamespace ("LuaSignal")
445 #               include "luasignal_syms.h"
446                 .endNamespace ();
447 #undef ENGINE
448 #undef SESSION
449 #undef STATIC
450
451         luabridge::getGlobalNamespace (L)
452                 .beginNamespace ("LuaSignal")
453                 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
454                 .endClass()
455                 .endNamespace ();
456
457 #if 0 // Dump size -> libs/ardour/luabindings.cc
458         printf ("LuaInstance: registered %d signals\n", LuaSignal::LAST_SIGNAL);
459 #endif
460 }
461
462 void
463 LuaInstance::bind_cairo (lua_State* L)
464 {
465         /* std::vector<double> for set_dash()
466          * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
467          *
468          * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
469          * the address of the one in libardour.dll is mapped when loading the .dll
470          *
471          * see LuaBindings::set_session() for a detailed explanation
472          */
473         luabridge::getGlobalNamespace (L)
474                 .beginNamespace ("C")
475                 .beginStdVector <double> ("DoubleVector")
476                 .endClass ()
477                 .endNamespace ();
478
479         luabridge::getGlobalNamespace (L)
480                 .beginNamespace ("Cairo")
481                 .beginClass <Cairo::Context> ("Context")
482                 .addFunction ("save", &Cairo::Context::save)
483                 .addFunction ("restore", &Cairo::Context::restore)
484                 .addFunction ("set_operator", &Cairo::Context::set_operator)
485                 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
486                 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
487                 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
488                 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
489                 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
490                 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
491                 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
492                 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
493                 .addFunction ("translate", &Cairo::Context::translate)
494                 .addFunction ("scale", &Cairo::Context::scale)
495                 .addFunction ("rotate", &Cairo::Context::rotate)
496                 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
497                 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
498                 .addFunction ("move_to", &Cairo::Context::move_to)
499                 .addFunction ("line_to", &Cairo::Context::line_to)
500                 .addFunction ("curve_to", &Cairo::Context::curve_to)
501                 .addFunction ("arc", &Cairo::Context::arc)
502                 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
503                 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
504                 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
505                 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
506                 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
507                 .addFunction ("close_path", &Cairo::Context::close_path)
508                 .addFunction ("paint", &Cairo::Context::paint)
509                 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
510                 .addFunction ("stroke", &Cairo::Context::stroke)
511                 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
512                 .addFunction ("fill", &Cairo::Context::fill)
513                 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
514                 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
515                 .addFunction ("clip", &Cairo::Context::clip)
516                 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
517                 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
518                 .addFunction ("show_text", &Cairo::Context::show_text)
519                 .endClass ()
520                 /* enums */
521                 // LineCap, LineJoin, Operator
522                 .beginNamespace ("LineCap")
523                 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
524                 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
525                 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
526                 .endNamespace ()
527
528                 .beginNamespace ("LineJoin")
529                 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
530                 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
531                 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
532                 .endNamespace ()
533
534                 .beginNamespace ("Operator")
535                 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
536                 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
537                 .addConst ("Over", CAIRO_OPERATOR_OVER)
538                 .addConst ("Add", CAIRO_OPERATOR_ADD)
539                 .endNamespace ()
540
541                 .beginNamespace ("Format")
542                 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
543                 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
544                 .endNamespace ()
545
546                 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
547                 .addConstructor <void (*) (Cairo::Format, int, int)> ()
548                 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
549                 .addFunction ("context", &LuaCairo::ImageSurface::context)
550                 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
551                 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
552                 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
553                 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
554                 .endClass ()
555
556                 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
557                 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
558                 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
559                 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
560                 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
561                 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
562                 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
563                 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
564                 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
565                 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
566                 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
567                 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
568                 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
569                 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
570                 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
571                 .endClass ()
572
573                 /* enums */
574                 .beginNamespace ("EllipsizeMode")
575                 .addConst ("None", Pango::ELLIPSIZE_NONE)
576                 .addConst ("Start", Pango::ELLIPSIZE_START)
577                 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
578                 .addConst ("End", Pango::ELLIPSIZE_END)
579                 .endNamespace ()
580
581                 .beginNamespace ("WrapMode")
582                 .addConst ("Word", Pango::WRAP_WORD)
583                 .addConst ("Char", Pango::WRAP_CHAR)
584                 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
585                 .endNamespace ()
586
587                 .endNamespace ();
588
589 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
590   one can work around this as follows:
591
592   LuaState lua;
593   LuaInstance::register_classes (lua.getState());
594   lua.do_command (
595       "function render (ctx)"
596       "  ctx:rectangle (0, 0, 100, 100)"
597       "  ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
598       "  ctx:fill ()"
599       " end"
600       );
601   {
602                 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
603     Cairo::Context ctx (context->cobj ());
604
605     luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
606     lua_render ((Cairo::Context *)&ctx);
607   }
608 */
609
610 }
611
612 void
613 LuaInstance::bind_dialog (lua_State* L)
614 {
615         luabridge::getGlobalNamespace (L)
616                 .beginNamespace ("LuaDialog")
617
618                 .beginClass <LuaDialog::Message> ("Message")
619                 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
620                 .addFunction ("run", &LuaDialog::Message::run)
621                 .endClass ()
622
623                 .beginClass <LuaDialog::Dialog> ("Dialog")
624                 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
625                 .addCFunction ("run", &LuaDialog::Dialog::run)
626                 .endClass ()
627
628                 /* enums */
629                 .beginNamespace ("MessageType")
630                 .addConst ("Info", LuaDialog::Message::Info)
631                 .addConst ("Warning", LuaDialog::Message::Warning)
632                 .addConst ("Question", LuaDialog::Message::Question)
633                 .addConst ("Error", LuaDialog::Message::Error)
634                 .endNamespace ()
635
636                 .beginNamespace ("ButtonType")
637                 .addConst ("OK", LuaDialog::Message::OK)
638                 .addConst ("Close", LuaDialog::Message::Close)
639                 .addConst ("Cancel", LuaDialog::Message::Cancel)
640                 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
641                 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
642                 .endNamespace ()
643
644                 .beginNamespace ("Response")
645                 .addConst ("OK", 0)
646                 .addConst ("Cancel", 1)
647                 .addConst ("Close", 2)
648                 .addConst ("Yes", 3)
649                 .addConst ("No", 4)
650                 .addConst ("None", -1)
651                 .endNamespace ()
652
653                 .endNamespace ();
654
655 }
656
657 void
658 LuaInstance::register_classes (lua_State* L)
659 {
660         LuaBindings::stddef (L);
661         LuaBindings::common (L);
662         LuaBindings::session (L);
663         LuaBindings::osc (L);
664
665         bind_cairo (L);
666         bind_dialog (L);
667
668         luabridge::getGlobalNamespace (L)
669                 .beginNamespace ("ArdourUI")
670
671                 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
672
673                 .addFunction ("processor_selection", &LuaMixer::processor_selection)
674
675                 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
676                 .endClass ()
677
678                 .beginClass <ArdourMarker> ("ArdourMarker")
679                 .addFunction ("name", &ArdourMarker::name)
680                 .addFunction ("position", &ArdourMarker::position)
681                 .addFunction ("_type", &ArdourMarker::type)
682                 .endClass ()
683
684                 .beginClass <AxisView> ("AxisView")
685                 .endClass ()
686
687                 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
688                 .endClass ()
689
690                 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
691                 .endClass ()
692
693                 .beginClass <Selectable> ("Selectable")
694                 .endClass ()
695
696                 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
697                 .endClass ()
698
699                 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
700                 .endClass ()
701
702                 .deriveClass <RouteUI, Selectable> ("RouteUI")
703                 .endClass ()
704
705                 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
706                 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
707                 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
708                 .endClass ()
709
710                 // std::list<Selectable*>
711                 .beginStdCPtrList <Selectable> ("SelectionList")
712                 .endClass ()
713
714                 // std::list<TimeAxisView*>
715                 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
716                 .endClass ()
717
718
719                 .beginClass <RegionSelection> ("RegionSelection")
720                 .addFunction ("start", &RegionSelection::start)
721                 .addFunction ("end_frame", &RegionSelection::end_frame)
722                 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
723                 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
724                 .endClass ()
725
726                 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
727                 .addFunction ("start", &TimeSelection::start)
728                 .addFunction ("end_frame", &TimeSelection::end_frame)
729                 .addFunction ("length", &TimeSelection::length)
730                 .endClass ()
731
732                 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
733                 .endClass ()
734
735                 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
736                 .addFunction ("contains", &TrackViewList::contains)
737                 .addFunction ("routelist", &TrackViewList::routelist)
738                 .endClass ()
739
740                 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
741                 .endClass ()
742
743                 .beginClass <Selection> ("Selection")
744                 .addFunction ("clear", &Selection::clear)
745                 .addFunction ("clear_all", &Selection::clear_all)
746                 .addFunction ("empty", &Selection::empty)
747                 .addData ("tracks", &Selection::tracks)
748                 .addData ("regions", &Selection::regions)
749                 .addData ("time", &Selection::time)
750                 .addData ("markers", &Selection::markers)
751 #if 0
752                 .addData ("lines", &Selection::lines)
753                 .addData ("playlists", &Selection::playlists)
754                 .addData ("points", &Selection::points)
755                 .addData ("midi_regions", &Selection::midi_regions)
756                 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
757 #endif
758                 .endClass ()
759
760                 .beginClass <PublicEditor> ("Editor")
761                 .addFunction ("snap_type", &PublicEditor::snap_type)
762                 .addFunction ("snap_mode", &PublicEditor::snap_mode)
763                 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
764                 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
765
766                 .addFunction ("undo", &PublicEditor::undo)
767                 .addFunction ("redo", &PublicEditor::redo)
768
769                 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
770                 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
771
772                 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
773
774                 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
775                 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
776                 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
777                 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
778
779                 .addFunction ("get_selection", &PublicEditor::get_selection)
780                 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
781                 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
782
783                 .addFunction ("set_selection", &PublicEditor::set_selection)
784
785                 .addFunction ("play_selection", &PublicEditor::play_selection)
786                 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
787                 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
788                 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
789
790                 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
791                 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
792
793                 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
794                 .addFunction ("show_measures", &PublicEditor::show_measures)
795                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
796
797                 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
798                 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
799
800                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
801
802                 .addRefFunction ("do_import", &PublicEditor::do_import)
803                 .addRefFunction ("do_embed", &PublicEditor::do_embed)
804
805                 .addFunction ("export_audio", &PublicEditor::export_audio)
806                 .addFunction ("stem_export", &PublicEditor::stem_export)
807                 .addFunction ("export_selection", &PublicEditor::export_selection)
808                 .addFunction ("export_range", &PublicEditor::export_range)
809
810                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
811                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
812                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
813                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
814
815                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
816                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
817                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
818                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
819
820                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
821                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
822
823 #if 0 // TimeAxisView&  can't be bound (pure virtual fn)
824                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
825                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
826                 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
827 #endif
828                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
829                 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
830                 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
831                 .addFunction ("fit_selection", &PublicEditor::fit_selection)
832
833                 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
834                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
835                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
836                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
837                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
838
839                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
840                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
841                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
842                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
843                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
844                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
845
846                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
847                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
848                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
849                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
850
851                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
852                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
853                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
854
855                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
856
857                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
858                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
859                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
860
861                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
862                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
863
864                 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
865                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
866                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
867                 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
868
869                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
870                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
871                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
872                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
873
874 #if 0
875                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
876                 .addFunction ("drags", &PublicEditor::drags)
877 #endif
878
879                 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
880                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
881                 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
882                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
883
884                 .addFunction ("center_screen", &PublicEditor::center_screen)
885
886                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
887                 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
888
889                 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
890                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
891                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
892 #if 0
893                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
894                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
895                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
896                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
897                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
898 #endif
899
900 #if 0
901                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
902                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
903                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
904                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
905 #endif
906
907                 .addFunction ("access_action", &PublicEditor::access_action)
908                 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
909                 .endClass ()
910
911                 /* ArdourUI enums */
912                 .beginNamespace ("MarkerType")
913                 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
914                 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
915                 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
916                 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
917                 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
918                 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
919                 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
920                 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
921                 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
922                 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
923                 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
924                 .endNamespace ()
925
926                 .beginNamespace ("SelectionOp")
927                 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
928                 .addConst ("Set", Selection::Operation(Selection::Set))
929                 .addConst ("Extend", Selection::Operation(Selection::Extend))
930                 .addConst ("Add", Selection::Operation(Selection::Add))
931                 .endNamespace ()
932
933                 .endNamespace () // end ArdourUI
934
935                 .beginNamespace ("os")
936 #ifndef PLATFORM_WINDOWS
937                 .addFunction ("execute", &lua_exec)
938 #endif
939                 .addCFunction ("forkexec", &lua_forkexec)
940                 .endNamespace ();
941
942         // Editing Symbols
943
944 #undef ZOOMFOCUS
945 #undef SNAPTYPE
946 #undef SNAPMODE
947 #undef MOUSEMODE
948 #undef DISPLAYCONTROL
949 #undef IMPORTMODE
950 #undef IMPORTPOSITION
951 #undef IMPORTDISPOSITION
952
953 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
954 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
955 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
956 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
957 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
958 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
959 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
960 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
961         luabridge::getGlobalNamespace (L)
962                 .beginNamespace ("Editing")
963 #               include "editing_syms.h"
964                 .endNamespace ();
965 }
966
967 #undef xstr
968 #undef stringify
969
970 ////////////////////////////////////////////////////////////////////////////////
971
972 using namespace ARDOUR;
973 using namespace ARDOUR_UI_UTILS;
974 using namespace PBD;
975 using namespace std;
976
977 static void _lua_print (std::string s) {
978 #ifndef NDEBUG
979         std::cout << "LuaInstance: " << s << "\n";
980 #endif
981         PBD::info << "LuaInstance: " << s << endmsg;
982 }
983
984 LuaInstance* LuaInstance::_instance = 0;
985
986 LuaInstance*
987 LuaInstance::instance ()
988 {
989         if (!_instance) {
990                 _instance  = new LuaInstance;
991         }
992
993         return _instance;
994 }
995
996 void
997 LuaInstance::destroy_instance ()
998 {
999         delete _instance;
1000         _instance = 0;
1001 }
1002
1003 LuaInstance::LuaInstance ()
1004 {
1005         lua.Print.connect (&_lua_print);
1006         init ();
1007
1008         LuaScriptParamList args;
1009 }
1010
1011 LuaInstance::~LuaInstance ()
1012 {
1013         delete _lua_call_action;
1014         delete _lua_render_icon;
1015         delete _lua_add_action;
1016         delete _lua_del_action;
1017         delete _lua_get_action;
1018
1019         delete _lua_load;
1020         delete _lua_save;
1021         delete _lua_clear;
1022         _callbacks.clear();
1023 }
1024
1025 void
1026 LuaInstance::init ()
1027 {
1028         lua.sandbox (false);
1029         lua.do_command (
1030                         "function ScriptManager ()"
1031                         "  local self = { scripts = {}, instances = {}, icons = {} }"
1032                         ""
1033                         "  local remove = function (id)"
1034                         "   self.scripts[id] = nil"
1035                         "   self.instances[id] = nil"
1036                         "   self.icons[id] = nil"
1037                         "  end"
1038                         ""
1039                         "  local addinternal = function (i, n, s, f, c, a)"
1040                         "   assert(type(i) == 'number', 'id must be numeric')"
1041                         "   assert(type(n) == 'string', 'Name must be string')"
1042                         "   assert(type(s) == 'string', 'Script must be string')"
1043                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1044                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1045                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1046                         "   local env = _ENV; env.f = nil env.io = nil"
1047                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1048                         "   if type(c) == 'function' then"
1049                         "     self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1050                         "   else"
1051                         "     self.icons[i] = nil"
1052                         "   end"
1053                         "  end"
1054                         ""
1055                         "  local call = function (id)"
1056                         "   if type(self.instances[id]) == 'function' then"
1057                         "     local status, err = pcall (self.instances[id])"
1058                         "     if not status then"
1059                         "       print ('action \"'.. id .. '\": ', err)" // error out
1060                         "       remove (id)"
1061                         "     end"
1062                         "   end"
1063                         "   collectgarbage()"
1064                         "  end"
1065                         ""
1066                         "  local icon = function (id, ...)"
1067                         "   if type(self.icons[id]) == 'function' then"
1068                         "     pcall (self.icons[id], ...)"
1069                         "   end"
1070                         "   collectgarbage()"
1071                         "  end"
1072                         ""
1073                         "  local add = function (i, n, s, b, c, a)"
1074                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1075                         "   f = nil load (b)()" // assigns f
1076                         "   icn = nil load (c)()" // may assign "icn"
1077                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1078                         "   addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1079                         "  end"
1080                         ""
1081                         "  local get = function (id)"
1082                         "   if type(self.scripts[id]) == 'table' then"
1083                         "    return { ['name'] = self.scripts[id]['n'],"
1084                         "             ['script'] = self.scripts[id]['s'],"
1085                         "             ['icon'] = type(self.scripts[id]['c']) == 'function',"
1086                         "             ['args'] = self.scripts[id]['a'] }"
1087                         "   end"
1088                         "   return nil"
1089                         "  end"
1090                         ""
1091                         "  local function basic_serialize (o)"
1092                         "    if type(o) == \"number\" then"
1093                         "     return tostring(o)"
1094                         "    else"
1095                         "     return string.format(\"%q\", o)"
1096                         "    end"
1097                         "  end"
1098                         ""
1099                         "  local function serialize (name, value)"
1100                         "   local rv = name .. ' = '"
1101                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1102                         "    return rv .. basic_serialize(value) .. ' '"
1103                         "   elseif type(value) == \"table\" then"
1104                         "    rv = rv .. '{} '"
1105                         "    for k,v in pairs(value) do"
1106                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1107                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1108                         "    end"
1109                         "    return rv;"
1110                         "   elseif type(value) == \"function\" then"
1111                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1112                         "   elseif type(value) == \"boolean\" then"
1113                         "     return rv .. tostring (value)"
1114                         "   else"
1115                         "    error('cannot save a ' .. type(value))"
1116                         "   end"
1117                         "  end"
1118                         ""
1119                         ""
1120                         "  local save = function ()"
1121                         "   return (serialize('scripts', self.scripts))"
1122                         "  end"
1123                         ""
1124                         "  local clear = function ()"
1125                         "   self.scripts = {}"
1126                         "   self.instances = {}"
1127                         "   self.icons = {}"
1128                         "   collectgarbage()"
1129                         "  end"
1130                         ""
1131                         "  local restore = function (state)"
1132                         "   clear()"
1133                         "   load (state)()"
1134                         "   for i, s in pairs (scripts) do"
1135                         "    addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1136                         "   end"
1137                         "   collectgarbage()"
1138                         "  end"
1139                         ""
1140                         " return { call = call, add = add, remove = remove, get = get,"
1141                         "          restore = restore, save = save, clear = clear, icon = icon}"
1142                         " end"
1143                         " "
1144                         " manager = ScriptManager ()"
1145                         " ScriptManager = nil"
1146                         );
1147         lua_State* L = lua.getState();
1148
1149         try {
1150                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1151                 lua.do_command ("manager = nil"); // hide it.
1152                 lua.do_command ("collectgarbage()");
1153
1154                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1155                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1156                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1157                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1158                 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1159                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1160                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1161                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1162
1163         } catch (luabridge::LuaException const& e) {
1164                 fatal << string_compose (_("programming error: %1"),
1165                                 std::string ("Failed to setup Lua action interpreter") + e.what ())
1166                         << endmsg;
1167                 abort(); /*NOTREACHED*/
1168         } catch (...) {
1169                 fatal << string_compose (_("programming error: %1"),
1170                                 X_("Failed to setup Lua action interpreter"))
1171                         << endmsg;
1172                 abort(); /*NOTREACHED*/
1173         }
1174
1175         register_classes (L);
1176         register_hooks (L);
1177
1178         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1179         lua_setglobal (L, "Editor");
1180 }
1181
1182 void LuaInstance::set_session (Session* s)
1183 {
1184         SessionHandlePtr::set_session (s);
1185         if (!_session) {
1186                 return;
1187         }
1188
1189         lua_State* L = lua.getState();
1190         LuaBindings::set_session (L, _session);
1191
1192         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1193                 i->second->set_session (s);
1194         }
1195         point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1196         SetSession (); /* EMIT SIGNAL */
1197 }
1198
1199 void
1200 LuaInstance::session_going_away ()
1201 {
1202         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1203         point_one_second_connection.disconnect ();
1204
1205         (*_lua_clear)();
1206         for (int i = 0; i < 9; ++i) {
1207                 ActionChanged (i, ""); /* EMIT SIGNAL */
1208         }
1209         SessionHandlePtr::session_going_away ();
1210         _session = 0;
1211
1212         lua_State* L = lua.getState();
1213         LuaBindings::set_session (L, _session);
1214         lua.do_command ("collectgarbage();");
1215 }
1216
1217 void
1218 LuaInstance::every_point_one_seconds ()
1219 {
1220         LuaTimerDS (); // emit signal
1221 }
1222
1223 int
1224 LuaInstance::set_state (const XMLNode& node)
1225 {
1226         XMLNode* child;
1227
1228         if ((child = find_named_node (node, "ActionScript"))) {
1229                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1230                         if (!(*n)->is_content ()) { continue; }
1231                         gsize size;
1232                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1233                         try {
1234                                 (*_lua_load)(std::string ((const char*)buf, size));
1235                         } catch (luabridge::LuaException const& e) {
1236                                 cerr << "LuaException:" << e.what () << endl;
1237                         } catch (...) { }
1238                         for (int i = 0; i < 9; ++i) {
1239                                 std::string name;
1240                                 if (lua_action_name (i, name)) {
1241                                         ActionChanged (i, name); /* EMIT SIGNAL */
1242                                 }
1243                         }
1244                         g_free (buf);
1245                 }
1246         }
1247
1248         if ((child = find_named_node (node, "ActionHooks"))) {
1249                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1250                         try {
1251                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1252                                 _callbacks.insert (std::make_pair(p->id(), p));
1253                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1254                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1255                         } catch (luabridge::LuaException const& e) {
1256                                 cerr << "LuaException:" << e.what () << endl;
1257                         } catch (...) { }
1258                 }
1259         }
1260
1261         return 0;
1262 }
1263
1264 bool
1265 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1266 {
1267         std::string title;
1268         std::string param_function = "action_params";
1269         std::vector<std::string> reg;
1270
1271         switch (type) {
1272                 case LuaScriptInfo::EditorAction:
1273                         reg = lua_action_names ();
1274                         title = _("Add Lua Action");
1275                         break;
1276                 case LuaScriptInfo::EditorHook:
1277                         reg = lua_slot_names ();
1278                         title = _("Add Lua Callback Hook");
1279                         break;
1280                 case LuaScriptInfo::Session:
1281                         if (!_session) {
1282                                 return false;
1283                         }
1284                         reg = _session->registered_lua_functions ();
1285                         title = _("Add Lua Session Script");
1286                         param_function = "sess_params";
1287                         break;
1288                 default:
1289                         return false;
1290         }
1291
1292         LuaScriptInfoPtr spi;
1293         ScriptSelector ss (title, type);
1294         switch (ss.run ()) {
1295                 case Gtk::RESPONSE_ACCEPT:
1296                         spi = ss.script();
1297                         break;
1298                 default:
1299                         return false;
1300         }
1301         ss.hide ();
1302
1303         std::string script = "";
1304
1305         try {
1306                 script = Glib::file_get_contents (spi->path);
1307         } catch (Glib::FileError e) {
1308                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1309                 Gtk::MessageDialog am (msg);
1310                 am.run ();
1311                 return false;
1312         }
1313
1314         LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1315
1316         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1317
1318         if (!spd.need_interation ()) {
1319                 switch (spd.run ()) {
1320                         case Gtk::RESPONSE_ACCEPT:
1321                                 break;
1322                         default:
1323                                 return false;
1324                 }
1325         }
1326
1327         LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false));
1328         lsp.push_back (lspp);
1329
1330         switch (type) {
1331                 case LuaScriptInfo::EditorAction:
1332                         return set_lua_action (id, spd.name(), script, lsp);
1333                         break;
1334                 case LuaScriptInfo::EditorHook:
1335                         return register_lua_slot (spd.name(), script, lsp);
1336                         break;
1337                 case LuaScriptInfo::Session:
1338                         try {
1339                                 _session->register_lua_function (spd.name(), script, lsp);
1340                         } catch (luabridge::LuaException const& e) {
1341                                 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1342                                 Gtk::MessageDialog am (msg);
1343                                 am.run ();
1344                         } catch (SessionException e) {
1345                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1346                                 Gtk::MessageDialog am (msg);
1347                                 am.run ();
1348                         } catch (...) {
1349                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1350                                 Gtk::MessageDialog am (msg);
1351                                 am.run ();
1352                         }
1353                 default:
1354                         break;
1355         }
1356         return false;
1357 }
1358
1359 XMLNode&
1360 LuaInstance::get_action_state ()
1361 {
1362         std::string saved;
1363         {
1364                 luabridge::LuaRef savedstate ((*_lua_save)());
1365                 saved = savedstate.cast<std::string>();
1366         }
1367         lua.collect_garbage ();
1368
1369         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1370         std::string b64s (b64);
1371         g_free (b64);
1372
1373         XMLNode* script_node = new XMLNode (X_("ActionScript"));
1374         script_node->set_property (X_("lua"), LUA_VERSION);
1375         script_node->add_content (b64s);
1376
1377         return *script_node;
1378 }
1379
1380 XMLNode&
1381 LuaInstance::get_hook_state ()
1382 {
1383         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1384         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1385                 script_node->add_child_nocopy (i->second->get_state ());
1386         }
1387         return *script_node;
1388 }
1389
1390 void
1391 LuaInstance::call_action (const int id)
1392 {
1393         try {
1394                 (*_lua_call_action)(id + 1);
1395                 lua.collect_garbage_step ();
1396         } catch (luabridge::LuaException const& e) {
1397                 cerr << "LuaException:" << e.what () << endl;
1398         } catch (...) { }
1399 }
1400
1401 void
1402 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1403         int ii = reinterpret_cast<uintptr_t> (i);
1404         instance()->render_icon (ii, cr, w, h, c);
1405 }
1406
1407 void
1408 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1409 {
1410          Cairo::Context ctx (cr);
1411          try {
1412                  (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1413          } catch (luabridge::LuaException const& e) {
1414                  cerr << "LuaException:" << e.what () << endl;
1415          } catch (...) { }
1416 }
1417
1418 bool
1419 LuaInstance::set_lua_action (
1420                 const int id,
1421                 const std::string& name,
1422                 const std::string& script,
1423                 const LuaScriptParamList& args)
1424 {
1425         try {
1426                 lua_State* L = lua.getState();
1427                 // get bytcode of factory-function in a sandbox
1428                 // (don't allow scripts to interfere)
1429                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1430                 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1431                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1432                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1433                         if ((*i)->optional && !(*i)->is_set) { continue; }
1434                         tbl_arg[(*i)->name] = (*i)->value;
1435                 }
1436                 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1437                 ActionChanged (id, name); /* EMIT SIGNAL */
1438         } catch (luabridge::LuaException const& e) {
1439                 cerr << "LuaException:" << e.what () << endl;
1440                 return false;
1441         } catch (...) {
1442                 return false;
1443         }
1444         _session->set_dirty ();
1445         return true;
1446 }
1447
1448 bool
1449 LuaInstance::remove_lua_action (const int id)
1450 {
1451         try {
1452                 (*_lua_del_action)(id + 1);
1453         } catch (luabridge::LuaException const& e) {
1454                 cerr << "LuaException:" << e.what () << endl;
1455                 return false;
1456         } catch (...) {
1457                 return false;
1458         }
1459         ActionChanged (id, ""); /* EMIT SIGNAL */
1460         _session->set_dirty ();
1461         return true;
1462 }
1463
1464 bool
1465 LuaInstance::lua_action_name (const int id, std::string& rv)
1466 {
1467         try {
1468                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1469                 if (ref.isNil()) {
1470                         return false;
1471                 }
1472                 if (ref["name"].isString()) {
1473                         rv = ref["name"].cast<std::string>();
1474                         return true;
1475                 }
1476                 return true;
1477         } catch (luabridge::LuaException const& e) {
1478                 cerr << "LuaException:" << e.what () << endl;
1479         } catch (...) { }
1480         return false;
1481 }
1482
1483 std::vector<std::string>
1484 LuaInstance::lua_action_names ()
1485 {
1486         std::vector<std::string> rv;
1487         for (int i = 0; i < 9; ++i) {
1488                 std::string name;
1489                 if (lua_action_name (i, name)) {
1490                         rv.push_back (name);
1491                 }
1492         }
1493         return rv;
1494 }
1495
1496 bool
1497 LuaInstance::lua_action_has_icon (const int id)
1498 {
1499         try {
1500                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1501                 if (ref.isNil()) {
1502                         return false;
1503                 }
1504                 if (ref["icon"].isBoolean()) {
1505                         return ref["icon"].cast<bool>();
1506                 }
1507         } catch (luabridge::LuaException const& e) {
1508                 cerr << "LuaException:" << e.what () << endl;
1509         } catch (...) { }
1510         return false;
1511 }
1512
1513 bool
1514 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1515 {
1516         try {
1517                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1518                 if (ref.isNil()) {
1519                         return false;
1520                 }
1521                 if (!ref["name"].isString()) {
1522                         return false;
1523                 }
1524                 if (!ref["script"].isString()) {
1525                         return false;
1526                 }
1527                 if (!ref["args"].isTable()) {
1528                         return false;
1529                 }
1530                 name = ref["name"].cast<std::string>();
1531                 script = ref["script"].cast<std::string>();
1532
1533                 args.clear();
1534                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1535                 if (!lsi) {
1536                         return false;
1537                 }
1538                 args = LuaScriptParams::script_params (lsi, "action_params");
1539                 luabridge::LuaRef rargs (ref["args"]);
1540                 LuaScriptParams::ref_to_params (args, &rargs);
1541                 return true;
1542         } catch (luabridge::LuaException const& e) {
1543                 cerr << "LuaException:" << e.what () << endl;
1544         } catch (...) { }
1545         return false;
1546 }
1547
1548 bool
1549 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1550 {
1551         /* parse script, get ActionHook(s) from script */
1552         ActionHook ah;
1553         try {
1554                 LuaState l;
1555                 l.Print.connect (&_lua_print);
1556                 l.sandbox (true);
1557                 lua_State* L = l.getState();
1558                 register_hooks (L);
1559                 l.do_command ("function ardour () end");
1560                 l.do_command (script);
1561                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1562                 if (signals.isFunction()) {
1563                         ah = signals();
1564                 }
1565         } catch (luabridge::LuaException const& e) {
1566                 cerr << "LuaException:" << e.what () << endl;
1567         } catch (...) { }
1568
1569         if (ah.none ()) {
1570                 cerr << "Script registered no hooks." << endl;
1571                 return false;
1572         }
1573
1574         /* register script w/args, get entry-point / ID */
1575
1576         try {
1577                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1578                 _callbacks.insert (std::make_pair(p->id(), p));
1579                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1580                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1581                 return true;
1582         } catch (luabridge::LuaException const& e) {
1583                 cerr << "LuaException:" << e.what () << endl;
1584         } catch (...) { }
1585         _session->set_dirty ();
1586         return false;
1587 }
1588
1589 bool
1590 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1591 {
1592         LuaCallbackMap::iterator i = _callbacks.find (id);
1593         if (i != _callbacks.end()) {
1594                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1595                 _callbacks.erase (i);
1596                 return true;
1597         }
1598         _session->set_dirty ();
1599         return false;
1600 }
1601
1602 std::vector<PBD::ID>
1603 LuaInstance::lua_slots () const
1604 {
1605         std::vector<PBD::ID> rv;
1606         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1607                 rv.push_back (i->first);
1608         }
1609         return rv;
1610 }
1611
1612 bool
1613 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1614 {
1615         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1616         if (i != _callbacks.end()) {
1617                 name = i->second->name();
1618                 return true;
1619         }
1620         return false;
1621 }
1622
1623 std::vector<std::string>
1624 LuaInstance::lua_slot_names () const
1625 {
1626         std::vector<std::string> rv;
1627         std::vector<PBD::ID> ids = lua_slots();
1628         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1629                 std::string name;
1630                 if (lua_slot_name (*i, name)) {
1631                         rv.push_back (name);
1632                 }
1633         }
1634         return rv;
1635 }
1636
1637 bool
1638 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1639 {
1640         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1641         if (i == _callbacks.end()) {
1642                 return false; // error
1643         }
1644         return i->second->lua_slot (name, script, ah, args);
1645 }
1646
1647 ///////////////////////////////////////////////////////////////////////////////
1648
1649 LuaCallback::LuaCallback (Session *s,
1650                 const std::string& name,
1651                 const std::string& script,
1652                 const ActionHook& ah,
1653                 const ARDOUR::LuaScriptParamList& args)
1654         : SessionHandlePtr (s)
1655         , _id ("0")
1656         , _name (name)
1657         , _signals (ah)
1658 {
1659         // TODO: allow to reference object (e.g region)
1660         init ();
1661
1662         lua_State* L = lua.getState();
1663         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1664         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1665                 if ((*i)->optional && !(*i)->is_set) { continue; }
1666                 tbl_arg[(*i)->name] = (*i)->value;
1667         }
1668
1669         try {
1670                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1671                 (*_lua_add)(name, script, bytecode, tbl_arg);
1672         } catch (luabridge::LuaException const& e) {
1673                 cerr << "LuaException:" << e.what () << endl;
1674                 throw failed_constructor ();
1675         } catch (...) {
1676                 throw failed_constructor ();
1677         }
1678
1679         _id.reset ();
1680         set_session (s);
1681 }
1682
1683 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1684         : SessionHandlePtr (s)
1685 {
1686         XMLNode* child = NULL;
1687         if (node.name() != X_("LuaCallback")
1688                         || !node.property ("signals")
1689                         || !node.property ("id")
1690                         || !node.property ("name")) {
1691                 throw failed_constructor ();
1692         }
1693
1694         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1695                 if (!(*n)->is_content ()) { continue; }
1696                 child = *n;
1697         }
1698
1699         if (!child) {
1700                 throw failed_constructor ();
1701         }
1702
1703         init ();
1704
1705         _id = PBD::ID (node.property ("id")->value ());
1706         _name = node.property ("name")->value ();
1707         _signals = ActionHook (node.property ("signals")->value ());
1708
1709         gsize size;
1710         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1711         try {
1712                 (*_lua_load)(std::string ((const char*)buf, size));
1713         } catch (luabridge::LuaException const& e) {
1714                 cerr << "LuaException:" << e.what () << endl;
1715         } catch (...) { }
1716         g_free (buf);
1717
1718         set_session (s);
1719 }
1720
1721 LuaCallback::~LuaCallback ()
1722 {
1723         delete _lua_add;
1724         delete _lua_get;
1725         delete _lua_call;
1726         delete _lua_load;
1727         delete _lua_save;
1728 }
1729
1730 XMLNode&
1731 LuaCallback::get_state (void)
1732 {
1733         std::string saved;
1734         {
1735                 luabridge::LuaRef savedstate ((*_lua_save)());
1736                 saved = savedstate.cast<std::string>();
1737         }
1738
1739         lua.collect_garbage (); // this may be expensive:
1740         /* Editor::instant_save() calls Editor::get_state() which
1741          * calls LuaInstance::get_hook_state() which in turn calls
1742          * this LuaCallback::get_state() for every registered hook.
1743          *
1744          * serialize in _lua_save() allocates many small strings
1745          * on the lua-stack, collecting them all may take a ms.
1746          */
1747
1748         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1749         std::string b64s (b64);
1750         g_free (b64);
1751
1752         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1753         script_node->set_property (X_("lua"), LUA_VERSION);
1754         script_node->set_property (X_("id"), _id.to_s ());
1755         script_node->set_property (X_("name"), _name);
1756         script_node->set_property (X_("signals"), _signals.to_string ());
1757         script_node->add_content (b64s);
1758         return *script_node;
1759 }
1760
1761 void
1762 LuaCallback::init (void)
1763 {
1764         lua.Print.connect (&_lua_print);
1765         lua.sandbox (false);
1766
1767         lua.do_command (
1768                         "function ScriptManager ()"
1769                         "  local self = { script = {}, instance = {} }"
1770                         ""
1771                         "  local addinternal = function (n, s, f, a)"
1772                         "   assert(type(n) == 'string', 'Name must be string')"
1773                         "   assert(type(s) == 'string', 'Script must be string')"
1774                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1775                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1776                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1777                         "   local env = _ENV; env.f = nil env.io = nil"
1778                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1779                         "  end"
1780                         ""
1781                         "  local call = function (...)"
1782                         "   if type(self.instance) == 'function' then"
1783                         "     local status, err = pcall (self.instance, ...)"
1784                         "     if not status then"
1785                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1786                         "       self.script = nil"
1787                         "       self.instance = nil"
1788                         "       return false"
1789                         "     end"
1790                         "   end"
1791                         "   collectgarbage()"
1792                         "   return true"
1793                         "  end"
1794                         ""
1795                         "  local add = function (n, s, b, a)"
1796                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1797                         "   load (b)()" // assigns f
1798                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1799                         "   addinternal (n, s, load(f), a)"
1800                         "  end"
1801                         ""
1802                         "  local get = function ()"
1803                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1804                         "    return { ['name'] = self.script['n'],"
1805                         "             ['script'] = self.script['s'],"
1806                         "             ['args'] = self.script['a'] }"
1807                         "   end"
1808                         "   return nil"
1809                         "  end"
1810                         ""
1811                         // code dup
1812                         ""
1813                         "  local function basic_serialize (o)"
1814                         "    if type(o) == \"number\" then"
1815                         "     return tostring(o)"
1816                         "    else"
1817                         "     return string.format(\"%q\", o)"
1818                         "    end"
1819                         "  end"
1820                         ""
1821                         "  local function serialize (name, value)"
1822                         "   local rv = name .. ' = '"
1823                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1824                         "    return rv .. basic_serialize(value) .. ' '"
1825                         "   elseif type(value) == \"table\" then"
1826                         "    rv = rv .. '{} '"
1827                         "    for k,v in pairs(value) do"
1828                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1829                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1830                         "    end"
1831                         "    return rv;"
1832                         "   elseif type(value) == \"function\" then"
1833                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1834                         "   elseif type(value) == \"boolean\" then"
1835                         "     return rv .. tostring (value)"
1836                         "   else"
1837                         "    error('cannot save a ' .. type(value))"
1838                         "   end"
1839                         "  end"
1840                         ""
1841                         // end code dup
1842                         ""
1843                         "  local save = function ()"
1844                         "   return (serialize('s', self.script))"
1845                         "  end"
1846                         ""
1847                         "  local restore = function (state)"
1848                         "   self.script = {}"
1849                         "   load (state)()"
1850                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1851                         "  end"
1852                         ""
1853                         " return { call = call, add = add, get = get,"
1854                         "          restore = restore, save = save}"
1855                         " end"
1856                         " "
1857                         " manager = ScriptManager ()"
1858                         " ScriptManager = nil"
1859                         );
1860
1861         lua_State* L = lua.getState();
1862
1863         try {
1864                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1865                 lua.do_command ("manager = nil"); // hide it.
1866                 lua.do_command ("collectgarbage()");
1867
1868                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1869                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1870                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1871                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1872                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1873
1874         } catch (luabridge::LuaException const& e) {
1875                 fatal << string_compose (_("programming error: %1"),
1876                                 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
1877                         << endmsg;
1878                 abort(); /*NOTREACHED*/
1879         } catch (...) {
1880                 fatal << string_compose (_("programming error: %1"),
1881                                 X_("Failed to setup Lua callback interpreter"))
1882                         << endmsg;
1883                 abort(); /*NOTREACHED*/
1884         }
1885
1886         LuaInstance::register_classes (L);
1887         LuaInstance::register_hooks (L);
1888
1889         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1890         lua_setglobal (L, "Editor");
1891 }
1892
1893 bool
1894 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1895 {
1896         // TODO consolidate w/ LuaInstance::lua_action()
1897         try {
1898                 luabridge::LuaRef ref = (*_lua_get)();
1899                 if (ref.isNil()) {
1900                         return false;
1901                 }
1902                 if (!ref["name"].isString()) {
1903                         return false;
1904                 }
1905                 if (!ref["script"].isString()) {
1906                         return false;
1907                 }
1908                 if (!ref["args"].isTable()) {
1909                         return false;
1910                 }
1911
1912                 ah = _signals;
1913                 name = ref["name"].cast<std::string> ();
1914                 script = ref["script"].cast<std::string> ();
1915
1916                 args.clear();
1917                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1918                 if (!lsi) {
1919                         return false;
1920                 }
1921                 args = LuaScriptParams::script_params (lsi, "action_params");
1922                 luabridge::LuaRef rargs (ref["args"]);
1923                 LuaScriptParams::ref_to_params (args, &rargs);
1924                 return true;
1925         } catch (luabridge::LuaException const& e) {
1926                 cerr << "LuaException:" << e.what () << endl;
1927                 return false;
1928         } catch (...) { }
1929         return false;
1930 }
1931
1932 void
1933 LuaCallback::set_session (ARDOUR::Session *s)
1934 {
1935         SessionHandlePtr::set_session (s);
1936
1937         if (!_session) {
1938                 return;
1939         }
1940
1941         lua_State* L = lua.getState();
1942         LuaBindings::set_session (L, _session);
1943
1944         reconnect();
1945 }
1946
1947 void
1948 LuaCallback::session_going_away ()
1949 {
1950         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1951         lua.do_command ("collectgarbage();");
1952
1953         SessionHandlePtr::session_going_away ();
1954         _session = 0;
1955
1956         drop_callback (); /* EMIT SIGNAL */
1957 }
1958
1959 void
1960 LuaCallback::reconnect ()
1961 {
1962         _connections.drop_connections ();
1963         if ((*_lua_get) ().isNil ()) {
1964                 drop_callback (); /* EMIT SIGNAL */
1965                 return;
1966         }
1967
1968         // TODO pass object which emits the signal (e.g region)
1969         //
1970         // save/load bound objects will be tricky.
1971         // Best idea so far is to save/lookup the PBD::ID
1972         // (either use boost::any indirection or templates for bindable
1973         // object types or a switch statement..)
1974         //
1975         // _session->route_by_id ()
1976         // _session->track_by_diskstream_id ()
1977         // _session->source_by_id ()
1978         // _session->controllable_by_id ()
1979         // _session->processor_by_id ()
1980         // RegionFactory::region_by_id ()
1981         //
1982         // TODO loop over objects (if any)
1983
1984         reconnect_object ((void*)0);
1985 }
1986
1987 template <class T> void
1988 LuaCallback::reconnect_object (T obj)
1989 {
1990         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1991                 if (_signals[i]) {
1992 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1993 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1994 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1995                         if (0) {}
1996 #                       include "luasignal_syms.h"
1997                         else {
1998                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1999                                 abort(); /*NOTREACHED*/
2000                         }
2001 #undef ENGINE
2002 #undef SESSION
2003 #undef STATIC
2004                 }
2005         }
2006 }
2007
2008 template <typename T, typename S> void
2009 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2010         signal->connect (
2011                         _connections, invalidator (*this),
2012                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2013                         gui_context());
2014 }
2015
2016 template <typename T, typename C1> void
2017 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2018         signal->connect (
2019                         _connections, invalidator (*this),
2020                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2021                         gui_context());
2022 }
2023
2024 template <typename T, typename C1, typename C2> void
2025 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2026         signal->connect (
2027                         _connections, invalidator (*this),
2028                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2029                         gui_context());
2030 }
2031
2032 template <typename T> void
2033 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2034         bool ok = true;
2035         {
2036                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2037                 if (! rv.cast<bool> ()) {
2038                         ok = false;
2039                 }
2040         }
2041         /* destroy LuaRef ^^ first before calling drop_callback() */
2042         if (!ok) {
2043                 drop_callback (); /* EMIT SIGNAL */
2044         }
2045 }
2046
2047 template <typename T, typename C1> void
2048 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2049         bool ok = true;
2050         {
2051                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2052                 if (! rv.cast<bool> ()) {
2053                         ok = false;
2054                 }
2055         }
2056         if (!ok) {
2057                 drop_callback (); /* EMIT SIGNAL */
2058         }
2059 }
2060
2061 template <typename T, typename C1, typename C2> void
2062 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2063         bool ok = true;
2064         {
2065                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2066                 if (! rv.cast<bool> ()) {
2067                         ok = false;
2068                 }
2069         }
2070         if (!ok) {
2071                 drop_callback (); /* EMIT SIGNAL */
2072         }
2073 }