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 "luadialog.h"
38 #include "luainstance.h"
39 #include "luasignal.h"
41 #include "region_view.h"
42 #include "processor_box.h"
43 #include "time_axis_view.h"
44 #include "time_axis_view_item.h"
45 #include "selection.h"
46 #include "script_selector.h"
48 #include "utils_videotl.h"
53 /** wrap RefPtr< Cairo::ImageSurface >
55 * Image surfaces provide the ability to render to memory buffers either
56 * allocated by cairo or by the calling code. The supported image formats are
57 * those defined in Cairo::Format.
62 * Creates an image surface of the specified format and dimensions. Initially
63 * the surface contents are all 0. (Specifically, within each pixel, each
64 * color or alpha channel belonging to format will be 0. The contents of bits
65 * within a pixel, but not belonging to the given format are undefined).
67 * @param format format of pixels in the surface to create
68 * @param width width of the surface, in pixels
69 * @param height height of the surface, in pixels
71 ImageSurface (Cairo::Format format, int width, int height)
72 : _surface (Cairo::ImageSurface::create (format, width, height))
73 , _ctx (Cairo::Context::create (_surface))
74 , ctx (_ctx->cobj ()) {}
79 * Set this surface as source for another context.
80 * This allows to draw this surface
82 void set_as_source (Cairo::Context* c, int x, int y) {
84 c->set_source (_surface, x, y);
88 * Returns a context object to perform operations on the surface
90 Cairo::Context* context () {
91 return (Cairo::Context *)&ctx;
95 * Returns the stride of the image surface in bytes (or 0 if surface is not
96 * an image surface). The stride is the distance in bytes from the beginning
97 * of one row of the image data to the beginning of the next row.
99 int get_stride () const {
100 return _surface->get_stride ();
103 /** Gets the width of the ImageSurface in pixels */
104 int get_width () const {
105 return _surface->get_width ();
108 /** Gets the height of the ImageSurface in pixels */
109 int get_height () const {
110 return _surface->get_height ();
114 * Get a pointer to the data of the image surface, for direct
115 * inspection or modification.
117 * Return value: a pointer to the image data of this surface or NULL
118 * if @surface is not an image surface.
121 unsigned char* get_data () {
122 return _surface->get_data ();
125 /** Tells cairo to consider the data buffer dirty.
127 * In particular, if you've created an ImageSurface with a data buffer that
128 * you've allocated yourself and you draw to that data buffer using means
129 * other than cairo, you must call mark_dirty() before doing any additional
130 * drawing to that surface with cairo.
132 * Note that if you do draw to the Surface outside of cairo, you must call
133 * flush() before doing the drawing.
136 _surface->mark_dirty ();
139 /** Marks a rectangular area of the given surface dirty.
141 * @param x X coordinate of dirty rectangle
142 * @param y Y coordinate of dirty rectangle
143 * @param width width of dirty rectangle
144 * @param height height of dirty rectangle
146 void mark_dirty (int x, int y, int width, int height) {
147 _surface->mark_dirty (x, y, width, height);
151 Cairo::RefPtr<Cairo::ImageSurface> _surface;
152 Cairo::RefPtr<Cairo::Context> _ctx;
158 /** Create a new PangoLayout Text Display
159 * @param c CairoContext for the layout
160 * @param font_name a font-description e.g. "Mono 8px"
162 PangoLayout (Cairo::Context* c, std::string font_name) {
163 ::PangoLayout* pl = pango_cairo_create_layout (c->cobj ());
164 _layout = Glib::wrap (pl);
165 Pango::FontDescription fd (font_name);
166 _layout->set_font_description (fd);
171 /** Gets the text in the layout. The returned text should not
172 * be freed or modified.
174 * @return The text in the @a layout.
176 std::string get_text () const {
177 return _layout->get_text ();
179 /** Set the text of the layout.
180 * @param text The text for the layout.
182 void set_text (const std::string& text) {
183 _layout->set_text (text);
186 /** Sets the layout text and attribute list from marked-up text (see markup format).
187 * Replaces the current text and attribute list.
188 * @param markup Some marked-up text.
190 void set_markup (const std::string& markup) {
191 _layout->set_markup (markup);
194 /** Sets the width to which the lines of the Pango::Layout should wrap or
195 * ellipsized. The default value is -1: no width set.
197 * @param width The desired width in Pango units, or -1 to indicate that no
198 * wrapping or ellipsization should be performed.
200 void set_width (int width) {
201 _layout->set_width (width * PANGO_SCALE);
204 /** Gets the width to which the lines of the Pango::Layout should wrap.
206 * @return The width in Pango units, or -1 if no width set.
208 int get_width () const {
209 return _layout->get_width () / PANGO_SCALE;
212 /** Sets the type of ellipsization being performed for @a layout.
213 * Depending on the ellipsization mode @a ellipsize text is
214 * removed from the start, middle, or end of text so they
215 * fit within the width and height of layout set with
216 * set_width() and set_height().
218 * If the layout contains characters such as newlines that
219 * force it to be layed out in multiple paragraphs, then whether
220 * each paragraph is ellipsized separately or the entire layout
221 * is ellipsized as a whole depends on the set height of the layout.
222 * See set_height() for details.
224 * @param ellipsize The new ellipsization mode for @a layout.
226 void set_ellipsize (Pango::EllipsizeMode ellipsize) {
227 _layout->set_ellipsize (ellipsize);
230 /** Gets the type of ellipsization being performed for @a layout.
231 * See set_ellipsize()
233 * @return The current ellipsization mode for @a layout.
235 * Use is_ellipsized() to query whether any paragraphs
236 * were actually ellipsized.
238 Pango::EllipsizeMode get_ellipsize () const {
239 return _layout->get_ellipsize ();
242 /** Queries whether the layout had to ellipsize any paragraphs.
244 * This returns <tt>true</tt> if the ellipsization mode for @a layout
245 * is not Pango::ELLIPSIZE_NONE, a positive width is set on @a layout,
246 * and there are paragraphs exceeding that width that have to be
249 * @return <tt>true</tt> if any paragraphs had to be ellipsized, <tt>false</tt>
252 bool is_ellipsized () const {
253 return _layout->is_ellipsized ();
256 /** Sets the wrap mode; the wrap mode only has effect if a width
257 * is set on the layout with set_width().
258 * To turn off wrapping, set the width to -1.
260 * @param wrap The wrap mode.
262 void set_wrap (Pango::WrapMode wrap) {
263 _layout->set_width (wrap);
266 /** Gets the wrap mode for the layout.
268 * Use is_wrapped() to query whether any paragraphs
269 * were actually wrapped.
271 * @return Active wrap mode.
273 Pango::WrapMode get_wrap () const {
274 return _layout->get_wrap ();
277 /** Queries whether the layout had to wrap any paragraphs.
279 * This returns <tt>true</tt> if a positive width is set on @a layout,
280 * ellipsization mode of @a layout is set to Pango::ELLIPSIZE_NONE,
281 * and there are paragraphs exceeding the layout width that have
284 * @return <tt>true</tt> if any paragraphs had to be wrapped, <tt>false</tt>
287 bool is_wrapped () const {
288 return _layout->is_wrapped ();
291 /** Determines the logical width and height of a Pango::Layout
294 int get_pixel_size (lua_State *L) {
296 _layout->get_pixel_size (width, height);
297 luabridge::Stack<int>::push (L, width);
298 luabridge::Stack<int>::push (L, height);
303 /** Draws a Layout in the specified Cairo @a context. The top-left
304 * corner of the Layout will be drawn at the current point of the
307 * @param context A Cairo context.
309 void show_in_cairo_context (Cairo::Context* c) {
310 pango_cairo_update_layout (c->cobj (), _layout->gobj());
311 pango_cairo_show_layout (c->cobj (), _layout->gobj());
314 void layout_cairo_path (Cairo::Context* c) {
315 pango_cairo_update_layout (c->cobj (), _layout->gobj());
316 pango_cairo_layout_path (c->cobj (), _layout->gobj());
320 Glib::RefPtr<Pango::Layout> _layout;
325 ////////////////////////////////////////////////////////////////////////////////
327 namespace LuaSignal {
329 #define STATIC(name,c,p) else if (!strcmp(type, #name)) {return name;}
330 #define SESSION(name,c,p) else if (!strcmp(type, #name)) {return name;}
331 #define ENGINE(name,c,p) else if (!strcmp(type, #name)) {return name;}
334 str2luasignal (const std::string &str) {
335 const char* type = str.c_str();
337 # include "luasignal_syms.h"
339 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", str) << endmsg;
340 abort(); /*NOTREACHED*/
347 #define STATIC(name,c,p) N_(#name),
348 #define SESSION(name,c,p) N_(#name),
349 #define ENGINE(name,c,p) N_(#name),
350 const char *luasignalstr[] = {
351 # include "luasignal_syms.h"
361 /** special cases for Ardour's Mixer UI */
364 ProcessorBox::ProcSelection
365 processor_selection () {
366 return ProcessorBox::current_processor_selection ();
371 ////////////////////////////////////////////////////////////////////////////////
373 #define xstr(s) stringify(s)
374 #define stringify(s) #s
376 using namespace ARDOUR;
378 PBD::Signal0<void> LuaInstance::LuaTimerDS;
381 LuaInstance::register_hooks (lua_State* L)
384 #define ENGINE(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
385 #define STATIC(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
386 #define SESSION(name,c,p) .addConst (stringify(name), (LuaSignal::LuaSignal)LuaSignal::name)
387 luabridge::getGlobalNamespace (L)
388 .beginNamespace ("LuaSignal")
389 # include "luasignal_syms.h"
395 luabridge::getGlobalNamespace (L)
396 .beginNamespace ("LuaSignal")
397 .beginStdBitSet <LuaSignal::LAST_SIGNAL> ("Set")
403 LuaInstance::bind_cairo (lua_State* L)
405 /* std::vector<double> for set_dash()
406 * for Windows (DLL, .exe) this needs to be bound in the same memory context as "Cairo".
408 * The std::vector<> argument in set_dash() has a fixed address in ardour.exe, while
409 * the address of the one in libardour.dll is mapped when loading the .dll
411 * see LuaBindings::set_session() for a detailed explanation
413 luabridge::getGlobalNamespace (L)
414 .beginNamespace ("C")
415 .beginStdVector <double> ("DoubleVector")
419 luabridge::getGlobalNamespace (L)
420 .beginNamespace ("Cairo")
421 .beginClass <Cairo::Context> ("Context")
422 .addFunction ("save", &Cairo::Context::save)
423 .addFunction ("restore", &Cairo::Context::restore)
424 .addFunction ("set_operator", &Cairo::Context::set_operator)
425 //.addFunction ("set_source", &Cairo::Context::set_operator) // needs RefPtr
426 .addFunction ("set_source_rgb", &Cairo::Context::set_source_rgb)
427 .addFunction ("set_source_rgba", &Cairo::Context::set_source_rgba)
428 .addFunction ("set_line_width", &Cairo::Context::set_line_width)
429 .addFunction ("set_line_cap", &Cairo::Context::set_line_cap)
430 .addFunction ("set_line_join", &Cairo::Context::set_line_join)
431 .addFunction ("set_dash", (void (Cairo::Context::*)(const std::vector<double>&, double))&Cairo::Context::set_dash)
432 .addFunction ("unset_dash", &Cairo::Context::unset_dash)
433 .addFunction ("translate", &Cairo::Context::translate)
434 .addFunction ("scale", &Cairo::Context::scale)
435 .addFunction ("rotate", &Cairo::Context::rotate)
436 .addFunction ("begin_new_path", &Cairo::Context::begin_new_path)
437 .addFunction ("begin_new_sub_path", &Cairo::Context::begin_new_sub_path)
438 .addFunction ("move_to", &Cairo::Context::move_to)
439 .addFunction ("line_to", &Cairo::Context::line_to)
440 .addFunction ("curve_to", &Cairo::Context::curve_to)
441 .addFunction ("arc", &Cairo::Context::arc)
442 .addFunction ("arc_negative", &Cairo::Context::arc_negative)
443 .addFunction ("rel_move_to", &Cairo::Context::rel_move_to)
444 .addFunction ("rel_line_to", &Cairo::Context::rel_line_to)
445 .addFunction ("rel_curve_to", &Cairo::Context::rel_curve_to)
446 .addFunction ("rectangle", (void (Cairo::Context::*)(double, double, double, double))&Cairo::Context::rectangle)
447 .addFunction ("close_path", &Cairo::Context::close_path)
448 .addFunction ("paint", &Cairo::Context::paint)
449 .addFunction ("paint_with_alpha", &Cairo::Context::paint_with_alpha)
450 .addFunction ("stroke", &Cairo::Context::stroke)
451 .addFunction ("stroke_preserve", &Cairo::Context::stroke_preserve)
452 .addFunction ("fill", &Cairo::Context::fill)
453 .addFunction ("fill_preserve", &Cairo::Context::fill_preserve)
454 .addFunction ("reset_clip", &Cairo::Context::reset_clip)
455 .addFunction ("clip", &Cairo::Context::clip)
456 .addFunction ("clip_preserve", &Cairo::Context::clip_preserve)
457 .addFunction ("set_font_size", &Cairo::Context::set_font_size)
458 .addFunction ("show_text", &Cairo::Context::show_text)
461 // LineCap, LineJoin, Operator
462 .beginNamespace ("LineCap")
463 .addConst ("Butt", CAIRO_LINE_CAP_BUTT)
464 .addConst ("Round", CAIRO_LINE_CAP_ROUND)
465 .addConst ("Square", CAIRO_LINE_CAP_SQUARE)
468 .beginNamespace ("LineJoin")
469 .addConst ("Miter", CAIRO_LINE_JOIN_MITER)
470 .addConst ("Round", CAIRO_LINE_JOIN_ROUND)
471 .addConst ("Bevel", CAIRO_LINE_JOIN_BEVEL)
474 .beginNamespace ("Operator")
475 .addConst ("Clear", CAIRO_OPERATOR_CLEAR)
476 .addConst ("Source", CAIRO_OPERATOR_SOURCE)
477 .addConst ("Over", CAIRO_OPERATOR_OVER)
478 .addConst ("Add", CAIRO_OPERATOR_ADD)
481 .beginNamespace ("Format")
482 .addConst ("ARGB32", CAIRO_FORMAT_ARGB32)
483 .addConst ("RGB24", CAIRO_FORMAT_RGB24)
486 .beginClass <LuaCairo::ImageSurface> ("ImageSurface")
487 .addConstructor <void (*) (Cairo::Format, int, int)> ()
488 .addFunction ("set_as_source", &LuaCairo::ImageSurface::set_as_source)
489 .addFunction ("context", &LuaCairo::ImageSurface::context)
490 .addFunction ("get_stride", &LuaCairo::ImageSurface::get_stride)
491 .addFunction ("get_width", &LuaCairo::ImageSurface::get_width)
492 .addFunction ("get_height", &LuaCairo::ImageSurface::get_height)
493 //.addFunction ("get_data", &LuaCairo::ImageSurface::get_data) // uint8_t* array is n/a
496 .beginClass <LuaCairo::PangoLayout> ("PangoLayout")
497 .addConstructor <void (*) (Cairo::Context*, std::string)> ()
498 .addCFunction ("get_pixel_size", &LuaCairo::PangoLayout::get_pixel_size)
499 .addFunction ("get_text", &LuaCairo::PangoLayout::get_text)
500 .addFunction ("set_text", &LuaCairo::PangoLayout::set_text)
501 .addFunction ("show_in_cairo_context", &LuaCairo::PangoLayout::show_in_cairo_context)
502 .addFunction ("layout_cairo_path", &LuaCairo::PangoLayout::layout_cairo_path)
503 .addFunction ("set_markup", &LuaCairo::PangoLayout::set_markup)
504 .addFunction ("set_width", &LuaCairo::PangoLayout::set_width)
505 .addFunction ("set_ellipsize", &LuaCairo::PangoLayout::set_ellipsize)
506 .addFunction ("get_ellipsize", &LuaCairo::PangoLayout::get_ellipsize)
507 .addFunction ("is_ellipsized", &LuaCairo::PangoLayout::is_ellipsized)
508 .addFunction ("set_wrap", &LuaCairo::PangoLayout::set_wrap)
509 .addFunction ("get_wrap", &LuaCairo::PangoLayout::get_wrap)
510 .addFunction ("is_wrapped", &LuaCairo::PangoLayout::is_wrapped)
514 .beginNamespace ("EllipsizeMode")
515 .addConst ("None", Pango::ELLIPSIZE_NONE)
516 .addConst ("Start", Pango::ELLIPSIZE_START)
517 .addConst ("Middle", Pango::ELLIPSIZE_MIDDLE)
518 .addConst ("End", Pango::ELLIPSIZE_END)
521 .beginNamespace ("WrapMode")
522 .addConst ("Word", Pango::WRAP_WORD)
523 .addConst ("Char", Pango::WRAP_CHAR)
524 .addConst ("WordChar", Pango::WRAP_WORD_CHAR)
529 /* Lua/cairo bindings operate on Cairo::Context, there is no Cairo::RefPtr wrapper [yet].
530 one can work around this as follows:
533 LuaInstance::register_classes (lua.getState());
535 "function render (ctx)"
536 " ctx:rectangle (0, 0, 100, 100)"
537 " ctx:set_source_rgba (0.1, 1.0, 0.1, 1.0)"
542 Cairo::RefPtr<Cairo::Context> context = get_window ()->create_cairo_context ();
543 Cairo::Context ctx (context->cobj ());
545 luabridge::LuaRef lua_render = luabridge::getGlobal (lua.getState(), "render");
546 lua_render ((Cairo::Context *)&ctx);
553 LuaInstance::bind_dialog (lua_State* L)
555 luabridge::getGlobalNamespace (L)
556 .beginNamespace ("LuaDialog")
558 .beginClass <LuaDialog::Message> ("Message")
559 .addConstructor <void (*) (std::string const&, std::string const&, LuaDialog::Message::MessageType, LuaDialog::Message::ButtonType)> ()
560 .addFunction ("run", &LuaDialog::Message::run)
563 .beginClass <LuaDialog::Dialog> ("Dialog")
564 .addConstructor <void (*) (std::string const&, luabridge::LuaRef)> ()
565 .addCFunction ("run", &LuaDialog::Dialog::run)
569 .beginNamespace ("MessageType")
570 .addConst ("Info", LuaDialog::Message::Info)
571 .addConst ("Warning", LuaDialog::Message::Warning)
572 .addConst ("Question", LuaDialog::Message::Question)
573 .addConst ("Error", LuaDialog::Message::Error)
576 .beginNamespace ("ButtonType")
577 .addConst ("OK", LuaDialog::Message::OK)
578 .addConst ("Close", LuaDialog::Message::Close)
579 .addConst ("Cancel", LuaDialog::Message::Cancel)
580 .addConst ("Yes_No", LuaDialog::Message::Yes_No)
581 .addConst ("OK_Cancel", LuaDialog::Message::OK_Cancel)
584 .beginNamespace ("Response")
586 .addConst ("Cancel", 1)
587 .addConst ("Close", 2)
590 .addConst ("None", -1)
598 LuaInstance::register_classes (lua_State* L)
600 LuaBindings::stddef (L);
601 LuaBindings::common (L);
602 LuaBindings::session (L);
603 LuaBindings::osc (L);
609 luabridge::getGlobalNamespace (L)
610 .beginNamespace ("ArdourUI")
612 .addFunction ("http_get", (std::string (*)(const std::string&))&ArdourCurl::http_get)
614 .addFunction ("processor_selection", &LuaMixer::processor_selection)
616 .beginStdList <ArdourMarker*> ("ArdourMarkerList")
619 .beginClass <ArdourMarker> ("ArdourMarker")
620 .addFunction ("name", &ArdourMarker::name)
621 .addFunction ("position", &ArdourMarker::position)
622 .addFunction ("_type", &ArdourMarker::type)
625 .beginClass <AxisView> ("AxisView")
628 .deriveClass <TimeAxisView, AxisView> ("TimeAxisView")
631 .deriveClass <StripableTimeAxisView, TimeAxisView> ("StripableTimeAxisView")
634 .beginClass <Selectable> ("Selectable")
637 .deriveClass <TimeAxisViewItem, Selectable> ("TimeAxisViewItem")
640 .deriveClass <RegionView, TimeAxisViewItem> ("RegionView")
643 .deriveClass <RouteUI, Selectable> ("RouteUI")
646 .deriveClass <RouteTimeAxisView, RouteUI> ("RouteTimeAxisView")
647 .addCast<StripableTimeAxisView> ("to_stripabletimeaxisview")
648 .addCast<TimeAxisView> ("to_timeaxisview") // deprecated
651 // std::list<Selectable*>
652 .beginStdCPtrList <Selectable> ("SelectionList")
655 // std::list<TimeAxisView*>
656 .beginStdCPtrList <TimeAxisView> ("TrackViewStdList")
660 .beginClass <RegionSelection> ("RegionSelection")
661 .addFunction ("start", &RegionSelection::start)
662 .addFunction ("end_frame", &RegionSelection::end_frame)
663 .addFunction ("n_midi_regions", &RegionSelection::n_midi_regions)
664 .addFunction ("regionlist", &RegionSelection::regionlist) // XXX check windows binding (libardour)
667 .deriveClass <TimeSelection, std::list<ARDOUR::AudioRange> > ("TimeSelection")
668 .addFunction ("start", &TimeSelection::start)
669 .addFunction ("end_frame", &TimeSelection::end_frame)
670 .addFunction ("length", &TimeSelection::length)
673 .deriveClass <MarkerSelection, std::list<ArdourMarker*> > ("MarkerSelection")
676 .deriveClass <TrackViewList, std::list<TimeAxisView*> > ("TrackViewList")
677 .addFunction ("contains", &TrackViewList::contains)
678 .addFunction ("routelist", &TrackViewList::routelist)
681 .deriveClass <TrackSelection, TrackViewList> ("TrackSelection")
684 .beginClass <Selection> ("Selection")
685 .addFunction ("clear", &Selection::clear)
686 .addFunction ("clear_all", &Selection::clear_all)
687 .addFunction ("empty", &Selection::empty)
688 .addData ("tracks", &Selection::tracks)
689 .addData ("regions", &Selection::regions)
690 .addData ("time", &Selection::time)
691 .addData ("markers", &Selection::markers)
693 .addData ("lines", &Selection::lines)
694 .addData ("playlists", &Selection::playlists)
695 .addData ("points", &Selection::points)
696 .addData ("midi_regions", &Selection::midi_regions)
697 .addData ("midi_notes", &Selection::midi_notes) // cut buffer only
701 .beginClass <PublicEditor> ("Editor")
702 .addFunction ("snap_type", &PublicEditor::snap_type)
703 .addFunction ("snap_mode", &PublicEditor::snap_mode)
704 .addFunction ("set_snap_mode", &PublicEditor::set_snap_mode)
705 .addFunction ("set_snap_threshold", &PublicEditor::set_snap_threshold)
707 .addFunction ("undo", &PublicEditor::undo)
708 .addFunction ("redo", &PublicEditor::redo)
710 .addFunction ("set_mouse_mode", &PublicEditor::set_mouse_mode)
711 .addFunction ("current_mouse_mode", &PublicEditor::current_mouse_mode)
713 .addFunction ("consider_auditioning", &PublicEditor::consider_auditioning)
715 .addFunction ("new_region_from_selection", &PublicEditor::new_region_from_selection)
716 .addFunction ("separate_region_from_selection", &PublicEditor::separate_region_from_selection)
717 .addFunction ("pixel_to_sample", &PublicEditor::pixel_to_sample)
718 .addFunction ("sample_to_pixel", &PublicEditor::sample_to_pixel)
720 .addFunction ("get_selection", &PublicEditor::get_selection)
721 .addFunction ("get_cut_buffer", &PublicEditor::get_cut_buffer)
722 .addRefFunction ("get_selection_extents", &PublicEditor::get_selection_extents)
724 .addFunction ("set_selection", &PublicEditor::set_selection)
726 .addFunction ("play_selection", &PublicEditor::play_selection)
727 .addFunction ("play_with_preroll", &PublicEditor::play_with_preroll)
728 .addFunction ("maybe_locate_with_edit_preroll", &PublicEditor::maybe_locate_with_edit_preroll)
729 .addFunction ("goto_nth_marker", &PublicEditor::goto_nth_marker)
731 .addFunction ("add_location_from_playhead_cursor", &PublicEditor::add_location_from_playhead_cursor)
732 .addFunction ("remove_location_at_playhead_cursor", &PublicEditor::remove_location_at_playhead_cursor)
734 .addFunction ("set_show_measures", &PublicEditor::set_show_measures)
735 .addFunction ("show_measures", &PublicEditor::show_measures)
736 .addFunction ("remove_tracks", &PublicEditor::remove_tracks)
738 .addFunction ("set_loop_range", &PublicEditor::set_loop_range)
739 .addFunction ("set_punch_range", &PublicEditor::set_punch_range)
741 .addFunction ("effective_mouse_mode", &PublicEditor::effective_mouse_mode)
743 .addRefFunction ("do_import", &PublicEditor::do_import)
744 .addRefFunction ("do_embed", &PublicEditor::do_embed)
746 .addFunction ("export_audio", &PublicEditor::export_audio)
747 .addFunction ("stem_export", &PublicEditor::stem_export)
748 .addFunction ("export_selection", &PublicEditor::export_selection)
749 .addFunction ("export_range", &PublicEditor::export_range)
751 .addFunction ("set_zoom_focus", &PublicEditor::set_zoom_focus)
752 .addFunction ("get_zoom_focus", &PublicEditor::get_zoom_focus)
753 .addFunction ("get_current_zoom", &PublicEditor::get_current_zoom)
754 .addFunction ("reset_zoom", &PublicEditor::reset_zoom)
756 .addFunction ("clear_playlist", &PublicEditor::clear_playlist)
757 .addFunction ("new_playlists", &PublicEditor::new_playlists)
758 .addFunction ("copy_playlists", &PublicEditor::copy_playlists)
759 .addFunction ("clear_playlists", &PublicEditor::clear_playlists)
761 .addFunction ("select_all_tracks", &PublicEditor::select_all_tracks)
762 .addFunction ("deselect_all", &PublicEditor::deselect_all)
764 #if 0 // TimeAxisView& can't be bound (pure virtual fn)
765 .addFunction ("set_selected_track", &PublicEditor::set_selected_track)
766 .addFunction ("set_selected_mixer_strip", &PublicEditor::set_selected_mixer_strip)
767 .addFunction ("ensure_time_axis_view_is_visible", &PublicEditor::ensure_time_axis_view_is_visible)
769 .addFunction ("hide_track_in_display", &PublicEditor::hide_track_in_display)
770 .addFunction ("show_track_in_display", &PublicEditor::show_track_in_display)
771 .addFunction ("set_visible_track_count", &PublicEditor::set_visible_track_count)
772 .addFunction ("fit_selection", &PublicEditor::fit_selection)
774 .addFunction ("regionview_from_region", &PublicEditor::regionview_from_region)
775 .addFunction ("set_stationary_playhead", &PublicEditor::set_stationary_playhead)
776 .addFunction ("stationary_playhead", &PublicEditor::stationary_playhead)
777 .addFunction ("set_follow_playhead", &PublicEditor::set_follow_playhead)
778 .addFunction ("follow_playhead", &PublicEditor::follow_playhead)
780 .addFunction ("dragging_playhead", &PublicEditor::dragging_playhead)
781 .addFunction ("leftmost_sample", &PublicEditor::leftmost_sample)
782 .addFunction ("current_page_samples", &PublicEditor::current_page_samples)
783 .addFunction ("visible_canvas_height", &PublicEditor::visible_canvas_height)
784 .addFunction ("temporal_zoom_step", &PublicEditor::temporal_zoom_step)
785 .addFunction ("override_visible_track_count", &PublicEditor::override_visible_track_count)
787 .addFunction ("scroll_tracks_down_line", &PublicEditor::scroll_tracks_down_line)
788 .addFunction ("scroll_tracks_up_line", &PublicEditor::scroll_tracks_up_line)
789 .addFunction ("scroll_down_one_track", &PublicEditor::scroll_down_one_track)
790 .addFunction ("scroll_up_one_track", &PublicEditor::scroll_up_one_track)
792 .addFunction ("reset_x_origin", &PublicEditor::reset_x_origin)
793 .addFunction ("get_y_origin", &PublicEditor::get_y_origin)
794 .addFunction ("reset_y_origin", &PublicEditor::reset_y_origin)
796 .addFunction ("remove_last_capture", &PublicEditor::remove_last_capture)
798 .addFunction ("maximise_editing_space", &PublicEditor::maximise_editing_space)
799 .addFunction ("restore_editing_space", &PublicEditor::restore_editing_space)
800 .addFunction ("toggle_meter_updating", &PublicEditor::toggle_meter_updating)
802 //.addFunction ("get_preferred_edit_position", &PublicEditor::get_preferred_edit_position)
803 //.addFunction ("split_regions_at", &PublicEditor::split_regions_at)
805 .addRefFunction ("get_nudge_distance", &PublicEditor::get_nudge_distance)
806 .addFunction ("get_paste_offset", &PublicEditor::get_paste_offset)
807 .addFunction ("get_grid_beat_divisions", &PublicEditor::get_grid_beat_divisions)
808 .addRefFunction ("get_grid_type_as_beats", &PublicEditor::get_grid_type_as_beats)
810 .addFunction ("toggle_ruler_video", &PublicEditor::toggle_ruler_video)
811 .addFunction ("toggle_xjadeo_proc", &PublicEditor::toggle_xjadeo_proc)
812 .addFunction ("get_videotl_bar_height", &PublicEditor::get_videotl_bar_height)
813 .addFunction ("set_video_timeline_height", &PublicEditor::set_video_timeline_height)
816 .addFunction ("get_equivalent_regions", &PublicEditor::get_equivalent_regions)
817 .addFunction ("drags", &PublicEditor::drags)
820 .addFunction ("get_stripable_time_axis_by_id", &PublicEditor::get_stripable_time_axis_by_id)
821 .addFunction ("get_track_views", &PublicEditor::get_track_views)
822 .addFunction ("rtav_from_route", &PublicEditor::rtav_from_route)
823 .addFunction ("axis_views_from_routes", &PublicEditor::axis_views_from_routes)
825 .addFunction ("center_screen", &PublicEditor::center_screen)
827 .addFunction ("get_smart_mode", &PublicEditor::get_smart_mode)
828 .addRefFunction ("get_pointer_position", &PublicEditor::get_pointer_position)
830 .addRefFunction ("find_location_from_marker", &PublicEditor::find_location_from_marker)
831 .addFunction ("find_marker_from_location_id", &PublicEditor::find_marker_from_location_id)
832 .addFunction ("mouse_add_new_marker", &PublicEditor::mouse_add_new_marker)
834 .addFunction ("get_regions_at", &PublicEditor::get_regions_at)
835 .addFunction ("get_regions_after", &PublicEditor::get_regions_after)
836 .addFunction ("get_regions_from_selection_and_mouse", &PublicEditor::get_regions_from_selection_and_mouse)
837 .addFunction ("get_regionviews_by_id", &PublicEditor::get_regionviews_by_id)
838 .addFunction ("get_per_region_note_selection", &PublicEditor::get_per_region_note_selection)
842 .addFunction ("mouse_add_new_tempo_event", &PublicEditor::mouse_add_new_tempo_event)
843 .addFunction ("mouse_add_new_meter_event", &PublicEditor::mouse_add_new_meter_event)
844 .addFunction ("edit_tempo_section", &PublicEditor::edit_tempo_section)
845 .addFunction ("edit_meter_section", &PublicEditor::edit_meter_section)
848 .addFunction ("access_action", &PublicEditor::access_action)
852 .beginNamespace ("MarkerType")
853 .addConst ("Mark", ArdourMarker::Type(ArdourMarker::Mark))
854 .addConst ("Tempo", ArdourMarker::Type(ArdourMarker::Tempo))
855 .addConst ("Meter", ArdourMarker::Type(ArdourMarker::Meter))
856 .addConst ("SessionStart", ArdourMarker::Type(ArdourMarker::SessionStart))
857 .addConst ("SessionEnd", ArdourMarker::Type(ArdourMarker::SessionEnd))
858 .addConst ("RangeStart", ArdourMarker::Type(ArdourMarker::RangeStart))
859 .addConst ("RangeEnd", ArdourMarker::Type(ArdourMarker::RangeEnd))
860 .addConst ("LoopStart", ArdourMarker::Type(ArdourMarker::LoopStart))
861 .addConst ("LoopEnd", ArdourMarker::Type(ArdourMarker::LoopEnd))
862 .addConst ("PunchIn", ArdourMarker::Type(ArdourMarker::PunchIn))
863 .addConst ("PunchOut", ArdourMarker::Type(ArdourMarker::PunchOut))
866 .beginNamespace ("SelectionOp")
867 .addConst ("Toggle", Selection::Operation(Selection::Toggle))
868 .addConst ("Set", Selection::Operation(Selection::Set))
869 .addConst ("Extend", Selection::Operation(Selection::Extend))
870 .addConst ("Add", Selection::Operation(Selection::Add))
873 .endNamespace (); // end ArdourUI
881 #undef DISPLAYCONTROL
883 #undef IMPORTPOSITION
884 #undef IMPORTDISPOSITION
886 #define ZOOMFOCUS(NAME) .addConst (stringify(NAME), (Editing::ZoomFocus)Editing::NAME)
887 #define SNAPTYPE(NAME) .addConst (stringify(NAME), (Editing::SnapType)Editing::NAME)
888 #define SNAPMODE(NAME) .addConst (stringify(NAME), (Editing::SnapMode)Editing::NAME)
889 #define MOUSEMODE(NAME) .addConst (stringify(NAME), (Editing::MouseMode)Editing::NAME)
890 #define DISPLAYCONTROL(NAME) .addConst (stringify(NAME), (Editing::DisplayControl)Editing::NAME)
891 #define IMPORTMODE(NAME) .addConst (stringify(NAME), (Editing::ImportMode)Editing::NAME)
892 #define IMPORTPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportPosition)Editing::NAME)
893 #define IMPORTDISPOSITION(NAME) .addConst (stringify(NAME), (Editing::ImportDisposition)Editing::NAME)
894 luabridge::getGlobalNamespace (L)
895 .beginNamespace ("Editing")
896 # include "editing_syms.h"
903 ////////////////////////////////////////////////////////////////////////////////
905 using namespace ARDOUR;
906 using namespace ARDOUR_UI_UTILS;
910 static void _lua_print (std::string s) {
912 std::cout << "LuaInstance: " << s << "\n";
914 PBD::info << "LuaInstance: " << s << endmsg;
917 LuaInstance* LuaInstance::_instance = 0;
920 LuaInstance::instance ()
923 _instance = new LuaInstance;
930 LuaInstance::destroy_instance ()
936 LuaInstance::LuaInstance ()
938 lua.Print.connect (&_lua_print);
941 LuaScriptParamList args;
944 LuaInstance::~LuaInstance ()
946 delete _lua_call_action;
947 delete _lua_render_icon;
948 delete _lua_add_action;
949 delete _lua_del_action;
950 delete _lua_get_action;
962 "function ScriptManager ()"
963 " local self = { scripts = {}, instances = {}, icons = {} }"
965 " local remove = function (id)"
966 " self.scripts[id] = nil"
967 " self.instances[id] = nil"
968 " self.icons[id] = nil"
971 " local addinternal = function (i, n, s, f, c, a)"
972 " assert(type(i) == 'number', 'id must be numeric')"
973 " assert(type(n) == 'string', 'Name must be string')"
974 " assert(type(s) == 'string', 'Script must be string')"
975 " assert(type(f) == 'function', 'Factory is a not a function')"
976 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
977 " self.scripts[i] = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a, ['c'] = c }"
978 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
979 " self.instances[i] = load (string.dump(f, true), nil, nil, env)(a)"
980 " if type(c) == 'function' then"
981 " self.icons[i] = load (string.dump(c, true), nil, nil, env)(a)"
983 " self.icons[i] = nil"
987 " local call = function (id)"
988 " if type(self.instances[id]) == 'function' then"
989 " local status, err = pcall (self.instances[id])"
990 " if not status then"
991 " print ('action \"'.. id .. '\": ', err)" // error out
998 " local icon = function (id, ...)"
999 " if type(self.icons[id]) == 'function' then"
1000 " pcall (self.icons[id], ...)"
1005 " local add = function (i, n, s, b, c, a)"
1006 " assert(type(b) == 'string', 'ByteCode must be string')"
1007 " f = nil load (b)()" // assigns f
1008 " icn = nil load (c)()" // may assign "icn"
1009 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1010 " addinternal (i, n, s, load(f), type(icn) ~= \"string\" or icn == '' or load(icn), a)"
1013 " local get = function (id)"
1014 " if type(self.scripts[id]) == 'table' then"
1015 " return { ['name'] = self.scripts[id]['n'],"
1016 " ['script'] = self.scripts[id]['s'],"
1017 " ['icon'] = type(self.scripts[id]['c']) == 'function',"
1018 " ['args'] = self.scripts[id]['a'] }"
1023 " local function basic_serialize (o)"
1024 " if type(o) == \"number\" then"
1025 " return tostring(o)"
1027 " return string.format(\"%q\", o)"
1031 " local function serialize (name, value)"
1032 " local rv = name .. ' = '"
1033 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1034 " return rv .. basic_serialize(value) .. ' '"
1035 " elseif type(value) == \"table\" then"
1037 " for k,v in pairs(value) do"
1038 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1039 " rv = rv .. serialize(fieldname, v) .. ' '"
1042 " elseif type(value) == \"function\" then"
1043 " return rv .. string.format(\"%q\", string.dump(value, true))"
1044 " elseif type(value) == \"boolean\" then"
1045 " return rv .. tostring (value)"
1047 " error('cannot save a ' .. type(value))"
1052 " local save = function ()"
1053 " return (serialize('scripts', self.scripts))"
1056 " local clear = function ()"
1057 " self.scripts = {}"
1058 " self.instances = {}"
1063 " local restore = function (state)"
1066 " for i, s in pairs (scripts) do"
1067 " addinternal (i, s['n'], s['s'], load(s['f']), type (s['c']) ~= \"string\" or s['c'] == '' or load (s['c']), s['a'])"
1072 " return { call = call, add = add, remove = remove, get = get,"
1073 " restore = restore, save = save, clear = clear, icon = icon}"
1076 " manager = ScriptManager ()"
1077 " ScriptManager = nil"
1080 lua_State* L = lua.getState();
1083 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1084 lua.do_command ("manager = nil"); // hide it.
1085 lua.do_command ("collectgarbage()");
1087 _lua_add_action = new luabridge::LuaRef(lua_mgr["add"]);
1088 _lua_del_action = new luabridge::LuaRef(lua_mgr["remove"]);
1089 _lua_get_action = new luabridge::LuaRef(lua_mgr["get"]);
1090 _lua_call_action = new luabridge::LuaRef(lua_mgr["call"]);
1091 _lua_render_icon = new luabridge::LuaRef(lua_mgr["icon"]);
1092 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1093 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1094 _lua_clear = new luabridge::LuaRef(lua_mgr["clear"]);
1096 } catch (luabridge::LuaException const& e) {
1097 fatal << string_compose (_("programming error: %1"),
1098 X_("Failed to setup Lua action interpreter"))
1100 abort(); /*NOTREACHED*/
1103 register_classes (L);
1105 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1106 lua_setglobal (L, "Editor");
1109 void LuaInstance::set_session (Session* s)
1111 SessionHandlePtr::set_session (s);
1116 lua_State* L = lua.getState();
1117 LuaBindings::set_session (L, _session);
1119 for (LuaCallbackMap::iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1120 i->second->set_session (s);
1122 point_one_second_connection = Timers::rapid_connect (sigc::mem_fun(*this, & LuaInstance::every_point_one_seconds));
1126 LuaInstance::session_going_away ()
1128 ENSURE_GUI_THREAD (*this, &LuaInstance::session_going_away);
1129 point_one_second_connection.disconnect ();
1132 for (int i = 0; i < 9; ++i) {
1133 ActionChanged (i, ""); /* EMIT SIGNAL */
1135 SessionHandlePtr::session_going_away ();
1138 lua_State* L = lua.getState();
1139 LuaBindings::set_session (L, _session);
1140 lua.do_command ("collectgarbage();");
1144 LuaInstance::every_point_one_seconds ()
1146 LuaTimerDS (); // emit signal
1150 LuaInstance::set_state (const XMLNode& node)
1154 if ((child = find_named_node (node, "ActionScript"))) {
1155 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1156 if (!(*n)->is_content ()) { continue; }
1158 guchar* buf = g_base64_decode ((*n)->content ().c_str (), &size);
1160 (*_lua_load)(std::string ((const char*)buf, size));
1161 } catch (luabridge::LuaException const& e) {
1162 cerr << "LuaException:" << e.what () << endl;
1164 for (int i = 0; i < 9; ++i) {
1166 if (lua_action_name (i, name)) {
1167 ActionChanged (i, name); /* EMIT SIGNAL */
1174 if ((child = find_named_node (node, "ActionHooks"))) {
1175 for (XMLNodeList::const_iterator n = child->children ().begin (); n != child->children ().end (); ++n) {
1177 LuaCallbackPtr p (new LuaCallback (_session, *(*n)));
1178 _callbacks.insert (std::make_pair(p->id(), p));
1179 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1180 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1181 } catch (luabridge::LuaException const& e) {
1182 cerr << "LuaException:" << e.what () << endl;
1191 LuaInstance::interactive_add (LuaScriptInfo::ScriptType type, int id)
1194 std::string param_function = "action_params";
1195 std::vector<std::string> reg;
1198 case LuaScriptInfo::EditorAction:
1199 reg = lua_action_names ();
1200 title = _("Add Lua Action");
1202 case LuaScriptInfo::EditorHook:
1203 reg = lua_slot_names ();
1204 title = _("Add Lua Callback Hook");
1206 case LuaScriptInfo::Session:
1210 reg = _session->registered_lua_functions ();
1211 title = _("Add Lua Session Script");
1212 param_function = "sess_params";
1218 LuaScriptInfoPtr spi;
1219 ScriptSelector ss (title, type);
1220 switch (ss.run ()) {
1221 case Gtk::RESPONSE_ACCEPT:
1229 std::string script = "";
1232 script = Glib::file_get_contents (spi->path);
1233 } catch (Glib::FileError e) {
1234 string msg = string_compose (_("Cannot read script '%1': %2"), spi->path, e.what());
1235 Gtk::MessageDialog am (msg);
1240 LuaScriptParamList lsp = LuaScriptParams::script_params (spi, param_function);
1242 ScriptParameterDialog spd (_("Set Script Parameters"), spi, reg, lsp);
1244 if (!spd.need_interation ()) {
1245 switch (spd.run ()) {
1246 case Gtk::RESPONSE_ACCEPT:
1253 LuaScriptParamPtr lspp (new LuaScriptParam("x-script-origin", "", spi->path, false));
1254 lsp.push_back (lspp);
1257 case LuaScriptInfo::EditorAction:
1258 return set_lua_action (id, spd.name(), script, lsp);
1260 case LuaScriptInfo::EditorHook:
1261 return register_lua_slot (spd.name(), script, lsp);
1263 case LuaScriptInfo::Session:
1265 _session->register_lua_function (spd.name(), script, lsp);
1266 } catch (luabridge::LuaException const& e) {
1267 string msg = string_compose (_("Session script '%1' instantiation failed: %2"), spd.name(), e.what ());
1268 Gtk::MessageDialog am (msg);
1270 } catch (SessionException e) {
1271 string msg = string_compose (_("Loading Session script '%1' failed: %2"), spd.name(), e.what ());
1272 Gtk::MessageDialog am (msg);
1282 LuaInstance::get_action_state ()
1286 luabridge::LuaRef savedstate ((*_lua_save)());
1287 saved = savedstate.cast<std::string>();
1289 lua.collect_garbage ();
1291 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1292 std::string b64s (b64);
1295 XMLNode* script_node = new XMLNode (X_("ActionScript"));
1296 script_node->set_property (X_("lua"), LUA_VERSION);
1297 script_node->add_content (b64s);
1299 return *script_node;
1303 LuaInstance::get_hook_state ()
1305 XMLNode* script_node = new XMLNode (X_("ActionHooks"));
1306 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1307 script_node->add_child_nocopy (i->second->get_state ());
1309 return *script_node;
1313 LuaInstance::call_action (const int id)
1316 (*_lua_call_action)(id + 1);
1317 lua.collect_garbage_step ();
1318 } catch (luabridge::LuaException const& e) {
1319 cerr << "LuaException:" << e.what () << endl;
1324 LuaInstance::render_action_icon (cairo_t* cr, int w, int h, uint32_t c, void* i) {
1325 int ii = reinterpret_cast<uintptr_t> (i);
1326 instance()->render_icon (ii, cr, w, h, c);
1330 LuaInstance::render_icon (int i, cairo_t* cr, int w, int h, uint32_t clr)
1332 Cairo::Context ctx (cr);
1334 (*_lua_render_icon)(i + 1, (Cairo::Context *)&ctx, w, h, clr);
1335 } catch (luabridge::LuaException const& e) {
1336 cerr << "LuaException:" << e.what () << endl;
1341 LuaInstance::set_lua_action (
1343 const std::string& name,
1344 const std::string& script,
1345 const LuaScriptParamList& args)
1348 lua_State* L = lua.getState();
1349 // get bytcode of factory-function in a sandbox
1350 // (don't allow scripts to interfere)
1351 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1352 const std::string& iconfunc = LuaScripting::get_factory_bytecode (script, "icon", "icn");
1353 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1354 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1355 if ((*i)->optional && !(*i)->is_set) { continue; }
1356 tbl_arg[(*i)->name] = (*i)->value;
1358 (*_lua_add_action)(id + 1, name, script, bytecode, iconfunc, tbl_arg);
1359 ActionChanged (id, name); /* EMIT SIGNAL */
1360 } catch (luabridge::LuaException const& e) {
1361 cerr << "LuaException:" << e.what () << endl;
1364 _session->set_dirty ();
1369 LuaInstance::remove_lua_action (const int id)
1372 (*_lua_del_action)(id + 1);
1373 } catch (luabridge::LuaException const& e) {
1374 cerr << "LuaException:" << e.what () << endl;
1377 ActionChanged (id, ""); /* EMIT SIGNAL */
1378 _session->set_dirty ();
1383 LuaInstance::lua_action_name (const int id, std::string& rv)
1386 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1390 if (ref["name"].isString()) {
1391 rv = ref["name"].cast<std::string>();
1395 } catch (luabridge::LuaException const& e) {
1396 cerr << "LuaException:" << e.what () << endl;
1402 std::vector<std::string>
1403 LuaInstance::lua_action_names ()
1405 std::vector<std::string> rv;
1406 for (int i = 0; i < 9; ++i) {
1408 if (lua_action_name (i, name)) {
1409 rv.push_back (name);
1416 LuaInstance::lua_action_has_icon (const int id)
1419 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1423 if (ref["icon"].isBoolean()) {
1424 return ref["icon"].cast<bool>();
1426 } catch (luabridge::LuaException const& e) {
1427 cerr << "LuaException:" << e.what () << endl;
1433 LuaInstance::lua_action (const int id, std::string& name, std::string& script, LuaScriptParamList& args)
1436 luabridge::LuaRef ref ((*_lua_get_action)(id + 1));
1440 if (!ref["name"].isString()) {
1443 if (!ref["script"].isString()) {
1446 if (!ref["args"].isTable()) {
1449 name = ref["name"].cast<std::string>();
1450 script = ref["script"].cast<std::string>();
1453 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1457 args = LuaScriptParams::script_params (lsi, "action_params");
1458 luabridge::LuaRef rargs (ref["args"]);
1459 LuaScriptParams::ref_to_params (args, &rargs);
1461 } catch (luabridge::LuaException const& e) {
1462 cerr << "LuaException:" << e.what () << endl;
1469 LuaInstance::register_lua_slot (const std::string& name, const std::string& script, const ARDOUR::LuaScriptParamList& args)
1471 /* parse script, get ActionHook(s) from script */
1475 l.Print.connect (&_lua_print);
1476 lua_State* L = l.getState();
1478 l.do_command ("function ardour () end");
1479 l.do_command (script);
1480 luabridge::LuaRef signals = luabridge::getGlobal (L, "signals");
1481 if (signals.isFunction()) {
1484 } catch (luabridge::LuaException const& e) {
1485 cerr << "LuaException:" << e.what () << endl;
1489 cerr << "Script registered no hooks." << endl;
1493 /* register script w/args, get entry-point / ID */
1496 LuaCallbackPtr p (new LuaCallback (_session, name, script, ah, args));
1497 _callbacks.insert (std::make_pair(p->id(), p));
1498 p->drop_callback.connect (_slotcon, MISSING_INVALIDATOR, boost::bind (&LuaInstance::unregister_lua_slot, this, p->id()), gui_context());
1499 SlotChanged (p->id(), p->name(), p->signals()); /* EMIT SIGNAL */
1501 } catch (luabridge::LuaException const& e) {
1502 cerr << "LuaException:" << e.what () << endl;
1504 _session->set_dirty ();
1509 LuaInstance::unregister_lua_slot (const PBD::ID& id)
1511 LuaCallbackMap::iterator i = _callbacks.find (id);
1512 if (i != _callbacks.end()) {
1513 SlotChanged (id, "", ActionHook()); /* EMIT SIGNAL */
1514 _callbacks.erase (i);
1517 _session->set_dirty ();
1521 std::vector<PBD::ID>
1522 LuaInstance::lua_slots () const
1524 std::vector<PBD::ID> rv;
1525 for (LuaCallbackMap::const_iterator i = _callbacks.begin(); i != _callbacks.end(); ++i) {
1526 rv.push_back (i->first);
1532 LuaInstance::lua_slot_name (const PBD::ID& id, std::string& name) const
1534 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1535 if (i != _callbacks.end()) {
1536 name = i->second->name();
1542 std::vector<std::string>
1543 LuaInstance::lua_slot_names () const
1545 std::vector<std::string> rv;
1546 std::vector<PBD::ID> ids = lua_slots();
1547 for (std::vector<PBD::ID>::const_iterator i = ids.begin(); i != ids.end(); ++i) {
1549 if (lua_slot_name (*i, name)) {
1550 rv.push_back (name);
1557 LuaInstance::lua_slot (const PBD::ID& id, std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1559 LuaCallbackMap::const_iterator i = _callbacks.find (id);
1560 if (i == _callbacks.end()) {
1561 return false; // error
1563 return i->second->lua_slot (name, script, ah, args);
1566 ///////////////////////////////////////////////////////////////////////////////
1568 LuaCallback::LuaCallback (Session *s,
1569 const std::string& name,
1570 const std::string& script,
1571 const ActionHook& ah,
1572 const ARDOUR::LuaScriptParamList& args)
1573 : SessionHandlePtr (s)
1578 // TODO: allow to reference object (e.g region)
1581 lua_State* L = lua.getState();
1582 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
1583 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
1584 if ((*i)->optional && !(*i)->is_set) { continue; }
1585 tbl_arg[(*i)->name] = (*i)->value;
1589 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
1590 (*_lua_add)(name, script, bytecode, tbl_arg);
1591 } catch (luabridge::LuaException const& e) {
1592 cerr << "LuaException:" << e.what () << endl;
1593 throw failed_constructor ();
1600 LuaCallback::LuaCallback (Session *s, XMLNode & node)
1601 : SessionHandlePtr (s)
1603 XMLNode* child = NULL;
1604 if (node.name() != X_("LuaCallback")
1605 || !node.property ("signals")
1606 || !node.property ("id")
1607 || !node.property ("name")) {
1608 throw failed_constructor ();
1611 for (XMLNodeList::const_iterator n = node.children ().begin (); n != node.children ().end (); ++n) {
1612 if (!(*n)->is_content ()) { continue; }
1617 throw failed_constructor ();
1622 _id = PBD::ID (node.property ("id")->value ());
1623 _name = node.property ("name")->value ();
1624 _signals = ActionHook (node.property ("signals")->value ());
1627 guchar* buf = g_base64_decode (child->content ().c_str (), &size);
1629 (*_lua_load)(std::string ((const char*)buf, size));
1630 } catch (luabridge::LuaException const& e) {
1631 cerr << "LuaException:" << e.what () << endl;
1638 LuaCallback::~LuaCallback ()
1648 LuaCallback::get_state (void)
1652 luabridge::LuaRef savedstate ((*_lua_save)());
1653 saved = savedstate.cast<std::string>();
1656 lua.collect_garbage (); // this may be expensive:
1657 /* Editor::instant_save() calls Editor::get_state() which
1658 * calls LuaInstance::get_hook_state() which in turn calls
1659 * this LuaCallback::get_state() for every registered hook.
1661 * serialize in _lua_save() allocates many small strings
1662 * on the lua-stack, collecting them all may take a ms.
1665 gchar* b64 = g_base64_encode ((const guchar*)saved.c_str (), saved.size ());
1666 std::string b64s (b64);
1669 XMLNode* script_node = new XMLNode (X_("LuaCallback"));
1670 script_node->set_property (X_("lua"), LUA_VERSION);
1671 script_node->set_property (X_("id"), _id.to_s ());
1672 script_node->set_property (X_("name"), _name);
1673 script_node->set_property (X_("signals"), _signals.to_string ());
1674 script_node->add_content (b64s);
1675 return *script_node;
1679 LuaCallback::init (void)
1681 lua.Print.connect (&_lua_print);
1684 "function ScriptManager ()"
1685 " local self = { script = {}, instance = {} }"
1687 " local addinternal = function (n, s, f, a)"
1688 " assert(type(n) == 'string', 'Name must be string')"
1689 " assert(type(s) == 'string', 'Script must be string')"
1690 " assert(type(f) == 'function', 'Factory is a not a function')"
1691 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
1692 " self.script = { ['n'] = n, ['s'] = s, ['f'] = f, ['a'] = a }"
1693 " local env = _ENV; env.f = nil env.debug = nil os.exit = nil require = nil dofile = nil loadfile = nil package = nil"
1694 " self.instance = load (string.dump(f, true), nil, nil, env)(a)"
1697 " local call = function (...)"
1698 " if type(self.instance) == 'function' then"
1699 " local status, err = pcall (self.instance, ...)"
1700 " if not status then"
1701 " print ('callback \"'.. self.script['n'] .. '\": ', err)" // error out
1702 " self.script = nil"
1703 " self.instance = nil"
1711 " local add = function (n, s, b, a)"
1712 " assert(type(b) == 'string', 'ByteCode must be string')"
1713 " load (b)()" // assigns f
1714 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
1715 " addinternal (n, s, load(f), a)"
1718 " local get = function ()"
1719 " if type(self.instance) == 'function' and type(self.script['n']) == 'string' then"
1720 " return { ['name'] = self.script['n'],"
1721 " ['script'] = self.script['s'],"
1722 " ['args'] = self.script['a'] }"
1729 " local function basic_serialize (o)"
1730 " if type(o) == \"number\" then"
1731 " return tostring(o)"
1733 " return string.format(\"%q\", o)"
1737 " local function serialize (name, value)"
1738 " local rv = name .. ' = '"
1739 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
1740 " return rv .. basic_serialize(value) .. ' '"
1741 " elseif type(value) == \"table\" then"
1743 " for k,v in pairs(value) do"
1744 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
1745 " rv = rv .. serialize(fieldname, v) .. ' '"
1748 " elseif type(value) == \"function\" then"
1749 " return rv .. string.format(\"%q\", string.dump(value, true))"
1750 " elseif type(value) == \"boolean\" then"
1751 " return rv .. tostring (value)"
1753 " error('cannot save a ' .. type(value))"
1759 " local save = function ()"
1760 " return (serialize('s', self.script))"
1763 " local restore = function (state)"
1766 " addinternal (s['n'], s['s'], load(s['f']), s['a'])"
1769 " return { call = call, add = add, get = get,"
1770 " restore = restore, save = save}"
1773 " manager = ScriptManager ()"
1774 " ScriptManager = nil"
1777 lua_State* L = lua.getState();
1780 luabridge::LuaRef lua_mgr = luabridge::getGlobal (L, "manager");
1781 lua.do_command ("manager = nil"); // hide it.
1782 lua.do_command ("collectgarbage()");
1784 _lua_add = new luabridge::LuaRef(lua_mgr["add"]);
1785 _lua_get = new luabridge::LuaRef(lua_mgr["get"]);
1786 _lua_call = new luabridge::LuaRef(lua_mgr["call"]);
1787 _lua_save = new luabridge::LuaRef(lua_mgr["save"]);
1788 _lua_load = new luabridge::LuaRef(lua_mgr["restore"]);
1790 } catch (luabridge::LuaException const& e) {
1791 fatal << string_compose (_("programming error: %1"),
1792 X_("Failed to setup Lua callback interpreter"))
1794 abort(); /*NOTREACHED*/
1797 LuaInstance::register_classes (L);
1799 luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
1800 lua_setglobal (L, "Editor");
1804 LuaCallback::lua_slot (std::string& name, std::string& script, ActionHook& ah, ARDOUR::LuaScriptParamList& args)
1806 // TODO consolidate w/ LuaInstance::lua_action()
1808 luabridge::LuaRef ref = (*_lua_get)();
1812 if (!ref["name"].isString()) {
1815 if (!ref["script"].isString()) {
1818 if (!ref["args"].isTable()) {
1823 name = ref["name"].cast<std::string> ();
1824 script = ref["script"].cast<std::string> ();
1827 LuaScriptInfoPtr lsi = LuaScripting::script_info (script);
1831 args = LuaScriptParams::script_params (lsi, "action_params");
1832 luabridge::LuaRef rargs (ref["args"]);
1833 LuaScriptParams::ref_to_params (args, &rargs);
1835 } catch (luabridge::LuaException const& e) {
1836 cerr << "LuaException:" << e.what () << endl;
1843 LuaCallback::set_session (ARDOUR::Session *s)
1845 SessionHandlePtr::set_session (s);
1851 lua_State* L = lua.getState();
1852 LuaBindings::set_session (L, _session);
1858 LuaCallback::session_going_away ()
1860 ENSURE_GUI_THREAD (*this, &LuaCallback::session_going_away);
1861 lua.do_command ("collectgarbage();");
1863 SessionHandlePtr::session_going_away ();
1866 drop_callback (); /* EMIT SIGNAL */
1870 LuaCallback::reconnect ()
1872 _connections.drop_connections ();
1873 if ((*_lua_get) ().isNil ()) {
1874 drop_callback (); /* EMIT SIGNAL */
1878 // TODO pass object which emits the signal (e.g region)
1880 // save/load bound objects will be tricky.
1881 // Best idea so far is to save/lookup the PBD::ID
1882 // (either use boost::any indirection or templates for bindable
1883 // object types or a switch statement..)
1885 // _session->route_by_id ()
1886 // _session->track_by_diskstream_id ()
1887 // _session->source_by_id ()
1888 // _session->controllable_by_id ()
1889 // _session->processor_by_id ()
1890 // RegionFactory::region_by_id ()
1892 // TODO loop over objects (if any)
1894 reconnect_object ((void*)0);
1897 template <class T> void
1898 LuaCallback::reconnect_object (T obj)
1900 for (uint32_t i = 0; i < LuaSignal::LAST_SIGNAL; ++i) {
1902 #define ENGINE(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, AudioEngine::instance(), &(AudioEngine::instance()->c)); }
1903 #define SESSION(n,c,p) else if (i == LuaSignal::n) { if (_session) { connect_ ## p (LuaSignal::n, _session, &(_session->c)); } }
1904 #define STATIC(n,c,p) else if (i == LuaSignal::n) { connect_ ## p (LuaSignal::n, obj, c); }
1906 # include "luasignal_syms.h"
1908 PBD::fatal << string_compose (_("programming error: %1: %2"), "Impossible LuaSignal type", i) << endmsg;
1909 abort(); /*NOTREACHED*/
1918 template <typename T, typename S> void
1919 LuaCallback::connect_0 (enum LuaSignal::LuaSignal ls, T ref, S *signal) {
1921 _connections, invalidator (*this),
1922 boost::bind (&LuaCallback::proxy_0<T>, this, ls, ref),
1926 template <typename T, typename C1> void
1927 LuaCallback::connect_1 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal1<void, C1> *signal) {
1929 _connections, invalidator (*this),
1930 boost::bind (&LuaCallback::proxy_1<T, C1>, this, ls, ref, _1),
1934 template <typename T, typename C1, typename C2> void
1935 LuaCallback::connect_2 (enum LuaSignal::LuaSignal ls, T ref, PBD::Signal2<void, C1, C2> *signal) {
1937 _connections, invalidator (*this),
1938 boost::bind (&LuaCallback::proxy_2<T, C1, C2>, this, ls, ref, _1, _2),
1942 template <typename T> void
1943 LuaCallback::proxy_0 (enum LuaSignal::LuaSignal ls, T ref) {
1946 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref));
1947 if (! rv.cast<bool> ()) {
1951 /* destroy LuaRef ^^ first before calling drop_callback() */
1953 drop_callback (); /* EMIT SIGNAL */
1957 template <typename T, typename C1> void
1958 LuaCallback::proxy_1 (enum LuaSignal::LuaSignal ls, T ref, C1 a1) {
1961 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1));
1962 if (! rv.cast<bool> ()) {
1967 drop_callback (); /* EMIT SIGNAL */
1971 template <typename T, typename C1, typename C2> void
1972 LuaCallback::proxy_2 (enum LuaSignal::LuaSignal ls, T ref, C1 a1, C2 a2) {
1975 const luabridge::LuaRef& rv ((*_lua_call)((int)ls, ref, a1, a2));
1976 if (! rv.cast<bool> ()) {
1981 drop_callback (); /* EMIT SIGNAL */