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 static std::string http_get_unlogged (const std::string& url) { return ArdourCurl::http_get (url, false); }
368 /** special cases for Ardour's Mixer UI */
371 ProcessorBox::ProcSelection
372 processor_selection () {
373 return ProcessorBox::current_processor_selection ();
378 ////////////////////////////////////////////////////////////////////////////////
380 static PBD::ScopedConnectionList _luaexecs;
382 static void reaper (ARDOUR::SystemExec* x)
388 lua_forkexec (lua_State *L)
390 int argc = lua_gettop (L);
392 return luaL_argerror (L, 1, "invalid number of arguments, forkexec (command, ...)");
394 // args are free()ed in ~SystemExec
395 char** args = (char**) malloc ((argc + 1) * sizeof(char*));
396 for (int i = 0; i < argc; ++i) {
397 args[i] = strdup (luaL_checkstring (L, i + 1));
401 ARDOUR::SystemExec* x = new ARDOUR::SystemExec (args[0], args);
402 x->Terminated.connect (_luaexecs, MISSING_INVALIDATOR, boost::bind (&reaper, x), gui_context());
406 luabridge::Stack<bool>::push (L, false);
409 luabridge::Stack<bool>::push (L, false);
414 #ifndef PLATFORM_WINDOWS
416 lua_exec (std::string cmd)
418 // args are free()ed in ~SystemExec
419 char** args = (char**) malloc (4 * sizeof(char*));
420 args[0] = strdup ("/bin/sh");
421 args[1] = strdup ("-c");
422 args[2] = strdup (cmd.c_str());
424 ARDOUR::SystemExec x ("/bin/sh", args);
433 ////////////////////////////////////////////////////////////////////////////////
436 lua_actionlist (lua_State *L)
440 vector<string> paths;
441 vector<string> labels;
442 vector<string> tooltips;
444 vector<Glib::RefPtr<Gtk::Action> > actions;
445 Gtkmm2ext::ActionMap::get_all_actions (paths, labels, tooltips, keys, actions);
447 vector<string>::iterator p;
448 vector<string>::iterator l;
450 luabridge::LuaRef action_tbl (luabridge::newTable (L));
452 for (l = labels.begin(), p = paths.begin(); l != labels.end(); ++p, ++l) {
457 vector<string> parts;
458 split (*p, parts, '/');
464 //kinda kludgy way to avoid displaying menu items as mappable
465 if (parts[1] == _("Main_menu"))
467 if (parts[1] == _("JACK"))
469 if (parts[1] == _("redirectmenu"))
471 if (parts[1] == _("Editor_menus"))
473 if (parts[1] == _("RegionList"))
475 if (parts[1] == _("ProcessorMenu"))
478 /* strip <Actions>/ from the start */
480 path = path.substr (strlen ("<Actions>/"));
482 if (!action_tbl[parts[1]].isTable()) {
483 action_tbl[parts[1]] = luabridge::newTable (L);
485 assert (action_tbl[parts[1]].isTable());
486 luabridge::LuaRef tbl (action_tbl[parts[1]]);
487 assert (tbl.isTable());
491 luabridge::push (L, action_tbl);
495 ////////////////////////////////////////////////////////////////////////////////
497 // ARDOUR_UI and instance() are not exposed.
498 ARDOUR::PresentationInfo::order_t
499 lua_translate_order (RouteDialogs::InsertAt place)
501 return ARDOUR_UI::instance()->translate_order (place);
504 ////////////////////////////////////////////////////////////////////////////////
506 #define xstr(s) stringify(s)
507 #define stringify(s) #s
509 using namespace ARDOUR;
511 PBD::Signal0<void> LuaInstance::LuaTimerDS;
512 PBD::Signal0<void> LuaInstance::SetSession;
515 LuaInstance::register_hooks (lua_State* L)
518 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
519 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
520 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
521 luabridge::getGlobalNamespace (L)
522 .beginNamespace ("LuaSignal")
523 # include "luasignal_syms.h"
529 luabridge::getGlobalNamespace (L)
530 .beginNamespace ("LuaSignal")
531 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
535 #if 0 // Dump size -> libs/ardour/luabindings.cc
536 printf ("LuaInstance: registered %d signals\n", LuaSignal::LAST_SIGNAL);
541 LuaInstance::bind_cairo (lua_State* L)
543 /* std::vector<double> for set_dash()
544 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
546 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
547 * the address of the one in libardour.dll is mapped when loading the .dll
549 * see LuaBindings::set_session() for a detailed explanation
551 luabridge::getGlobalNamespace (L)
552 .beginNamespace ("C")
553 .beginStdVector <double> ("DoubleVector")
557 luabridge::getGlobalNamespace (L)
558 .beginNamespace ("Cairo")
559 .beginClass <Cairo::Context> ("Context")
560 .addFunction ("save", &Cairo::Context::save)
561 .addFunction ("restore", &Cairo::Context::restore)
562 .addFunction ("set_operator", &Cairo::Context::set_operator)
563 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
564 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
565 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
566 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
567 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
568 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
569 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
570 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
571 .addFunction ("translate", &Cairo::Context::translate)
572 .addFunction ("scale", &Cairo::Context::scale)
573 .addFunction ("rotate", &Cairo::Context::rotate)
574 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
575 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
576 .addFunction ("move_to", &Cairo::Context::move_to)
577 .addFunction ("line_to", &Cairo::Context::line_to)
578 .addFunction ("curve_to", &Cairo::Context::curve_to)
579 .addFunction ("arc", &Cairo::Context::arc)
580 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
581 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
582 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
583 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
584 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
585 .addFunction ("close_path", &Cairo::Context::close_path)
586 .addFunction ("paint", &Cairo::Context::paint)
587 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
588 .addFunction ("stroke", &Cairo::Context::stroke)
589 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
590 .addFunction ("fill", &Cairo::Context::fill)
591 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
592 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
593 .addFunction ("clip", &Cairo::Context::clip)
594 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
595 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
596 .addFunction ("show_text", &Cairo::Context::show_text)
599 // LineCap, LineJoin, Operator
600 .beginNamespace ("LineCap")
601 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
602 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
603 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
606 .beginNamespace ("LineJoin")
607 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
608 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
609 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
612 .beginNamespace ("Operator")
613 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
614 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
615 .addConst ("Over", CAIRO_OPERATOR_OVER)
616 .addConst ("Add", CAIRO_OPERATOR_ADD)
619 .beginNamespace ("Format")
620 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
621 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
624 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
625 .addConstructor <void (*) (Cairo::Format, int, int)> ()
626 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
627 .addFunction ("context", &LuaCairo::ImageSurface::context)
628 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
629 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
630 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
631 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
634 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
635 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
636 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
637 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
638 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
639 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
640 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
641 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
642 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
643 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
644 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
645 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
646 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
647 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
648 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
652 .beginNamespace ("EllipsizeMode")
653 .addConst ("None", Pango::ELLIPSIZE_NONE)
654 .addConst ("Start", Pango::ELLIPSIZE_START)
655 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
656 .addConst ("End", Pango::ELLIPSIZE_END)
659 .beginNamespace ("WrapMode")
660 .addConst ("Word", Pango::WRAP_WORD)
661 .addConst ("Char", Pango::WRAP_CHAR)
662 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
667 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
668 one can work around this as follows:
671 LuaInstance::register_classes (lua.getState());
673 "function render (ctx)"
674 " ctx:rectangle (0, 0, 100, 100)"
675 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
680 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
681 Cairo::Context ctx (context->cobj ());
683 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
684 lua_render ((Cairo::Context *)&ctx);
691 LuaInstance::bind_dialog (lua_State* L)
693 luabridge::getGlobalNamespace (L)
694 .beginNamespace ("LuaDialog")
696 .beginClass <LuaDialog::Message> ("Message")
697 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
698 .addFunction ("run", &LuaDialog::Message::run)
701 .beginClass <LuaDialog::Dialog> ("Dialog")
702 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
703 .addCFunction ("run", &LuaDialog::Dialog::run)
707 .beginNamespace ("MessageType")
708 .addConst ("Info", LuaDialog::Message::Info)
709 .addConst ("Warning", LuaDialog::Message::Warning)
710 .addConst ("Question", LuaDialog::Message::Question)
711 .addConst ("Error", LuaDialog::Message::Error)
714 .beginNamespace ("ButtonType")
715 .addConst ("OK", LuaDialog::Message::OK)
716 .addConst ("Close", LuaDialog::Message::Close)
717 .addConst ("Cancel", LuaDialog::Message::Cancel)
718 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
719 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
722 .beginNamespace ("Response")
724 .addConst ("Cancel", 1)
725 .addConst ("Close", 2)
728 .addConst ("None", -1)
736 LuaInstance::register_classes (lua_State* L)
738 LuaBindings::stddef (L);
739 LuaBindings::common (L);
740 LuaBindings::session (L);
741 LuaBindings::osc (L);
746 luabridge::getGlobalNamespace (L)
747 .beginNamespace ("ArdourUI")
749 .addFunction ("http_get", &http_get_unlogged)
751 .addFunction ("processor_selection", &LuaMixer::processor_selection)
753 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
756 .beginClass <ArdourMarker> ("ArdourMarker")
757 .addFunction ("name", &ArdourMarker::name)
758 .addFunction ("position", &ArdourMarker::position)
759 .addFunction ("_type", &ArdourMarker::type)
762 .beginClass <AxisView> ("AxisView")
765 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
768 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
771 .beginClass <Selectable> ("Selectable")
774 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
777 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
780 .deriveClass <RouteUI, Selectable> ("RouteUI")
783 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
784 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
785 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
788 // std::list<Selectable*>
789 .beginStdCPtrList <Selectable> ("SelectionList")
792 // std::list<TimeAxisView*>
793 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
797 .beginClass <RegionSelection> ("RegionSelection")
798 .addFunction ("start", &RegionSelection::start)
799 .addFunction ("end_sample", &RegionSelection::end_sample)
800 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
801 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
804 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
805 .addFunction ("start", &TimeSelection::start)
806 .addFunction ("end_sample", &TimeSelection::end_sample)
807 .addFunction ("length", &TimeSelection::length)
810 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
813 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
814 .addFunction ("contains", &TrackViewList::contains)
815 .addFunction ("routelist", &TrackViewList::routelist)
818 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
821 .beginClass <Selection> ("Selection")
822 .addFunction ("clear", &Selection::clear)
823 .addFunction ("clear_all", &Selection::clear_all)
824 .addFunction ("empty", &Selection::empty)
825 .addData ("tracks", &Selection::tracks)
826 .addData ("regions", &Selection::regions)
827 .addData ("time", &Selection::time)
828 .addData ("markers", &Selection::markers)
830 .addData ("lines", &Selection::lines)
831 .addData ("playlists", &Selection::playlists)
832 .addData ("points", &Selection::points)
833 .addData ("midi_regions", &Selection::midi_regions)
834 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
838 .beginClass <PublicEditor> ("Editor")
839 .addFunction ("grid_type", &PublicEditor::grid_type)
840 .addFunction ("snap_mode", &PublicEditor::snap_mode)
841 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
843 .addFunction ("undo", &PublicEditor::undo)
844 .addFunction ("redo", &PublicEditor::redo)
846 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
847 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
849 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
851 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
852 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
853 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
854 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
856 .addFunction ("get_selection", &PublicEditor::get_selection)
857 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
858 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
860 .addFunction ("set_selection", &PublicEditor::set_selection)
862 .addFunction ("play_selection", &PublicEditor::play_selection)
863 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
864 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
865 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
867 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
868 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
870 .addFunction ("update_grid", &PublicEditor::update_grid)
871 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
873 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
874 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
876 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
878 .addRefFunction ("do_import", &PublicEditor::do_import)
879 .addRefFunction ("do_embed", &PublicEditor::do_embed)
881 .addFunction ("export_audio", &PublicEditor::export_audio)
882 .addFunction ("stem_export", &PublicEditor::stem_export)
883 .addFunction ("export_selection", &PublicEditor::export_selection)
884 .addFunction ("export_range", &PublicEditor::export_range)
886 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
887 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
888 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
889 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
891 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
892 .addFunction ("new_playlists", &PublicEditor::new_playlists)
893 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
894 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
896 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
897 .addFunction ("deselect_all", &PublicEditor::deselect_all)
899 #if 0 // TimeAxisView& can't be bound (pure virtual fn)
900 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
901 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
902 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
904 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
905 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
906 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
907 .addFunction ("fit_selection", &PublicEditor::fit_selection)
909 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
910 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
911 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
912 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
913 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
915 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
916 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
917 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
918 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
919 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
920 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
922 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
923 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
924 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
925 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
927 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
928 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
929 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
931 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
933 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
934 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
935 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
937 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
938 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
940 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
941 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
942 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
943 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
945 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
946 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
947 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
948 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
951 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
952 .addFunction ("drags", &PublicEditor::drags)
955 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
956 .addFunction ("get_track_views", &PublicEditor::get_track_views)
957 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
958 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
960 .addFunction ("center_screen", &PublicEditor::center_screen)
962 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
963 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
965 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
966 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
967 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
969 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
970 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
971 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
972 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
973 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
977 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
978 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
979 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
980 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
983 .addFunction ("access_action", &PublicEditor::access_action)
984 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
987 .addFunction ("translate_order", &lua_translate_order)
990 .beginNamespace ("InsertAt")
991 .addConst ("BeforeSelection", RouteDialogs::InsertAt(RouteDialogs::BeforeSelection))
992 .addConst ("AfterSelection", RouteDialogs::InsertAt(RouteDialogs::AfterSelection))
993 .addConst ("First", RouteDialogs::InsertAt(RouteDialogs::First))
994 .addConst ("Last", RouteDialogs::InsertAt(RouteDialogs::Last))
997 .beginNamespace ("MarkerType")
998 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
999 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
1000 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
1001 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
1002 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
1003 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
1004 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
1005 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
1006 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
1007 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
1008 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
1011 .beginNamespace ("SelectionOp")
1012 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
1013 .addConst ("Set", Selection::Operation(Selection::Set))
1014 .addConst ("Extend", Selection::Operation(Selection::Extend))
1015 .addConst ("Add", Selection::Operation(Selection::Add))
1018 .addCFunction ("actionlist", &lua_actionlist)
1020 .endNamespace () // end ArdourUI
1022 .beginNamespace ("os")
1023 #ifndef PLATFORM_WINDOWS
1024 .addFunction ("execute", &lua_exec)
1026 .addCFunction ("forkexec", &lua_forkexec)
1035 #undef DISPLAYCONTROL
1037 #undef IMPORTPOSITION
1038 #undef IMPORTDISPOSITION
1040 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
1041 #define GRIDTYPE(NAME) .addConst (stringify(NAME), (Editing::GridType)Editing::NAME)
1042 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
1043 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
1044 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
1045 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
1046 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
1047 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
1048 luabridge::getGlobalNamespace (L)
1049 .beginNamespace ("Editing")
1050 # include "editing_syms.h"
1057 ////////////////////////////////////////////////////////////////////////////////
1059 using namespace ARDOUR;
1060 using namespace ARDOUR_UI_UTILS;
1061 using namespace PBD;
1062 using namespace std;
1064 static void _lua_print (std::string s) {
1066 std::cout << "LuaInstance: " << s << "\n";
1068 PBD::info << "LuaInstance: " << s << endmsg;
1071 LuaInstance* LuaInstance::_instance = 0;
1074 LuaInstance::instance ()
1077 _instance = new LuaInstance;
1084 LuaInstance::destroy_instance ()
1090 LuaInstance::LuaInstance ()
1092 lua.Print.connect (&_lua_print);
1095 LuaScriptParamList args;
1098 LuaInstance::~LuaInstance ()
1100 delete _lua_call_action;
1101 delete _lua_render_icon;
1102 delete _lua_add_action;
1103 delete _lua_del_action;
1104 delete _lua_get_action;
1113 LuaInstance::init ()
1115 lua.sandbox (false);
1117 "function ScriptManager ()"
1118 " local self = { scripts = {}, instances = {}, icons = {} }"
1120 " local remove = function (id)"
1121 " self.scripts[id] = nil"
1122 " self.instances[id] = nil"
1123 " self.icons[id] = nil"
1126 " local addinternal = function (i, n, s, f, c, a)"
1127 " assert(type(i) == 'number', 'id must be numeric')"
1128 " assert(type(n) == 'string', 'Name must be string')"
1129 " assert(type(s) == 'string', 'Script must be string')"
1130 " assert(type(f) == 'function', 'Factory is a not a function')"
1131 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1132 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1133 " local env = _ENV; env.f = nil"
1134 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1135 " if type(c) == 'function' then"
1136 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1138 " self.icons[i] = nil"
1142 " local call = function (id)"
1143 " if type(self.instances[id]) == 'function' then"
1144 " local status, err = pcall (self.instances[id])"
1145 " if not status then"
1146 " print ('action \"'.. id .. '\": ', err)" // error out
1153 " local icon = function (id, ...)"
1154 " if type(self.icons[id]) == 'function' then"
1155 " pcall (self.icons[id], ...)"
1160 " local add = function (i, n, s, b, c, a)"
1161 " assert(type(b) == 'string', 'ByteCode must be string')"
1162 " f = nil load (b)()" // assigns f
1163 " icn = nil load (c)()" // may assign "icn"
1164 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1165 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1168 " local get = function (id)"
1169 " if type(self.scripts[id]) == 'table' then"
1170 " return { ['name'] = self.scripts[id]['n'],"
1171 " ['script'] = self.scripts[id]['s'],"
1172 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
1173 " ['args'] = self.scripts[id]['a'] }"
1178 " local function basic_serialize (o)"
1179 " if type(o) == \"number\" then"
1180 " return tostring(o)"
1182 " return string.format(\"%q\", o)"
1186 " local function serialize (name, value)"
1187 " local rv = name .. ' = '"
1188 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1189 " return rv .. basic_serialize(value) .. ' '"
1190 " elseif type(value) == \"table\" then"
1192 " for k,v in pairs(value) do"
1193 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1194 " rv = rv .. serialize(fieldname, v) .. ' '"
1197 " elseif type(value) == \"function\" then"
1198 " return rv .. string.format(\"%q\", string.dump(value, true))"
1199 " elseif type(value) == \"boolean\" then"
1200 " return rv .. tostring (value)"
1202 " error('cannot save a ' .. type(value))"
1207 " local save = function ()"
1208 " return (serialize('scripts', self.scripts))"
1211 " local clear = function ()"
1212 " self.scripts = {}"
1213 " self.instances = {}"
1218 " local restore = function (state)"
1221 " for i, s in pairs (scripts) do"
1222 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1227 " return { call = call, add = add, remove = remove, get = get,"
1228 " restore = restore, save = save, clear = clear, icon = icon}"
1231 " manager = ScriptManager ()"
1232 " ScriptManager = nil"
1234 lua_State* L = lua.getState();
1237 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1238 lua.do_command ("manager = nil"); // hide it.
1239 lua.do_command ("collectgarbage()");
1241 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1242 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1243 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1244 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1245 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1246 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1247 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1248 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1250 } catch (luabridge::LuaException const& e) {
1251 fatal << string_compose (_("programming error: %1"),
1252 std::string ("Failed to setup Lua action interpreter") + e.what ())
1254 abort(); /*NOTREACHED*/
1256 fatal << string_compose (_("programming error: %1"),
1257 X_("Failed to setup Lua action interpreter"))
1259 abort(); /*NOTREACHED*/
1262 register_classes (L);
1265 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1266 lua_setglobal (L, "Editor");
1269 void LuaInstance::set_session (Session* s)
1271 SessionHandlePtr::set_session (s);
1276 lua_State* L = lua.getState();
1277 LuaBindings::set_session (L, _session);
1279 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1280 i->second->set_session (s);
1282 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1283 SetSession (); /* EMIT SIGNAL */
1287 LuaInstance::session_going_away ()
1289 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1290 point_one_second_connection.disconnect ();
1293 for (int i = 0; i < 9; ++i) {
1294 ActionChanged (i, ""); /* EMIT SIGNAL */
1296 SessionHandlePtr::session_going_away ();
1299 lua_State* L = lua.getState();
1300 LuaBindings::set_session (L, _session);
1301 lua.do_command ("collectgarbage();");
1305 LuaInstance::every_point_one_seconds ()
1307 LuaTimerDS (); // emit signal
1311 LuaInstance::set_state (const XMLNode& node)
1315 if ((child = find_named_node (node, "ActionScript"))) {
1316 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1317 if (!(*n)->is_content ()) { continue; }
1319 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1321 (*_lua_load)(std::string ((const char*)buf, size));
1322 } catch (luabridge::LuaException const& e) {
1323 cerr << "LuaException:" << e.what () << endl;
1325 for (int i = 0; i < 9; ++i) {
1327 if (lua_action_name (i, name)) {
1328 ActionChanged (i, name); /* EMIT SIGNAL */
1335 if ((child = find_named_node (node, "ActionHooks"))) {
1336 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1338 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1339 _callbacks.insert (std::make_pair(p->id(), p));
1340 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1341 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1342 } catch (luabridge::LuaException const& e) {
1343 cerr << "LuaException:" << e.what () << endl;
1352 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1355 std::string param_function = "action_params";
1356 std::vector<std::string> reg;
1359 case LuaScriptInfo::EditorAction:
1360 reg = lua_action_names ();
1361 title = _("Add Shortcut or Lua Script");
1363 case LuaScriptInfo::EditorHook:
1364 reg = lua_slot_names ();
1365 title = _("Add Lua Callback Hook");
1367 case LuaScriptInfo::Session:
1371 reg = _session->registered_lua_functions ();
1372 title = _("Add Lua Session Script");
1373 param_function = "sess_params";
1379 LuaScriptInfoPtr spi;
1380 ScriptSelector ss (title, type);
1381 switch (ss.run ()) {
1382 case Gtk::RESPONSE_ACCEPT:
1390 std::string script = "";
1393 script = Glib::file_get_contents (spi->path);
1394 } catch (Glib::FileError const& e) {
1395 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1396 Gtk::MessageDialog am (msg);
1402 register_classes (ls.getState ());
1403 LuaScriptParamList lsp = LuaScriptParams::script_params (ls, spi->path, param_function);
1406 for (size_t i = 0; i < lsp.size(); ++i) {
1407 if (lsp[i]->preseeded && lsp[i]->name == "x-script-abort") {
1412 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1414 if (spd.need_interation ()) {
1415 switch (spd.run ()) {
1416 case Gtk::RESPONSE_ACCEPT:
1423 LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false, true));
1424 lsp.push_back (lspp);
1427 case LuaScriptInfo::EditorAction:
1428 return set_lua_action (id, spd.name(), script, lsp);
1430 case LuaScriptInfo::EditorHook:
1431 return register_lua_slot (spd.name(), script, lsp);
1433 case LuaScriptInfo::Session:
1435 _session->register_lua_function (spd.name(), script, lsp);
1436 } catch (luabridge::LuaException const& e) {
1437 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1438 Gtk::MessageDialog am (msg);
1440 } catch (SessionException const& e) {
1441 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1442 Gtk::MessageDialog am (msg);
1445 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1446 Gtk::MessageDialog am (msg);
1456 LuaInstance::get_action_state ()
1460 luabridge::LuaRef savedstate ((*_lua_save)());
1461 saved = savedstate.cast<std::string>();
1463 lua.collect_garbage ();
1465 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1466 std::string b64s (b64);
1469 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1470 script_node->set_property (X_("lua"), LUA_VERSION);
1471 script_node->add_content (b64s);
1473 return *script_node;
1477 LuaInstance::get_hook_state ()
1479 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1480 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1481 script_node->add_child_nocopy (i->second->get_state ());
1483 return *script_node;
1487 LuaInstance::call_action (const int id)
1490 (*_lua_call_action)(id + 1);
1491 lua.collect_garbage_step ();
1492 } catch (luabridge::LuaException const& e) {
1493 cerr << "LuaException:" << e.what () << endl;
1498 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1499 int ii = reinterpret_cast<uintptr_t> (i);
1500 instance()->render_icon (ii, cr, w, h, c);
1504 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1506 Cairo::Context ctx (cr);
1508 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1509 } catch (luabridge::LuaException const& e) {
1510 cerr << "LuaException:" << e.what () << endl;
1515 LuaInstance::set_lua_action (
1517 const std::string& name,
1518 const std::string& script,
1519 const LuaScriptParamList& args)
1522 lua_State* L = lua.getState();
1523 // get bytcode of factory-function in a sandbox
1524 // (don't allow scripts to interfere)
1525 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1526 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1527 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1528 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1529 if ((*i)->optional && !(*i)->is_set) { continue; }
1530 tbl_arg[(*i)->name] = (*i)->value;
1532 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1533 ActionChanged (id, name); /* EMIT SIGNAL */
1534 } catch (luabridge::LuaException const& e) {
1535 cerr << "LuaException:" << e.what () << endl;
1540 _session->set_dirty ();
1545 LuaInstance::remove_lua_action (const int id)
1548 (*_lua_del_action)(id + 1);
1549 } catch (luabridge::LuaException const& e) {
1550 cerr << "LuaException:" << e.what () << endl;
1555 ActionChanged (id, ""); /* EMIT SIGNAL */
1556 _session->set_dirty ();
1561 LuaInstance::lua_action_name (const int id, std::string& rv)
1564 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1568 if (ref["name"].isString()) {
1569 rv = ref["name"].cast<std::string>();
1573 } catch (luabridge::LuaException const& e) {
1574 cerr << "LuaException:" << e.what () << endl;
1579 std::vector<std::string>
1580 LuaInstance::lua_action_names ()
1582 std::vector<std::string> rv;
1583 for (int i = 0; i < 9; ++i) {
1585 if (lua_action_name (i, name)) {
1586 rv.push_back (name);
1593 LuaInstance::lua_action_has_icon (const int id)
1596 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1600 if (ref["icon"].isBoolean()) {
1601 return ref["icon"].cast<bool>();
1603 } catch (luabridge::LuaException const& e) {
1604 cerr << "LuaException:" << e.what () << endl;
1610 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1613 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1617 if (!ref["name"].isString()) {
1620 if (!ref["script"].isString()) {
1623 if (!ref["args"].isTable()) {
1626 name = ref["name"].cast<std::string>();
1627 script = ref["script"].cast<std::string>();
1630 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1634 args = LuaScriptParams::script_params (lsi, "action_params");
1635 luabridge::LuaRef rargs (ref["args"]);
1636 LuaScriptParams::ref_to_params (args, &rargs);
1638 } catch (luabridge::LuaException const& e) {
1639 cerr << "LuaException:" << e.what () << endl;
1645 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1647 /* parse script, get ActionHook(s) from script */
1651 l.Print.connect (&_lua_print);
1653 lua_State* L = l.getState();
1655 l.do_command ("function ardour () end");
1656 l.do_command (script);
1657 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1658 if (signals.isFunction()) {
1661 } catch (luabridge::LuaException const& e) {
1662 cerr << "LuaException:" << e.what () << endl;
1666 cerr << "Script registered no hooks." << endl;
1670 /* register script w/args, get entry-point / ID */
1673 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1674 _callbacks.insert (std::make_pair(p->id(), p));
1675 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1676 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1678 } catch (luabridge::LuaException const& e) {
1679 cerr << "LuaException:" << e.what () << endl;
1681 _session->set_dirty ();
1686 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1688 LuaCallbackMap::iterator i = _callbacks.find (id);
1689 if (i != _callbacks.end()) {
1690 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1691 _callbacks.erase (i);
1694 _session->set_dirty ();
1698 std::vector<PBD::ID>
1699 LuaInstance::lua_slots () const
1701 std::vector<PBD::ID> rv;
1702 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1703 rv.push_back (i->first);
1709 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1711 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1712 if (i != _callbacks.end()) {
1713 name = i->second->name();
1719 std::vector<std::string>
1720 LuaInstance::lua_slot_names () const
1722 std::vector<std::string> rv;
1723 std::vector<PBD::ID> ids = lua_slots();
1724 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1726 if (lua_slot_name (*i, name)) {
1727 rv.push_back (name);
1734 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1736 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1737 if (i == _callbacks.end()) {
1738 return false; // error
1740 return i->second->lua_slot (name, script, ah, args);
1743 ///////////////////////////////////////////////////////////////////////////////
1745 LuaCallback::LuaCallback (Session *s,
1746 const std::string& name,
1747 const std::string& script,
1748 const ActionHook& ah,
1749 const ARDOUR::LuaScriptParamList& args)
1750 : SessionHandlePtr (s)
1755 // TODO: allow to reference object (e.g region)
1758 lua_State* L = lua.getState();
1759 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1760 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1761 if ((*i)->optional && !(*i)->is_set) { continue; }
1762 tbl_arg[(*i)->name] = (*i)->value;
1766 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1767 (*_lua_add)(name, script, bytecode, tbl_arg);
1768 } catch (luabridge::LuaException const& e) {
1769 cerr << "LuaException:" << e.what () << endl;
1770 throw failed_constructor ();
1772 throw failed_constructor ();
1779 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1780 : SessionHandlePtr (s)
1782 XMLNode* child = NULL;
1783 if (node.name() != X_("LuaCallback")
1784 || !node.property ("signals")
1785 || !node.property ("id")
1786 || !node.property ("name")) {
1787 throw failed_constructor ();
1790 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1791 if (!(*n)->is_content ()) { continue; }
1796 throw failed_constructor ();
1801 _id = PBD::ID (node.property ("id")->value ());
1802 _name = node.property ("name")->value ();
1803 _signals = ActionHook (node.property ("signals")->value ());
1806 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1808 (*_lua_load)(std::string ((const char*)buf, size));
1809 } catch (luabridge::LuaException const& e) {
1810 cerr << "LuaException:" << e.what () << endl;
1817 LuaCallback::~LuaCallback ()
1827 LuaCallback::get_state (void)
1831 luabridge::LuaRef savedstate ((*_lua_save)());
1832 saved = savedstate.cast<std::string>();
1835 lua.collect_garbage (); // this may be expensive:
1836 /* Editor::instant_save() calls Editor::get_state() which
1837 * calls LuaInstance::get_hook_state() which in turn calls
1838 * this LuaCallback::get_state() for every registered hook.
1840 * serialize in _lua_save() allocates many small strings
1841 * on the lua-stack, collecting them all may take a ms.
1844 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1845 std::string b64s (b64);
1848 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1849 script_node->set_property (X_("lua"), LUA_VERSION);
1850 script_node->set_property (X_("id"), _id.to_s ());
1851 script_node->set_property (X_("name"), _name);
1852 script_node->set_property (X_("signals"), _signals.to_string ());
1853 script_node->add_content (b64s);
1854 return *script_node;
1858 LuaCallback::init (void)
1860 lua.Print.connect (&_lua_print);
1861 lua.sandbox (false);
1864 "function ScriptManager ()"
1865 " local self = { script = {}, instance = {} }"
1867 " local addinternal = function (n, s, f, a)"
1868 " assert(type(n) == 'string', 'Name must be string')"
1869 " assert(type(s) == 'string', 'Script must be string')"
1870 " assert(type(f) == 'function', 'Factory is a not a function')"
1871 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1872 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1873 " local env = _ENV; env.f = nil"
1874 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1877 " local call = function (...)"
1878 " if type(self.instance) == 'function' then"
1879 " local status, err = pcall (self.instance, ...)"
1880 " if not status then"
1881 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1882 " self.script = nil"
1883 " self.instance = nil"
1891 " local add = function (n, s, b, a)"
1892 " assert(type(b) == 'string', 'ByteCode must be string')"
1893 " load (b)()" // assigns f
1894 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1895 " addinternal (n, s, load(f), a)"
1898 " local get = function ()"
1899 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1900 " return { ['name'] = self.script['n'],"
1901 " ['script'] = self.script['s'],"
1902 " ['args'] = self.script['a'] }"
1909 " local function basic_serialize (o)"
1910 " if type(o) == \"number\" then"
1911 " return tostring(o)"
1913 " return string.format(\"%q\", o)"
1917 " local function serialize (name, value)"
1918 " local rv = name .. ' = '"
1919 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1920 " return rv .. basic_serialize(value) .. ' '"
1921 " elseif type(value) == \"table\" then"
1923 " for k,v in pairs(value) do"
1924 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1925 " rv = rv .. serialize(fieldname, v) .. ' '"
1928 " elseif type(value) == \"function\" then"
1929 " return rv .. string.format(\"%q\", string.dump(value, true))"
1930 " elseif type(value) == \"boolean\" then"
1931 " return rv .. tostring (value)"
1933 " error('cannot save a ' .. type(value))"
1939 " local save = function ()"
1940 " return (serialize('s', self.script))"
1943 " local restore = function (state)"
1946 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1949 " return { call = call, add = add, get = get,"
1950 " restore = restore, save = save}"
1953 " manager = ScriptManager ()"
1954 " ScriptManager = nil"
1957 lua_State* L = lua.getState();
1960 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1961 lua.do_command ("manager = nil"); // hide it.
1962 lua.do_command ("collectgarbage()");
1964 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1965 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1966 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1967 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1968 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1970 } catch (luabridge::LuaException const& e) {
1971 fatal << string_compose (_("programming error: %1"),
1972 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
1974 abort(); /*NOTREACHED*/
1976 fatal << string_compose (_("programming error: %1"),
1977 X_("Failed to setup Lua callback interpreter"))
1979 abort(); /*NOTREACHED*/
1982 LuaInstance::register_classes (L);
1983 LuaInstance::register_hooks (L);
1985 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1986 lua_setglobal (L, "Editor");
1990 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1992 // TODO consolidate w/ LuaInstance::lua_action()
1994 luabridge::LuaRef ref = (*_lua_get)();
1998 if (!ref["name"].isString()) {
2001 if (!ref["script"].isString()) {
2004 if (!ref["args"].isTable()) {
2009 name = ref["name"].cast<std::string> ();
2010 script = ref["script"].cast<std::string> ();
2013 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
2017 args = LuaScriptParams::script_params (lsi, "action_params");
2018 luabridge::LuaRef rargs (ref["args"]);
2019 LuaScriptParams::ref_to_params (args, &rargs);
2021 } catch (luabridge::LuaException const& e) {
2022 cerr << "LuaException:" << e.what () << endl;
2029 LuaCallback::set_session (ARDOUR::Session *s)
2031 SessionHandlePtr::set_session (s);
2037 lua_State* L = lua.getState();
2038 LuaBindings::set_session (L, _session);
2044 LuaCallback::session_going_away ()
2046 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
2047 lua.do_command ("collectgarbage();");
2049 SessionHandlePtr::session_going_away ();
2052 drop_callback (); /* EMIT SIGNAL */
2056 LuaCallback::reconnect ()
2058 _connections.drop_connections ();
2059 if ((*_lua_get) ().isNil ()) {
2060 drop_callback (); /* EMIT SIGNAL */
2064 // TODO pass object which emits the signal (e.g region)
2066 // save/load bound objects will be tricky.
2067 // Best idea so far is to save/lookup the PBD::ID
2068 // (either use boost::any indirection or templates for bindable
2069 // object types or a switch statement..)
2071 // _session->route_by_id ()
2072 // _session->track_by_diskstream_id ()
2073 // _session->source_by_id ()
2074 // _session->controllable_by_id ()
2075 // _session->processor_by_id ()
2076 // RegionFactory::region_by_id ()
2078 // TODO loop over objects (if any)
2080 reconnect_object ((void*)0);
2083 template <class T> void
2084 LuaCallback::reconnect_object (T obj)
2086 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
2088 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
2089 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
2090 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
2092 # include "luasignal_syms.h"
2094 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
2095 abort(); /*NOTREACHED*/
2104 template <typename T, typename S> void
2105 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2107 _connections, invalidator (*this),
2108 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2112 template <typename T, typename C1> void
2113 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2115 _connections, invalidator (*this),
2116 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2120 template <typename T, typename C1, typename C2> void
2121 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2123 _connections, invalidator (*this),
2124 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2128 template <typename T, typename C1, typename C2, typename C3> void
2129 LuaCallback::connect_3 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal3<void, C1, C2, C3> *signal) {
2131 _connections, invalidator (*this),
2132 boost::bind (&LuaCallback::proxy_3<T, C1, C2, C3>, this, ls, ref, _1, _2, _3),
2136 template <typename T> void
2137 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2140 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2141 if (! rv.cast<bool> ()) {
2145 /* destroy LuaRef ^^ first before calling drop_callback() */
2147 drop_callback (); /* EMIT SIGNAL */
2151 template <typename T, typename C1> void
2152 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2155 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2156 if (! rv.cast<bool> ()) {
2161 drop_callback (); /* EMIT SIGNAL */
2165 template <typename T, typename C1, typename C2> void
2166 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2169 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2170 if (! rv.cast<bool> ()) {
2175 drop_callback (); /* EMIT SIGNAL */
2179 template <typename T, typename C1, typename C2, typename C3> void
2180 LuaCallback::proxy_3 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2, C3 a3) {
2183 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2, a3));
2184 if (! rv.cast<bool> ()) {
2189 drop_callback (); /* EMIT SIGNAL */