Add a PianoKeyboard to GenericUI (on a MIDI track)
[ardour.git] / gtk2_ardour / generic_pluginui.cc
1 /*
2     Copyright (C) 2000 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
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.
13
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., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <climits>
25 #include <cerrno>
26 #include <cmath>
27 #include <string>
28 #include <vector>
29
30 #include <gtkmm/separator.h>
31
32 #include "pbd/stl_delete.h"
33 #include "pbd/unwind.h"
34 #include "pbd/xml++.h"
35 #include "pbd/failed_constructor.h"
36
37 #include "evoral/midi_events.h"
38 #include "evoral/PatchChange.hpp"
39
40 #include "midi++/midnam_patch.h"
41
42 #include "ardour/midi_patch_manager.h"
43 #include "ardour/midi_track.h"
44 #include "ardour/plugin.h"
45 #include "ardour/plugin_insert.h"
46 #include "ardour/session.h"
47 #include "ardour/value_as_string.h"
48
49 #include "gtkmm2ext/menu_elems.h"
50 #include "gtkmm2ext/utils.h"
51 #include "gtkmm2ext/doi.h"
52
53 #include "widgets/ardour_knob.h"
54 #include "widgets/click_box.h"
55 #include "widgets/fastmeter.h"
56 #include "widgets/slider_controller.h"
57 #include "widgets/tooltips.h"
58
59 #include "plugin_ui.h"
60 #include "plugin_display.h"
61 #include "gui_thread.h"
62 #include "automation_controller.h"
63 #include "gain_meter.h"
64 #include "timers.h"
65 #include "ui_config.h"
66
67 #include "pbd/i18n.h"
68
69 using namespace std;
70 using namespace ARDOUR;
71 using namespace PBD;
72 using namespace Gtkmm2ext;
73 using namespace ArdourWidgets;
74 using namespace Gtk;
75 using namespace ARDOUR_UI_UTILS;
76
77 GenericPluginUI::GenericPluginUI (boost::shared_ptr<PluginInsert> pi, bool scrollable)
78         : PlugUIBase (pi)
79         , automation_menu (0)
80         , is_scrollable(scrollable)
81         , _plugin_pianokeyboard_expander (_("MIDI Keyboard"))
82         , _piano (0)
83         , _pianomm (0)
84         , _piano_velocity (*manage (new Adjustment (100, 1, 127, 1, 16)))
85         , _piano_channel (*manage (new Adjustment (0, 1, 16, 1, 1)))
86 {
87         set_name ("PluginEditor");
88         set_border_width (10);
89         //set_homogeneous (false);
90
91         pack_start (main_contents, true, true);
92         settings_box.set_homogeneous (false);
93
94         HBox* constraint_hbox = manage (new HBox);
95         HBox* smaller_hbox = manage (new HBox);
96         smaller_hbox->set_spacing (4);
97         Label* combo_label = manage (new Label (_("<span size=\"large\">Presets</span>")));
98         combo_label->set_use_markup (true);
99
100         latency_button.signal_clicked.connect (sigc::mem_fun (*this, &PlugUIBase::latency_button_clicked));
101         set_latency_label ();
102
103         smaller_hbox->pack_start (latency_button, false, false, 4);
104         smaller_hbox->pack_start (pin_management_button, false, false, 4);
105         smaller_hbox->pack_start (_preset_combo, false, false);
106         smaller_hbox->pack_start (_preset_modified, false, false);
107         smaller_hbox->pack_start (add_button, false, false);
108         smaller_hbox->pack_start (save_button, false, false);
109         smaller_hbox->pack_start (delete_button, false, false);
110         if (pi->controls().size() > 0) {
111                 smaller_hbox->pack_start (reset_button, false, false, 4);
112         }
113         smaller_hbox->pack_start (bypass_button, false, true, 4);
114
115         automation_manual_all_button.set_text(_("Manual"));
116         automation_manual_all_button.set_name (X_("generic button"));
117         automation_play_all_button.set_text(_("Play"));
118         automation_play_all_button.set_name (X_("generic button"));
119         automation_write_all_button.set_text(_("Write"));
120         automation_write_all_button.set_name (X_("generic button"));
121         automation_touch_all_button.set_text(_("Touch"));
122         automation_touch_all_button.set_name (X_("generic button"));
123
124         constraint_hbox->set_spacing (5);
125         constraint_hbox->set_homogeneous (false);
126
127         VBox* v1_box = manage (new VBox);
128         VBox* v2_box = manage (new VBox);
129         if (pi->is_instrument ()) {
130                 if (dynamic_cast<MidiTrack*> (pi->owner())) {
131                         _piano = (PianoKeyboard*)piano_keyboard_new();
132                         _pianomm = Glib::wrap((GtkWidget*)_piano);
133                         _pianomm->set_flags(Gtk::CAN_FOCUS);
134                         _pianomm->add_events(Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
135
136                         g_signal_connect (G_OBJECT (_piano), "note-on", G_CALLBACK (GenericPluginUI::_note_on_event_handler), this);
137                         g_signal_connect (G_OBJECT (_piano), "note-off", G_CALLBACK (GenericPluginUI::_note_off_event_handler), this);
138
139                         HBox* box = manage (new HBox);
140                         box->pack_start (*manage (new Label (_("Channel:"))), false, false);
141                         box->pack_start (_piano_channel, false, false);
142                         box->pack_start (*manage (new Label (_("Velocity:"))), false, false);
143                         box->pack_start (_piano_velocity, false, false);
144
145                         Box* box2 = manage (new HBox ());
146                         box2->pack_start (*box, true, false);
147
148                         _pianobox.set_spacing (4);
149                         _pianobox.pack_start (*box2, true, true);
150                         _pianobox.pack_start (*_pianomm, true, true);
151
152                         _plugin_pianokeyboard_expander.set_expanded(false);
153                         _plugin_pianokeyboard_expander.property_expanded().signal_changed().connect( sigc::mem_fun(*this, &GenericPluginUI::toggle_pianokeyboard));
154
155                         pack_end (_plugin_pianokeyboard_expander, false, false);
156                 }
157         } else {
158                 pack_end (plugin_analysis_expander, false, false);
159         }
160         if (!plugin->get_docs().empty()) {
161                 pack_end (description_expander, false, false);
162         }
163
164         v1_box->set_spacing (6);
165         v1_box->pack_start (*smaller_hbox, false, true);
166         if (pi->controls().size() > 0) {
167                 HBox* automation_hbox = manage (new HBox);
168                 automation_hbox->set_spacing (6);
169                 Label* l = manage (new Label (_("All Automation")));
170                 l->set_alignment (1.0, 0.5);
171                 automation_hbox->pack_start (*l, true, true);
172                 automation_hbox->pack_start (automation_manual_all_button, false, false);
173                 automation_hbox->pack_start (automation_play_all_button, false, false);
174                 automation_hbox->pack_start (automation_write_all_button, false, false);
175                 automation_hbox->pack_start (automation_touch_all_button, false, false);
176                 v1_box->pack_start (*automation_hbox, false, true);
177         }
178         v2_box->pack_start (focus_button, false, true);
179
180         main_contents.pack_start (settings_box, false, false);
181
182         constraint_hbox->pack_end (*v2_box, false, false);
183         constraint_hbox->pack_end (*v1_box, false, false);
184
185         main_contents.pack_start (*constraint_hbox, false, false);
186
187         pi->ActiveChanged.connect (active_connection, invalidator (*this), boost::bind (&GenericPluginUI::processor_active_changed, this, boost::weak_ptr<Processor>(pi)), gui_context());
188
189         bypass_button.set_active (!pi->enabled());
190
191         /* ScrolledWindow will wrap hpacker in a Viewport */
192         scroller.add (hpacker);
193         Viewport* view = static_cast<Viewport*>(scroller.get_child());
194         view->set_shadow_type(Gtk::SHADOW_NONE);
195
196         main_contents.pack_start (scroller, true, true);
197
198         prefheight = 0;
199         build ();
200
201         if (insert->plugin()->has_midnam() && insert->plugin()->knows_bank_patch()) {
202                 /* right now PC are sent via MIDI Track controls only */
203                 if (dynamic_cast<MidiTrack*> (insert->owner())) {
204                         build_midi_table ();
205                 }
206         }
207
208         if (is_scrollable) {
209                 scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
210                 scroller.set_name ("PluginEditor");
211         } else {
212                 scroller.signal_size_request().connect (sigc::mem_fun(*this, &GenericPluginUI::scroller_size_request));
213                 scroller.set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER);
214         }
215
216
217         /* Listen for property changes that are not notified normally because
218          * AutomationControl has only support for numeric values currently.
219          * The only case is Variant::PATH for now */
220         plugin->PropertyChanged.connect(*this, invalidator(*this),
221                                         boost::bind(&GenericPluginUI::path_property_changed, this, _1, _2),
222                                         gui_context());
223
224         main_contents.show ();
225 }
226
227 GenericPluginUI::~GenericPluginUI ()
228 {
229         if (output_controls.size() > 0) {
230                 screen_update_connection.disconnect();
231         }
232         delete _pianomm;
233 }
234
235 void
236 GenericPluginUI::scroller_size_request (Gtk::Requisition* a)
237 {
238         Glib::RefPtr<Gdk::Screen> screen = get_screen();
239         if (!screen)
240                 screen = Gdk::Screen::get_default();
241
242         int maximum_width;
243         {
244                 Gdk::Rectangle monitor;
245                 const int monitor_num = screen->get_monitor_at_window (get_window ());
246                 screen->get_monitor_geometry (
247                                 (monitor_num < 0) ? 0 : monitor_num,
248                                 monitor);
249
250                 maximum_width = monitor.get_width() * 0.9;
251         }
252
253         GtkRequisition request = hpacker.size_request();
254
255         if (request.width > maximum_width) {
256                 for (vector<ControlUI*>::const_iterator cuip = input_controls.begin();
257                                                         cuip != input_controls.end();
258                                                         ++cuip) {
259                         if (!(*cuip)->short_autostate)
260                                 set_short_autostate(*cuip, true);
261                 }
262                 request = hpacker.size_request();
263         }
264
265         a->width = min(request.width, maximum_width);
266 }
267
268 // Some functions for calculating the 'similarity' of two plugin
269 // control labels.
270
271 static int get_number(string label) {
272 static const char *digits = "0123456789";
273 int value = -1;
274
275         std::size_t first_digit_pos = label.find_first_of(digits);
276         if (first_digit_pos != string::npos) {
277                 // found some digits: there's a number in there somewhere
278                 stringstream s;
279                 s << label.substr(first_digit_pos);
280                 s >> value;
281         }
282         return value;
283 }
284
285 static int match_or_digit(char c1, char c2) {
286         return c1 == c2 || (isdigit(c1) && isdigit(c2));
287 }
288
289 static std::size_t matching_chars_at_head(const string s1, const string s2) {
290 std::size_t length, n = 0;
291
292         length = min(s1.length(), s2.length());
293         while (n < length) {
294                 if (!match_or_digit(s1[n], s2[n]))
295                         break;
296                 n++;
297         }
298         return n;
299 }
300
301 static std::size_t matching_chars_at_tail(const string s1, const string s2) {
302 std::size_t s1pos, s2pos, n = 0;
303
304         s1pos = s1.length();
305         s2pos = s2.length();
306         while (s1pos-- > 0 && s2pos-- > 0) {
307                 if (!match_or_digit(s1[s1pos], s2[s2pos])       )
308                         break;
309                 n++;
310         }
311         return n;
312 }
313
314 static const guint32 min_controls_per_column = 17, max_controls_per_column = 24;
315 static const float default_similarity_threshold = 0.3;
316
317 void
318 GenericPluginUI::build ()
319 {
320         std::vector<ControlUI *> control_uis;
321         bool grid = plugin->parameter_count() > 0;
322
323         // Build a ControlUI for each control port
324         for (size_t i = 0; i < plugin->parameter_count(); ++i) {
325
326                 if (plugin->parameter_is_control (i)) {
327
328                         /* Don't show latency control ports */
329
330                         const Evoral::Parameter param(PluginAutomation, 0, i);
331                         if (plugin->describe_parameter (param) == X_("latency")) {
332                                 continue;
333                         }
334
335                         if (plugin->describe_parameter (param) == X_("hidden")) {
336                                 continue;
337                         }
338
339                         const float value = plugin->get_parameter(i);
340
341                         ControlUI* cui;
342                         Plugin::UILayoutHint hint;
343
344                         if (!plugin->get_layout(i, hint)) {
345                                 grid = false;
346                         }
347
348                         boost::shared_ptr<ARDOUR::AutomationControl> c
349                                 = boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(
350                                         insert->control(param));
351
352                         ParameterDescriptor desc;
353                         plugin->get_parameter_descriptor(i, desc);
354                         if ((cui = build_control_ui (param, desc, c, value, plugin->parameter_is_input(i), hint.knob)) == 0) {
355                                 error << string_compose(_("Plugin Editor: could not build control element for port %1"), i) << endmsg;
356                                 continue;
357                         }
358
359                         if (grid) {
360                                 cui->x0 = hint.x0;
361                                 cui->x1 = hint.x1;
362                                 cui->y0 = hint.y0;
363                                 cui->y1 = hint.y1;
364                         }
365
366                         const std::string param_docs = plugin->get_parameter_docs(i);
367                         if (!param_docs.empty()) {
368                                 set_tooltip(cui, param_docs.c_str());
369                         }
370
371                         control_uis.push_back(cui);
372                 }
373         }
374
375         // Build a ControlUI for each property
376         const Plugin::PropertyDescriptors& descs = plugin->get_supported_properties();
377         for (Plugin::PropertyDescriptors::const_iterator d = descs.begin(); d != descs.end(); ++d) {
378                 const ParameterDescriptor& desc = d->second;
379                 const Evoral::Parameter    param(PluginPropertyAutomation, 0, desc.key);
380
381                 boost::shared_ptr<ARDOUR::AutomationControl> c
382                         = boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(
383                                 insert->control(param));
384
385                 if (!c) {
386                         error << string_compose(_("Plugin Editor: no control for property %1"), desc.key) << endmsg;
387                         continue;
388                 }
389
390                 ControlUI* cui = build_control_ui(param, desc, c, c->get_value(), true);
391                 if (!cui) {
392                         error << string_compose(_("Plugin Editor: could not build control element for property %1"),
393                                                 desc.key) << endmsg;
394                         continue;
395                 }
396
397                 control_uis.push_back(cui);
398         }
399         if (!descs.empty()) {
400                 plugin->announce_property_values();
401         }
402
403         if (grid) {
404                 custom_layout (control_uis);
405         } else {
406                 automatic_layout (control_uis);
407         }
408
409         output_update ();
410
411         automation_manual_all_button.signal_clicked.connect(sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::set_all_automation), ARDOUR::Off));
412         automation_play_all_button.signal_clicked.connect(sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::set_all_automation), ARDOUR::Play));
413         automation_write_all_button.signal_clicked.connect(sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::set_all_automation), ARDOUR::Write));
414         automation_touch_all_button.signal_clicked.connect(sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::set_all_automation), ARDOUR::Touch));
415
416         /* XXX This is a workaround for AutomationControl not knowing about preset loads */
417         plugin->PresetLoaded.connect (*this, invalidator (*this), boost::bind (&GenericPluginUI::update_input_displays, this), gui_context ());
418 }
419
420
421 void
422 GenericPluginUI::automatic_layout (const std::vector<ControlUI*>& control_uis)
423 {
424         guint32 x = 0;
425
426         static const int32_t initial_button_rows = 12;
427         static const int32_t initial_button_cols = 1;
428         static const int32_t initial_output_rows = 1;
429         static const int32_t initial_output_cols = 4;
430
431         Gtk::Table* button_table = manage (new Gtk::Table (initial_button_rows, initial_button_cols));
432         Gtk::Table* output_table = manage (new Gtk::Table (initial_output_rows, initial_output_cols));
433
434         Frame* frame;
435         Frame* bt_frame;
436         VBox* box;
437         int output_row, output_col;
438         int button_row, button_col;
439         int output_rows, output_cols;
440         int button_rows, button_cols;
441
442         hpacker.set_spacing (10);
443         hpacker.set_border_width (10);
444
445         output_rows = initial_output_rows;
446         output_cols = initial_output_cols;
447         button_rows = initial_button_rows;
448         button_cols = initial_button_cols;
449         output_row = 0;
450         button_row = 0;
451         output_col = 0;
452         button_col = 0;
453
454         button_table->set_homogeneous (false);
455         button_table->set_row_spacings (2);
456         button_table->set_col_spacings (2);
457         button_table->set_border_width (5);
458
459         output_table->set_homogeneous (true);
460         output_table->set_row_spacings (2);
461         output_table->set_col_spacings (2);
462         output_table->set_border_width (5);
463
464
465         bt_frame = manage (new Frame);
466         bt_frame->set_name ("BaseFrame");
467         bt_frame->set_label (_("Switches"));
468         bt_frame->add (*button_table);
469         hpacker.pack_start(*bt_frame, true, true);
470
471         box = manage (new VBox);
472         box->set_border_width (5);
473         box->set_spacing (1);
474
475         frame = manage (new Frame);
476         frame->set_name ("BaseFrame");
477         frame->set_label (_("Controls"));
478         frame->add (*box);
479         hpacker.pack_start(*frame, true, true);
480
481         // Add special controls to UI, and build list of normal controls to be layed out later
482         std::vector<ControlUI *> cui_controls_list;
483         for (size_t i = 0; i < control_uis.size(); ++i) {
484                 ControlUI* cui = control_uis[i];
485
486                 if (cui->button || cui->file_button) {
487
488                         if (!is_scrollable && button_row == button_rows) {
489                                 button_row = 0;
490                                 if (++button_col == button_cols) {
491                                         button_cols += 2;
492                                         button_table->resize (button_rows, button_cols);
493                                 }
494                         }
495
496                         button_table->attach (*cui, button_col, button_col + 1, button_row, button_row+1,
497                                              FILL|EXPAND, FILL);
498                         button_row++;
499
500                 } else if (cui->controller || cui->clickbox || cui->combo) {
501                         // Get all of the controls into a list, so that
502                         // we can lay them out a bit more nicely later.
503                         cui_controls_list.push_back(cui);
504
505                 } else if (cui->display) {
506
507                         output_table->attach (*cui, output_col, output_col + 1, output_row, output_row+1,
508                                              FILL|EXPAND, FILL);
509
510                         // TODO: The meters should be divided into multiple rows
511
512                         if (++output_col == output_cols) {
513                                 output_cols ++;
514                                 output_table->resize (output_rows, output_cols);
515                         }
516                 }
517         }
518
519         // Iterate over the list of controls to find which adjacent controls
520         // are similar enough to be grouped together.
521
522         string label, previous_label = "";
523         std::vector<int> numbers_in_labels(cui_controls_list.size());
524
525         std::vector<float> similarity_scores(cui_controls_list.size());
526         float most_similar = 0.0, least_similar = 1.0;
527
528         size_t i = 0;
529         for (vector<ControlUI*>::iterator cuip = cui_controls_list.begin(); cuip != cui_controls_list.end(); ++cuip, ++i) {
530                 label = (*cuip)->label.get_text();
531                 numbers_in_labels[i] = get_number(label);
532
533                 if (i > 0) {
534                         // A hand-wavy calculation of how similar this control's
535                         // label is to the previous.
536                         similarity_scores[i] =
537                                 (float) (
538                                         ( matching_chars_at_head(label, previous_label) +
539                                           matching_chars_at_tail(label, previous_label) +
540                                           1
541                                         )
542                                 ) / (label.length() + previous_label.length());
543                         if (numbers_in_labels[i] >= 0) {
544                                 similarity_scores[i] += (numbers_in_labels[i] == numbers_in_labels[i-1]);
545                         }
546                         least_similar = min(least_similar, similarity_scores[i]);
547                         most_similar  = max(most_similar, similarity_scores[i]);
548                 } else {
549                         similarity_scores[0] = 1.0;
550                 }
551
552                 // cerr << "label: " << label << " sim: " << fixed << setprecision(3) << similarity_scores[i] << " num: " << numbers_in_labels[i] << endl;
553                 previous_label = label;
554         }
555
556
557         // cerr << "most similar: " << most_similar << ", least similar: " << least_similar << endl;
558         float similarity_threshold;
559
560         if (most_similar > 1.0) {
561                 similarity_threshold = default_similarity_threshold;
562         } else {
563                 similarity_threshold = most_similar - (1 - default_similarity_threshold);
564         }
565
566         // Now iterate over the list of controls to display them, placing an
567         // HSeparator between controls of less than a certain similarity, and
568         // starting a new column when necessary.
569
570         i = 0;
571         for (vector<ControlUI*>::iterator cuip = cui_controls_list.begin(); cuip != cui_controls_list.end(); ++cuip, ++i) {
572
573                 ControlUI* cui = *cuip;
574
575                 if (!is_scrollable) {
576                         x++;
577                 }
578
579                 if (x > max_controls_per_column || similarity_scores[i] <= similarity_threshold) {
580                         if (x > min_controls_per_column) {
581                                 frame = manage (new Frame);
582                                 frame->set_name ("BaseFrame");
583                                 frame->set_label (_("Controls"));
584                                 box = manage (new VBox);
585                                 box->set_border_width (5);
586                                 box->set_spacing (1);
587                                 frame->add (*box);
588                                 hpacker.pack_start(*frame, true, true);
589                                 x = 0;
590                         } else {
591                                 HSeparator *split = new HSeparator();
592                                 split->set_size_request(-1, 5);
593                                 box->pack_start(*split, false, false, 0);
594                         }
595
596                 }
597                 box->pack_start (*cui, false, false);
598         }
599
600         if (is_scrollable) {
601                 prefheight = 30 * i;
602         }
603
604         if (box->children().empty()) {
605                 hpacker.remove (*frame);
606         }
607
608         if (button_table->children().empty()) {
609                 hpacker.remove (*bt_frame);
610                 delete button_table;
611         } else {
612                 button_table->show_all ();
613         }
614
615         if (!output_table->children().empty()) {
616                 frame = manage (new Frame);
617                 frame->set_name ("BaseFrame");
618                 frame->set_label(_("Meters"));
619                 frame->add (*output_table);
620                 hpacker.pack_end (*frame, true, true);
621                 output_table->show_all ();
622         } else {
623                 delete output_table;
624         }
625
626         if (plugin->has_inline_display () && plugin->inline_display_in_gui ()) {
627                 PluginDisplay* pd = manage (new PluginDisplay (plugin, 300));
628                 hpacker.pack_end (*pd, true, true);
629         }
630         show_all();
631
632 }
633
634 void
635 GenericPluginUI::custom_layout (const std::vector<ControlUI*>& control_uis)
636 {
637         Gtk::Table* layout = manage (new Gtk::Table ());
638
639         for (vector<ControlUI*>::const_iterator i = control_uis.begin(); i != control_uis.end(); ++i) {
640                 ControlUI* cui = *i;
641                 if (cui->x0 < 0 || cui->y0 < 0) {
642                         continue;
643                 }
644                 layout->attach (*cui, cui->x0, cui->x1, cui->y0, cui->y1, FILL, SHRINK, 2, 2);
645         }
646         hpacker.pack_start (*layout, true, true);
647
648         if (plugin->has_inline_display () && plugin->inline_display_in_gui ()) {
649                 PluginDisplay* pd = manage (new PluginDisplay (plugin, 300));
650                 hpacker.pack_end (*pd, true, true);
651         }
652 }
653
654 void
655 GenericPluginUI::build_midi_table ()
656 {
657         Gtk::Table* pgm_table = manage (new Gtk::Table (8, 2));
658
659         pgm_table->set_homogeneous (true);
660         pgm_table->set_row_spacings (2);
661         pgm_table->set_col_spacings (2);
662         pgm_table->set_border_width (5);
663
664         Frame* frame = manage (new Frame);
665         frame->set_name ("BaseFrame");
666         frame->set_label (_("MIDI Progams (sent to track)"));
667         //frame->set_label (_("MIDI Progams (volatile)"));
668         frame->add (*pgm_table);
669         hpacker.pack_start (*frame, true, true);
670
671         for (uint8_t chn = 0; chn < 16; ++chn) {
672                 int col = chn / 8;
673                 int row = chn % 8;
674                 ArdourDropdown* cui = manage (new ArdourWidgets::ArdourDropdown ());
675                 // TODO set size_request
676                 cui->set_text_ellipsize (Pango::ELLIPSIZE_END);
677                 cui->set_layout_ellipsize_width (PANGO_SCALE * 112 * UIConfiguration::instance ().get_ui_scale ());
678                 midi_pgmsel.push_back (cui);
679                 pgm_table->attach (*cui, col, col + 1, row, row+1, FILL|EXPAND, FILL);
680         }
681
682         midi_refill_patches ();
683
684         insert->plugin()->BankPatchChange.connect (
685                         midi_connections, invalidator (*this),
686                         boost::bind (&GenericPluginUI::midi_bank_patch_change, this, _1),
687                         gui_context());
688
689         /* Note: possible race with MidiTimeAxisView::update_patch_selector()
690          * which uses this signal to update/re-register the midnam (also in gui context).
691          * MTAV does register before us, so the midnam should already be updated when
692          * we're notified.
693          */
694         insert->plugin()->UpdateMidnam.connect (
695                         midi_connections, invalidator (*this),
696                         boost::bind (&GenericPluginUI::midi_refill_patches, this),
697                         gui_context());
698 }
699
700 void
701 GenericPluginUI::midi_refill_patches ()
702 {
703         assert (midi_pgmsel.size() == 16);
704
705         pgm_names.clear ();
706
707         const std::string model = insert->plugin ()->midnam_model ();
708         std::string mode;
709         const std::list<std::string> device_modes = MIDI::Name::MidiPatchManager::instance().custom_device_mode_names_by_model (model);
710         if (device_modes.size() > 0) {
711                 mode = device_modes.front();
712         }
713
714         for (uint8_t chn = 0; chn < 16; ++chn) {
715                 midi_pgmsel[chn]->clear_items ();
716                 boost::shared_ptr<MIDI::Name::ChannelNameSet> cns =
717                         MIDI::Name::MidiPatchManager::instance().find_channel_name_set (model, mode, chn);
718
719                 if (cns) {
720                         using namespace Menu_Helpers;
721                         using namespace Gtkmm2ext;
722
723                         for (MIDI::Name::ChannelNameSet::PatchBanks::const_iterator i = cns->patch_banks().begin(); i != cns->patch_banks().end(); ++i) {
724                                 const MIDI::Name::PatchNameList& patches = (*i)->patch_name_list ();
725                                 for (MIDI::Name::PatchNameList::const_iterator j = patches.begin(); j != patches.end(); ++j) {
726                                         const std::string pgm = (*j)->name ();
727                                         MIDI::Name::PatchPrimaryKey const& key = (*j)->patch_primary_key ();
728                                         assert ((*i)->number () == key.bank());
729                                         const uint32_t bp = (key.bank() << 7) | key.program();
730                                         midi_pgmsel[chn]->AddMenuElem (MenuElemNoMnemonic (pgm, sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::midi_bank_patch_select), chn, bp)));
731                                         pgm_names[bp] = pgm;
732                                 }
733                         }
734                 }
735
736                 midi_bank_patch_change (chn);
737         }
738 }
739
740 void
741 GenericPluginUI::midi_bank_patch_change (uint8_t chn)
742 {
743         assert (chn < 16 && midi_pgmsel.size() == 16);
744         uint32_t bankpgm = insert->plugin()->bank_patch (chn);
745         if (bankpgm == UINT32_MAX) {
746                 midi_pgmsel[chn]->set_text (_("--Unset--"));
747         } else {
748                 int bank = bankpgm >> 7;
749                 int pgm = bankpgm & 127;
750                 if (pgm_names.find (bankpgm) != pgm_names.end ()) {
751                         midi_pgmsel[chn]->set_text (pgm_names[bankpgm]);
752                 } else {
753                         midi_pgmsel[chn]->set_text (string_compose ("Bank %1,%2 Pgm %3",
754                                                 (bank >> 7) + 1, (bank & 127) + 1, pgm +1));
755                 }
756         }
757 }
758
759 void
760 GenericPluginUI::midi_bank_patch_select (uint8_t chn, uint32_t bankpgm)
761 {
762         int bank = bankpgm >> 7;
763         int pgm = bankpgm & 127;
764         if (1) {
765                 /* send to track */
766                 MidiTrack* mt = dynamic_cast<MidiTrack*> (insert->owner());
767                 if (!mt) {
768                         return;
769                 }
770
771                 boost::shared_ptr<AutomationControl> bank_msb = mt->automation_control(Evoral::Parameter (MidiCCAutomation, chn, MIDI_CTL_MSB_BANK), true);
772                 boost::shared_ptr<AutomationControl> bank_lsb = mt->automation_control(Evoral::Parameter (MidiCCAutomation, chn, MIDI_CTL_LSB_BANK), true);
773                 boost::shared_ptr<AutomationControl> program = mt->automation_control(Evoral::Parameter (MidiPgmChangeAutomation, chn), true);
774
775                 bank_msb->set_value (bank >> 7, PBD::Controllable::NoGroup);
776                 bank_lsb->set_value (bank & 127, PBD::Controllable::NoGroup);
777                 program->set_value (pgm, PBD::Controllable::NoGroup);
778
779         } else {
780 #if 0 // TODO inject directly to plugin..
781                 const int cnt = insert->get_count();
782                 for (int i=0; i < cnt; i++ ) {
783                         boost::shared_ptr<LV2Plugin> lv2i = boost::dynamic_pointer_cast<LV2Plugin> (insert->plugin(i));
784                         //lv2i->write_from_ui(port_index, format, buffer_size, (const uint8_t*)buffer);
785
786                 }
787 #endif
788         }
789 }
790
791 GenericPluginUI::ControlUI::ControlUI (const Evoral::Parameter& p)
792         : param(p)
793         , automate_button (X_("")) // force creation of a label
794         , combo (0)
795         , clickbox (0)
796         , file_button (0)
797         , spin_box (0)
798         , display (0)
799         , hbox (0)
800         , vbox (0)
801         , meterinfo (0)
802         , knobtable (0)
803 {
804         automate_button.set_name ("plugin automation state button");
805         set_tooltip (automate_button, _("Automation control"));
806
807         ignore_change = false;
808         update_pending = false;
809         button = false;
810
811         x0 = x1 = y0 = y1 = -1;
812 }
813
814 GenericPluginUI::ControlUI::~ControlUI()
815 {
816         if (meterinfo) {
817                 delete meterinfo->meter;
818                 delete meterinfo;
819         }
820 }
821
822 void
823 GenericPluginUI::set_short_autostate (ControlUI* cui, bool value)
824 {
825         cui->short_autostate = value;
826         if (value) {
827                 cui->automate_button.set_sizing_text("M");
828         } else {
829                 /* XXX translators: use a string here that will be at least as long
830                    as the longest automation label (see ::automation_state_changed()
831                    below). be sure to include a descender. */
832                 cui->automate_button.set_sizing_text(_("Mgnual"));
833         }
834         automation_state_changed(cui);
835 }
836
837 void
838 GenericPluginUI::automation_state_changed (ControlUI* cui)
839 {
840         /* update button label */
841
842         // don't lock to avoid deadlock because we're triggered by
843         // AutomationControl::Changed() while the automation lock is taken
844
845         AutoState state = insert->get_parameter_automation_state (cui->parameter());
846
847         cui->automate_button.set_active((state != ARDOUR::Off));
848
849         if (cui->short_autostate) {
850                 cui->automate_button.set_text (
851                                 GainMeterBase::astate_string (state));
852                 return;
853         }
854
855         switch (state & (ARDOUR::Off|Play|Touch|Write)) {
856         case ARDOUR::Off:
857                 cui->automate_button.set_text (S_("Automation|Manual"));
858                 break;
859         case Play:
860                 cui->automate_button.set_text (_("Play"));
861                 break;
862         case Write:
863                 cui->automate_button.set_text (_("Write"));
864                 break;
865         case Touch:
866                 cui->automate_button.set_text (_("Touch"));
867                 break;
868         default:
869                 cui->automate_button.set_text (_("???"));
870                 break;
871         }
872 }
873
874 bool
875 GenericPluginUI::integer_printer (char buf[32], Adjustment &adj, ControlUI* cui)
876 {
877         float const        v   = cui->control->interface_to_internal(adj.get_value ());
878         const std::string& str = ARDOUR::value_as_string(cui->control->desc(), Variant(v));
879         const size_t       len = str.copy(buf, 31);
880         buf[len] = '\0';
881         return true;
882 }
883
884 bool
885 GenericPluginUI::midinote_printer (char buf[32], Adjustment &adj, ControlUI* cui)
886 {
887         float const        v   = cui->control->interface_to_internal(adj.get_value ());
888         const std::string& str = ARDOUR::value_as_string(cui->control->desc(), Variant(v));
889         const size_t       len = str.copy(buf, 31);
890         buf[len] = '\0';
891         return true;
892 }
893
894 void
895 GenericPluginUI::print_parameter (char *buf, uint32_t len, uint32_t param)
896 {
897         plugin->print_parameter (param, buf, len);
898 }
899
900 /** Build a ControlUI for a parameter/property.
901  * Note that mcontrol may be NULL for outputs.
902  */
903 GenericPluginUI::ControlUI*
904 GenericPluginUI::build_control_ui (const Evoral::Parameter&             param,
905                                    const ParameterDescriptor&           desc,
906                                    boost::shared_ptr<AutomationControl> mcontrol,
907                                    float                                value,
908                                    bool                                 is_input,
909                                    bool                                 use_knob)
910 {
911         ControlUI* control_ui = 0;
912
913         control_ui = manage (new ControlUI (param));
914         control_ui->combo = 0;
915         control_ui->control = mcontrol;
916         control_ui->label.set_text (desc.label);
917         control_ui->label.set_alignment (0.0, 0.5);
918         control_ui->label.set_name ("PluginParameterLabel");
919         control_ui->set_spacing (5);
920         set_short_autostate(control_ui, false);
921
922         if (is_input) {
923
924                 if (desc.datatype == Variant::PATH) {
925
926                         /* We shouldn't get that type for input ports */
927                         assert(param.type() == PluginPropertyAutomation);
928
929                         /* Build a file selector button */
930
931                         // Create/add controller
932                         control_ui->file_button = manage(new Gtk::FileChooserButton(Gtk::FILE_CHOOSER_ACTION_OPEN));
933                         control_ui->file_button->set_title(desc.label);
934
935                         if (use_knob) {
936                                 control_ui->knobtable = manage (new Table());
937                                 control_ui->pack_start(*control_ui->knobtable, true, false);
938                                 control_ui->knobtable->attach (control_ui->label, 0, 1, 0, 1);
939                                 control_ui->knobtable->attach (*control_ui->file_button, 0, 1, 1, 2);
940                         } else {
941                                 control_ui->pack_start (control_ui->label, false, true);
942                                 control_ui->pack_start (*control_ui->file_button, true, true);
943                         }
944
945                         // Monitor changes from the user.
946                         control_ui->file_button->signal_file_set().connect(
947                                 sigc::bind(sigc::mem_fun(*this, &GenericPluginUI::set_path_property),
948                                            desc, control_ui->file_button));
949
950                         /* Add the filebutton control to a map so that we can update it when
951                          * the corresponding property changes. This doesn't go through the usual
952                          * AutomationControls, because they don't support non-numeric values. */
953                         _filepath_controls.insert(std::make_pair(desc.key, control_ui->file_button));
954
955                         return control_ui;
956                 }
957
958                 assert(mcontrol);
959
960                 /* See if there any named values for our input value */
961                 control_ui->scale_points = desc.scale_points;
962
963                 /* If this parameter is an integer, work out the number of distinct values
964                    it can take on (assuming that lower and upper values are allowed).
965                 */
966                 int const steps = desc.integer_step ? (desc.upper - desc.lower + 1) / desc.step : 0;
967
968                 if (control_ui->scale_points && ((steps && int (control_ui->scale_points->size()) == steps) || desc.enumeration)) {
969
970                         /* Either:
971                          *   a) There is a label for each possible value of this input, or
972                          *   b) This port is marked as being an enumeration.
973                          */
974
975                         control_ui->combo = new ArdourDropdown();
976                         for (ARDOUR::ScalePoints::const_iterator i = control_ui->scale_points->begin();
977                              i != control_ui->scale_points->end();
978                              ++i) {
979                                 control_ui->combo->AddMenuElem(Menu_Helpers::MenuElem(
980                                                 i->first,
981                                                 sigc::bind(sigc::mem_fun(*this, &GenericPluginUI::control_combo_changed),
982                                                            control_ui,
983                                                            i->second)));
984                         }
985
986                         control_ui->combo->set_controllable (mcontrol);
987
988                         update_control_display(control_ui);
989
990                 } else {
991
992                         /* create the controller */
993
994                         /* XXX memory leak: SliderController not destroyed by ControlUI
995                          * destructor, and manage() reports object hierarchy
996                          * ambiguity.
997                          */
998                         control_ui->controller = AutomationController::create(mcontrol->parameter(), desc, mcontrol, use_knob);
999
1000                         /* Control UI's don't need the rapid timer workaround */
1001                         control_ui->controller->stop_updating ();
1002
1003                         /* XXX this code is not right yet, because it doesn't handle
1004                            the absence of bounds in any sensible fashion.
1005                         */
1006
1007                         Adjustment* adj = control_ui->controller->adjustment();
1008
1009                         if (desc.integer_step && !desc.toggled) {
1010                                 control_ui->clickbox = new ArdourWidgets::ClickBox (adj, "PluginUIClickBox", true);
1011                                 Gtkmm2ext::set_size_request_to_display_given_text (*control_ui->clickbox, "g9999999", 2, 2);
1012                                 if (desc.unit == ParameterDescriptor::MIDI_NOTE) {
1013                                         control_ui->clickbox->set_printer (sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::midinote_printer), control_ui));
1014                                 } else {
1015                                         control_ui->clickbox->set_printer (sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::integer_printer), control_ui));
1016                                 }
1017                                 control_ui->clickbox->set_controllable (mcontrol);
1018                         } else if (desc.toggled) {
1019                                 ArdourButton* but = dynamic_cast<ArdourButton*> (control_ui->controller->widget());
1020                                 assert(but);
1021                                 but->set_tweaks(ArdourButton::Square);
1022                         } else if (use_knob) {
1023                                 /* Delay size request so that styles are gotten right */
1024                                 control_ui->controller->widget()->signal_size_request().connect(
1025                                                 sigc::bind (sigc::mem_fun (*this, &GenericPluginUI::knob_size_request), control_ui));
1026                         } else {
1027                                 control_ui->controller->set_size_request (200, -1);
1028                                 control_ui->controller->set_name (X_("ProcessorControlSlider"));
1029                         }
1030
1031                         if (!desc.integer_step && !desc.toggled && use_knob) {
1032                                 control_ui->spin_box = manage (new ArdourSpinner (mcontrol, adj));
1033                         }
1034
1035                         adj->set_value (mcontrol->internal_to_interface(value));
1036
1037                 }
1038
1039                 if (use_knob) {
1040                         set_short_autostate(control_ui, true);
1041
1042                         control_ui->label.set_alignment (0.5, 0.5);
1043                         control_ui->knobtable = manage (new Table());
1044                         control_ui->pack_start(*control_ui->knobtable, true, true);
1045
1046                         if (control_ui->combo) {
1047                                 control_ui->knobtable->attach (control_ui->label, 0, 1, 0, 1);
1048                                 control_ui->knobtable->attach (*control_ui->combo, 0, 1, 1, 2);
1049                         } else if (control_ui->clickbox) {
1050                                 control_ui->knobtable->attach (*control_ui->clickbox, 0, 2, 0, 1);
1051                                 control_ui->knobtable->attach (control_ui->label, 0, 1, 1, 2, FILL, SHRINK);
1052                                 control_ui->knobtable->attach (control_ui->automate_button, 1, 2, 1, 2, SHRINK, SHRINK, 2, 0);
1053                         } else if (control_ui->spin_box) {
1054                                 ArdourKnob* knob = dynamic_cast<ArdourKnob*>(control_ui->controller->widget ());
1055                                 knob->set_tooltip_prefix (desc.label + ": ");
1056                                 Alignment *align = manage (new Alignment (.5, .5, 0, 0));
1057                                 align->add (*control_ui->controller);
1058                                 control_ui->knobtable->attach (*align, 0, 1, 0, 1, EXPAND, SHRINK, 1, 2);
1059                                 control_ui->knobtable->attach (*control_ui->spin_box, 0, 2, 1, 2);
1060                                 control_ui->knobtable->attach (control_ui->automate_button, 1, 2, 0, 1, SHRINK, SHRINK, 2, 0);
1061                         } else if (desc.toggled) {
1062                                 Alignment *align = manage (new Alignment (.5, .5, 0, 0));
1063                                 align->add (*control_ui->controller);
1064                                 control_ui->knobtable->attach (*align, 0, 2, 0, 1, EXPAND, SHRINK, 2, 2);
1065                                 control_ui->knobtable->attach (control_ui->label, 0, 1, 1, 2, FILL, SHRINK);
1066                                 control_ui->knobtable->attach (control_ui->automate_button, 1, 2, 1, 2, SHRINK, SHRINK, 2, 0);
1067                         } else {
1068                                 control_ui->knobtable->attach (*control_ui->controller, 0, 2, 0, 1);
1069                                 control_ui->knobtable->attach (control_ui->label, 0, 1, 1, 2, FILL, SHRINK);
1070                                 control_ui->knobtable->attach (control_ui->automate_button, 1, 2, 1, 2, SHRINK, SHRINK, 2, 0);
1071                         }
1072
1073                 } else {
1074
1075                         control_ui->pack_start (control_ui->label, true, true);
1076                         if (control_ui->combo) {
1077                                 control_ui->pack_start(*control_ui->combo, false, true);
1078                         } else if (control_ui->clickbox) {
1079                                 control_ui->pack_start (*control_ui->clickbox, false, false);
1080                         } else if (control_ui->spin_box) {
1081                                 control_ui->pack_start (*control_ui->spin_box, false, false);
1082                                 control_ui->pack_start (*control_ui->controller, false, false);
1083                         } else {
1084                                 control_ui->pack_start (*control_ui->controller, false, false);
1085                         }
1086                         control_ui->pack_start (control_ui->automate_button, false, false);
1087                 }
1088
1089
1090                 if (mcontrol->flags () & Controllable::NotAutomatable) {
1091                         control_ui->automate_button.set_sensitive (false);
1092                         set_tooltip(control_ui->automate_button, _("This control cannot be automated"));
1093                 } else {
1094                         control_ui->automate_button.signal_button_press_event().connect (
1095                                         sigc::bind (sigc::mem_fun(*this, &GenericPluginUI::astate_button_event),
1096                                                     control_ui),
1097                                         false);
1098                         mcontrol->alist()->automation_state_changed.connect (
1099                                         control_connections,
1100                                         invalidator (*this),
1101                                         boost::bind (&GenericPluginUI::automation_state_changed, this, control_ui),
1102                                         gui_context());
1103                         input_controls_with_automation.push_back (control_ui);
1104                 }
1105
1106                 if (desc.toggled && !control_ui->combo) {
1107                         control_ui->button = true;
1108                         ArdourButton* but = dynamic_cast<ArdourButton*>(control_ui->controller->widget ());
1109                         assert (but);
1110                         but->set_name ("pluginui toggle");
1111                         update_control_display(control_ui);
1112                 }
1113
1114                 automation_state_changed (control_ui);
1115
1116                 /* Add to the list of CUIs that need manual update to workaround
1117                  * AutomationControl not knowing about preset loads */
1118                 input_controls.push_back (control_ui);
1119
1120         } else {
1121
1122                 control_ui->display = manage (new EventBox);
1123                 control_ui->display->set_name ("ParameterValueDisplay");
1124
1125                 control_ui->display_label = manage (new Label);
1126
1127                 control_ui->display_label->set_name ("ParameterValueDisplay");
1128
1129                 control_ui->display->add (*control_ui->display_label);
1130                 Gtkmm2ext::set_size_request_to_display_given_text (*control_ui->display, "-888.8g", 2, 6);
1131
1132                 control_ui->display->show_all ();
1133
1134                 control_ui->vbox = manage (new VBox);
1135                 control_ui->vbox->set_spacing(3);
1136
1137                 if (desc.unit == ParameterDescriptor::MIDI_NOTE) {
1138                         control_ui->vbox->pack_end (*control_ui->display, false, false);
1139                         control_ui->vbox->pack_end (control_ui->label, false, false);
1140                 } else if (desc.integer_step || desc.enumeration) {
1141                         control_ui->vbox->pack_end (*control_ui->display, false, false);
1142                         control_ui->vbox->pack_end (control_ui->label, false, false);
1143                 } else {
1144                         /* set up a meter for float ports */
1145
1146                         MeterInfo * info = new MeterInfo();
1147                         control_ui->meterinfo = info;
1148
1149                         info->meter = new FastMeter (
1150                                         5, 5, FastMeter::Vertical, 0,
1151                                         0x0000aaff,
1152                                         0x008800ff, 0x008800ff,
1153                                         0x00ff00ff, 0x00ff00ff,
1154                                         0xcccc00ff, 0xcccc00ff,
1155                                         0xffaa00ff, 0xffaa00ff,
1156                                         0xff0000ff,
1157                                         UIConfiguration::instance().color ("meter background bottom"),
1158                                         UIConfiguration::instance().color ("meter background top")
1159                                         );
1160
1161                         control_ui->label.set_angle(90);
1162
1163                         HBox* center =  manage (new HBox);
1164                         center->set_spacing(1);
1165                         center->pack_start (control_ui->label, false, false);
1166                         center->pack_start (*info->meter, false, false);
1167
1168                         control_ui->hbox = manage (new HBox);
1169                         control_ui->hbox->pack_start (*center, true, false);
1170
1171                         // horizontally center this hbox in the vbox
1172                         control_ui->vbox->pack_start (*control_ui->hbox, false, false);
1173
1174                         control_ui->meterinfo->meter->show_all();
1175                         control_ui->meterinfo->packed = true;
1176                         control_ui->vbox->pack_start (*control_ui->display, false, false);
1177                 }
1178
1179                 control_ui->pack_start (*control_ui->vbox);
1180
1181                 output_controls.push_back (control_ui);
1182         }
1183
1184         if (mcontrol) {
1185                 mcontrol->Changed.connect(control_connections, invalidator(*this),
1186                                           boost::bind(&GenericPluginUI::ui_parameter_changed,
1187                                                       this, control_ui),
1188                                           gui_context());
1189         }
1190
1191         return control_ui;
1192 }
1193
1194 void
1195 GenericPluginUI::knob_size_request(Gtk::Requisition* req, ControlUI* cui) {
1196         Gtk::Requisition astate_req (cui->automate_button.size_request());
1197         const int size = (int) (astate_req.height * 1.5);
1198         req->width = max(req->width, size);
1199         req->height = max(req->height, size);
1200 }
1201
1202
1203 bool
1204 GenericPluginUI::astate_button_event (GdkEventButton* ev, ControlUI* cui)
1205 {
1206         if (ev->button != 1) {
1207                 return true;
1208         }
1209
1210         using namespace Menu_Helpers;
1211
1212         if (automation_menu == 0) {
1213                 automation_menu = manage (new Menu);
1214                 automation_menu->set_name ("ArdourContextMenu");
1215                 automation_menu->set_reserve_toggle_size(false);
1216         }
1217
1218         MenuList& items (automation_menu->items());
1219
1220         items.clear ();
1221         items.push_back (MenuElem (S_("Automation|Manual"),
1222                                    sigc::bind (sigc::mem_fun(*this, &GenericPluginUI::set_automation_state), (AutoState) ARDOUR::Off, cui)));
1223         items.push_back (MenuElem (_("Play"),
1224                                    sigc::bind (sigc::mem_fun(*this, &GenericPluginUI::set_automation_state), (AutoState) Play, cui)));
1225         items.push_back (MenuElem (_("Write"),
1226                                    sigc::bind (sigc::mem_fun(*this, &GenericPluginUI::set_automation_state), (AutoState) Write, cui)));
1227         items.push_back (MenuElem (_("Touch"),
1228                                    sigc::bind (sigc::mem_fun(*this, &GenericPluginUI::set_automation_state), (AutoState) Touch, cui)));
1229
1230         anchored_menu_popup(automation_menu, &cui->automate_button, cui->automate_button.get_text(),
1231                             1, ev->time);
1232
1233         return true;
1234 }
1235
1236 void
1237 GenericPluginUI::set_all_automation (AutoState as)
1238 {
1239         for (vector<ControlUI*>::iterator i = input_controls_with_automation.begin(); i != input_controls_with_automation.end(); ++i) {
1240                 set_automation_state (as, (*i));
1241         }
1242 }
1243
1244 void
1245 GenericPluginUI::set_automation_state (AutoState state, ControlUI* cui)
1246 {
1247         insert->set_parameter_automation_state (cui->parameter(), state);
1248 }
1249
1250 void
1251 GenericPluginUI::ui_parameter_changed (ControlUI* cui)
1252 {
1253         if (!cui->update_pending) {
1254                 cui->update_pending = true;
1255                 Gtkmm2ext::UI::instance()->call_slot (MISSING_INVALIDATOR, boost::bind (&GenericPluginUI::update_control_display, this, cui));
1256         }
1257 }
1258
1259 void
1260 GenericPluginUI::update_control_display (ControlUI* cui)
1261 {
1262         /* XXX how do we handle logarithmic stuff here ? */
1263
1264         cui->update_pending = false;
1265
1266         float val = cui->control->get_value();
1267
1268         PBD::Unwinder<bool> (cui->ignore_change, true);
1269
1270         if (cui->combo && cui->scale_points) {
1271                 for (ARDOUR::ScalePoints::iterator it = cui->scale_points->begin(); it != cui->scale_points->end(); ++it) {
1272                         if (it->second == val) {
1273                                 cui->combo->set_text(it->first);
1274                                 break;
1275                         }
1276                 }
1277         } else if (cui->button) {
1278                 // AutomationController handles this
1279         }
1280
1281         if( cui->controller ) {
1282             cui->controller->display_effective_value();
1283         }
1284
1285
1286         /*} else {
1287                 if (cui->logarithmic) {
1288                         val = log(val);
1289                 }
1290                 if (val != cui->adjustment->get_value()) {
1291                         cui->adjustment->set_value (val);
1292                 }
1293         }*/
1294 }
1295
1296 void
1297 GenericPluginUI::update_input_displays ()
1298 {
1299         /* XXX This is a workaround for AutomationControl not knowing about preset loads */
1300         for (vector<ControlUI*>::iterator i = input_controls.begin();
1301              i != input_controls.end();
1302              ++i) {
1303                 update_control_display(*i);
1304         }
1305         return;
1306 }
1307
1308 void
1309 GenericPluginUI::control_combo_changed (ControlUI* cui, float value)
1310 {
1311         if (!cui->ignore_change) {
1312                 insert->automation_control (cui->parameter())->set_value (value, Controllable::NoGroup);
1313         }
1314 }
1315
1316 bool
1317 GenericPluginUI::start_updating (GdkEventAny*)
1318 {
1319         if (output_controls.size() > 0 ) {
1320                 screen_update_connection.disconnect();
1321                 screen_update_connection = Timers::super_rapid_connect (sigc::mem_fun(*this, &GenericPluginUI::output_update));
1322         }
1323         return false;
1324 }
1325
1326 bool
1327 GenericPluginUI::stop_updating (GdkEventAny*)
1328 {
1329         if (output_controls.size() > 0 ) {
1330                 screen_update_connection.disconnect();
1331         }
1332         return false;
1333 }
1334
1335 void
1336 GenericPluginUI::output_update ()
1337 {
1338         for (vector<ControlUI*>::iterator i = output_controls.begin(); i != output_controls.end(); ++i) {
1339                 float val = plugin->get_parameter ((*i)->parameter().id());
1340                 char buf[32];
1341                 boost::shared_ptr<ReadOnlyControl> c = insert->control_output ((*i)->parameter().id());
1342                 const std::string& str = ARDOUR::value_as_string(c->desc(), Variant(val));
1343                 size_t len = str.copy(buf, 31);
1344                 buf[len] = '\0';
1345                 (*i)->display_label->set_text (buf);
1346
1347                 if ((*i)->meterinfo && (*i)->meterinfo->packed) {
1348                         (*i)->meterinfo->meter->set (c->desc().to_interface (val));
1349                 }
1350         }
1351 }
1352
1353 void
1354 GenericPluginUI::set_path_property (const ParameterDescriptor& desc,
1355                                     Gtk::FileChooserButton*    widget)
1356 {
1357         plugin->set_property(desc.key, Variant(Variant::PATH, widget->get_filename()));
1358 }
1359
1360 void
1361 GenericPluginUI::path_property_changed (uint32_t key, const Variant& value)
1362 {
1363         FilePathControls::iterator c = _filepath_controls.find(key);
1364         if (c != _filepath_controls.end()) {
1365                 c->second->set_filename(value.get_path());
1366         } else {
1367                 std::cerr << "warning: property change for property with no control" << std::endl;
1368         }
1369 }
1370
1371 void
1372 GenericPluginUI::toggle_pianokeyboard ()
1373 {
1374         if (_plugin_pianokeyboard_expander.get_expanded()) {
1375                 _plugin_pianokeyboard_expander.add (_pianobox);
1376                 _pianobox.show_all ();
1377         } else {
1378                 const int child_height = _plugin_pianokeyboard_expander.get_child ()->get_height ();
1379                 _plugin_pianokeyboard_expander.get_child ()->hide ();
1380                 _plugin_pianokeyboard_expander.remove ();
1381
1382                 Gtk::Window *toplevel = (Gtk::Window*) _plugin_pianokeyboard_expander.get_ancestor (GTK_TYPE_WINDOW);
1383                 if (toplevel) {
1384                         Gtk::Requisition wr;
1385                         toplevel->get_size (wr.width, wr.height);
1386                         wr.height -= child_height;
1387                         toplevel->resize (wr.width, wr.height);
1388                 }
1389         }
1390 }
1391
1392 void
1393 GenericPluginUI::_note_on_event_handler(GtkWidget*, int note, gpointer arg)
1394 {
1395         ((GenericPluginUI*)arg)->note_on_event_handler(note);
1396 }
1397
1398 void
1399 GenericPluginUI::_note_off_event_handler(GtkWidget*, int note, gpointer arg)
1400 {
1401         ((GenericPluginUI*)arg)->note_off_event_handler(note);
1402 }
1403
1404 void
1405 GenericPluginUI::note_on_event_handler (int note)
1406 {
1407         // TODO add option to send to synth directly (bypass track)
1408         MidiTrack* mt = dynamic_cast<MidiTrack*> (insert->owner());
1409         if (!mt) { return; }
1410         _pianomm->grab_focus ();
1411         uint8_t channel = _piano_channel.get_value_as_int () - 1;
1412         uint8_t event[3];
1413         event[0] = (MIDI_CMD_NOTE_ON | channel);
1414         event[1] = note;
1415         event[2] = _piano_velocity.get_value_as_int ();
1416         mt->write_immediate_event (3, event);
1417 }
1418
1419 void
1420 GenericPluginUI::note_off_event_handler (int note)
1421 {
1422         MidiTrack* mt = dynamic_cast<MidiTrack*> (insert->owner());
1423         if (!mt) { return; }
1424         uint8_t channel = _piano_channel.get_value_as_int () - 1;
1425         uint8_t event[3];
1426         event[0] = (MIDI_CMD_NOTE_OFF | channel);
1427         event[1] = note;
1428         event[2] = 0;
1429         mt->write_immediate_event (3, event);
1430 }