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 "region_view.h"
41 #include "processor_box.h"
42 #include "time_axis_view.h"
43 #include "time_axis_view_item.h"
44 #include "selection.h"
45 #include "script_selector.h"
47 #include "utils_videotl.h"
52 /** wrap RefPtr< Cairo::ImageSurface >
54 * Image surfaces provide the ability to render to memory buffers either
55 * allocated by cairo or by the calling code. The supported image formats are
56 * those defined in Cairo::Format.
61 * Creates an image surface of the specified format and dimensions. Initially
62 * the surface contents are all 0. (Specifically, within each pixel, each
63 * color or alpha channel belonging to format will be 0. The contents of bits
64 * within a pixel, but not belonging to the given format are undefined).
66 * @param format format of pixels in the surface to create
67 * @param width width of the surface, in pixels
68 * @param height height of the surface, in pixels
70 ImageSurface (Cairo::Format format, int width, int height)
71 : _surface (Cairo::ImageSurface::create (format, width, height))
72 , _ctx (Cairo::Context::create (_surface))
73 , ctx (_ctx->cobj ()) {}
78 * Set this surface as source for another context.
79 * This allows to draw this surface
81 void set_as_source (Cairo::Context* c, int x, int y) {
83 c->set_source (_surface, x, y);
87 * Returns a context object to perform operations on the surface
89 Cairo::Context* context () {
90 return (Cairo::Context *)&ctx;
94 * Returns the stride of the image surface in bytes (or 0 if surface is not
95 * an image surface). The stride is the distance in bytes from the beginning
96 * of one row of the image data to the beginning of the next row.
98 int get_stride () const {
99 return _surface->get_stride ();
102 /** Gets the width of the ImageSurface in pixels */
103 int get_width () const {
104 return _surface->get_width ();
107 /** Gets the height of the ImageSurface in pixels */
108 int get_height () const {
109 return _surface->get_height ();
113 * Get a pointer to the data of the image surface, for direct
114 * inspection or modification.
116 * Return value: a pointer to the image data of this surface or NULL
117 * if @surface is not an image surface.
120 unsigned char* get_data () {
121 return _surface->get_data ();
124 /** Tells cairo to consider the data buffer dirty.
126 * In particular, if you've created an ImageSurface with a data buffer that
127 * you've allocated yourself and you draw to that data buffer using means
128 * other than cairo, you must call mark_dirty() before doing any additional
129 * drawing to that surface with cairo.
131 * Note that if you do draw to the Surface outside of cairo, you must call
132 * flush() before doing the drawing.
135 _surface->mark_dirty ();
138 /** Marks a rectangular area of the given surface dirty.
140 * @param x X coordinate of dirty rectangle
141 * @param y Y coordinate of dirty rectangle
142 * @param width width of dirty rectangle
143 * @param height height of dirty rectangle
145 void mark_dirty (int x, int y, int width, int height) {
146 _surface->mark_dirty (x, y, width, height);
150 Cairo::RefPtr<Cairo::ImageSurface> _surface;
151 Cairo::RefPtr<Cairo::Context> _ctx;
157 /** Create a new PangoLayout Text Display
158 * @param c CairoContext for the layout
159 * @param font_name a font-description e.g. "Mono 8px"
161 PangoLayout (Cairo::Context* c, std::string font_name) {
162 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
163 _layout = Glib::wrap (pl);
164 Pango::FontDescription fd (font_name);
165 _layout->set_font_description (fd);
170 /** Gets the text in the layout. The returned text should not
171 * be freed or modified.
173 * @return The text in the @a layout.
175 std::string get_text () const {
176 return _layout->get_text ();
178 /** Set the text of the layout.
179 * @param text The text for the layout.
181 void set_text (const std::string& text) {
182 _layout->set_text (text);
185 /** Sets the layout text and attribute list from marked-up text (see markup format).
186 * Replaces the current text and attribute list.
187 * @param markup Some marked-up text.
189 void set_markup (const std::string& markup) {
190 _layout->set_markup (markup);
193 /** Sets the width to which the lines of the Pango::Layout should wrap or
194 * ellipsized. The default value is -1: no width set.
196 * @param width The desired width in Pango units, or -1 to indicate that no
197 * wrapping or ellipsization should be performed.
199 void set_width (int width) {
200 _layout->set_width (width * PANGO_SCALE);
203 /** Gets the width to which the lines of the Pango::Layout should wrap.
205 * @return The width in Pango units, or -1 if no width set.
207 int get_width () const {
208 return _layout->get_width () / PANGO_SCALE;
211 /** Sets the type of ellipsization being performed for @a layout.
212 * Depending on the ellipsization mode @a ellipsize text is
213 * removed from the start, middle, or end of text so they
214 * fit within the width and height of layout set with
215 * set_width() and set_height().
217 * If the layout contains characters such as newlines that
218 * force it to be layed out in multiple paragraphs, then whether
219 * each paragraph is ellipsized separately or the entire layout
220 * is ellipsized as a whole depends on the set height of the layout.
221 * See set_height() for details.
223 * @param ellipsize The new ellipsization mode for @a layout.
225 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
226 _layout->set_ellipsize (ellipsize);
229 /** Gets the type of ellipsization being performed for @a layout.
230 * See set_ellipsize()
232 * @return The current ellipsization mode for @a layout.
234 * Use is_ellipsized() to query whether any paragraphs
235 * were actually ellipsized.
237 Pango::EllipsizeMode get_ellipsize () const {
238 return _layout->get_ellipsize ();
241 /** Queries whether the layout had to ellipsize any paragraphs.
243 * This returns <tt>true</tt> if the ellipsization mode for @a layout
244 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
245 * and there are paragraphs exceeding that width that have to be
248 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
251 bool is_ellipsized () const {
252 return _layout->is_ellipsized ();
255 /** Sets the wrap mode; the wrap mode only has effect if a width
256 * is set on the layout with set_width().
257 * To turn off wrapping, set the width to -1.
259 * @param wrap The wrap mode.
261 void set_wrap (Pango::WrapMode wrap) {
262 _layout->set_width (wrap);
265 /** Gets the wrap mode for the layout.
267 * Use is_wrapped() to query whether any paragraphs
268 * were actually wrapped.
270 * @return Active wrap mode.
272 Pango::WrapMode get_wrap () const {
273 return _layout->get_wrap ();
276 /** Queries whether the layout had to wrap any paragraphs.
278 * This returns <tt>true</tt> if a positive width is set on @a layout,
279 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
280 * and there are paragraphs exceeding the layout width that have
283 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
286 bool is_wrapped () const {
287 return _layout->is_wrapped ();
290 /** Determines the logical width and height of a Pango::Layout
293 int get_pixel_size (lua_State *L) {
295 _layout->get_pixel_size (width, height);
296 luabridge::Stack<int>::push (L, width);
297 luabridge::Stack<int>::push (L, height);
302 /** Draws a Layout in the specified Cairo @a context. The top-left
303 * corner of the Layout will be drawn at the current point of the
306 * @param context A Cairo context.
308 void show_in_cairo_context (Cairo::Context* c) {
309 pango_cairo_update_layout (c->cobj (), _layout->gobj());
310 pango_cairo_show_layout (c->cobj (), _layout->gobj());
313 void layout_cairo_path (Cairo::Context* c) {
314 pango_cairo_update_layout (c->cobj (), _layout->gobj());
315 pango_cairo_layout_path (c->cobj (), _layout->gobj());
319 Glib::RefPtr<Pango::Layout> _layout;
324 ////////////////////////////////////////////////////////////////////////////////
326 namespace LuaSignal {
328 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
329 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
330 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
333 str2luasignal (const std::string &str) {
334 const char* type = str.c_str();
336 # include "luasignal_syms.h"
338 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
339 abort(); /*NOTREACHED*/
346 #define STATIC(name,c,p) N_(#name),
347 #define SESSION(name,c,p) N_(#name),
348 #define ENGINE(name,c,p) N_(#name),
349 const char *luasignalstr[] = {
350 # include "luasignal_syms.h"
360 /** special cases for Ardour's Mixer UI */
363 ProcessorBox::ProcSelection
364 processor_selection () {
365 return ProcessorBox::current_processor_selection ();
370 ////////////////////////////////////////////////////////////////////////////////
372 #define xstr(s) stringify(s)
373 #define stringify(s) #s
375 using namespace ARDOUR;
377 PBD::Signal0<void> LuaInstance::LuaTimerDS;
380 LuaInstance::register_hooks (lua_State* L)
383 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
384 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
385 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
386 luabridge::getGlobalNamespace (L)
387 .beginNamespace ("LuaSignal")
388 # include "luasignal_syms.h"
394 luabridge::getGlobalNamespace (L)
395 .beginNamespace ("LuaSignal")
396 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
402 LuaInstance::bind_cairo (lua_State* L)
404 /* std::vector<double> for set_dash()
405 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
407 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
408 * the address of the one in libardour.dll is mapped when loading the .dll
410 * see LuaBindings::set_session() for a detailed explanation
412 luabridge::getGlobalNamespace (L)
413 .beginNamespace ("C")
414 .beginStdVector <double> ("DoubleVector")
418 luabridge::getGlobalNamespace (L)
419 .beginNamespace ("Cairo")
420 .beginClass <Cairo::Context> ("Context")
421 .addFunction ("save", &Cairo::Context::save)
422 .addFunction ("restore", &Cairo::Context::restore)
423 .addFunction ("set_operator", &Cairo::Context::set_operator)
424 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
425 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
426 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
427 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
428 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
429 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
430 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
431 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
432 .addFunction ("translate", &Cairo::Context::translate)
433 .addFunction ("scale", &Cairo::Context::scale)
434 .addFunction ("rotate", &Cairo::Context::rotate)
435 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
436 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
437 .addFunction ("move_to", &Cairo::Context::move_to)
438 .addFunction ("line_to", &Cairo::Context::line_to)
439 .addFunction ("curve_to", &Cairo::Context::curve_to)
440 .addFunction ("arc", &Cairo::Context::arc)
441 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
442 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
443 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
444 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
445 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
446 .addFunction ("close_path", &Cairo::Context::close_path)
447 .addFunction ("paint", &Cairo::Context::paint)
448 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
449 .addFunction ("stroke", &Cairo::Context::stroke)
450 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
451 .addFunction ("fill", &Cairo::Context::fill)
452 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
453 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
454 .addFunction ("clip", &Cairo::Context::clip)
455 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
456 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
457 .addFunction ("show_text", &Cairo::Context::show_text)
460 // LineCap, LineJoin, Operator
461 .beginNamespace ("LineCap")
462 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
463 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
464 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
467 .beginNamespace ("LineJoin")
468 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
469 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
470 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
473 .beginNamespace ("Operator")
474 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
475 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
476 .addConst ("Over", CAIRO_OPERATOR_OVER)
477 .addConst ("Add", CAIRO_OPERATOR_ADD)
480 .beginNamespace ("Format")
481 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
482 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
485 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
486 .addConstructor <void (*) (Cairo::Format, int, int)> ()
487 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
488 .addFunction ("context", &LuaCairo::ImageSurface::context)
489 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
490 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
491 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
492 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
495 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
496 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
497 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
498 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
499 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
500 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
501 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
502 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
503 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
504 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
505 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
506 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
507 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
508 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
509 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
513 .beginNamespace ("EllipsizeMode")
514 .addConst ("None", Pango::ELLIPSIZE_NONE)
515 .addConst ("Start", Pango::ELLIPSIZE_START)
516 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
517 .addConst ("End", Pango::ELLIPSIZE_END)
520 .beginNamespace ("WrapMode")
521 .addConst ("Word", Pango::WRAP_WORD)
522 .addConst ("Char", Pango::WRAP_CHAR)
523 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
528 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
529 one can work around this as follows:
532 LuaInstance::register_classes (lua.getState());
534 "function render (ctx)"
535 " ctx:rectangle (0, 0, 100, 100)"
536 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
541 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
542 Cairo::Context ctx (context->cobj ());
544 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
545 lua_render ((Cairo::Context *)&ctx);
552 LuaInstance::register_classes (lua_State* L)
554 LuaBindings::stddef (L);
555 LuaBindings::common (L);
556 LuaBindings::session (L);
557 LuaBindings::osc (L);
562 luabridge::getGlobalNamespace (L)
563 .beginNamespace ("ArdourUI")
565 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
567 .addFunction ("processor_selection", &LuaMixer::processor_selection)
569 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
572 .beginClass <ArdourMarker> ("ArdourMarker")
573 .addFunction ("name", &ArdourMarker::name)
574 .addFunction ("position", &ArdourMarker::position)
575 .addFunction ("_type", &ArdourMarker::type)
579 .beginClass <AxisView> ("AxisView")
581 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
583 .deriveClass <RouteTimeAxisView, TimeAxisView> ("RouteTimeAxisView")
587 .beginClass <Selectable> ("Selectable")
589 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
591 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
594 .beginStdCPtrList <Selectable> ("SelectionList")
597 .beginClass <RegionSelection> ("RegionSelection")
598 .addFunction ("start", &RegionSelection::start)
599 .addFunction ("end_frame", &RegionSelection::end_frame)
600 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
601 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
604 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
605 .addFunction ("start", &TimeSelection::start)
606 .addFunction ("end_frame", &TimeSelection::end_frame)
607 .addFunction ("length", &TimeSelection::length)
610 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
613 .beginClass <TrackViewList> ("TrackViewList")
614 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
617 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
620 .beginClass <Selection> ("Selection")
621 .addFunction ("clear", &Selection::clear)
622 .addFunction ("clear_all", &Selection::clear_all)
623 .addFunction ("empty", &Selection::empty)
624 .addData ("tracks", &Selection::tracks)
625 .addData ("regions", &Selection::regions)
626 .addData ("time", &Selection::time)
627 .addData ("markers", &Selection::markers)
629 .addData ("lines", &Selection::lines)
630 .addData ("playlists", &Selection::playlists)
631 .addData ("points", &Selection::points)
632 .addData ("midi_regions", &Selection::midi_regions)
633 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
637 .beginClass <PublicEditor> ("Editor")
638 .addFunction ("snap_type", &PublicEditor::snap_type)
639 .addFunction ("snap_mode", &PublicEditor::snap_mode)
640 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
641 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
643 .addFunction ("undo", &PublicEditor::undo)
644 .addFunction ("redo", &PublicEditor::redo)
646 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
647 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
649 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
651 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
652 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
653 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
654 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
656 .addFunction ("get_selection", &PublicEditor::get_selection)
657 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
658 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
660 .addFunction ("set_selection", &PublicEditor::set_selection)
662 .addFunction ("play_selection", &PublicEditor::play_selection)
663 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
664 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
665 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
667 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
668 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
670 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
671 .addFunction ("show_measures", &PublicEditor::show_measures)
672 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
674 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
675 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
677 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
679 .addRefFunction ("do_import", &PublicEditor::do_import)
680 .addRefFunction ("do_embed", &PublicEditor::do_embed)
682 .addFunction ("export_audio", &PublicEditor::export_audio)
683 .addFunction ("stem_export", &PublicEditor::stem_export)
684 .addFunction ("export_selection", &PublicEditor::export_selection)
685 .addFunction ("export_range", &PublicEditor::export_range)
687 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
688 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
689 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
690 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
692 #if 0 // These need TimeAxisView* which isn't exposed, yet
693 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
694 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
695 .addFunction ("new_playlists", &PublicEditor::new_playlists)
696 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
697 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
700 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
701 .addFunction ("deselect_all", &PublicEditor::deselect_all)
703 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
704 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
705 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
708 .addFunction ("get_regionview_from_region", &PublicEditor::get_regionview_from_region)
709 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
710 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
711 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
712 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
714 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
715 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
716 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
717 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
718 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
719 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
720 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
722 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
723 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
724 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
725 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
727 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
728 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
729 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
731 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
733 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
734 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
735 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
737 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
738 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
740 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
741 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
742 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
743 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
745 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
746 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
747 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
748 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
751 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
752 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
754 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
755 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
756 .addFunction ("get_track_views", &PublicEditor::get_track_views)
757 .addFunction ("drags", &PublicEditor::drags)
760 .addFunction ("center_screen", &PublicEditor::center_screen)
762 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
763 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
765 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
766 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
767 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
769 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
770 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
771 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
772 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
773 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
777 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
778 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
779 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
780 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
783 .addFunction ("access_action", &PublicEditor::access_action)
787 .beginNamespace ("MarkerType")
788 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
789 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
790 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
791 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
792 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
793 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
794 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
795 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
796 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
797 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
798 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
801 .beginNamespace ("SelectionOp")
802 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
803 .addConst ("Set", Selection::Operation(Selection::Set))
804 .addConst ("Extend", Selection::Operation(Selection::Extend))
805 .addConst ("Add", Selection::Operation(Selection::Add))
808 .endNamespace (); // end ArdourUI
816 #undef DISPLAYCONTROL
818 #undef IMPORTPOSITION
819 #undef IMPORTDISPOSITION
821 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
822 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
823 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
824 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
825 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
826 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
827 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
828 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
829 luabridge::getGlobalNamespace (L)
830 .beginNamespace ("Editing")
831 # include "editing_syms.h"
838 ////////////////////////////////////////////////////////////////////////////////
840 using namespace ARDOUR;
841 using namespace ARDOUR_UI_UTILS;
845 static void _lua_print (std::string s) {
847 std::cout << "LuaInstance: " << s << "\n";
849 PBD::info << "LuaInstance: " << s << endmsg;
852 LuaInstance* LuaInstance::_instance = 0;
855 LuaInstance::instance ()
858 _instance = new LuaInstance;
865 LuaInstance::destroy_instance ()
871 LuaInstance::LuaInstance ()
873 lua.Print.connect (&_lua_print);
876 LuaScriptParamList args;
879 LuaInstance::~LuaInstance ()
881 delete _lua_call_action;
882 delete _lua_render_icon;
883 delete _lua_add_action;
884 delete _lua_del_action;
885 delete _lua_get_action;
897 "function ScriptManager ()"
898 " local self = { scripts = {}, instances = {}, icons = {} }"
900 " local remove = function (id)"
901 " self.scripts[id] = nil"
902 " self.instances[id] = nil"
903 " self.icons[id] = nil"
906 " local addinternal = function (i, n, s, f, c, a)"
907 " assert(type(i) == 'number', 'id must be numeric')"
908 " assert(type(n) == 'string', 'Name must be string')"
909 " assert(type(s) == 'string', 'Script must be string')"
910 " assert(type(f) == 'function', 'Factory is a not a function')"
911 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
912 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
913 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
914 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
915 " if type(c) == 'function' then"
916 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
918 " self.icons[i] = nil"
922 " local call = function (id)"
923 " if type(self.instances[id]) == 'function' then"
924 " local status, err = pcall (self.instances[id])"
925 " if not status then"
926 " print ('action \"'.. id .. '\": ', err)" // error out
933 " local icon = function (id, ...)"
934 " if type(self.icons[id]) == 'function' then"
935 " pcall (self.icons[id], ...)"
940 " local add = function (i, n, s, b, c, a)"
941 " assert(type(b) == 'string', 'ByteCode must be string')"
942 " f = nil load (b)()" // assigns f
943 " icn = nil load (c)()" // may assign "icn"
944 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
945 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
948 " local get = function (id)"
949 " if type(self.scripts[id]) == 'table' then"
950 " return { ['name'] = self.scripts[id]['n'],"
951 " ['script'] = self.scripts[id]['s'],"
952 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
953 " ['args'] = self.scripts[id]['a'] }"
958 " local function basic_serialize (o)"
959 " if type(o) == \"number\" then"
960 " return tostring(o)"
962 " return string.format(\"%q\", o)"
966 " local function serialize (name, value)"
967 " local rv = name .. ' = '"
969 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
970 " return rv .. basic_serialize(value) .. ' '"
971 " elseif type(value) == \"table\" then"
973 " for k,v in pairs(value) do"
974 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
975 " rv = rv .. serialize(fieldname, v) .. ' '"
976 " collectgarbage()" // string concatenation allocates a new string
979 " elseif type(value) == \"function\" then"
980 " return rv .. string.format(\"%q\", string.dump(value, true))"
981 " elseif type(value) == \"boolean\" then"
982 " return rv .. tostring (value)"
984 " error('cannot save a ' .. type(value))"
989 " local save = function ()"
990 " return (serialize('scripts', self.scripts))"
993 " local clear = function ()"
995 " self.instances = {}"
1000 " local restore = function (state)"
1003 " for i, s in pairs (scripts) do"
1004 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1009 " return { call = call, add = add, remove = remove, get = get,"
1010 " restore = restore, save = save, clear = clear, icon = icon}"
1013 " manager = ScriptManager ()"
1014 " ScriptManager = nil"
1017 lua_State* L = lua.getState();
1020 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1021 lua.do_command ("manager = nil"); // hide it.
1022 lua.do_command ("collectgarbage()");
1024 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1025 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1026 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1027 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1028 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1029 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1030 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1031 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1033 } catch (luabridge::LuaException const& e) {
1034 fatal << string_compose (_("programming error: %1"),
1035 X_("Failed to setup Lua action interpreter"))
1037 abort(); /*NOTREACHED*/
1040 register_classes (L);
1042 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1043 lua_setglobal (L, "Editor");
1046 void LuaInstance::set_session (Session* s)
1048 SessionHandlePtr::set_session (s);
1053 lua_State* L = lua.getState();
1054 LuaBindings::set_session (L, _session);
1056 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1057 i->second->set_session (s);
1059 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1063 LuaInstance::session_going_away ()
1065 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1066 point_one_second_connection.disconnect ();
1069 for (int i = 0; i < 9; ++i) {
1070 ActionChanged (i, ""); /* EMIT SIGNAL */
1072 SessionHandlePtr::session_going_away ();
1075 lua_State* L = lua.getState();
1076 LuaBindings::set_session (L, _session);
1077 lua.do_command ("collectgarbage();");
1081 LuaInstance::every_point_one_seconds ()
1083 LuaTimerDS (); // emit signal
1087 LuaInstance::set_state (const XMLNode& node)
1092 if ((child = find_named_node (node, "ActionScript"))) {
1093 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1094 if (!(*n)->is_content ()) { continue; }
1096 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1098 (*_lua_load)(std::string ((const char*)buf, size));
1099 } catch (luabridge::LuaException const& e) {
1100 cerr << "LuaException:" << e.what () << endl;
1102 for (int i = 0; i < 9; ++i) {
1104 if (lua_action_name (i, name)) {
1105 ActionChanged (i, name); /* EMIT SIGNAL */
1112 if ((child = find_named_node (node, "ActionHooks"))) {
1113 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1115 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1116 _callbacks.insert (std::make_pair(p->id(), p));
1117 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1118 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1119 } catch (luabridge::LuaException const& e) {
1120 cerr << "LuaException:" << e.what () << endl;
1129 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1132 std::string param_function = "action_params";
1133 std::vector<std::string> reg;
1136 case LuaScriptInfo::EditorAction:
1137 reg = lua_action_names ();
1138 title = _("Add Lua Action");
1140 case LuaScriptInfo::EditorHook:
1141 reg = lua_slot_names ();
1142 title = _("Add Lua Callback Hook");
1144 case LuaScriptInfo::Session:
1148 reg = _session->registered_lua_functions ();
1149 title = _("Add Lua Session Script");
1150 param_function = "sess_params";
1156 LuaScriptInfoPtr spi;
1157 ScriptSelector ss (title, type);
1158 switch (ss.run ()) {
1159 case Gtk::RESPONSE_ACCEPT:
1167 std::string script = "";
1170 script = Glib::file_get_contents (spi->path);
1171 } catch (Glib::FileError e) {
1172 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1173 Gtk::MessageDialog am (msg);
1178 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1180 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1181 switch (spd.run ()) {
1182 case Gtk::RESPONSE_ACCEPT:
1189 case LuaScriptInfo::EditorAction:
1190 return set_lua_action (id, spd.name(), script, lsp);
1192 case LuaScriptInfo::EditorHook:
1193 return register_lua_slot (spd.name(), script, lsp);
1195 case LuaScriptInfo::Session:
1197 _session->register_lua_function (spd.name(), script, lsp);
1198 } catch (luabridge::LuaException const& e) {
1199 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1200 Gtk::MessageDialog am (msg);
1202 } catch (SessionException e) {
1203 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1204 Gtk::MessageDialog am (msg);
1214 LuaInstance::get_action_state ()
1219 luabridge::LuaRef savedstate ((*_lua_save)());
1220 saved = savedstate.cast<std::string>();
1222 lua.collect_garbage ();
1224 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1225 std::string b64s (b64);
1228 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1229 script_node->add_property (X_("lua"), LUA_VERSION);
1230 script_node->add_content (b64s);
1232 return *script_node;
1236 LuaInstance::get_hook_state ()
1238 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1239 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1240 script_node->add_child_nocopy (i->second->get_state ());
1242 return *script_node;
1246 LuaInstance::call_action (const int id)
1249 (*_lua_call_action)(id + 1);
1250 lua.collect_garbage_step ();
1251 } catch (luabridge::LuaException const& e) {
1252 cerr << "LuaException:" << e.what () << endl;
1257 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1258 int ii = reinterpret_cast<uintptr_t> (i);
1259 instance()->render_icon (ii, cr, w, h, c);
1263 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1265 Cairo::Context ctx (cr);
1267 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1268 } catch (luabridge::LuaException const& e) {
1269 cerr << "LuaException:" << e.what () << endl;
1274 LuaInstance::set_lua_action (
1276 const std::string& name,
1277 const std::string& script,
1278 const LuaScriptParamList& args)
1281 lua_State* L = lua.getState();
1282 // get bytcode of factory-function in a sandbox
1283 // (don't allow scripts to interfere)
1284 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1285 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1286 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1287 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1288 if ((*i)->optional && !(*i)->is_set) { continue; }
1289 tbl_arg[(*i)->name] = (*i)->value;
1291 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1292 ActionChanged (id, name); /* EMIT SIGNAL */
1293 } catch (luabridge::LuaException const& e) {
1294 cerr << "LuaException:" << e.what () << endl;
1297 _session->set_dirty ();
1302 LuaInstance::remove_lua_action (const int id)
1305 (*_lua_del_action)(id + 1);
1306 } catch (luabridge::LuaException const& e) {
1307 cerr << "LuaException:" << e.what () << endl;
1310 ActionChanged (id, ""); /* EMIT SIGNAL */
1311 _session->set_dirty ();
1316 LuaInstance::lua_action_name (const int id, std::string& rv)
1319 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1323 if (ref["name"].isString()) {
1324 rv = ref["name"].cast<std::string>();
1328 } catch (luabridge::LuaException const& e) {
1329 cerr << "LuaException:" << e.what () << endl;
1335 std::vector<std::string>
1336 LuaInstance::lua_action_names ()
1338 std::vector<std::string> rv;
1339 for (int i = 0; i < 9; ++i) {
1341 if (lua_action_name (i, name)) {
1342 rv.push_back (name);
1349 LuaInstance::lua_action_has_icon (const int id)
1352 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1356 if (ref["icon"].isBoolean()) {
1357 return ref["icon"].cast<bool>();
1359 } catch (luabridge::LuaException const& e) {
1360 cerr << "LuaException:" << e.what () << endl;
1366 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1369 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1373 if (!ref["name"].isString()) {
1376 if (!ref["script"].isString()) {
1379 if (!ref["args"].isTable()) {
1382 name = ref["name"].cast<std::string>();
1383 script = ref["script"].cast<std::string>();
1386 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1390 args = LuaScriptParams::script_params (lsi, "action_params");
1391 luabridge::LuaRef rargs (ref["args"]);
1392 LuaScriptParams::ref_to_params (args, &rargs);
1394 } catch (luabridge::LuaException const& e) {
1395 cerr << "LuaException:" << e.what () << endl;
1402 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1404 /* parse script, get ActionHook(s) from script */
1408 l.Print.connect (&_lua_print);
1409 lua_State* L = l.getState();
1411 l.do_command ("function ardour () end");
1412 l.do_command (script);
1413 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1414 if (signals.isFunction()) {
1417 } catch (luabridge::LuaException const& e) {
1418 cerr << "LuaException:" << e.what () << endl;
1422 cerr << "Script registered no hooks." << endl;
1426 /* register script w/args, get entry-point / ID */
1429 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1430 _callbacks.insert (std::make_pair(p->id(), p));
1431 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1432 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1434 } catch (luabridge::LuaException const& e) {
1435 cerr << "LuaException:" << e.what () << endl;
1437 _session->set_dirty ();
1442 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1444 LuaCallbackMap::iterator i = _callbacks.find (id);
1445 if (i != _callbacks.end()) {
1446 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1447 _callbacks.erase (i);
1450 _session->set_dirty ();
1454 std::vector<PBD::ID>
1455 LuaInstance::lua_slots () const
1457 std::vector<PBD::ID> rv;
1458 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1459 rv.push_back (i->first);
1465 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1467 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1468 if (i != _callbacks.end()) {
1469 name = i->second->name();
1475 std::vector<std::string>
1476 LuaInstance::lua_slot_names () const
1478 std::vector<std::string> rv;
1479 std::vector<PBD::ID> ids = lua_slots();
1480 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1482 if (lua_slot_name (*i, name)) {
1483 rv.push_back (name);
1490 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1492 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1493 if (i == _callbacks.end()) {
1494 return false; // error
1496 return i->second->lua_slot (name, script, ah, args);
1499 ///////////////////////////////////////////////////////////////////////////////
1501 LuaCallback::LuaCallback (Session *s,
1502 const std::string& name,
1503 const std::string& script,
1504 const ActionHook& ah,
1505 const ARDOUR::LuaScriptParamList& args)
1506 : SessionHandlePtr (s)
1511 // TODO: allow to reference object (e.g region)
1514 lua_State* L = lua.getState();
1515 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1516 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1517 if ((*i)->optional && !(*i)->is_set) { continue; }
1518 tbl_arg[(*i)->name] = (*i)->value;
1522 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1523 (*_lua_add)(name, script, bytecode, tbl_arg);
1524 } catch (luabridge::LuaException const& e) {
1525 cerr << "LuaException:" << e.what () << endl;
1526 throw failed_constructor ();
1533 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1534 : SessionHandlePtr (s)
1536 XMLNode* child = NULL;
1537 if (node.name() != X_("LuaCallback")
1538 || !node.property ("signals")
1539 || !node.property ("id")
1540 || !node.property ("name")) {
1541 throw failed_constructor ();
1544 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1545 if (!(*n)->is_content ()) { continue; }
1550 throw failed_constructor ();
1555 _id = PBD::ID (node.property ("id")->value ());
1556 _name = node.property ("name")->value ();
1557 _signals = ActionHook (node.property ("signals")->value ());
1560 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1562 (*_lua_load)(std::string ((const char*)buf, size));
1563 } catch (luabridge::LuaException const& e) {
1564 cerr << "LuaException:" << e.what () << endl;
1571 LuaCallback::~LuaCallback ()
1581 LuaCallback::get_state (void)
1585 luabridge::LuaRef savedstate ((*_lua_save)());
1586 saved = savedstate.cast<std::string>();
1588 lua.collect_garbage ();
1590 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1591 std::string b64s (b64);
1594 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1595 script_node->add_property (X_("lua"), LUA_VERSION);
1596 script_node->add_property (X_("id"), _id.to_s ());
1597 script_node->add_property (X_("name"), _name);
1598 script_node->add_property (X_("signals"), _signals.to_string ());
1599 script_node->add_content (b64s);
1600 return *script_node;
1604 LuaCallback::init (void)
1606 lua.Print.connect (&_lua_print);
1609 "function ScriptManager ()"
1610 " local self = { script = {}, instance = {} }"
1612 " local addinternal = function (n, s, f, a)"
1613 " assert(type(n) == 'string', 'Name must be string')"
1614 " assert(type(s) == 'string', 'Script must be string')"
1615 " assert(type(f) == 'function', 'Factory is a not a function')"
1616 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1617 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1618 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1619 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1622 " local call = function (...)"
1623 " if type(self.instance) == 'function' then"
1624 " local status, err = pcall (self.instance, ...)"
1625 " if not status then"
1626 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1627 " self.script = nil"
1628 " self.instance = nil"
1636 " local add = function (n, s, b, a)"
1637 " assert(type(b) == 'string', 'ByteCode must be string')"
1638 " load (b)()" // assigns f
1639 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1640 " addinternal (n, s, load(f), a)"
1643 " local get = function ()"
1644 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1645 " return { ['name'] = self.script['n'],"
1646 " ['script'] = self.script['s'],"
1647 " ['args'] = self.script['a'] }"
1654 " local function basic_serialize (o)"
1655 " if type(o) == \"number\" then"
1656 " return tostring(o)"
1658 " return string.format(\"%q\", o)"
1662 " local function serialize (name, value)"
1663 " local rv = name .. ' = '"
1665 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1666 " return rv .. basic_serialize(value) .. ' '"
1667 " elseif type(value) == \"table\" then"
1669 " for k,v in pairs(value) do"
1670 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1671 " rv = rv .. serialize(fieldname, v) .. ' '"
1672 " collectgarbage()" // string concatenation allocates a new string
1675 " elseif type(value) == \"function\" then"
1676 " return rv .. string.format(\"%q\", string.dump(value, true))"
1677 " elseif type(value) == \"boolean\" then"
1678 " return rv .. tostring (value)"
1680 " error('cannot save a ' .. type(value))"
1686 " local save = function ()"
1687 " return (serialize('s', self.script))"
1690 " local restore = function (state)"
1693 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1696 " return { call = call, add = add, get = get,"
1697 " restore = restore, save = save}"
1700 " manager = ScriptManager ()"
1701 " ScriptManager = nil"
1704 lua_State* L = lua.getState();
1707 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1708 lua.do_command ("manager = nil"); // hide it.
1709 lua.do_command ("collectgarbage()");
1711 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1712 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1713 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1714 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1715 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1717 } catch (luabridge::LuaException const& e) {
1718 fatal << string_compose (_("programming error: %1"),
1719 X_("Failed to setup Lua callback interpreter"))
1721 abort(); /*NOTREACHED*/
1724 LuaInstance::register_classes (L);
1726 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1727 lua_setglobal (L, "Editor");
1731 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1733 // TODO consolidate w/ LuaInstance::lua_action()
1735 luabridge::LuaRef ref = (*_lua_get)();
1739 if (!ref["name"].isString()) {
1742 if (!ref["script"].isString()) {
1745 if (!ref["args"].isTable()) {
1750 name = ref["name"].cast<std::string> ();
1751 script = ref["script"].cast<std::string> ();
1754 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1758 args = LuaScriptParams::script_params (lsi, "action_params");
1759 luabridge::LuaRef rargs (ref["args"]);
1760 LuaScriptParams::ref_to_params (args, &rargs);
1762 } catch (luabridge::LuaException const& e) {
1763 cerr << "LuaException:" << e.what () << endl;
1770 LuaCallback::set_session (ARDOUR::Session *s)
1772 SessionHandlePtr::set_session (s);
1778 lua_State* L = lua.getState();
1779 LuaBindings::set_session (L, _session);
1785 LuaCallback::session_going_away ()
1787 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1788 lua.do_command ("collectgarbage();");
1790 SessionHandlePtr::session_going_away ();
1793 drop_callback (); /* EMIT SIGNAL */
1797 LuaCallback::reconnect ()
1799 _connections.drop_connections ();
1800 if ((*_lua_get) ().isNil ()) {
1801 drop_callback (); /* EMIT SIGNAL */
1805 // TODO pass object which emits the signal (e.g region)
1807 // save/load bound objects will be tricky.
1808 // Best idea so far is to save/lookup the PBD::ID
1809 // (either use boost::any indirection or templates for bindable
1810 // object types or a switch statement..)
1812 // _session->route_by_id ()
1813 // _session->track_by_diskstream_id ()
1814 // _session->source_by_id ()
1815 // _session->controllable_by_id ()
1816 // _session->processor_by_id ()
1817 // RegionFactory::region_by_id ()
1819 // TODO loop over objects (if any)
1821 reconnect_object ((void*)0);
1824 template <class T> void
1825 LuaCallback::reconnect_object (T obj)
1827 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1829 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1830 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1831 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1833 # include "luasignal_syms.h"
1835 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1836 abort(); /*NOTREACHED*/
1845 template <typename T, typename S> void
1846 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1848 _connections, invalidator (*this),
1849 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1853 template <typename T, typename C1> void
1854 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1856 _connections, invalidator (*this),
1857 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1861 template <typename T, typename C1, typename C2> void
1862 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1864 _connections, invalidator (*this),
1865 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1869 template <typename T> void
1870 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1873 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1874 if (! rv.cast<bool> ()) {
1878 /* destroy LuaRef ^^ first before calling drop_callback() */
1880 drop_callback (); /* EMIT SIGNAL */
1884 template <typename T, typename C1> void
1885 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1888 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1889 if (! rv.cast<bool> ()) {
1894 drop_callback (); /* EMIT SIGNAL */
1898 template <typename T, typename C1, typename C2> void
1899 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1902 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1903 if (! rv.cast<bool> ()) {
1908 drop_callback (); /* EMIT SIGNAL */