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