2 * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 #include <cairomm/context.h>
20 #include <cairomm/surface.h>
21 #include <pango/pangocairo.h>
23 #include "pbd/strsplit.h"
25 #include "gtkmm2ext/bindings.h"
26 #include "gtkmm2ext/gui_thread.h"
28 #include "ardour/audioengine.h"
29 #include "ardour/disk_reader.h"
30 #include "ardour/disk_writer.h"
31 #include "ardour/plugin_manager.h"
32 #include "ardour/route.h"
33 #include "ardour/session.h"
34 #include "ardour/system_exec.h"
36 #include "LuaBridge/LuaBridge.h"
38 #include "ardour_http.h"
39 #include "ardour_ui.h"
40 #include "public_editor.h"
41 #include "region_selection.h"
42 #include "luadialog.h"
43 #include "luainstance.h"
44 #include "luasignal.h"
46 #include "region_view.h"
47 #include "processor_box.h"
48 #include "time_axis_view.h"
49 #include "time_axis_view_item.h"
50 #include "selection.h"
51 #include "script_selector.h"
53 #include "utils_videotl.h"
58 /** wrap RefPtr< Cairo::ImageSurface >
60 * Image surfaces provide the ability to render to memory buffers either
61 * allocated by cairo or by the calling code. The supported image formats are
62 * those defined in Cairo::Format.
67 * Creates an image surface of the specified format and dimensions. Initially
68 * the surface contents are all 0. (Specifically, within each pixel, each
69 * color or alpha channel belonging to format will be 0. The contents of bits
70 * within a pixel, but not belonging to the given format are undefined).
72 * @param format format of pixels in the surface to create
73 * @param width width of the surface, in pixels
74 * @param height height of the surface, in pixels
76 ImageSurface (Cairo::Format format, int width, int height)
77 : _surface (Cairo::ImageSurface::create (format, width, height))
78 , _ctx (Cairo::Context::create (_surface))
79 , ctx (_ctx->cobj ()) {}
84 * Set this surface as source for another context.
85 * This allows to draw this surface
87 void set_as_source (Cairo::Context* c, int x, int y) {
89 c->set_source (_surface, x, y);
93 * Returns a context object to perform operations on the surface
95 Cairo::Context* context () {
96 return (Cairo::Context *)&ctx;
100 * Returns the stride of the image surface in bytes (or 0 if surface is not
101 * an image surface). The stride is the distance in bytes from the beginning
102 * of one row of the image data to the beginning of the next row.
104 int get_stride () const {
105 return _surface->get_stride ();
108 /** Gets the width of the ImageSurface in pixels */
109 int get_width () const {
110 return _surface->get_width ();
113 /** Gets the height of the ImageSurface in pixels */
114 int get_height () const {
115 return _surface->get_height ();
119 * Get a pointer to the data of the image surface, for direct
120 * inspection or modification.
122 * Return value: a pointer to the image data of this surface or NULL
123 * if @surface is not an image surface.
126 unsigned char* get_data () {
127 return _surface->get_data ();
130 /** Tells cairo to consider the data buffer dirty.
132 * In particular, if you've created an ImageSurface with a data buffer that
133 * you've allocated yourself and you draw to that data buffer using means
134 * other than cairo, you must call mark_dirty() before doing any additional
135 * drawing to that surface with cairo.
137 * Note that if you do draw to the Surface outside of cairo, you must call
138 * flush() before doing the drawing.
141 _surface->mark_dirty ();
144 /** Marks a rectangular area of the given surface dirty.
146 * @param x X coordinate of dirty rectangle
147 * @param y Y coordinate of dirty rectangle
148 * @param width width of dirty rectangle
149 * @param height height of dirty rectangle
151 void mark_dirty (int x, int y, int width, int height) {
152 _surface->mark_dirty (x, y, width, height);
156 Cairo::RefPtr<Cairo::ImageSurface> _surface;
157 Cairo::RefPtr<Cairo::Context> _ctx;
163 /** Create a new PangoLayout Text Display
164 * @param c CairoContext for the layout
165 * @param font_name a font-description e.g. "Mono 8px"
167 PangoLayout (Cairo::Context* c, std::string font_name) {
168 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
169 _layout = Glib::wrap (pl);
170 Pango::FontDescription fd (font_name);
171 _layout->set_font_description (fd);
176 /** Gets the text in the layout. The returned text should not
177 * be freed or modified.
179 * @return The text in the @a layout.
181 std::string get_text () const {
182 return _layout->get_text ();
184 /** Set the text of the layout.
185 * @param text The text for the layout.
187 void set_text (const std::string& text) {
188 _layout->set_text (text);
191 /** Sets the layout text and attribute list from marked-up text (see markup format).
192 * Replaces the current text and attribute list.
193 * @param markup Some marked-up text.
195 void set_markup (const std::string& markup) {
196 _layout->set_markup (markup);
199 /** Sets the width to which the lines of the Pango::Layout should wrap or
200 * ellipsized. The default value is -1: no width set.
202 * @param width The desired width in Pango units, or -1 to indicate that no
203 * wrapping or ellipsization should be performed.
205 void set_width (int width) {
206 _layout->set_width (width * PANGO_SCALE);
209 /** Gets the width to which the lines of the Pango::Layout should wrap.
211 * @return The width in Pango units, or -1 if no width set.
213 int get_width () const {
214 return _layout->get_width () / PANGO_SCALE;
217 /** Sets the type of ellipsization being performed for @a layout.
218 * Depending on the ellipsization mode @a ellipsize text is
219 * removed from the start, middle, or end of text so they
220 * fit within the width and height of layout set with
221 * set_width() and set_height().
223 * If the layout contains characters such as newlines that
224 * force it to be layed out in multiple paragraphs, then whether
225 * each paragraph is ellipsized separately or the entire layout
226 * is ellipsized as a whole depends on the set height of the layout.
227 * See set_height() for details.
229 * @param ellipsize The new ellipsization mode for @a layout.
231 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
232 _layout->set_ellipsize (ellipsize);
235 /** Gets the type of ellipsization being performed for @a layout.
236 * See set_ellipsize()
238 * @return The current ellipsization mode for @a layout.
240 * Use is_ellipsized() to query whether any paragraphs
241 * were actually ellipsized.
243 Pango::EllipsizeMode get_ellipsize () const {
244 return _layout->get_ellipsize ();
247 /** Queries whether the layout had to ellipsize any paragraphs.
249 * This returns <tt>true</tt> if the ellipsization mode for @a layout
250 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
251 * and there are paragraphs exceeding that width that have to be
254 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
257 bool is_ellipsized () const {
258 return _layout->is_ellipsized ();
261 /** Sets the wrap mode; the wrap mode only has effect if a width
262 * is set on the layout with set_width().
263 * To turn off wrapping, set the width to -1.
265 * @param wrap The wrap mode.
267 void set_wrap (Pango::WrapMode wrap) {
268 _layout->set_width (wrap);
271 /** Gets the wrap mode for the layout.
273 * Use is_wrapped() to query whether any paragraphs
274 * were actually wrapped.
276 * @return Active wrap mode.
278 Pango::WrapMode get_wrap () const {
279 return _layout->get_wrap ();
282 /** Queries whether the layout had to wrap any paragraphs.
284 * This returns <tt>true</tt> if a positive width is set on @a layout,
285 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
286 * and there are paragraphs exceeding the layout width that have
289 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
292 bool is_wrapped () const {
293 return _layout->is_wrapped ();
296 /** Determines the logical width and height of a Pango::Layout
299 int get_pixel_size (lua_State *L) {
301 _layout->get_pixel_size (width, height);
302 luabridge::Stack<int>::push (L, width);
303 luabridge::Stack<int>::push (L, height);
308 /** Draws a Layout in the specified Cairo @a context. The top-left
309 * corner of the Layout will be drawn at the current point of the
312 * @param context A Cairo context.
314 void show_in_cairo_context (Cairo::Context* c) {
315 pango_cairo_update_layout (c->cobj (), _layout->gobj());
316 pango_cairo_show_layout (c->cobj (), _layout->gobj());
319 void layout_cairo_path (Cairo::Context* c) {
320 pango_cairo_update_layout (c->cobj (), _layout->gobj());
321 pango_cairo_layout_path (c->cobj (), _layout->gobj());
325 Glib::RefPtr<Pango::Layout> _layout;
330 ////////////////////////////////////////////////////////////////////////////////
332 namespace LuaSignal {
334 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
335 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
336 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
339 str2luasignal (const std::string &str) {
340 const char* type = str.c_str();
342 # include "luasignal_syms.h"
344 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
345 abort(); /*NOTREACHED*/
352 #define STATIC(name,c,p) N_(#name),
353 #define SESSION(name,c,p) N_(#name),
354 #define ENGINE(name,c,p) N_(#name),
355 const char *luasignalstr[] = {
356 # include "luasignal_syms.h"
366 /** special cases for Ardour's Mixer UI */
369 ProcessorBox::ProcSelection
370 processor_selection () {
371 return ProcessorBox::current_processor_selection ();
376 ////////////////////////////////////////////////////////////////////////////////
378 static PBD::ScopedConnectionList _luaexecs;
380 static void reaper (ARDOUR::SystemExec* x)
386 lua_forkexec (lua_State *L)
388 int argc = lua_gettop (L);
390 return luaL_argerror (L, 1, "invalid number of arguments, forkexec (command, ...)");
392 // args are free()ed in ~SystemExec
393 char** args = (char**) malloc ((argc + 1) * sizeof(char*));
394 for (int i = 0; i < argc; ++i) {
395 args[i] = strdup (luaL_checkstring (L, i + 1));
399 ARDOUR::SystemExec* x = new ARDOUR::SystemExec (args[0], args);
400 x->Terminated.connect (_luaexecs, MISSING_INVALIDATOR, boost::bind (&reaper, x), gui_context());
404 luabridge::Stack<bool>::push (L, false);
407 luabridge::Stack<bool>::push (L, false);
412 #ifndef PLATFORM_WINDOWS
414 lua_exec (std::string cmd)
416 // args are free()ed in ~SystemExec
417 char** args = (char**) malloc (4 * sizeof(char*));
418 args[0] = strdup ("/bin/sh");
419 args[1] = strdup ("-c");
420 args[2] = strdup (cmd.c_str());
422 ARDOUR::SystemExec x ("/bin/sh", args);
431 ////////////////////////////////////////////////////////////////////////////////
434 lua_actionlist (lua_State *L)
438 vector<string> paths;
439 vector<string> labels;
440 vector<string> tooltips;
442 vector<Glib::RefPtr<Gtk::Action> > actions;
443 Gtkmm2ext::ActionMap::get_all_actions (paths, labels, tooltips, keys, actions);
445 vector<string>::iterator p;
446 vector<string>::iterator l;
448 luabridge::LuaRef action_tbl (luabridge::newTable (L));
450 for (l = labels.begin(), p = paths.begin(); l != labels.end(); ++p, ++l) {
455 vector<string> parts;
456 split (*p, parts, '/');
462 //kinda kludgy way to avoid displaying menu items as mappable
463 if (parts[1] == _("Main_menu"))
465 if (parts[1] == _("JACK"))
467 if (parts[1] == _("redirectmenu"))
469 if (parts[1] == _("Editor_menus"))
471 if (parts[1] == _("RegionList"))
473 if (parts[1] == _("ProcessorMenu"))
476 /* strip <Actions>/ from the start */
478 path = path.substr (strlen ("<Actions>/"));
480 if (!action_tbl[parts[1]].isTable()) {
481 action_tbl[parts[1]] = luabridge::newTable (L);
483 assert (action_tbl[parts[1]].isTable());
484 luabridge::LuaRef tbl (action_tbl[parts[1]]);
485 assert (tbl.isTable());
489 luabridge::push (L, action_tbl);
493 ////////////////////////////////////////////////////////////////////////////////
495 // ARDOUR_UI and instance() are not exposed.
496 ARDOUR::PresentationInfo::order_t
497 lua_translate_order (RouteDialogs::InsertAt place)
499 return ARDOUR_UI::instance()->translate_order (place);
502 ////////////////////////////////////////////////////////////////////////////////
504 #define xstr(s) stringify(s)
505 #define stringify(s) #s
507 using namespace ARDOUR;
509 PBD::Signal0<void> LuaInstance::LuaTimerDS;
510 PBD::Signal0<void> LuaInstance::SetSession;
513 LuaInstance::register_hooks (lua_State* L)
516 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
517 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
518 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
519 luabridge::getGlobalNamespace (L)
520 .beginNamespace ("LuaSignal")
521 # include "luasignal_syms.h"
527 luabridge::getGlobalNamespace (L)
528 .beginNamespace ("LuaSignal")
529 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
533 #if 0 // Dump size -> libs/ardour/luabindings.cc
534 printf ("LuaInstance: registered %d signals\n", LuaSignal::LAST_SIGNAL);
539 LuaInstance::bind_cairo (lua_State* L)
541 /* std::vector<double> for set_dash()
542 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
544 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
545 * the address of the one in libardour.dll is mapped when loading the .dll
547 * see LuaBindings::set_session() for a detailed explanation
549 luabridge::getGlobalNamespace (L)
550 .beginNamespace ("C")
551 .beginStdVector <double> ("DoubleVector")
555 luabridge::getGlobalNamespace (L)
556 .beginNamespace ("Cairo")
557 .beginClass <Cairo::Context> ("Context")
558 .addFunction ("save", &Cairo::Context::save)
559 .addFunction ("restore", &Cairo::Context::restore)
560 .addFunction ("set_operator", &Cairo::Context::set_operator)
561 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
562 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
563 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
564 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
565 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
566 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
567 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
568 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
569 .addFunction ("translate", &Cairo::Context::translate)
570 .addFunction ("scale", &Cairo::Context::scale)
571 .addFunction ("rotate", &Cairo::Context::rotate)
572 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
573 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
574 .addFunction ("move_to", &Cairo::Context::move_to)
575 .addFunction ("line_to", &Cairo::Context::line_to)
576 .addFunction ("curve_to", &Cairo::Context::curve_to)
577 .addFunction ("arc", &Cairo::Context::arc)
578 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
579 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
580 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
581 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
582 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
583 .addFunction ("close_path", &Cairo::Context::close_path)
584 .addFunction ("paint", &Cairo::Context::paint)
585 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
586 .addFunction ("stroke", &Cairo::Context::stroke)
587 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
588 .addFunction ("fill", &Cairo::Context::fill)
589 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
590 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
591 .addFunction ("clip", &Cairo::Context::clip)
592 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
593 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
594 .addFunction ("show_text", &Cairo::Context::show_text)
597 // LineCap, LineJoin, Operator
598 .beginNamespace ("LineCap")
599 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
600 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
601 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
604 .beginNamespace ("LineJoin")
605 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
606 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
607 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
610 .beginNamespace ("Operator")
611 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
612 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
613 .addConst ("Over", CAIRO_OPERATOR_OVER)
614 .addConst ("Add", CAIRO_OPERATOR_ADD)
617 .beginNamespace ("Format")
618 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
619 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
622 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
623 .addConstructor <void (*) (Cairo::Format, int, int)> ()
624 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
625 .addFunction ("context", &LuaCairo::ImageSurface::context)
626 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
627 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
628 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
629 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
632 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
633 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
634 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
635 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
636 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
637 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
638 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
639 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
640 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
641 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
642 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
643 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
644 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
645 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
646 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
650 .beginNamespace ("EllipsizeMode")
651 .addConst ("None", Pango::ELLIPSIZE_NONE)
652 .addConst ("Start", Pango::ELLIPSIZE_START)
653 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
654 .addConst ("End", Pango::ELLIPSIZE_END)
657 .beginNamespace ("WrapMode")
658 .addConst ("Word", Pango::WRAP_WORD)
659 .addConst ("Char", Pango::WRAP_CHAR)
660 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
665 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
666 one can work around this as follows:
669 LuaInstance::register_classes (lua.getState());
671 "function render (ctx)"
672 " ctx:rectangle (0, 0, 100, 100)"
673 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
678 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
679 Cairo::Context ctx (context->cobj ());
681 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
682 lua_render ((Cairo::Context *)&ctx);
689 LuaInstance::bind_dialog (lua_State* L)
691 luabridge::getGlobalNamespace (L)
692 .beginNamespace ("LuaDialog")
694 .beginClass <LuaDialog::Message> ("Message")
695 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
696 .addFunction ("run", &LuaDialog::Message::run)
699 .beginClass <LuaDialog::Dialog> ("Dialog")
700 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
701 .addCFunction ("run", &LuaDialog::Dialog::run)
705 .beginNamespace ("MessageType")
706 .addConst ("Info", LuaDialog::Message::Info)
707 .addConst ("Warning", LuaDialog::Message::Warning)
708 .addConst ("Question", LuaDialog::Message::Question)
709 .addConst ("Error", LuaDialog::Message::Error)
712 .beginNamespace ("ButtonType")
713 .addConst ("OK", LuaDialog::Message::OK)
714 .addConst ("Close", LuaDialog::Message::Close)
715 .addConst ("Cancel", LuaDialog::Message::Cancel)
716 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
717 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
720 .beginNamespace ("Response")
722 .addConst ("Cancel", 1)
723 .addConst ("Close", 2)
726 .addConst ("None", -1)
734 LuaInstance::register_classes (lua_State* L)
736 LuaBindings::stddef (L);
737 LuaBindings::common (L);
738 LuaBindings::session (L);
739 LuaBindings::osc (L);
744 luabridge::getGlobalNamespace (L)
745 .beginNamespace ("ArdourUI")
747 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get_unlogged)
749 .addFunction ("processor_selection", &LuaMixer::processor_selection)
751 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
754 .beginClass <ArdourMarker> ("ArdourMarker")
755 .addFunction ("name", &ArdourMarker::name)
756 .addFunction ("position", &ArdourMarker::position)
757 .addFunction ("_type", &ArdourMarker::type)
760 .beginClass <AxisView> ("AxisView")
763 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
766 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
769 .beginClass <Selectable> ("Selectable")
772 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
775 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
778 .deriveClass <RouteUI, Selectable> ("RouteUI")
781 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
782 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
783 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
786 // std::list<Selectable*>
787 .beginStdCPtrList <Selectable> ("SelectionList")
790 // std::list<TimeAxisView*>
791 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
795 .beginClass <RegionSelection> ("RegionSelection")
796 .addFunction ("start", &RegionSelection::start)
797 .addFunction ("end_sample", &RegionSelection::end_sample)
798 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
799 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
802 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
803 .addFunction ("start", &TimeSelection::start)
804 .addFunction ("end_sample", &TimeSelection::end_sample)
805 .addFunction ("length", &TimeSelection::length)
808 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
811 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
812 .addFunction ("contains", &TrackViewList::contains)
813 .addFunction ("routelist", &TrackViewList::routelist)
816 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
819 .beginClass <Selection> ("Selection")
820 .addFunction ("clear", &Selection::clear)
821 .addFunction ("clear_all", &Selection::clear_all)
822 .addFunction ("empty", &Selection::empty)
823 .addData ("tracks", &Selection::tracks)
824 .addData ("regions", &Selection::regions)
825 .addData ("time", &Selection::time)
826 .addData ("markers", &Selection::markers)
828 .addData ("lines", &Selection::lines)
829 .addData ("playlists", &Selection::playlists)
830 .addData ("points", &Selection::points)
831 .addData ("midi_regions", &Selection::midi_regions)
832 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
836 .beginClass <PublicEditor> ("Editor")
837 .addFunction ("grid_type", &PublicEditor::grid_type)
838 .addFunction ("snap_mode", &PublicEditor::snap_mode)
839 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
841 .addFunction ("undo", &PublicEditor::undo)
842 .addFunction ("redo", &PublicEditor::redo)
844 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
845 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
847 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
849 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
850 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
851 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
852 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
854 .addFunction ("get_selection", &PublicEditor::get_selection)
855 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
856 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
858 .addFunction ("set_selection", &PublicEditor::set_selection)
860 .addFunction ("play_selection", &PublicEditor::play_selection)
861 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
862 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
863 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
865 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
866 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
868 .addFunction ("update_grid", &PublicEditor::update_grid)
869 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
871 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
872 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
874 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
876 .addRefFunction ("do_import", &PublicEditor::do_import)
877 .addRefFunction ("do_embed", &PublicEditor::do_embed)
879 .addFunction ("export_audio", &PublicEditor::export_audio)
880 .addFunction ("stem_export", &PublicEditor::stem_export)
881 .addFunction ("export_selection", &PublicEditor::export_selection)
882 .addFunction ("export_range", &PublicEditor::export_range)
884 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
885 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
886 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
887 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
889 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
890 .addFunction ("new_playlists", &PublicEditor::new_playlists)
891 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
892 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
894 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
895 .addFunction ("deselect_all", &PublicEditor::deselect_all)
897 #if 0 // TimeAxisView& can't be bound (pure virtual fn)
898 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
899 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
900 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
902 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
903 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
904 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
905 .addFunction ("fit_selection", &PublicEditor::fit_selection)
907 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
908 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
909 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
910 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
911 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
913 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
914 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
915 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
916 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
917 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
918 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
920 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
921 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
922 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
923 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
925 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
926 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
927 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
929 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
931 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
932 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
933 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
935 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
936 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
938 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
939 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
940 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
941 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
943 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
944 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
945 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
946 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
949 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
950 .addFunction ("drags", &PublicEditor::drags)
953 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
954 .addFunction ("get_track_views", &PublicEditor::get_track_views)
955 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
956 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
958 .addFunction ("center_screen", &PublicEditor::center_screen)
960 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
961 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
963 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
964 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
965 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
967 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
968 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
969 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
970 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
971 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
975 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
976 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
977 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
978 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
981 .addFunction ("access_action", &PublicEditor::access_action)
982 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
985 .addFunction ("translate_order", &lua_translate_order)
988 .beginNamespace ("InsertAt")
989 .addConst ("BeforeSelection", RouteDialogs::InsertAt(RouteDialogs::BeforeSelection))
990 .addConst ("AfterSelection", RouteDialogs::InsertAt(RouteDialogs::AfterSelection))
991 .addConst ("First", RouteDialogs::InsertAt(RouteDialogs::First))
992 .addConst ("Last", RouteDialogs::InsertAt(RouteDialogs::Last))
995 .beginNamespace ("MarkerType")
996 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
997 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
998 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
999 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
1000 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
1001 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
1002 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
1003 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
1004 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
1005 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
1006 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
1009 .beginNamespace ("SelectionOp")
1010 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
1011 .addConst ("Set", Selection::Operation(Selection::Set))
1012 .addConst ("Extend", Selection::Operation(Selection::Extend))
1013 .addConst ("Add", Selection::Operation(Selection::Add))
1016 .addCFunction ("actionlist", &lua_actionlist)
1018 .endNamespace () // end ArdourUI
1020 .beginNamespace ("os")
1021 #ifndef PLATFORM_WINDOWS
1022 .addFunction ("execute", &lua_exec)
1024 .addCFunction ("forkexec", &lua_forkexec)
1033 #undef DISPLAYCONTROL
1035 #undef IMPORTPOSITION
1036 #undef IMPORTDISPOSITION
1038 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
1039 #define GRIDTYPE(NAME) .addConst (stringify(NAME), (Editing::GridType)Editing::NAME)
1040 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
1041 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
1042 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
1043 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
1044 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
1045 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
1046 luabridge::getGlobalNamespace (L)
1047 .beginNamespace ("Editing")
1048 # include "editing_syms.h"
1055 ////////////////////////////////////////////////////////////////////////////////
1057 using namespace ARDOUR;
1058 using namespace ARDOUR_UI_UTILS;
1059 using namespace PBD;
1060 using namespace std;
1062 static void _lua_print (std::string s) {
1064 std::cout << "LuaInstance: " << s << "\n";
1066 PBD::info << "LuaInstance: " << s << endmsg;
1069 LuaInstance* LuaInstance::_instance = 0;
1072 LuaInstance::instance ()
1075 _instance = new LuaInstance;
1082 LuaInstance::destroy_instance ()
1088 LuaInstance::LuaInstance ()
1090 lua.Print.connect (&_lua_print);
1093 LuaScriptParamList args;
1096 LuaInstance::~LuaInstance ()
1098 delete _lua_call_action;
1099 delete _lua_render_icon;
1100 delete _lua_add_action;
1101 delete _lua_del_action;
1102 delete _lua_get_action;
1111 LuaInstance::init ()
1113 lua.sandbox (false);
1115 "function ScriptManager ()"
1116 " local self = { scripts = {}, instances = {}, icons = {} }"
1118 " local remove = function (id)"
1119 " self.scripts[id] = nil"
1120 " self.instances[id] = nil"
1121 " self.icons[id] = nil"
1124 " local addinternal = function (i, n, s, f, c, a)"
1125 " assert(type(i) == 'number', 'id must be numeric')"
1126 " assert(type(n) == 'string', 'Name must be string')"
1127 " assert(type(s) == 'string', 'Script must be string')"
1128 " assert(type(f) == 'function', 'Factory is a not a function')"
1129 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1130 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1131 " local env = _ENV; env.f = nil"
1132 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1133 " if type(c) == 'function' then"
1134 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1136 " self.icons[i] = nil"
1140 " local call = function (id)"
1141 " if type(self.instances[id]) == 'function' then"
1142 " local status, err = pcall (self.instances[id])"
1143 " if not status then"
1144 " print ('action \"'.. id .. '\": ', err)" // error out
1151 " local icon = function (id, ...)"
1152 " if type(self.icons[id]) == 'function' then"
1153 " pcall (self.icons[id], ...)"
1158 " local add = function (i, n, s, b, c, a)"
1159 " assert(type(b) == 'string', 'ByteCode must be string')"
1160 " f = nil load (b)()" // assigns f
1161 " icn = nil load (c)()" // may assign "icn"
1162 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1163 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1166 " local get = function (id)"
1167 " if type(self.scripts[id]) == 'table' then"
1168 " return { ['name'] = self.scripts[id]['n'],"
1169 " ['script'] = self.scripts[id]['s'],"
1170 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
1171 " ['args'] = self.scripts[id]['a'] }"
1176 " local function basic_serialize (o)"
1177 " if type(o) == \"number\" then"
1178 " return tostring(o)"
1180 " return string.format(\"%q\", o)"
1184 " local function serialize (name, value)"
1185 " local rv = name .. ' = '"
1186 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1187 " return rv .. basic_serialize(value) .. ' '"
1188 " elseif type(value) == \"table\" then"
1190 " for k,v in pairs(value) do"
1191 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1192 " rv = rv .. serialize(fieldname, v) .. ' '"
1195 " elseif type(value) == \"function\" then"
1196 " return rv .. string.format(\"%q\", string.dump(value, true))"
1197 " elseif type(value) == \"boolean\" then"
1198 " return rv .. tostring (value)"
1200 " error('cannot save a ' .. type(value))"
1205 " local save = function ()"
1206 " return (serialize('scripts', self.scripts))"
1209 " local clear = function ()"
1210 " self.scripts = {}"
1211 " self.instances = {}"
1216 " local restore = function (state)"
1219 " for i, s in pairs (scripts) do"
1220 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1225 " return { call = call, add = add, remove = remove, get = get,"
1226 " restore = restore, save = save, clear = clear, icon = icon}"
1229 " manager = ScriptManager ()"
1230 " ScriptManager = nil"
1232 lua_State* L = lua.getState();
1235 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1236 lua.do_command ("manager = nil"); // hide it.
1237 lua.do_command ("collectgarbage()");
1239 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1240 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1241 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1242 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1243 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1244 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1245 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1246 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1248 } catch (luabridge::LuaException const& e) {
1249 fatal << string_compose (_("programming error: %1"),
1250 std::string ("Failed to setup Lua action interpreter") + e.what ())
1252 abort(); /*NOTREACHED*/
1254 fatal << string_compose (_("programming error: %1"),
1255 X_("Failed to setup Lua action interpreter"))
1257 abort(); /*NOTREACHED*/
1260 register_classes (L);
1263 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1264 lua_setglobal (L, "Editor");
1267 void LuaInstance::set_session (Session* s)
1269 SessionHandlePtr::set_session (s);
1274 lua_State* L = lua.getState();
1275 LuaBindings::set_session (L, _session);
1277 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1278 i->second->set_session (s);
1280 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1281 SetSession (); /* EMIT SIGNAL */
1285 LuaInstance::session_going_away ()
1287 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1288 point_one_second_connection.disconnect ();
1291 for (int i = 0; i < 9; ++i) {
1292 ActionChanged (i, ""); /* EMIT SIGNAL */
1294 SessionHandlePtr::session_going_away ();
1297 lua_State* L = lua.getState();
1298 LuaBindings::set_session (L, _session);
1299 lua.do_command ("collectgarbage();");
1303 LuaInstance::every_point_one_seconds ()
1305 LuaTimerDS (); // emit signal
1309 LuaInstance::set_state (const XMLNode& node)
1313 if ((child = find_named_node (node, "ActionScript"))) {
1314 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1315 if (!(*n)->is_content ()) { continue; }
1317 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1319 (*_lua_load)(std::string ((const char*)buf, size));
1320 } catch (luabridge::LuaException const& e) {
1321 cerr << "LuaException:" << e.what () << endl;
1323 for (int i = 0; i < 9; ++i) {
1325 if (lua_action_name (i, name)) {
1326 ActionChanged (i, name); /* EMIT SIGNAL */
1333 if ((child = find_named_node (node, "ActionHooks"))) {
1334 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1336 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1337 _callbacks.insert (std::make_pair(p->id(), p));
1338 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1339 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1340 } catch (luabridge::LuaException const& e) {
1341 cerr << "LuaException:" << e.what () << endl;
1350 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1353 std::string param_function = "action_params";
1354 std::vector<std::string> reg;
1357 case LuaScriptInfo::EditorAction:
1358 reg = lua_action_names ();
1359 title = _("Add Shortcut or Lua Script");
1361 case LuaScriptInfo::EditorHook:
1362 reg = lua_slot_names ();
1363 title = _("Add Lua Callback Hook");
1365 case LuaScriptInfo::Session:
1369 reg = _session->registered_lua_functions ();
1370 title = _("Add Lua Session Script");
1371 param_function = "sess_params";
1377 LuaScriptInfoPtr spi;
1378 ScriptSelector ss (title, type);
1379 switch (ss.run ()) {
1380 case Gtk::RESPONSE_ACCEPT:
1388 std::string script = "";
1391 script = Glib::file_get_contents (spi->path);
1392 } catch (Glib::FileError const& e) {
1393 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1394 Gtk::MessageDialog am (msg);
1400 register_classes (ls.getState ());
1401 LuaScriptParamList lsp = LuaScriptParams::script_params (ls, spi->path, param_function);
1404 for (size_t i = 0; i < lsp.size(); ++i) {
1405 if (lsp[i]->preseeded && lsp[i]->name == "x-script-abort") {
1410 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1412 if (spd.need_interation ()) {
1413 switch (spd.run ()) {
1414 case Gtk::RESPONSE_ACCEPT:
1421 LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false, true));
1422 lsp.push_back (lspp);
1425 case LuaScriptInfo::EditorAction:
1426 return set_lua_action (id, spd.name(), script, lsp);
1428 case LuaScriptInfo::EditorHook:
1429 return register_lua_slot (spd.name(), script, lsp);
1431 case LuaScriptInfo::Session:
1433 _session->register_lua_function (spd.name(), script, lsp);
1434 } catch (luabridge::LuaException const& e) {
1435 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1436 Gtk::MessageDialog am (msg);
1438 } catch (SessionException const& e) {
1439 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1440 Gtk::MessageDialog am (msg);
1443 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1444 Gtk::MessageDialog am (msg);
1454 LuaInstance::get_action_state ()
1458 luabridge::LuaRef savedstate ((*_lua_save)());
1459 saved = savedstate.cast<std::string>();
1461 lua.collect_garbage ();
1463 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1464 std::string b64s (b64);
1467 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1468 script_node->set_property (X_("lua"), LUA_VERSION);
1469 script_node->add_content (b64s);
1471 return *script_node;
1475 LuaInstance::get_hook_state ()
1477 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1478 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1479 script_node->add_child_nocopy (i->second->get_state ());
1481 return *script_node;
1485 LuaInstance::call_action (const int id)
1488 (*_lua_call_action)(id + 1);
1489 lua.collect_garbage_step ();
1490 } catch (luabridge::LuaException const& e) {
1491 cerr << "LuaException:" << e.what () << endl;
1496 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1497 int ii = reinterpret_cast<uintptr_t> (i);
1498 instance()->render_icon (ii, cr, w, h, c);
1502 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1504 Cairo::Context ctx (cr);
1506 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1507 } catch (luabridge::LuaException const& e) {
1508 cerr << "LuaException:" << e.what () << endl;
1513 LuaInstance::set_lua_action (
1515 const std::string& name,
1516 const std::string& script,
1517 const LuaScriptParamList& args)
1520 lua_State* L = lua.getState();
1521 // get bytcode of factory-function in a sandbox
1522 // (don't allow scripts to interfere)
1523 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1524 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1525 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1526 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1527 if ((*i)->optional && !(*i)->is_set) { continue; }
1528 tbl_arg[(*i)->name] = (*i)->value;
1530 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1531 ActionChanged (id, name); /* EMIT SIGNAL */
1532 } catch (luabridge::LuaException const& e) {
1533 cerr << "LuaException:" << e.what () << endl;
1538 _session->set_dirty ();
1543 LuaInstance::remove_lua_action (const int id)
1546 (*_lua_del_action)(id + 1);
1547 } catch (luabridge::LuaException const& e) {
1548 cerr << "LuaException:" << e.what () << endl;
1553 ActionChanged (id, ""); /* EMIT SIGNAL */
1554 _session->set_dirty ();
1559 LuaInstance::lua_action_name (const int id, std::string& rv)
1562 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1566 if (ref["name"].isString()) {
1567 rv = ref["name"].cast<std::string>();
1571 } catch (luabridge::LuaException const& e) {
1572 cerr << "LuaException:" << e.what () << endl;
1577 std::vector<std::string>
1578 LuaInstance::lua_action_names ()
1580 std::vector<std::string> rv;
1581 for (int i = 0; i < 9; ++i) {
1583 if (lua_action_name (i, name)) {
1584 rv.push_back (name);
1591 LuaInstance::lua_action_has_icon (const int id)
1594 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1598 if (ref["icon"].isBoolean()) {
1599 return ref["icon"].cast<bool>();
1601 } catch (luabridge::LuaException const& e) {
1602 cerr << "LuaException:" << e.what () << endl;
1608 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1611 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1615 if (!ref["name"].isString()) {
1618 if (!ref["script"].isString()) {
1621 if (!ref["args"].isTable()) {
1624 name = ref["name"].cast<std::string>();
1625 script = ref["script"].cast<std::string>();
1628 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1632 args = LuaScriptParams::script_params (lsi, "action_params");
1633 luabridge::LuaRef rargs (ref["args"]);
1634 LuaScriptParams::ref_to_params (args, &rargs);
1636 } catch (luabridge::LuaException const& e) {
1637 cerr << "LuaException:" << e.what () << endl;
1643 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1645 /* parse script, get ActionHook(s) from script */
1649 l.Print.connect (&_lua_print);
1651 lua_State* L = l.getState();
1653 l.do_command ("function ardour () end");
1654 l.do_command (script);
1655 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1656 if (signals.isFunction()) {
1659 } catch (luabridge::LuaException const& e) {
1660 cerr << "LuaException:" << e.what () << endl;
1664 cerr << "Script registered no hooks." << endl;
1668 /* register script w/args, get entry-point / ID */
1671 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1672 _callbacks.insert (std::make_pair(p->id(), p));
1673 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1674 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1676 } catch (luabridge::LuaException const& e) {
1677 cerr << "LuaException:" << e.what () << endl;
1679 _session->set_dirty ();
1684 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1686 LuaCallbackMap::iterator i = _callbacks.find (id);
1687 if (i != _callbacks.end()) {
1688 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1689 _callbacks.erase (i);
1692 _session->set_dirty ();
1696 std::vector<PBD::ID>
1697 LuaInstance::lua_slots () const
1699 std::vector<PBD::ID> rv;
1700 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1701 rv.push_back (i->first);
1707 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1709 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1710 if (i != _callbacks.end()) {
1711 name = i->second->name();
1717 std::vector<std::string>
1718 LuaInstance::lua_slot_names () const
1720 std::vector<std::string> rv;
1721 std::vector<PBD::ID> ids = lua_slots();
1722 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1724 if (lua_slot_name (*i, name)) {
1725 rv.push_back (name);
1732 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1734 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1735 if (i == _callbacks.end()) {
1736 return false; // error
1738 return i->second->lua_slot (name, script, ah, args);
1741 ///////////////////////////////////////////////////////////////////////////////
1743 LuaCallback::LuaCallback (Session *s,
1744 const std::string& name,
1745 const std::string& script,
1746 const ActionHook& ah,
1747 const ARDOUR::LuaScriptParamList& args)
1748 : SessionHandlePtr (s)
1753 // TODO: allow to reference object (e.g region)
1756 lua_State* L = lua.getState();
1757 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1758 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1759 if ((*i)->optional && !(*i)->is_set) { continue; }
1760 tbl_arg[(*i)->name] = (*i)->value;
1764 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1765 (*_lua_add)(name, script, bytecode, tbl_arg);
1766 } catch (luabridge::LuaException const& e) {
1767 cerr << "LuaException:" << e.what () << endl;
1768 throw failed_constructor ();
1770 throw failed_constructor ();
1777 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1778 : SessionHandlePtr (s)
1780 XMLNode* child = NULL;
1781 if (node.name() != X_("LuaCallback")
1782 || !node.property ("signals")
1783 || !node.property ("id")
1784 || !node.property ("name")) {
1785 throw failed_constructor ();
1788 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1789 if (!(*n)->is_content ()) { continue; }
1794 throw failed_constructor ();
1799 _id = PBD::ID (node.property ("id")->value ());
1800 _name = node.property ("name")->value ();
1801 _signals = ActionHook (node.property ("signals")->value ());
1804 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1806 (*_lua_load)(std::string ((const char*)buf, size));
1807 } catch (luabridge::LuaException const& e) {
1808 cerr << "LuaException:" << e.what () << endl;
1815 LuaCallback::~LuaCallback ()
1825 LuaCallback::get_state (void)
1829 luabridge::LuaRef savedstate ((*_lua_save)());
1830 saved = savedstate.cast<std::string>();
1833 lua.collect_garbage (); // this may be expensive:
1834 /* Editor::instant_save() calls Editor::get_state() which
1835 * calls LuaInstance::get_hook_state() which in turn calls
1836 * this LuaCallback::get_state() for every registered hook.
1838 * serialize in _lua_save() allocates many small strings
1839 * on the lua-stack, collecting them all may take a ms.
1842 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1843 std::string b64s (b64);
1846 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1847 script_node->set_property (X_("lua"), LUA_VERSION);
1848 script_node->set_property (X_("id"), _id.to_s ());
1849 script_node->set_property (X_("name"), _name);
1850 script_node->set_property (X_("signals"), _signals.to_string ());
1851 script_node->add_content (b64s);
1852 return *script_node;
1856 LuaCallback::init (void)
1858 lua.Print.connect (&_lua_print);
1859 lua.sandbox (false);
1862 "function ScriptManager ()"
1863 " local self = { script = {}, instance = {} }"
1865 " local addinternal = function (n, s, f, a)"
1866 " assert(type(n) == 'string', 'Name must be string')"
1867 " assert(type(s) == 'string', 'Script must be string')"
1868 " assert(type(f) == 'function', 'Factory is a not a function')"
1869 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1870 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1871 " local env = _ENV; env.f = nil"
1872 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1875 " local call = function (...)"
1876 " if type(self.instance) == 'function' then"
1877 " local status, err = pcall (self.instance, ...)"
1878 " if not status then"
1879 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1880 " self.script = nil"
1881 " self.instance = nil"
1889 " local add = function (n, s, b, a)"
1890 " assert(type(b) == 'string', 'ByteCode must be string')"
1891 " load (b)()" // assigns f
1892 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1893 " addinternal (n, s, load(f), a)"
1896 " local get = function ()"
1897 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1898 " return { ['name'] = self.script['n'],"
1899 " ['script'] = self.script['s'],"
1900 " ['args'] = self.script['a'] }"
1907 " local function basic_serialize (o)"
1908 " if type(o) == \"number\" then"
1909 " return tostring(o)"
1911 " return string.format(\"%q\", o)"
1915 " local function serialize (name, value)"
1916 " local rv = name .. ' = '"
1917 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1918 " return rv .. basic_serialize(value) .. ' '"
1919 " elseif type(value) == \"table\" then"
1921 " for k,v in pairs(value) do"
1922 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1923 " rv = rv .. serialize(fieldname, v) .. ' '"
1926 " elseif type(value) == \"function\" then"
1927 " return rv .. string.format(\"%q\", string.dump(value, true))"
1928 " elseif type(value) == \"boolean\" then"
1929 " return rv .. tostring (value)"
1931 " error('cannot save a ' .. type(value))"
1937 " local save = function ()"
1938 " return (serialize('s', self.script))"
1941 " local restore = function (state)"
1944 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1947 " return { call = call, add = add, get = get,"
1948 " restore = restore, save = save}"
1951 " manager = ScriptManager ()"
1952 " ScriptManager = nil"
1955 lua_State* L = lua.getState();
1958 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1959 lua.do_command ("manager = nil"); // hide it.
1960 lua.do_command ("collectgarbage()");
1962 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1963 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1964 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1965 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1966 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1968 } catch (luabridge::LuaException const& e) {
1969 fatal << string_compose (_("programming error: %1"),
1970 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
1972 abort(); /*NOTREACHED*/
1974 fatal << string_compose (_("programming error: %1"),
1975 X_("Failed to setup Lua callback interpreter"))
1977 abort(); /*NOTREACHED*/
1980 LuaInstance::register_classes (L);
1981 LuaInstance::register_hooks (L);
1983 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1984 lua_setglobal (L, "Editor");
1988 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1990 // TODO consolidate w/ LuaInstance::lua_action()
1992 luabridge::LuaRef ref = (*_lua_get)();
1996 if (!ref["name"].isString()) {
1999 if (!ref["script"].isString()) {
2002 if (!ref["args"].isTable()) {
2007 name = ref["name"].cast<std::string> ();
2008 script = ref["script"].cast<std::string> ();
2011 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
2015 args = LuaScriptParams::script_params (lsi, "action_params");
2016 luabridge::LuaRef rargs (ref["args"]);
2017 LuaScriptParams::ref_to_params (args, &rargs);
2019 } catch (luabridge::LuaException const& e) {
2020 cerr << "LuaException:" << e.what () << endl;
2027 LuaCallback::set_session (ARDOUR::Session *s)
2029 SessionHandlePtr::set_session (s);
2035 lua_State* L = lua.getState();
2036 LuaBindings::set_session (L, _session);
2042 LuaCallback::session_going_away ()
2044 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
2045 lua.do_command ("collectgarbage();");
2047 SessionHandlePtr::session_going_away ();
2050 drop_callback (); /* EMIT SIGNAL */
2054 LuaCallback::reconnect ()
2056 _connections.drop_connections ();
2057 if ((*_lua_get) ().isNil ()) {
2058 drop_callback (); /* EMIT SIGNAL */
2062 // TODO pass object which emits the signal (e.g region)
2064 // save/load bound objects will be tricky.
2065 // Best idea so far is to save/lookup the PBD::ID
2066 // (either use boost::any indirection or templates for bindable
2067 // object types or a switch statement..)
2069 // _session->route_by_id ()
2070 // _session->track_by_diskstream_id ()
2071 // _session->source_by_id ()
2072 // _session->controllable_by_id ()
2073 // _session->processor_by_id ()
2074 // RegionFactory::region_by_id ()
2076 // TODO loop over objects (if any)
2078 reconnect_object ((void*)0);
2081 template <class T> void
2082 LuaCallback::reconnect_object (T obj)
2084 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
2086 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
2087 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
2088 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
2090 # include "luasignal_syms.h"
2092 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
2093 abort(); /*NOTREACHED*/
2102 template <typename T, typename S> void
2103 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2105 _connections, invalidator (*this),
2106 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2110 template <typename T, typename C1> void
2111 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2113 _connections, invalidator (*this),
2114 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2118 template <typename T, typename C1, typename C2> void
2119 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2121 _connections, invalidator (*this),
2122 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2126 template <typename T, typename C1, typename C2, typename C3> void
2127 LuaCallback::connect_3 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal3<void, C1, C2, C3> *signal) {
2129 _connections, invalidator (*this),
2130 boost::bind (&LuaCallback::proxy_3<T, C1, C2, C3>, this, ls, ref, _1, _2, _3),
2134 template <typename T> void
2135 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2138 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2139 if (! rv.cast<bool> ()) {
2143 /* destroy LuaRef ^^ first before calling drop_callback() */
2145 drop_callback (); /* EMIT SIGNAL */
2149 template <typename T, typename C1> void
2150 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2153 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2154 if (! rv.cast<bool> ()) {
2159 drop_callback (); /* EMIT SIGNAL */
2163 template <typename T, typename C1, typename C2> void
2164 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2167 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2168 if (! rv.cast<bool> ()) {
2173 drop_callback (); /* EMIT SIGNAL */
2177 template <typename T, typename C1, typename C2, typename C3> void
2178 LuaCallback::proxy_3 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2, C3 a3) {
2181 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2, a3));
2182 if (! rv.cast<bool> ()) {
2187 drop_callback (); /* EMIT SIGNAL */