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 .beginStdCPtrList <Selectable> ("SelectionList")
603 .beginClass <RegionSelection> ("RegionSelection")
604 .addFunction ("start", &RegionSelection::start)
605 .addFunction ("end_frame", &RegionSelection::end_frame)
606 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
607 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
610 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
611 .addFunction ("start", &TimeSelection::start)
612 .addFunction ("end_frame", &TimeSelection::end_frame)
613 .addFunction ("length", &TimeSelection::length)
616 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
619 .beginClass <TrackViewList> ("TrackViewList")
620 .addFunction ("routelist", &TrackViewList::routelist) // XXX check windows binding (libardour)
623 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
626 .beginClass <Selection> ("Selection")
627 .addFunction ("clear", &Selection::clear)
628 .addFunction ("clear_all", &Selection::clear_all)
629 .addFunction ("empty", &Selection::empty)
630 .addData ("tracks", &Selection::tracks)
631 .addData ("regions", &Selection::regions)
632 .addData ("time", &Selection::time)
633 .addData ("markers", &Selection::markers)
635 .addData ("lines", &Selection::lines)
636 .addData ("playlists", &Selection::playlists)
637 .addData ("points", &Selection::points)
638 .addData ("midi_regions", &Selection::midi_regions)
639 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
643 .beginClass <PublicEditor> ("Editor")
644 .addFunction ("snap_type", &PublicEditor::snap_type)
645 .addFunction ("snap_mode", &PublicEditor::snap_mode)
646 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
647 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
649 .addFunction ("undo", &PublicEditor::undo)
650 .addFunction ("redo", &PublicEditor::redo)
652 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
653 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
655 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
657 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
658 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
659 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
660 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
662 .addFunction ("get_selection", &PublicEditor::get_selection)
663 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
664 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
666 .addFunction ("set_selection", &PublicEditor::set_selection)
668 .addFunction ("play_selection", &PublicEditor::play_selection)
669 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
670 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
671 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
673 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
674 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
676 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
677 .addFunction ("show_measures", &PublicEditor::show_measures)
678 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
680 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
681 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
683 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
685 .addRefFunction ("do_import", &PublicEditor::do_import)
686 .addRefFunction ("do_embed", &PublicEditor::do_embed)
688 .addFunction ("export_audio", &PublicEditor::export_audio)
689 .addFunction ("stem_export", &PublicEditor::stem_export)
690 .addFunction ("export_selection", &PublicEditor::export_selection)
691 .addFunction ("export_range", &PublicEditor::export_range)
693 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
694 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
695 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
696 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
698 #if 0 // These need TimeAxisView* which isn't exposed, yet
699 .addFunction ("playlist_selector", &PublicEditor::playlist_selector)
700 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
701 .addFunction ("new_playlists", &PublicEditor::new_playlists)
702 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
703 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
706 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
707 .addFunction ("deselect_all", &PublicEditor::deselect_all)
709 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
710 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
711 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
714 .addFunction ("get_regionview_from_region", &PublicEditor::get_regionview_from_region)
715 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
716 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
717 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
718 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
720 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
721 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
722 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
723 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
724 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
725 //.addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
726 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
728 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
729 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
730 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
731 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
733 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
734 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
735 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
737 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
739 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
740 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
741 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
743 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
744 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
746 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
747 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
748 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
749 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
751 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
752 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
753 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
754 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
757 .addFunction ("get_route_view_by_route_id", &PublicEditor::get_route_view_by_route_id)
758 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
760 .addFunction ("axis_view_from_route", &PublicEditor::axis_view_from_route)
761 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
762 .addFunction ("get_track_views", &PublicEditor::get_track_views)
763 .addFunction ("drags", &PublicEditor::drags)
766 .addFunction ("center_screen", &PublicEditor::center_screen)
768 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
769 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
771 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
772 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
773 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
775 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
776 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
777 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
778 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
779 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
783 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
784 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
785 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
786 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
789 .addFunction ("access_action", &PublicEditor::access_action)
793 .beginNamespace ("MarkerType")
794 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
795 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
796 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
797 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
798 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
799 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
800 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
801 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
802 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
803 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
804 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
807 .beginNamespace ("SelectionOp")
808 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
809 .addConst ("Set", Selection::Operation(Selection::Set))
810 .addConst ("Extend", Selection::Operation(Selection::Extend))
811 .addConst ("Add", Selection::Operation(Selection::Add))
814 .endNamespace (); // end ArdourUI
822 #undef DISPLAYCONTROL
824 #undef IMPORTPOSITION
825 #undef IMPORTDISPOSITION
827 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
828 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
829 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
830 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
831 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
832 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
833 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
834 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
835 luabridge::getGlobalNamespace (L)
836 .beginNamespace ("Editing")
837 # include "editing_syms.h"
844 ////////////////////////////////////////////////////////////////////////////////
846 using namespace ARDOUR;
847 using namespace ARDOUR_UI_UTILS;
851 static void _lua_print (std::string s) {
853 std::cout << "LuaInstance: " << s << "\n";
855 PBD::info << "LuaInstance: " << s << endmsg;
858 LuaInstance* LuaInstance::_instance = 0;
861 LuaInstance::instance ()
864 _instance = new LuaInstance;
871 LuaInstance::destroy_instance ()
877 LuaInstance::LuaInstance ()
879 lua.Print.connect (&_lua_print);
882 LuaScriptParamList args;
885 LuaInstance::~LuaInstance ()
887 delete _lua_call_action;
888 delete _lua_render_icon;
889 delete _lua_add_action;
890 delete _lua_del_action;
891 delete _lua_get_action;
903 "function ScriptManager ()"
904 " local self = { scripts = {}, instances = {}, icons = {} }"
906 " local remove = function (id)"
907 " self.scripts[id] = nil"
908 " self.instances[id] = nil"
909 " self.icons[id] = nil"
912 " local addinternal = function (i, n, s, f, c, a)"
913 " assert(type(i) == 'number', 'id must be numeric')"
914 " assert(type(n) == 'string', 'Name must be string')"
915 " assert(type(s) == 'string', 'Script must be string')"
916 " assert(type(f) == 'function', 'Factory is a not a function')"
917 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
918 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
919 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
920 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
921 " if type(c) == 'function' then"
922 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
924 " self.icons[i] = nil"
928 " local call = function (id)"
929 " if type(self.instances[id]) == 'function' then"
930 " local status, err = pcall (self.instances[id])"
931 " if not status then"
932 " print ('action \"'.. id .. '\": ', err)" // error out
939 " local icon = function (id, ...)"
940 " if type(self.icons[id]) == 'function' then"
941 " pcall (self.icons[id], ...)"
946 " local add = function (i, n, s, b, c, a)"
947 " assert(type(b) == 'string', 'ByteCode must be string')"
948 " f = nil load (b)()" // assigns f
949 " icn = nil load (c)()" // may assign "icn"
950 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
951 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
954 " local get = function (id)"
955 " if type(self.scripts[id]) == 'table' then"
956 " return { ['name'] = self.scripts[id]['n'],"
957 " ['script'] = self.scripts[id]['s'],"
958 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
959 " ['args'] = self.scripts[id]['a'] }"
964 " local function basic_serialize (o)"
965 " if type(o) == \"number\" then"
966 " return tostring(o)"
968 " return string.format(\"%q\", o)"
972 " local function serialize (name, value)"
973 " local rv = name .. ' = '"
975 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
976 " return rv .. basic_serialize(value) .. ' '"
977 " elseif type(value) == \"table\" then"
979 " for k,v in pairs(value) do"
980 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
981 " rv = rv .. serialize(fieldname, v) .. ' '"
982 " collectgarbage()" // string concatenation allocates a new string
985 " elseif type(value) == \"function\" then"
986 " return rv .. string.format(\"%q\", string.dump(value, true))"
987 " elseif type(value) == \"boolean\" then"
988 " return rv .. tostring (value)"
990 " error('cannot save a ' .. type(value))"
995 " local save = function ()"
996 " return (serialize('scripts', self.scripts))"
999 " local clear = function ()"
1000 " self.scripts = {}"
1001 " self.instances = {}"
1006 " local restore = function (state)"
1009 " for i, s in pairs (scripts) do"
1010 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1015 " return { call = call, add = add, remove = remove, get = get,"
1016 " restore = restore, save = save, clear = clear, icon = icon}"
1019 " manager = ScriptManager ()"
1020 " ScriptManager = nil"
1023 lua_State* L = lua.getState();
1026 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1027 lua.do_command ("manager = nil"); // hide it.
1028 lua.do_command ("collectgarbage()");
1030 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1031 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1032 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1033 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1034 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1035 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1036 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1037 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1039 } catch (luabridge::LuaException const& e) {
1040 fatal << string_compose (_("programming error: %1"),
1041 X_("Failed to setup Lua action interpreter"))
1043 abort(); /*NOTREACHED*/
1046 register_classes (L);
1048 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1049 lua_setglobal (L, "Editor");
1052 void LuaInstance::set_session (Session* s)
1054 SessionHandlePtr::set_session (s);
1059 lua_State* L = lua.getState();
1060 LuaBindings::set_session (L, _session);
1062 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1063 i->second->set_session (s);
1065 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1069 LuaInstance::session_going_away ()
1071 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1072 point_one_second_connection.disconnect ();
1075 for (int i = 0; i < 9; ++i) {
1076 ActionChanged (i, ""); /* EMIT SIGNAL */
1078 SessionHandlePtr::session_going_away ();
1081 lua_State* L = lua.getState();
1082 LuaBindings::set_session (L, _session);
1083 lua.do_command ("collectgarbage();");
1087 LuaInstance::every_point_one_seconds ()
1089 LuaTimerDS (); // emit signal
1093 LuaInstance::set_state (const XMLNode& node)
1098 if ((child = find_named_node (node, "ActionScript"))) {
1099 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1100 if (!(*n)->is_content ()) { continue; }
1102 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1104 (*_lua_load)(std::string ((const char*)buf, size));
1105 } catch (luabridge::LuaException const& e) {
1106 cerr << "LuaException:" << e.what () << endl;
1108 for (int i = 0; i < 9; ++i) {
1110 if (lua_action_name (i, name)) {
1111 ActionChanged (i, name); /* EMIT SIGNAL */
1118 if ((child = find_named_node (node, "ActionHooks"))) {
1119 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1121 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1122 _callbacks.insert (std::make_pair(p->id(), p));
1123 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1124 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1125 } catch (luabridge::LuaException const& e) {
1126 cerr << "LuaException:" << e.what () << endl;
1135 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1138 std::string param_function = "action_params";
1139 std::vector<std::string> reg;
1142 case LuaScriptInfo::EditorAction:
1143 reg = lua_action_names ();
1144 title = _("Add Lua Action");
1146 case LuaScriptInfo::EditorHook:
1147 reg = lua_slot_names ();
1148 title = _("Add Lua Callback Hook");
1150 case LuaScriptInfo::Session:
1154 reg = _session->registered_lua_functions ();
1155 title = _("Add Lua Session Script");
1156 param_function = "sess_params";
1162 LuaScriptInfoPtr spi;
1163 ScriptSelector ss (title, type);
1164 switch (ss.run ()) {
1165 case Gtk::RESPONSE_ACCEPT:
1173 std::string script = "";
1176 script = Glib::file_get_contents (spi->path);
1177 } catch (Glib::FileError e) {
1178 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1179 Gtk::MessageDialog am (msg);
1184 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1186 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1187 switch (spd.run ()) {
1188 case Gtk::RESPONSE_ACCEPT:
1195 case LuaScriptInfo::EditorAction:
1196 return set_lua_action (id, spd.name(), script, lsp);
1198 case LuaScriptInfo::EditorHook:
1199 return register_lua_slot (spd.name(), script, lsp);
1201 case LuaScriptInfo::Session:
1203 _session->register_lua_function (spd.name(), script, lsp);
1204 } catch (luabridge::LuaException const& e) {
1205 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1206 Gtk::MessageDialog am (msg);
1208 } catch (SessionException e) {
1209 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1210 Gtk::MessageDialog am (msg);
1220 LuaInstance::get_action_state ()
1225 luabridge::LuaRef savedstate ((*_lua_save)());
1226 saved = savedstate.cast<std::string>();
1228 lua.collect_garbage ();
1230 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1231 std::string b64s (b64);
1234 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1235 script_node->add_property (X_("lua"), LUA_VERSION);
1236 script_node->add_content (b64s);
1238 return *script_node;
1242 LuaInstance::get_hook_state ()
1244 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1245 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1246 script_node->add_child_nocopy (i->second->get_state ());
1248 return *script_node;
1252 LuaInstance::call_action (const int id)
1255 (*_lua_call_action)(id + 1);
1256 lua.collect_garbage_step ();
1257 } catch (luabridge::LuaException const& e) {
1258 cerr << "LuaException:" << e.what () << endl;
1263 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1264 int ii = reinterpret_cast<uintptr_t> (i);
1265 instance()->render_icon (ii, cr, w, h, c);
1269 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1271 Cairo::Context ctx (cr);
1273 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1274 } catch (luabridge::LuaException const& e) {
1275 cerr << "LuaException:" << e.what () << endl;
1280 LuaInstance::set_lua_action (
1282 const std::string& name,
1283 const std::string& script,
1284 const LuaScriptParamList& args)
1287 lua_State* L = lua.getState();
1288 // get bytcode of factory-function in a sandbox
1289 // (don't allow scripts to interfere)
1290 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1291 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1292 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1293 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1294 if ((*i)->optional && !(*i)->is_set) { continue; }
1295 tbl_arg[(*i)->name] = (*i)->value;
1297 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1298 ActionChanged (id, name); /* EMIT SIGNAL */
1299 } catch (luabridge::LuaException const& e) {
1300 cerr << "LuaException:" << e.what () << endl;
1303 _session->set_dirty ();
1308 LuaInstance::remove_lua_action (const int id)
1311 (*_lua_del_action)(id + 1);
1312 } catch (luabridge::LuaException const& e) {
1313 cerr << "LuaException:" << e.what () << endl;
1316 ActionChanged (id, ""); /* EMIT SIGNAL */
1317 _session->set_dirty ();
1322 LuaInstance::lua_action_name (const int id, std::string& rv)
1325 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1329 if (ref["name"].isString()) {
1330 rv = ref["name"].cast<std::string>();
1334 } catch (luabridge::LuaException const& e) {
1335 cerr << "LuaException:" << e.what () << endl;
1341 std::vector<std::string>
1342 LuaInstance::lua_action_names ()
1344 std::vector<std::string> rv;
1345 for (int i = 0; i < 9; ++i) {
1347 if (lua_action_name (i, name)) {
1348 rv.push_back (name);
1355 LuaInstance::lua_action_has_icon (const int id)
1358 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1362 if (ref["icon"].isBoolean()) {
1363 return ref["icon"].cast<bool>();
1365 } catch (luabridge::LuaException const& e) {
1366 cerr << "LuaException:" << e.what () << endl;
1372 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1375 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1379 if (!ref["name"].isString()) {
1382 if (!ref["script"].isString()) {
1385 if (!ref["args"].isTable()) {
1388 name = ref["name"].cast<std::string>();
1389 script = ref["script"].cast<std::string>();
1392 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1396 args = LuaScriptParams::script_params (lsi, "action_params");
1397 luabridge::LuaRef rargs (ref["args"]);
1398 LuaScriptParams::ref_to_params (args, &rargs);
1400 } catch (luabridge::LuaException const& e) {
1401 cerr << "LuaException:" << e.what () << endl;
1408 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1410 /* parse script, get ActionHook(s) from script */
1414 l.Print.connect (&_lua_print);
1415 lua_State* L = l.getState();
1417 l.do_command ("function ardour () end");
1418 l.do_command (script);
1419 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1420 if (signals.isFunction()) {
1423 } catch (luabridge::LuaException const& e) {
1424 cerr << "LuaException:" << e.what () << endl;
1428 cerr << "Script registered no hooks." << endl;
1432 /* register script w/args, get entry-point / ID */
1435 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1436 _callbacks.insert (std::make_pair(p->id(), p));
1437 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1438 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1440 } catch (luabridge::LuaException const& e) {
1441 cerr << "LuaException:" << e.what () << endl;
1443 _session->set_dirty ();
1448 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1450 LuaCallbackMap::iterator i = _callbacks.find (id);
1451 if (i != _callbacks.end()) {
1452 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1453 _callbacks.erase (i);
1456 _session->set_dirty ();
1460 std::vector<PBD::ID>
1461 LuaInstance::lua_slots () const
1463 std::vector<PBD::ID> rv;
1464 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1465 rv.push_back (i->first);
1471 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1473 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1474 if (i != _callbacks.end()) {
1475 name = i->second->name();
1481 std::vector<std::string>
1482 LuaInstance::lua_slot_names () const
1484 std::vector<std::string> rv;
1485 std::vector<PBD::ID> ids = lua_slots();
1486 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1488 if (lua_slot_name (*i, name)) {
1489 rv.push_back (name);
1496 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1498 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1499 if (i == _callbacks.end()) {
1500 return false; // error
1502 return i->second->lua_slot (name, script, ah, args);
1505 ///////////////////////////////////////////////////////////////////////////////
1507 LuaCallback::LuaCallback (Session *s,
1508 const std::string& name,
1509 const std::string& script,
1510 const ActionHook& ah,
1511 const ARDOUR::LuaScriptParamList& args)
1512 : SessionHandlePtr (s)
1517 // TODO: allow to reference object (e.g region)
1520 lua_State* L = lua.getState();
1521 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1522 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1523 if ((*i)->optional && !(*i)->is_set) { continue; }
1524 tbl_arg[(*i)->name] = (*i)->value;
1528 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1529 (*_lua_add)(name, script, bytecode, tbl_arg);
1530 } catch (luabridge::LuaException const& e) {
1531 cerr << "LuaException:" << e.what () << endl;
1532 throw failed_constructor ();
1539 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1540 : SessionHandlePtr (s)
1542 XMLNode* child = NULL;
1543 if (node.name() != X_("LuaCallback")
1544 || !node.property ("signals")
1545 || !node.property ("id")
1546 || !node.property ("name")) {
1547 throw failed_constructor ();
1550 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1551 if (!(*n)->is_content ()) { continue; }
1556 throw failed_constructor ();
1561 _id = PBD::ID (node.property ("id")->value ());
1562 _name = node.property ("name")->value ();
1563 _signals = ActionHook (node.property ("signals")->value ());
1566 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1568 (*_lua_load)(std::string ((const char*)buf, size));
1569 } catch (luabridge::LuaException const& e) {
1570 cerr << "LuaException:" << e.what () << endl;
1577 LuaCallback::~LuaCallback ()
1587 LuaCallback::get_state (void)
1591 luabridge::LuaRef savedstate ((*_lua_save)());
1592 saved = savedstate.cast<std::string>();
1594 lua.collect_garbage ();
1596 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1597 std::string b64s (b64);
1600 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1601 script_node->add_property (X_("lua"), LUA_VERSION);
1602 script_node->add_property (X_("id"), _id.to_s ());
1603 script_node->add_property (X_("name"), _name);
1604 script_node->add_property (X_("signals"), _signals.to_string ());
1605 script_node->add_content (b64s);
1606 return *script_node;
1610 LuaCallback::init (void)
1612 lua.Print.connect (&_lua_print);
1615 "function ScriptManager ()"
1616 " local self = { script = {}, instance = {} }"
1618 " local addinternal = function (n, s, f, a)"
1619 " assert(type(n) == 'string', 'Name must be string')"
1620 " assert(type(s) == 'string', 'Script must be string')"
1621 " assert(type(f) == 'function', 'Factory is a not a function')"
1622 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1623 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1624 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1625 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1628 " local call = function (...)"
1629 " if type(self.instance) == 'function' then"
1630 " local status, err = pcall (self.instance, ...)"
1631 " if not status then"
1632 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1633 " self.script = nil"
1634 " self.instance = nil"
1642 " local add = function (n, s, b, a)"
1643 " assert(type(b) == 'string', 'ByteCode must be string')"
1644 " load (b)()" // assigns f
1645 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1646 " addinternal (n, s, load(f), a)"
1649 " local get = function ()"
1650 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1651 " return { ['name'] = self.script['n'],"
1652 " ['script'] = self.script['s'],"
1653 " ['args'] = self.script['a'] }"
1660 " local function basic_serialize (o)"
1661 " if type(o) == \"number\" then"
1662 " return tostring(o)"
1664 " return string.format(\"%q\", o)"
1668 " local function serialize (name, value)"
1669 " local rv = name .. ' = '"
1671 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1672 " return rv .. basic_serialize(value) .. ' '"
1673 " elseif type(value) == \"table\" then"
1675 " for k,v in pairs(value) do"
1676 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1677 " rv = rv .. serialize(fieldname, v) .. ' '"
1678 " collectgarbage()" // string concatenation allocates a new string
1681 " elseif type(value) == \"function\" then"
1682 " return rv .. string.format(\"%q\", string.dump(value, true))"
1683 " elseif type(value) == \"boolean\" then"
1684 " return rv .. tostring (value)"
1686 " error('cannot save a ' .. type(value))"
1692 " local save = function ()"
1693 " return (serialize('s', self.script))"
1696 " local restore = function (state)"
1699 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1702 " return { call = call, add = add, get = get,"
1703 " restore = restore, save = save}"
1706 " manager = ScriptManager ()"
1707 " ScriptManager = nil"
1710 lua_State* L = lua.getState();
1713 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1714 lua.do_command ("manager = nil"); // hide it.
1715 lua.do_command ("collectgarbage()");
1717 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1718 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1719 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1720 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1721 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1723 } catch (luabridge::LuaException const& e) {
1724 fatal << string_compose (_("programming error: %1"),
1725 X_("Failed to setup Lua callback interpreter"))
1727 abort(); /*NOTREACHED*/
1730 LuaInstance::register_classes (L);
1732 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1733 lua_setglobal (L, "Editor");
1737 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1739 // TODO consolidate w/ LuaInstance::lua_action()
1741 luabridge::LuaRef ref = (*_lua_get)();
1745 if (!ref["name"].isString()) {
1748 if (!ref["script"].isString()) {
1751 if (!ref["args"].isTable()) {
1756 name = ref["name"].cast<std::string> ();
1757 script = ref["script"].cast<std::string> ();
1760 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1764 args = LuaScriptParams::script_params (lsi, "action_params");
1765 luabridge::LuaRef rargs (ref["args"]);
1766 LuaScriptParams::ref_to_params (args, &rargs);
1768 } catch (luabridge::LuaException const& e) {
1769 cerr << "LuaException:" << e.what () << endl;
1776 LuaCallback::set_session (ARDOUR::Session *s)
1778 SessionHandlePtr::set_session (s);
1784 lua_State* L = lua.getState();
1785 LuaBindings::set_session (L, _session);
1791 LuaCallback::session_going_away ()
1793 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1794 lua.do_command ("collectgarbage();");
1796 SessionHandlePtr::session_going_away ();
1799 drop_callback (); /* EMIT SIGNAL */
1803 LuaCallback::reconnect ()
1805 _connections.drop_connections ();
1806 if ((*_lua_get) ().isNil ()) {
1807 drop_callback (); /* EMIT SIGNAL */
1811 // TODO pass object which emits the signal (e.g region)
1813 // save/load bound objects will be tricky.
1814 // Best idea so far is to save/lookup the PBD::ID
1815 // (either use boost::any indirection or templates for bindable
1816 // object types or a switch statement..)
1818 // _session->route_by_id ()
1819 // _session->track_by_diskstream_id ()
1820 // _session->source_by_id ()
1821 // _session->controllable_by_id ()
1822 // _session->processor_by_id ()
1823 // RegionFactory::region_by_id ()
1825 // TODO loop over objects (if any)
1827 reconnect_object ((void*)0);
1830 template <class T> void
1831 LuaCallback::reconnect_object (T obj)
1833 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1835 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1836 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1837 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1839 # include "luasignal_syms.h"
1841 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1842 abort(); /*NOTREACHED*/
1851 template <typename T, typename S> void
1852 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1854 _connections, invalidator (*this),
1855 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1859 template <typename T, typename C1> void
1860 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1862 _connections, invalidator (*this),
1863 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1867 template <typename T, typename C1, typename C2> void
1868 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1870 _connections, invalidator (*this),
1871 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1875 template <typename T> void
1876 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1879 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1880 if (! rv.cast<bool> ()) {
1884 /* destroy LuaRef ^^ first before calling drop_callback() */
1886 drop_callback (); /* EMIT SIGNAL */
1890 template <typename T, typename C1> void
1891 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1894 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1895 if (! rv.cast<bool> ()) {
1900 drop_callback (); /* EMIT SIGNAL */
1904 template <typename T, typename C1, typename C2> void
1905 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1908 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1909 if (! rv.cast<bool> ()) {
1914 drop_callback (); /* EMIT SIGNAL */