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"
24 #include "canvas/colors.h"
26 #include "ardour/audioengine.h"
27 #include "ardour/diskstream.h"
28 #include "ardour/plugin_manager.h"
29 #include "ardour/route.h"
30 #include "ardour/session.h"
32 #include "LuaBridge/LuaBridge.h"
34 #include "ardour_http.h"
35 #include "ardour_ui.h"
36 #include "public_editor.h"
37 #include "region_selection.h"
38 #include "luainstance.h"
39 #include "luasignal.h"
41 #include "processor_box.h"
42 #include "time_axis_view.h"
43 #include "selection.h"
44 #include "script_selector.h"
46 #include "utils_videotl.h"
51 /** wrap RefPtr< Cairo::ImageSurface >
53 * Image surfaces provide the ability to render to memory buffers either
54 * allocated by cairo or by the calling code. The supported image formats are
55 * those defined in Cairo::Format.
60 * Creates an image surface of the specified format and dimensions. Initially
61 * the surface contents are all 0. (Specifically, within each pixel, each
62 * color or alpha channel belonging to format will be 0. The contents of bits
63 * within a pixel, but not belonging to the given format are undefined).
65 * @param format format of pixels in the surface to create
66 * @param width width of the surface, in pixels
67 * @param height height of the surface, in pixels
69 ImageSurface (Cairo::Format format, int width, int height)
70 : _surface (Cairo::ImageSurface::create (format, width, height))
71 , _ctx (Cairo::Context::create (_surface))
72 , ctx (_ctx->cobj ()) {}
77 * Set this surface as source for another context.
78 * This allows to draw this surface
80 void set_as_source (Cairo::Context* c, int x, int y) {
82 c->set_source (_surface, x, y);
86 * Returns a context object to perform operations on the surface
88 Cairo::Context* context () {
89 return (Cairo::Context *)&ctx;
93 * Returns the stride of the image surface in bytes (or 0 if surface is not
94 * an image surface). The stride is the distance in bytes from the beginning
95 * of one row of the image data to the beginning of the next row.
97 int get_stride () const {
98 return _surface->get_stride ();
101 /** Gets the width of the ImageSurface in pixels */
102 int get_width () const {
103 return _surface->get_width ();
106 /** Gets the height of the ImageSurface in pixels */
107 int get_height () const {
108 return _surface->get_height ();
112 * Get a pointer to the data of the image surface, for direct
113 * inspection or modification.
115 * Return value: a pointer to the image data of this surface or NULL
116 * if @surface is not an image surface.
119 unsigned char* get_data () {
120 return _surface->get_data ();
123 /** Tells cairo to consider the data buffer dirty.
125 * In particular, if you've created an ImageSurface with a data buffer that
126 * you've allocated yourself and you draw to that data buffer using means
127 * other than cairo, you must call mark_dirty() before doing any additional
128 * drawing to that surface with cairo.
130 * Note that if you do draw to the Surface outside of cairo, you must call
131 * flush() before doing the drawing.
134 _surface->mark_dirty ();
137 /** Marks a rectangular area of the given surface dirty.
139 * @param x X coordinate of dirty rectangle
140 * @param y Y coordinate of dirty rectangle
141 * @param width width of dirty rectangle
142 * @param height height of dirty rectangle
144 void mark_dirty (int x, int y, int width, int height) {
145 _surface->mark_dirty (x, y, width, height);
149 Cairo::RefPtr<Cairo::ImageSurface> _surface;
150 Cairo::RefPtr<Cairo::Context> _ctx;
156 /** Create a new PangoLayout Text Display
157 * @param c CairoContext for the layout
158 * @param font_name a font-description e.g. "Mono 8px"
160 PangoLayout (Cairo::Context* c, std::string font_name) {
161 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
162 _layout = Glib::wrap (pl);
163 Pango::FontDescription fd (font_name);
164 _layout->set_font_description (fd);
169 /** Gets the text in the layout. The returned text should not
170 * be freed or modified.
172 * @return The text in the @a layout.
174 std::string get_text () const {
175 return _layout->get_text ();
177 /** Set the text of the layout.
178 * @param text The text for the layout.
180 void set_text (const std::string& text) {
181 _layout->set_text (text);
184 /** Sets the layout text and attribute list from marked-up text (see markup format).
185 * Replaces the current text and attribute list.
186 * @param markup Some marked-up text.
188 void set_markup (const std::string& markup) {
189 _layout->set_markup (markup);
192 /** Sets the width to which the lines of the Pango::Layout should wrap or
193 * ellipsized. The default value is -1: no width set.
195 * @param width The desired width in Pango units, or -1 to indicate that no
196 * wrapping or ellipsization should be performed.
198 void set_width (int width) {
199 _layout->set_width (width * PANGO_SCALE);
202 /** Gets the width to which the lines of the Pango::Layout should wrap.
204 * @return The width in Pango units, or -1 if no width set.
206 int get_width () const {
207 return _layout->get_width () / PANGO_SCALE;
210 /** Sets the type of ellipsization being performed for @a layout.
211 * Depending on the ellipsization mode @a ellipsize text is
212 * removed from the start, middle, or end of text so they
213 * fit within the width and height of layout set with
214 * set_width() and set_height().
216 * If the layout contains characters such as newlines that
217 * force it to be layed out in multiple paragraphs, then whether
218 * each paragraph is ellipsized separately or the entire layout
219 * is ellipsized as a whole depends on the set height of the layout.
220 * See set_height() for details.
222 * @param ellipsize The new ellipsization mode for @a layout.
224 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
225 _layout->set_ellipsize (ellipsize);
228 /** Gets the type of ellipsization being performed for @a layout.
229 * See set_ellipsize()
231 * @return The current ellipsization mode for @a layout.
233 * Use is_ellipsized() to query whether any paragraphs
234 * were actually ellipsized.
236 Pango::EllipsizeMode get_ellipsize () const {
237 return _layout->get_ellipsize ();
240 /** Queries whether the layout had to ellipsize any paragraphs.
242 * This returns <tt>true</tt> if the ellipsization mode for @a layout
243 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
244 * and there are paragraphs exceeding that width that have to be
247 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
250 bool is_ellipsized () const {
251 return _layout->is_ellipsized ();
254 /** Sets the wrap mode; the wrap mode only has effect if a width
255 * is set on the layout with set_width().
256 * To turn off wrapping, set the width to -1.
258 * @param wrap The wrap mode.
260 void set_wrap (Pango::WrapMode wrap) {
261 _layout->set_width (wrap);
264 /** Gets the wrap mode for the layout.
266 * Use is_wrapped() to query whether any paragraphs
267 * were actually wrapped.
269 * @return Active wrap mode.
271 Pango::WrapMode get_wrap () const {
272 return _layout->get_wrap ();
275 /** Queries whether the layout had to wrap any paragraphs.
277 * This returns <tt>true</tt> if a positive width is set on @a layout,
278 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
279 * and there are paragraphs exceeding the layout width that have
282 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
285 bool is_wrapped () const {
286 return _layout->is_wrapped ();
289 /** Determines the logical width and height of a Pango::Layout
292 int get_pixel_size (lua_State *L) {
294 _layout->get_pixel_size (width, height);
295 luabridge::Stack<int>::push (L, width);
296 luabridge::Stack<int>::push (L, height);
301 /** Draws a Layout in the specified Cairo @a context. The top-left
302 * corner of the Layout will be drawn at the current point of the
305 * @param context A Cairo context.
307 void show_in_cairo_context (Cairo::Context* c) {
308 pango_cairo_update_layout (c->cobj (), _layout->gobj());
309 pango_cairo_show_layout (c->cobj (), _layout->gobj());
313 Glib::RefPtr<Pango::Layout> _layout;
316 /** expand RGBA color to parameters
318 * convert a Canvas::Color (uint32_t 0xRRGGBBAA) into
319 * double RGBA values which can be passed as parameters to
320 * Cairo::Context::set_source_rgba
322 * @returns r, g, b, a
324 static int color_to_rgba (lua_State *L)
326 int top = lua_gettop (L);
328 return luaL_argerror (L, 1, "invalid number of arguments, color_to_rgba (uint32_t)");
330 uint32_t color = luabridge::Stack<uint32_t>::get (L, 1);
332 ArdourCanvas::color_to_rgba (color, r, g, b, a);
333 luabridge::Stack <double>::push (L, r);
334 luabridge::Stack <double>::push (L, g);
335 luabridge::Stack <double>::push (L, b);
336 luabridge::Stack <double>::push (L, a);
342 ////////////////////////////////////////////////////////////////////////////////
344 namespace LuaSignal {
346 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
347 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
348 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
351 str2luasignal (const std::string &str) {
352 const char* type = str.c_str();
354 # include "luasignal_syms.h"
356 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
357 abort(); /*NOTREACHED*/
364 #define STATIC(name,c,p) N_(#name),
365 #define SESSION(name,c,p) N_(#name),
366 #define ENGINE(name,c,p) N_(#name),
367 const char *luasignalstr[] = {
368 # include "luasignal_syms.h"
378 /** special cases for Ardour's Mixer UI */
381 ProcessorBox::ProcSelection
382 processor_selection () {
383 return ProcessorBox::current_processor_selection ();
388 ////////////////////////////////////////////////////////////////////////////////
390 #define xstr(s) stringify(s)
391 #define stringify(s) #s
393 using namespace ARDOUR;
395 PBD::Signal0<void> LuaInstance::LuaTimerDS;
398 LuaInstance::register_hooks (lua_State* L)
401 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
402 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
403 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
404 luabridge::getGlobalNamespace (L)
405 .beginNamespace ("LuaSignal")
406 # include "luasignal_syms.h"
412 luabridge::getGlobalNamespace (L)
413 .beginNamespace ("LuaSignal")
414 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
420 LuaInstance::bind_cairo (lua_State* L)
422 /* std::vector<double> for set_dash()
423 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
425 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
426 * the address of the one in libardour.dll is mapped when loading the .dll
428 * see LuaBindings::set_session() for a detailed explanation
430 luabridge::getGlobalNamespace (L)
431 .beginNamespace ("C")
432 .beginStdVector <double> ("DoubleVector")
436 luabridge::getGlobalNamespace (L)
437 .beginNamespace ("Cairo")
438 .beginClass <Cairo::Context> ("Context")
439 .addFunction ("save", &Cairo::Context::save)
440 .addFunction ("restore", &Cairo::Context::restore)
441 .addFunction ("set_operator", &Cairo::Context::set_operator)
442 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
443 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
444 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
445 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
446 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
447 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
448 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
449 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
450 .addFunction ("translate", &Cairo::Context::translate)
451 .addFunction ("scale", &Cairo::Context::scale)
452 .addFunction ("rotate", &Cairo::Context::rotate)
453 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
454 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
455 .addFunction ("move_to", &Cairo::Context::move_to)
456 .addFunction ("line_to", &Cairo::Context::line_to)
457 .addFunction ("curve_to", &Cairo::Context::curve_to)
458 .addFunction ("arc", &Cairo::Context::arc)
459 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
460 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
461 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
462 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
463 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
464 .addFunction ("close_path", &Cairo::Context::close_path)
465 .addFunction ("paint", &Cairo::Context::paint)
466 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
467 .addFunction ("stroke", &Cairo::Context::stroke)
468 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
469 .addFunction ("fill", &Cairo::Context::fill)
470 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
471 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
472 .addFunction ("clip", &Cairo::Context::clip)
473 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
474 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
475 .addFunction ("show_text", &Cairo::Context::show_text)
478 // LineCap, LineJoin, Operator
479 .beginNamespace ("LineCap")
480 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
481 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
482 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
485 .beginNamespace ("LineJoin")
486 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
487 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
488 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
491 .beginNamespace ("Operator")
492 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
493 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
494 .addConst ("Over", CAIRO_OPERATOR_OVER)
495 .addConst ("Add", CAIRO_OPERATOR_ADD)
498 .beginNamespace ("Format")
499 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
500 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
503 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
504 .addConstructor <void (*) (Cairo::Format, int, int)> ()
505 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
506 .addFunction ("context", &LuaCairo::ImageSurface::context)
507 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
508 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
509 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
510 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
513 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
514 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
515 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
516 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
517 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
518 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
519 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
520 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
521 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
522 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
523 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
524 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
525 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
526 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
530 .beginNamespace ("EllipsizeMode")
531 .addConst ("None", Pango::ELLIPSIZE_NONE)
532 .addConst ("Start", Pango::ELLIPSIZE_START)
533 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
534 .addConst ("End", Pango::ELLIPSIZE_END)
537 .beginNamespace ("WrapMode")
538 .addConst ("Word", Pango::WRAP_WORD)
539 .addConst ("Char", Pango::WRAP_CHAR)
540 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
546 .beginNamespace ("LuaCairo")
547 .addCFunction ("color_to_rgba", &LuaCairo::color_to_rgba)
550 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
551 one can work around this as follows:
554 LuaInstance::register_classes (lua.getState());
556 "function render (ctx)"
557 " ctx:rectangle (0, 0, 100, 100)"
558 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
563 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
564 Cairo::Context ctx (context->cobj ());
566 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
567 lua_render ((Cairo::Context *)&ctx);
574 LuaInstance::register_classes (lua_State* L)
576 LuaBindings::stddef (L);
577 LuaBindings::common (L);
578 LuaBindings::session (L);
579 LuaBindings::osc (L);
584 luabridge::getGlobalNamespace (L)
585 .beginNamespace ("ArdourUI")
587 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
589 .addFunction ("processor_selection", &LuaMixer::processor_selection)
591 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
594 .beginClass <ArdourMarker> ("ArdourMarker")
595 .addFunction ("name", &ArdourMarker::name)
596 .addFunction ("position", &ArdourMarker::position)
597 .addFunction ("_type", &ArdourMarker::type)
601 .beginClass <AxisView> ("AxisView")
603 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
605 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
609 .beginClass <RegionSelection> ("RegionSelection")
610 .addFunction ("clear_all", &RegionSelection::clear_all)
611 .addFunction ("start", &RegionSelection::start)
612 .addFunction ("end_frame", &RegionSelection::end_frame)
613 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
614 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
617 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
618 .addFunction ("start", &TimeSelection::start)
619 .addFunction ("end_frame", &TimeSelection::end_frame)
620 .addFunction ("length", &TimeSelection::length)
623 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
626 .beginClass <TrackViewList> ("TrackViewList")
627 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
630 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
633 .beginClass <Selection> ("Selection")
634 .addFunction ("clear", &Selection::clear)
635 .addFunction ("clear_all", &Selection::clear_all)
636 .addFunction ("empty", &Selection::empty)
637 .addData ("tracks", &Selection::tracks)
638 .addData ("regions", &Selection::regions)
639 .addData ("time", &Selection::time)
640 .addData ("markers", &Selection::markers)
642 .addData ("lines", &Selection::lines)
643 .addData ("playlists", &Selection::playlists)
644 .addData ("points", &Selection::points)
645 .addData ("midi_regions", &Selection::midi_regions)
646 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
650 .beginClass <PublicEditor> ("Editor")
651 .addFunction ("snap_type", &PublicEditor::snap_type)
652 .addFunction ("snap_mode", &PublicEditor::snap_mode)
653 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
654 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
656 .addFunction ("undo", &PublicEditor::undo)
657 .addFunction ("redo", &PublicEditor::redo)
659 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
660 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
662 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
664 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
665 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
666 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
667 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
669 .addFunction ("get_selection", &PublicEditor::get_selection)
670 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
671 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
673 .addFunction ("play_selection", &PublicEditor::play_selection)
674 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
675 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
676 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
678 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
679 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
681 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
682 .addFunction ("show_measures", &PublicEditor::show_measures)
683 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
685 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
686 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
688 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
690 .addRefFunction ("do_import", &PublicEditor::do_import)
691 .addRefFunction ("do_embed", &PublicEditor::do_embed)
693 .addFunction ("export_audio", &PublicEditor::export_audio)
694 .addFunction ("stem_export", &PublicEditor::stem_export)
695 .addFunction ("export_selection", &PublicEditor::export_selection)
696 .addFunction ("export_range", &PublicEditor::export_range)
698 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
699 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
700 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
701 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
703 #if 0 // These need TimeAxisView* which isn't exposed, yet
704 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
705 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
706 .addFunction ("new_playlists", &PublicEditor::new_playlists)
707 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
708 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
711 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
712 .addFunction ("deselect_all", &PublicEditor::deselect_all)
714 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
715 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
716 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
718 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
719 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
720 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
721 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
723 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
724 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
725 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
726 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
727 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
728 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
729 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
731 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
732 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
733 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
734 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
736 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
737 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
738 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
740 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
742 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
743 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
744 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
746 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
747 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
749 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
750 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
751 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
752 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
754 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
755 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
756 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
757 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
760 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
761 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
763 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
764 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
765 .addFunction ("get_track_views", &PublicEditor::get_track_views)
766 .addFunction ("drags", &PublicEditor::drags)
769 .addFunction ("center_screen", &PublicEditor::center_screen)
771 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
772 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
774 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
775 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
776 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
778 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
779 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
780 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
781 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
782 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
786 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
787 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
788 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
789 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
792 .addFunction ("access_action", &PublicEditor::access_action)
796 .beginNamespace ("MarkerType")
797 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
798 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
799 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
800 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
801 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
802 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
803 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
804 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
805 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
806 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
807 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
810 .endNamespace (); // end ArdourUI
818 #undef DISPLAYCONTROL
820 #undef IMPORTPOSITION
821 #undef IMPORTDISPOSITION
823 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
824 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
825 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
826 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
827 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
828 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
829 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
830 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
831 luabridge::getGlobalNamespace (L)
832 .beginNamespace ("Editing")
833 # include "editing_syms.h"
840 ////////////////////////////////////////////////////////////////////////////////
842 using namespace ARDOUR;
843 using namespace ARDOUR_UI_UTILS;
847 static void _lua_print (std::string s) {
849 std::cout << "LuaInstance: " << s << "\n";
851 PBD::info << "LuaInstance: " << s << endmsg;
854 LuaInstance* LuaInstance::_instance = 0;
857 LuaInstance::instance ()
860 _instance = new LuaInstance;
867 LuaInstance::destroy_instance ()
873 LuaInstance::LuaInstance ()
875 lua.Print.connect (&_lua_print);
878 LuaScriptParamList args;
881 LuaInstance::~LuaInstance ()
883 delete _lua_call_action;
884 delete _lua_render_icon;
885 delete _lua_add_action;
886 delete _lua_del_action;
887 delete _lua_get_action;
899 "function ScriptManager ()"
900 " local self = { scripts = {}, instances = {}, icons = {} }"
902 " local remove = function (id)"
903 " self.scripts[id] = nil"
904 " self.instances[id] = nil"
905 " self.icons[id] = nil"
908 " local addinternal = function (i, n, s, f, c, a)"
909 " assert(type(i) == 'number', 'id must be numeric')"
910 " assert(type(n) == 'string', 'Name must be string')"
911 " assert(type(s) == 'string', 'Script must be string')"
912 " assert(type(f) == 'function', 'Factory is a not a function')"
913 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
914 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
915 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
916 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
917 " if type(c) == 'function' then"
918 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
920 " self.icons[i] = nil"
924 " local call = function (id)"
925 " if type(self.instances[id]) == 'function' then"
926 " local status, err = pcall (self.instances[id])"
927 " if not status then"
928 " print ('action \"'.. id .. '\": ', err)" // error out
935 " local icon = function (id, ...)"
936 " if type(self.icons[id]) == 'function' then"
937 " pcall (self.icons[id], ...)"
942 " local add = function (i, n, s, b, c, a)"
943 " assert(type(b) == 'string', 'ByteCode must be string')"
944 " f = nil load (b)()" // assigns f
945 " icn = nil load (c)()" // may assign "icn"
946 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
947 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
950 " local get = function (id)"
951 " if type(self.scripts[id]) == 'table' then"
952 " return { ['name'] = self.scripts[id]['n'],"
953 " ['script'] = self.scripts[id]['s'],"
954 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
955 " ['args'] = self.scripts[id]['a'] }"
960 " local function basic_serialize (o)"
961 " if type(o) == \"number\" then"
962 " return tostring(o)"
964 " return string.format(\"%q\", o)"
968 " local function serialize (name, value)"
969 " local rv = name .. ' = '"
971 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
972 " return rv .. basic_serialize(value) .. ' '"
973 " elseif type(value) == \"table\" then"
975 " for k,v in pairs(value) do"
976 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
977 " rv = rv .. serialize(fieldname, v) .. ' '"
978 " collectgarbage()" // string concatenation allocates a new string
981 " elseif type(value) == \"function\" then"
982 " return rv .. string.format(\"%q\", string.dump(value, true))"
983 " elseif type(value) == \"boolean\" then"
984 " return rv .. tostring (value)"
986 " error('cannot save a ' .. type(value))"
991 " local save = function ()"
992 " return (serialize('scripts', self.scripts))"
995 " local clear = function ()"
997 " self.instances = {}"
1002 " local restore = function (state)"
1005 " for i, s in pairs (scripts) do"
1006 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1011 " return { call = call, add = add, remove = remove, get = get,"
1012 " restore = restore, save = save, clear = clear, icon = icon}"
1015 " manager = ScriptManager ()"
1016 " ScriptManager = nil"
1019 lua_State* L = lua.getState();
1022 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1023 lua.do_command ("manager = nil"); // hide it.
1024 lua.do_command ("collectgarbage()");
1026 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1027 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1028 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1029 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1030 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1031 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1032 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1033 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1035 } catch (luabridge::LuaException const& e) {
1036 fatal << string_compose (_("programming error: %1"),
1037 X_("Failed to setup Lua action interpreter"))
1039 abort(); /*NOTREACHED*/
1042 register_classes (L);
1044 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1045 lua_setglobal (L, "Editor");
1048 void LuaInstance::set_session (Session* s)
1050 SessionHandlePtr::set_session (s);
1055 lua_State* L = lua.getState();
1056 LuaBindings::set_session (L, _session);
1058 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1059 i->second->set_session (s);
1061 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1065 LuaInstance::session_going_away ()
1067 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1068 point_one_second_connection.disconnect ();
1071 for (int i = 0; i < 9; ++i) {
1072 ActionChanged (i, ""); /* EMIT SIGNAL */
1074 SessionHandlePtr::session_going_away ();
1077 lua_State* L = lua.getState();
1078 LuaBindings::set_session (L, _session);
1079 lua.do_command ("collectgarbage();");
1083 LuaInstance::every_point_one_seconds ()
1085 LuaTimerDS (); // emit signal
1089 LuaInstance::set_state (const XMLNode& node)
1094 if ((child = find_named_node (node, "ActionScript"))) {
1095 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1096 if (!(*n)->is_content ()) { continue; }
1098 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1100 (*_lua_load)(std::string ((const char*)buf, size));
1101 } catch (luabridge::LuaException const& e) {
1102 cerr << "LuaException:" << e.what () << endl;
1104 for (int i = 0; i < 9; ++i) {
1106 if (lua_action_name (i, name)) {
1107 ActionChanged (i, name); /* EMIT SIGNAL */
1114 if ((child = find_named_node (node, "ActionHooks"))) {
1115 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1117 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1118 _callbacks.insert (std::make_pair(p->id(), p));
1119 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1120 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1121 } catch (luabridge::LuaException const& e) {
1122 cerr << "LuaException:" << e.what () << endl;
1131 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1134 std::vector<std::string> reg;
1137 case LuaScriptInfo::EditorAction:
1138 reg = lua_action_names ();
1139 title = "Add Lua Action";
1141 case LuaScriptInfo::EditorHook:
1142 reg = lua_slot_names ();
1143 title = "Add Lua Callback Hook";
1149 LuaScriptInfoPtr spi;
1150 ScriptSelector ss (title, type);
1151 switch (ss.run ()) {
1152 case Gtk::RESPONSE_ACCEPT:
1160 std::string script = "";
1163 script = Glib::file_get_contents (spi->path);
1164 } catch (Glib::FileError e) {
1165 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1166 Gtk::MessageDialog am (msg);
1171 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, "action_params");
1173 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1174 switch (spd.run ()) {
1175 case Gtk::RESPONSE_ACCEPT:
1182 case LuaScriptInfo::EditorAction:
1183 return set_lua_action (id, spd.name(), script, lsp);
1185 case LuaScriptInfo::EditorHook:
1186 return register_lua_slot (spd.name(), script, lsp);
1195 LuaInstance::get_action_state ()
1200 luabridge::LuaRef savedstate ((*_lua_save)());
1201 saved = savedstate.cast<std::string>();
1203 lua.collect_garbage ();
1205 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1206 std::string b64s (b64);
1209 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1210 script_node->add_property (X_("lua"), LUA_VERSION);
1211 script_node->add_content (b64s);
1213 return *script_node;
1217 LuaInstance::get_hook_state ()
1219 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1220 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1221 script_node->add_child_nocopy (i->second->get_state ());
1223 return *script_node;
1227 LuaInstance::call_action (const int id)
1230 (*_lua_call_action)(id + 1);
1231 lua.collect_garbage_step ();
1232 } catch (luabridge::LuaException const& e) {
1233 cerr << "LuaException:" << e.what () << endl;
1238 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1239 int ii = reinterpret_cast<uintptr_t> (i);
1240 instance()->render_icon (ii, cr, w, h, c);
1244 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1246 Cairo::Context ctx (cr);
1248 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1249 } catch (luabridge::LuaException const& e) {
1250 cerr << "LuaException:" << e.what () << endl;
1255 LuaInstance::set_lua_action (
1257 const std::string& name,
1258 const std::string& script,
1259 const LuaScriptParamList& args)
1262 lua_State* L = lua.getState();
1263 // get bytcode of factory-function in a sandbox
1264 // (don't allow scripts to interfere)
1265 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1266 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1267 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1268 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1269 if ((*i)->optional && !(*i)->is_set) { continue; }
1270 tbl_arg[(*i)->name] = (*i)->value;
1272 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1273 ActionChanged (id, name); /* EMIT SIGNAL */
1274 } catch (luabridge::LuaException const& e) {
1275 cerr << "LuaException:" << e.what () << endl;
1278 _session->set_dirty ();
1283 LuaInstance::remove_lua_action (const int id)
1286 (*_lua_del_action)(id + 1);
1287 } catch (luabridge::LuaException const& e) {
1288 cerr << "LuaException:" << e.what () << endl;
1291 ActionChanged (id, ""); /* EMIT SIGNAL */
1292 _session->set_dirty ();
1297 LuaInstance::lua_action_name (const int id, std::string& rv)
1300 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1304 if (ref["name"].isString()) {
1305 rv = ref["name"].cast<std::string>();
1309 } catch (luabridge::LuaException const& e) {
1310 cerr << "LuaException:" << e.what () << endl;
1316 std::vector<std::string>
1317 LuaInstance::lua_action_names ()
1319 std::vector<std::string> rv;
1320 for (int i = 0; i < 9; ++i) {
1322 if (lua_action_name (i, name)) {
1323 rv.push_back (name);
1330 LuaInstance::lua_action_has_icon (const int id)
1333 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1337 if (ref["icon"].isBoolean()) {
1338 return ref["icon"].cast<bool>();
1340 } catch (luabridge::LuaException const& e) {
1341 cerr << "LuaException:" << e.what () << endl;
1347 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1350 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1354 if (!ref["name"].isString()) {
1357 if (!ref["script"].isString()) {
1360 if (!ref["args"].isTable()) {
1363 name = ref["name"].cast<std::string>();
1364 script = ref["script"].cast<std::string>();
1367 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1371 args = LuaScriptParams::script_params (lsi, "action_params");
1372 luabridge::LuaRef rargs (ref["args"]);
1373 LuaScriptParams::ref_to_params (args, &rargs);
1375 } catch (luabridge::LuaException const& e) {
1376 cerr << "LuaException:" << e.what () << endl;
1383 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1385 /* parse script, get ActionHook(s) from script */
1389 l.Print.connect (&_lua_print);
1390 lua_State* L = l.getState();
1392 l.do_command ("function ardour () end");
1393 l.do_command (script);
1394 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1395 if (signals.isFunction()) {
1398 } catch (luabridge::LuaException const& e) {
1399 cerr << "LuaException:" << e.what () << endl;
1403 cerr << "Script registered no hooks." << endl;
1407 /* register script w/args, get entry-point / ID */
1410 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1411 _callbacks.insert (std::make_pair(p->id(), p));
1412 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1413 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1415 } catch (luabridge::LuaException const& e) {
1416 cerr << "LuaException:" << e.what () << endl;
1418 _session->set_dirty ();
1423 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1425 LuaCallbackMap::iterator i = _callbacks.find (id);
1426 if (i != _callbacks.end()) {
1427 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1428 _callbacks.erase (i);
1431 _session->set_dirty ();
1435 std::vector<PBD::ID>
1436 LuaInstance::lua_slots () const
1438 std::vector<PBD::ID> rv;
1439 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1440 rv.push_back (i->first);
1446 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1448 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1449 if (i != _callbacks.end()) {
1450 name = i->second->name();
1456 std::vector<std::string>
1457 LuaInstance::lua_slot_names () const
1459 std::vector<std::string> rv;
1460 std::vector<PBD::ID> ids = lua_slots();
1461 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1463 if (lua_slot_name (*i, name)) {
1464 rv.push_back (name);
1471 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1473 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1474 if (i == _callbacks.end()) {
1475 return false; // error
1477 return i->second->lua_slot (name, script, ah, args);
1480 ///////////////////////////////////////////////////////////////////////////////
1482 LuaCallback::LuaCallback (Session *s,
1483 const std::string& name,
1484 const std::string& script,
1485 const ActionHook& ah,
1486 const ARDOUR::LuaScriptParamList& args)
1487 : SessionHandlePtr (s)
1492 // TODO: allow to reference object (e.g region)
1495 lua_State* L = lua.getState();
1496 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1497 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1498 if ((*i)->optional && !(*i)->is_set) { continue; }
1499 tbl_arg[(*i)->name] = (*i)->value;
1503 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1504 (*_lua_add)(name, script, bytecode, tbl_arg);
1505 } catch (luabridge::LuaException const& e) {
1506 cerr << "LuaException:" << e.what () << endl;
1507 throw failed_constructor ();
1514 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1515 : SessionHandlePtr (s)
1517 XMLNode* child = NULL;
1518 if (node.name() != X_("LuaCallback")
1519 || !node.property ("signals")
1520 || !node.property ("id")
1521 || !node.property ("name")) {
1522 throw failed_constructor ();
1525 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1526 if (!(*n)->is_content ()) { continue; }
1531 throw failed_constructor ();
1536 _id = PBD::ID (node.property ("id")->value ());
1537 _name = node.property ("name")->value ();
1538 _signals = ActionHook (node.property ("signals")->value ());
1541 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1543 (*_lua_load)(std::string ((const char*)buf, size));
1544 } catch (luabridge::LuaException const& e) {
1545 cerr << "LuaException:" << e.what () << endl;
1552 LuaCallback::~LuaCallback ()
1562 LuaCallback::get_state (void)
1566 luabridge::LuaRef savedstate ((*_lua_save)());
1567 saved = savedstate.cast<std::string>();
1569 lua.collect_garbage ();
1571 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1572 std::string b64s (b64);
1575 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1576 script_node->add_property (X_("lua"), LUA_VERSION);
1577 script_node->add_property (X_("id"), _id.to_s ());
1578 script_node->add_property (X_("name"), _name);
1579 script_node->add_property (X_("signals"), _signals.to_string ());
1580 script_node->add_content (b64s);
1581 return *script_node;
1585 LuaCallback::init (void)
1587 lua.Print.connect (&_lua_print);
1590 "function ScriptManager ()"
1591 " local self = { script = {}, instance = {} }"
1593 " local addinternal = function (n, s, f, a)"
1594 " assert(type(n) == 'string', 'Name must be string')"
1595 " assert(type(s) == 'string', 'Script must be string')"
1596 " assert(type(f) == 'function', 'Factory is a not a function')"
1597 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1598 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1599 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1600 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1603 " local call = function (...)"
1604 " if type(self.instance) == 'function' then"
1605 " local status, err = pcall (self.instance, ...)"
1606 " if not status then"
1607 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1608 " self.script = nil"
1609 " self.instance = nil"
1617 " local add = function (n, s, b, a)"
1618 " assert(type(b) == 'string', 'ByteCode must be string')"
1619 " load (b)()" // assigns f
1620 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1621 " addinternal (n, s, load(f), a)"
1624 " local get = function ()"
1625 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1626 " return { ['name'] = self.script['n'],"
1627 " ['script'] = self.script['s'],"
1628 " ['args'] = self.script['a'] }"
1635 " local function basic_serialize (o)"
1636 " if type(o) == \"number\" then"
1637 " return tostring(o)"
1639 " return string.format(\"%q\", o)"
1643 " local function serialize (name, value)"
1644 " local rv = name .. ' = '"
1646 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1647 " return rv .. basic_serialize(value) .. ' '"
1648 " elseif type(value) == \"table\" then"
1650 " for k,v in pairs(value) do"
1651 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1652 " rv = rv .. serialize(fieldname, v) .. ' '"
1653 " collectgarbage()" // string concatenation allocates a new string
1656 " elseif type(value) == \"function\" then"
1657 " return rv .. string.format(\"%q\", string.dump(value, true))"
1658 " elseif type(value) == \"boolean\" then"
1659 " return rv .. tostring (value)"
1661 " error('cannot save a ' .. type(value))"
1667 " local save = function ()"
1668 " return (serialize('s', self.script))"
1671 " local restore = function (state)"
1674 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1677 " return { call = call, add = add, get = get,"
1678 " restore = restore, save = save}"
1681 " manager = ScriptManager ()"
1682 " ScriptManager = nil"
1685 lua_State* L = lua.getState();
1688 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1689 lua.do_command ("manager = nil"); // hide it.
1690 lua.do_command ("collectgarbage()");
1692 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1693 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1694 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1695 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1696 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1698 } catch (luabridge::LuaException const& e) {
1699 fatal << string_compose (_("programming error: %1"),
1700 X_("Failed to setup Lua callback interpreter"))
1702 abort(); /*NOTREACHED*/
1705 LuaInstance::register_classes (L);
1707 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1708 lua_setglobal (L, "Editor");
1712 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1714 // TODO consolidate w/ LuaInstance::lua_action()
1716 luabridge::LuaRef ref = (*_lua_get)();
1720 if (!ref["name"].isString()) {
1723 if (!ref["script"].isString()) {
1726 if (!ref["args"].isTable()) {
1731 name = ref["name"].cast<std::string> ();
1732 script = ref["script"].cast<std::string> ();
1735 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1739 args = LuaScriptParams::script_params (lsi, "action_params");
1740 luabridge::LuaRef rargs (ref["args"]);
1741 LuaScriptParams::ref_to_params (args, &rargs);
1743 } catch (luabridge::LuaException const& e) {
1744 cerr << "LuaException:" << e.what () << endl;
1751 LuaCallback::set_session (ARDOUR::Session *s)
1753 SessionHandlePtr::set_session (s);
1759 lua_State* L = lua.getState();
1760 LuaBindings::set_session (L, _session);
1766 LuaCallback::session_going_away ()
1768 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1769 lua.do_command ("collectgarbage();");
1771 SessionHandlePtr::session_going_away ();
1774 drop_callback (); /* EMIT SIGNAL */
1778 LuaCallback::reconnect ()
1780 _connections.drop_connections ();
1781 if ((*_lua_get) ().isNil ()) {
1782 drop_callback (); /* EMIT SIGNAL */
1786 // TODO pass object which emits the signal (e.g region)
1788 // save/load bound objects will be tricky.
1789 // Best idea so far is to save/lookup the PBD::ID
1790 // (either use boost::any indirection or templates for bindable
1791 // object types or a switch statement..)
1793 // _session->route_by_id ()
1794 // _session->track_by_diskstream_id ()
1795 // _session->source_by_id ()
1796 // _session->controllable_by_id ()
1797 // _session->processor_by_id ()
1798 // RegionFactory::region_by_id ()
1800 // TODO loop over objects (if any)
1802 reconnect_object ((void*)0);
1805 template <class T> void
1806 LuaCallback::reconnect_object (T obj)
1808 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1810 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1811 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1812 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1814 # include "luasignal_syms.h"
1816 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1817 abort(); /*NOTREACHED*/
1826 template <typename T, typename S> void
1827 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1829 _connections, invalidator (*this),
1830 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1834 template <typename T, typename C1> void
1835 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1837 _connections, invalidator (*this),
1838 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1842 template <typename T, typename C1, typename C2> void
1843 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1845 _connections, invalidator (*this),
1846 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1850 template <typename T> void
1851 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1854 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1855 if (! rv.cast<bool> ()) {
1859 /* destroy LuaRef ^^ first before calling drop_callback() */
1861 drop_callback (); /* EMIT SIGNAL */
1865 template <typename T, typename C1> void
1866 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1869 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1870 if (! rv.cast<bool> ()) {
1875 drop_callback (); /* EMIT SIGNAL */
1879 template <typename T, typename C1, typename C2> void
1880 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1883 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1884 if (! rv.cast<bool> ()) {
1889 drop_callback (); /* EMIT SIGNAL */