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