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