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