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