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