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/diskstream.h"
27 #include "ardour/plugin_manager.h"
28 #include "ardour/route.h"
29 #include "ardour/session.h"
31 #include "LuaBridge/LuaBridge.h"
33 #include "ardour_http.h"
34 #include "ardour_ui.h"
35 #include "public_editor.h"
36 #include "region_selection.h"
37 #include "luainstance.h"
38 #include "luasignal.h"
40 #include "time_axis_view.h"
41 #include "selection.h"
42 #include "script_selector.h"
43 #include "utils_videotl.h"
48 /** wrap RefPtr< Cairo::ImageSurface >
50 * Image surfaces provide the ability to render to memory buffers either
51 * allocated by cairo or by the calling code. The supported image formats are
52 * those defined in Cairo::Format.
57 * Creates an image surface of the specified format and dimensions. Initially
58 * the surface contents are all 0. (Specifically, within each pixel, each
59 * color or alpha channel belonging to format will be 0. The contents of bits
60 * within a pixel, but not belonging to the given format are undefined).
62 * @param format format of pixels in the surface to create
63 * @param width width of the surface, in pixels
64 * @param height height of the surface, in pixels
66 ImageSurface (Cairo::Format format, int width, int height)
67 : _surface (Cairo::ImageSurface::create (format, width, height))
68 , _ctx (Cairo::Context::create (_surface))
69 , ctx (_ctx->cobj ()) {}
74 * Set this surface as source for another context.
75 * This allows to draw this surface
77 void set_as_source (Cairo::Context* c, int x, int y) {
79 c->set_source (_surface, x, y);
83 * Returns a context object to perform operations on the surface
85 Cairo::Context* context () {
86 return (Cairo::Context *)&ctx;
90 * Returns the stride of the image surface in bytes (or 0 if surface is not
91 * an image surface). The stride is the distance in bytes from the beginning
92 * of one row of the image data to the beginning of the next row.
94 int get_stride () const {
95 return _surface->get_stride ();
98 /** Gets the width of the ImageSurface in pixels */
99 int get_width () const {
100 return _surface->get_width ();
103 /** Gets the height of the ImageSurface in pixels */
104 int get_height () const {
105 return _surface->get_height ();
109 * Get a pointer to the data of the image surface, for direct
110 * inspection or modification.
112 * Return value: a pointer to the image data of this surface or NULL
113 * if @surface is not an image surface.
116 unsigned char* get_data () {
117 return _surface->get_data ();
120 /** Tells cairo to consider the data buffer dirty.
122 * In particular, if you've created an ImageSurface with a data buffer that
123 * you've allocated yourself and you draw to that data buffer using means
124 * other than cairo, you must call mark_dirty() before doing any additional
125 * drawing to that surface with cairo.
127 * Note that if you do draw to the Surface outside of cairo, you must call
128 * flush() before doing the drawing.
131 _surface->mark_dirty ();
134 /** Marks a rectangular area of the given surface dirty.
136 * @param x X coordinate of dirty rectangle
137 * @param y Y coordinate of dirty rectangle
138 * @param width width of dirty rectangle
139 * @param height height of dirty rectangle
141 void mark_dirty (int x, int y, int width, int height) {
142 _surface->mark_dirty (x, y, width, height);
146 Cairo::RefPtr<Cairo::ImageSurface> _surface;
147 Cairo::RefPtr<Cairo::Context> _ctx;
153 /** Create a new PangoLayout Text Display
154 * @param c CairoContext for the layout
155 * @param font_name a font-description e.g. "Mono 8px"
157 PangoLayout (Cairo::Context* c, std::string font_name) {
158 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
159 _layout = Glib::wrap (pl);
160 Pango::FontDescription fd (font_name);
161 _layout->set_font_description (fd);
166 /** Gets the text in the layout. The returned text should not
167 * be freed or modified.
169 * @return The text in the @a layout.
171 std::string get_text () const {
172 return _layout->get_text ();
174 /** Set the text of the layout.
175 * @param text The text for the layout.
177 void set_text (const std::string& text) {
178 _layout->set_text (text);
181 /** Sets the layout text and attribute list from marked-up text (see markup format).
182 * Replaces the current text and attribute list.
183 * @param markup Some marked-up text.
185 void set_markup (const std::string& markup) {
186 _layout->set_markup (markup);
189 /** Sets the width to which the lines of the Pango::Layout should wrap or
190 * ellipsized. The default value is -1: no width set.
192 * @param width The desired width in Pango units, or -1 to indicate that no
193 * wrapping or ellipsization should be performed.
195 void set_width (int width) {
196 _layout->set_width (width * PANGO_SCALE);
199 /** Gets the width to which the lines of the Pango::Layout should wrap.
201 * @return The width in Pango units, or -1 if no width set.
203 int get_width () const {
204 return _layout->get_width () / PANGO_SCALE;
207 /** Sets the type of ellipsization being performed for @a layout.
208 * Depending on the ellipsization mode @a ellipsize text is
209 * removed from the start, middle, or end of text so they
210 * fit within the width and height of layout set with
211 * set_width() and set_height().
213 * If the layout contains characters such as newlines that
214 * force it to be layed out in multiple paragraphs, then whether
215 * each paragraph is ellipsized separately or the entire layout
216 * is ellipsized as a whole depends on the set height of the layout.
217 * See set_height() for details.
219 * @param ellipsize The new ellipsization mode for @a layout.
221 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
222 _layout->set_ellipsize (ellipsize);
225 /** Gets the type of ellipsization being performed for @a layout.
226 * See set_ellipsize()
228 * @return The current ellipsization mode for @a layout.
230 * Use is_ellipsized() to query whether any paragraphs
231 * were actually ellipsized.
233 Pango::EllipsizeMode get_ellipsize () const {
234 return _layout->get_ellipsize ();
237 /** Queries whether the layout had to ellipsize any paragraphs.
239 * This returns <tt>true</tt> if the ellipsization mode for @a layout
240 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
241 * and there are paragraphs exceeding that width that have to be
244 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
247 bool is_ellipsized () const {
248 return _layout->is_ellipsized ();
251 /** Sets the wrap mode; the wrap mode only has effect if a width
252 * is set on the layout with set_width().
253 * To turn off wrapping, set the width to -1.
255 * @param wrap The wrap mode.
257 void set_wrap (Pango::WrapMode wrap) {
258 _layout->set_width (wrap);
261 /** Gets the wrap mode for the layout.
263 * Use is_wrapped() to query whether any paragraphs
264 * were actually wrapped.
266 * @return Active wrap mode.
268 Pango::WrapMode get_wrap () const {
269 return _layout->get_wrap ();
272 /** Queries whether the layout had to wrap any paragraphs.
274 * This returns <tt>true</tt> if a positive width is set on @a layout,
275 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
276 * and there are paragraphs exceeding the layout width that have
279 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
282 bool is_wrapped () const {
283 return _layout->is_wrapped ();
286 /** Determines the logical width and height of a Pango::Layout
289 int get_pixel_size (lua_State *L) {
291 _layout->get_pixel_size (width, height);
292 luabridge::Stack<int>::push (L, width);
293 luabridge::Stack<int>::push (L, height);
298 /** Draws a Layout in the specified Cairo @a context. The top-left
299 * corner of the Layout will be drawn at the current point of the
302 * @param context A Cairo context.
304 void show_in_cairo_context (Cairo::Context* c) {
305 pango_cairo_update_layout (c->cobj (), _layout->gobj());
306 pango_cairo_show_layout (c->cobj (), _layout->gobj());
310 Glib::RefPtr<Pango::Layout> _layout;
315 ////////////////////////////////////////////////////////////////////////////////
317 namespace LuaSignal {
319 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
320 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
321 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
324 str2luasignal (const std::string &str) {
325 const char* type = str.c_str();
327 # include "luasignal_syms.h"
329 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
330 abort(); /*NOTREACHED*/
337 #define STATIC(name,c,p) N_(#name),
338 #define SESSION(name,c,p) N_(#name),
339 #define ENGINE(name,c,p) N_(#name),
340 const char *luasignalstr[] = {
341 # include "luasignal_syms.h"
351 ////////////////////////////////////////////////////////////////////////////////
353 #define xstr(s) stringify(s)
354 #define stringify(s) #s
356 using namespace ARDOUR;
359 LuaInstance::register_hooks (lua_State* L)
362 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
363 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
364 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
365 luabridge::getGlobalNamespace (L)
366 .beginNamespace ("LuaSignal")
367 # include "luasignal_syms.h"
373 luabridge::getGlobalNamespace (L)
374 .beginNamespace ("LuaSignal")
375 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
381 LuaInstance::bind_cairo (lua_State* L)
383 /* std::vector<double> for set_dash()
384 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
386 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
387 * the address of the one in libardour.dll is mapped when loading the .dll
389 * see LuaBindings::set_session() for a detailed explanation
391 luabridge::getGlobalNamespace (L)
392 .beginNamespace ("C")
393 .beginStdVector <double> ("DoubleVector")
397 luabridge::getGlobalNamespace (L)
398 .beginNamespace ("Cairo")
399 .beginClass <Cairo::Context> ("Context")
400 .addFunction ("save", &Cairo::Context::save)
401 .addFunction ("restore", &Cairo::Context::restore)
402 .addFunction ("set_operator", &Cairo::Context::set_operator)
403 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
404 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
405 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
406 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
407 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
408 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
409 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
410 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
411 .addFunction ("translate", &Cairo::Context::translate)
412 .addFunction ("scale", &Cairo::Context::scale)
413 .addFunction ("rotate", &Cairo::Context::rotate)
414 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
415 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
416 .addFunction ("move_to", &Cairo::Context::move_to)
417 .addFunction ("line_to", &Cairo::Context::line_to)
418 .addFunction ("curve_to", &Cairo::Context::curve_to)
419 .addFunction ("arc", &Cairo::Context::arc)
420 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
421 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
422 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
423 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
424 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
425 .addFunction ("close_path", &Cairo::Context::close_path)
426 .addFunction ("paint", &Cairo::Context::paint)
427 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
428 .addFunction ("stroke", &Cairo::Context::stroke)
429 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
430 .addFunction ("fill", &Cairo::Context::fill)
431 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
432 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
433 .addFunction ("clip", &Cairo::Context::clip)
434 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
435 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
436 .addFunction ("show_text", &Cairo::Context::show_text)
439 // LineCap, LineJoin, Operator
440 .beginNamespace ("LineCap")
441 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
442 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
443 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
446 .beginNamespace ("LineJoin")
447 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
448 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
449 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
452 .beginNamespace ("Operator")
453 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
454 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
455 .addConst ("Over", CAIRO_OPERATOR_OVER)
456 .addConst ("Add", CAIRO_OPERATOR_ADD)
459 .beginNamespace ("Format")
460 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
461 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
464 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
465 .addConstructor <void (*) (Cairo::Format, int, int)> ()
466 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
467 .addFunction ("context", &LuaCairo::ImageSurface::context)
468 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
469 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
470 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
471 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
474 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
475 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
476 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
477 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
478 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
479 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
480 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
481 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
482 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
483 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
484 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
485 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
486 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
487 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
491 .beginNamespace ("EllipsizeMode")
492 .addConst ("None", Pango::ELLIPSIZE_NONE)
493 .addConst ("Start", Pango::ELLIPSIZE_START)
494 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
495 .addConst ("End", Pango::ELLIPSIZE_END)
498 .beginNamespace ("WrapMode")
499 .addConst ("Word", Pango::WRAP_WORD)
500 .addConst ("Char", Pango::WRAP_CHAR)
501 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
506 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
507 one can work around this as follows:
510 LuaInstance::register_classes (lua.getState());
512 "function render (ctx)"
513 " ctx:rectangle (0, 0, 100, 100)"
514 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
519 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
520 Cairo::Context ctx (context->cobj ());
522 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
523 lua_render ((Cairo::Context *)&ctx);
530 LuaInstance::register_classes (lua_State* L)
532 LuaBindings::stddef (L);
533 LuaBindings::common (L);
534 LuaBindings::session (L);
535 LuaBindings::osc (L);
540 luabridge::getGlobalNamespace (L)
541 .beginNamespace ("ArdourUI")
543 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
545 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
548 .beginClass <ArdourMarker> ("ArdourMarker")
549 .addFunction ("name", &ArdourMarker::name)
550 .addFunction ("position", &ArdourMarker::position)
551 .addFunction ("_type", &ArdourMarker::type)
555 .beginClass <AxisView> ("AxisView")
557 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
559 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
563 .beginClass <RegionSelection> ("RegionSelection")
564 .addFunction ("clear_all", &RegionSelection::clear_all)
565 .addFunction ("start", &RegionSelection::start)
566 .addFunction ("end_frame", &RegionSelection::end_frame)
567 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
568 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
571 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
572 .addFunction ("start", &TimeSelection::start)
573 .addFunction ("end_frame", &TimeSelection::end_frame)
574 .addFunction ("length", &TimeSelection::length)
577 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
580 .beginClass <TrackViewList> ("TrackViewList")
581 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
584 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
587 .beginClass <Selection> ("Selection")
588 .addFunction ("clear", &Selection::clear)
589 .addFunction ("clear_all", &Selection::clear_all)
590 .addFunction ("empty", &Selection::empty)
591 .addData ("tracks", &Selection::tracks)
592 .addData ("regions", &Selection::regions)
593 .addData ("time", &Selection::time)
594 .addData ("markers", &Selection::markers)
596 .addData ("lines", &Selection::lines)
597 .addData ("playlists", &Selection::playlists)
598 .addData ("points", &Selection::points)
599 .addData ("midi_regions", &Selection::midi_regions)
600 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
604 .beginClass <PublicEditor> ("Editor")
605 .addFunction ("snap_type", &PublicEditor::snap_type)
606 .addFunction ("snap_mode", &PublicEditor::snap_mode)
607 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
608 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
610 .addFunction ("undo", &PublicEditor::undo)
611 .addFunction ("redo", &PublicEditor::redo)
613 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
614 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
616 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
618 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
619 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
620 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
621 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
623 .addFunction ("get_selection", &PublicEditor::get_selection)
624 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
625 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
627 .addFunction ("play_selection", &PublicEditor::play_selection)
628 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
629 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
630 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
632 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
633 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
635 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
636 .addFunction ("show_measures", &PublicEditor::show_measures)
637 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
639 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
640 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
642 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
644 .addRefFunction ("do_import", &PublicEditor::do_import)
645 .addRefFunction ("do_embed", &PublicEditor::do_embed)
647 .addFunction ("export_audio", &PublicEditor::export_audio)
648 .addFunction ("stem_export", &PublicEditor::stem_export)
649 .addFunction ("export_selection", &PublicEditor::export_selection)
650 .addFunction ("export_range", &PublicEditor::export_range)
652 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
653 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
654 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
655 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
657 #if 0 // These need TimeAxisView* which isn't exposed, yet
658 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
659 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
660 .addFunction ("new_playlists", &PublicEditor::new_playlists)
661 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
662 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
665 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
666 .addFunction ("deselect_all", &PublicEditor::deselect_all)
668 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
669 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
670 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
672 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
673 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
674 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
675 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
677 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
678 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
679 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
680 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
681 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
682 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
683 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
685 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
686 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
687 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
688 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
690 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
691 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
692 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
694 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
696 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
697 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
698 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
700 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
701 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
703 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
704 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
705 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
706 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
708 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
709 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
710 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
711 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
714 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
715 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
717 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
718 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
719 .addFunction ("get_track_views", &PublicEditor::get_track_views)
720 .addFunction ("drags", &PublicEditor::drags)
723 .addFunction ("center_screen", &PublicEditor::center_screen)
725 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
726 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
728 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
729 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
730 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
732 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
733 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
734 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
735 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
736 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
740 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
741 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
742 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
743 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
746 .addFunction ("access_action", &PublicEditor::access_action)
750 .beginNamespace ("MarkerType")
751 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
752 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
753 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
754 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
755 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
756 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
757 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
758 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
759 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
760 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
761 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
764 .endNamespace (); // end ArdourUI
772 #undef DISPLAYCONTROL
774 #undef IMPORTPOSITION
775 #undef IMPORTDISPOSITION
777 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
778 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
779 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
780 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
781 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
782 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
783 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
784 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
785 luabridge::getGlobalNamespace (L)
786 .beginNamespace ("Editing")
787 # include "editing_syms.h"
794 ////////////////////////////////////////////////////////////////////////////////
796 using namespace ARDOUR;
797 using namespace ARDOUR_UI_UTILS;
802 static void _lua_print (std::string s) {
803 std::cout << "LuaInstance: " << s << "\n";
807 LuaInstance* LuaInstance::_instance = 0;
810 LuaInstance::instance ()
813 _instance = new LuaInstance;
819 LuaInstance::LuaInstance ()
822 lua.Print.connect (&_lua_print);
826 LuaScriptParamList args;
829 LuaInstance::~LuaInstance ()
831 delete _lua_call_action;
832 delete _lua_add_action;
833 delete _lua_del_action;
834 delete _lua_get_action;
846 "function ScriptManager ()"
847 " local self = { scripts = {}, instances = {} }"
849 " local remove = function (id)"
850 " self.scripts[id] = nil"
851 " self.instances[id] = nil"
854 " local addinternal = function (i, n, s, f, a)"
855 " assert(type(i) == 'number', 'id must be numeric')"
856 " assert(type(n) == 'string', 'Name must be string')"
857 " assert(type(s) == 'string', 'Script must be string')"
858 " assert(type(f) == 'function', 'Factory is a not a function')"
859 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
860 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
861 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
862 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
865 " local call = function (id)"
866 " if type(self.instances[id]) == 'function' then"
867 " local status, err = pcall (self.instances[id])"
868 " if not status then"
869 " print ('action \"'.. id .. '\": ', err)" // error out
876 " local add = function (i, n, s, b, a)"
877 " assert(type(b) == 'string', 'ByteCode must be string')"
878 " load (b)()" // assigns f
879 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
880 " addinternal (i, n, s, load(f), a)"
883 " local get = function (id)"
884 " if type(self.scripts[id]) == 'table' then"
885 " return { ['name'] = self.scripts[id]['n'],"
886 " ['script'] = self.scripts[id]['s'],"
887 " ['args'] = self.scripts[id]['a'] }"
892 " local function basic_serialize (o)"
893 " if type(o) == \"number\" then"
894 " return tostring(o)"
896 " return string.format(\"%q\", o)"
900 " local function serialize (name, value)"
901 " local rv = name .. ' = '"
903 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
904 " return rv .. basic_serialize(value) .. ' '"
905 " elseif type(value) == \"table\" then"
907 " for k,v in pairs(value) do"
908 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
909 " rv = rv .. serialize(fieldname, v) .. ' '"
910 " collectgarbage()" // string concatenation allocates a new string
913 " elseif type(value) == \"function\" then"
914 " return rv .. string.format(\"%q\", string.dump(value, true))"
916 " error('cannot save a ' .. type(value))"
921 " local save = function ()"
922 " return (serialize('scripts', self.scripts))"
925 " local clear = function ()"
927 " self.instances = {}"
931 " local restore = function (state)"
934 " for i, s in pairs (scripts) do"
935 " addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
940 " return { call = call, add = add, remove = remove, get = get,"
941 " restore = restore, save = save, clear = clear}"
944 " manager = ScriptManager ()"
945 " ScriptManager = nil"
948 lua_State* L = lua.getState();
951 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
952 lua.do_command ("manager = nil"); // hide it.
953 lua.do_command ("collectgarbage()");
955 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
956 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
957 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
958 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
959 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
960 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
961 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
963 } catch (luabridge::LuaException const& e) {
964 fatal << string_compose (_("programming error: %1"),
965 X_("Failed to setup Lua action interpreter"))
967 abort(); /*NOTREACHED*/
970 register_classes (L);
972 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
973 lua_setglobal (L, "Editor");
976 void LuaInstance::set_session (Session* s)
978 SessionHandlePtr::set_session (s);
983 lua_State* L = lua.getState();
984 LuaBindings::set_session (L, _session);
986 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
987 i->second->set_session (s);
992 LuaInstance::session_going_away ()
994 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
996 for (int i = 0; i < 9; ++i) {
997 ActionChanged (i, ""); /* EMIT SIGNAL */
999 SessionHandlePtr::session_going_away ();
1002 lua_State* L = lua.getState();
1003 LuaBindings::set_session (L, _session);
1004 lua.do_command ("collectgarbage();");
1008 LuaInstance::set_state (const XMLNode& node)
1013 if ((child = find_named_node (node, "ActionScript"))) {
1014 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1015 if (!(*n)->is_content ()) { continue; }
1017 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1019 (*_lua_load)(std::string ((const char*)buf, size));
1020 } catch (luabridge::LuaException const& e) {
1021 cerr << "LuaException:" << e.what () << endl;
1023 for (int i = 0; i < 9; ++i) {
1025 if (lua_action_name (i, name)) {
1026 ActionChanged (i, name); /* EMIT SIGNAL */
1033 if ((child = find_named_node (node, "ActionHooks"))) {
1034 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1036 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1037 _callbacks.insert (std::make_pair(p->id(), p));
1038 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1039 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1040 } catch (luabridge::LuaException const& e) {
1041 cerr << "LuaException:" << e.what () << endl;
1050 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1053 std::vector<std::string> reg;
1056 case LuaScriptInfo::EditorAction:
1057 reg = lua_action_names ();
1058 title = "Add Lua Action";
1060 case LuaScriptInfo::EditorHook:
1061 reg = lua_slot_names ();
1062 title = "Add Lua Callback Hook";
1068 LuaScriptInfoPtr spi;
1069 ScriptSelector ss (title, type);
1070 switch (ss.run ()) {
1071 case Gtk::RESPONSE_ACCEPT:
1079 std::string script = "";
1082 script = Glib::file_get_contents (spi->path);
1083 } catch (Glib::FileError e) {
1084 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1085 Gtk::MessageDialog am (msg);
1090 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, "action_params");
1092 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1093 switch (spd.run ()) {
1094 case Gtk::RESPONSE_ACCEPT:
1101 case LuaScriptInfo::EditorAction:
1102 return set_lua_action (id, spd.name(), script, lsp);
1104 case LuaScriptInfo::EditorHook:
1105 return register_lua_slot (spd.name(), script, lsp);
1114 LuaInstance::get_action_state ()
1119 luabridge::LuaRef savedstate ((*_lua_save)());
1120 saved = savedstate.cast<std::string>();
1122 lua.collect_garbage ();
1124 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1125 std::string b64s (b64);
1128 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1129 script_node->add_property (X_("lua"), LUA_VERSION);
1130 script_node->add_content (b64s);
1132 return *script_node;
1136 LuaInstance::get_hook_state ()
1138 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1139 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1140 script_node->add_child_nocopy (i->second->get_state ());
1142 return *script_node;
1146 LuaInstance::call_action (const int id)
1149 (*_lua_call_action)(id + 1);
1150 lua.collect_garbage_step ();
1151 } catch (luabridge::LuaException const& e) {
1152 cerr << "LuaException:" << e.what () << endl;
1157 LuaInstance::set_lua_action (
1159 const std::string& name,
1160 const std::string& script,
1161 const LuaScriptParamList& args)
1164 lua_State* L = lua.getState();
1165 // get bytcode of factory-function in a sandbox
1166 // (don't allow scripts to interfere)
1167 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1168 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1169 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1170 if ((*i)->optional && !(*i)->is_set) { continue; }
1171 tbl_arg[(*i)->name] = (*i)->value;
1173 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
1174 ActionChanged (id, name); /* EMIT SIGNAL */
1175 } catch (luabridge::LuaException const& e) {
1176 cerr << "LuaException:" << e.what () << endl;
1183 LuaInstance::remove_lua_action (const int id)
1186 (*_lua_del_action)(id + 1);
1187 } catch (luabridge::LuaException const& e) {
1188 cerr << "LuaException:" << e.what () << endl;
1191 ActionChanged (id, ""); /* EMIT SIGNAL */
1196 LuaInstance::lua_action_name (const int id, std::string& rv)
1199 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1203 if (ref["name"].isString()) {
1204 rv = ref["name"].cast<std::string>();
1208 } catch (luabridge::LuaException const& e) {
1209 cerr << "LuaException:" << e.what () << endl;
1215 std::vector<std::string>
1216 LuaInstance::lua_action_names ()
1218 std::vector<std::string> rv;
1219 for (int i = 0; i < 9; ++i) {
1221 if (lua_action_name (i, name)) {
1222 rv.push_back (name);
1229 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1232 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1236 if (!ref["name"].isString()) {
1239 if (!ref["script"].isString()) {
1242 if (!ref["args"].isTable()) {
1245 name = ref["name"].cast<std::string>();
1246 script = ref["script"].cast<std::string>();
1249 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1253 args = LuaScriptParams::script_params (lsi, "action_params");
1254 luabridge::LuaRef rargs (ref["args"]);
1255 LuaScriptParams::ref_to_params (args, &rargs);
1257 } catch (luabridge::LuaException const& e) {
1258 cerr << "LuaException:" << e.what () << endl;
1265 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1267 /* parse script, get ActionHook(s) from script */
1272 l.Print.connect (&_lua_print);
1274 lua_State* L = l.getState();
1276 l.do_command ("function ardour () end");
1277 l.do_command (script);
1278 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1279 if (signals.isFunction()) {
1282 } catch (luabridge::LuaException const& e) {
1283 cerr << "LuaException:" << e.what () << endl;
1287 cerr << "Script registered no hooks." << endl;
1291 /* register script w/args, get entry-point / ID */
1294 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1295 _callbacks.insert (std::make_pair(p->id(), p));
1296 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1297 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1299 } catch (luabridge::LuaException const& e) {
1300 cerr << "LuaException:" << e.what () << endl;
1306 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1308 LuaCallbackMap::iterator i = _callbacks.find (id);
1309 if (i != _callbacks.end()) {
1310 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1311 _callbacks.erase (i);
1317 std::vector<PBD::ID>
1318 LuaInstance::lua_slots () const
1320 std::vector<PBD::ID> rv;
1321 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1322 rv.push_back (i->first);
1328 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1330 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1331 if (i != _callbacks.end()) {
1332 name = i->second->name();
1338 std::vector<std::string>
1339 LuaInstance::lua_slot_names () const
1341 std::vector<std::string> rv;
1342 std::vector<PBD::ID> ids = lua_slots();
1343 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1345 if (lua_slot_name (*i, name)) {
1346 rv.push_back (name);
1353 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1355 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1356 if (i == _callbacks.end()) {
1357 return false; // error
1359 return i->second->lua_slot (name, script, ah, args);
1362 ///////////////////////////////////////////////////////////////////////////////
1364 LuaCallback::LuaCallback (Session *s,
1365 const std::string& name,
1366 const std::string& script,
1367 const ActionHook& ah,
1368 const ARDOUR::LuaScriptParamList& args)
1369 : SessionHandlePtr (s)
1374 // TODO: allow to reference object (e.g region)
1377 lua_State* L = lua.getState();
1378 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1379 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1380 if ((*i)->optional && !(*i)->is_set) { continue; }
1381 tbl_arg[(*i)->name] = (*i)->value;
1385 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1386 (*_lua_add)(name, script, bytecode, tbl_arg);
1387 } catch (luabridge::LuaException const& e) {
1388 cerr << "LuaException:" << e.what () << endl;
1389 throw failed_constructor ();
1396 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1397 : SessionHandlePtr (s)
1399 XMLNode* child = NULL;
1400 if (node.name() != X_("LuaCallback")
1401 || !node.property ("signals")
1402 || !node.property ("id")
1403 || !node.property ("name")) {
1404 throw failed_constructor ();
1407 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1408 if (!(*n)->is_content ()) { continue; }
1413 throw failed_constructor ();
1418 _id = PBD::ID (node.property ("id")->value ());
1419 _name = node.property ("name")->value ();
1420 _signals = ActionHook (node.property ("signals")->value ());
1423 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1425 (*_lua_load)(std::string ((const char*)buf, size));
1426 } catch (luabridge::LuaException const& e) {
1427 cerr << "LuaException:" << e.what () << endl;
1434 LuaCallback::~LuaCallback ()
1444 LuaCallback::get_state (void)
1448 luabridge::LuaRef savedstate ((*_lua_save)());
1449 saved = savedstate.cast<std::string>();
1451 lua.collect_garbage ();
1453 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1454 std::string b64s (b64);
1457 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1458 script_node->add_property (X_("lua"), LUA_VERSION);
1459 script_node->add_property (X_("id"), _id.to_s ());
1460 script_node->add_property (X_("name"), _name);
1461 script_node->add_property (X_("signals"), _signals.to_string ());
1462 script_node->add_content (b64s);
1463 return *script_node;
1467 LuaCallback::init (void)
1470 lua.Print.connect (&_lua_print);
1474 "function ScriptManager ()"
1475 " local self = { script = {}, instance = {} }"
1477 " local addinternal = function (n, s, f, a)"
1478 " assert(type(n) == 'string', 'Name must be string')"
1479 " assert(type(s) == 'string', 'Script must be string')"
1480 " assert(type(f) == 'function', 'Factory is a not a function')"
1481 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1482 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1483 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1484 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1487 " local call = function (...)"
1488 " if type(self.instance) == 'function' then"
1489 " local status, err = pcall (self.instance, ...)"
1490 " if not status then"
1491 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1492 " self.script = nil"
1493 " self.instance = nil"
1501 " local add = function (n, s, b, a)"
1502 " assert(type(b) == 'string', 'ByteCode must be string')"
1503 " load (b)()" // assigns f
1504 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1505 " addinternal (n, s, load(f), a)"
1508 " local get = function ()"
1509 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1510 " return { ['name'] = self.script['n'],"
1511 " ['script'] = self.script['s'],"
1512 " ['args'] = self.script['a'] }"
1519 " local function basic_serialize (o)"
1520 " if type(o) == \"number\" then"
1521 " return tostring(o)"
1523 " return string.format(\"%q\", o)"
1527 " local function serialize (name, value)"
1528 " local rv = name .. ' = '"
1530 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1531 " return rv .. basic_serialize(value) .. ' '"
1532 " elseif type(value) == \"table\" then"
1534 " for k,v in pairs(value) do"
1535 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1536 " rv = rv .. serialize(fieldname, v) .. ' '"
1537 " collectgarbage()" // string concatenation allocates a new string
1540 " elseif type(value) == \"function\" then"
1541 " return rv .. string.format(\"%q\", string.dump(value, true))"
1543 " error('cannot save a ' .. type(value))"
1549 " local save = function ()"
1550 " return (serialize('s', self.script))"
1553 " local restore = function (state)"
1556 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1559 " return { call = call, add = add, get = get,"
1560 " restore = restore, save = save}"
1563 " manager = ScriptManager ()"
1564 " ScriptManager = nil"
1567 lua_State* L = lua.getState();
1570 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1571 lua.do_command ("manager = nil"); // hide it.
1572 lua.do_command ("collectgarbage()");
1574 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1575 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1576 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1577 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1578 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1580 } catch (luabridge::LuaException const& e) {
1581 fatal << string_compose (_("programming error: %1"),
1582 X_("Failed to setup Lua callback interpreter"))
1584 abort(); /*NOTREACHED*/
1587 LuaInstance::register_classes (L);
1589 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1590 lua_setglobal (L, "Editor");
1594 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1596 // TODO consolidate w/ LuaInstance::lua_action()
1598 luabridge::LuaRef ref = (*_lua_get)();
1602 if (!ref["name"].isString()) {
1605 if (!ref["script"].isString()) {
1608 if (!ref["args"].isTable()) {
1613 name = ref["name"].cast<std::string> ();
1614 script = ref["script"].cast<std::string> ();
1617 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1621 args = LuaScriptParams::script_params (lsi, "action_params");
1622 luabridge::LuaRef rargs (ref["args"]);
1623 LuaScriptParams::ref_to_params (args, &rargs);
1625 } catch (luabridge::LuaException const& e) {
1626 cerr << "LuaException:" << e.what () << endl;
1633 LuaCallback::set_session (ARDOUR::Session *s)
1635 SessionHandlePtr::set_session (s);
1638 lua_State* L = lua.getState();
1639 LuaBindings::set_session (L, _session);
1646 LuaCallback::session_going_away ()
1648 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1649 lua.do_command ("collectgarbage();");
1651 SessionHandlePtr::session_going_away ();
1654 drop_callback (); /* EMIT SIGNAL */
1658 LuaCallback::reconnect ()
1660 _connections.drop_connections ();
1661 if ((*_lua_get) ().isNil ()) {
1662 drop_callback (); /* EMIT SIGNAL */
1666 // TODO pass object which emits the signal (e.g region)
1668 // save/load bound objects will be tricky.
1669 // Best idea so far is to save/lookup the PBD::ID
1670 // (either use boost::any indirection or templates for bindable
1671 // object types or a switch statement..)
1673 // _session->route_by_id ()
1674 // _session->track_by_diskstream_id ()
1675 // _session->source_by_id ()
1676 // _session->controllable_by_id ()
1677 // _session->processor_by_id ()
1678 // RegionFactory::region_by_id ()
1680 // TODO loop over objects (if any)
1682 reconnect_object ((void*)0);
1685 template <class T> void
1686 LuaCallback::reconnect_object (T obj)
1688 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1690 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1691 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1692 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1694 # include "luasignal_syms.h"
1696 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1697 abort(); /*NOTREACHED*/
1706 template <typename T, typename S> void
1707 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1709 _connections, invalidator (*this),
1710 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1714 template <typename T, typename C1> void
1715 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1717 _connections, invalidator (*this),
1718 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1722 template <typename T, typename C1, typename C2> void
1723 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1725 _connections, invalidator (*this),
1726 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1730 template <typename T> void
1731 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1734 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1735 if (! rv.cast<bool> ()) {
1739 /* destroy LuaRef ^^ first before calling drop_callback() */
1741 drop_callback (); /* EMIT SIGNAL */
1745 template <typename T, typename C1> void
1746 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1749 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1750 if (! rv.cast<bool> ()) {
1755 drop_callback (); /* EMIT SIGNAL */
1759 template <typename T, typename C1, typename C2> void
1760 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1763 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1764 if (! rv.cast<bool> ()) {
1769 drop_callback (); /* EMIT SIGNAL */