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