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)
578 .beginClass <AxisView> ("AxisView")
581 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
584 .beginClass <Selectable> ("Selectable")
587 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
590 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
593 .deriveClass <RouteUI, Selectable> ("RouteUI")
596 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
597 .addCast<TimeAxisView> ("to_timeaxisview")
600 // std::list<Selectable*>
601 .beginStdCPtrList <Selectable> ("SelectionList")
604 // std::list<TimeAxisView*>
605 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
609 .beginClass <RegionSelection> ("RegionSelection")
610 .addFunction ("start", &RegionSelection::start)
611 .addFunction ("end_frame", &RegionSelection::end_frame)
612 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
613 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
616 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
617 .addFunction ("start", &TimeSelection::start)
618 .addFunction ("end_frame", &TimeSelection::end_frame)
619 .addFunction ("length", &TimeSelection::length)
622 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
625 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
626 .addFunction ("contains", &TrackViewList::contains)
627 .addFunction ("routelist", &TrackViewList::routelist)
630 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
633 .beginClass <Selection> ("Selection")
634 .addFunction ("clear", &Selection::clear)
635 .addFunction ("clear_all", &Selection::clear_all)
636 .addFunction ("empty", &Selection::empty)
637 .addData ("tracks", &Selection::tracks)
638 .addData ("regions", &Selection::regions)
639 .addData ("time", &Selection::time)
640 .addData ("markers", &Selection::markers)
642 .addData ("lines", &Selection::lines)
643 .addData ("playlists", &Selection::playlists)
644 .addData ("points", &Selection::points)
645 .addData ("midi_regions", &Selection::midi_regions)
646 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
650 .beginClass <PublicEditor> ("Editor")
651 .addFunction ("snap_type", &PublicEditor::snap_type)
652 .addFunction ("snap_mode", &PublicEditor::snap_mode)
653 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
654 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
656 .addFunction ("undo", &PublicEditor::undo)
657 .addFunction ("redo", &PublicEditor::redo)
659 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
660 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
662 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
664 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
665 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
666 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
667 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
669 .addFunction ("get_selection", &PublicEditor::get_selection)
670 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
671 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
673 .addFunction ("set_selection", &PublicEditor::set_selection)
675 .addFunction ("play_selection", &PublicEditor::play_selection)
676 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
677 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
678 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
680 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
681 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
683 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
684 .addFunction ("show_measures", &PublicEditor::show_measures)
685 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
687 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
688 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
690 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
692 .addRefFunction ("do_import", &PublicEditor::do_import)
693 .addRefFunction ("do_embed", &PublicEditor::do_embed)
695 .addFunction ("export_audio", &PublicEditor::export_audio)
696 .addFunction ("stem_export", &PublicEditor::stem_export)
697 .addFunction ("export_selection", &PublicEditor::export_selection)
698 .addFunction ("export_range", &PublicEditor::export_range)
700 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
701 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
702 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
703 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
705 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
706 .addFunction ("new_playlists", &PublicEditor::new_playlists)
707 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
708 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
710 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
711 .addFunction ("deselect_all", &PublicEditor::deselect_all)
713 #if 0 // TimeAxisView& can't be bound (pure virtual fn)
714 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
715 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
716 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
718 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
719 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
721 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
722 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
723 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
724 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
725 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
727 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
728 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
729 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
730 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
731 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
732 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
734 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
735 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
736 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
737 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
739 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
740 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
741 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
743 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
745 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
746 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
747 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
749 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
750 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
752 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
753 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
754 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
755 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
757 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
758 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
759 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
760 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
763 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
764 .addFunction ("drags", &PublicEditor::drags)
767 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
768 .addFunction ("get_track_views", &PublicEditor::get_track_views)
769 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
770 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
772 .addFunction ("center_screen", &PublicEditor::center_screen)
774 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
775 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
777 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
778 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
779 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
781 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
782 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
783 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
784 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
785 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
789 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
790 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
791 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
792 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
795 .addFunction ("access_action", &PublicEditor::access_action)
799 .beginNamespace ("MarkerType")
800 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
801 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
802 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
803 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
804 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
805 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
806 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
807 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
808 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
809 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
810 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
813 .beginNamespace ("SelectionOp")
814 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
815 .addConst ("Set", Selection::Operation(Selection::Set))
816 .addConst ("Extend", Selection::Operation(Selection::Extend))
817 .addConst ("Add", Selection::Operation(Selection::Add))
820 .endNamespace (); // end ArdourUI
828 #undef DISPLAYCONTROL
830 #undef IMPORTPOSITION
831 #undef IMPORTDISPOSITION
833 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
834 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
835 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
836 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
837 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
838 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
839 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
840 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
841 luabridge::getGlobalNamespace (L)
842 .beginNamespace ("Editing")
843 # include "editing_syms.h"
850 ////////////////////////////////////////////////////////////////////////////////
852 using namespace ARDOUR;
853 using namespace ARDOUR_UI_UTILS;
857 static void _lua_print (std::string s) {
859 std::cout << "LuaInstance: " << s << "\n";
861 PBD::info << "LuaInstance: " << s << endmsg;
864 LuaInstance* LuaInstance::_instance = 0;
867 LuaInstance::instance ()
870 _instance = new LuaInstance;
877 LuaInstance::destroy_instance ()
883 LuaInstance::LuaInstance ()
885 lua.Print.connect (&_lua_print);
888 LuaScriptParamList args;
891 LuaInstance::~LuaInstance ()
893 delete _lua_call_action;
894 delete _lua_render_icon;
895 delete _lua_add_action;
896 delete _lua_del_action;
897 delete _lua_get_action;
909 "function ScriptManager ()"
910 " local self = { scripts = {}, instances = {}, icons = {} }"
912 " local remove = function (id)"
913 " self.scripts[id] = nil"
914 " self.instances[id] = nil"
915 " self.icons[id] = nil"
918 " local addinternal = function (i, n, s, f, c, a)"
919 " assert(type(i) == 'number', 'id must be numeric')"
920 " assert(type(n) == 'string', 'Name must be string')"
921 " assert(type(s) == 'string', 'Script must be string')"
922 " assert(type(f) == 'function', 'Factory is a not a function')"
923 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
924 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
925 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
926 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
927 " if type(c) == 'function' then"
928 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
930 " self.icons[i] = nil"
934 " local call = function (id)"
935 " if type(self.instances[id]) == 'function' then"
936 " local status, err = pcall (self.instances[id])"
937 " if not status then"
938 " print ('action \"'.. id .. '\": ', err)" // error out
945 " local icon = function (id, ...)"
946 " if type(self.icons[id]) == 'function' then"
947 " pcall (self.icons[id], ...)"
952 " local add = function (i, n, s, b, c, a)"
953 " assert(type(b) == 'string', 'ByteCode must be string')"
954 " f = nil load (b)()" // assigns f
955 " icn = nil load (c)()" // may assign "icn"
956 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
957 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
960 " local get = function (id)"
961 " if type(self.scripts[id]) == 'table' then"
962 " return { ['name'] = self.scripts[id]['n'],"
963 " ['script'] = self.scripts[id]['s'],"
964 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
965 " ['args'] = self.scripts[id]['a'] }"
970 " local function basic_serialize (o)"
971 " if type(o) == \"number\" then"
972 " return tostring(o)"
974 " return string.format(\"%q\", o)"
978 " local function serialize (name, value)"
979 " local rv = name .. ' = '"
981 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
982 " return rv .. basic_serialize(value) .. ' '"
983 " elseif type(value) == \"table\" then"
985 " for k,v in pairs(value) do"
986 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
987 " rv = rv .. serialize(fieldname, v) .. ' '"
988 " collectgarbage()" // string concatenation allocates a new string
991 " elseif type(value) == \"function\" then"
992 " return rv .. string.format(\"%q\", string.dump(value, true))"
993 " elseif type(value) == \"boolean\" then"
994 " return rv .. tostring (value)"
996 " error('cannot save a ' .. type(value))"
1001 " local save = function ()"
1002 " return (serialize('scripts', self.scripts))"
1005 " local clear = function ()"
1006 " self.scripts = {}"
1007 " self.instances = {}"
1012 " local restore = function (state)"
1015 " for i, s in pairs (scripts) do"
1016 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1021 " return { call = call, add = add, remove = remove, get = get,"
1022 " restore = restore, save = save, clear = clear, icon = icon}"
1025 " manager = ScriptManager ()"
1026 " ScriptManager = nil"
1029 lua_State* L = lua.getState();
1032 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1033 lua.do_command ("manager = nil"); // hide it.
1034 lua.do_command ("collectgarbage()");
1036 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1037 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1038 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1039 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1040 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1041 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1042 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1043 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1045 } catch (luabridge::LuaException const& e) {
1046 fatal << string_compose (_("programming error: %1"),
1047 X_("Failed to setup Lua action interpreter"))
1049 abort(); /*NOTREACHED*/
1052 register_classes (L);
1054 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1055 lua_setglobal (L, "Editor");
1058 void LuaInstance::set_session (Session* s)
1060 SessionHandlePtr::set_session (s);
1065 lua_State* L = lua.getState();
1066 LuaBindings::set_session (L, _session);
1068 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1069 i->second->set_session (s);
1071 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1075 LuaInstance::session_going_away ()
1077 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1078 point_one_second_connection.disconnect ();
1081 for (int i = 0; i < 9; ++i) {
1082 ActionChanged (i, ""); /* EMIT SIGNAL */
1084 SessionHandlePtr::session_going_away ();
1087 lua_State* L = lua.getState();
1088 LuaBindings::set_session (L, _session);
1089 lua.do_command ("collectgarbage();");
1093 LuaInstance::every_point_one_seconds ()
1095 LuaTimerDS (); // emit signal
1099 LuaInstance::set_state (const XMLNode& node)
1104 if ((child = find_named_node (node, "ActionScript"))) {
1105 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1106 if (!(*n)->is_content ()) { continue; }
1108 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1110 (*_lua_load)(std::string ((const char*)buf, size));
1111 } catch (luabridge::LuaException const& e) {
1112 cerr << "LuaException:" << e.what () << endl;
1114 for (int i = 0; i < 9; ++i) {
1116 if (lua_action_name (i, name)) {
1117 ActionChanged (i, name); /* EMIT SIGNAL */
1124 if ((child = find_named_node (node, "ActionHooks"))) {
1125 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1127 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1128 _callbacks.insert (std::make_pair(p->id(), p));
1129 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1130 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1131 } catch (luabridge::LuaException const& e) {
1132 cerr << "LuaException:" << e.what () << endl;
1141 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1144 std::string param_function = "action_params";
1145 std::vector<std::string> reg;
1148 case LuaScriptInfo::EditorAction:
1149 reg = lua_action_names ();
1150 title = _("Add Lua Action");
1152 case LuaScriptInfo::EditorHook:
1153 reg = lua_slot_names ();
1154 title = _("Add Lua Callback Hook");
1156 case LuaScriptInfo::Session:
1160 reg = _session->registered_lua_functions ();
1161 title = _("Add Lua Session Script");
1162 param_function = "sess_params";
1168 LuaScriptInfoPtr spi;
1169 ScriptSelector ss (title, type);
1170 switch (ss.run ()) {
1171 case Gtk::RESPONSE_ACCEPT:
1179 std::string script = "";
1182 script = Glib::file_get_contents (spi->path);
1183 } catch (Glib::FileError e) {
1184 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1185 Gtk::MessageDialog am (msg);
1190 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1192 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1193 switch (spd.run ()) {
1194 case Gtk::RESPONSE_ACCEPT:
1201 case LuaScriptInfo::EditorAction:
1202 return set_lua_action (id, spd.name(), script, lsp);
1204 case LuaScriptInfo::EditorHook:
1205 return register_lua_slot (spd.name(), script, lsp);
1207 case LuaScriptInfo::Session:
1209 _session->register_lua_function (spd.name(), script, lsp);
1210 } catch (luabridge::LuaException const& e) {
1211 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1212 Gtk::MessageDialog am (msg);
1214 } catch (SessionException e) {
1215 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1216 Gtk::MessageDialog am (msg);
1226 LuaInstance::get_action_state ()
1231 luabridge::LuaRef savedstate ((*_lua_save)());
1232 saved = savedstate.cast<std::string>();
1234 lua.collect_garbage ();
1236 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1237 std::string b64s (b64);
1240 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1241 script_node->add_property (X_("lua"), LUA_VERSION);
1242 script_node->add_content (b64s);
1244 return *script_node;
1248 LuaInstance::get_hook_state ()
1250 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1251 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1252 script_node->add_child_nocopy (i->second->get_state ());
1254 return *script_node;
1258 LuaInstance::call_action (const int id)
1261 (*_lua_call_action)(id + 1);
1262 lua.collect_garbage_step ();
1263 } catch (luabridge::LuaException const& e) {
1264 cerr << "LuaException:" << e.what () << endl;
1269 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1270 int ii = reinterpret_cast<uintptr_t> (i);
1271 instance()->render_icon (ii, cr, w, h, c);
1275 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1277 Cairo::Context ctx (cr);
1279 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1280 } catch (luabridge::LuaException const& e) {
1281 cerr << "LuaException:" << e.what () << endl;
1286 LuaInstance::set_lua_action (
1288 const std::string& name,
1289 const std::string& script,
1290 const LuaScriptParamList& args)
1293 lua_State* L = lua.getState();
1294 // get bytcode of factory-function in a sandbox
1295 // (don't allow scripts to interfere)
1296 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1297 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1298 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1299 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1300 if ((*i)->optional && !(*i)->is_set) { continue; }
1301 tbl_arg[(*i)->name] = (*i)->value;
1303 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1304 ActionChanged (id, name); /* EMIT SIGNAL */
1305 } catch (luabridge::LuaException const& e) {
1306 cerr << "LuaException:" << e.what () << endl;
1309 _session->set_dirty ();
1314 LuaInstance::remove_lua_action (const int id)
1317 (*_lua_del_action)(id + 1);
1318 } catch (luabridge::LuaException const& e) {
1319 cerr << "LuaException:" << e.what () << endl;
1322 ActionChanged (id, ""); /* EMIT SIGNAL */
1323 _session->set_dirty ();
1328 LuaInstance::lua_action_name (const int id, std::string& rv)
1331 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1335 if (ref["name"].isString()) {
1336 rv = ref["name"].cast<std::string>();
1340 } catch (luabridge::LuaException const& e) {
1341 cerr << "LuaException:" << e.what () << endl;
1347 std::vector<std::string>
1348 LuaInstance::lua_action_names ()
1350 std::vector<std::string> rv;
1351 for (int i = 0; i < 9; ++i) {
1353 if (lua_action_name (i, name)) {
1354 rv.push_back (name);
1361 LuaInstance::lua_action_has_icon (const int id)
1364 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1368 if (ref["icon"].isBoolean()) {
1369 return ref["icon"].cast<bool>();
1371 } catch (luabridge::LuaException const& e) {
1372 cerr << "LuaException:" << e.what () << endl;
1378 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1381 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1385 if (!ref["name"].isString()) {
1388 if (!ref["script"].isString()) {
1391 if (!ref["args"].isTable()) {
1394 name = ref["name"].cast<std::string>();
1395 script = ref["script"].cast<std::string>();
1398 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1402 args = LuaScriptParams::script_params (lsi, "action_params");
1403 luabridge::LuaRef rargs (ref["args"]);
1404 LuaScriptParams::ref_to_params (args, &rargs);
1406 } catch (luabridge::LuaException const& e) {
1407 cerr << "LuaException:" << e.what () << endl;
1414 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1416 /* parse script, get ActionHook(s) from script */
1420 l.Print.connect (&_lua_print);
1421 lua_State* L = l.getState();
1423 l.do_command ("function ardour () end");
1424 l.do_command (script);
1425 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1426 if (signals.isFunction()) {
1429 } catch (luabridge::LuaException const& e) {
1430 cerr << "LuaException:" << e.what () << endl;
1434 cerr << "Script registered no hooks." << endl;
1438 /* register script w/args, get entry-point / ID */
1441 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1442 _callbacks.insert (std::make_pair(p->id(), p));
1443 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1444 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1446 } catch (luabridge::LuaException const& e) {
1447 cerr << "LuaException:" << e.what () << endl;
1449 _session->set_dirty ();
1454 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1456 LuaCallbackMap::iterator i = _callbacks.find (id);
1457 if (i != _callbacks.end()) {
1458 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1459 _callbacks.erase (i);
1462 _session->set_dirty ();
1466 std::vector<PBD::ID>
1467 LuaInstance::lua_slots () const
1469 std::vector<PBD::ID> rv;
1470 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1471 rv.push_back (i->first);
1477 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1479 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1480 if (i != _callbacks.end()) {
1481 name = i->second->name();
1487 std::vector<std::string>
1488 LuaInstance::lua_slot_names () const
1490 std::vector<std::string> rv;
1491 std::vector<PBD::ID> ids = lua_slots();
1492 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1494 if (lua_slot_name (*i, name)) {
1495 rv.push_back (name);
1502 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1504 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1505 if (i == _callbacks.end()) {
1506 return false; // error
1508 return i->second->lua_slot (name, script, ah, args);
1511 ///////////////////////////////////////////////////////////////////////////////
1513 LuaCallback::LuaCallback (Session *s,
1514 const std::string& name,
1515 const std::string& script,
1516 const ActionHook& ah,
1517 const ARDOUR::LuaScriptParamList& args)
1518 : SessionHandlePtr (s)
1523 // TODO: allow to reference object (e.g region)
1526 lua_State* L = lua.getState();
1527 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1528 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1529 if ((*i)->optional && !(*i)->is_set) { continue; }
1530 tbl_arg[(*i)->name] = (*i)->value;
1534 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1535 (*_lua_add)(name, script, bytecode, tbl_arg);
1536 } catch (luabridge::LuaException const& e) {
1537 cerr << "LuaException:" << e.what () << endl;
1538 throw failed_constructor ();
1545 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1546 : SessionHandlePtr (s)
1548 XMLNode* child = NULL;
1549 if (node.name() != X_("LuaCallback")
1550 || !node.property ("signals")
1551 || !node.property ("id")
1552 || !node.property ("name")) {
1553 throw failed_constructor ();
1556 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1557 if (!(*n)->is_content ()) { continue; }
1562 throw failed_constructor ();
1567 _id = PBD::ID (node.property ("id")->value ());
1568 _name = node.property ("name")->value ();
1569 _signals = ActionHook (node.property ("signals")->value ());
1572 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1574 (*_lua_load)(std::string ((const char*)buf, size));
1575 } catch (luabridge::LuaException const& e) {
1576 cerr << "LuaException:" << e.what () << endl;
1583 LuaCallback::~LuaCallback ()
1593 LuaCallback::get_state (void)
1597 luabridge::LuaRef savedstate ((*_lua_save)());
1598 saved = savedstate.cast<std::string>();
1600 lua.collect_garbage ();
1602 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1603 std::string b64s (b64);
1606 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1607 script_node->add_property (X_("lua"), LUA_VERSION);
1608 script_node->add_property (X_("id"), _id.to_s ());
1609 script_node->add_property (X_("name"), _name);
1610 script_node->add_property (X_("signals"), _signals.to_string ());
1611 script_node->add_content (b64s);
1612 return *script_node;
1616 LuaCallback::init (void)
1618 lua.Print.connect (&_lua_print);
1621 "function ScriptManager ()"
1622 " local self = { script = {}, instance = {} }"
1624 " local addinternal = function (n, s, f, a)"
1625 " assert(type(n) == 'string', 'Name must be string')"
1626 " assert(type(s) == 'string', 'Script must be string')"
1627 " assert(type(f) == 'function', 'Factory is a not a function')"
1628 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1629 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1630 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1631 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1634 " local call = function (...)"
1635 " if type(self.instance) == 'function' then"
1636 " local status, err = pcall (self.instance, ...)"
1637 " if not status then"
1638 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1639 " self.script = nil"
1640 " self.instance = nil"
1648 " local add = function (n, s, b, a)"
1649 " assert(type(b) == 'string', 'ByteCode must be string')"
1650 " load (b)()" // assigns f
1651 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1652 " addinternal (n, s, load(f), a)"
1655 " local get = function ()"
1656 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1657 " return { ['name'] = self.script['n'],"
1658 " ['script'] = self.script['s'],"
1659 " ['args'] = self.script['a'] }"
1666 " local function basic_serialize (o)"
1667 " if type(o) == \"number\" then"
1668 " return tostring(o)"
1670 " return string.format(\"%q\", o)"
1674 " local function serialize (name, value)"
1675 " local rv = name .. ' = '"
1677 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1678 " return rv .. basic_serialize(value) .. ' '"
1679 " elseif type(value) == \"table\" then"
1681 " for k,v in pairs(value) do"
1682 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1683 " rv = rv .. serialize(fieldname, v) .. ' '"
1684 " collectgarbage()" // string concatenation allocates a new string
1687 " elseif type(value) == \"function\" then"
1688 " return rv .. string.format(\"%q\", string.dump(value, true))"
1689 " elseif type(value) == \"boolean\" then"
1690 " return rv .. tostring (value)"
1692 " error('cannot save a ' .. type(value))"
1698 " local save = function ()"
1699 " return (serialize('s', self.script))"
1702 " local restore = function (state)"
1705 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1708 " return { call = call, add = add, get = get,"
1709 " restore = restore, save = save}"
1712 " manager = ScriptManager ()"
1713 " ScriptManager = nil"
1716 lua_State* L = lua.getState();
1719 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1720 lua.do_command ("manager = nil"); // hide it.
1721 lua.do_command ("collectgarbage()");
1723 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1724 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1725 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1726 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1727 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1729 } catch (luabridge::LuaException const& e) {
1730 fatal << string_compose (_("programming error: %1"),
1731 X_("Failed to setup Lua callback interpreter"))
1733 abort(); /*NOTREACHED*/
1736 LuaInstance::register_classes (L);
1738 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1739 lua_setglobal (L, "Editor");
1743 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1745 // TODO consolidate w/ LuaInstance::lua_action()
1747 luabridge::LuaRef ref = (*_lua_get)();
1751 if (!ref["name"].isString()) {
1754 if (!ref["script"].isString()) {
1757 if (!ref["args"].isTable()) {
1762 name = ref["name"].cast<std::string> ();
1763 script = ref["script"].cast<std::string> ();
1766 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1770 args = LuaScriptParams::script_params (lsi, "action_params");
1771 luabridge::LuaRef rargs (ref["args"]);
1772 LuaScriptParams::ref_to_params (args, &rargs);
1774 } catch (luabridge::LuaException const& e) {
1775 cerr << "LuaException:" << e.what () << endl;
1782 LuaCallback::set_session (ARDOUR::Session *s)
1784 SessionHandlePtr::set_session (s);
1790 lua_State* L = lua.getState();
1791 LuaBindings::set_session (L, _session);
1797 LuaCallback::session_going_away ()
1799 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1800 lua.do_command ("collectgarbage();");
1802 SessionHandlePtr::session_going_away ();
1805 drop_callback (); /* EMIT SIGNAL */
1809 LuaCallback::reconnect ()
1811 _connections.drop_connections ();
1812 if ((*_lua_get) ().isNil ()) {
1813 drop_callback (); /* EMIT SIGNAL */
1817 // TODO pass object which emits the signal (e.g region)
1819 // save/load bound objects will be tricky.
1820 // Best idea so far is to save/lookup the PBD::ID
1821 // (either use boost::any indirection or templates for bindable
1822 // object types or a switch statement..)
1824 // _session->route_by_id ()
1825 // _session->track_by_diskstream_id ()
1826 // _session->source_by_id ()
1827 // _session->controllable_by_id ()
1828 // _session->processor_by_id ()
1829 // RegionFactory::region_by_id ()
1831 // TODO loop over objects (if any)
1833 reconnect_object ((void*)0);
1836 template <class T> void
1837 LuaCallback::reconnect_object (T obj)
1839 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1841 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1842 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1843 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1845 # include "luasignal_syms.h"
1847 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1848 abort(); /*NOTREACHED*/
1857 template <typename T, typename S> void
1858 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1860 _connections, invalidator (*this),
1861 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1865 template <typename T, typename C1> void
1866 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1868 _connections, invalidator (*this),
1869 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1873 template <typename T, typename C1, typename C2> void
1874 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1876 _connections, invalidator (*this),
1877 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1881 template <typename T> void
1882 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1885 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1886 if (! rv.cast<bool> ()) {
1890 /* destroy LuaRef ^^ first before calling drop_callback() */
1892 drop_callback (); /* EMIT SIGNAL */
1896 template <typename T, typename C1> void
1897 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1900 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1901 if (! rv.cast<bool> ()) {
1906 drop_callback (); /* EMIT SIGNAL */
1910 template <typename T, typename C1, typename C2> void
1911 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1914 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1915 if (! rv.cast<bool> ()) {
1920 drop_callback (); /* EMIT SIGNAL */