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