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