Optimize automation-event process splitting
[ardour.git] / gtk2_ardour / lv2_plugin_ui.cc
1 /*
2     Copyright (C) 2008-2012 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <gtkmm/stock.h>
21
22 #include "ardour/lv2_plugin.h"
23 #include "ardour/session.h"
24 #include "pbd/error.h"
25 #include "pbd/stacktrace.h"
26
27 #include "gui_thread.h"
28 #include "lv2_plugin_ui.h"
29 #include "timers.h"
30
31 #include "gtkmm2ext/utils.h"
32
33 #include "lv2/lv2plug.in/ns/extensions/ui/ui.h"
34
35 #include <lilv/lilv.h>
36 #include <suil/suil.h>
37
38 #include "pbd/i18n.h"
39
40 using namespace ARDOUR;
41 using namespace Gtk;
42 using namespace PBD;
43
44 #define NS_UI "http://lv2plug.in/ns/extensions/ui#"
45
46 static SuilHost* ui_host = NULL;
47
48 void
49 LV2PluginUI::write_from_ui(void*       controller,
50                            uint32_t    port_index,
51                            uint32_t    buffer_size,
52                            uint32_t    format,
53                            const void* buffer)
54 {
55         LV2PluginUI* me = (LV2PluginUI*)controller;
56         if (format == 0) {
57                 if (port_index >= me->_controllables.size()) {
58                         return;
59                 }
60
61                 boost::shared_ptr<AutomationControl> ac = me->_controllables[port_index];
62
63                 me->_updates.insert (port_index);
64
65                 if (ac) {
66                         ac->set_value(*(const float*)buffer, Controllable::NoGroup);
67                 }
68         } else if (format == URIMap::instance().urids.atom_eventTransfer) {
69
70                 const int cnt = me->_pi->get_count();
71                 for (int i=0; i < cnt; i++ ) {
72                         boost::shared_ptr<LV2Plugin> lv2i = boost::dynamic_pointer_cast<LV2Plugin> (me->_pi->plugin(i));
73                         lv2i->write_from_ui(port_index, format, buffer_size, (const uint8_t*)buffer);
74                 }
75         }
76 }
77
78 void
79 LV2PluginUI::write_to_ui(void*       controller,
80                          uint32_t    port_index,
81                          uint32_t    buffer_size,
82                          uint32_t    format,
83                          const void* buffer)
84 {
85         LV2PluginUI* me = (LV2PluginUI*)controller;
86         if (me->_inst) {
87                 suil_instance_port_event((SuilInstance*)me->_inst,
88                                          port_index, buffer_size, format, buffer);
89         }
90 }
91
92 uint32_t
93 LV2PluginUI::port_index(void* controller, const char* symbol)
94 {
95         return ((LV2PluginUI*)controller)->_lv2->port_index(symbol);
96 }
97
98 void
99 LV2PluginUI::touch(void*    controller,
100                    uint32_t port_index,
101                    bool     grabbed)
102 {
103         LV2PluginUI* me = (LV2PluginUI*)controller;
104         if (port_index >= me->_controllables.size()) {
105                 return;
106         }
107         if (!me->_lv2->parameter_is_control(port_index) || !me->_lv2->parameter_is_input(port_index)) {
108                 return;
109         }
110
111         ControllableRef control = me->_controllables[port_index];
112         if (grabbed) {
113                 control->start_touch(control->session().transport_sample());
114         } else {
115                 control->stop_touch(control->session().transport_sample());
116         }
117 }
118
119 void
120 LV2PluginUI::set_path_property (int response,
121                                 const ParameterDescriptor& desc,
122                                 Gtk::FileChooserDialog*    widget)
123 {
124         if (response == Gtk::RESPONSE_ACCEPT) {
125                 plugin->set_property (desc.key, Variant (Variant::PATH, widget->get_filename()));
126         }
127 #if 0
128         widget->hide ();
129         delete_when_idle (widget);
130 #else
131         delete widget;
132 #endif
133         active_parameter_requests.erase (desc.key);
134 }
135
136 uint32_t
137 LV2PluginUI::request_parameter (void* handle, LV2_URID key)
138 {
139         LV2PluginUI* me = (LV2PluginUI*)handle;
140
141         /* This will return `PropertyDescriptors nothing` when not found */
142         const ParameterDescriptor& desc (me->_lv2->get_property_descriptor(key));
143         if (desc.datatype != Variant::PATH) {
144                 return 0;
145         }
146
147 #if 0 // MODAL, blocking
148
149         Gtk::FileChooserDialog* lv2ui_file_dialog (desc.label, FILE_CHOOSER_ACTION_OPEN);
150         Gtkmm2ext::add_volume_shortcuts (lv2ui_file_dialog);
151         lv2ui_file_dialog.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
152         lv2ui_file_dialog.add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
153         lv2ui_file_dialog.set_default_response(Gtk::RESPONSE_ACCEPT);
154         if (_file_dialog.run()= Gtk::RESPONSE_ACCEPT) {
155                 me->plugin->set_property (desc.key, Variant(Variant::PATH, lv2ui_file_dialog.get_filename()));
156         }
157         return 0;
158
159 #else
160
161         if (me->active_parameter_requests.find (key) != me->active_parameter_requests.end()) {
162                 return 0; /* already showing dialog */
163         }
164         me->active_parameter_requests.insert (key);
165
166         Gtk::FileChooserDialog* lv2ui_file_dialog = new Gtk::FileChooserDialog(desc.label, FILE_CHOOSER_ACTION_OPEN);
167         Gtkmm2ext::add_volume_shortcuts (*lv2ui_file_dialog);
168         lv2ui_file_dialog->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
169         lv2ui_file_dialog->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
170         lv2ui_file_dialog->set_default_response(Gtk::RESPONSE_ACCEPT);
171
172         /* this assumes  announce_property_values() was called, or
173          * the plugin has previously sent a patch:Set */
174         const Variant& value = me->_lv2->get_property_value (desc.key);
175         if (value.type() == Variant::PATH) {
176                 lv2ui_file_dialog->set_filename (value.get_path());
177         }
178
179 #if 0 // TODO mime-type, file-extension filter, get from LV2 Parameter Property
180         FileFilter file_ext_filter;
181         file_ext_filter.add_pattern ("*.foo");
182         file_ext_filter.set_name ("Foo File");
183         lv2ui_file_dialog.add_filter (file_ext_filter);
184 #endif
185
186         lv2ui_file_dialog->signal_response().connect (sigc::bind (sigc::mem_fun (*me, &LV2PluginUI::set_path_property), desc, lv2ui_file_dialog));
187         lv2ui_file_dialog->present();
188         return 0;
189
190 #endif
191 }
192
193 void
194 LV2PluginUI::update_timeout()
195 {
196         _lv2->emit_to_ui(this, &LV2PluginUI::write_to_ui);
197 }
198
199 void
200 LV2PluginUI::on_external_ui_closed(void* controller)
201 {
202         //printf("LV2PluginUI::on_external_ui_closed\n");
203         LV2PluginUI* me = (LV2PluginUI*)controller;
204         me->_screen_update_connection.disconnect();
205         me->_external_ui_ptr = NULL;
206 }
207
208 void
209 LV2PluginUI::control_changed (uint32_t port_index)
210 {
211         /* Must run in GUI thread because we modify _updates with no lock */
212         if (_lv2->get_parameter (port_index) != _values_last_sent_to_ui[port_index]) {
213                 /* current plugin parameter does not match last value received
214                    from GUI, so queue an update to push it to the GUI during
215                    our regular timeout.
216                 */
217                 _updates.insert (port_index);
218         }
219 }
220
221 bool
222 LV2PluginUI::start_updating(GdkEventAny*)
223 {
224         _screen_update_connection.disconnect();
225         _screen_update_connection = Timers::super_rapid_connect
226                 (sigc::mem_fun(*this, &LV2PluginUI::output_update));
227         return false;
228 }
229
230 bool
231 LV2PluginUI::stop_updating(GdkEventAny*)
232 {
233         //cout << "stop_updating" << endl;
234         _screen_update_connection.disconnect();
235         return false;
236 }
237
238 void
239 LV2PluginUI::queue_port_update()
240 {
241         const uint32_t num_ports = _lv2->num_ports();
242         for (uint32_t i = 0; i < num_ports; ++i) {
243                 bool     ok;
244                 uint32_t port = _lv2->nth_parameter(i, ok);
245                 if (ok) {
246                         _updates.insert (port);
247                 }
248         }
249 }
250
251 void
252 LV2PluginUI::output_update()
253 {
254         //cout << "output_update" << endl;
255         if (_external_ui_ptr) {
256                 LV2_EXTERNAL_UI_RUN(_external_ui_ptr);
257                 if (_lv2->is_external_kx() && !_external_ui_ptr) {
258                         // clean up external UI if it closes itself via
259                         // on_external_ui_closed() during run()
260                         //printf("LV2PluginUI::output_update -- UI was closed\n");
261                         //_screen_update_connection.disconnect();
262                         _message_update_connection.disconnect();
263                         if (_inst) {
264                                 suil_instance_free((SuilInstance*)_inst);
265                         }
266                         _inst = NULL;
267                         _external_ui_ptr = NULL;
268                         return;
269                 }
270         }
271
272         if (!_inst) {
273                 return;
274         }
275
276         /* output ports (values set by DSP) need propagating to GUI */
277
278         uint32_t nports = _output_ports.size();
279         for (uint32_t i = 0; i < nports; ++i) {
280                 uint32_t index = _output_ports[i];
281                 float val = _lv2->get_parameter (index);
282
283                 if (val != _values_last_sent_to_ui[index]) {
284                         /* Send to GUI */
285                         suil_instance_port_event ((SuilInstance*)_inst, index, 4, 0, &val);
286                         /* Cache current value */
287                         _values_last_sent_to_ui[index] = val;
288                 }
289         }
290
291         /* Input ports marked for update because the control value changed
292            since the last redisplay.
293         */
294
295         for (Updates::iterator i = _updates.begin(); i != _updates.end(); ++i) {
296                 float val = _lv2->get_parameter (*i);
297                 /* push current value to the GUI */
298                 suil_instance_port_event ((SuilInstance*)_inst, (*i), 4, 0, &val);
299                 _values_last_sent_to_ui[(*i)] = val;
300         }
301
302         _updates.clear ();
303 }
304
305 LV2PluginUI::LV2PluginUI(boost::shared_ptr<PluginInsert> pi,
306                          boost::shared_ptr<LV2Plugin>    lv2p)
307         : PlugUIBase(pi)
308         , _pi(pi)
309         , _lv2(lv2p)
310         , _gui_widget(NULL)
311         , _values_last_sent_to_ui(NULL)
312         , _external_ui_ptr(NULL)
313         , _inst(NULL)
314 {
315         _ardour_buttons_box.set_spacing (6);
316         _ardour_buttons_box.set_border_width (6);
317         _ardour_buttons_box.pack_end (focus_button, false, false);
318         _ardour_buttons_box.pack_end (bypass_button, false, false, 4);
319         if (pi->controls().size() > 0) {
320                 _ardour_buttons_box.pack_end (reset_button, false, false, 4);
321         }
322         _ardour_buttons_box.pack_end (delete_button, false, false);
323         _ardour_buttons_box.pack_end (save_button, false, false);
324         _ardour_buttons_box.pack_end (add_button, false, false);
325         _ardour_buttons_box.pack_end (_preset_combo, false, false);
326         _ardour_buttons_box.pack_end (_preset_modified, false, false);
327         _ardour_buttons_box.pack_end (pin_management_button, false, false);
328
329         plugin->PresetLoaded.connect (*this, invalidator (*this), boost::bind (&LV2PluginUI::queue_port_update, this), gui_context ());
330 }
331
332 void
333 LV2PluginUI::lv2ui_instantiate(const std::string& title)
334 {
335         bool          is_external_ui = _lv2->is_external_ui();
336         LV2_Feature** features_src   = const_cast<LV2_Feature**>(_lv2->features());
337         LV2_Feature** features       = const_cast<LV2_Feature**>(_lv2->features());
338         size_t        features_count = 0;
339         while (*features++) {
340                 ++features_count;
341         }
342
343         if (is_external_ui) {
344                 features = (LV2_Feature**)malloc(sizeof(LV2_Feature*) * (features_count + 4));
345         } else {
346                 features = (LV2_Feature**)malloc(sizeof(LV2_Feature*) * (features_count + 3));
347         }
348
349         size_t fi = 0;
350         for (; fi < features_count; ++fi) {
351                 features[fi] = features_src[fi];
352         }
353
354         _lv2ui_request_paramater.handle = this;
355         _lv2ui_request_paramater.request = LV2PluginUI::request_parameter;
356         _lv2ui_request_feature.URI  = LV2_UI_PREFIX "requestParameter";
357         _lv2ui_request_feature.data = &_lv2ui_request_paramater;
358
359         features[fi++] = &_lv2ui_request_feature;
360
361         Gtk::Alignment* container = NULL;
362         if (is_external_ui) {
363                 _external_ui_host.ui_closed       = LV2PluginUI::on_external_ui_closed;
364                 _external_ui_host.plugin_human_id = strdup(title.c_str());
365
366                 _external_ui_feature.URI  = LV2_EXTERNAL_UI_URI;
367                 _external_ui_feature.data = &_external_ui_host;
368
369                 _external_kxui_feature.URI  = LV2_EXTERNAL_UI_KX__Host;
370                 _external_kxui_feature.data = &_external_ui_host;
371
372                 features[fi++] = &_external_kxui_feature;
373                 features[fi++] = &_external_ui_feature;
374         } else {
375                 if (_ardour_buttons_box.get_parent()) {
376                         _ardour_buttons_box.get_parent()->remove(_ardour_buttons_box);
377                 }
378                 pack_start(_ardour_buttons_box, false, false);
379                 _ardour_buttons_box.show_all();
380
381                 _gui_widget = Gtk::manage((container = new Gtk::Alignment()));
382                 pack_start(*_gui_widget, true, true);
383                 _gui_widget->show();
384
385                 _parent_feature.URI  = LV2_UI__parent;
386                 _parent_feature.data = _gui_widget->gobj();
387
388                 features[fi++] = &_parent_feature;
389         }
390
391         features[fi] = NULL;
392         assert (fi == features_count + (is_external_ui ? 3 : 2));
393
394         if (!ui_host) {
395                 ui_host = suil_host_new(LV2PluginUI::write_from_ui,
396                                         LV2PluginUI::port_index,
397                                         NULL, NULL);
398                 suil_host_set_touch_func(ui_host, LV2PluginUI::touch);
399         }
400         const char* container_type = (is_external_ui)
401                 ? NS_UI "external"
402                 : NS_UI "GtkUI";
403
404         if (_lv2->has_message_output()) {
405                 _lv2->enable_ui_emission();
406         }
407
408         const LilvUI*   ui     = (const LilvUI*)_lv2->c_ui();
409         const LilvNode* bundle = lilv_ui_get_bundle_uri(ui);
410         const LilvNode* binary = lilv_ui_get_binary_uri(ui);
411 #ifdef HAVE_LILV_0_21_3
412         char* ui_bundle_path = lilv_file_uri_parse(lilv_node_as_uri(bundle), NULL);
413         char* ui_binary_path = lilv_file_uri_parse(lilv_node_as_uri(binary), NULL);
414 #else
415         char* ui_bundle_path = strdup(lilv_uri_to_path(lilv_node_as_uri(bundle)));
416         char* ui_binary_path = strdup(lilv_uri_to_path(lilv_node_as_uri(binary)));
417 #endif
418         if (!ui_bundle_path || !ui_binary_path) {
419                 error << _("failed to get path for UI bindle or binary") << endmsg;
420                 free(ui_bundle_path);
421                 free(ui_binary_path);
422                 free(features);
423                 return;
424         }
425
426         _inst = suil_instance_new(
427                 ui_host,
428                 this,
429                 container_type,
430                 _lv2->uri(),
431                 lilv_node_as_uri(lilv_ui_get_uri(ui)),
432                 lilv_node_as_uri((const LilvNode*)_lv2->c_ui_type()),
433                 ui_bundle_path,
434                 ui_binary_path,
435                 features);
436
437         free(ui_bundle_path);
438         free(ui_binary_path);
439         free(features);
440
441         if (!_inst) {
442                 error << _("failed to instantiate LV2 GUI") << endmsg;
443                 return;
444         }
445
446 #define GET_WIDGET(inst) suil_instance_get_widget((SuilInstance*)inst);
447
448         const uint32_t num_ports = _lv2->num_ports();
449         for (uint32_t i = 0; i < num_ports; ++i) {
450                 if (_lv2->parameter_is_output(i)
451                     && _lv2->parameter_is_control(i)
452                     && is_update_wanted(i)) {
453                         _output_ports.push_back(i);
454                 }
455         }
456
457         _external_ui_ptr = NULL;
458         if (!is_external_ui) {
459                 GtkWidget* c_widget = (GtkWidget*)GET_WIDGET(_inst);
460                 if (!c_widget) {
461                         error << _("failed to get LV2 UI widget") << endmsg;
462                         suil_instance_free((SuilInstance*)_inst);
463                         _inst = NULL;
464                         return;
465                 }
466                 if (!container->get_child()) {
467                         // Suil didn't add the UI to the container for us, so do it now
468                         container->add(*Gtk::manage(Glib::wrap(c_widget)));
469                 }
470                 container->show_all();
471                 gtk_widget_set_can_focus(c_widget, true);
472                 gtk_widget_grab_focus(c_widget);
473         } else {
474                 _external_ui_ptr = (struct lv2_external_ui*)GET_WIDGET(_inst);
475         }
476
477         _values_last_sent_to_ui = new float[num_ports];
478         _controllables.resize(num_ports);
479
480         for (uint32_t i = 0; i < num_ports; ++i) {
481                 bool     ok;
482                 uint32_t port = _lv2->nth_parameter(i, ok);
483                 if (ok) {
484                         /* Cache initial value of the parameter, regardless of
485                            whether it is input or output
486                         */
487
488                         _values_last_sent_to_ui[port]        = _lv2->get_parameter(port);
489                         _controllables[port] = boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (
490                                 insert->control(Evoral::Parameter(PluginAutomation, 0, port)));
491
492                         if (_lv2->parameter_is_control(port) && _lv2->parameter_is_input(port)) {
493                                 if (_controllables[port]) {
494                                         _controllables[port]->Changed.connect (control_connections, invalidator (*this), boost::bind (&LV2PluginUI::control_changed, this, port), gui_context());
495                                 }
496                         }
497
498                         /* queue for first update ("push") to GUI */
499                         _updates.insert (port);
500                 }
501         }
502
503         if (_lv2->has_message_output()) {
504                 _message_update_connection = Timers::super_rapid_connect (
505                         sigc::mem_fun(*this, &LV2PluginUI::update_timeout));
506         }
507 }
508
509 void
510 LV2PluginUI::grab_focus()
511 {
512         if (_inst && !_lv2->is_external_ui()) {
513                 GtkWidget* c_widget = (GtkWidget*)GET_WIDGET(_inst);
514                 gtk_widget_grab_focus(c_widget);
515         }
516 }
517
518 void
519 LV2PluginUI::lv2ui_free()
520 {
521         stop_updating (0);
522
523         if (_gui_widget) {
524                 remove (*_gui_widget);
525                 _gui_widget = NULL;
526         }
527
528         if (_inst) {
529                 suil_instance_free((SuilInstance*)_inst);
530                 _inst = NULL;
531         }
532 }
533
534 LV2PluginUI::~LV2PluginUI ()
535 {
536         delete [] _values_last_sent_to_ui;
537
538         _message_update_connection.disconnect();
539         _screen_update_connection.disconnect();
540
541         if (_external_ui_ptr && _lv2->is_external_kx()) {
542                 LV2_EXTERNAL_UI_HIDE(_external_ui_ptr);
543         }
544         lv2ui_free();
545         _external_ui_ptr = NULL;
546 }
547
548 int
549 LV2PluginUI::get_preferred_height()
550 {
551         Gtk::Requisition r = size_request();
552         return r.height;
553 }
554
555 int
556 LV2PluginUI::get_preferred_width()
557 {
558         Gtk::Requisition r = size_request();
559         return r.width;
560 }
561
562 bool
563 LV2PluginUI::resizable()
564 {
565         return _lv2->ui_is_resizable();
566 }
567
568 int
569 LV2PluginUI::package(Gtk::Window& win)
570 {
571         if (_external_ui_ptr) {
572                 _win_ptr = &win;
573         } else {
574                 /* forward configure events to plugin window */
575                 win.signal_configure_event().connect(
576                         sigc::mem_fun(*this, &LV2PluginUI::configure_handler));
577                 win.signal_map_event().connect(
578                         sigc::mem_fun(*this, &LV2PluginUI::start_updating));
579                 win.signal_unmap_event().connect(
580                         sigc::mem_fun(*this, &LV2PluginUI::stop_updating));
581         }
582         return 0;
583 }
584
585 bool
586 LV2PluginUI::configure_handler(GdkEventConfigure*)
587 {
588         std::cout << "CONFIGURE" << std::endl;
589         return false;
590 }
591
592 bool
593 LV2PluginUI::is_update_wanted(uint32_t /*index*/)
594 {
595         /* FIXME: use port notification properties
596            and/or new UI extension subscription methods
597         */
598         return true;
599 }
600
601 bool
602 LV2PluginUI::on_window_show(const std::string& title)
603 {
604         //cout << "on_window_show - " << title << endl; flush(cout);
605
606         if (_lv2->is_external_ui()) {
607                 if (_external_ui_ptr) {
608                         _screen_update_connection.disconnect();
609                         _message_update_connection.disconnect();
610                         LV2_EXTERNAL_UI_SHOW(_external_ui_ptr);
611                         _screen_update_connection = Timers::super_rapid_connect
612                         (sigc::mem_fun(*this, &LV2PluginUI::output_update));
613                         if (_lv2->has_message_output()) {
614                                 _message_update_connection = Timers::super_rapid_connect (
615                                         sigc::mem_fun(*this, &LV2PluginUI::update_timeout));
616                         }
617                         return false;
618                 }
619                 lv2ui_instantiate(title);
620                 if (!_external_ui_ptr) {
621                         return false;
622                 }
623
624                 _screen_update_connection.disconnect();
625                 _message_update_connection.disconnect();
626                 LV2_EXTERNAL_UI_SHOW(_external_ui_ptr);
627                 _screen_update_connection = Timers::super_rapid_connect
628                         (sigc::mem_fun(*this, &LV2PluginUI::output_update));
629                 if (_lv2->has_message_output()) {
630                         _message_update_connection = Timers::super_rapid_connect (
631                                 sigc::mem_fun(*this, &LV2PluginUI::update_timeout));
632                 }
633                 return false;
634         } else {
635                 lv2ui_instantiate("gtk2gui");
636         }
637
638         return _inst ? true : false;
639 }
640
641 void
642 LV2PluginUI::on_window_hide()
643 {
644         //printf("LV2PluginUI::on_window_hide\n");
645
646         if (_lv2->is_external_ui()) {
647                 if (!_external_ui_ptr) { return; }
648                 LV2_EXTERNAL_UI_HIDE(_external_ui_ptr);
649                 if (!_lv2->is_external_kx()) { return ; }
650                 _message_update_connection.disconnect();
651                 _screen_update_connection.disconnect();
652                 _external_ui_ptr = NULL;
653                 suil_instance_free((SuilInstance*)_inst);
654                 _inst = NULL;
655         } else {
656                 lv2ui_free();
657         }
658 }