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