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_ui.h"
34 #include "public_editor.h"
35 #include "region_selection.h"
36 #include "luainstance.h"
37 #include "luasignal.h"
39 #include "time_axis_view.h"
40 #include "selection.h"
41 #include "script_selector.h"
42 #include "utils_videotl.h"
47 /** wrap RefPtr< Cairo::ImageSurface >
49 * Image surfaces provide the ability to render to memory buffers either
50 * allocated by cairo or by the calling code. The supported image formats are
51 * those defined in Cairo::Format.
56 * Creates an image surface of the specified format and dimensions. Initially
57 * the surface contents are all 0. (Specifically, within each pixel, each
58 * color or alpha channel belonging to format will be 0. The contents of bits
59 * within a pixel, but not belonging to the given format are undefined).
61 * @param format format of pixels in the surface to create
62 * @param width width of the surface, in pixels
63 * @param height height of the surface, in pixels
65 ImageSurface (Cairo::Format format, int width, int height)
66 : _surface (Cairo::ImageSurface::create (format, width, height))
67 , _ctx (Cairo::Context::create (_surface))
68 , ctx (_ctx->cobj ()) {}
73 * Set this surface as source for another context.
74 * This allows to draw this surface
76 void set_as_source (Cairo::Context* c, int x, int y) {
78 c->set_source (_surface, x, y);
82 * Returns a context object to perform operations on the surface
84 Cairo::Context* context () {
85 return (Cairo::Context *)&ctx;
89 * Returns the stride of the image surface in bytes (or 0 if surface is not
90 * an image surface). The stride is the distance in bytes from the beginning
91 * of one row of the image data to the beginning of the next row.
93 int get_stride () const {
94 return _surface->get_stride ();
97 /** Gets the width of the ImageSurface in pixels */
98 int get_width () const {
99 return _surface->get_width ();
102 /** Gets the height of the ImageSurface in pixels */
103 int get_height () const {
104 return _surface->get_height ();
108 * Get a pointer to the data of the image surface, for direct
109 * inspection or modification.
111 * Return value: a pointer to the image data of this surface or NULL
112 * if @surface is not an image surface.
115 unsigned char* get_data () {
116 return _surface->get_data ();
119 /** Tells cairo to consider the data buffer dirty.
121 * In particular, if you've created an ImageSurface with a data buffer that
122 * you've allocated yourself and you draw to that data buffer using means
123 * other than cairo, you must call mark_dirty() before doing any additional
124 * drawing to that surface with cairo.
126 * Note that if you do draw to the Surface outside of cairo, you must call
127 * flush() before doing the drawing.
130 _surface->mark_dirty ();
133 /** Marks a rectangular area of the given surface dirty.
135 * @param x X coordinate of dirty rectangle
136 * @param y Y coordinate of dirty rectangle
137 * @param width width of dirty rectangle
138 * @param height height of dirty rectangle
140 void mark_dirty (int x, int y, int width, int height) {
141 _surface->mark_dirty (x, y, width, height);
145 Cairo::RefPtr<Cairo::ImageSurface> _surface;
146 Cairo::RefPtr<Cairo::Context> _ctx;
152 /** Create a new PangoLayout Text Display
153 * @param c CairoContext for the layout
154 * @param font_name a font-description e.g. "Mono 8px"
156 PangoLayout (Cairo::Context* c, std::string font_name) {
157 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
158 _layout = Glib::wrap (pl);
159 Pango::FontDescription fd (font_name);
160 _layout->set_font_description (fd);
165 /** Gets the text in the layout. The returned text should not
166 * be freed or modified.
168 * @return The text in the @a layout.
170 std::string get_text () const {
171 return _layout->get_text ();
173 /** Set the text of the layout.
174 * @param text The text for the layout.
176 void set_text (const std::string& text) {
177 _layout->set_text (text);
180 /** Sets the layout text and attribute list from marked-up text (see markup format).
181 * Replaces the current text and attribute list.
182 * @param markup Some marked-up text.
184 void set_markup (const std::string& markup) {
185 _layout->set_markup (markup);
188 /** Sets the width to which the lines of the Pango::Layout should wrap or
189 * ellipsized. The default value is -1: no width set.
191 * @param width The desired width in Pango units, or -1 to indicate that no
192 * wrapping or ellipsization should be performed.
194 void set_width (int width) {
195 _layout->set_width (width * PANGO_SCALE);
198 /** Gets the width to which the lines of the Pango::Layout should wrap.
200 * @return The width in Pango units, or -1 if no width set.
202 int get_width () const {
203 return _layout->get_width () / PANGO_SCALE;
206 /** Sets the type of ellipsization being performed for @a layout.
207 * Depending on the ellipsization mode @a ellipsize text is
208 * removed from the start, middle, or end of text so they
209 * fit within the width and height of layout set with
210 * set_width() and set_height().
212 * If the layout contains characters such as newlines that
213 * force it to be layed out in multiple paragraphs, then whether
214 * each paragraph is ellipsized separately or the entire layout
215 * is ellipsized as a whole depends on the set height of the layout.
216 * See set_height() for details.
218 * @param ellipsize The new ellipsization mode for @a layout.
220 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
221 _layout->set_ellipsize (ellipsize);
224 /** Gets the type of ellipsization being performed for @a layout.
225 * See set_ellipsize()
227 * @return The current ellipsization mode for @a layout.
229 * Use is_ellipsized() to query whether any paragraphs
230 * were actually ellipsized.
232 Pango::EllipsizeMode get_ellipsize () const {
233 return _layout->get_ellipsize ();
236 /** Queries whether the layout had to ellipsize any paragraphs.
238 * This returns <tt>true</tt> if the ellipsization mode for @a layout
239 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
240 * and there are paragraphs exceeding that width that have to be
243 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
246 bool is_ellipsized () const {
247 return _layout->is_ellipsized ();
250 /** Sets the wrap mode; the wrap mode only has effect if a width
251 * is set on the layout with set_width().
252 * To turn off wrapping, set the width to -1.
254 * @param wrap The wrap mode.
256 void set_wrap (Pango::WrapMode wrap) {
257 _layout->set_width (wrap);
260 /** Gets the wrap mode for the layout.
262 * Use is_wrapped() to query whether any paragraphs
263 * were actually wrapped.
265 * @return Active wrap mode.
267 Pango::WrapMode get_wrap () const {
268 return _layout->get_wrap ();
271 /** Queries whether the layout had to wrap any paragraphs.
273 * This returns <tt>true</tt> if a positive width is set on @a layout,
274 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
275 * and there are paragraphs exceeding the layout width that have
278 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
281 bool is_wrapped () const {
282 return _layout->is_wrapped ();
285 /** Determines the logical width and height of a Pango::Layout
288 int get_pixel_size (lua_State *L) {
290 _layout->get_pixel_size (width, height);
291 luabridge::Stack<int>::push (L, width);
292 luabridge::Stack<int>::push (L, height);
297 /** Draws a Layout in the specified Cairo @a context. The top-left
298 * corner of the Layout will be drawn at the current point of the
301 * @param context A Cairo context.
303 void show_in_cairo_context (Cairo::Context* c) {
304 pango_cairo_update_layout (c->cobj (), _layout->gobj());
305 pango_cairo_show_layout (c->cobj (), _layout->gobj());
309 Glib::RefPtr<Pango::Layout> _layout;
314 ////////////////////////////////////////////////////////////////////////////////
316 namespace LuaSignal {
318 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
319 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
320 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
323 str2luasignal (const std::string &str) {
324 const char* type = str.c_str();
326 # include "luasignal_syms.h"
328 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
329 abort(); /*NOTREACHED*/
336 #define STATIC(name,c,p) N_(#name),
337 #define SESSION(name,c,p) N_(#name),
338 #define ENGINE(name,c,p) N_(#name),
339 const char *luasignalstr[] = {
340 # include "luasignal_syms.h"
350 std::string lua_http_get (const char *u) {
351 char *rv = a3_curl_http_get (u, NULL);
360 ////////////////////////////////////////////////////////////////////////////////
362 #define xstr(s) stringify(s)
363 #define stringify(s) #s
365 using namespace ARDOUR;
368 LuaInstance::register_hooks (lua_State* L)
371 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
372 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
373 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
374 luabridge::getGlobalNamespace (L)
375 .beginNamespace ("LuaSignal")
376 # include "luasignal_syms.h"
382 luabridge::getGlobalNamespace (L)
383 .beginNamespace ("LuaSignal")
384 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
390 LuaInstance::bind_cairo (lua_State* L)
392 /* std::vector<double> for set_dash()
393 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
395 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
396 * the address of the one in libardour.dll is mapped when loading the .dll
398 * see LuaBindings::set_session() for a detailed explanation
400 luabridge::getGlobalNamespace (L)
401 .beginNamespace ("C")
402 .beginStdVector <double> ("DoubleVector")
406 luabridge::getGlobalNamespace (L)
407 .beginNamespace ("Cairo")
408 .beginClass <Cairo::Context> ("Context")
409 .addFunction ("save", &Cairo::Context::save)
410 .addFunction ("restore", &Cairo::Context::restore)
411 .addFunction ("set_operator", &Cairo::Context::set_operator)
412 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
413 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
414 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
415 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
416 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
417 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
418 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
419 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
420 .addFunction ("translate", &Cairo::Context::translate)
421 .addFunction ("scale", &Cairo::Context::scale)
422 .addFunction ("rotate", &Cairo::Context::rotate)
423 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
424 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
425 .addFunction ("move_to", &Cairo::Context::move_to)
426 .addFunction ("line_to", &Cairo::Context::line_to)
427 .addFunction ("curve_to", &Cairo::Context::curve_to)
428 .addFunction ("arc", &Cairo::Context::arc)
429 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
430 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
431 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
432 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
433 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
434 .addFunction ("close_path", &Cairo::Context::close_path)
435 .addFunction ("paint", &Cairo::Context::paint)
436 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
437 .addFunction ("stroke", &Cairo::Context::stroke)
438 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
439 .addFunction ("fill", &Cairo::Context::fill)
440 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
441 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
442 .addFunction ("clip", &Cairo::Context::clip)
443 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
444 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
445 .addFunction ("show_text", &Cairo::Context::show_text)
448 // LineCap, LineJoin, Operator
449 .beginNamespace ("LineCap")
450 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
451 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
452 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
455 .beginNamespace ("LineJoin")
456 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
457 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
458 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
461 .beginNamespace ("Operator")
462 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
463 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
464 .addConst ("Over", CAIRO_OPERATOR_OVER)
465 .addConst ("Add", CAIRO_OPERATOR_ADD)
468 .beginNamespace ("Format")
469 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
470 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
473 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
474 .addConstructor <void (*) (Cairo::Format, int, int)> ()
475 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
476 .addFunction ("context", &LuaCairo::ImageSurface::context)
477 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
478 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
479 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
480 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
483 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
484 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
485 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
486 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
487 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
488 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
489 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
490 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
491 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
492 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
493 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
494 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
495 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
496 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
500 .beginNamespace ("EllipsizeMode")
501 .addConst ("None", Pango::ELLIPSIZE_NONE)
502 .addConst ("Start", Pango::ELLIPSIZE_START)
503 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
504 .addConst ("End", Pango::ELLIPSIZE_END)
507 .beginNamespace ("WrapMode")
508 .addConst ("Word", Pango::WRAP_WORD)
509 .addConst ("Char", Pango::WRAP_CHAR)
510 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
515 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
516 one can work around this as follows:
519 LuaInstance::register_classes (lua.getState());
521 "function render (ctx)"
522 " ctx:rectangle (0, 0, 100, 100)"
523 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
528 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
529 Cairo::Context ctx (context->cobj ());
531 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
532 lua_render ((Cairo::Context *)&ctx);
539 LuaInstance::register_classes (lua_State* L)
541 LuaBindings::stddef (L);
542 LuaBindings::common (L);
543 LuaBindings::session (L);
544 LuaBindings::osc (L);
549 luabridge::getGlobalNamespace (L)
550 .beginNamespace ("ArdourUI")
552 .addFunction ("curl_http_get", &lua_http_get)
554 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
557 .beginClass <ArdourMarker> ("ArdourMarker")
558 .addFunction ("name", &ArdourMarker::name)
559 .addFunction ("position", &ArdourMarker::position)
560 .addFunction ("_type", &ArdourMarker::type)
564 .beginClass <AxisView> ("AxisView")
566 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
568 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
572 .beginClass <RegionSelection> ("RegionSelection")
573 .addFunction ("clear_all", &RegionSelection::clear_all)
574 .addFunction ("start", &RegionSelection::start)
575 .addFunction ("end_frame", &RegionSelection::end_frame)
576 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
577 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
580 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
581 .addFunction ("start", &TimeSelection::start)
582 .addFunction ("end_frame", &TimeSelection::end_frame)
583 .addFunction ("length", &TimeSelection::length)
586 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
589 .beginClass <TrackViewList> ("TrackViewList")
590 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
593 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
596 .beginClass <Selection> ("Selection")
597 .addFunction ("clear", &Selection::clear)
598 .addFunction ("clear_all", &Selection::clear_all)
599 .addFunction ("empty", &Selection::empty)
600 .addData ("tracks", &Selection::tracks)
601 .addData ("regions", &Selection::regions)
602 .addData ("time", &Selection::time)
603 .addData ("markers", &Selection::markers)
605 .addData ("lines", &Selection::lines)
606 .addData ("playlists", &Selection::playlists)
607 .addData ("points", &Selection::points)
608 .addData ("midi_regions", &Selection::midi_regions)
609 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
613 .beginClass <PublicEditor> ("Editor")
614 .addFunction ("snap_type", &PublicEditor::snap_type)
615 .addFunction ("snap_mode", &PublicEditor::snap_mode)
616 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
617 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
619 .addFunction ("undo", &PublicEditor::undo)
620 .addFunction ("redo", &PublicEditor::redo)
622 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
623 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
625 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
627 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
628 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
629 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
630 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
632 .addFunction ("get_selection", &PublicEditor::get_selection)
633 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
634 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
636 .addFunction ("play_selection", &PublicEditor::play_selection)
637 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
638 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
639 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
641 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
642 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
644 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
645 .addFunction ("show_measures", &PublicEditor::show_measures)
646 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
648 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
649 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
651 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
653 .addRefFunction ("do_import", &PublicEditor::do_import)
654 .addRefFunction ("do_embed", &PublicEditor::do_embed)
656 .addFunction ("export_audio", &PublicEditor::export_audio)
657 .addFunction ("stem_export", &PublicEditor::stem_export)
658 .addFunction ("export_selection", &PublicEditor::export_selection)
659 .addFunction ("export_range", &PublicEditor::export_range)
661 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
662 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
663 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
664 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
666 #if 0 // These need TimeAxisView* which isn't exposed, yet
667 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
668 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
669 .addFunction ("new_playlists", &PublicEditor::new_playlists)
670 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
671 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
674 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
675 .addFunction ("deselect_all", &PublicEditor::deselect_all)
677 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
678 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
679 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
681 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
682 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
683 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
684 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
686 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
687 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
688 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
689 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
690 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
691 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
692 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
694 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
695 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
696 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
697 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
699 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
700 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
701 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
703 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
705 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
706 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
707 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
709 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
710 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
712 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
713 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
714 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
715 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
717 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
718 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
719 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
720 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
723 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
724 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
726 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
727 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
728 .addFunction ("get_track_views", &PublicEditor::get_track_views)
729 .addFunction ("drags", &PublicEditor::drags)
732 .addFunction ("center_screen", &PublicEditor::center_screen)
734 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
735 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
737 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
738 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
739 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
741 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
742 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
743 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
744 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
745 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
749 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
750 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
751 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
752 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
755 .addFunction ("access_action", &PublicEditor::access_action)
759 .beginNamespace ("MarkerType")
760 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
761 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
762 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
763 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
764 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
765 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
766 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
767 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
768 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
769 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
770 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
773 .endNamespace (); // end ArdourUI
781 #undef DISPLAYCONTROL
783 #undef IMPORTPOSITION
784 #undef IMPORTDISPOSITION
786 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
787 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
788 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
789 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
790 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
791 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
792 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
793 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
794 luabridge::getGlobalNamespace (L)
795 .beginNamespace ("Editing")
796 # include "editing_syms.h"
803 ////////////////////////////////////////////////////////////////////////////////
805 using namespace ARDOUR;
806 using namespace ARDOUR_UI_UTILS;
811 static void _lua_print (std::string s) {
812 std::cout << "LuaInstance: " << s << "\n";
816 LuaInstance* LuaInstance::_instance = 0;
819 LuaInstance::instance ()
822 _instance = new LuaInstance;
828 LuaInstance::LuaInstance ()
831 lua.Print.connect (&_lua_print);
835 LuaScriptParamList args;
838 LuaInstance::~LuaInstance ()
840 delete _lua_call_action;
841 delete _lua_add_action;
842 delete _lua_del_action;
843 delete _lua_get_action;
855 "function ScriptManager ()"
856 " local self = { scripts = {}, instances = {} }"
858 " local remove = function (id)"
859 " self.scripts[id] = nil"
860 " self.instances[id] = nil"
863 " local addinternal = function (i, n, s, f, a)"
864 " assert(type(i) == 'number', 'id must be numeric')"
865 " assert(type(n) == 'string', 'Name must be string')"
866 " assert(type(s) == 'string', 'Script must be string')"
867 " assert(type(f) == 'function', 'Factory is a not a function')"
868 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
869 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
870 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
871 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
874 " local call = function (id)"
875 " if type(self.instances[id]) == 'function' then"
876 " local status, err = pcall (self.instances[id])"
877 " if not status then"
878 " print ('action \"'.. id .. '\": ', err)" // error out
885 " local add = function (i, n, s, b, a)"
886 " assert(type(b) == 'string', 'ByteCode must be string')"
887 " load (b)()" // assigns f
888 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
889 " addinternal (i, n, s, load(f), a)"
892 " local get = function (id)"
893 " if type(self.scripts[id]) == 'table' then"
894 " return { ['name'] = self.scripts[id]['n'],"
895 " ['script'] = self.scripts[id]['s'],"
896 " ['args'] = self.scripts[id]['a'] }"
901 " local function basic_serialize (o)"
902 " if type(o) == \"number\" then"
903 " return tostring(o)"
905 " return string.format(\"%q\", o)"
909 " local function serialize (name, value)"
910 " local rv = name .. ' = '"
912 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
913 " return rv .. basic_serialize(value) .. ' '"
914 " elseif type(value) == \"table\" then"
916 " for k,v in pairs(value) do"
917 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
918 " rv = rv .. serialize(fieldname, v) .. ' '"
919 " collectgarbage()" // string concatenation allocates a new string
922 " elseif type(value) == \"function\" then"
923 " return rv .. string.format(\"%q\", string.dump(value, true))"
925 " error('cannot save a ' .. type(value))"
930 " local save = function ()"
931 " return (serialize('scripts', self.scripts))"
934 " local clear = function ()"
936 " self.instances = {}"
940 " local restore = function (state)"
943 " for i, s in pairs (scripts) do"
944 " addinternal (i, s['n'], s['s'], load(s['f']), s['a'])"
949 " return { call = call, add = add, remove = remove, get = get,"
950 " restore = restore, save = save, clear = clear}"
953 " manager = ScriptManager ()"
954 " ScriptManager = nil"
957 lua_State* L = lua.getState();
960 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
961 lua.do_command ("manager = nil"); // hide it.
962 lua.do_command ("collectgarbage()");
964 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
965 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
966 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
967 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
968 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
969 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
970 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
972 } catch (luabridge::LuaException const& e) {
973 fatal << string_compose (_("programming error: %1"),
974 X_("Failed to setup Lua action interpreter"))
976 abort(); /*NOTREACHED*/
979 register_classes (L);
981 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
982 lua_setglobal (L, "Editor");
985 void LuaInstance::set_session (Session* s)
987 SessionHandlePtr::set_session (s);
992 lua_State* L = lua.getState();
993 LuaBindings::set_session (L, _session);
995 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
996 i->second->set_session (s);
1001 LuaInstance::session_going_away ()
1003 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1005 for (int i = 0; i < 9; ++i) {
1006 ActionChanged (i, ""); /* EMIT SIGNAL */
1008 SessionHandlePtr::session_going_away ();
1011 lua_State* L = lua.getState();
1012 LuaBindings::set_session (L, _session);
1013 lua.do_command ("collectgarbage();");
1017 LuaInstance::set_state (const XMLNode& node)
1022 if ((child = find_named_node (node, "ActionScript"))) {
1023 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1024 if (!(*n)->is_content ()) { continue; }
1026 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1028 (*_lua_load)(std::string ((const char*)buf, size));
1029 } catch (luabridge::LuaException const& e) {
1030 cerr << "LuaException:" << e.what () << endl;
1032 for (int i = 0; i < 9; ++i) {
1034 if (lua_action_name (i, name)) {
1035 ActionChanged (i, name); /* EMIT SIGNAL */
1042 if ((child = find_named_node (node, "ActionHooks"))) {
1043 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1045 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1046 _callbacks.insert (std::make_pair(p->id(), p));
1047 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1048 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1049 } catch (luabridge::LuaException const& e) {
1050 cerr << "LuaException:" << e.what () << endl;
1059 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1062 std::vector<std::string> reg;
1065 case LuaScriptInfo::EditorAction:
1066 reg = lua_action_names ();
1067 title = "Add Lua Action";
1069 case LuaScriptInfo::EditorHook:
1070 reg = lua_slot_names ();
1071 title = "Add Lua Callback Hook";
1077 LuaScriptInfoPtr spi;
1078 ScriptSelector ss (title, type);
1079 switch (ss.run ()) {
1080 case Gtk::RESPONSE_ACCEPT:
1088 std::string script = "";
1091 script = Glib::file_get_contents (spi->path);
1092 } catch (Glib::FileError e) {
1093 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1094 Gtk::MessageDialog am (msg);
1099 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, "action_params");
1101 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1102 switch (spd.run ()) {
1103 case Gtk::RESPONSE_ACCEPT:
1110 case LuaScriptInfo::EditorAction:
1111 return set_lua_action (id, spd.name(), script, lsp);
1113 case LuaScriptInfo::EditorHook:
1114 return register_lua_slot (spd.name(), script, lsp);
1123 LuaInstance::get_action_state ()
1128 luabridge::LuaRef savedstate ((*_lua_save)());
1129 saved = savedstate.cast<std::string>();
1131 lua.collect_garbage ();
1133 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1134 std::string b64s (b64);
1137 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1138 script_node->add_property (X_("lua"), LUA_VERSION);
1139 script_node->add_content (b64s);
1141 return *script_node;
1145 LuaInstance::get_hook_state ()
1147 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1148 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1149 script_node->add_child_nocopy (i->second->get_state ());
1151 return *script_node;
1155 LuaInstance::call_action (const int id)
1158 (*_lua_call_action)(id + 1);
1159 } catch (luabridge::LuaException const& e) {
1160 cerr << "LuaException:" << e.what () << endl;
1165 LuaInstance::set_lua_action (
1167 const std::string& name,
1168 const std::string& script,
1169 const LuaScriptParamList& args)
1172 lua_State* L = lua.getState();
1173 // get bytcode of factory-function in a sandbox
1174 // (don't allow scripts to interfere)
1175 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1176 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1177 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1178 if ((*i)->optional && !(*i)->is_set) { continue; }
1179 tbl_arg[(*i)->name] = (*i)->value;
1181 (*_lua_add_action)(id + 1, name, script, bytecode, tbl_arg);
1182 ActionChanged (id, name); /* EMIT SIGNAL */
1183 } catch (luabridge::LuaException const& e) {
1184 cerr << "LuaException:" << e.what () << endl;
1191 LuaInstance::remove_lua_action (const int id)
1194 (*_lua_del_action)(id + 1);
1195 } catch (luabridge::LuaException const& e) {
1196 cerr << "LuaException:" << e.what () << endl;
1199 ActionChanged (id, ""); /* EMIT SIGNAL */
1204 LuaInstance::lua_action_name (const int id, std::string& rv)
1207 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1211 if (ref["name"].isString()) {
1212 rv = ref["name"].cast<std::string>();
1216 } catch (luabridge::LuaException const& e) {
1217 cerr << "LuaException:" << e.what () << endl;
1223 std::vector<std::string>
1224 LuaInstance::lua_action_names ()
1226 std::vector<std::string> rv;
1227 for (int i = 0; i < 9; ++i) {
1229 if (lua_action_name (i, name)) {
1230 rv.push_back (name);
1237 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1240 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1244 if (!ref["name"].isString()) {
1247 if (!ref["script"].isString()) {
1250 if (!ref["args"].isTable()) {
1253 name = ref["name"].cast<std::string>();
1254 script = ref["script"].cast<std::string>();
1257 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1261 args = LuaScriptParams::script_params (lsi, "action_params");
1262 luabridge::LuaRef rargs (ref["args"]);
1263 LuaScriptParams::ref_to_params (args, &rargs);
1265 } catch (luabridge::LuaException const& e) {
1266 cerr << "LuaException:" << e.what () << endl;
1273 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1275 /* parse script, get ActionHook(s) from script */
1280 l.Print.connect (&_lua_print);
1282 lua_State* L = l.getState();
1284 l.do_command ("function ardour () end");
1285 l.do_command (script);
1286 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1287 if (signals.isFunction()) {
1290 } catch (luabridge::LuaException const& e) {
1291 cerr << "LuaException:" << e.what () << endl;
1295 cerr << "Script registered no hooks." << endl;
1299 /* register script w/args, get entry-point / ID */
1302 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1303 _callbacks.insert (std::make_pair(p->id(), p));
1304 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1305 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1307 } catch (luabridge::LuaException const& e) {
1308 cerr << "LuaException:" << e.what () << endl;
1314 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1316 LuaCallbackMap::iterator i = _callbacks.find (id);
1317 if (i != _callbacks.end()) {
1318 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1319 _callbacks.erase (i);
1325 std::vector<PBD::ID>
1326 LuaInstance::lua_slots () const
1328 std::vector<PBD::ID> rv;
1329 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1330 rv.push_back (i->first);
1336 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1338 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1339 if (i != _callbacks.end()) {
1340 name = i->second->name();
1346 std::vector<std::string>
1347 LuaInstance::lua_slot_names () const
1349 std::vector<std::string> rv;
1350 std::vector<PBD::ID> ids = lua_slots();
1351 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1353 if (lua_slot_name (*i, name)) {
1354 rv.push_back (name);
1361 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1363 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1364 if (i == _callbacks.end()) {
1365 return false; // error
1367 return i->second->lua_slot (name, script, ah, args);
1370 ///////////////////////////////////////////////////////////////////////////////
1372 LuaCallback::LuaCallback (Session *s,
1373 const std::string& name,
1374 const std::string& script,
1375 const ActionHook& ah,
1376 const ARDOUR::LuaScriptParamList& args)
1377 : SessionHandlePtr (s)
1382 // TODO: allow to reference object (e.g region)
1385 lua_State* L = lua.getState();
1386 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1387 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1388 if ((*i)->optional && !(*i)->is_set) { continue; }
1389 tbl_arg[(*i)->name] = (*i)->value;
1393 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1394 (*_lua_add)(name, script, bytecode, tbl_arg);
1395 } catch (luabridge::LuaException const& e) {
1396 cerr << "LuaException:" << e.what () << endl;
1397 throw failed_constructor ();
1404 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1405 : SessionHandlePtr (s)
1407 XMLNode* child = NULL;
1408 if (node.name() != X_("LuaCallback")
1409 || !node.property ("signals")
1410 || !node.property ("id")
1411 || !node.property ("name")) {
1412 throw failed_constructor ();
1415 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1416 if (!(*n)->is_content ()) { continue; }
1421 throw failed_constructor ();
1426 _id = PBD::ID (node.property ("id")->value ());
1427 _name = node.property ("name")->value ();
1428 _signals = ActionHook (node.property ("signals")->value ());
1431 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1433 (*_lua_load)(std::string ((const char*)buf, size));
1434 } catch (luabridge::LuaException const& e) {
1435 cerr << "LuaException:" << e.what () << endl;
1442 LuaCallback::~LuaCallback ()
1452 LuaCallback::get_state (void)
1456 luabridge::LuaRef savedstate ((*_lua_save)());
1457 saved = savedstate.cast<std::string>();
1459 lua.collect_garbage ();
1461 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1462 std::string b64s (b64);
1465 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1466 script_node->add_property (X_("lua"), LUA_VERSION);
1467 script_node->add_property (X_("id"), _id.to_s ());
1468 script_node->add_property (X_("name"), _name);
1469 script_node->add_property (X_("signals"), _signals.to_string ());
1470 script_node->add_content (b64s);
1471 return *script_node;
1475 LuaCallback::init (void)
1478 lua.Print.connect (&_lua_print);
1482 "function ScriptManager ()"
1483 " local self = { script = {}, instance = {} }"
1485 " local addinternal = function (n, s, f, a)"
1486 " assert(type(n) == 'string', 'Name must be string')"
1487 " assert(type(s) == 'string', 'Script must be string')"
1488 " assert(type(f) == 'function', 'Factory is a not a function')"
1489 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1490 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1491 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1492 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1495 " local call = function (...)"
1496 " if type(self.instance) == 'function' then"
1497 " local status, err = pcall (self.instance, ...)"
1498 " if not status then"
1499 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1500 " self.script = nil"
1501 " self.instance = nil"
1509 " local add = function (n, s, b, a)"
1510 " assert(type(b) == 'string', 'ByteCode must be string')"
1511 " load (b)()" // assigns f
1512 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1513 " addinternal (n, s, load(f), a)"
1516 " local get = function ()"
1517 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1518 " return { ['name'] = self.script['n'],"
1519 " ['script'] = self.script['s'],"
1520 " ['args'] = self.script['a'] }"
1527 " local function basic_serialize (o)"
1528 " if type(o) == \"number\" then"
1529 " return tostring(o)"
1531 " return string.format(\"%q\", o)"
1535 " local function serialize (name, value)"
1536 " local rv = name .. ' = '"
1538 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1539 " return rv .. basic_serialize(value) .. ' '"
1540 " elseif type(value) == \"table\" then"
1542 " for k,v in pairs(value) do"
1543 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1544 " rv = rv .. serialize(fieldname, v) .. ' '"
1545 " collectgarbage()" // string concatenation allocates a new string
1548 " elseif type(value) == \"function\" then"
1549 " return rv .. string.format(\"%q\", string.dump(value, true))"
1551 " error('cannot save a ' .. type(value))"
1557 " local save = function ()"
1558 " return (serialize('s', self.script))"
1561 " local restore = function (state)"
1564 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1567 " return { call = call, add = add, get = get,"
1568 " restore = restore, save = save}"
1571 " manager = ScriptManager ()"
1572 " ScriptManager = nil"
1575 lua_State* L = lua.getState();
1578 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1579 lua.do_command ("manager = nil"); // hide it.
1580 lua.do_command ("collectgarbage()");
1582 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1583 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1584 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1585 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1586 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1588 } catch (luabridge::LuaException const& e) {
1589 fatal << string_compose (_("programming error: %1"),
1590 X_("Failed to setup Lua callback interpreter"))
1592 abort(); /*NOTREACHED*/
1595 LuaInstance::register_classes (L);
1597 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1598 lua_setglobal (L, "Editor");
1602 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1604 // TODO consolidate w/ LuaInstance::lua_action()
1606 luabridge::LuaRef ref = (*_lua_get)();
1610 if (!ref["name"].isString()) {
1613 if (!ref["script"].isString()) {
1616 if (!ref["args"].isTable()) {
1621 name = ref["name"].cast<std::string> ();
1622 script = ref["script"].cast<std::string> ();
1625 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1629 args = LuaScriptParams::script_params (lsi, "action_params");
1630 luabridge::LuaRef rargs (ref["args"]);
1631 LuaScriptParams::ref_to_params (args, &rargs);
1633 } catch (luabridge::LuaException const& e) {
1634 cerr << "LuaException:" << e.what () << endl;
1641 LuaCallback::set_session (ARDOUR::Session *s)
1643 SessionHandlePtr::set_session (s);
1646 lua_State* L = lua.getState();
1647 LuaBindings::set_session (L, _session);
1654 LuaCallback::session_going_away ()
1656 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1657 lua.do_command ("collectgarbage();");
1659 SessionHandlePtr::session_going_away ();
1662 drop_callback (); /* EMIT SIGNAL */
1666 LuaCallback::reconnect ()
1668 _connections.drop_connections ();
1669 if ((*_lua_get) ().isNil ()) {
1670 drop_callback (); /* EMIT SIGNAL */
1674 // TODO pass object which emits the signal (e.g region)
1676 // save/load bound objects will be tricky.
1677 // Best idea so far is to save/lookup the PBD::ID
1678 // (either use boost::any indirection or templates for bindable
1679 // object types or a switch statement..)
1681 // _session->route_by_id ()
1682 // _session->track_by_diskstream_id ()
1683 // _session->source_by_id ()
1684 // _session->controllable_by_id ()
1685 // _session->processor_by_id ()
1686 // RegionFactory::region_by_id ()
1688 // TODO loop over objects (if any)
1690 reconnect_object ((void*)0);
1693 template <class T> void
1694 LuaCallback::reconnect_object (T obj)
1696 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1698 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1699 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1700 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1702 # include "luasignal_syms.h"
1704 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1705 abort(); /*NOTREACHED*/
1714 template <typename T, typename S> void
1715 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1717 _connections, invalidator (*this),
1718 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1722 template <typename T, typename C1> void
1723 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1725 _connections, invalidator (*this),
1726 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1730 template <typename T, typename C1, typename C2> void
1731 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1733 _connections, invalidator (*this),
1734 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1738 template <typename T> void
1739 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1742 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1743 if (! rv.cast<bool> ()) {
1747 /* destroy LuaRef ^^ first before calling drop_callback() */
1749 drop_callback (); /* EMIT SIGNAL */
1753 template <typename T, typename C1> void
1754 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1757 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1758 if (! rv.cast<bool> ()) {
1763 drop_callback (); /* EMIT SIGNAL */
1767 template <typename T, typename C1, typename C2> void
1768 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1771 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1772 if (! rv.cast<bool> ()) {
1777 drop_callback (); /* EMIT SIGNAL */