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