new_snap: Snapped Cursor ( squashed commit )
[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)
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 ("snap_type", &PublicEditor::snap_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 ("set_show_measures", &PublicEditor::set_show_measures)
869                 .addFunction ("show_measures", &PublicEditor::show_measures)
870                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
871
872                 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
873                 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
874
875                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
876
877                 .addRefFunction ("do_import", &PublicEditor::do_import)
878                 .addRefFunction ("do_embed", &PublicEditor::do_embed)
879
880                 .addFunction ("export_audio", &PublicEditor::export_audio)
881                 .addFunction ("stem_export", &PublicEditor::stem_export)
882                 .addFunction ("export_selection", &PublicEditor::export_selection)
883                 .addFunction ("export_range", &PublicEditor::export_range)
884
885                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
886                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
887                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
888                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
889
890                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
891                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
892                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
893                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
894
895                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
896                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
897
898 #if 0 // TimeAxisView&  can't be bound (pure virtual fn)
899                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
900                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
901                 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
902 #endif
903                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
904                 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
905                 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
906                 .addFunction ("fit_selection", &PublicEditor::fit_selection)
907
908                 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
909                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
910                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
911                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
912                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
913
914                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
915                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
916                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
917                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
918                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
919                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
920
921                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
922                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
923                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
924                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
925
926                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
927                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
928                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
929
930                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
931
932                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
933                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
934                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
935
936                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
937                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
938
939                 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
940                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
941                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
942                 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
943
944                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
945                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
946                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
947                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
948
949 #if 0
950                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
951                 .addFunction ("drags", &PublicEditor::drags)
952 #endif
953
954                 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
955                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
956                 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
957                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
958
959                 .addFunction ("center_screen", &PublicEditor::center_screen)
960
961                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
962                 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
963
964                 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
965                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
966                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
967 #if 0
968                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
969                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
970                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
971                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
972                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
973 #endif
974
975 #if 0
976                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
977                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
978                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
979                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
980 #endif
981
982                 .addFunction ("access_action", &PublicEditor::access_action)
983                 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
984                 .endClass ()
985
986                 .addFunction ("translate_order", &lua_translate_order)
987
988                 /* ArdourUI enums */
989                 .beginNamespace ("InsertAt")
990                 .addConst ("BeforeSelection", RouteDialogs::InsertAt(RouteDialogs::BeforeSelection))
991                 .addConst ("AfterSelection", RouteDialogs::InsertAt(RouteDialogs::AfterSelection))
992                 .addConst ("First", RouteDialogs::InsertAt(RouteDialogs::First))
993                 .addConst ("Last", RouteDialogs::InsertAt(RouteDialogs::Last))
994                 .endNamespace ()
995
996                 .beginNamespace ("MarkerType")
997                 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
998                 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
999                 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
1000                 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
1001                 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
1002                 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
1003                 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
1004                 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
1005                 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
1006                 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
1007                 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
1008                 .endNamespace ()
1009
1010                 .beginNamespace ("SelectionOp")
1011                 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
1012                 .addConst ("Set", Selection::Operation(Selection::Set))
1013                 .addConst ("Extend", Selection::Operation(Selection::Extend))
1014                 .addConst ("Add", Selection::Operation(Selection::Add))
1015                 .endNamespace ()
1016
1017                 .addCFunction ("actionlist", &lua_actionlist)
1018
1019                 .endNamespace () // end ArdourUI
1020
1021                 .beginNamespace ("os")
1022 #ifndef PLATFORM_WINDOWS
1023                 .addFunction ("execute", &lua_exec)
1024 #endif
1025                 .addCFunction ("forkexec", &lua_forkexec)
1026                 .endNamespace ();
1027
1028         // Editing Symbols
1029
1030 #undef ZOOMFOCUS
1031 #undef SNAPTYPE
1032 #undef SNAPMODE
1033 #undef MOUSEMODE
1034 #undef DISPLAYCONTROL
1035 #undef IMPORTMODE
1036 #undef IMPORTPOSITION
1037 #undef IMPORTDISPOSITION
1038
1039 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
1040 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
1041 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
1042 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
1043 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
1044 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
1045 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
1046 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
1047         luabridge::getGlobalNamespace (L)
1048                 .beginNamespace ("Editing")
1049 #               include "editing_syms.h"
1050                 .endNamespace ();
1051 }
1052
1053 #undef xstr
1054 #undef stringify
1055
1056 ////////////////////////////////////////////////////////////////////////////////
1057
1058 using namespace ARDOUR;
1059 using namespace ARDOUR_UI_UTILS;
1060 using namespace PBD;
1061 using namespace std;
1062
1063 static void _lua_print (std::string s) {
1064 #ifndef NDEBUG
1065         std::cout << "LuaInstance: " << s << "\n";
1066 #endif
1067         PBD::info << "LuaInstance: " << s << endmsg;
1068 }
1069
1070 LuaInstance* LuaInstance::_instance = 0;
1071
1072 LuaInstance*
1073 LuaInstance::instance ()
1074 {
1075         if (!_instance) {
1076                 _instance  = new LuaInstance;
1077         }
1078
1079         return _instance;
1080 }
1081
1082 void
1083 LuaInstance::destroy_instance ()
1084 {
1085         delete _instance;
1086         _instance = 0;
1087 }
1088
1089 LuaInstance::LuaInstance ()
1090 {
1091         lua.Print.connect (&_lua_print);
1092         init ();
1093
1094         LuaScriptParamList args;
1095 }
1096
1097 LuaInstance::~LuaInstance ()
1098 {
1099         delete _lua_call_action;
1100         delete _lua_render_icon;
1101         delete _lua_add_action;
1102         delete _lua_del_action;
1103         delete _lua_get_action;
1104
1105         delete _lua_load;
1106         delete _lua_save;
1107         delete _lua_clear;
1108         _callbacks.clear();
1109 }
1110
1111 void
1112 LuaInstance::init ()
1113 {
1114         lua.sandbox (false);
1115         lua.do_command (
1116                         "function ScriptManager ()"
1117                         "  local self = { scripts = {}, instances = {}, icons = {} }"
1118                         ""
1119                         "  local remove = function (id)"
1120                         "   self.scripts[id] = nil"
1121                         "   self.instances[id] = nil"
1122                         "   self.icons[id] = nil"
1123                         "  end"
1124                         ""
1125                         "  local addinternal = function (i, n, s, f, c, a)"
1126                         "   assert(type(i) == 'number', 'id must be numeric')"
1127                         "   assert(type(n) == 'string', 'Name must be string')"
1128                         "   assert(type(s) == 'string', 'Script must be string')"
1129                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1130                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1131                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1132                         "   local env = _ENV; env.f = nil"
1133                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1134                         "   if type(c) == 'function' then"
1135                         "     self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1136                         "   else"
1137                         "     self.icons[i] = nil"
1138                         "   end"
1139                         "  end"
1140                         ""
1141                         "  local call = function (id)"
1142                         "   if type(self.instances[id]) == 'function' then"
1143                         "     local status, err = pcall (self.instances[id])"
1144                         "     if not status then"
1145                         "       print ('action \"'.. id .. '\": ', err)" // error out
1146                         "       remove (id)"
1147                         "     end"
1148                         "   end"
1149                         "   collectgarbage()"
1150                         "  end"
1151                         ""
1152                         "  local icon = function (id, ...)"
1153                         "   if type(self.icons[id]) == 'function' then"
1154                         "     pcall (self.icons[id], ...)"
1155                         "   end"
1156                         "   collectgarbage()"
1157                         "  end"
1158                         ""
1159                         "  local add = function (i, n, s, b, c, a)"
1160                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1161                         "   f = nil load (b)()" // assigns f
1162                         "   icn = nil load (c)()" // may assign "icn"
1163                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1164                         "   addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1165                         "  end"
1166                         ""
1167                         "  local get = function (id)"
1168                         "   if type(self.scripts[id]) == 'table' then"
1169                         "    return { ['name'] = self.scripts[id]['n'],"
1170                         "             ['script'] = self.scripts[id]['s'],"
1171                         "             ['icon'] = type(self.scripts[id]['c']) == 'function',"
1172                         "             ['args'] = self.scripts[id]['a'] }"
1173                         "   end"
1174                         "   return nil"
1175                         "  end"
1176                         ""
1177                         "  local function basic_serialize (o)"
1178                         "    if type(o) == \"number\" then"
1179                         "     return tostring(o)"
1180                         "    else"
1181                         "     return string.format(\"%q\", o)"
1182                         "    end"
1183                         "  end"
1184                         ""
1185                         "  local function serialize (name, value)"
1186                         "   local rv = name .. ' = '"
1187                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1188                         "    return rv .. basic_serialize(value) .. ' '"
1189                         "   elseif type(value) == \"table\" then"
1190                         "    rv = rv .. '{} '"
1191                         "    for k,v in pairs(value) do"
1192                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1193                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1194                         "    end"
1195                         "    return rv;"
1196                         "   elseif type(value) == \"function\" then"
1197                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1198                         "   elseif type(value) == \"boolean\" then"
1199                         "     return rv .. tostring (value)"
1200                         "   else"
1201                         "    error('cannot save a ' .. type(value))"
1202                         "   end"
1203                         "  end"
1204                         ""
1205                         ""
1206                         "  local save = function ()"
1207                         "   return (serialize('scripts', self.scripts))"
1208                         "  end"
1209                         ""
1210                         "  local clear = function ()"
1211                         "   self.scripts = {}"
1212                         "   self.instances = {}"
1213                         "   self.icons = {}"
1214                         "   collectgarbage()"
1215                         "  end"
1216                         ""
1217                         "  local restore = function (state)"
1218                         "   clear()"
1219                         "   load (state)()"
1220                         "   for i, s in pairs (scripts) do"
1221                         "    addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1222                         "   end"
1223                         "   collectgarbage()"
1224                         "  end"
1225                         ""
1226                         " return { call = call, add = add, remove = remove, get = get,"
1227                         "          restore = restore, save = save, clear = clear, icon = icon}"
1228                         " end"
1229                         " "
1230                         " manager = ScriptManager ()"
1231                         " ScriptManager = nil"
1232                         );
1233         lua_State* L = lua.getState();
1234
1235         try {
1236                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1237                 lua.do_command ("manager = nil"); // hide it.
1238                 lua.do_command ("collectgarbage()");
1239
1240                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1241                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1242                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1243                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1244                 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1245                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1246                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1247                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1248
1249         } catch (luabridge::LuaException const& e) {
1250                 fatal << string_compose (_("programming error: %1"),
1251                                 std::string ("Failed to setup Lua action interpreter") + e.what ())
1252                         << endmsg;
1253                 abort(); /*NOTREACHED*/
1254         } catch (...) {
1255                 fatal << string_compose (_("programming error: %1"),
1256                                 X_("Failed to setup Lua action interpreter"))
1257                         << endmsg;
1258                 abort(); /*NOTREACHED*/
1259         }
1260
1261         register_classes (L);
1262         register_hooks (L);
1263
1264         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1265         lua_setglobal (L, "Editor");
1266 }
1267
1268 void LuaInstance::set_session (Session* s)
1269 {
1270         SessionHandlePtr::set_session (s);
1271         if (!_session) {
1272                 return;
1273         }
1274
1275         lua_State* L = lua.getState();
1276         LuaBindings::set_session (L, _session);
1277
1278         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1279                 i->second->set_session (s);
1280         }
1281         point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1282         SetSession (); /* EMIT SIGNAL */
1283 }
1284
1285 void
1286 LuaInstance::session_going_away ()
1287 {
1288         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1289         point_one_second_connection.disconnect ();
1290
1291         (*_lua_clear)();
1292         for (int i = 0; i < 9; ++i) {
1293                 ActionChanged (i, ""); /* EMIT SIGNAL */
1294         }
1295         SessionHandlePtr::session_going_away ();
1296         _session = 0;
1297
1298         lua_State* L = lua.getState();
1299         LuaBindings::set_session (L, _session);
1300         lua.do_command ("collectgarbage();");
1301 }
1302
1303 void
1304 LuaInstance::every_point_one_seconds ()
1305 {
1306         LuaTimerDS (); // emit signal
1307 }
1308
1309 int
1310 LuaInstance::set_state (const XMLNode& node)
1311 {
1312         XMLNode* child;
1313
1314         if ((child = find_named_node (node, "ActionScript"))) {
1315                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1316                         if (!(*n)->is_content ()) { continue; }
1317                         gsize size;
1318                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1319                         try {
1320                                 (*_lua_load)(std::string ((const char*)buf, size));
1321                         } catch (luabridge::LuaException const& e) {
1322                                 cerr << "LuaException:" << e.what () << endl;
1323                         } catch (...) { }
1324                         for (int i = 0; i < 9; ++i) {
1325                                 std::string name;
1326                                 if (lua_action_name (i, name)) {
1327                                         ActionChanged (i, name); /* EMIT SIGNAL */
1328                                 }
1329                         }
1330                         g_free (buf);
1331                 }
1332         }
1333
1334         if ((child = find_named_node (node, "ActionHooks"))) {
1335                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1336                         try {
1337                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1338                                 _callbacks.insert (std::make_pair(p->id(), p));
1339                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1340                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1341                         } catch (luabridge::LuaException const& e) {
1342                                 cerr << "LuaException:" << e.what () << endl;
1343                         } catch (...) { }
1344                 }
1345         }
1346
1347         return 0;
1348 }
1349
1350 bool
1351 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1352 {
1353         std::string title;
1354         std::string param_function = "action_params";
1355         std::vector<std::string> reg;
1356
1357         switch (type) {
1358                 case LuaScriptInfo::EditorAction:
1359                         reg = lua_action_names ();
1360                         title = _("Add Shortcut or Lua Script");
1361                         break;
1362                 case LuaScriptInfo::EditorHook:
1363                         reg = lua_slot_names ();
1364                         title = _("Add Lua Callback Hook");
1365                         break;
1366                 case LuaScriptInfo::Session:
1367                         if (!_session) {
1368                                 return false;
1369                         }
1370                         reg = _session->registered_lua_functions ();
1371                         title = _("Add Lua Session Script");
1372                         param_function = "sess_params";
1373                         break;
1374                 default:
1375                         return false;
1376         }
1377
1378         LuaScriptInfoPtr spi;
1379         ScriptSelector ss (title, type);
1380         switch (ss.run ()) {
1381                 case Gtk::RESPONSE_ACCEPT:
1382                         spi = ss.script();
1383                         break;
1384                 default:
1385                         return false;
1386         }
1387         ss.hide ();
1388
1389         std::string script = "";
1390
1391         try {
1392                 script = Glib::file_get_contents (spi->path);
1393         } catch (Glib::FileError const& e) {
1394                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1395                 Gtk::MessageDialog am (msg);
1396                 am.run ();
1397                 return false;
1398         }
1399
1400         LuaState ls;
1401         register_classes (ls.getState ());
1402         LuaScriptParamList lsp = LuaScriptParams::script_params (ls, spi->path, param_function);
1403
1404         /* allow cancel */
1405         for (size_t i = 0; i < lsp.size(); ++i) {
1406                 if (lsp[i]->preseeded && lsp[i]->name == "x-script-abort") {
1407                         return false;
1408                 }
1409         }
1410
1411         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1412
1413         if (spd.need_interation ()) {
1414                 switch (spd.run ()) {
1415                         case Gtk::RESPONSE_ACCEPT:
1416                                 break;
1417                         default:
1418                                 return false;
1419                 }
1420         }
1421
1422         LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false, true));
1423         lsp.push_back (lspp);
1424
1425         switch (type) {
1426                 case LuaScriptInfo::EditorAction:
1427                         return set_lua_action (id, spd.name(), script, lsp);
1428                         break;
1429                 case LuaScriptInfo::EditorHook:
1430                         return register_lua_slot (spd.name(), script, lsp);
1431                         break;
1432                 case LuaScriptInfo::Session:
1433                         try {
1434                                 _session->register_lua_function (spd.name(), script, lsp);
1435                         } catch (luabridge::LuaException const& e) {
1436                                 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1437                                 Gtk::MessageDialog am (msg);
1438                                 am.run ();
1439                         } catch (SessionException const& e) {
1440                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1441                                 Gtk::MessageDialog am (msg);
1442                                 am.run ();
1443                         } catch (...) {
1444                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1445                                 Gtk::MessageDialog am (msg);
1446                                 am.run ();
1447                         }
1448                 default:
1449                         break;
1450         }
1451         return false;
1452 }
1453
1454 XMLNode&
1455 LuaInstance::get_action_state ()
1456 {
1457         std::string saved;
1458         {
1459                 luabridge::LuaRef savedstate ((*_lua_save)());
1460                 saved = savedstate.cast<std::string>();
1461         }
1462         lua.collect_garbage ();
1463
1464         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1465         std::string b64s (b64);
1466         g_free (b64);
1467
1468         XMLNode* script_node = new XMLNode (X_("ActionScript"));
1469         script_node->set_property (X_("lua"), LUA_VERSION);
1470         script_node->add_content (b64s);
1471
1472         return *script_node;
1473 }
1474
1475 XMLNode&
1476 LuaInstance::get_hook_state ()
1477 {
1478         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1479         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1480                 script_node->add_child_nocopy (i->second->get_state ());
1481         }
1482         return *script_node;
1483 }
1484
1485 void
1486 LuaInstance::call_action (const int id)
1487 {
1488         try {
1489                 (*_lua_call_action)(id + 1);
1490                 lua.collect_garbage_step ();
1491         } catch (luabridge::LuaException const& e) {
1492                 cerr << "LuaException:" << e.what () << endl;
1493         } catch (...) { }
1494 }
1495
1496 void
1497 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1498         int ii = reinterpret_cast<uintptr_t> (i);
1499         instance()->render_icon (ii, cr, w, h, c);
1500 }
1501
1502 void
1503 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1504 {
1505          Cairo::Context ctx (cr);
1506          try {
1507                  (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1508          } catch (luabridge::LuaException const& e) {
1509                  cerr << "LuaException:" << e.what () << endl;
1510          } catch (...) { }
1511 }
1512
1513 bool
1514 LuaInstance::set_lua_action (
1515                 const int id,
1516                 const std::string& name,
1517                 const std::string& script,
1518                 const LuaScriptParamList& args)
1519 {
1520         try {
1521                 lua_State* L = lua.getState();
1522                 // get bytcode of factory-function in a sandbox
1523                 // (don't allow scripts to interfere)
1524                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1525                 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1526                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1527                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1528                         if ((*i)->optional && !(*i)->is_set) { continue; }
1529                         tbl_arg[(*i)->name] = (*i)->value;
1530                 }
1531                 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1532                 ActionChanged (id, name); /* EMIT SIGNAL */
1533         } catch (luabridge::LuaException const& e) {
1534                 cerr << "LuaException:" << e.what () << endl;
1535                 return false;
1536         } catch (...) {
1537                 return false;
1538         }
1539         _session->set_dirty ();
1540         return true;
1541 }
1542
1543 bool
1544 LuaInstance::remove_lua_action (const int id)
1545 {
1546         try {
1547                 (*_lua_del_action)(id + 1);
1548         } catch (luabridge::LuaException const& e) {
1549                 cerr << "LuaException:" << e.what () << endl;
1550                 return false;
1551         } catch (...) {
1552                 return false;
1553         }
1554         ActionChanged (id, ""); /* EMIT SIGNAL */
1555         _session->set_dirty ();
1556         return true;
1557 }
1558
1559 bool
1560 LuaInstance::lua_action_name (const int id, std::string& rv)
1561 {
1562         try {
1563                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1564                 if (ref.isNil()) {
1565                         return false;
1566                 }
1567                 if (ref["name"].isString()) {
1568                         rv = ref["name"].cast<std::string>();
1569                         return true;
1570                 }
1571                 return true;
1572         } catch (luabridge::LuaException const& e) {
1573                 cerr << "LuaException:" << e.what () << endl;
1574         } catch (...) { }
1575         return false;
1576 }
1577
1578 std::vector<std::string>
1579 LuaInstance::lua_action_names ()
1580 {
1581         std::vector<std::string> rv;
1582         for (int i = 0; i < 9; ++i) {
1583                 std::string name;
1584                 if (lua_action_name (i, name)) {
1585                         rv.push_back (name);
1586                 }
1587         }
1588         return rv;
1589 }
1590
1591 bool
1592 LuaInstance::lua_action_has_icon (const int id)
1593 {
1594         try {
1595                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1596                 if (ref.isNil()) {
1597                         return false;
1598                 }
1599                 if (ref["icon"].isBoolean()) {
1600                         return ref["icon"].cast<bool>();
1601                 }
1602         } catch (luabridge::LuaException const& e) {
1603                 cerr << "LuaException:" << e.what () << endl;
1604         } catch (...) { }
1605         return false;
1606 }
1607
1608 bool
1609 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1610 {
1611         try {
1612                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1613                 if (ref.isNil()) {
1614                         return false;
1615                 }
1616                 if (!ref["name"].isString()) {
1617                         return false;
1618                 }
1619                 if (!ref["script"].isString()) {
1620                         return false;
1621                 }
1622                 if (!ref["args"].isTable()) {
1623                         return false;
1624                 }
1625                 name = ref["name"].cast<std::string>();
1626                 script = ref["script"].cast<std::string>();
1627
1628                 args.clear();
1629                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1630                 if (!lsi) {
1631                         return false;
1632                 }
1633                 args = LuaScriptParams::script_params (lsi, "action_params");
1634                 luabridge::LuaRef rargs (ref["args"]);
1635                 LuaScriptParams::ref_to_params (args, &rargs);
1636                 return true;
1637         } catch (luabridge::LuaException const& e) {
1638                 cerr << "LuaException:" << e.what () << endl;
1639         } catch (...) { }
1640         return false;
1641 }
1642
1643 bool
1644 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1645 {
1646         /* parse script, get ActionHook(s) from script */
1647         ActionHook ah;
1648         try {
1649                 LuaState l;
1650                 l.Print.connect (&_lua_print);
1651                 l.sandbox (true);
1652                 lua_State* L = l.getState();
1653                 register_hooks (L);
1654                 l.do_command ("function ardour () end");
1655                 l.do_command (script);
1656                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1657                 if (signals.isFunction()) {
1658                         ah = signals();
1659                 }
1660         } catch (luabridge::LuaException const& e) {
1661                 cerr << "LuaException:" << e.what () << endl;
1662         } catch (...) { }
1663
1664         if (ah.none ()) {
1665                 cerr << "Script registered no hooks." << endl;
1666                 return false;
1667         }
1668
1669         /* register script w/args, get entry-point / ID */
1670
1671         try {
1672                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1673                 _callbacks.insert (std::make_pair(p->id(), p));
1674                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1675                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1676                 return true;
1677         } catch (luabridge::LuaException const& e) {
1678                 cerr << "LuaException:" << e.what () << endl;
1679         } catch (...) { }
1680         _session->set_dirty ();
1681         return false;
1682 }
1683
1684 bool
1685 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1686 {
1687         LuaCallbackMap::iterator i = _callbacks.find (id);
1688         if (i != _callbacks.end()) {
1689                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1690                 _callbacks.erase (i);
1691                 return true;
1692         }
1693         _session->set_dirty ();
1694         return false;
1695 }
1696
1697 std::vector<PBD::ID>
1698 LuaInstance::lua_slots () const
1699 {
1700         std::vector<PBD::ID> rv;
1701         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1702                 rv.push_back (i->first);
1703         }
1704         return rv;
1705 }
1706
1707 bool
1708 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1709 {
1710         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1711         if (i != _callbacks.end()) {
1712                 name = i->second->name();
1713                 return true;
1714         }
1715         return false;
1716 }
1717
1718 std::vector<std::string>
1719 LuaInstance::lua_slot_names () const
1720 {
1721         std::vector<std::string> rv;
1722         std::vector<PBD::ID> ids = lua_slots();
1723         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1724                 std::string name;
1725                 if (lua_slot_name (*i, name)) {
1726                         rv.push_back (name);
1727                 }
1728         }
1729         return rv;
1730 }
1731
1732 bool
1733 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1734 {
1735         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1736         if (i == _callbacks.end()) {
1737                 return false; // error
1738         }
1739         return i->second->lua_slot (name, script, ah, args);
1740 }
1741
1742 ///////////////////////////////////////////////////////////////////////////////
1743
1744 LuaCallback::LuaCallback (Session *s,
1745                 const std::string& name,
1746                 const std::string& script,
1747                 const ActionHook& ah,
1748                 const ARDOUR::LuaScriptParamList& args)
1749         : SessionHandlePtr (s)
1750         , _id ("0")
1751         , _name (name)
1752         , _signals (ah)
1753 {
1754         // TODO: allow to reference object (e.g region)
1755         init ();
1756
1757         lua_State* L = lua.getState();
1758         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1759         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1760                 if ((*i)->optional && !(*i)->is_set) { continue; }
1761                 tbl_arg[(*i)->name] = (*i)->value;
1762         }
1763
1764         try {
1765                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1766                 (*_lua_add)(name, script, bytecode, tbl_arg);
1767         } catch (luabridge::LuaException const& e) {
1768                 cerr << "LuaException:" << e.what () << endl;
1769                 throw failed_constructor ();
1770         } catch (...) {
1771                 throw failed_constructor ();
1772         }
1773
1774         _id.reset ();
1775         set_session (s);
1776 }
1777
1778 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1779         : SessionHandlePtr (s)
1780 {
1781         XMLNode* child = NULL;
1782         if (node.name() != X_("LuaCallback")
1783                         || !node.property ("signals")
1784                         || !node.property ("id")
1785                         || !node.property ("name")) {
1786                 throw failed_constructor ();
1787         }
1788
1789         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1790                 if (!(*n)->is_content ()) { continue; }
1791                 child = *n;
1792         }
1793
1794         if (!child) {
1795                 throw failed_constructor ();
1796         }
1797
1798         init ();
1799
1800         _id = PBD::ID (node.property ("id")->value ());
1801         _name = node.property ("name")->value ();
1802         _signals = ActionHook (node.property ("signals")->value ());
1803
1804         gsize size;
1805         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1806         try {
1807                 (*_lua_load)(std::string ((const char*)buf, size));
1808         } catch (luabridge::LuaException const& e) {
1809                 cerr << "LuaException:" << e.what () << endl;
1810         } catch (...) { }
1811         g_free (buf);
1812
1813         set_session (s);
1814 }
1815
1816 LuaCallback::~LuaCallback ()
1817 {
1818         delete _lua_add;
1819         delete _lua_get;
1820         delete _lua_call;
1821         delete _lua_load;
1822         delete _lua_save;
1823 }
1824
1825 XMLNode&
1826 LuaCallback::get_state (void)
1827 {
1828         std::string saved;
1829         {
1830                 luabridge::LuaRef savedstate ((*_lua_save)());
1831                 saved = savedstate.cast<std::string>();
1832         }
1833
1834         lua.collect_garbage (); // this may be expensive:
1835         /* Editor::instant_save() calls Editor::get_state() which
1836          * calls LuaInstance::get_hook_state() which in turn calls
1837          * this LuaCallback::get_state() for every registered hook.
1838          *
1839          * serialize in _lua_save() allocates many small strings
1840          * on the lua-stack, collecting them all may take a ms.
1841          */
1842
1843         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1844         std::string b64s (b64);
1845         g_free (b64);
1846
1847         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1848         script_node->set_property (X_("lua"), LUA_VERSION);
1849         script_node->set_property (X_("id"), _id.to_s ());
1850         script_node->set_property (X_("name"), _name);
1851         script_node->set_property (X_("signals"), _signals.to_string ());
1852         script_node->add_content (b64s);
1853         return *script_node;
1854 }
1855
1856 void
1857 LuaCallback::init (void)
1858 {
1859         lua.Print.connect (&_lua_print);
1860         lua.sandbox (false);
1861
1862         lua.do_command (
1863                         "function ScriptManager ()"
1864                         "  local self = { script = {}, instance = {} }"
1865                         ""
1866                         "  local addinternal = function (n, s, f, a)"
1867                         "   assert(type(n) == 'string', 'Name must be string')"
1868                         "   assert(type(s) == 'string', 'Script must be string')"
1869                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1870                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1871                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1872                         "   local env = _ENV; env.f = nil"
1873                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1874                         "  end"
1875                         ""
1876                         "  local call = function (...)"
1877                         "   if type(self.instance) == 'function' then"
1878                         "     local status, err = pcall (self.instance, ...)"
1879                         "     if not status then"
1880                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1881                         "       self.script = nil"
1882                         "       self.instance = nil"
1883                         "       return false"
1884                         "     end"
1885                         "   end"
1886                         "   collectgarbage()"
1887                         "   return true"
1888                         "  end"
1889                         ""
1890                         "  local add = function (n, s, b, a)"
1891                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1892                         "   load (b)()" // assigns f
1893                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1894                         "   addinternal (n, s, load(f), a)"
1895                         "  end"
1896                         ""
1897                         "  local get = function ()"
1898                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1899                         "    return { ['name'] = self.script['n'],"
1900                         "             ['script'] = self.script['s'],"
1901                         "             ['args'] = self.script['a'] }"
1902                         "   end"
1903                         "   return nil"
1904                         "  end"
1905                         ""
1906                         // code dup
1907                         ""
1908                         "  local function basic_serialize (o)"
1909                         "    if type(o) == \"number\" then"
1910                         "     return tostring(o)"
1911                         "    else"
1912                         "     return string.format(\"%q\", o)"
1913                         "    end"
1914                         "  end"
1915                         ""
1916                         "  local function serialize (name, value)"
1917                         "   local rv = name .. ' = '"
1918                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1919                         "    return rv .. basic_serialize(value) .. ' '"
1920                         "   elseif type(value) == \"table\" then"
1921                         "    rv = rv .. '{} '"
1922                         "    for k,v in pairs(value) do"
1923                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1924                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1925                         "    end"
1926                         "    return rv;"
1927                         "   elseif type(value) == \"function\" then"
1928                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1929                         "   elseif type(value) == \"boolean\" then"
1930                         "     return rv .. tostring (value)"
1931                         "   else"
1932                         "    error('cannot save a ' .. type(value))"
1933                         "   end"
1934                         "  end"
1935                         ""
1936                         // end code dup
1937                         ""
1938                         "  local save = function ()"
1939                         "   return (serialize('s', self.script))"
1940                         "  end"
1941                         ""
1942                         "  local restore = function (state)"
1943                         "   self.script = {}"
1944                         "   load (state)()"
1945                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1946                         "  end"
1947                         ""
1948                         " return { call = call, add = add, get = get,"
1949                         "          restore = restore, save = save}"
1950                         " end"
1951                         " "
1952                         " manager = ScriptManager ()"
1953                         " ScriptManager = nil"
1954                         );
1955
1956         lua_State* L = lua.getState();
1957
1958         try {
1959                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1960                 lua.do_command ("manager = nil"); // hide it.
1961                 lua.do_command ("collectgarbage()");
1962
1963                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1964                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1965                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1966                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1967                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1968
1969         } catch (luabridge::LuaException const& e) {
1970                 fatal << string_compose (_("programming error: %1"),
1971                                 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
1972                         << endmsg;
1973                 abort(); /*NOTREACHED*/
1974         } catch (...) {
1975                 fatal << string_compose (_("programming error: %1"),
1976                                 X_("Failed to setup Lua callback interpreter"))
1977                         << endmsg;
1978                 abort(); /*NOTREACHED*/
1979         }
1980
1981         LuaInstance::register_classes (L);
1982         LuaInstance::register_hooks (L);
1983
1984         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1985         lua_setglobal (L, "Editor");
1986 }
1987
1988 bool
1989 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1990 {
1991         // TODO consolidate w/ LuaInstance::lua_action()
1992         try {
1993                 luabridge::LuaRef ref = (*_lua_get)();
1994                 if (ref.isNil()) {
1995                         return false;
1996                 }
1997                 if (!ref["name"].isString()) {
1998                         return false;
1999                 }
2000                 if (!ref["script"].isString()) {
2001                         return false;
2002                 }
2003                 if (!ref["args"].isTable()) {
2004                         return false;
2005                 }
2006
2007                 ah = _signals;
2008                 name = ref["name"].cast<std::string> ();
2009                 script = ref["script"].cast<std::string> ();
2010
2011                 args.clear();
2012                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
2013                 if (!lsi) {
2014                         return false;
2015                 }
2016                 args = LuaScriptParams::script_params (lsi, "action_params");
2017                 luabridge::LuaRef rargs (ref["args"]);
2018                 LuaScriptParams::ref_to_params (args, &rargs);
2019                 return true;
2020         } catch (luabridge::LuaException const& e) {
2021                 cerr << "LuaException:" << e.what () << endl;
2022                 return false;
2023         } catch (...) { }
2024         return false;
2025 }
2026
2027 void
2028 LuaCallback::set_session (ARDOUR::Session *s)
2029 {
2030         SessionHandlePtr::set_session (s);
2031
2032         if (!_session) {
2033                 return;
2034         }
2035
2036         lua_State* L = lua.getState();
2037         LuaBindings::set_session (L, _session);
2038
2039         reconnect();
2040 }
2041
2042 void
2043 LuaCallback::session_going_away ()
2044 {
2045         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
2046         lua.do_command ("collectgarbage();");
2047
2048         SessionHandlePtr::session_going_away ();
2049         _session = 0;
2050
2051         drop_callback (); /* EMIT SIGNAL */
2052 }
2053
2054 void
2055 LuaCallback::reconnect ()
2056 {
2057         _connections.drop_connections ();
2058         if ((*_lua_get) ().isNil ()) {
2059                 drop_callback (); /* EMIT SIGNAL */
2060                 return;
2061         }
2062
2063         // TODO pass object which emits the signal (e.g region)
2064         //
2065         // save/load bound objects will be tricky.
2066         // Best idea so far is to save/lookup the PBD::ID
2067         // (either use boost::any indirection or templates for bindable
2068         // object types or a switch statement..)
2069         //
2070         // _session->route_by_id ()
2071         // _session->track_by_diskstream_id ()
2072         // _session->source_by_id ()
2073         // _session->controllable_by_id ()
2074         // _session->processor_by_id ()
2075         // RegionFactory::region_by_id ()
2076         //
2077         // TODO loop over objects (if any)
2078
2079         reconnect_object ((void*)0);
2080 }
2081
2082 template <class T> void
2083 LuaCallback::reconnect_object (T obj)
2084 {
2085         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
2086                 if (_signals[i]) {
2087 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
2088 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
2089 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
2090                         if (0) {}
2091 #                       include "luasignal_syms.h"
2092                         else {
2093                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
2094                                 abort(); /*NOTREACHED*/
2095                         }
2096 #undef ENGINE
2097 #undef SESSION
2098 #undef STATIC
2099                 }
2100         }
2101 }
2102
2103 template <typename T, typename S> void
2104 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2105         signal->connect (
2106                         _connections, invalidator (*this),
2107                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2108                         gui_context());
2109 }
2110
2111 template <typename T, typename C1> void
2112 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2113         signal->connect (
2114                         _connections, invalidator (*this),
2115                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2116                         gui_context());
2117 }
2118
2119 template <typename T, typename C1, typename C2> void
2120 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2121         signal->connect (
2122                         _connections, invalidator (*this),
2123                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2124                         gui_context());
2125 }
2126
2127 template <typename T, typename C1, typename C2, typename C3> void
2128 LuaCallback::connect_3 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal3<void, C1, C2, C3> *signal) {
2129         signal->connect (
2130                         _connections, invalidator (*this),
2131                         boost::bind (&LuaCallback::proxy_3<T, C1, C2, C3>, this, ls, ref, _1, _2, _3),
2132                         gui_context());
2133 }
2134
2135 template <typename T> void
2136 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2137         bool ok = true;
2138         {
2139                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2140                 if (! rv.cast<bool> ()) {
2141                         ok = false;
2142                 }
2143         }
2144         /* destroy LuaRef ^^ first before calling drop_callback() */
2145         if (!ok) {
2146                 drop_callback (); /* EMIT SIGNAL */
2147         }
2148 }
2149
2150 template <typename T, typename C1> void
2151 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2152         bool ok = true;
2153         {
2154                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2155                 if (! rv.cast<bool> ()) {
2156                         ok = false;
2157                 }
2158         }
2159         if (!ok) {
2160                 drop_callback (); /* EMIT SIGNAL */
2161         }
2162 }
2163
2164 template <typename T, typename C1, typename C2> void
2165 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2166         bool ok = true;
2167         {
2168                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2169                 if (! rv.cast<bool> ()) {
2170                         ok = false;
2171                 }
2172         }
2173         if (!ok) {
2174                 drop_callback (); /* EMIT SIGNAL */
2175         }
2176 }
2177
2178 template <typename T, typename C1, typename C2, typename C3> void
2179 LuaCallback::proxy_3 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2, C3 a3) {
2180         bool ok = true;
2181         {
2182                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2, a3));
2183                 if (! rv.cast<bool> ()) {
2184                         ok = false;
2185                 }
2186         }
2187         if (!ok) {
2188                 drop_callback (); /* EMIT SIGNAL */
2189         }
2190 }