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