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