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