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