Fix MIDI disk-writer flush
[ardour.git] / gtk2_ardour / luainstance.cc
1 /*
2  * Copyright (C) 2016-2019 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2016-2019 Robin Gareus <robin@gareus.org>
4  * Copyright (C) 2016 Tim Mayberry <mojofunk@gmail.com>
5  * Copyright (C) 2017-2018 Ben Loftis <ben@harrisonconsoles.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <cairomm/context.h>
23 #include <cairomm/surface.h>
24 #include <pango/pangocairo.h>
25
26 #include "pbd/file_utils.h"
27 #include "pbd/strsplit.h"
28
29 #include "gtkmm2ext/bindings.h"
30 #include "gtkmm2ext/gui_thread.h"
31
32 #include "ardour/audioengine.h"
33 #include "ardour/disk_reader.h"
34 #include "ardour/disk_writer.h"
35 #include "ardour/filesystem_paths.h"
36 #include "ardour/plugin_manager.h"
37 #include "ardour/route.h"
38 #include "ardour/session.h"
39 #include "ardour/system_exec.h"
40
41 #include "LuaBridge/LuaBridge.h"
42
43 #include "ardour_http.h"
44 #include "ardour_ui.h"
45 #include "public_editor.h"
46 #include "region_selection.h"
47 #include "luadialog.h"
48 #include "luainstance.h"
49 #include "luasignal.h"
50 #include "marker.h"
51 #include "mixer_ui.h"
52 #include "region_view.h"
53 #include "processor_box.h"
54 #include "time_axis_view.h"
55 #include "time_axis_view_item.h"
56 #include "selection.h"
57 #include "script_selector.h"
58 #include "timers.h"
59 #include "ui_config.h"
60 #include "utils_videotl.h"
61
62 #include "pbd/i18n.h"
63
64 static const char* ui_scripts_file_name = "ui_scripts";
65
66 namespace LuaCairo {
67 /** wrap RefPtr< Cairo::ImageSurface >
68  *
69  * Image surfaces provide the ability to render to memory buffers either
70  * allocated by cairo or by the calling code. The supported image formats are
71  * those defined in Cairo::Format.
72  */
73 class ImageSurface {
74         public:
75                 /**
76                  * Creates an image surface of the specified format and dimensions. Initially
77                  * the surface contents are all 0. (Specifically, within each pixel, each
78                  * color or alpha channel belonging to format will be 0. The contents of bits
79                  * within a pixel, but not belonging to the given format are undefined).
80                  *
81                  * @param format  format of pixels in the surface to create
82                  * @param width   width of the surface, in pixels
83                  * @param height  height of the surface, in pixels
84                  */
85                 ImageSurface (Cairo::Format format, int width, int height)
86                         : _surface (Cairo::ImageSurface::create (format, width, height))
87                         , _ctx (Cairo::Context::create (_surface))
88                         , ctx (_ctx->cobj ()) {}
89
90                 ~ImageSurface () {}
91
92                 /**
93                  * Set this surface as source for another context.
94                  * This allows to draw this surface
95                  */
96                 void set_as_source (Cairo::Context* c, int x, int y) {
97                         _surface->flush ();
98                         c->set_source (_surface, x, y);
99                 }
100
101                 /**
102                  * Returns a context object to perform operations on the surface
103                  */
104                 Cairo::Context* context () {
105                         return (Cairo::Context *)&ctx;
106                 }
107
108                 /**
109                  * Returns the stride of the image surface in bytes (or 0 if surface is not
110                  * an image surface). The stride is the distance in bytes from the beginning
111                  * of one row of the image data to the beginning of the next row.
112                  */
113                 int get_stride () const {
114                         return _surface->get_stride ();
115                 }
116
117                 /** Gets the width of the ImageSurface in pixels */
118                 int get_width () const {
119                         return _surface->get_width ();
120                 }
121
122                 /** Gets the height of the ImageSurface in pixels */
123                 int get_height () const {
124                         return _surface->get_height ();
125                 }
126
127                 /**
128                  * Get a pointer to the data of the image surface, for direct
129                  * inspection or modification.
130                  *
131                  * Return value: a pointer to the image data of this surface or NULL
132                  * if @surface is not an image surface.
133                  *
134                  */
135                 unsigned char* get_data () {
136                         return _surface->get_data ();
137                 }
138
139                 /** Tells cairo to consider the data buffer dirty.
140                  *
141                  * In particular, if you've created an ImageSurface with a data buffer that
142                  * you've allocated yourself and you draw to that data buffer using means
143                  * other than cairo, you must call mark_dirty() before doing any additional
144                  * drawing to that surface with cairo.
145                  *
146                  * Note that if you do draw to the Surface outside of cairo, you must call
147                  * flush() before doing the drawing.
148                  */
149                 void mark_dirty () {
150                         _surface->mark_dirty ();
151                 }
152
153                 /** Marks a rectangular area of the given surface dirty.
154                  *
155                  * @param x X coordinate of dirty rectangle
156                  * @param y Y coordinate of dirty rectangle
157                  * @param width width of dirty rectangle
158                  * @param height height of dirty rectangle
159                  */
160                 void mark_dirty (int x, int y, int width, int height) {
161                         _surface->mark_dirty (x, y, width, height);
162                 }
163
164         private:
165                 Cairo::RefPtr<Cairo::ImageSurface> _surface;
166                 Cairo::RefPtr<Cairo::Context> _ctx;
167                 Cairo::Context ctx;
168 };
169
170 class PangoLayout {
171         public:
172                 /** Create a new PangoLayout Text Display
173                  * @param c CairoContext for the layout
174                  * @param font_name a font-description e.g. "Mono 8px"
175                  */
176                 PangoLayout (Cairo::Context* c, std::string font_name) {
177                         ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
178                         _layout = Glib::wrap (pl);
179                         Pango::FontDescription fd (font_name);
180                         _layout->set_font_description (fd);
181                 }
182
183                 ~PangoLayout () {}
184
185                 /** Gets the text in the layout. The returned text should not
186                  * be freed or modified.
187                  *
188                  * @return The text in the @a layout.
189                  */
190                 std::string get_text () const {
191                         return _layout->get_text ();
192                 }
193                 /** Set the text of the layout.
194                  * @param text The text for the layout.
195                  */
196                 void set_text (const std::string& text) {
197                         _layout->set_text (text);
198                 }
199
200                 /** Sets the layout text and attribute list from marked-up text (see markup format).
201                  * Replaces the current text and attribute list.
202                  * @param markup Some marked-up text.
203                  */
204                 void set_markup (const std::string& markup) {
205                         _layout->set_markup (markup);
206                 }
207
208                 /** Sets the width to which the lines of the Pango::Layout should wrap or
209                  * ellipsized.  The default value is -1: no width set.
210                  *
211                  * @param width The desired width in Pango units, or -1 to indicate that no
212                  * wrapping or ellipsization should be performed.
213                  */
214                 void set_width (float width) {
215                         _layout->set_width (width * PANGO_SCALE);
216                 }
217
218                 /** Gets the width to which the lines of the Pango::Layout should wrap.
219                  *
220                  * @return The width in Pango units, or -1 if no width set.
221                  */
222                 int get_width () const {
223                         return _layout->get_width () / PANGO_SCALE;
224                 }
225
226                 /** Sets the type of ellipsization being performed for @a layout.
227                  * Depending on the ellipsization mode @a ellipsize text is
228                  * removed from the start, middle, or end of text so they
229                  * fit within the width and height of layout set with
230                  * set_width() and set_height().
231                  *
232                  * If the layout contains characters such as newlines that
233                  * force it to be layed out in multiple paragraphs, then whether
234                  * each paragraph is ellipsized separately or the entire layout
235                  * is ellipsized as a whole depends on the set height of the layout.
236                  * See set_height() for details.
237                  *
238                  * @param ellipsize The new ellipsization mode for @a layout.
239                  */
240                 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
241                         _layout->set_ellipsize (ellipsize);
242                 }
243
244                 /** Gets the type of ellipsization being performed for @a layout.
245                  * See set_ellipsize()
246                  *
247                  * @return The current ellipsization mode for @a layout.
248                  *
249                  * Use is_ellipsized() to query whether any paragraphs
250                  * were actually ellipsized.
251                  */
252                 Pango::EllipsizeMode get_ellipsize () const {
253                         return _layout->get_ellipsize ();
254                 }
255
256                 /** Queries whether the layout had to ellipsize any paragraphs.
257                  *
258                  * This returns <tt>true</tt> if the ellipsization mode for @a layout
259                  * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
260                  * and there are paragraphs exceeding that width that have to be
261                  * ellipsized.
262                  *
263                  * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
264                  * otherwise.
265                  */
266                 bool is_ellipsized () const {
267                         return _layout->is_ellipsized ();
268                 }
269
270                 /** Sets the alignment for the layout: how partial lines are
271                  * positioned within the horizontal space available.
272                  * @param alignment The alignment.
273                  */
274                 void set_alignment(Pango::Alignment alignment) {
275                         _layout->set_alignment (alignment);
276                 }
277
278                 /** Gets the alignment for the layout: how partial lines are
279                  * positioned within the horizontal space available.
280                  * @return The alignment.
281                  */
282                 Pango::Alignment get_alignment() const {
283                         return _layout->get_alignment ();
284                 }
285
286                 /** Sets the wrap mode; the wrap mode only has effect if a width
287                  * is set on the layout with set_width().
288                  * To turn off wrapping, set the width to -1.
289                  *
290                  * @param wrap The wrap mode.
291                  */
292                 void set_wrap (Pango::WrapMode wrap) {
293                         _layout->set_width (wrap);
294                 }
295
296                 /** Gets the wrap mode for the layout.
297                  *
298                  * Use is_wrapped() to query whether any paragraphs
299                  * were actually wrapped.
300                  *
301                  * @return Active wrap mode.
302                  */
303                 Pango::WrapMode get_wrap () const {
304                         return _layout->get_wrap ();
305                 }
306
307                 /** Queries whether the layout had to wrap any paragraphs.
308                  *
309                  * This returns <tt>true</tt> if a positive width is set on @a layout,
310                  * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
311                  * and there are paragraphs exceeding the layout width that have
312                  * to be wrapped.
313                  *
314                  * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
315                  * otherwise.
316                  */
317                 bool is_wrapped () const {
318                         return _layout->is_wrapped ();
319                 }
320
321                 /** Determines the logical width and height of a Pango::Layout
322                  * in device units.
323                  */
324                 int get_pixel_size (lua_State *L) {
325                         int width, height;
326                         _layout->get_pixel_size (width, height);
327                         luabridge::Stack<int>::push (L, width);
328                         luabridge::Stack<int>::push (L, height);
329                         return 2;
330                 }
331
332                 /** Draws a Layout in the specified Cairo @a context. The top-left
333                  *  corner of the Layout will be drawn at the current point of the
334                  *  cairo context.
335                  *
336                  * @param context A Cairo context.
337                  */
338                 void show_in_cairo_context (Cairo::Context* c) {
339                         pango_cairo_update_layout (c->cobj (), _layout->gobj());
340                         pango_cairo_show_layout (c->cobj (), _layout->gobj());
341                 }
342
343                 void layout_cairo_path (Cairo::Context* c) {
344                         pango_cairo_update_layout (c->cobj (), _layout->gobj());
345                         pango_cairo_layout_path (c->cobj (), _layout->gobj());
346                 }
347
348         private:
349                 Glib::RefPtr<Pango::Layout> _layout;
350 };
351
352 }; // namespace
353
354 ////////////////////////////////////////////////////////////////////////////////
355
356 namespace LuaSignal {
357
358 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
359 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
360 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
361
362 LuaSignal
363 str2luasignal (const std::string &str) {
364         const char* type = str.c_str();
365         if (0) { }
366 #       include "luasignal_syms.h"
367         else {
368                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
369                 abort(); /*NOTREACHED*/
370         }
371 }
372 #undef STATIC
373 #undef SESSION
374 #undef ENGINE
375
376 #define STATIC(name,c,p) N_(#name),
377 #define SESSION(name,c,p) N_(#name),
378 #define ENGINE(name,c,p) N_(#name),
379 const char *luasignalstr[] = {
380 #       include "luasignal_syms.h"
381         0
382 };
383
384 #undef STATIC
385 #undef SESSION
386 #undef ENGINE
387 }; // namespace
388
389
390 static std::string http_get_unlogged (const std::string& url) { return ArdourCurl::http_get (url, false); }
391
392 /** special cases for Ardour's Mixer UI */
393 namespace LuaMixer {
394
395         ProcessorBox::ProcSelection
396         processor_selection () {
397                 return ProcessorBox::current_processor_selection ();
398         }
399
400 };
401
402 static void mixer_screenshot (const std::string& fn) {
403         Mixer_UI::instance()->screenshot (fn);
404 }
405
406 /** Access libardour global configuration */
407 static UIConfiguration* _ui_config () {
408         return &UIConfiguration::instance();
409 }
410
411
412 ////////////////////////////////////////////////////////////////////////////////
413
414 static PBD::ScopedConnectionList _luaexecs;
415
416 static void reaper (ARDOUR::SystemExec* x)
417 {
418         delete x;
419 }
420
421 static int
422 lua_forkexec (lua_State *L)
423 {
424         int argc = lua_gettop (L);
425         if (argc == 0) {
426                 return luaL_argerror (L, 1, "invalid number of arguments, forkexec (command, ...)");
427         }
428         // args are free()ed in ~SystemExec
429         char** args = (char**) malloc ((argc + 1) * sizeof(char*));
430         for (int i = 0; i < argc; ++i) {
431                 args[i] = strdup (luaL_checkstring (L, i + 1));
432         }
433         args[argc] = 0;
434
435         ARDOUR::SystemExec* x = new ARDOUR::SystemExec (args[0], args);
436         x->Terminated.connect (_luaexecs, MISSING_INVALIDATOR, boost::bind (&reaper, x), gui_context());
437
438         if (x->start()) {
439                 reaper (x);
440                 luabridge::Stack<bool>::push (L, false);
441                 return -1;
442         } else {
443                 luabridge::Stack<bool>::push (L, false);
444         }
445         return 1;
446 }
447
448 #ifndef PLATFORM_WINDOWS
449 static int
450 lua_exec (std::string cmd)
451 {
452         // args are free()ed in ~SystemExec
453         char** args = (char**) malloc (4 * sizeof(char*));
454         args[0] = strdup ("/bin/sh");
455         args[1] = strdup ("-c");
456         args[2] = strdup (cmd.c_str());
457         args[3] = 0;
458         ARDOUR::SystemExec x ("/bin/sh", args);
459         if (x.start()) {
460                 return -1;
461         }
462         x.wait ();
463         return 0;
464 }
465 #endif
466
467 ////////////////////////////////////////////////////////////////////////////////
468
469 static int
470 lua_actionlist (lua_State *L)
471 {
472         using namespace std;
473
474         vector<string> paths;
475         vector<string> labels;
476         vector<string> tooltips;
477         vector<string> keys;
478         vector<Glib::RefPtr<Gtk::Action> > actions;
479         ActionManager::get_all_actions (paths, labels, tooltips, keys, actions);
480
481         vector<string>::iterator p;
482         vector<string>::iterator l;
483
484         luabridge::LuaRef action_tbl (luabridge::newTable (L));
485
486         for (l = labels.begin(), p = paths.begin(); l != labels.end(); ++p, ++l) {
487                 if (l->empty ()) {
488                         continue;
489                 }
490
491                 vector<string> parts;
492                 split (*p, parts, '/');
493
494                 if (parts.empty()) {
495                         continue;
496                 }
497
498                 //kinda kludgy way to avoid displaying menu items as mappable
499                 if (parts[1] == _("Main_menu"))
500                         continue;
501                 if (parts[1] == _("JACK"))
502                         continue;
503                 if (parts[1] == _("redirectmenu"))
504                         continue;
505                 if (parts[1] == _("RegionList"))
506                         continue;
507                 if (parts[1] == _("ProcessorMenu"))
508                         continue;
509
510                 if (!action_tbl[parts[1]].isTable()) {
511                         action_tbl[parts[1]] = luabridge::newTable (L);
512                 }
513                 assert (action_tbl[parts[1]].isTable());
514                 luabridge::LuaRef tbl (action_tbl[parts[1]]);
515                 assert (tbl.isTable());
516                 tbl[*l] = *p;
517         }
518
519         luabridge::push (L, action_tbl);
520         return 1;
521 }
522
523 ////////////////////////////////////////////////////////////////////////////////
524
525 // ARDOUR_UI and instance() are not exposed.
526 ARDOUR::PresentationInfo::order_t
527 lua_translate_order (RouteDialogs::InsertAt place)
528 {
529         return ARDOUR_UI::instance()->translate_order (place);
530 }
531
532 ////////////////////////////////////////////////////////////////////////////////
533
534 #define xstr(s) stringify(s)
535 #define stringify(s) #s
536
537 using namespace ARDOUR;
538
539 PBD::Signal0<void> LuaInstance::LuaTimerS;
540 PBD::Signal0<void> LuaInstance::LuaTimerDS;
541 PBD::Signal0<void> LuaInstance::SetSession;
542
543 void
544 LuaInstance::register_hooks (lua_State* L)
545 {
546
547 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
548 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
549 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
550         luabridge::getGlobalNamespace (L)
551                 .beginNamespace ("LuaSignal")
552 #               include "luasignal_syms.h"
553                 .endNamespace ();
554 #undef ENGINE
555 #undef SESSION
556 #undef STATIC
557
558         luabridge::getGlobalNamespace (L)
559                 .beginNamespace ("LuaSignal")
560                 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
561                 .endClass()
562                 .endNamespace ();
563
564 #if 0 // Dump size -> libs/ardour/luabindings.cc
565         printf ("LuaInstance: registered %d signals\n", LuaSignal::LAST_SIGNAL);
566 #endif
567 }
568
569 void
570 LuaInstance::bind_cairo (lua_State* L)
571 {
572         /* std::vector<double> for set_dash()
573          * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
574          *
575          * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
576          * the address of the one in libardour.dll is mapped when loading the .dll
577          *
578          * see LuaBindings::set_session() for a detailed explanation
579          */
580         luabridge::getGlobalNamespace (L)
581                 .beginNamespace ("C")
582                 .registerArray <double> ("DoubleArray")
583                 .beginStdVector <double> ("DoubleVector")
584                 .endClass ()
585                 .endNamespace ();
586
587         luabridge::getGlobalNamespace (L)
588                 .beginNamespace ("Cairo")
589                 .beginClass <Cairo::Context> ("Context")
590                 .addFunction ("save", &Cairo::Context::save)
591                 .addFunction ("restore", &Cairo::Context::restore)
592                 .addFunction ("set_operator", &Cairo::Context::set_operator)
593                 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
594                 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
595                 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
596                 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
597                 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
598                 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
599                 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
600                 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
601                 .addFunction ("translate", &Cairo::Context::translate)
602                 .addFunction ("scale", &Cairo::Context::scale)
603                 .addFunction ("rotate", &Cairo::Context::rotate)
604                 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
605                 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
606                 .addFunction ("move_to", &Cairo::Context::move_to)
607                 .addFunction ("line_to", &Cairo::Context::line_to)
608                 .addFunction ("curve_to", &Cairo::Context::curve_to)
609                 .addFunction ("arc", &Cairo::Context::arc)
610                 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
611                 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
612                 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
613                 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
614                 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
615                 .addFunction ("close_path", &Cairo::Context::close_path)
616                 .addFunction ("paint", &Cairo::Context::paint)
617                 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
618                 .addFunction ("stroke", &Cairo::Context::stroke)
619                 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
620                 .addFunction ("fill", &Cairo::Context::fill)
621                 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
622                 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
623                 .addFunction ("clip", &Cairo::Context::clip)
624                 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
625                 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
626                 .addFunction ("show_text", &Cairo::Context::show_text)
627                 .endClass ()
628                 /* enums */
629                 // LineCap, LineJoin, Operator
630                 .beginNamespace ("LineCap")
631                 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
632                 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
633                 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
634                 .endNamespace ()
635
636                 .beginNamespace ("LineJoin")
637                 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
638                 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
639                 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
640                 .endNamespace ()
641
642                 .beginNamespace ("Operator")
643                 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
644                 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
645                 .addConst ("Over", CAIRO_OPERATOR_OVER)
646                 .addConst ("Add", CAIRO_OPERATOR_ADD)
647                 .endNamespace ()
648
649                 .beginNamespace ("Format")
650                 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
651                 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
652                 .endNamespace ()
653
654                 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
655                 .addConstructor <void (*) (Cairo::Format, int, int)> ()
656                 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
657                 .addFunction ("context", &LuaCairo::ImageSurface::context)
658                 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
659                 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
660                 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
661                 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
662                 .endClass ()
663
664                 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
665                 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
666                 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
667                 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
668                 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
669                 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
670                 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
671                 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
672                 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
673                 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
674                 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
675                 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
676                 .addFunction ("set_alignment", &LuaCairo::PangoLayout::set_alignment)
677                 .addFunction ("get_alignment", &LuaCairo::PangoLayout::get_alignment)
678                 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
679                 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
680                 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
681                 .endClass ()
682
683                 /* enums */
684                 .beginNamespace ("EllipsizeMode")
685                 .addConst ("None", Pango::ELLIPSIZE_NONE)
686                 .addConst ("Start", Pango::ELLIPSIZE_START)
687                 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
688                 .addConst ("End", Pango::ELLIPSIZE_END)
689                 .endNamespace ()
690
691                 .beginNamespace ("Alignment")
692                 .addConst ("Left", Pango::ALIGN_LEFT)
693                 .addConst ("Center", Pango::ALIGN_CENTER)
694                 .addConst ("Right", Pango::ALIGN_RIGHT)
695                 .endNamespace ()
696
697                 .beginNamespace ("WrapMode")
698                 .addConst ("Word", Pango::WRAP_WORD)
699                 .addConst ("Char", Pango::WRAP_CHAR)
700                 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
701                 .endNamespace ()
702
703                 .endNamespace ();
704
705 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
706   one can work around this as follows:
707
708   LuaState lua;
709   LuaInstance::register_classes (lua.getState());
710   lua.do_command (
711       "function render (ctx)"
712       "  ctx:rectangle (0, 0, 100, 100)"
713       "  ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
714       "  ctx:fill ()"
715       " end"
716       );
717   {
718                 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
719     Cairo::Context ctx (context->cobj ());
720
721     luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
722     lua_render ((Cairo::Context *)&ctx);
723   }
724 */
725
726 }
727
728 void
729 LuaInstance::bind_dialog (lua_State* L)
730 {
731         luabridge::getGlobalNamespace (L)
732                 .beginNamespace ("LuaDialog")
733
734                 .beginClass <LuaDialog::Message> ("Message")
735                 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
736                 .addFunction ("run", &LuaDialog::Message::run)
737                 .endClass ()
738
739                 .beginClass <LuaDialog::Dialog> ("Dialog")
740                 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
741                 .addCFunction ("run", &LuaDialog::Dialog::run)
742                 .endClass ()
743
744                 /* enums */
745                 .beginNamespace ("MessageType")
746                 .addConst ("Info", LuaDialog::Message::Info)
747                 .addConst ("Warning", LuaDialog::Message::Warning)
748                 .addConst ("Question", LuaDialog::Message::Question)
749                 .addConst ("Error", LuaDialog::Message::Error)
750                 .endNamespace ()
751
752                 .beginNamespace ("ButtonType")
753                 .addConst ("OK", LuaDialog::Message::OK)
754                 .addConst ("Close", LuaDialog::Message::Close)
755                 .addConst ("Cancel", LuaDialog::Message::Cancel)
756                 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
757                 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
758                 .endNamespace ()
759
760                 .beginNamespace ("Response")
761                 .addConst ("OK", 0)
762                 .addConst ("Cancel", 1)
763                 .addConst ("Close", 2)
764                 .addConst ("Yes", 3)
765                 .addConst ("No", 4)
766                 .addConst ("None", -1)
767                 .endNamespace ()
768
769                 .beginClass <LuaDialog::ProgressWindow> ("ProgressWindow")
770                 .addConstructor <void (*) (std::string const&, bool)> ()
771                 .addFunction ("progress", &LuaDialog::ProgressWindow::progress)
772                 .addFunction ("done", &LuaDialog::ProgressWindow::done)
773                 .addFunction ("canceled", &LuaDialog::ProgressWindow::canceled)
774                 .endClass ()
775
776                 .endNamespace ();
777 }
778
779 void
780 LuaInstance::register_classes (lua_State* L)
781 {
782         LuaBindings::stddef (L);
783         LuaBindings::common (L);
784         LuaBindings::session (L);
785         LuaBindings::osc (L);
786
787         bind_cairo (L);
788         bind_dialog (L);
789
790         luabridge::getGlobalNamespace (L)
791                 .beginNamespace ("ArdourUI")
792
793                 .addFunction ("http_get", &http_get_unlogged)
794
795                 .addFunction ("mixer_screenshot", &mixer_screenshot)
796
797                 .addFunction ("processor_selection", &LuaMixer::processor_selection)
798
799                 .beginStdCPtrList <ArdourMarker> ("ArdourMarkerList")
800                 .endClass ()
801
802                 .beginClass <ArdourMarker> ("ArdourMarker")
803                 .addFunction ("name", &ArdourMarker::name)
804                 .addFunction ("position", &ArdourMarker::position)
805                 .addFunction ("_type", &ArdourMarker::type)
806                 .endClass ()
807
808                 .beginClass <AxisView> ("AxisView")
809                 .endClass ()
810
811                 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
812                 .addFunction ("order", &TimeAxisView::order)
813                 .addFunction ("y_position", &TimeAxisView::y_position)
814                 .addFunction ("effective_height", &TimeAxisView::effective_height)
815                 .addFunction ("current_height", &TimeAxisView::current_height)
816                 .addFunction ("set_height", &TimeAxisView::set_height)
817                 .endClass ()
818
819                 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
820                 .endClass ()
821
822                 .beginClass <Selectable> ("Selectable")
823                 .endClass ()
824
825                 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
826                 .endClass ()
827
828                 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
829                 .endClass ()
830
831                 .deriveClass <RouteUI, Selectable> ("RouteUI")
832                 .endClass ()
833
834                 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
835                 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
836                 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
837                 .endClass ()
838
839                 // std::list<Selectable*>
840                 .beginStdCPtrList <Selectable> ("SelectionList")
841                 .endClass ()
842
843                 // std::list<TimeAxisView*>
844                 .beginConstStdCPtrList <TimeAxisView> ("TrackViewStdList")
845                 .endClass ()
846
847
848                 .beginClass <RegionSelection> ("RegionSelection")
849                 .addFunction ("start", &RegionSelection::start)
850                 .addFunction ("end_sample", &RegionSelection::end_sample)
851                 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
852                 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
853                 .endClass ()
854
855                 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
856                 .addFunction ("start", &TimeSelection::start)
857                 .addFunction ("end_sample", &TimeSelection::end_sample)
858                 .addFunction ("length", &TimeSelection::length)
859                 .endClass ()
860
861                 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
862                 .endClass ()
863
864                 .beginClass <TrackViewList> ("TrackViewList")
865                 .addCast<std::list<TimeAxisView*> > ("to_tav_list")
866                 .addFunction ("contains", &TrackViewList::contains)
867                 .addFunction ("routelist", &TrackViewList::routelist)
868                 .endClass ()
869
870                 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
871                 .endClass ()
872
873                 .beginClass <Selection> ("Selection")
874                 .addFunction ("clear", &Selection::clear)
875                 .addFunction ("clear_all", &Selection::clear_all)
876                 .addFunction ("empty", &Selection::empty)
877                 .addData ("tracks", &Selection::tracks)
878                 .addData ("regions", &Selection::regions)
879                 .addData ("time", &Selection::time)
880                 .addData ("markers", &Selection::markers)
881 #if 0
882                 .addData ("lines", &Selection::lines)
883                 .addData ("playlists", &Selection::playlists)
884                 .addData ("points", &Selection::points)
885                 .addData ("midi_regions", &Selection::midi_regions)
886                 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
887 #endif
888                 .endClass ()
889
890                 .beginClass <PublicEditor> ("Editor")
891                 .addFunction ("grid_type", &PublicEditor::grid_type)
892                 .addFunction ("snap_mode", &PublicEditor::snap_mode)
893                 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
894
895                 .addFunction ("undo", &PublicEditor::undo)
896                 .addFunction ("redo", &PublicEditor::redo)
897
898                 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
899                 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
900
901                 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
902
903                 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
904                 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
905                 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
906                 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
907
908                 .addFunction ("get_selection", &PublicEditor::get_selection)
909                 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
910                 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
911
912                 .addFunction ("set_selection", &PublicEditor::set_selection)
913
914                 .addFunction ("play_selection", &PublicEditor::play_selection)
915                 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
916                 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
917                 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
918
919                 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
920                 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
921
922                 .addFunction ("update_grid", &PublicEditor::update_grid)
923                 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
924
925                 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
926                 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
927
928                 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
929
930                 .addRefFunction ("do_import", &PublicEditor::do_import)
931                 .addRefFunction ("do_embed", &PublicEditor::do_embed)
932
933                 .addFunction ("export_audio", &PublicEditor::export_audio)
934                 .addFunction ("stem_export", &PublicEditor::stem_export)
935                 .addFunction ("export_selection", &PublicEditor::export_selection)
936                 .addFunction ("export_range", &PublicEditor::export_range)
937
938                 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
939                 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
940                 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
941                 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
942
943                 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
944                 .addFunction ("new_playlists", &PublicEditor::new_playlists)
945                 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
946                 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
947
948                 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
949                 .addFunction ("deselect_all", &PublicEditor::deselect_all)
950
951 #if 0 // TimeAxisView&  can't be bound (pure virtual fn)
952                 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
953                 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
954                 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
955 #endif
956                 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
957                 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
958                 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
959                 .addFunction ("fit_selection", &PublicEditor::fit_selection)
960
961                 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
962                 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
963                 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
964                 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
965                 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
966
967                 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
968                 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
969                 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
970                 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
971                 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
972                 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
973
974                 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
975                 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
976                 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
977                 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
978
979                 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
980                 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
981                 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
982
983                 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
984
985                 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
986                 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
987                 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
988
989                 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
990                 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
991
992                 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
993                 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
994                 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
995                 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
996
997                 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
998                 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
999                 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
1000                 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
1001
1002 #if 0
1003                 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
1004                 .addFunction ("drags", &PublicEditor::drags)
1005 #endif
1006
1007                 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
1008                 .addFunction ("get_track_views", &PublicEditor::get_track_views)
1009                 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
1010                 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
1011
1012                 .addFunction ("center_screen", &PublicEditor::center_screen)
1013
1014                 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
1015                 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
1016
1017                 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
1018                 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
1019                 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
1020 #if 0
1021                 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
1022                 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
1023                 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
1024                 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
1025                 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
1026 #endif
1027
1028 #if 0
1029                 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
1030                 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
1031                 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
1032                 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
1033 #endif
1034
1035                 .addFunction ("access_action", &PublicEditor::access_action)
1036                 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
1037                 .endClass ()
1038
1039                 .addFunction ("translate_order", &lua_translate_order)
1040
1041                 /* ArdourUI enums */
1042                 .beginNamespace ("InsertAt")
1043                 .addConst ("BeforeSelection", RouteDialogs::InsertAt(RouteDialogs::BeforeSelection))
1044                 .addConst ("AfterSelection", RouteDialogs::InsertAt(RouteDialogs::AfterSelection))
1045                 .addConst ("First", RouteDialogs::InsertAt(RouteDialogs::First))
1046                 .addConst ("Last", RouteDialogs::InsertAt(RouteDialogs::Last))
1047                 .endNamespace ()
1048
1049                 .beginNamespace ("MarkerType")
1050                 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
1051                 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
1052                 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
1053                 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
1054                 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
1055                 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
1056                 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
1057                 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
1058                 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
1059                 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
1060                 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
1061                 .endNamespace ()
1062
1063                 .beginNamespace ("SelectionOp")
1064                 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
1065                 .addConst ("Set", Selection::Operation(Selection::Set))
1066                 .addConst ("Extend", Selection::Operation(Selection::Extend))
1067                 .addConst ("Add", Selection::Operation(Selection::Add))
1068                 .endNamespace ()
1069
1070                 .beginNamespace ("TrackHeightMode")
1071                 .addConst ("OnlySelf", TimeAxisView::TrackHeightMode(TimeAxisView::OnlySelf))
1072                 .addConst ("TotalHeight", TimeAxisView::TrackHeightMode(TimeAxisView::TotalHeight))
1073                 .addConst ("HeightPerLane,", TimeAxisView::TrackHeightMode(TimeAxisView::HeightPerLane))
1074                 .endNamespace ()
1075
1076                 .addCFunction ("actionlist", &lua_actionlist)
1077
1078
1079                 .beginClass <UIConfiguration> ("UIConfiguration")
1080 #undef  UI_CONFIG_VARIABLE
1081 #define UI_CONFIG_VARIABLE(Type,var,name,value) \
1082                 .addFunction ("get_" # var, &UIConfiguration::get_##var) \
1083                 .addFunction ("set_" # var, &UIConfiguration::set_##var) \
1084                 .addProperty (#var, &UIConfiguration::get_##var, &UIConfiguration::set_##var)
1085
1086 #include "ui_config_vars.h"
1087
1088 #undef UI_CONFIG_VARIABLE
1089                 .endClass()
1090
1091                 .addFunction ("config", &_ui_config)
1092
1093                 .endNamespace () // end ArdourUI
1094
1095                 .beginNamespace ("os")
1096 #ifndef PLATFORM_WINDOWS
1097                 .addFunction ("execute", &lua_exec)
1098 #endif
1099                 .addCFunction ("forkexec", &lua_forkexec)
1100                 .endNamespace ();
1101
1102         // Editing Symbols
1103
1104 #undef ZOOMFOCUS
1105 #undef GRIDTYPE
1106 #undef SNAPMODE
1107 #undef MOUSEMODE
1108 #undef DISPLAYCONTROL
1109 #undef IMPORTMODE
1110 #undef IMPORTPOSITION
1111 #undef IMPORTDISPOSITION
1112
1113 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
1114 #define GRIDTYPE(NAME) .addConst (stringify(NAME), (Editing::GridType)Editing::NAME)
1115 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
1116 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
1117 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
1118 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
1119 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
1120 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
1121         luabridge::getGlobalNamespace (L)
1122                 .beginNamespace ("Editing")
1123 #               include "editing_syms.h"
1124                 .endNamespace ();
1125 }
1126
1127 #undef xstr
1128 #undef stringify
1129
1130 ////////////////////////////////////////////////////////////////////////////////
1131
1132 using namespace ARDOUR;
1133 using namespace ARDOUR_UI_UTILS;
1134 using namespace PBD;
1135 using namespace std;
1136
1137 static void _lua_print (std::string s) {
1138 #ifndef NDEBUG
1139         std::cout << "LuaInstance: " << s << "\n";
1140 #endif
1141         PBD::info << "LuaInstance: " << s << endmsg;
1142 }
1143
1144 LuaInstance* LuaInstance::_instance = 0;
1145
1146 LuaInstance*
1147 LuaInstance::instance ()
1148 {
1149         if (!_instance) {
1150                 _instance  = new LuaInstance;
1151         }
1152
1153         return _instance;
1154 }
1155
1156 void
1157 LuaInstance::destroy_instance ()
1158 {
1159         delete _instance;
1160         _instance = 0;
1161 }
1162
1163 LuaInstance::LuaInstance ()
1164 {
1165         lua.Print.connect (&_lua_print);
1166         init ();
1167 }
1168
1169 LuaInstance::~LuaInstance ()
1170 {
1171         delete _lua_call_action;
1172         delete _lua_render_icon;
1173         delete _lua_add_action;
1174         delete _lua_del_action;
1175         delete _lua_get_action;
1176
1177         delete _lua_load;
1178         delete _lua_save;
1179         delete _lua_clear;
1180         _callbacks.clear();
1181 }
1182
1183 void
1184 LuaInstance::init ()
1185 {
1186         lua.sandbox (false);
1187         lua.do_command (
1188                         "function ScriptManager ()"
1189                         "  local self = { scripts = {}, instances = {}, icons = {} }"
1190                         ""
1191                         "  local remove = function (id)"
1192                         "   self.scripts[id] = nil"
1193                         "   self.instances[id] = nil"
1194                         "   self.icons[id] = nil"
1195                         "  end"
1196                         ""
1197                         "  local addinternal = function (i, n, s, f, c, a)"
1198                         "   assert(type(i) == 'number', 'id must be numeric')"
1199                         "   assert(type(n) == 'string', 'Name must be string')"
1200                         "   assert(type(s) == 'string', 'Script must be string')"
1201                         "   assert(type(f) == 'function', 'Factory is a not a function')"
1202                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1203                         "   self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1204                         "   local env = _ENV; env.f = nil"
1205                         "   self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1206                         "   if type(c) == 'function' then"
1207                         "     self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1208                         "   else"
1209                         "     self.icons[i] = nil"
1210                         "   end"
1211                         "  end"
1212                         ""
1213                         "  local call = function (id)"
1214                         "   if type(self.instances[id]) == 'function' then"
1215                         "     local status, err = pcall (self.instances[id])"
1216                         "     if not status then"
1217                         "       print ('action \"'.. id .. '\": ', err)" // error out
1218                         "       remove (id)"
1219                         "     end"
1220                         "   end"
1221                         "   collectgarbage()"
1222                         "  end"
1223                         ""
1224                         "  local icon = function (id, ...)"
1225                         "   if type(self.icons[id]) == 'function' then"
1226                         "     pcall (self.icons[id], ...)"
1227                         "   end"
1228                         "   collectgarbage()"
1229                         "  end"
1230                         ""
1231                         "  local add = function (i, n, s, b, c, a)"
1232                         "   assert(type(b) == 'string', 'ByteCode must be string')"
1233                         "   f = nil load (b)()" // assigns f
1234                         "   icn = nil load (c)()" // may assign "icn"
1235                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1236                         "   addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1237                         "  end"
1238                         ""
1239                         "  local get = function (id)"
1240                         "   if type(self.scripts[id]) == 'table' then"
1241                         "    return { ['name'] = self.scripts[id]['n'],"
1242                         "             ['script'] = self.scripts[id]['s'],"
1243                         "             ['icon'] = type(self.scripts[id]['c']) == 'function',"
1244                         "             ['args'] = self.scripts[id]['a'] }"
1245                         "   end"
1246                         "   return nil"
1247                         "  end"
1248                         ""
1249                         "  local function basic_serialize (o)"
1250                         "    if type(o) == \"number\" then"
1251                         "     return tostring(o)"
1252                         "    else"
1253                         "     return string.format(\"%q\", o)"
1254                         "    end"
1255                         "  end"
1256                         ""
1257                         "  local function serialize (name, value)"
1258                         "   local rv = name .. ' = '"
1259                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1260                         "    return rv .. basic_serialize(value) .. ' '"
1261                         "   elseif type(value) == \"table\" then"
1262                         "    rv = rv .. '{} '"
1263                         "    for k,v in pairs(value) do"
1264                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1265                         "     rv = rv .. serialize(fieldname, v) .. ' '"
1266                         "    end"
1267                         "    return rv;"
1268                         "   elseif type(value) == \"function\" then"
1269                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
1270                         "   elseif type(value) == \"boolean\" then"
1271                         "     return rv .. tostring (value)"
1272                         "   else"
1273                         "    error('cannot save a ' .. type(value))"
1274                         "   end"
1275                         "  end"
1276                         ""
1277                         ""
1278                         "  local save = function ()"
1279                         "   return (serialize('scripts', self.scripts))"
1280                         "  end"
1281                         ""
1282                         "  local clear = function ()"
1283                         "   self.scripts = {}"
1284                         "   self.instances = {}"
1285                         "   self.icons = {}"
1286                         "   collectgarbage()"
1287                         "  end"
1288                         ""
1289                         "  local restore = function (state)"
1290                         "   clear()"
1291                         "   load (state)()"
1292                         "   for i, s in pairs (scripts) do"
1293                         "    addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1294                         "   end"
1295                         "   collectgarbage()"
1296                         "  end"
1297                         ""
1298                         " return { call = call, add = add, remove = remove, get = get,"
1299                         "          restore = restore, save = save, clear = clear, icon = icon}"
1300                         " end"
1301                         " "
1302                         " manager = ScriptManager ()"
1303                         " ScriptManager = nil"
1304                         );
1305         lua_State* L = lua.getState();
1306
1307         try {
1308                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1309                 lua.do_command ("manager = nil"); // hide it.
1310                 lua.do_command ("collectgarbage()");
1311
1312                 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1313                 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1314                 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1315                 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1316                 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1317                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1318                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1319                 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1320
1321         } catch (luabridge::LuaException const& e) {
1322                 fatal << string_compose (_("programming error: %1"),
1323                                 std::string ("Failed to setup Lua action interpreter") + e.what ())
1324                         << endmsg;
1325                 abort(); /*NOTREACHED*/
1326         } catch (...) {
1327                 fatal << string_compose (_("programming error: %1"),
1328                                 X_("Failed to setup Lua action interpreter"))
1329                         << endmsg;
1330                 abort(); /*NOTREACHED*/
1331         }
1332
1333         register_classes (L);
1334         register_hooks (L);
1335
1336         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1337         lua_setglobal (L, "Editor");
1338 }
1339
1340 int
1341 LuaInstance::load_state ()
1342 {
1343         std::string uiscripts;
1344         if (!find_file (ardour_config_search_path(), ui_scripts_file_name, uiscripts)) {
1345                 pre_seed_scripts ();
1346                 return -1;
1347         }
1348         XMLTree tree;
1349
1350         info << string_compose (_("Loading user ui scripts file %1"), uiscripts) << endmsg;
1351
1352         if (!tree.read (uiscripts)) {
1353                 error << string_compose(_("cannot read ui scripts file \"%1\""), uiscripts) << endmsg;
1354                 return -1;
1355         }
1356
1357         if (set_state (*tree.root())) {
1358                 error << string_compose(_("user ui scripts file \"%1\" not loaded successfully."), uiscripts) << endmsg;
1359                 return -1;
1360         }
1361
1362         return 0;
1363 }
1364
1365 int
1366 LuaInstance::save_state ()
1367 {
1368         if (!_session) {
1369                 /* action scripts are un-registered with the session */
1370                 return -1;
1371         }
1372
1373         std::string uiscripts = Glib::build_filename (user_config_directory(), ui_scripts_file_name);
1374
1375         XMLNode* node = new XMLNode (X_("UIScripts"));
1376         node->add_child_nocopy (get_action_state ());
1377         node->add_child_nocopy (get_hook_state ());
1378
1379         XMLTree tree;
1380         tree.set_root (node);
1381
1382         if (!tree.write (uiscripts.c_str())){
1383                 error << string_compose (_("UI script file %1 not saved"), uiscripts) << endmsg;
1384                 return -1;
1385         }
1386         return 0;
1387 }
1388
1389 void
1390 LuaInstance::set_dirty ()
1391 {
1392         if (!_session || _session->deletion_in_progress()) {
1393                 return;
1394         }
1395         save_state ();
1396         _session->set_dirty (); // XXX is this reasonable?
1397 }
1398
1399 void LuaInstance::set_session (Session* s)
1400 {
1401         SessionHandlePtr::set_session (s);
1402         if (!_session) {
1403                 return;
1404         }
1405
1406         load_state ();
1407
1408         lua_State* L = lua.getState();
1409         LuaBindings::set_session (L, _session);
1410
1411         for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1412                 i->second->set_session (s);
1413         }
1414         second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_second));
1415         point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1416         SetSession (); /* EMIT SIGNAL */
1417 }
1418
1419 void
1420 LuaInstance::session_going_away ()
1421 {
1422         ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1423         second_connection.disconnect ();
1424         point_one_second_connection.disconnect ();
1425
1426         (*_lua_clear)();
1427         for (int i = 0; i < MAX_LUA_ACTION_SCRIPTS; ++i) {
1428                 ActionChanged (i, ""); /* EMIT SIGNAL */
1429         }
1430         SessionHandlePtr::session_going_away ();
1431         _session = 0;
1432
1433         lua_State* L = lua.getState();
1434         LuaBindings::set_session (L, _session);
1435         lua.do_command ("collectgarbage();");
1436 }
1437
1438 void
1439 LuaInstance::every_second ()
1440 {
1441         LuaTimerS (); // emit signal
1442 }
1443
1444 void
1445 LuaInstance::every_point_one_seconds ()
1446 {
1447         LuaTimerDS (); // emit signal
1448 }
1449
1450 int
1451 LuaInstance::set_state (const XMLNode& node)
1452 {
1453         XMLNode* child;
1454
1455         if ((child = find_named_node (node, "ActionScript"))) {
1456                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1457                         if (!(*n)->is_content ()) { continue; }
1458                         gsize size;
1459                         guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1460                         try {
1461                                 (*_lua_load)(std::string ((const char*)buf, size));
1462                         } catch (luabridge::LuaException const& e) {
1463                                 cerr << "LuaException:" << e.what () << endl;
1464                         } catch (...) { }
1465                         for (int i = 0; i < MAX_LUA_ACTION_SCRIPTS; ++i) {
1466                                 std::string name;
1467                                 if (lua_action_name (i, name)) {
1468                                         ActionChanged (i, name); /* EMIT SIGNAL */
1469                                 }
1470                         }
1471                         g_free (buf);
1472                 }
1473         }
1474
1475         assert (_callbacks.empty());
1476         if ((child = find_named_node (node, "ActionHooks"))) {
1477                 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1478                         try {
1479                                 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1480                                 _callbacks.insert (std::make_pair(p->id(), p));
1481                                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1482                                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1483                         } catch (luabridge::LuaException const& e) {
1484                                 cerr << "LuaException:" << e.what () << endl;
1485                         } catch (...) { }
1486                 }
1487         }
1488
1489         return 0;
1490 }
1491
1492 void
1493 LuaInstance::pre_seed_scripts ()
1494 {
1495         LuaScriptInfoPtr spi = LuaScripting::instance ().by_name ("Mixer Screenshot", LuaScriptInfo::EditorAction);
1496         int id = 0;
1497         if (spi) {
1498                 try {
1499                         std::string script = Glib::file_get_contents (spi->path);
1500                         LuaState ls;
1501                         register_classes (ls.getState ());
1502                         LuaScriptParamList lsp = LuaScriptParams::script_params (ls, spi->path, "action_params");
1503                         LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false, true));
1504                         lsp.push_back (lspp);
1505                         set_lua_action (id++, "Mixer Screenshot", script, lsp);
1506                 } catch (...) { }
1507         }
1508 }
1509
1510 bool
1511 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1512 {
1513         std::string title;
1514         std::string param_function = "action_params";
1515         std::vector<std::string> reg;
1516
1517         switch (type) {
1518                 case LuaScriptInfo::EditorAction:
1519                         reg = lua_action_names ();
1520                         title = _("Add Shortcut or Lua Script");
1521                         break;
1522                 case LuaScriptInfo::EditorHook:
1523                         reg = lua_slot_names ();
1524                         title = _("Add Lua Callback Hook");
1525                         break;
1526                 case LuaScriptInfo::Session:
1527                         if (!_session) {
1528                                 return false;
1529                         }
1530                         reg = _session->registered_lua_functions ();
1531                         title = _("Add Lua Session Script");
1532                         param_function = "sess_params";
1533                         break;
1534                 default:
1535                         return false;
1536         }
1537
1538         LuaScriptInfoPtr spi;
1539         ScriptSelector ss (title, type);
1540         switch (ss.run ()) {
1541                 case Gtk::RESPONSE_ACCEPT:
1542                         spi = ss.script();
1543                         break;
1544                 default:
1545                         return false;
1546         }
1547         ss.hide ();
1548
1549         std::string script = "";
1550
1551         try {
1552                 script = Glib::file_get_contents (spi->path);
1553         } catch (Glib::FileError const& e) {
1554                 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1555                 Gtk::MessageDialog am (msg);
1556                 am.run ();
1557                 return false;
1558         }
1559
1560         LuaState ls;
1561         register_classes (ls.getState ());
1562         LuaScriptParamList lsp = LuaScriptParams::script_params (ls, spi->path, param_function);
1563
1564         /* allow cancel */
1565         for (size_t i = 0; i < lsp.size(); ++i) {
1566                 if (lsp[i]->preseeded && lsp[i]->name == "x-script-abort") {
1567                         return false;
1568                 }
1569         }
1570
1571         ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1572
1573         if (spd.need_interation ()) {
1574                 switch (spd.run ()) {
1575                         case Gtk::RESPONSE_ACCEPT:
1576                                 break;
1577                         default:
1578                                 return false;
1579                 }
1580         }
1581
1582         LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false, true));
1583         lsp.push_back (lspp);
1584
1585         switch (type) {
1586                 case LuaScriptInfo::EditorAction:
1587                         return set_lua_action (id, spd.name(), script, lsp);
1588                         break;
1589                 case LuaScriptInfo::EditorHook:
1590                         return register_lua_slot (spd.name(), script, lsp);
1591                         break;
1592                 case LuaScriptInfo::Session:
1593                         try {
1594                                 _session->register_lua_function (spd.name(), script, lsp);
1595                         } catch (luabridge::LuaException const& e) {
1596                                 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1597                                 Gtk::MessageDialog am (msg);
1598                                 am.run ();
1599                         } catch (SessionException const& e) {
1600                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1601                                 Gtk::MessageDialog am (msg);
1602                                 am.run ();
1603                         } catch (...) {
1604                                 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1605                                 Gtk::MessageDialog am (msg);
1606                                 am.run ();
1607                         }
1608                 default:
1609                         break;
1610         }
1611         return false;
1612 }
1613
1614 XMLNode&
1615 LuaInstance::get_action_state ()
1616 {
1617         std::string saved;
1618         {
1619                 luabridge::LuaRef savedstate ((*_lua_save)());
1620                 saved = savedstate.cast<std::string>();
1621         }
1622         lua.collect_garbage ();
1623
1624         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1625         std::string b64s (b64);
1626         g_free (b64);
1627
1628         XMLNode* script_node = new XMLNode (X_("ActionScript"));
1629         script_node->set_property (X_("lua"), LUA_VERSION);
1630         script_node->add_content (b64s);
1631
1632         return *script_node;
1633 }
1634
1635 XMLNode&
1636 LuaInstance::get_hook_state ()
1637 {
1638         XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1639         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1640                 script_node->add_child_nocopy (i->second->get_state ());
1641         }
1642         return *script_node;
1643 }
1644
1645 void
1646 LuaInstance::call_action (const int id)
1647 {
1648         try {
1649                 (*_lua_call_action)(id + 1);
1650                 lua.collect_garbage_step ();
1651         } catch (luabridge::LuaException const& e) {
1652                 cerr << "LuaException:" << e.what () << endl;
1653         } catch (...) { }
1654 }
1655
1656 void
1657 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1658         int ii = reinterpret_cast<uintptr_t> (i);
1659         instance()->render_icon (ii, cr, w, h, c);
1660 }
1661
1662 void
1663 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1664 {
1665          Cairo::Context ctx (cr);
1666          try {
1667                  (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1668          } catch (luabridge::LuaException const& e) {
1669                  cerr << "LuaException:" << e.what () << endl;
1670          } catch (...) { }
1671 }
1672
1673 bool
1674 LuaInstance::set_lua_action (
1675                 const int id,
1676                 const std::string& name,
1677                 const std::string& script,
1678                 const LuaScriptParamList& args)
1679 {
1680         try {
1681                 lua_State* L = lua.getState();
1682                 // get bytcode of factory-function in a sandbox
1683                 // (don't allow scripts to interfere)
1684                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1685                 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1686                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1687                 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1688                         if ((*i)->optional && !(*i)->is_set) { continue; }
1689                         tbl_arg[(*i)->name] = (*i)->value;
1690                 }
1691                 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1692                 ActionChanged (id, name); /* EMIT SIGNAL */
1693         } catch (luabridge::LuaException const& e) {
1694                 cerr << "LuaException:" << e.what () << endl;
1695                 return false;
1696         } catch (...) {
1697                 return false;
1698         }
1699         set_dirty ();
1700         return true;
1701 }
1702
1703 bool
1704 LuaInstance::remove_lua_action (const int id)
1705 {
1706         try {
1707                 (*_lua_del_action)(id + 1);
1708         } catch (luabridge::LuaException const& e) {
1709                 cerr << "LuaException:" << e.what () << endl;
1710                 return false;
1711         } catch (...) {
1712                 return false;
1713         }
1714         ActionChanged (id, ""); /* EMIT SIGNAL */
1715         set_dirty ();
1716         return true;
1717 }
1718
1719 bool
1720 LuaInstance::lua_action_name (const int id, std::string& rv)
1721 {
1722         try {
1723                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1724                 if (ref.isNil()) {
1725                         return false;
1726                 }
1727                 if (ref["name"].isString()) {
1728                         rv = ref["name"].cast<std::string>();
1729                         return true;
1730                 }
1731                 return true;
1732         } catch (luabridge::LuaException const& e) {
1733                 cerr << "LuaException:" << e.what () << endl;
1734         } catch (...) { }
1735         return false;
1736 }
1737
1738 std::vector<std::string>
1739 LuaInstance::lua_action_names ()
1740 {
1741         std::vector<std::string> rv;
1742         for (int i = 0; i < MAX_LUA_ACTION_SCRIPTS; ++i) {
1743                 std::string name;
1744                 if (lua_action_name (i, name)) {
1745                         rv.push_back (name);
1746                 }
1747         }
1748         return rv;
1749 }
1750
1751 bool
1752 LuaInstance::lua_action_has_icon (const int id)
1753 {
1754         try {
1755                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1756                 if (ref.isNil()) {
1757                         return false;
1758                 }
1759                 if (ref["icon"].isBoolean()) {
1760                         return ref["icon"].cast<bool>();
1761                 }
1762         } catch (luabridge::LuaException const& e) {
1763                 cerr << "LuaException:" << e.what () << endl;
1764         } catch (...) { }
1765         return false;
1766 }
1767
1768 bool
1769 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1770 {
1771         try {
1772                 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1773                 if (ref.isNil()) {
1774                         return false;
1775                 }
1776                 if (!ref["name"].isString()) {
1777                         return false;
1778                 }
1779                 if (!ref["script"].isString()) {
1780                         return false;
1781                 }
1782                 if (!ref["args"].isTable()) {
1783                         return false;
1784                 }
1785                 name = ref["name"].cast<std::string>();
1786                 script = ref["script"].cast<std::string>();
1787
1788                 args.clear();
1789                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1790                 if (!lsi) {
1791                         return false;
1792                 }
1793                 args = LuaScriptParams::script_params (lsi, "action_params");
1794                 luabridge::LuaRef rargs (ref["args"]);
1795                 LuaScriptParams::ref_to_params (args, &rargs);
1796                 return true;
1797         } catch (luabridge::LuaException const& e) {
1798                 cerr << "LuaException:" << e.what () << endl;
1799         } catch (...) { }
1800         return false;
1801 }
1802
1803 bool
1804 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1805 {
1806         /* parse script, get ActionHook(s) from script */
1807         ActionHook ah;
1808         try {
1809                 LuaState l;
1810                 l.Print.connect (&_lua_print);
1811                 l.sandbox (true);
1812                 lua_State* L = l.getState();
1813                 register_hooks (L);
1814                 l.do_command ("function ardour () end");
1815                 l.do_command (script);
1816                 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1817                 if (signals.isFunction()) {
1818                         ah = signals();
1819                 }
1820         } catch (luabridge::LuaException const& e) {
1821                 cerr << "LuaException:" << e.what () << endl;
1822         } catch (...) { }
1823
1824         if (ah.none ()) {
1825                 cerr << "Script registered no hooks." << endl;
1826                 return false;
1827         }
1828
1829         /* register script w/args, get entry-point / ID */
1830
1831         try {
1832                 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1833                 _callbacks.insert (std::make_pair(p->id(), p));
1834                 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1835                 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1836                 set_dirty ();
1837                 return true;
1838         } catch (luabridge::LuaException const& e) {
1839                 cerr << "LuaException:" << e.what () << endl;
1840         } catch (...) { }
1841         return false;
1842 }
1843
1844 bool
1845 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1846 {
1847         LuaCallbackMap::iterator i = _callbacks.find (id);
1848         if (i != _callbacks.end()) {
1849                 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1850                 _callbacks.erase (i);
1851                 set_dirty ();
1852                 return true;
1853         }
1854         return false;
1855 }
1856
1857 std::vector<PBD::ID>
1858 LuaInstance::lua_slots () const
1859 {
1860         std::vector<PBD::ID> rv;
1861         for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1862                 rv.push_back (i->first);
1863         }
1864         return rv;
1865 }
1866
1867 bool
1868 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1869 {
1870         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1871         if (i != _callbacks.end()) {
1872                 name = i->second->name();
1873                 return true;
1874         }
1875         return false;
1876 }
1877
1878 std::vector<std::string>
1879 LuaInstance::lua_slot_names () const
1880 {
1881         std::vector<std::string> rv;
1882         std::vector<PBD::ID> ids = lua_slots();
1883         for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1884                 std::string name;
1885                 if (lua_slot_name (*i, name)) {
1886                         rv.push_back (name);
1887                 }
1888         }
1889         return rv;
1890 }
1891
1892 bool
1893 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1894 {
1895         LuaCallbackMap::const_iterator i = _callbacks.find (id);
1896         if (i == _callbacks.end()) {
1897                 return false; // error
1898         }
1899         return i->second->lua_slot (name, script, ah, args);
1900 }
1901
1902 ///////////////////////////////////////////////////////////////////////////////
1903
1904 LuaCallback::LuaCallback (Session *s,
1905                 const std::string& name,
1906                 const std::string& script,
1907                 const ActionHook& ah,
1908                 const ARDOUR::LuaScriptParamList& args)
1909         : SessionHandlePtr (s)
1910         , _id ("0")
1911         , _name (name)
1912         , _signals (ah)
1913 {
1914         // TODO: allow to reference object (e.g region)
1915         init ();
1916
1917         lua_State* L = lua.getState();
1918         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1919         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1920                 if ((*i)->optional && !(*i)->is_set) { continue; }
1921                 tbl_arg[(*i)->name] = (*i)->value;
1922         }
1923
1924         try {
1925                 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1926                 (*_lua_add)(name, script, bytecode, tbl_arg);
1927         } catch (luabridge::LuaException const& e) {
1928                 cerr << "LuaException:" << e.what () << endl;
1929                 throw failed_constructor ();
1930         } catch (...) {
1931                 throw failed_constructor ();
1932         }
1933
1934         _id.reset ();
1935         set_session (s);
1936 }
1937
1938 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1939         : SessionHandlePtr (s)
1940 {
1941         XMLNode* child = NULL;
1942         if (node.name() != X_("LuaCallback")
1943                         || !node.property ("signals")
1944                         || !node.property ("id")
1945                         || !node.property ("name")) {
1946                 throw failed_constructor ();
1947         }
1948
1949         for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1950                 if (!(*n)->is_content ()) { continue; }
1951                 child = *n;
1952         }
1953
1954         if (!child) {
1955                 throw failed_constructor ();
1956         }
1957
1958         init ();
1959
1960         _id = PBD::ID (node.property ("id")->value ());
1961         _name = node.property ("name")->value ();
1962         _signals = ActionHook (node.property ("signals")->value ());
1963
1964         gsize size;
1965         guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1966         try {
1967                 (*_lua_load)(std::string ((const char*)buf, size));
1968         } catch (luabridge::LuaException const& e) {
1969                 cerr << "LuaException:" << e.what () << endl;
1970         } catch (...) { }
1971         g_free (buf);
1972
1973         set_session (s);
1974 }
1975
1976 LuaCallback::~LuaCallback ()
1977 {
1978         delete _lua_add;
1979         delete _lua_get;
1980         delete _lua_call;
1981         delete _lua_load;
1982         delete _lua_save;
1983 }
1984
1985 XMLNode&
1986 LuaCallback::get_state (void)
1987 {
1988         std::string saved;
1989         {
1990                 luabridge::LuaRef savedstate ((*_lua_save)());
1991                 saved = savedstate.cast<std::string>();
1992         }
1993
1994         lua.collect_garbage (); // this may be expensive:
1995         /* Editor::instant_save() calls Editor::get_state() which
1996          * calls LuaInstance::get_hook_state() which in turn calls
1997          * this LuaCallback::get_state() for every registered hook.
1998          *
1999          * serialize in _lua_save() allocates many small strings
2000          * on the lua-stack, collecting them all may take a ms.
2001          */
2002
2003         gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
2004         std::string b64s (b64);
2005         g_free (b64);
2006
2007         XMLNode* script_node = new XMLNode (X_("LuaCallback"));
2008         script_node->set_property (X_("lua"), LUA_VERSION);
2009         script_node->set_property (X_("id"), _id.to_s ());
2010         script_node->set_property (X_("name"), _name);
2011         script_node->set_property (X_("signals"), _signals.to_string ());
2012         script_node->add_content (b64s);
2013         return *script_node;
2014 }
2015
2016 void
2017 LuaCallback::init (void)
2018 {
2019         lua.Print.connect (&_lua_print);
2020         lua.sandbox (false);
2021
2022         lua.do_command (
2023                         "function ScriptManager ()"
2024                         "  local self = { script = {}, instance = {} }"
2025                         ""
2026                         "  local addinternal = function (n, s, f, a)"
2027                         "   assert(type(n) == 'string', 'Name must be string')"
2028                         "   assert(type(s) == 'string', 'Script must be string')"
2029                         "   assert(type(f) == 'function', 'Factory is a not a function')"
2030                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
2031                         "   self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
2032                         "   local env = _ENV; env.f = nil"
2033                         "   self.instance = load (string.dump(f, true), nil, nil, env)(a)"
2034                         "  end"
2035                         ""
2036                         "  local call = function (...)"
2037                         "   if type(self.instance) == 'function' then"
2038                         "     local status, err = pcall (self.instance, ...)"
2039                         "     if not status then"
2040                         "       print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
2041                         "       self.script = nil"
2042                         "       self.instance = nil"
2043                         "       return false"
2044                         "     end"
2045                         "   end"
2046                         "   collectgarbage()"
2047                         "   return true"
2048                         "  end"
2049                         ""
2050                         "  local add = function (n, s, b, a)"
2051                         "   assert(type(b) == 'string', 'ByteCode must be string')"
2052                         "   load (b)()" // assigns f
2053                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
2054                         "   addinternal (n, s, load(f), a)"
2055                         "  end"
2056                         ""
2057                         "  local get = function ()"
2058                         "   if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
2059                         "    return { ['name'] = self.script['n'],"
2060                         "             ['script'] = self.script['s'],"
2061                         "             ['args'] = self.script['a'] }"
2062                         "   end"
2063                         "   return nil"
2064                         "  end"
2065                         ""
2066                         // code dup
2067                         ""
2068                         "  local function basic_serialize (o)"
2069                         "    if type(o) == \"number\" then"
2070                         "     return tostring(o)"
2071                         "    else"
2072                         "     return string.format(\"%q\", o)"
2073                         "    end"
2074                         "  end"
2075                         ""
2076                         "  local function serialize (name, value)"
2077                         "   local rv = name .. ' = '"
2078                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
2079                         "    return rv .. basic_serialize(value) .. ' '"
2080                         "   elseif type(value) == \"table\" then"
2081                         "    rv = rv .. '{} '"
2082                         "    for k,v in pairs(value) do"
2083                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
2084                         "     rv = rv .. serialize(fieldname, v) .. ' '"
2085                         "    end"
2086                         "    return rv;"
2087                         "   elseif type(value) == \"function\" then"
2088                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
2089                         "   elseif type(value) == \"boolean\" then"
2090                         "     return rv .. tostring (value)"
2091                         "   else"
2092                         "    error('cannot save a ' .. type(value))"
2093                         "   end"
2094                         "  end"
2095                         ""
2096                         // end code dup
2097                         ""
2098                         "  local save = function ()"
2099                         "   return (serialize('s', self.script))"
2100                         "  end"
2101                         ""
2102                         "  local restore = function (state)"
2103                         "   self.script = {}"
2104                         "   load (state)()"
2105                         "   addinternal (s['n'], s['s'], load(s['f']), s['a'])"
2106                         "  end"
2107                         ""
2108                         " return { call = call, add = add, get = get,"
2109                         "          restore = restore, save = save}"
2110                         " end"
2111                         " "
2112                         " manager = ScriptManager ()"
2113                         " ScriptManager = nil"
2114                         );
2115
2116         lua_State* L = lua.getState();
2117
2118         try {
2119                 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
2120                 lua.do_command ("manager = nil"); // hide it.
2121                 lua.do_command ("collectgarbage()");
2122
2123                 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
2124                 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
2125                 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
2126                 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
2127                 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
2128
2129         } catch (luabridge::LuaException const& e) {
2130                 fatal << string_compose (_("programming error: %1"),
2131                                 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
2132                         << endmsg;
2133                 abort(); /*NOTREACHED*/
2134         } catch (...) {
2135                 fatal << string_compose (_("programming error: %1"),
2136                                 X_("Failed to setup Lua callback interpreter"))
2137                         << endmsg;
2138                 abort(); /*NOTREACHED*/
2139         }
2140
2141         LuaInstance::register_classes (L);
2142         LuaInstance::register_hooks (L);
2143
2144         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
2145         lua_setglobal (L, "Editor");
2146 }
2147
2148 bool
2149 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
2150 {
2151         // TODO consolidate w/ LuaInstance::lua_action()
2152         try {
2153                 luabridge::LuaRef ref = (*_lua_get)();
2154                 if (ref.isNil()) {
2155                         return false;
2156                 }
2157                 if (!ref["name"].isString()) {
2158                         return false;
2159                 }
2160                 if (!ref["script"].isString()) {
2161                         return false;
2162                 }
2163                 if (!ref["args"].isTable()) {
2164                         return false;
2165                 }
2166
2167                 ah = _signals;
2168                 name = ref["name"].cast<std::string> ();
2169                 script = ref["script"].cast<std::string> ();
2170
2171                 args.clear();
2172                 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
2173                 if (!lsi) {
2174                         return false;
2175                 }
2176                 args = LuaScriptParams::script_params (lsi, "action_params");
2177                 luabridge::LuaRef rargs (ref["args"]);
2178                 LuaScriptParams::ref_to_params (args, &rargs);
2179                 return true;
2180         } catch (luabridge::LuaException const& e) {
2181                 cerr << "LuaException:" << e.what () << endl;
2182                 return false;
2183         } catch (...) { }
2184         return false;
2185 }
2186
2187 void
2188 LuaCallback::set_session (ARDOUR::Session *s)
2189 {
2190         SessionHandlePtr::set_session (s);
2191
2192         if (!_session) {
2193                 return;
2194         }
2195
2196         lua_State* L = lua.getState();
2197         LuaBindings::set_session (L, _session);
2198
2199         reconnect();
2200 }
2201
2202 void
2203 LuaCallback::session_going_away ()
2204 {
2205         ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
2206         lua.do_command ("collectgarbage();");
2207
2208         SessionHandlePtr::session_going_away ();
2209         _session = 0;
2210
2211         drop_callback (); /* EMIT SIGNAL */
2212 }
2213
2214 void
2215 LuaCallback::reconnect ()
2216 {
2217         _connections.drop_connections ();
2218         if ((*_lua_get) ().isNil ()) {
2219                 drop_callback (); /* EMIT SIGNAL */
2220                 return;
2221         }
2222
2223         // TODO pass object which emits the signal (e.g region)
2224         //
2225         // save/load bound objects will be tricky.
2226         // Best idea so far is to save/lookup the PBD::ID
2227         // (either use boost::any indirection or templates for bindable
2228         // object types or a switch statement..)
2229         //
2230         // _session->route_by_id ()
2231         // _session->track_by_diskstream_id ()
2232         // _session->source_by_id ()
2233         // _session->controllable_by_id ()
2234         // _session->processor_by_id ()
2235         // RegionFactory::region_by_id ()
2236         //
2237         // TODO loop over objects (if any)
2238
2239         reconnect_object ((void*)0);
2240 }
2241
2242 template <class T> void
2243 LuaCallback::reconnect_object (T obj)
2244 {
2245         for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
2246                 if (_signals[i]) {
2247 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
2248 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
2249 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
2250                         if (0) {}
2251 #                       include "luasignal_syms.h"
2252                         else {
2253                                 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
2254                                 abort(); /*NOTREACHED*/
2255                         }
2256 #undef ENGINE
2257 #undef SESSION
2258 #undef STATIC
2259                 }
2260         }
2261 }
2262
2263 template <typename T, typename S> void
2264 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2265         signal->connect (
2266                         _connections, invalidator (*this),
2267                         boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2268                         gui_context());
2269 }
2270
2271 template <typename T, typename C1> void
2272 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2273         signal->connect (
2274                         _connections, invalidator (*this),
2275                         boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2276                         gui_context());
2277 }
2278
2279 template <typename T, typename C1, typename C2> void
2280 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2281         signal->connect (
2282                         _connections, invalidator (*this),
2283                         boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2284                         gui_context());
2285 }
2286
2287 template <typename T, typename C1, typename C2, typename C3> void
2288 LuaCallback::connect_3 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal3<void, C1, C2, C3> *signal) {
2289         signal->connect (
2290                         _connections, invalidator (*this),
2291                         boost::bind (&LuaCallback::proxy_3<T, C1, C2, C3>, this, ls, ref, _1, _2, _3),
2292                         gui_context());
2293 }
2294
2295 template <typename T> void
2296 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2297         bool ok = true;
2298         {
2299                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2300                 if (! rv.cast<bool> ()) {
2301                         ok = false;
2302                 }
2303         }
2304         /* destroy LuaRef ^^ first before calling drop_callback() */
2305         if (!ok) {
2306                 drop_callback (); /* EMIT SIGNAL */
2307         }
2308 }
2309
2310 template <typename T, typename C1> void
2311 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2312         bool ok = true;
2313         {
2314                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2315                 if (! rv.cast<bool> ()) {
2316                         ok = false;
2317                 }
2318         }
2319         if (!ok) {
2320                 drop_callback (); /* EMIT SIGNAL */
2321         }
2322 }
2323
2324 template <typename T, typename C1, typename C2> void
2325 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2326         bool ok = true;
2327         {
2328                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2329                 if (! rv.cast<bool> ()) {
2330                         ok = false;
2331                 }
2332         }
2333         if (!ok) {
2334                 drop_callback (); /* EMIT SIGNAL */
2335         }
2336 }
2337
2338 template <typename T, typename C1, typename C2, typename C3> void
2339 LuaCallback::proxy_3 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2, C3 a3) {
2340         bool ok = true;
2341         {
2342                 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2, a3));
2343                 if (! rv.cast<bool> ()) {
2344                         ok = false;
2345                 }
2346         }
2347         if (!ok) {
2348                 drop_callback (); /* EMIT SIGNAL */
2349         }
2350 }