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