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 "gtkmm2ext/gui_thread.h"
25 #include "ardour/audioengine.h"
26 #include "ardour/disk_reader.h"
27 #include "ardour/disk_writer.h"
28 #include "ardour/plugin_manager.h"
29 #include "ardour/route.h"
30 #include "ardour/session.h"
31 #include "ardour/system_exec.h"
33 #include "LuaBridge/LuaBridge.h"
35 #include "ardour_http.h"
36 #include "ardour_ui.h"
37 #include "public_editor.h"
38 #include "region_selection.h"
39 #include "luadialog.h"
40 #include "luainstance.h"
41 #include "luasignal.h"
43 #include "region_view.h"
44 #include "processor_box.h"
45 #include "time_axis_view.h"
46 #include "time_axis_view_item.h"
47 #include "selection.h"
48 #include "script_selector.h"
50 #include "utils_videotl.h"
55 /** wrap RefPtr< Cairo::ImageSurface >
57 * Image surfaces provide the ability to render to memory buffers either
58 * allocated by cairo or by the calling code. The supported image formats are
59 * those defined in Cairo::Format.
64 * Creates an image surface of the specified format and dimensions. Initially
65 * the surface contents are all 0. (Specifically, within each pixel, each
66 * color or alpha channel belonging to format will be 0. The contents of bits
67 * within a pixel, but not belonging to the given format are undefined).
69 * @param format format of pixels in the surface to create
70 * @param width width of the surface, in pixels
71 * @param height height of the surface, in pixels
73 ImageSurface (Cairo::Format format, int width, int height)
74 : _surface (Cairo::ImageSurface::create (format, width, height))
75 , _ctx (Cairo::Context::create (_surface))
76 , ctx (_ctx->cobj ()) {}
81 * Set this surface as source for another context.
82 * This allows to draw this surface
84 void set_as_source (Cairo::Context* c, int x, int y) {
86 c->set_source (_surface, x, y);
90 * Returns a context object to perform operations on the surface
92 Cairo::Context* context () {
93 return (Cairo::Context *)&ctx;
97 * Returns the stride of the image surface in bytes (or 0 if surface is not
98 * an image surface). The stride is the distance in bytes from the beginning
99 * of one row of the image data to the beginning of the next row.
101 int get_stride () const {
102 return _surface->get_stride ();
105 /** Gets the width of the ImageSurface in pixels */
106 int get_width () const {
107 return _surface->get_width ();
110 /** Gets the height of the ImageSurface in pixels */
111 int get_height () const {
112 return _surface->get_height ();
116 * Get a pointer to the data of the image surface, for direct
117 * inspection or modification.
119 * Return value: a pointer to the image data of this surface or NULL
120 * if @surface is not an image surface.
123 unsigned char* get_data () {
124 return _surface->get_data ();
127 /** Tells cairo to consider the data buffer dirty.
129 * In particular, if you've created an ImageSurface with a data buffer that
130 * you've allocated yourself and you draw to that data buffer using means
131 * other than cairo, you must call mark_dirty() before doing any additional
132 * drawing to that surface with cairo.
134 * Note that if you do draw to the Surface outside of cairo, you must call
135 * flush() before doing the drawing.
138 _surface->mark_dirty ();
141 /** Marks a rectangular area of the given surface dirty.
143 * @param x X coordinate of dirty rectangle
144 * @param y Y coordinate of dirty rectangle
145 * @param width width of dirty rectangle
146 * @param height height of dirty rectangle
148 void mark_dirty (int x, int y, int width, int height) {
149 _surface->mark_dirty (x, y, width, height);
153 Cairo::RefPtr<Cairo::ImageSurface> _surface;
154 Cairo::RefPtr<Cairo::Context> _ctx;
160 /** Create a new PangoLayout Text Display
161 * @param c CairoContext for the layout
162 * @param font_name a font-description e.g. "Mono 8px"
164 PangoLayout (Cairo::Context* c, std::string font_name) {
165 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
166 _layout = Glib::wrap (pl);
167 Pango::FontDescription fd (font_name);
168 _layout->set_font_description (fd);
173 /** Gets the text in the layout. The returned text should not
174 * be freed or modified.
176 * @return The text in the @a layout.
178 std::string get_text () const {
179 return _layout->get_text ();
181 /** Set the text of the layout.
182 * @param text The text for the layout.
184 void set_text (const std::string& text) {
185 _layout->set_text (text);
188 /** Sets the layout text and attribute list from marked-up text (see markup format).
189 * Replaces the current text and attribute list.
190 * @param markup Some marked-up text.
192 void set_markup (const std::string& markup) {
193 _layout->set_markup (markup);
196 /** Sets the width to which the lines of the Pango::Layout should wrap or
197 * ellipsized. The default value is -1: no width set.
199 * @param width The desired width in Pango units, or -1 to indicate that no
200 * wrapping or ellipsization should be performed.
202 void set_width (int width) {
203 _layout->set_width (width * PANGO_SCALE);
206 /** Gets the width to which the lines of the Pango::Layout should wrap.
208 * @return The width in Pango units, or -1 if no width set.
210 int get_width () const {
211 return _layout->get_width () / PANGO_SCALE;
214 /** Sets the type of ellipsization being performed for @a layout.
215 * Depending on the ellipsization mode @a ellipsize text is
216 * removed from the start, middle, or end of text so they
217 * fit within the width and height of layout set with
218 * set_width() and set_height().
220 * If the layout contains characters such as newlines that
221 * force it to be layed out in multiple paragraphs, then whether
222 * each paragraph is ellipsized separately or the entire layout
223 * is ellipsized as a whole depends on the set height of the layout.
224 * See set_height() for details.
226 * @param ellipsize The new ellipsization mode for @a layout.
228 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
229 _layout->set_ellipsize (ellipsize);
232 /** Gets the type of ellipsization being performed for @a layout.
233 * See set_ellipsize()
235 * @return The current ellipsization mode for @a layout.
237 * Use is_ellipsized() to query whether any paragraphs
238 * were actually ellipsized.
240 Pango::EllipsizeMode get_ellipsize () const {
241 return _layout->get_ellipsize ();
244 /** Queries whether the layout had to ellipsize any paragraphs.
246 * This returns <tt>true</tt> if the ellipsization mode for @a layout
247 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
248 * and there are paragraphs exceeding that width that have to be
251 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
254 bool is_ellipsized () const {
255 return _layout->is_ellipsized ();
258 /** Sets the wrap mode; the wrap mode only has effect if a width
259 * is set on the layout with set_width().
260 * To turn off wrapping, set the width to -1.
262 * @param wrap The wrap mode.
264 void set_wrap (Pango::WrapMode wrap) {
265 _layout->set_width (wrap);
268 /** Gets the wrap mode for the layout.
270 * Use is_wrapped() to query whether any paragraphs
271 * were actually wrapped.
273 * @return Active wrap mode.
275 Pango::WrapMode get_wrap () const {
276 return _layout->get_wrap ();
279 /** Queries whether the layout had to wrap any paragraphs.
281 * This returns <tt>true</tt> if a positive width is set on @a layout,
282 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
283 * and there are paragraphs exceeding the layout width that have
286 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
289 bool is_wrapped () const {
290 return _layout->is_wrapped ();
293 /** Determines the logical width and height of a Pango::Layout
296 int get_pixel_size (lua_State *L) {
298 _layout->get_pixel_size (width, height);
299 luabridge::Stack<int>::push (L, width);
300 luabridge::Stack<int>::push (L, height);
305 /** Draws a Layout in the specified Cairo @a context. The top-left
306 * corner of the Layout will be drawn at the current point of the
309 * @param context A Cairo context.
311 void show_in_cairo_context (Cairo::Context* c) {
312 pango_cairo_update_layout (c->cobj (), _layout->gobj());
313 pango_cairo_show_layout (c->cobj (), _layout->gobj());
316 void layout_cairo_path (Cairo::Context* c) {
317 pango_cairo_update_layout (c->cobj (), _layout->gobj());
318 pango_cairo_layout_path (c->cobj (), _layout->gobj());
322 Glib::RefPtr<Pango::Layout> _layout;
327 ////////////////////////////////////////////////////////////////////////////////
329 namespace LuaSignal {
331 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
332 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
333 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
336 str2luasignal (const std::string &str) {
337 const char* type = str.c_str();
339 # include "luasignal_syms.h"
341 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
342 abort(); /*NOTREACHED*/
349 #define STATIC(name,c,p) N_(#name),
350 #define SESSION(name,c,p) N_(#name),
351 #define ENGINE(name,c,p) N_(#name),
352 const char *luasignalstr[] = {
353 # include "luasignal_syms.h"
363 /** special cases for Ardour's Mixer UI */
366 ProcessorBox::ProcSelection
367 processor_selection () {
368 return ProcessorBox::current_processor_selection ();
373 ////////////////////////////////////////////////////////////////////////////////
375 static PBD::ScopedConnectionList _luaexecs;
377 static void reaper (ARDOUR::SystemExec* x)
383 lua_forkexec (lua_State *L)
385 int argc = lua_gettop (L);
387 return luaL_argerror (L, 1, "invalid number of arguments, forkexec (command, ...)");
389 // args are free()ed in ~SystemExec
390 char** args = (char**) malloc ((argc + 1) * sizeof(char*));
391 for (int i = 0; i < argc; ++i) {
392 args[i] = strdup (luaL_checkstring (L, i + 1));
396 ARDOUR::SystemExec* x = new ARDOUR::SystemExec (args[0], args);
397 x->Terminated.connect (_luaexecs, MISSING_INVALIDATOR, boost::bind (&reaper, x), gui_context());
401 luabridge::Stack<bool>::push (L, false);
404 luabridge::Stack<bool>::push (L, false);
409 #ifndef PLATFORM_WINDOWS
411 lua_exec (std::string cmd)
413 // args are free()ed in ~SystemExec
414 char** args = (char**) malloc (4 * sizeof(char*));
415 args[0] = strdup ("/bin/sh");
416 args[1] = strdup ("-c");
417 args[2] = strdup (cmd.c_str());
419 ARDOUR::SystemExec x ("/bin/sh", args);
427 ////////////////////////////////////////////////////////////////////////////////
429 // ARDOUR_UI and instance() are not exposed.
430 ARDOUR::PresentationInfo::order_t
431 lua_translate_order (RouteDialogs::InsertAt place)
433 return ARDOUR_UI::instance()->translate_order (place);
436 ////////////////////////////////////////////////////////////////////////////////
438 #define xstr(s) stringify(s)
439 #define stringify(s) #s
441 using namespace ARDOUR;
443 PBD::Signal0<void> LuaInstance::LuaTimerDS;
444 PBD::Signal0<void> LuaInstance::SetSession;
447 LuaInstance::register_hooks (lua_State* L)
450 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
451 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
452 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
453 luabridge::getGlobalNamespace (L)
454 .beginNamespace ("LuaSignal")
455 # include "luasignal_syms.h"
461 luabridge::getGlobalNamespace (L)
462 .beginNamespace ("LuaSignal")
463 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
467 #if 0 // Dump size -> libs/ardour/luabindings.cc
468 printf ("LuaInstance: registered %d signals\n", LuaSignal::LAST_SIGNAL);
473 LuaInstance::bind_cairo (lua_State* L)
475 /* std::vector<double> for set_dash()
476 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
478 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
479 * the address of the one in libardour.dll is mapped when loading the .dll
481 * see LuaBindings::set_session() for a detailed explanation
483 luabridge::getGlobalNamespace (L)
484 .beginNamespace ("C")
485 .beginStdVector <double> ("DoubleVector")
489 luabridge::getGlobalNamespace (L)
490 .beginNamespace ("Cairo")
491 .beginClass <Cairo::Context> ("Context")
492 .addFunction ("save", &Cairo::Context::save)
493 .addFunction ("restore", &Cairo::Context::restore)
494 .addFunction ("set_operator", &Cairo::Context::set_operator)
495 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
496 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
497 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
498 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
499 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
500 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
501 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
502 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
503 .addFunction ("translate", &Cairo::Context::translate)
504 .addFunction ("scale", &Cairo::Context::scale)
505 .addFunction ("rotate", &Cairo::Context::rotate)
506 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
507 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
508 .addFunction ("move_to", &Cairo::Context::move_to)
509 .addFunction ("line_to", &Cairo::Context::line_to)
510 .addFunction ("curve_to", &Cairo::Context::curve_to)
511 .addFunction ("arc", &Cairo::Context::arc)
512 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
513 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
514 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
515 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
516 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
517 .addFunction ("close_path", &Cairo::Context::close_path)
518 .addFunction ("paint", &Cairo::Context::paint)
519 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
520 .addFunction ("stroke", &Cairo::Context::stroke)
521 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
522 .addFunction ("fill", &Cairo::Context::fill)
523 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
524 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
525 .addFunction ("clip", &Cairo::Context::clip)
526 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
527 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
528 .addFunction ("show_text", &Cairo::Context::show_text)
531 // LineCap, LineJoin, Operator
532 .beginNamespace ("LineCap")
533 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
534 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
535 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
538 .beginNamespace ("LineJoin")
539 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
540 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
541 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
544 .beginNamespace ("Operator")
545 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
546 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
547 .addConst ("Over", CAIRO_OPERATOR_OVER)
548 .addConst ("Add", CAIRO_OPERATOR_ADD)
551 .beginNamespace ("Format")
552 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
553 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
556 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
557 .addConstructor <void (*) (Cairo::Format, int, int)> ()
558 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
559 .addFunction ("context", &LuaCairo::ImageSurface::context)
560 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
561 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
562 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
563 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
566 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
567 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
568 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
569 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
570 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
571 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
572 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
573 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
574 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
575 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
576 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
577 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
578 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
579 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
580 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
584 .beginNamespace ("EllipsizeMode")
585 .addConst ("None", Pango::ELLIPSIZE_NONE)
586 .addConst ("Start", Pango::ELLIPSIZE_START)
587 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
588 .addConst ("End", Pango::ELLIPSIZE_END)
591 .beginNamespace ("WrapMode")
592 .addConst ("Word", Pango::WRAP_WORD)
593 .addConst ("Char", Pango::WRAP_CHAR)
594 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
599 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
600 one can work around this as follows:
603 LuaInstance::register_classes (lua.getState());
605 "function render (ctx)"
606 " ctx:rectangle (0, 0, 100, 100)"
607 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
612 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
613 Cairo::Context ctx (context->cobj ());
615 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
616 lua_render ((Cairo::Context *)&ctx);
623 LuaInstance::bind_dialog (lua_State* L)
625 luabridge::getGlobalNamespace (L)
626 .beginNamespace ("LuaDialog")
628 .beginClass <LuaDialog::Message> ("Message")
629 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
630 .addFunction ("run", &LuaDialog::Message::run)
633 .beginClass <LuaDialog::Dialog> ("Dialog")
634 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
635 .addCFunction ("run", &LuaDialog::Dialog::run)
639 .beginNamespace ("MessageType")
640 .addConst ("Info", LuaDialog::Message::Info)
641 .addConst ("Warning", LuaDialog::Message::Warning)
642 .addConst ("Question", LuaDialog::Message::Question)
643 .addConst ("Error", LuaDialog::Message::Error)
646 .beginNamespace ("ButtonType")
647 .addConst ("OK", LuaDialog::Message::OK)
648 .addConst ("Close", LuaDialog::Message::Close)
649 .addConst ("Cancel", LuaDialog::Message::Cancel)
650 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
651 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
654 .beginNamespace ("Response")
656 .addConst ("Cancel", 1)
657 .addConst ("Close", 2)
660 .addConst ("None", -1)
668 LuaInstance::register_classes (lua_State* L)
670 LuaBindings::stddef (L);
671 LuaBindings::common (L);
672 LuaBindings::session (L);
673 LuaBindings::osc (L);
678 luabridge::getGlobalNamespace (L)
679 .beginNamespace ("ArdourUI")
681 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
683 .addFunction ("processor_selection", &LuaMixer::processor_selection)
685 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
688 .beginClass <ArdourMarker> ("ArdourMarker")
689 .addFunction ("name", &ArdourMarker::name)
690 .addFunction ("position", &ArdourMarker::position)
691 .addFunction ("_type", &ArdourMarker::type)
694 .beginClass <AxisView> ("AxisView")
697 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
700 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
703 .beginClass <Selectable> ("Selectable")
706 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
709 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
712 .deriveClass <RouteUI, Selectable> ("RouteUI")
715 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
716 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
717 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
720 // std::list<Selectable*>
721 .beginStdCPtrList <Selectable> ("SelectionList")
724 // std::list<TimeAxisView*>
725 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
729 .beginClass <RegionSelection> ("RegionSelection")
730 .addFunction ("start", &RegionSelection::start)
731 .addFunction ("end_frame", &RegionSelection::end_frame)
732 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
733 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
736 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
737 .addFunction ("start", &TimeSelection::start)
738 .addFunction ("end_frame", &TimeSelection::end_frame)
739 .addFunction ("length", &TimeSelection::length)
742 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
745 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
746 .addFunction ("contains", &TrackViewList::contains)
747 .addFunction ("routelist", &TrackViewList::routelist)
750 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
753 .beginClass <Selection> ("Selection")
754 .addFunction ("clear", &Selection::clear)
755 .addFunction ("clear_all", &Selection::clear_all)
756 .addFunction ("empty", &Selection::empty)
757 .addData ("tracks", &Selection::tracks)
758 .addData ("regions", &Selection::regions)
759 .addData ("time", &Selection::time)
760 .addData ("markers", &Selection::markers)
762 .addData ("lines", &Selection::lines)
763 .addData ("playlists", &Selection::playlists)
764 .addData ("points", &Selection::points)
765 .addData ("midi_regions", &Selection::midi_regions)
766 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
770 .beginClass <PublicEditor> ("Editor")
771 .addFunction ("snap_type", &PublicEditor::snap_type)
772 .addFunction ("snap_mode", &PublicEditor::snap_mode)
773 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
774 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
776 .addFunction ("undo", &PublicEditor::undo)
777 .addFunction ("redo", &PublicEditor::redo)
779 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
780 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
782 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
784 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
785 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
786 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
787 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
789 .addFunction ("get_selection", &PublicEditor::get_selection)
790 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
791 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
793 .addFunction ("set_selection", &PublicEditor::set_selection)
795 .addFunction ("play_selection", &PublicEditor::play_selection)
796 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
797 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
798 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
800 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
801 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
803 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
804 .addFunction ("show_measures", &PublicEditor::show_measures)
805 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
807 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
808 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
810 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
812 .addRefFunction ("do_import", &PublicEditor::do_import)
813 .addRefFunction ("do_embed", &PublicEditor::do_embed)
815 .addFunction ("export_audio", &PublicEditor::export_audio)
816 .addFunction ("stem_export", &PublicEditor::stem_export)
817 .addFunction ("export_selection", &PublicEditor::export_selection)
818 .addFunction ("export_range", &PublicEditor::export_range)
820 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
821 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
822 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
823 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
825 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
826 .addFunction ("new_playlists", &PublicEditor::new_playlists)
827 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
828 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
830 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
831 .addFunction ("deselect_all", &PublicEditor::deselect_all)
833 #if 0 // TimeAxisView& can't be bound (pure virtual fn)
834 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
835 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
836 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
838 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
839 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
840 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
841 .addFunction ("fit_selection", &PublicEditor::fit_selection)
843 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
844 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
845 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
846 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
847 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
849 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
850 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
851 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
852 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
853 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
854 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
856 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
857 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
858 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
859 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
861 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
862 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
863 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
865 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
867 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
868 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
869 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
871 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
872 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
874 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
875 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
876 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
877 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
879 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
880 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
881 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
882 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
885 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
886 .addFunction ("drags", &PublicEditor::drags)
889 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
890 .addFunction ("get_track_views", &PublicEditor::get_track_views)
891 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
892 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
894 .addFunction ("center_screen", &PublicEditor::center_screen)
896 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
897 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
899 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
900 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
901 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
903 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
904 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
905 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
906 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
907 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
911 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
912 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
913 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
914 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
917 .addFunction ("access_action", &PublicEditor::access_action)
918 .addFunction ("set_toggleaction", &PublicEditor::set_toggleaction)
921 .addFunction ("translate_order", &lua_translate_order)
924 .beginNamespace ("InsertAt")
925 .addConst ("BeforeSelection", RouteDialogs::InsertAt(RouteDialogs::BeforeSelection))
926 .addConst ("AfterSelection", RouteDialogs::InsertAt(RouteDialogs::AfterSelection))
927 .addConst ("First", RouteDialogs::InsertAt(RouteDialogs::First))
928 .addConst ("Last", RouteDialogs::InsertAt(RouteDialogs::Last))
931 .beginNamespace ("MarkerType")
932 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
933 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
934 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
935 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
936 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
937 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
938 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
939 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
940 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
941 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
942 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
945 .beginNamespace ("SelectionOp")
946 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
947 .addConst ("Set", Selection::Operation(Selection::Set))
948 .addConst ("Extend", Selection::Operation(Selection::Extend))
949 .addConst ("Add", Selection::Operation(Selection::Add))
952 .endNamespace () // end ArdourUI
954 .beginNamespace ("os")
955 #ifndef PLATFORM_WINDOWS
956 .addFunction ("execute", &lua_exec)
958 .addCFunction ("forkexec", &lua_forkexec)
967 #undef DISPLAYCONTROL
969 #undef IMPORTPOSITION
970 #undef IMPORTDISPOSITION
972 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
973 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
974 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
975 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
976 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
977 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
978 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
979 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
980 luabridge::getGlobalNamespace (L)
981 .beginNamespace ("Editing")
982 # include "editing_syms.h"
989 ////////////////////////////////////////////////////////////////////////////////
991 using namespace ARDOUR;
992 using namespace ARDOUR_UI_UTILS;
996 static void _lua_print (std::string s) {
998 std::cout << "LuaInstance: " << s << "\n";
1000 PBD::info << "LuaInstance: " << s << endmsg;
1003 LuaInstance* LuaInstance::_instance = 0;
1006 LuaInstance::instance ()
1009 _instance = new LuaInstance;
1016 LuaInstance::destroy_instance ()
1022 LuaInstance::LuaInstance ()
1024 lua.Print.connect (&_lua_print);
1027 LuaScriptParamList args;
1030 LuaInstance::~LuaInstance ()
1032 delete _lua_call_action;
1033 delete _lua_render_icon;
1034 delete _lua_add_action;
1035 delete _lua_del_action;
1036 delete _lua_get_action;
1045 LuaInstance::init ()
1047 lua.sandbox (false);
1049 "function ScriptManager ()"
1050 " local self = { scripts = {}, instances = {}, icons = {} }"
1052 " local remove = function (id)"
1053 " self.scripts[id] = nil"
1054 " self.instances[id] = nil"
1055 " self.icons[id] = nil"
1058 " local addinternal = function (i, n, s, f, c, a)"
1059 " assert(type(i) == 'number', 'id must be numeric')"
1060 " assert(type(n) == 'string', 'Name must be string')"
1061 " assert(type(s) == 'string', 'Script must be string')"
1062 " assert(type(f) == 'function', 'Factory is a not a function')"
1063 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1064 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
1065 " local env = _ENV; env.f = nil"
1066 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
1067 " if type(c) == 'function' then"
1068 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
1070 " self.icons[i] = nil"
1074 " local call = function (id)"
1075 " if type(self.instances[id]) == 'function' then"
1076 " local status, err = pcall (self.instances[id])"
1077 " if not status then"
1078 " print ('action \"'.. id .. '\": ', err)" // error out
1085 " local icon = function (id, ...)"
1086 " if type(self.icons[id]) == 'function' then"
1087 " pcall (self.icons[id], ...)"
1092 " local add = function (i, n, s, b, c, a)"
1093 " assert(type(b) == 'string', 'ByteCode must be string')"
1094 " f = nil load (b)()" // assigns f
1095 " icn = nil load (c)()" // may assign "icn"
1096 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1097 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1100 " local get = function (id)"
1101 " if type(self.scripts[id]) == 'table' then"
1102 " return { ['name'] = self.scripts[id]['n'],"
1103 " ['script'] = self.scripts[id]['s'],"
1104 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
1105 " ['args'] = self.scripts[id]['a'] }"
1110 " local function basic_serialize (o)"
1111 " if type(o) == \"number\" then"
1112 " return tostring(o)"
1114 " return string.format(\"%q\", o)"
1118 " local function serialize (name, value)"
1119 " local rv = name .. ' = '"
1120 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1121 " return rv .. basic_serialize(value) .. ' '"
1122 " elseif type(value) == \"table\" then"
1124 " for k,v in pairs(value) do"
1125 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1126 " rv = rv .. serialize(fieldname, v) .. ' '"
1129 " elseif type(value) == \"function\" then"
1130 " return rv .. string.format(\"%q\", string.dump(value, true))"
1131 " elseif type(value) == \"boolean\" then"
1132 " return rv .. tostring (value)"
1134 " error('cannot save a ' .. type(value))"
1139 " local save = function ()"
1140 " return (serialize('scripts', self.scripts))"
1143 " local clear = function ()"
1144 " self.scripts = {}"
1145 " self.instances = {}"
1150 " local restore = function (state)"
1153 " for i, s in pairs (scripts) do"
1154 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1159 " return { call = call, add = add, remove = remove, get = get,"
1160 " restore = restore, save = save, clear = clear, icon = icon}"
1163 " manager = ScriptManager ()"
1164 " ScriptManager = nil"
1166 lua_State* L = lua.getState();
1169 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1170 lua.do_command ("manager = nil"); // hide it.
1171 lua.do_command ("collectgarbage()");
1173 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1174 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1175 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1176 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1177 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1178 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1179 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1180 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1182 } catch (luabridge::LuaException const& e) {
1183 fatal << string_compose (_("programming error: %1"),
1184 std::string ("Failed to setup Lua action interpreter") + e.what ())
1186 abort(); /*NOTREACHED*/
1188 fatal << string_compose (_("programming error: %1"),
1189 X_("Failed to setup Lua action interpreter"))
1191 abort(); /*NOTREACHED*/
1194 register_classes (L);
1197 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1198 lua_setglobal (L, "Editor");
1201 void LuaInstance::set_session (Session* s)
1203 SessionHandlePtr::set_session (s);
1208 lua_State* L = lua.getState();
1209 LuaBindings::set_session (L, _session);
1211 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1212 i->second->set_session (s);
1214 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1215 SetSession (); /* EMIT SIGNAL */
1219 LuaInstance::session_going_away ()
1221 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1222 point_one_second_connection.disconnect ();
1225 for (int i = 0; i < 9; ++i) {
1226 ActionChanged (i, ""); /* EMIT SIGNAL */
1228 SessionHandlePtr::session_going_away ();
1231 lua_State* L = lua.getState();
1232 LuaBindings::set_session (L, _session);
1233 lua.do_command ("collectgarbage();");
1237 LuaInstance::every_point_one_seconds ()
1239 LuaTimerDS (); // emit signal
1243 LuaInstance::set_state (const XMLNode& node)
1247 if ((child = find_named_node (node, "ActionScript"))) {
1248 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1249 if (!(*n)->is_content ()) { continue; }
1251 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1253 (*_lua_load)(std::string ((const char*)buf, size));
1254 } catch (luabridge::LuaException const& e) {
1255 cerr << "LuaException:" << e.what () << endl;
1257 for (int i = 0; i < 9; ++i) {
1259 if (lua_action_name (i, name)) {
1260 ActionChanged (i, name); /* EMIT SIGNAL */
1267 if ((child = find_named_node (node, "ActionHooks"))) {
1268 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1270 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1271 _callbacks.insert (std::make_pair(p->id(), p));
1272 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1273 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1274 } catch (luabridge::LuaException const& e) {
1275 cerr << "LuaException:" << e.what () << endl;
1284 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1287 std::string param_function = "action_params";
1288 std::vector<std::string> reg;
1291 case LuaScriptInfo::EditorAction:
1292 reg = lua_action_names ();
1293 title = _("Add Lua Action");
1295 case LuaScriptInfo::EditorHook:
1296 reg = lua_slot_names ();
1297 title = _("Add Lua Callback Hook");
1299 case LuaScriptInfo::Session:
1303 reg = _session->registered_lua_functions ();
1304 title = _("Add Lua Session Script");
1305 param_function = "sess_params";
1311 LuaScriptInfoPtr spi;
1312 ScriptSelector ss (title, type);
1313 switch (ss.run ()) {
1314 case Gtk::RESPONSE_ACCEPT:
1322 std::string script = "";
1325 script = Glib::file_get_contents (spi->path);
1326 } catch (Glib::FileError e) {
1327 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1328 Gtk::MessageDialog am (msg);
1333 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1335 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1337 if (!spd.need_interation ()) {
1338 switch (spd.run ()) {
1339 case Gtk::RESPONSE_ACCEPT:
1346 LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false));
1347 lsp.push_back (lspp);
1350 case LuaScriptInfo::EditorAction:
1351 return set_lua_action (id, spd.name(), script, lsp);
1353 case LuaScriptInfo::EditorHook:
1354 return register_lua_slot (spd.name(), script, lsp);
1356 case LuaScriptInfo::Session:
1358 _session->register_lua_function (spd.name(), script, lsp);
1359 } catch (luabridge::LuaException const& e) {
1360 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1361 Gtk::MessageDialog am (msg);
1363 } catch (SessionException e) {
1364 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1365 Gtk::MessageDialog am (msg);
1368 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), "Unknown Exception");
1369 Gtk::MessageDialog am (msg);
1379 LuaInstance::get_action_state ()
1383 luabridge::LuaRef savedstate ((*_lua_save)());
1384 saved = savedstate.cast<std::string>();
1386 lua.collect_garbage ();
1388 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1389 std::string b64s (b64);
1392 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1393 script_node->set_property (X_("lua"), LUA_VERSION);
1394 script_node->add_content (b64s);
1396 return *script_node;
1400 LuaInstance::get_hook_state ()
1402 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1403 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1404 script_node->add_child_nocopy (i->second->get_state ());
1406 return *script_node;
1410 LuaInstance::call_action (const int id)
1413 (*_lua_call_action)(id + 1);
1414 lua.collect_garbage_step ();
1415 } catch (luabridge::LuaException const& e) {
1416 cerr << "LuaException:" << e.what () << endl;
1421 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1422 int ii = reinterpret_cast<uintptr_t> (i);
1423 instance()->render_icon (ii, cr, w, h, c);
1427 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1429 Cairo::Context ctx (cr);
1431 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1432 } catch (luabridge::LuaException const& e) {
1433 cerr << "LuaException:" << e.what () << endl;
1438 LuaInstance::set_lua_action (
1440 const std::string& name,
1441 const std::string& script,
1442 const LuaScriptParamList& args)
1445 lua_State* L = lua.getState();
1446 // get bytcode of factory-function in a sandbox
1447 // (don't allow scripts to interfere)
1448 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1449 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1450 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1451 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1452 if ((*i)->optional && !(*i)->is_set) { continue; }
1453 tbl_arg[(*i)->name] = (*i)->value;
1455 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1456 ActionChanged (id, name); /* EMIT SIGNAL */
1457 } catch (luabridge::LuaException const& e) {
1458 cerr << "LuaException:" << e.what () << endl;
1463 _session->set_dirty ();
1468 LuaInstance::remove_lua_action (const int id)
1471 (*_lua_del_action)(id + 1);
1472 } catch (luabridge::LuaException const& e) {
1473 cerr << "LuaException:" << e.what () << endl;
1478 ActionChanged (id, ""); /* EMIT SIGNAL */
1479 _session->set_dirty ();
1484 LuaInstance::lua_action_name (const int id, std::string& rv)
1487 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1491 if (ref["name"].isString()) {
1492 rv = ref["name"].cast<std::string>();
1496 } catch (luabridge::LuaException const& e) {
1497 cerr << "LuaException:" << e.what () << endl;
1502 std::vector<std::string>
1503 LuaInstance::lua_action_names ()
1505 std::vector<std::string> rv;
1506 for (int i = 0; i < 9; ++i) {
1508 if (lua_action_name (i, name)) {
1509 rv.push_back (name);
1516 LuaInstance::lua_action_has_icon (const int id)
1519 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1523 if (ref["icon"].isBoolean()) {
1524 return ref["icon"].cast<bool>();
1526 } catch (luabridge::LuaException const& e) {
1527 cerr << "LuaException:" << e.what () << endl;
1533 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1536 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1540 if (!ref["name"].isString()) {
1543 if (!ref["script"].isString()) {
1546 if (!ref["args"].isTable()) {
1549 name = ref["name"].cast<std::string>();
1550 script = ref["script"].cast<std::string>();
1553 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1557 args = LuaScriptParams::script_params (lsi, "action_params");
1558 luabridge::LuaRef rargs (ref["args"]);
1559 LuaScriptParams::ref_to_params (args, &rargs);
1561 } catch (luabridge::LuaException const& e) {
1562 cerr << "LuaException:" << e.what () << endl;
1568 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1570 /* parse script, get ActionHook(s) from script */
1574 l.Print.connect (&_lua_print);
1576 lua_State* L = l.getState();
1578 l.do_command ("function ardour () end");
1579 l.do_command (script);
1580 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1581 if (signals.isFunction()) {
1584 } catch (luabridge::LuaException const& e) {
1585 cerr << "LuaException:" << e.what () << endl;
1589 cerr << "Script registered no hooks." << endl;
1593 /* register script w/args, get entry-point / ID */
1596 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1597 _callbacks.insert (std::make_pair(p->id(), p));
1598 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1599 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1601 } catch (luabridge::LuaException const& e) {
1602 cerr << "LuaException:" << e.what () << endl;
1604 _session->set_dirty ();
1609 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1611 LuaCallbackMap::iterator i = _callbacks.find (id);
1612 if (i != _callbacks.end()) {
1613 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1614 _callbacks.erase (i);
1617 _session->set_dirty ();
1621 std::vector<PBD::ID>
1622 LuaInstance::lua_slots () const
1624 std::vector<PBD::ID> rv;
1625 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1626 rv.push_back (i->first);
1632 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1634 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1635 if (i != _callbacks.end()) {
1636 name = i->second->name();
1642 std::vector<std::string>
1643 LuaInstance::lua_slot_names () const
1645 std::vector<std::string> rv;
1646 std::vector<PBD::ID> ids = lua_slots();
1647 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1649 if (lua_slot_name (*i, name)) {
1650 rv.push_back (name);
1657 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1659 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1660 if (i == _callbacks.end()) {
1661 return false; // error
1663 return i->second->lua_slot (name, script, ah, args);
1666 ///////////////////////////////////////////////////////////////////////////////
1668 LuaCallback::LuaCallback (Session *s,
1669 const std::string& name,
1670 const std::string& script,
1671 const ActionHook& ah,
1672 const ARDOUR::LuaScriptParamList& args)
1673 : SessionHandlePtr (s)
1678 // TODO: allow to reference object (e.g region)
1681 lua_State* L = lua.getState();
1682 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1683 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1684 if ((*i)->optional && !(*i)->is_set) { continue; }
1685 tbl_arg[(*i)->name] = (*i)->value;
1689 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1690 (*_lua_add)(name, script, bytecode, tbl_arg);
1691 } catch (luabridge::LuaException const& e) {
1692 cerr << "LuaException:" << e.what () << endl;
1693 throw failed_constructor ();
1695 throw failed_constructor ();
1702 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1703 : SessionHandlePtr (s)
1705 XMLNode* child = NULL;
1706 if (node.name() != X_("LuaCallback")
1707 || !node.property ("signals")
1708 || !node.property ("id")
1709 || !node.property ("name")) {
1710 throw failed_constructor ();
1713 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1714 if (!(*n)->is_content ()) { continue; }
1719 throw failed_constructor ();
1724 _id = PBD::ID (node.property ("id")->value ());
1725 _name = node.property ("name")->value ();
1726 _signals = ActionHook (node.property ("signals")->value ());
1729 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1731 (*_lua_load)(std::string ((const char*)buf, size));
1732 } catch (luabridge::LuaException const& e) {
1733 cerr << "LuaException:" << e.what () << endl;
1740 LuaCallback::~LuaCallback ()
1750 LuaCallback::get_state (void)
1754 luabridge::LuaRef savedstate ((*_lua_save)());
1755 saved = savedstate.cast<std::string>();
1758 lua.collect_garbage (); // this may be expensive:
1759 /* Editor::instant_save() calls Editor::get_state() which
1760 * calls LuaInstance::get_hook_state() which in turn calls
1761 * this LuaCallback::get_state() for every registered hook.
1763 * serialize in _lua_save() allocates many small strings
1764 * on the lua-stack, collecting them all may take a ms.
1767 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1768 std::string b64s (b64);
1771 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1772 script_node->set_property (X_("lua"), LUA_VERSION);
1773 script_node->set_property (X_("id"), _id.to_s ());
1774 script_node->set_property (X_("name"), _name);
1775 script_node->set_property (X_("signals"), _signals.to_string ());
1776 script_node->add_content (b64s);
1777 return *script_node;
1781 LuaCallback::init (void)
1783 lua.Print.connect (&_lua_print);
1784 lua.sandbox (false);
1787 "function ScriptManager ()"
1788 " local self = { script = {}, instance = {} }"
1790 " local addinternal = function (n, s, f, a)"
1791 " assert(type(n) == 'string', 'Name must be string')"
1792 " assert(type(s) == 'string', 'Script must be string')"
1793 " assert(type(f) == 'function', 'Factory is a not a function')"
1794 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1795 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1796 " local env = _ENV; env.f = nil"
1797 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1800 " local call = function (...)"
1801 " if type(self.instance) == 'function' then"
1802 " local status, err = pcall (self.instance, ...)"
1803 " if not status then"
1804 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1805 " self.script = nil"
1806 " self.instance = nil"
1814 " local add = function (n, s, b, a)"
1815 " assert(type(b) == 'string', 'ByteCode must be string')"
1816 " load (b)()" // assigns f
1817 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1818 " addinternal (n, s, load(f), a)"
1821 " local get = function ()"
1822 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1823 " return { ['name'] = self.script['n'],"
1824 " ['script'] = self.script['s'],"
1825 " ['args'] = self.script['a'] }"
1832 " local function basic_serialize (o)"
1833 " if type(o) == \"number\" then"
1834 " return tostring(o)"
1836 " return string.format(\"%q\", o)"
1840 " local function serialize (name, value)"
1841 " local rv = name .. ' = '"
1842 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1843 " return rv .. basic_serialize(value) .. ' '"
1844 " elseif type(value) == \"table\" then"
1846 " for k,v in pairs(value) do"
1847 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1848 " rv = rv .. serialize(fieldname, v) .. ' '"
1851 " elseif type(value) == \"function\" then"
1852 " return rv .. string.format(\"%q\", string.dump(value, true))"
1853 " elseif type(value) == \"boolean\" then"
1854 " return rv .. tostring (value)"
1856 " error('cannot save a ' .. type(value))"
1862 " local save = function ()"
1863 " return (serialize('s', self.script))"
1866 " local restore = function (state)"
1869 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1872 " return { call = call, add = add, get = get,"
1873 " restore = restore, save = save}"
1876 " manager = ScriptManager ()"
1877 " ScriptManager = nil"
1880 lua_State* L = lua.getState();
1883 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1884 lua.do_command ("manager = nil"); // hide it.
1885 lua.do_command ("collectgarbage()");
1887 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1888 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1889 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1890 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1891 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1893 } catch (luabridge::LuaException const& e) {
1894 fatal << string_compose (_("programming error: %1"),
1895 std::string ("Failed to setup Lua callback interpreter: ") + e.what ())
1897 abort(); /*NOTREACHED*/
1899 fatal << string_compose (_("programming error: %1"),
1900 X_("Failed to setup Lua callback interpreter"))
1902 abort(); /*NOTREACHED*/
1905 LuaInstance::register_classes (L);
1906 LuaInstance::register_hooks (L);
1908 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1909 lua_setglobal (L, "Editor");
1913 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1915 // TODO consolidate w/ LuaInstance::lua_action()
1917 luabridge::LuaRef ref = (*_lua_get)();
1921 if (!ref["name"].isString()) {
1924 if (!ref["script"].isString()) {
1927 if (!ref["args"].isTable()) {
1932 name = ref["name"].cast<std::string> ();
1933 script = ref["script"].cast<std::string> ();
1936 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1940 args = LuaScriptParams::script_params (lsi, "action_params");
1941 luabridge::LuaRef rargs (ref["args"]);
1942 LuaScriptParams::ref_to_params (args, &rargs);
1944 } catch (luabridge::LuaException const& e) {
1945 cerr << "LuaException:" << e.what () << endl;
1952 LuaCallback::set_session (ARDOUR::Session *s)
1954 SessionHandlePtr::set_session (s);
1960 lua_State* L = lua.getState();
1961 LuaBindings::set_session (L, _session);
1967 LuaCallback::session_going_away ()
1969 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1970 lua.do_command ("collectgarbage();");
1972 SessionHandlePtr::session_going_away ();
1975 drop_callback (); /* EMIT SIGNAL */
1979 LuaCallback::reconnect ()
1981 _connections.drop_connections ();
1982 if ((*_lua_get) ().isNil ()) {
1983 drop_callback (); /* EMIT SIGNAL */
1987 // TODO pass object which emits the signal (e.g region)
1989 // save/load bound objects will be tricky.
1990 // Best idea so far is to save/lookup the PBD::ID
1991 // (either use boost::any indirection or templates for bindable
1992 // object types or a switch statement..)
1994 // _session->route_by_id ()
1995 // _session->track_by_diskstream_id ()
1996 // _session->source_by_id ()
1997 // _session->controllable_by_id ()
1998 // _session->processor_by_id ()
1999 // RegionFactory::region_by_id ()
2001 // TODO loop over objects (if any)
2003 reconnect_object ((void*)0);
2006 template <class T> void
2007 LuaCallback::reconnect_object (T obj)
2009 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
2011 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
2012 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
2013 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
2015 # include "luasignal_syms.h"
2017 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
2018 abort(); /*NOTREACHED*/
2027 template <typename T, typename S> void
2028 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
2030 _connections, invalidator (*this),
2031 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
2035 template <typename T, typename C1> void
2036 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
2038 _connections, invalidator (*this),
2039 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
2043 template <typename T, typename C1, typename C2> void
2044 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
2046 _connections, invalidator (*this),
2047 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
2051 template <typename T> void
2052 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
2055 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
2056 if (! rv.cast<bool> ()) {
2060 /* destroy LuaRef ^^ first before calling drop_callback() */
2062 drop_callback (); /* EMIT SIGNAL */
2066 template <typename T, typename C1> void
2067 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
2070 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
2071 if (! rv.cast<bool> ()) {
2076 drop_callback (); /* EMIT SIGNAL */
2080 template <typename T, typename C1, typename C2> void
2081 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
2084 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
2085 if (! rv.cast<bool> ()) {
2090 drop_callback (); /* EMIT SIGNAL */