small is beautiful
[ardour.git] / gtk2_ardour / processor_box.cc
1 /*
2     Copyright (C) 2000-2004 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 <cmath>
25 #include <iostream>
26 #include <set>
27
28 #include <sigc++/bind.h>
29
30 #include "pbd/convert.h"
31 #include "canvas/utils.h"
32
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
35
36 #include <gtkmm/messagedialog.h>
37
38 #include <gtkmm2ext/gtk_ui.h>
39 #include <gtkmm2ext/utils.h>
40 #include <gtkmm2ext/choice.h>
41 #include <gtkmm2ext/utils.h>
42 #include <gtkmm2ext/doi.h>
43 #include <gtkmm2ext/rgb_macros.h>
44
45 #include "ardour/amp.h"
46 #include "ardour/audio_track.h"
47 #include "ardour/audioengine.h"
48 #include "ardour/internal_return.h"
49 #include "ardour/internal_send.h"
50 #include "ardour/luaproc.h"
51 #include "ardour/luascripting.h"
52 #include "ardour/meter.h"
53 #include "ardour/panner_shell.h"
54 #include "ardour/plugin_insert.h"
55 #include "ardour/pannable.h"
56 #include "ardour/port_insert.h"
57 #include "ardour/profile.h"
58 #include "ardour/return.h"
59 #include "ardour/route.h"
60 #include "ardour/send.h"
61 #include "ardour/session.h"
62 #include "ardour/types.h"
63
64 #include "LuaBridge/LuaBridge.h"
65
66 #include "actions.h"
67 #include "ardour_dialog.h"
68 #include "ardour_ui.h"
69 #include "gui_thread.h"
70 #include "io_selector.h"
71 #include "keyboard.h"
72 #include "luainstance.h"
73 #include "mixer_ui.h"
74 #include "mixer_strip.h"
75 #include "plugin_pin_dialog.h"
76 #include "plugin_selector.h"
77 #include "plugin_ui.h"
78 #include "port_insert_ui.h"
79 #include "processor_box.h"
80 #include "public_editor.h"
81 #include "return_ui.h"
82 #include "route_processor_selection.h"
83 #include "script_selector.h"
84 #include "send_ui.h"
85 #include "timers.h"
86 #include "tooltips.h"
87 #include "new_plugin_preset_dialog.h"
88
89 #include "i18n.h"
90
91 #ifdef AUDIOUNIT_SUPPORT
92 class AUPluginUI;
93 #endif
94
95 #ifndef NDEBUG
96 bool ProcessorBox::show_all_processors = false;
97 #endif
98
99 using namespace std;
100 using namespace ARDOUR;
101 using namespace PBD;
102 using namespace Gtk;
103 using namespace Glib;
104 using namespace Gtkmm2ext;
105
106 ProcessorBox*  ProcessorBox::_current_processor_box = 0;
107 RefPtr<Action> ProcessorBox::paste_action;
108 RefPtr<Action> ProcessorBox::cut_action;
109 RefPtr<Action> ProcessorBox::copy_action;
110 RefPtr<Action> ProcessorBox::rename_action;
111 RefPtr<Action> ProcessorBox::delete_action;
112 RefPtr<Action> ProcessorBox::manage_pins_action;
113 RefPtr<Action> ProcessorBox::edit_action;
114 RefPtr<Action> ProcessorBox::edit_generic_action;
115 RefPtr<ActionGroup> ProcessorBox::processor_box_actions;
116 Gtkmm2ext::ActionMap ProcessorBox::myactions (X_("processor box"));
117 Gtkmm2ext::Bindings* ProcessorBox::bindings = 0;
118
119
120 // TODO consolidate with PluginPinDialog::set_color
121 static void set_routing_color (cairo_t* cr, bool midi)
122 {
123         static const uint32_t audio_port_color = 0x4A8A0EFF; // Green
124         static const uint32_t midi_port_color = 0x960909FF; //Red
125
126         if (midi) {
127                 cairo_set_source_rgb (cr,
128                                 UINT_RGBA_R_FLT(midi_port_color),
129                                 UINT_RGBA_G_FLT(midi_port_color),
130                                 UINT_RGBA_B_FLT(midi_port_color));
131         } else {
132                 cairo_set_source_rgb (cr,
133                                 UINT_RGBA_R_FLT(audio_port_color),
134                                 UINT_RGBA_G_FLT(audio_port_color),
135                                 UINT_RGBA_B_FLT(audio_port_color));
136         }
137 }
138
139 ProcessorEntry::ProcessorEntry (ProcessorBox* parent, boost::shared_ptr<Processor> p, Width w)
140         : _button (ArdourButton::led_default_elements)
141         , _position (PreFader)
142         , _position_num(0)
143         , _parent (parent)
144         , _selectable(true)
145         , _unknown_processor(false)
146         , _processor (p)
147         , _width (w)
148         , input_icon(true)
149         , output_icon(false)
150         , routing_icon(true)
151         , output_routing_icon(false)
152         , _plugin_display(0)
153 {
154         _vbox.show ();
155
156         _button.set_distinct_led_click (true);
157         _button.set_fallthrough_to_parent(true);
158         _button.set_led_left (true);
159         _button.signal_led_clicked.connect (sigc::mem_fun (*this, &ProcessorEntry::led_clicked));
160         _button.set_text (name (_width));
161
162         if (boost::dynamic_pointer_cast<PeakMeter> (_processor)) {
163                 _button.set_elements(ArdourButton::Element(_button.elements() & ~ArdourButton::Indicator));
164         }
165         if (boost::dynamic_pointer_cast<UnknownProcessor> (_processor)) {
166                 _button.set_elements(ArdourButton::Element(_button.elements() & ~ArdourButton::Indicator));
167                 _unknown_processor = true;
168         }
169         {
170                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
171                 if (pi && pi->plugin() && pi->plugin()->get_info()->type != ARDOUR::Lua) {
172                         _plugin_preset_pointer = PluginPresetPtr (new PluginPreset (pi->plugin()->get_info()));
173                 }
174         }
175         if (_processor) {
176
177                 _vbox.pack_start (routing_icon);
178                 _vbox.pack_start (input_icon);
179                 _vbox.pack_start (_button, true, true);
180
181                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
182                 if (pi && pi->plugin() && pi->plugin()->has_inline_display()) {
183                         if (pi->plugin()->get_info()->type != ARDOUR::Lua) {
184                                 _plugin_display = new PluginDisplay (pi->plugin(),
185                                                 std::max (60.f, rintf(112.f * UIConfiguration::instance().get_ui_scale())));
186                         } else {
187                                 assert (boost::dynamic_pointer_cast<LuaProc>(pi->plugin()));
188                                 _plugin_display = new LuaPluginDisplay (boost::dynamic_pointer_cast<LuaProc>(pi->plugin()),
189                                                 std::max (60.f, rintf(112.f * UIConfiguration::instance().get_ui_scale())));
190                         }
191                         _vbox.pack_start (*_plugin_display);
192                         _plugin_display->set_no_show_all (true);
193                         if (UIConfiguration::instance().get_show_inline_display_by_default ()) {
194                                 _plugin_display->show ();
195                         }
196                 }
197                 _vbox.pack_end (output_routing_icon);
198                 _vbox.pack_end (output_icon);
199
200                 _button.set_active (_processor->active());
201
202                 input_icon.set_no_show_all(true);
203                 routing_icon.set_no_show_all(true);
204                 output_icon.set_no_show_all(true);
205                 output_routing_icon.set_no_show_all(true);
206
207                 _button.show ();
208                 input_icon.hide();
209                 output_icon.show();
210                 routing_icon.hide();
211                 output_routing_icon.hide();
212
213                 _processor->ActiveChanged.connect (active_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_active_changed, this), gui_context());
214                 _processor->PropertyChanged.connect (name_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_property_changed, this, _1), gui_context());
215                 _processor->ConfigurationChanged.connect (config_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_configuration_changed, this, _1, _2), gui_context());
216
217                 set<Evoral::Parameter> p = _processor->what_can_be_automated ();
218                 for (set<Evoral::Parameter>::iterator i = p.begin(); i != p.end(); ++i) {
219
220                         std::string label = _processor->describe_parameter (*i);
221
222                         if (boost::dynamic_pointer_cast<Send> (_processor)) {
223                                 label = _("Send");
224                         } else if (boost::dynamic_pointer_cast<Return> (_processor)) {
225                                 label = _("Return");
226                         }
227
228                         Control* c = new Control (_processor->automation_control (*i), label);
229
230                         _controls.push_back (c);
231
232                         if (boost::dynamic_pointer_cast<Amp> (_processor) == 0) {
233                                 /* Add non-Amp (Fader & Trim) controls to the processor box */
234                                 _vbox.pack_start (c->box);
235                         }
236                 }
237
238                 setup_tooltip ();
239                 setup_visuals ();
240         } else {
241                 _vbox.set_size_request (-1, _button.size_request().height);
242         }
243 }
244
245 ProcessorEntry::~ProcessorEntry ()
246 {
247         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
248                 delete *i;
249         }
250         delete _plugin_display;
251 }
252
253 EventBox&
254 ProcessorEntry::action_widget ()
255 {
256         return _button;
257 }
258
259 Gtk::Widget&
260 ProcessorEntry::widget ()
261 {
262         return _vbox;
263 }
264
265 string
266 ProcessorEntry::drag_text () const
267 {
268         return name (Wide);
269 }
270
271 bool
272 ProcessorEntry::can_copy_state (Gtkmm2ext::DnDVBoxChild* o) const
273 {
274         ProcessorEntry *other = dynamic_cast<ProcessorEntry*> (o);
275         if (!other) {
276                 return false;
277         }
278         boost::shared_ptr<ARDOUR::Processor> otherproc = other->processor();
279         boost::shared_ptr<PluginInsert> my_pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
280         boost::shared_ptr<PluginInsert> ot_pi = boost::dynamic_pointer_cast<PluginInsert> (otherproc);
281         if (boost::dynamic_pointer_cast<UnknownProcessor> (_processor)) {
282                 return false;
283         }
284         if (boost::dynamic_pointer_cast<UnknownProcessor> (otherproc)) {
285                 return false;
286         }
287         if (!my_pi || !ot_pi) {
288                 return false;
289         }
290         if (my_pi->type() != ot_pi->type()) {
291                 return false;
292         }
293         boost::shared_ptr<Plugin> my_p = my_pi->plugin();
294         boost::shared_ptr<Plugin> ot_p = ot_pi->plugin();
295         if (!my_p || !ot_p) {
296                 return false;
297         }
298         if (my_p->unique_id() != ot_p->unique_id()) {
299                 return false;
300         }
301         return true;
302 }
303
304 bool
305 ProcessorEntry::drag_data_get (Glib::RefPtr<Gdk::DragContext> const, Gtk::SelectionData &data)
306 {
307         if (data.get_target() == "PluginPresetPtr") {
308                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
309
310                 if (!_plugin_preset_pointer || !pi) {
311                         data.set (data.get_target(), 8, NULL, 0);
312                         return true;
313                 }
314
315                 boost::shared_ptr<ARDOUR::Plugin> plugin = pi->plugin();
316                 assert (plugin);
317
318                 PluginManager& manager (PluginManager::instance());
319                 bool fav = manager.get_status (_plugin_preset_pointer->_pip) == PluginManager::Favorite;
320
321                 NewPluginPresetDialog d (plugin,
322                                 string_compose(_("New Favorite Preset for \"%1\""),_plugin_preset_pointer->_pip->name), !fav);
323
324                 _plugin_preset_pointer->_preset.valid = false;
325
326                 switch (d.run ()) {
327                         case Gtk::RESPONSE_CANCEL:
328                                 data.set (data.get_target(), 8, NULL, 0);
329                                 return true;
330                                 break;
331
332                         case Gtk::RESPONSE_NO:
333                                 break;
334
335                         case Gtk::RESPONSE_ACCEPT:
336                                 if (d.name().empty()) {
337                                         break;
338                                 }
339
340                                 if (d.replace ()) {
341                                         plugin->remove_preset (d.name ());
342                                 }
343
344                                 Plugin::PresetRecord const r = plugin->save_preset (d.name());
345
346                                 if (!r.uri.empty ()) {
347                                         _plugin_preset_pointer->_preset.uri   = r.uri;
348                                         _plugin_preset_pointer->_preset.label = r.label;
349                                         _plugin_preset_pointer->_preset.user  = r.user;
350                                         _plugin_preset_pointer->_preset.valid = r.valid;
351                                 }
352                 }
353                 data.set (data.get_target(), 8, (const guchar *) &_plugin_preset_pointer, sizeof (PluginPresetPtr));
354                 return true;
355         }
356         return false;
357 }
358
359 void
360 ProcessorEntry::set_position (Position p, uint32_t num)
361 {
362         _position = p;
363         _position_num = num;
364         setup_visuals ();
365 }
366
367 void
368 ProcessorEntry::set_visual_state (Gtkmm2ext::VisualState s, bool yn)
369 {
370         if (yn) {
371                 _button.set_visual_state (Gtkmm2ext::VisualState (_button.visual_state() | s));
372         } else {
373                 _button.set_visual_state (Gtkmm2ext::VisualState (_button.visual_state() & ~s));
374         }
375 }
376
377 void
378 ProcessorEntry::setup_visuals ()
379 {
380         if (_unknown_processor) {
381                 _button.set_name ("processor stub");
382                 return;
383         }
384         boost::shared_ptr<Send> send;
385         if ((send = boost::dynamic_pointer_cast<Send> (_processor))) {
386                 if (send->remove_on_disconnect ()) {
387                         _button.set_name ("processor sidechain");
388                         return;
389                 }
390         }
391
392         switch (_position) {
393         case PreFader:
394                 if (_plugin_display) { _plugin_display->set_name ("processor prefader"); }
395                 _button.set_name ("processor prefader");
396                 break;
397
398         case Fader:
399                 _button.set_name ("processor fader");
400                 break;
401
402         case PostFader:
403                 if (_plugin_display) { _plugin_display->set_name ("processor postfader"); }
404                 _button.set_name ("processor postfader");
405                 break;
406         }
407 }
408
409
410 boost::shared_ptr<Processor>
411 ProcessorEntry::processor () const
412 {
413         if (!_processor) {
414                 return boost::shared_ptr<Processor>();
415         }
416         return _processor;
417 }
418
419 void
420 ProcessorEntry::set_enum_width (Width w)
421 {
422         _width = w;
423         _button.set_text (name (_width));
424 }
425
426 void
427 ProcessorEntry::led_clicked(GdkEventButton *ev)
428 {
429         bool ctrl_shift_pressed = false;
430         Keyboard::ModifierMask ctrl_shift_mask = Keyboard::ModifierMask (Keyboard::PrimaryModifier|Keyboard::TertiaryModifier);
431
432         if (Keyboard::modifier_state_equals (ev->state, ctrl_shift_mask)) {
433                 ctrl_shift_pressed = true;
434         }
435
436         if (_processor) {
437                 if (_button.get_active ()) {
438                         if (ctrl_shift_pressed) {
439                                 _parent->all_visible_processors_active(false);
440
441                                 if (_position == Fader) {
442                                         _processor->deactivate ();
443                                 }
444                         }
445                         else {
446                                 _processor->deactivate ();
447                         }
448
449                 } else {
450                         if (ctrl_shift_pressed) {
451                                 _parent->all_visible_processors_active(true);
452
453                                 if (_position == Fader) {
454                                         _processor->activate ();
455                                 }
456                         }
457                         else {
458                                 _processor->activate ();
459                         }
460                 }
461         }
462 }
463
464 void
465 ProcessorEntry::processor_active_changed ()
466 {
467         if (_processor) {
468                 _button.set_active (_processor->active());
469         }
470 }
471
472 void
473 ProcessorEntry::processor_property_changed (const PropertyChange& what_changed)
474 {
475         if (what_changed.contains (ARDOUR::Properties::name)) {
476                 _button.set_text (name (_width));
477                 setup_tooltip ();
478         }
479 }
480
481 void
482 ProcessorEntry::processor_configuration_changed (const ChanCount in, const ChanCount out)
483 {
484         _parent->setup_routing_feeds ();
485         input_icon.queue_draw();
486         output_icon.queue_draw();
487         routing_icon.queue_draw();
488         output_routing_icon.queue_draw();
489 }
490
491 void
492 ProcessorEntry::setup_tooltip ()
493 {
494         if (_processor) {
495                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
496                 if (pi) {
497                         std::string postfix = "";
498                         uint32_t replicated;
499                         if ((replicated = pi->get_count()) > 1) {
500                                 postfix = string_compose(_("\nThis mono plugin has been replicated %1 times."), replicated);
501                         }
502                         if (pi->plugin()->has_editor()) {
503                                 ARDOUR_UI_UTILS::set_tooltip (_button,
504                                                 string_compose (_("<b>%1</b>\nDouble-click to show GUI.\n%2+double-click to show generic GUI.%3"), name (Wide), Keyboard::primary_modifier_name (), postfix));
505                         } else {
506                                 ARDOUR_UI_UTILS::set_tooltip (_button,
507                                                 string_compose (_("<b>%1</b>\nDouble-click to show generic GUI.%2"), name (Wide), postfix));
508                         }
509                         return;
510                 }
511                 if(boost::dynamic_pointer_cast<UnknownProcessor> (_processor)) {
512                         ARDOUR_UI::instance()->set_tip (_button,
513                                         string_compose (_("<b>%1</b>\nThe Plugin is not available on this system\nand has been replaced by a stub."), name (Wide)));
514                         return;
515                 }
516                 boost::shared_ptr<Send> send;
517                 if ((send = boost::dynamic_pointer_cast<Send> (_processor)) != 0 &&
518                                 !boost::dynamic_pointer_cast<InternalSend>(_processor)) {
519                         if (send->remove_on_disconnect ()) {
520                                 ARDOUR_UI_UTILS::set_tooltip (_button, string_compose ("<b>&gt; %1</b>\nThis (sidechain) send will be removed when disconnected.", _processor->name()));
521                         } else {
522                                 ARDOUR_UI_UTILS::set_tooltip (_button, string_compose ("<b>&gt; %1</b>", _processor->name()));
523                         }
524                         return;
525                 }
526         }
527         ARDOUR_UI_UTILS::set_tooltip (_button, string_compose ("<b>%1</b>", name (Wide)));
528 }
529
530 string
531 ProcessorEntry::name (Width w) const
532 {
533         boost::shared_ptr<Send> send;
534         string name_display;
535
536         if (!_processor) {
537                 return string();
538         }
539
540         if ((send = boost::dynamic_pointer_cast<Send> (_processor)) != 0 &&
541             !boost::dynamic_pointer_cast<InternalSend>(_processor)) {
542
543                 name_display += '>';
544                 std::string send_name;
545                 bool pretty_ok = true;
546
547                 if (send->remove_on_disconnect ()) {
548                         // assume it's a sidechain, find pretty name of connected port(s)
549                         PortSet& ps (send->output ()->ports ());
550                         for (PortSet::iterator i = ps.begin (); i != ps.end () && pretty_ok; ++i) {
551                                 vector<string> connections;
552                                 if (i->get_connections (connections)) {
553                                         vector<string>::const_iterator ci;
554                                         for (ci = connections.begin(); ci != connections.end(); ++ci) {
555                                                 std::string pn = AudioEngine::instance()->get_pretty_name_by_name (*ci);
556                                                 if (pn.empty ()) {
557                                                         continue;
558                                                 }
559                                                 if (send_name.empty ()) {
560                                                         send_name = pn;
561                                                 } else if (send_name != pn) {
562                                                         // pretty names don't match
563                                                         pretty_ok = false;
564                                                         break;
565                                                 }
566                                         }
567                                 }
568                         }
569                 }
570
571                 if (!pretty_ok) {
572                         send_name = "";
573                 }
574
575                 /* grab the send name out of its overall name */
576                 if (send_name.empty()) {
577                         send_name = send->name();
578                         string::size_type lbracket, rbracket;
579                         lbracket = send_name.find ('[');
580                         rbracket = send_name.find (']');
581                         send_name = send_name.substr (lbracket+1, lbracket-rbracket-1);
582                 }
583
584                 switch (w) {
585                 case Wide:
586                         name_display += send_name;
587                         break;
588                 case Narrow:
589                         name_display += PBD::short_version (send_name, 5);
590                         break;
591                 }
592
593         } else {
594                 boost::shared_ptr<ARDOUR::PluginInsert> pi;
595                 uint32_t replicated;
596                 if ((pi = boost::dynamic_pointer_cast<ARDOUR::PluginInsert> (_processor)) != 0
597                                 && (replicated = pi->get_count()) > 1)
598                 {
599                         name_display += string_compose(_("(%1x1) "), replicated);
600                 }
601
602                 switch (w) {
603                 case Wide:
604                         name_display += _processor->display_name();
605                         break;
606                 case Narrow:
607                         name_display += PBD::short_version (_processor->display_name(), 5);
608                         break;
609                 }
610
611         }
612
613         return name_display;
614 }
615
616 void
617 ProcessorEntry::show_all_controls ()
618 {
619         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
620                 (*i)->set_visible (true);
621         }
622
623         _parent->update_gui_object_state (this);
624 }
625
626 void
627 ProcessorEntry::hide_all_controls ()
628 {
629         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
630                 (*i)->set_visible (false);
631         }
632
633         _parent->update_gui_object_state (this);
634 }
635
636 void
637 ProcessorEntry::add_control_state (XMLNode* node) const
638 {
639         for (list<Control*>::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
640                 (*i)->add_state (node);
641         }
642
643         if (_plugin_display) {
644                 XMLNode* c = new XMLNode (X_("Object"));
645                 c->add_property (X_("id"), X_("InlineDisplay"));
646                 c->add_property (X_("visible"), _plugin_display->is_visible ());
647                 node->add_child_nocopy (*c);
648         }
649 }
650
651 void
652 ProcessorEntry::set_control_state (XMLNode const * node)
653 {
654         for (list<Control*>::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
655                 (*i)->set_state (node);
656         }
657
658         if (_plugin_display) {
659                 XMLNode* n = GUIObjectState::get_node (node, X_("InlineDisplay"));
660                 XMLProperty* p = n ? n->property (X_("visible")) : NULL;
661                 if (p) {
662                         if (string_is_affirmative (p->value ())) {
663                                 _plugin_display->show();
664                         } else {
665                                 _plugin_display->hide();
666                         }
667                 }
668         }
669 }
670
671 string
672 ProcessorEntry::state_id () const
673 {
674         return string_compose ("processor %1", _processor->id().to_s());
675 }
676
677 void
678 ProcessorEntry::hide_things ()
679 {
680         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
681                 (*i)->hide_things ();
682         }
683 }
684
685
686 Menu *
687 ProcessorEntry::build_controls_menu ()
688 {
689         using namespace Menu_Helpers;
690         Menu* menu = manage (new Menu);
691         MenuList& items = menu->items ();
692
693         if (_plugin_display) {
694                 items.push_back (CheckMenuElem (_("Inline Display")));
695                 Gtk::CheckMenuItem* c = dynamic_cast<Gtk::CheckMenuItem*> (&items.back ());
696                 c->set_active (_plugin_display->is_visible ());
697                 c->signal_toggled().connect (sigc::mem_fun (*this, &ProcessorEntry::toggle_inline_display_visibility));
698                 items.push_back (SeparatorElem ());
699         }
700
701         items.push_back (
702                 MenuElem (_("Show All Controls"), sigc::mem_fun (*this, &ProcessorEntry::show_all_controls))
703                 );
704
705         items.push_back (
706                 MenuElem (_("Hide All Controls"), sigc::mem_fun (*this, &ProcessorEntry::hide_all_controls))
707                 );
708
709         if (!_controls.empty ()) {
710                 items.push_back (SeparatorElem ());
711         }
712
713         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
714                 items.push_back (CheckMenuElem ((*i)->name ()));
715                 Gtk::CheckMenuItem* c = dynamic_cast<Gtk::CheckMenuItem*> (&items.back ());
716                 c->set_active ((*i)->visible ());
717                 c->signal_toggled().connect (sigc::bind (sigc::mem_fun (*this, &ProcessorEntry::toggle_control_visibility), *i));
718         }
719
720         return menu;
721 }
722
723 void
724 ProcessorEntry::toggle_inline_display_visibility ()
725 {
726         if (_plugin_display->is_visible ()) {
727                 _plugin_display->hide();
728         } else {
729                 _plugin_display->show();
730         }
731         _parent->update_gui_object_state (this);
732 }
733
734 void
735 ProcessorEntry::toggle_control_visibility (Control* c)
736 {
737         c->set_visible (!c->visible ());
738         _parent->update_gui_object_state (this);
739 }
740
741 Menu *
742 ProcessorEntry::build_send_options_menu ()
743 {
744         using namespace Menu_Helpers;
745         Menu* menu = manage (new Menu);
746         MenuList& items = menu->items ();
747
748         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (_processor);
749         if (send) {
750
751                 items.push_back (CheckMenuElem (_("Link panner controls")));
752                 Gtk::CheckMenuItem* c = dynamic_cast<Gtk::CheckMenuItem*> (&items.back ());
753                 c->set_active (send->panner_shell()->is_linked_to_route());
754                 c->signal_toggled().connect (sigc::mem_fun (*this, &ProcessorEntry::toggle_panner_link));
755
756         }
757         return menu;
758 }
759
760 void
761 ProcessorEntry::toggle_panner_link ()
762 {
763         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (_processor);
764         if (send) {
765                 send->panner_shell()->set_linked_to_route(!send->panner_shell()->is_linked_to_route());
766         }
767 }
768
769 ProcessorEntry::Control::Control (boost::shared_ptr<AutomationControl> c, string const & n)
770         : _control (c)
771         , _adjustment (gain_to_slider_position_with_max (1.0, Config->get_max_gain()), 0, 1, 0.01, 0.1)
772         , _slider (&_adjustment, boost::shared_ptr<PBD::Controllable>(), 0, max(13.f, rintf(13.f * UIConfiguration::instance().get_ui_scale())))
773         , _slider_persistant_tooltip (&_slider)
774         , _button (ArdourButton::led_default_elements)
775         , _ignore_ui_adjustment (false)
776         , _visible (false)
777         , _name (n)
778 {
779         _slider.set_controllable (c);
780         box.set_padding(0, 0, 4, 4);
781
782         if (c->toggled()) {
783                 _button.set_text (_name);
784                 _button.set_led_left (true);
785                 _button.set_name ("processor control button");
786                 box.add (_button);
787                 _button.show ();
788
789                 _button.signal_clicked.connect (sigc::mem_fun (*this, &Control::button_clicked));
790                 _button.signal_led_clicked.connect (sigc::mem_fun (*this, &Control::button_clicked_event));
791                 // dup. currently timers are used :(
792                 //c->Changed.connect (_connection, MISSING_INVALIDATOR, boost::bind (&Control::control_changed, this), gui_context ());
793
794         } else {
795
796                 _slider.set_name ("ProcessorControlSlider");
797                 _slider.set_text (_name);
798
799                 box.add (_slider);
800                 _slider.show ();
801
802                 const ARDOUR::ParameterDescriptor& desc = c->desc();
803                 double const lo = c->internal_to_interface(desc.lower);
804                 double const up = c->internal_to_interface(desc.upper);
805                 double const normal = c->internal_to_interface(desc.normal);
806                 double smallstep = desc.smallstep;
807                 double largestep = desc.largestep;
808
809                 if (smallstep == 0.0) {
810                         smallstep = up / 1000.;
811                 } else {
812                         smallstep = c->internal_to_interface(desc.lower + smallstep);
813                 }
814
815                 if (largestep == 0.0) {
816                         largestep = up / 40.;
817                 } else {
818                         largestep = c->internal_to_interface(desc.lower + largestep);
819                 }
820
821                 _adjustment.set_lower (lo);
822                 _adjustment.set_upper (up);
823                 _adjustment.set_step_increment (smallstep);
824                 _adjustment.set_page_increment (largestep);
825                 _slider.set_default_value (normal);
826
827                 _adjustment.signal_value_changed().connect (sigc::mem_fun (*this, &Control::slider_adjusted));
828                 // dup. currently timers are used :(
829                 //c->Changed.connect (_connection, MISSING_INVALIDATOR, boost::bind (&Control::control_changed, this), gui_context ());
830         }
831
832         // yuck, do we really need to do this?
833         // according to c404374 this is only needed for send automation
834         timer_connection = Timers::rapid_connect (sigc::mem_fun (*this, &Control::control_changed));
835
836         control_changed ();
837         set_tooltip ();
838
839         /* We're providing our own PersistentTooltip */
840         set_no_tooltip_whatsoever (_slider);
841 }
842
843 ProcessorEntry::Control::~Control ()
844 {
845         timer_connection.disconnect ();
846 }
847
848 void
849 ProcessorEntry::Control::set_tooltip ()
850 {
851         boost::shared_ptr<AutomationControl> c = _control.lock ();
852
853         if (!c) {
854                 return;
855         }
856         char tmp[256];
857         if (c->toggled ()) {
858                 snprintf (tmp, sizeof(tmp), "%s: %s", _name.c_str(), c->get_value() > 0.5 ? _("on") : _("off"));
859         } else {
860                 snprintf (tmp, sizeof(tmp), "%s: %.2f", _name.c_str(), c->internal_to_user (c->get_value ()));
861         }
862
863         string sm = Gtkmm2ext::markup_escape_text (tmp);
864         _slider_persistant_tooltip.set_tip (sm);
865         ARDOUR_UI_UTILS::set_tooltip (_button, sm);
866 }
867
868 void
869 ProcessorEntry::Control::slider_adjusted ()
870 {
871         if (_ignore_ui_adjustment) {
872                 return;
873         }
874
875         boost::shared_ptr<AutomationControl> c = _control.lock ();
876
877         if (!c) {
878                 return;
879         }
880
881         c->set_value ( c->interface_to_internal(_adjustment.get_value ()) , Controllable::NoGroup);
882         set_tooltip ();
883 }
884
885 void
886 ProcessorEntry::Control::button_clicked ()
887 {
888         boost::shared_ptr<AutomationControl> c = _control.lock ();
889
890         if (!c) {
891                 return;
892         }
893
894         bool const n = _button.get_active ();
895
896         c->set_value (n ? 0 : 1, Controllable::NoGroup);
897         _button.set_active (!n);
898         set_tooltip ();
899 }
900
901 void
902 ProcessorEntry::Control::button_clicked_event (GdkEventButton *ev)
903 {
904         (void) ev;
905
906         button_clicked ();
907 }
908
909 void
910 ProcessorEntry::Control::control_changed ()
911 {
912         boost::shared_ptr<AutomationControl> c = _control.lock ();
913         if (!c) {
914                 return;
915         }
916
917         _ignore_ui_adjustment = true;
918
919         if (c->toggled ()) {
920
921                 _button.set_active (c->get_value() > 0.5);
922
923         } else {
924                 // as long as rapid timers are used, only update the tooltip
925                 // if the value has changed.
926                 const double nval = c->internal_to_interface (c->get_value ());
927                 if (_adjustment.get_value() != nval) {
928                         _adjustment.set_value (nval);
929                         set_tooltip ();
930                 }
931         }
932
933         _ignore_ui_adjustment = false;
934 }
935
936 void
937 ProcessorEntry::Control::add_state (XMLNode* node) const
938 {
939         XMLNode* c = new XMLNode (X_("Object"));
940         c->add_property (X_("id"), state_id ());
941         c->add_property (X_("visible"), _visible);
942         node->add_child_nocopy (*c);
943 }
944
945 void
946 ProcessorEntry::Control::set_state (XMLNode const * node)
947 {
948         XMLNode* n = GUIObjectState::get_node (node, state_id ());
949         if (n) {
950                 XMLProperty* p = n->property (X_("visible"));
951                 set_visible (p && string_is_affirmative (p->value ()));
952         } else {
953                 set_visible (false);
954         }
955 }
956
957 void
958 ProcessorEntry::Control::set_visible (bool v)
959 {
960         if (v) {
961                 box.show ();
962         } else {
963                 box.hide ();
964         }
965
966         _visible = v;
967 }
968
969 /** Called when the Editor might have re-shown things that
970     we want hidden.
971 */
972 void
973 ProcessorEntry::Control::hide_things ()
974 {
975         if (!_visible) {
976                 box.hide ();
977         }
978 }
979
980 string
981 ProcessorEntry::Control::state_id () const
982 {
983         boost::shared_ptr<AutomationControl> c = _control.lock ();
984         assert (c);
985
986         return string_compose (X_("control %1"), c->id().to_s ());
987 }
988
989 PluginInsertProcessorEntry::PluginInsertProcessorEntry (ProcessorBox* b, boost::shared_ptr<ARDOUR::PluginInsert> p, Width w)
990         : ProcessorEntry (b, p, w)
991         , _plugin_insert (p)
992 {
993         p->PluginIoReConfigure.connect (
994                 _iomap_connection, invalidator (*this), boost::bind (&PluginInsertProcessorEntry::iomap_changed, this), gui_context()
995                 );
996         p->PluginMapChanged.connect (
997                 _iomap_connection, invalidator (*this), boost::bind (&PluginInsertProcessorEntry::iomap_changed, this), gui_context()
998                 );
999         p->PluginConfigChanged.connect (
1000                 _iomap_connection, invalidator (*this), boost::bind (&PluginInsertProcessorEntry::iomap_changed, this), gui_context()
1001                 );
1002 }
1003
1004 void
1005 PluginInsertProcessorEntry::iomap_changed ()
1006 {
1007         _parent->setup_routing_feeds ();
1008         routing_icon.queue_draw();
1009         output_routing_icon.queue_draw();
1010 }
1011
1012 void
1013 PluginInsertProcessorEntry::hide_things ()
1014 {
1015         ProcessorEntry::hide_things ();
1016 }
1017
1018 ProcessorEntry::PortIcon::PortIcon(bool input) {
1019         _input = input;
1020         _ports = ARDOUR::ChanCount(ARDOUR::DataType::AUDIO, 1);
1021         set_size_request (-1, std::max (2.f, rintf(2.f * UIConfiguration::instance().get_ui_scale())));
1022 }
1023
1024 bool
1025 ProcessorEntry::PortIcon::on_expose_event (GdkEventExpose* ev)
1026 {
1027         cairo_t* cr = gdk_cairo_create (get_window()->gobj());
1028
1029         cairo_rectangle (cr, ev->area.x, ev->area.y, ev->area.width, ev->area.height);
1030         cairo_clip (cr);
1031
1032         Gtk::Allocation a = get_allocation();
1033         double const width = a.get_width();
1034         double const height = a.get_height();
1035
1036         Gdk::Color const bg = get_style()->get_bg (STATE_NORMAL);
1037         cairo_set_source_rgb (cr, bg.get_red_p (), bg.get_green_p (), bg.get_blue_p ());
1038
1039         cairo_rectangle (cr, 0, 0, width, height);
1040         cairo_fill (cr);
1041
1042         const double dx = rint(max(2., 2. * UIConfiguration::instance().get_ui_scale()));
1043         for (uint32_t i = 0; i < _ports.n_total(); ++i) {
1044                 set_routing_color (cr, i < _ports.n_midi());
1045                 const double x = ProcessorEntry::RoutingIcon::pin_x_pos (i, width, _ports.n_total(), 0 , false);
1046                 cairo_rectangle (cr, x - .5 - dx * .5, 0, 1 + dx, height);
1047                 cairo_fill(cr);
1048         }
1049
1050         cairo_destroy(cr);
1051         return true;
1052 }
1053
1054 ProcessorEntry::RoutingIcon::RoutingIcon (bool input)
1055         : _fed_by (false)
1056         , _input (input)
1057 {
1058         set_terminal (false);
1059 }
1060
1061 void
1062 ProcessorEntry::RoutingIcon::set_terminal (bool b) {
1063         _terminal = b;
1064         int h = std::max (8.f, rintf(8.f * sqrt (UIConfiguration::instance().get_ui_scale())));
1065         if (_terminal) {
1066                 h += std::max (4.f, rintf(4.f * sqrt (UIConfiguration::instance().get_ui_scale())));
1067         }
1068         set_size_request (-1, h);
1069 }
1070
1071 void
1072 ProcessorEntry::RoutingIcon::set (
1073                 const ARDOUR::ChanCount& in,
1074                 const ARDOUR::ChanCount& out,
1075                 const ARDOUR::ChanCount& sinks,
1076                 const ARDOUR::ChanCount& sources,
1077                 const ARDOUR::ChanMapping& in_map,
1078                 const ARDOUR::ChanMapping& out_map,
1079                 const ARDOUR::ChanMapping& thru_map)
1080 {
1081         _in       = in;
1082         _out      = out;
1083         _sources  = sources;
1084         _sinks    = sinks;
1085         _in_map   = in_map;
1086         _out_map  = out_map;
1087         _thru_map = thru_map;
1088 }
1089
1090 bool
1091 ProcessorEntry::RoutingIcon::in_identity () const {
1092         if (_thru_map.n_total () > 0) {
1093                 return false;
1094         }
1095         if (!_in_map.is_monotonic () || !_in_map.is_identity ()) {
1096                 return false;
1097         }
1098         if (_in_map.n_total () != _sinks.n_total () || _in.n_total () != _sinks.n_total ()) {
1099                 return false;
1100         }
1101         return true;
1102 }
1103
1104 bool
1105 ProcessorEntry::RoutingIcon::out_identity () const {
1106         if (_thru_map.n_total () > 0) {
1107                 // TODO skip if trhu is not connected to any of next's inputs
1108                 return false;
1109         }
1110         if (!_out_map.is_monotonic () || !_out_map.is_identity ()) {
1111                 return false;
1112         }
1113         if (_out_map.n_total () != _sources.n_total () || _out.n_total () != _sources.n_total ()) {
1114                 return false;
1115         }
1116         return true;
1117 }
1118
1119 bool
1120 ProcessorEntry::RoutingIcon::can_coalesce () const {
1121         if (_thru_map.n_total () > 0) {
1122                 return false;
1123         }
1124         if (_fed_by && _f_out != _f_sources) {
1125                 return false;
1126         }
1127         if (_input && _sinks == _in && (!_fed_by || _f_out == _in)) {
1128                 return true;
1129         }
1130         return false;
1131 }
1132
1133 void
1134 ProcessorEntry::RoutingIcon::set_fed_by (
1135                                 const ARDOUR::ChanCount& out,
1136                                 const ARDOUR::ChanCount& sources,
1137                                 const ARDOUR::ChanMapping& out_map,
1138                                 const ARDOUR::ChanMapping& thru_map)
1139 {
1140         _f_out      = out;
1141         _f_sources  = sources;
1142         _f_out_map  = out_map;
1143         _f_thru_map = thru_map;
1144         _fed_by     = true;
1145 }
1146
1147 void
1148 ProcessorEntry::RoutingIcon::set_feeding (
1149                                 const ARDOUR::ChanCount& in,
1150                                 const ARDOUR::ChanCount& sinks,
1151                                 const ARDOUR::ChanMapping& in_map,
1152                                 const ARDOUR::ChanMapping& thru_map)
1153 {
1154         _i_in       = in;
1155         _i_sinks    = sinks;
1156         _i_in_map   = in_map;
1157         _i_thru_map = thru_map;
1158         _feeding    = true;
1159 }
1160
1161 double
1162 ProcessorEntry::RoutingIcon::pin_x_pos (uint32_t i, double width, uint32_t n_total, uint32_t n_midi, bool midi)
1163 {
1164         if (!midi) { i += n_midi; }
1165         if (n_total == 1) {
1166                 assert (i == 0);
1167                 return rint (width * .5) +.5;
1168         }
1169         return rint (width * (.15 + .7 * i / (n_total - 1))) + .5;
1170 }
1171
1172 void
1173 ProcessorEntry::RoutingIcon::draw_gnd (cairo_t* cr, double x0, double y0, double height, bool midi)
1174 {
1175         const double dx = 1 + rint (max(2., 2. * UIConfiguration::instance().get_ui_scale()));
1176         const double y1 = rint (height * .66) + .5;
1177
1178         cairo_save (cr);
1179         cairo_translate (cr, x0, y0);
1180         cairo_move_to (cr, 0, height);
1181         cairo_line_to (cr, 0, y1);
1182         cairo_move_to (cr, 0 - dx, y1);
1183         cairo_line_to (cr, 0 + dx, y1);
1184
1185         set_routing_color (cr, midi);
1186         cairo_set_line_width (cr, 1.0);
1187         cairo_stroke (cr);
1188         cairo_restore (cr);
1189 }
1190
1191 void
1192 ProcessorEntry::RoutingIcon::draw_sidechain (cairo_t* cr, double x0, double y0, double height, bool midi)
1193 {
1194         const double dx = 1 + rint (max(2., 2. * UIConfiguration::instance().get_ui_scale()));
1195         const double y1 = rint (height * .5) - .5;
1196
1197         cairo_save (cr);
1198         cairo_translate (cr, x0, y0);
1199         cairo_move_to (cr, 0 - dx, height);
1200         cairo_line_to (cr, 0, y1);
1201         cairo_line_to (cr, 0 + dx, height);
1202         cairo_close_path (cr);
1203
1204         set_routing_color (cr, midi);
1205         cairo_fill (cr);
1206         cairo_restore (cr);
1207 }
1208
1209 void
1210 ProcessorEntry::RoutingIcon::draw_thru_src (cairo_t* cr, double x0, double y0, double height, bool midi)
1211 {
1212         const double rad = 1;
1213         const double y1 = height - rad - 1.5;
1214
1215         cairo_arc (cr, x0, y0 + y1, rad, 0, 2. * M_PI);
1216         cairo_move_to (cr, x0, y0 + height - 1.5);
1217         cairo_line_to (cr, x0, y0 + height);
1218         set_routing_color (cr, midi);
1219         cairo_set_line_width  (cr, 1.0);
1220         cairo_stroke (cr);
1221 }
1222
1223 void
1224 ProcessorEntry::RoutingIcon::draw_thru_sink (cairo_t* cr, double x0, double y0, double height, bool midi)
1225 {
1226         const double rad = 1;
1227         const double y1 = rad + 1;
1228
1229         cairo_arc (cr, x0, y0 + y1, rad, 0, 2. * M_PI);
1230         cairo_move_to (cr, x0, y0);
1231         cairo_line_to (cr, x0, y0 + 1);
1232         set_routing_color (cr, midi);
1233         cairo_set_line_width  (cr, 1.0);
1234         cairo_stroke (cr);
1235 }
1236
1237 void
1238 ProcessorEntry::RoutingIcon::draw_connection (cairo_t* cr, double x0, double x1, double y0, double y1, bool midi, bool dashed)
1239 {
1240         double bz = abs (y1 - y0);
1241
1242         cairo_move_to (cr, x0, y0);
1243         cairo_curve_to (cr, x0, y0 + bz, x1, y1 - bz, x1, y1);
1244         cairo_set_line_width  (cr, 1.0);
1245         cairo_set_line_cap  (cr,  CAIRO_LINE_CAP_ROUND);
1246         cairo_set_source_rgb (cr, 1, 0, 0);
1247         if (dashed) {
1248                 const double dashes[] = { 2, 3 };
1249                 cairo_set_dash (cr, dashes, 2, 0);
1250         }
1251         set_routing_color (cr, midi);
1252         cairo_stroke (cr);
1253         if (dashed) {
1254                 cairo_set_dash (cr, 0, 0, 0);
1255         }
1256 }
1257
1258 bool
1259 ProcessorEntry::RoutingIcon::on_expose_event (GdkEventExpose* ev)
1260 {
1261         cairo_t* cr = gdk_cairo_create (get_window()->gobj());
1262
1263         cairo_rectangle (cr, ev->area.x, ev->area.y, ev->area.width, ev->area.height);
1264         cairo_clip (cr);
1265
1266         cairo_set_line_cap (cr, CAIRO_LINE_CAP_ROUND);
1267
1268         Gtk::Allocation a = get_allocation();
1269         double const width = a.get_width();
1270         double const height = a.get_height();
1271
1272         Gdk::Color const bg = get_style()->get_bg (STATE_NORMAL);
1273         cairo_set_source_rgb (cr, bg.get_red_p (), bg.get_green_p (), bg.get_blue_p ());
1274
1275         cairo_rectangle (cr, 0, 0, width, height);
1276         cairo_fill (cr);
1277
1278         if (_input) {
1279                 if (can_coalesce ()) {
1280                         expose_coalesced_input_map (cr, width, height);
1281                 } else {
1282                         expose_input_map (cr, width, height);
1283                 }
1284         } else {
1285                 expose_output_map (cr, width, height);
1286         }
1287
1288         cairo_destroy(cr);
1289         return true;
1290 }
1291
1292 void
1293 ProcessorEntry::RoutingIcon::expose_coalesced_input_map (cairo_t* cr, const double width, const double height)
1294 {
1295         const uint32_t pc_in = _sinks.n_total();
1296         const uint32_t pc_in_midi = _sinks.n_midi();
1297
1298         for (uint32_t i = 0; i < pc_in; ++i) {
1299                 const bool is_midi = i < pc_in_midi;
1300                 bool valid_in;
1301                 uint32_t pn = is_midi ? i : i - pc_in_midi;
1302                 DataType dt = is_midi ? DataType::MIDI : DataType::AUDIO;
1303                 uint32_t idx = _in_map.get (dt, pn, &valid_in);
1304                 if (!valid_in) {
1305                         double x = pin_x_pos (i, width, pc_in, 0, is_midi);
1306                         draw_gnd (cr, x, 0, height, is_midi);
1307                         continue;
1308                 }
1309                 if (idx >= _in.get (dt)) {
1310                         // side-chain, probably
1311                         double x = pin_x_pos (i, width, pc_in, 0, is_midi);
1312                         draw_sidechain (cr, x, 0, height, is_midi);
1313                         continue;
1314                 }
1315                 double c_x0;
1316                 double c_x1 = pin_x_pos (i, width, pc_in, 0, false);
1317
1318                 if (_fed_by) {
1319                         bool valid_src;
1320                         uint32_t src = _f_out_map.get_src (dt, idx, &valid_src);
1321                         if (!valid_src) {
1322                                 double x = pin_x_pos (i, width, pc_in, 0, false);
1323                                 bool valid_thru;
1324                                 _f_thru_map.get (dt, idx, &valid_thru);
1325                                 if (valid_thru) {
1326                                         draw_thru_src (cr, x, 0, height, is_midi);
1327                                 } else {
1328                                         draw_gnd (cr, x, 0, height, is_midi);
1329                                 }
1330                                 continue;
1331                         }
1332                         c_x0 = pin_x_pos (src, width, _f_sources.n_total(), _f_sources.n_midi(), is_midi);
1333                 } else {
1334                         c_x0 = pin_x_pos (idx, width, _in.n_total(), _in.n_midi(), is_midi);
1335                 }
1336                 draw_connection (cr, c_x0, c_x1, 0, height, is_midi);
1337         }
1338 }
1339
1340 void
1341 ProcessorEntry::RoutingIcon::expose_input_map (cairo_t* cr, const double width, const double height)
1342 {
1343         const uint32_t n_in = _in.n_total();
1344         const uint32_t n_in_midi = _in.n_midi();
1345         const uint32_t pc_in = _sinks.n_total();
1346         const uint32_t pc_in_midi = _sinks.n_midi();
1347
1348         // draw inputs to this
1349         for (uint32_t i = 0; i < pc_in; ++i) {
1350                 const bool is_midi = i < pc_in_midi;
1351                 bool valid_in;
1352                 uint32_t pn = is_midi ? i : i - pc_in_midi;
1353                 DataType dt = is_midi ? DataType::MIDI : DataType::AUDIO;
1354                 uint32_t idx = _in_map.get (dt, pn, &valid_in);
1355                 // check if it's fed
1356                 bool valid_src = true;
1357                 if (valid_in && idx < _in.get (dt) && _fed_by) {
1358                         bool valid_out;
1359                         bool valid_thru;
1360                         _f_out_map.get_src (dt, idx, &valid_out);
1361                         _f_thru_map.get (dt, idx, &valid_thru);
1362                         if (!valid_out && !valid_thru) {
1363                                 valid_src = false;
1364                         }
1365                 }
1366                 if (!valid_in || !valid_src) {
1367                         double x = pin_x_pos (i, width, pc_in, 0, is_midi);
1368                         draw_gnd (cr, x, 0, height, is_midi);
1369                         continue;
1370                 }
1371                 if (idx >= _in.get (dt)) {
1372                         // side-chain, probably
1373                         double x = pin_x_pos (i, width, pc_in, 0, is_midi);
1374                         draw_sidechain (cr, x, 0, height, is_midi);
1375                         continue;
1376                 }
1377                 double c_x1 = pin_x_pos (i, width, pc_in, 0, false);
1378                 double c_x0 = pin_x_pos (idx, width, n_in, n_in_midi, is_midi);
1379                 draw_connection (cr, c_x0, c_x1, 0, height, is_midi);
1380         }
1381
1382         // draw reverse thru
1383         for (uint32_t i = 0; i < n_in; ++i) {
1384                 const bool is_midi = i < n_in_midi;
1385                 bool valid_thru;
1386                 uint32_t pn = is_midi ? i : i - n_in_midi;
1387                 DataType dt = is_midi ? DataType::MIDI : DataType::AUDIO;
1388                 _thru_map.get_src (dt, pn, &valid_thru);
1389                 if (!valid_thru) {
1390                         continue;
1391                 }
1392                 double x = pin_x_pos (i, width, n_in, 0, is_midi);
1393                 draw_thru_sink (cr, x, 0, height, is_midi);
1394         }
1395 }
1396
1397 void
1398 ProcessorEntry::RoutingIcon::expose_output_map (cairo_t* cr, const double width, const double height)
1399 {
1400         int dh = std::max (4.f, rintf(4.f * UIConfiguration::instance().get_ui_scale()));
1401         double ht = _terminal ? height - dh : height;
1402
1403         // draw outputs of this
1404         const uint32_t pc_out = _sources.n_total();
1405         const uint32_t pc_out_midi = _sources.n_midi();
1406         const uint32_t n_out = _out.n_total();
1407         const uint32_t n_out_midi = _out.n_midi();
1408
1409         for (uint32_t i = 0; i < pc_out; ++i) {
1410                 const bool is_midi = i < pc_out_midi;
1411                 bool valid_out;
1412                 uint32_t pn = is_midi ? i : i - pc_out_midi;
1413                 DataType dt = is_midi ? DataType::MIDI : DataType::AUDIO;
1414                 uint32_t idx = _out_map.get (dt, pn, &valid_out);
1415                 if (!valid_out) {
1416                         continue;
1417                 }
1418                 // skip connections that are not used in the next's input
1419                 if (_feeding) {
1420                         bool valid_thru, valid_sink;
1421                         _i_in_map.get_src (dt, idx, &valid_sink);
1422                         _i_thru_map.get_src (dt, idx, &valid_thru);
1423                         if (!valid_thru && !valid_sink) {
1424                                 continue;
1425                         }
1426                 }
1427                 double c_x0 = pin_x_pos (i, width, pc_out, 0, false);
1428                 double c_x1 = pin_x_pos (idx, width, n_out, n_out_midi, is_midi);
1429                 draw_connection (cr, c_x0, c_x1, 0, ht, is_midi);
1430         }
1431
1432         for (uint32_t i = 0; i < n_out; ++i) {
1433                 const bool is_midi = i < n_out_midi;
1434                 uint32_t pn = is_midi ? i : i - n_out_midi;
1435                 DataType dt = is_midi ? DataType::MIDI : DataType::AUDIO;
1436                 double x = pin_x_pos (i, width, n_out, 0, is_midi);
1437
1438                 if (!_terminal) {
1439                         bool valid_thru_f = false;
1440                         // skip connections that are not used in the next's input
1441                         if (_feeding) {
1442                                 bool valid_sink;
1443                                 _i_in_map.get_src (dt, pn, &valid_sink);
1444                                 _i_thru_map.get_src (dt, pn, &valid_thru_f);
1445                                 if (!valid_thru_f && !valid_sink) {
1446                                         continue;
1447                                 }
1448                         }
1449
1450                         bool valid_src;
1451                         _out_map.get_src (dt, pn, &valid_src);
1452                         if (!valid_src) {
1453                                 bool valid_thru;
1454                                 uint32_t idx = _thru_map.get (dt, pn, &valid_thru);
1455                                 if (valid_thru) {
1456                                         if (idx >= _in.get (dt)) {
1457                                                 draw_sidechain (cr, x, 0, height, is_midi);
1458                                         } else {
1459                                                 draw_thru_src (cr, x, 0, height, is_midi);
1460                                         }
1461                                 } else if (valid_thru_f){
1462                                         // gnd is part of input, unless it's a thru input
1463                                         // (also only true if !coalesced into one small display)
1464                                         draw_gnd (cr, x, 0, height, is_midi);
1465                                 }
1466                         }
1467                 } else {
1468                         // terminal node, add arrows
1469                         bool valid_src;
1470                         _out_map.get_src (dt, pn, &valid_src);
1471                         if (!valid_src) {
1472                                 bool valid_thru;
1473                                 uint32_t idx = _thru_map.get (dt, pn, &valid_thru);
1474                                 if (valid_thru) {
1475                                         if (idx >= _in.get (dt)) {
1476                                                 draw_sidechain (cr, x, 0, height - dh, is_midi);
1477                                         } else {
1478                                                 draw_thru_src (cr, x, 0, height - dh, is_midi);
1479                                         }
1480                                 } else {
1481                                         draw_gnd (cr, x, 0, height - dh, is_midi);
1482                                 }
1483                         }
1484
1485                         set_routing_color (cr, is_midi);
1486                         cairo_set_line_width (cr, 1.0);
1487                         cairo_move_to (cr, x, height - dh);
1488                         cairo_line_to (cr, x, height - 2);
1489                         cairo_stroke (cr);
1490
1491                         const double ar = dh - 1;
1492                         cairo_move_to (cr, x - ar, height - ar);
1493                         cairo_line_to (cr, x     , height - .5);
1494                         cairo_line_to (cr, x + ar, height - ar);
1495                         cairo_line_to (cr, x     , height - ar * .5);
1496                         cairo_close_path (cr);
1497                         cairo_fill_preserve (cr);
1498                         cairo_stroke (cr);
1499                 }
1500         }
1501 }
1502
1503 ProcessorEntry::PluginDisplay::PluginDisplay (boost::shared_ptr<ARDOUR::Plugin> p, uint32_t max_height)
1504         : _plug (p)
1505         , _surf (0)
1506         , _max_height (max_height)
1507         , _cur_height (1)
1508         , _scroll (false)
1509 {
1510         set_name ("processor prefader");
1511         _plug->QueueDraw.connect (_qdraw_connection, invalidator (*this),
1512                         boost::bind (&Gtk::Widget::queue_draw, this), gui_context ());
1513 }
1514
1515 ProcessorEntry::PluginDisplay::~PluginDisplay ()
1516 {
1517         if (_surf) {
1518                 cairo_surface_destroy (_surf);
1519         }
1520 }
1521
1522 void
1523 ProcessorEntry::PluginDisplay::on_size_request (Gtk::Requisition* req)
1524 {
1525         req->width = 56;
1526         req->height = _cur_height;
1527 }
1528
1529
1530 void
1531 ProcessorEntry::PluginDisplay::update_height_alloc (uint32_t inline_height)
1532 {
1533         /* work-around scroll-bar + aspect ratio
1534          * show inline-view -> height changes -> scrollbar gets added
1535          * -> width changes -> inline-view, fixed aspect ratio -> height changes
1536          * -> scroll bar is removed [-> width changes ; repeat ]
1537          */
1538         uint32_t shm = std::min (_max_height, inline_height);
1539         bool sc = false;
1540         Gtk::Container* pr = get_parent();
1541         for (uint32_t i = 0; i < 4 && pr; ++i) {
1542                 // VBox, EventBox, ViewPort, ScrolledWindow
1543                 pr = pr->get_parent();
1544         }
1545         Gtk::ScrolledWindow* sw = dynamic_cast<Gtk::ScrolledWindow*> (pr);
1546         if (sw) {
1547                 const Gtk::VScrollbar* vsb = sw->get_vscrollbar();
1548                 sc = vsb && vsb->is_visible();
1549         }
1550
1551         if (shm != _cur_height) {
1552                 if (_scroll == sc || _cur_height < shm) {
1553                         queue_resize ();
1554                 }
1555                 _cur_height = shm;
1556         }
1557         _scroll = sc;
1558 }
1559
1560 uint32_t
1561 ProcessorEntry::PluginDisplay::render_inline (cairo_t* cr, uint32_t width)
1562 {
1563         Plugin::Display_Image_Surface* dis = _plug->render_inline_display (width, _max_height);
1564         if (!dis) {
1565                 return 0;
1566         }
1567
1568         /* allocate a local image-surface,
1569          * We cannot re-use the data via cairo_image_surface_create_for_data(),
1570          * since pixman keeps a reference to it.
1571          * we'd need to hand over the data and ha cairo_surface_destroy to free it.
1572          * it might be possible to work around via cairo_surface_set_user_data().
1573          */
1574         if (!_surf
1575                         || dis->width !=  cairo_image_surface_get_width (_surf)
1576                         || dis->height !=  cairo_image_surface_get_height (_surf)
1577                  ) {
1578                 if (_surf) {
1579                         cairo_surface_destroy (_surf);
1580                 }
1581                 _surf = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, dis->width, dis->height);
1582         }
1583
1584         if (cairo_image_surface_get_stride (_surf) == dis->stride) {
1585                 memcpy (cairo_image_surface_get_data (_surf), dis->data, dis->stride * dis->height);
1586         } else {
1587                 unsigned char *src = dis->data;
1588                 unsigned char *dst = cairo_image_surface_get_data (_surf);
1589                 const int dst_stride =  cairo_image_surface_get_stride (_surf);
1590                 for (int y = 0; y < dis->height; ++y) {
1591                         memcpy (dst, src, dis->width * 4 /*ARGB32*/);
1592                         src += dis->stride;
1593                         dst += dst_stride;
1594                 }
1595         }
1596
1597         cairo_surface_mark_dirty(_surf);
1598         const double xc = floor ((width - dis->width) * .5);
1599         cairo_set_source_surface(cr, _surf, xc, 0);
1600         cairo_paint (cr);
1601
1602         return dis->height;
1603 }
1604
1605 bool
1606 ProcessorEntry::PluginDisplay::on_expose_event (GdkEventExpose* ev)
1607 {
1608         Gtk::Allocation a = get_allocation();
1609         double const width = a.get_width();
1610         double const height = a.get_height();
1611
1612         cairo_t* cr = gdk_cairo_create (get_window()->gobj());
1613         cairo_rectangle (cr, ev->area.x, ev->area.y, ev->area.width, ev->area.height);
1614         cairo_clip (cr);
1615
1616         Gdk::Color const bg = get_style()->get_bg (STATE_NORMAL);
1617         cairo_set_source_rgb (cr, bg.get_red_p (), bg.get_green_p (), bg.get_blue_p ());
1618         cairo_rectangle (cr, 0, 0, width, height);
1619         cairo_fill (cr);
1620
1621         cairo_save (cr);
1622         cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
1623         Gtkmm2ext::rounded_rectangle (cr, .5, -1.5, width - 1, height + 1, 7);
1624         cairo_clip (cr);
1625         cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
1626
1627         uint32_t ht = render_inline (cr, width);
1628         cairo_restore (cr);
1629
1630         if (ht == 0) {
1631                 hide ();
1632                 if (_cur_height != 1) {
1633                         _cur_height = 1;
1634                         queue_resize ();
1635                 }
1636                 cairo_destroy (cr);
1637                 return true;
1638         } else {
1639                 update_height_alloc (ht);
1640         }
1641
1642         bool failed = false;
1643         std::string name = get_name();
1644         ArdourCanvas::Color fill_color = UIConfiguration::instance().color (string_compose ("%1: fill active", name), &failed);
1645
1646         Gtkmm2ext::rounded_rectangle (cr, .5, -1.5, width - 1, height + 1, 7);
1647         cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
1648         cairo_set_line_width(cr, 1.0);
1649         ArdourCanvas::set_source_rgb_a (cr, fill_color, 1.0);
1650         cairo_stroke (cr);
1651
1652         cairo_destroy(cr);
1653         return true;
1654 }
1655
1656 ProcessorEntry::LuaPluginDisplay::LuaPluginDisplay (boost::shared_ptr<ARDOUR::LuaProc> p, uint32_t max_height)
1657         : PluginDisplay (p, max_height)
1658         , _luaproc (p)
1659         , _lua_render_inline (0)
1660 {
1661         p->setup_lua_inline_gui (&lua_gui);
1662
1663         lua_State* LG = lua_gui.getState ();
1664         LuaInstance::bind_cairo (LG);
1665         luabridge::LuaRef lua_render = luabridge::getGlobal (LG, "render_inline");
1666         assert (lua_render.isFunction ());
1667         _lua_render_inline = new luabridge::LuaRef (lua_render);
1668 }
1669
1670 ProcessorEntry::LuaPluginDisplay::~LuaPluginDisplay ()
1671 {
1672         delete (_lua_render_inline);
1673 }
1674
1675 uint32_t
1676 ProcessorEntry::LuaPluginDisplay::render_inline (cairo_t *cr, uint32_t width)
1677 {
1678         Cairo::Context ctx (cr);
1679         try {
1680                 luabridge::LuaRef rv = (*_lua_render_inline)((Cairo::Context *)&ctx, width, _max_height);
1681                 if (rv.isTable ()) {
1682                         uint32_t h = rv[2];
1683                         return h;
1684                 }
1685         } catch (luabridge::LuaException const& e) {
1686                 ;
1687         }
1688         return 0;
1689 }
1690
1691
1692 static std::list<Gtk::TargetEntry> drop_targets()
1693 {
1694         std::list<Gtk::TargetEntry> tmp;
1695         tmp.push_back (Gtk::TargetEntry ("processor")); // from processor-box to processor-box
1696         tmp.push_back (Gtk::TargetEntry ("PluginInfoPtr")); // from plugin-manager
1697         tmp.push_back (Gtk::TargetEntry ("PluginPresetPtr")); // from sidebar
1698         return tmp;
1699 }
1700
1701 static std::list<Gtk::TargetEntry> drag_targets()
1702 {
1703         std::list<Gtk::TargetEntry> tmp;
1704         tmp.push_back (Gtk::TargetEntry ("PluginPresetPtr")); // to sidebar (optional preset)
1705         tmp.push_back (Gtk::TargetEntry ("processor")); // to processor-box (copy)
1706         return tmp;
1707 }
1708
1709 static std::list<Gtk::TargetEntry> drag_targets_noplugin()
1710 {
1711         std::list<Gtk::TargetEntry> tmp;
1712         tmp.push_back (Gtk::TargetEntry ("processor")); // to processor box (sends, faders re-order)
1713         return tmp;
1714 }
1715
1716 ProcessorBox::ProcessorBox (ARDOUR::Session* sess, boost::function<PluginSelector*()> get_plugin_selector,
1717                             RouteProcessorSelection& rsel, MixerStrip* parent, bool owner_is_mixer)
1718         : _parent_strip (parent)
1719         , _owner_is_mixer (owner_is_mixer)
1720         , ab_direction (true)
1721         , _get_plugin_selector (get_plugin_selector)
1722         , _placement (-1)
1723         , _visible_prefader_processors (0)
1724         , _rr_selection(rsel)
1725         , processor_display (drop_targets())
1726         , _redisplay_pending (false)
1727 {
1728         set_session (sess);
1729
1730         /* ProcessorBox actions and bindings created statically by call to
1731          * ProcessorBox::register_actions(), made by ARDOUR_UI so that actions
1732          * are available for context menus.
1733          */
1734
1735         processor_display.set_data ("ardour-bindings", bindings);
1736
1737         _width = Wide;
1738         processor_menu = 0;
1739         no_processor_redisplay = false;
1740
1741         processor_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1742         processor_scroller.add (processor_display);
1743         pack_start (processor_scroller, true, true);
1744
1745         processor_display.set_flags (CAN_FOCUS);
1746         processor_display.set_name ("ProcessorList");
1747         processor_display.set_data ("processorbox", this);
1748         processor_display.set_size_request (48, -1);
1749         processor_display.set_spacing (0);
1750
1751         processor_display.signal_enter_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::enter_notify), false);
1752         processor_display.signal_leave_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::leave_notify), false);
1753
1754         processor_display.ButtonPress.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_press_event));
1755         processor_display.ButtonRelease.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_release_event));
1756
1757         processor_display.Reordered.connect (sigc::mem_fun (*this, &ProcessorBox::reordered));
1758         processor_display.DropFromAnotherBox.connect (sigc::mem_fun (*this, &ProcessorBox::object_drop));
1759         processor_display.DropFromExternal.connect (sigc::mem_fun (*this, &ProcessorBox::plugin_drop));
1760
1761         processor_scroller.show ();
1762         processor_display.show ();
1763
1764         if (parent) {
1765                 parent->DeliveryChanged.connect (
1766                         _mixer_strip_connections, invalidator (*this), boost::bind (&ProcessorBox::mixer_strip_delivery_changed, this, _1), gui_context ()
1767                         );
1768         }
1769
1770         ARDOUR_UI_UTILS::set_tooltip (processor_display, _("Right-click to add/remove/edit\nplugins,inserts,sends and more"));
1771 }
1772
1773 ProcessorBox::~ProcessorBox ()
1774 {
1775         /* it may appear as if we should delete processor_menu but that is a
1776          * pointer to a widget owned by the UI Manager, and has potentially
1777          * be returned to many other ProcessorBoxes. GTK doesn't really make
1778          * clear the ownership of this widget, which is a menu and thus is
1779          * never packed into any container other than an implict GtkWindow.
1780          *
1781          * For now, until or if we ever get clarification over the ownership
1782          * story just let it continue to exist. At worst, its a small memory leak.
1783          */
1784 }
1785
1786 void
1787 ProcessorBox::set_route (boost::shared_ptr<Route> r)
1788 {
1789         if (_route == r) {
1790                 return;
1791         }
1792
1793         _route_connections.drop_connections();
1794
1795         /* new route: any existing block on processor redisplay must be meaningless */
1796         no_processor_redisplay = false;
1797         _route = r;
1798
1799         _route->processors_changed.connect (
1800                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_processors_changed, this, _1), gui_context()
1801                 );
1802
1803         _route->DropReferences.connect (
1804                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_going_away, this), gui_context()
1805                 );
1806
1807         _route->PropertyChanged.connect (
1808                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_property_changed, this, _1), gui_context()
1809                 );
1810
1811         redisplay_processors ();
1812 }
1813
1814 void
1815 ProcessorBox::route_going_away ()
1816 {
1817         /* don't keep updating display as processors are deleted */
1818         no_processor_redisplay = true;
1819         _route.reset ();
1820 }
1821
1822 boost::shared_ptr<Processor>
1823 ProcessorBox::find_drop_position (ProcessorEntry* position)
1824 {
1825         boost::shared_ptr<Processor> p;
1826         if (position) {
1827                 p = position->processor ();
1828                 if (!p) {
1829                         /* dropped on the blank entry (which will be before the
1830                                  fader), so use the first non-blank child as our
1831                                  `dropped on' processor */
1832                         list<ProcessorEntry*> c = processor_display.children ();
1833                         list<ProcessorEntry*>::iterator i = c.begin ();
1834
1835                         assert (i != c.end ());
1836                         p = (*i)->processor ();
1837                         assert (p);
1838                 }
1839         }
1840         return p;
1841 }
1842
1843 void
1844 ProcessorBox::_drop_plugin_preset (Gtk::SelectionData const &data, Route::ProcessorList &pl)
1845 {
1846                 const void * d = data.get_data();
1847                 const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>* tv = reinterpret_cast<const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>*>(d);
1848
1849                 PluginPresetList nfos;
1850                 TreeView* source;
1851                 tv->get_object_drag_data (nfos, &source);
1852
1853                 for (list<PluginPresetPtr>::const_iterator i = nfos.begin(); i != nfos.end(); ++i) {
1854                         PluginPresetPtr ppp = (*i);
1855                         PluginInfoPtr pip = ppp->_pip;
1856                         PluginPtr p = pip->load (*_session);
1857                         if (!p) {
1858                                 continue;
1859                         }
1860
1861                         if (ppp->_preset.valid) {
1862                                 p->load_preset (ppp->_preset);
1863                         }
1864
1865                         boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
1866                         if (Config->get_new_plugins_active ()) {
1867                                 processor->activate ();
1868                         }
1869                         pl.push_back (processor);
1870                 }
1871 }
1872
1873 void
1874 ProcessorBox::_drop_plugin (Gtk::SelectionData const &data, Route::ProcessorList &pl)
1875 {
1876                 const void * d = data.get_data();
1877                 const Gtkmm2ext::DnDTreeView<ARDOUR::PluginInfoPtr>* tv = reinterpret_cast<const Gtkmm2ext::DnDTreeView<ARDOUR::PluginInfoPtr>*>(d);
1878                 PluginInfoList nfos;
1879
1880                 TreeView* source;
1881                 tv->get_object_drag_data (nfos, &source);
1882
1883                 for (list<PluginInfoPtr>::const_iterator i = nfos.begin(); i != nfos.end(); ++i) {
1884                         PluginPtr p = (*i)->load (*_session);
1885                         if (!p) {
1886                                 continue;
1887                         }
1888                         boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
1889                         if (Config->get_new_plugins_active ()) {
1890                                 processor->activate ();
1891                         }
1892                         pl.push_back (processor);
1893                 }
1894 }
1895
1896 void
1897 ProcessorBox::plugin_drop (Gtk::SelectionData const &data, ProcessorEntry* position, Glib::RefPtr<Gdk::DragContext> const & context)
1898 {
1899         if (!_session) {
1900                 return;
1901         }
1902
1903         boost::shared_ptr<Processor> p = find_drop_position (position);
1904         Route::ProcessorList pl;
1905
1906         if (data.get_target() == "PluginInfoPtr") {
1907                 _drop_plugin (data, pl);
1908         }
1909         else if (data.get_target() == "PluginPresetPtr") {
1910                 _drop_plugin_preset (data, pl);
1911         }
1912         else {
1913                 return;
1914         }
1915
1916         Route::ProcessorStreams err;
1917         if (_route->add_processors (pl, p, &err)) {
1918                 string msg = _(
1919                                 "Processor Drag/Drop failed. Probably because\n\
1920 the I/O configuration of the plugins could\n\
1921 not match the configuration of this track.");
1922                 MessageDialog am (msg);
1923                 am.run ();
1924         }
1925 }
1926
1927 void
1928 ProcessorBox::object_drop (DnDVBox<ProcessorEntry>* source, ProcessorEntry* position, Glib::RefPtr<Gdk::DragContext> const & context)
1929 {
1930         if (Gdk::ACTION_LINK == context->get_selected_action()) {
1931                 list<ProcessorEntry*> children = source->selection ();
1932                 assert (children.size() == 1);
1933                 ProcessorEntry* other = *children.begin();
1934                 assert (other->can_copy_state (position));
1935                 boost::shared_ptr<ARDOUR::Processor> otherproc = other->processor();
1936                 boost::shared_ptr<ARDOUR::Processor> proc = position->processor();
1937                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
1938                 assert (otherproc && proc && pi);
1939
1940                 PBD::ID id = pi->id();
1941                 XMLNode& state = otherproc->get_state ();
1942                 /* strip side-chain state (processor inside processor must be a side-chain)
1943                  * otherwise we'll end up with duplicate ports-names.
1944                  * (this needs a better solution which retains connections)
1945                  */
1946                 state.remove_nodes ("Processor");
1947                 proc->set_state (state, Stateful::loading_state_version);
1948                 boost::dynamic_pointer_cast<PluginInsert>(proc)->update_id (id);
1949                 return;
1950         }
1951
1952         boost::shared_ptr<Processor> p = find_drop_position (position);
1953
1954         list<ProcessorEntry*> children = source->selection ();
1955         list<boost::shared_ptr<Processor> > procs;
1956         for (list<ProcessorEntry*>::const_iterator i = children.begin(); i != children.end(); ++i) {
1957                 if ((*i)->processor ()) {
1958                         if (boost::dynamic_pointer_cast<UnknownProcessor> ((*i)->processor())) {
1959                                 continue;
1960                         }
1961                         procs.push_back ((*i)->processor ());
1962                 }
1963         }
1964
1965         for (list<boost::shared_ptr<Processor> >::const_iterator i = procs.begin(); i != procs.end(); ++i) {
1966                 XMLNode& state = (*i)->get_state ();
1967                 XMLNodeList nlist;
1968                 nlist.push_back (&state);
1969                 paste_processor_state (nlist, p);
1970                 delete &state;
1971         }
1972
1973         /* since the dndvbox doesn't take care of this properly, we have to delete the originals
1974            ourselves.
1975         */
1976
1977         if ((context->get_suggested_action() == Gdk::ACTION_MOVE) && source) {
1978                 ProcessorBox* other = reinterpret_cast<ProcessorBox*> (source->get_data ("processorbox"));
1979                 if (other) {
1980                         other->delete_dragged_processors (procs);
1981                 }
1982         }
1983 }
1984
1985 void
1986 ProcessorBox::set_width (Width w)
1987 {
1988         if (_width == w) {
1989                 return;
1990         }
1991
1992         _width = w;
1993
1994         list<ProcessorEntry*> children = processor_display.children ();
1995         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
1996                 (*i)->set_enum_width (w);
1997         }
1998
1999         queue_resize ();
2000 }
2001
2002 Gtk::Menu*
2003 ProcessorBox::build_possible_aux_menu ()
2004 {
2005         boost::shared_ptr<RouteList> rl = _session->get_routes_with_internal_returns();
2006
2007         if (rl->empty()) {
2008                 /* No aux sends if there are no busses */
2009                 return 0;
2010         }
2011
2012         if (_route->is_monitor ()) {
2013                 return 0;
2014         }
2015
2016         using namespace Menu_Helpers;
2017         Menu* menu = manage (new Menu);
2018         MenuList& items = menu->items();
2019
2020         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
2021                 if (!_route->internal_send_for (*r) && *r != _route) {
2022                         items.push_back (MenuElem ((*r)->name(), sigc::bind (sigc::ptr_fun (ProcessorBox::rb_choose_aux), boost::weak_ptr<Route>(*r))));
2023                 }
2024         }
2025
2026         return menu;
2027 }
2028
2029 void
2030 ProcessorBox::show_processor_menu (int arg)
2031 {
2032         if (processor_menu == 0) {
2033                 processor_menu = build_processor_menu ();
2034                 processor_menu->signal_unmap().connect (sigc::mem_fun (*this, &ProcessorBox::processor_menu_unmapped));
2035         }
2036
2037         /* Sort out the plugin submenu */
2038
2039         Gtk::MenuItem* plugin_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/newplugin"));
2040
2041         if (plugin_menu_item) {
2042                 plugin_menu_item->set_submenu (*_get_plugin_selector()->plugin_menu());
2043         }
2044
2045         /* And the aux submenu */
2046
2047         Gtk::MenuItem* aux_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/newaux"));
2048
2049         if (aux_menu_item) {
2050                 Menu* m = build_possible_aux_menu();
2051                 if (m && !m->items().empty()) {
2052                         aux_menu_item->set_submenu (*m);
2053                         aux_menu_item->set_sensitive (true);
2054                 } else {
2055                         /* stupid gtkmm: we need to pass a null reference here */
2056                         gtk_menu_item_set_submenu (aux_menu_item->gobj(), 0);
2057                         aux_menu_item->set_sensitive (false);
2058                 }
2059         }
2060
2061         ActionManager::get_action (X_("ProcessorMenu"), "newinsert")->set_sensitive (!_route->is_monitor ());
2062         ActionManager::get_action (X_("ProcessorMenu"), "newsend")->set_sensitive (!_route->is_monitor ());
2063
2064         ProcessorEntry* single_selection = 0;
2065         if (processor_display.selection().size() == 1) {
2066                 single_selection = processor_display.selection().front();
2067         }
2068
2069         /* And the controls submenu */
2070
2071         Gtk::MenuItem* controls_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/controls"));
2072
2073         if (controls_menu_item) {
2074                 if (single_selection) {
2075                         Menu* m = single_selection->build_controls_menu ();
2076                         if (m && !m->items().empty()) {
2077                                 controls_menu_item->set_submenu (*m);
2078                                 controls_menu_item->set_sensitive (true);
2079                         } else {
2080                                 gtk_menu_item_set_submenu (controls_menu_item->gobj(), 0);
2081                                 controls_menu_item->set_sensitive (false);
2082                         }
2083                 } else {
2084                         controls_menu_item->set_sensitive (false);
2085                 }
2086         }
2087
2088         Gtk::MenuItem* send_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/send_options"));
2089         if (send_menu_item) {
2090                 if (single_selection && !_route->is_monitor()) {
2091                         Menu* m = single_selection->build_send_options_menu ();
2092                         if (m && !m->items().empty()) {
2093                                 send_menu_item->set_submenu (*m);
2094                                 send_menu_item->set_sensitive (true);
2095                         } else {
2096                                 gtk_menu_item_set_submenu (send_menu_item->gobj(), 0);
2097                                 send_menu_item->set_sensitive (false);
2098                         }
2099                 } else {
2100                         send_menu_item->set_sensitive (false);
2101                 }
2102         }
2103
2104         /* Sensitise actions as approprioate */
2105
2106
2107         const bool sensitive = !processor_display.selection().empty() && ! stub_processor_selected ();
2108
2109         paste_action->set_sensitive (!_rr_selection.processors.empty());
2110         cut_action->set_sensitive (sensitive && can_cut ());
2111         copy_action->set_sensitive (sensitive);
2112         delete_action->set_sensitive (sensitive || stub_processor_selected ());
2113
2114         edit_action->set_sensitive (one_processor_can_be_edited ());
2115         edit_generic_action->set_sensitive (one_processor_can_be_edited ());
2116
2117         boost::shared_ptr<PluginInsert> pi;
2118         if (single_selection) {
2119                 pi = boost::dynamic_pointer_cast<PluginInsert> (single_selection->processor ());
2120         }
2121
2122         manage_pins_action->set_sensitive (pi != 0);
2123
2124         /* allow editing with an Ardour-generated UI for plugin inserts with editors */
2125         edit_action->set_sensitive (pi && pi->plugin()->has_editor ());
2126
2127         /* disallow rename for multiple selections, for plugin inserts and for the fader */
2128         rename_action->set_sensitive (single_selection
2129                         && !pi
2130                         && !boost::dynamic_pointer_cast<Amp> (single_selection->processor ())
2131                         && !boost::dynamic_pointer_cast<UnknownProcessor> (single_selection->processor ()));
2132
2133         processor_menu->popup (1, arg);
2134
2135         /* Add a placeholder gap to the processor list to indicate where a processor would be
2136            inserted were one chosen from the menu.
2137         */
2138         int x, y;
2139         processor_display.get_pointer (x, y);
2140         _placement = processor_display.add_placeholder (y);
2141
2142         if (_visible_prefader_processors == 0 && _placement > 0) {
2143                 --_placement;
2144         }
2145 }
2146
2147 bool
2148 ProcessorBox::enter_notify (GdkEventCrossing*)
2149 {
2150         processor_display.grab_focus ();
2151         _current_processor_box = this;
2152         return false;
2153 }
2154
2155 bool
2156 ProcessorBox::leave_notify (GdkEventCrossing* ev)
2157 {
2158         if (ev->detail == GDK_NOTIFY_INFERIOR) {
2159                 return false;
2160         }
2161
2162         Widget* top = get_toplevel();
2163
2164         if (top->is_toplevel()) {
2165                 Window* win = dynamic_cast<Window*> (top);
2166                 gtk_window_set_focus (win->gobj(), 0);
2167         }
2168
2169         return false;
2170 }
2171
2172 bool
2173 ProcessorBox::processor_operation (ProcessorOperation op)
2174 {
2175         ProcSelection targets;
2176
2177         get_selected_processors (targets);
2178
2179 /*      if (targets.empty()) {
2180
2181                 int x, y;
2182                 processor_display.get_pointer (x, y);
2183
2184                 pair<ProcessorEntry *, double> const pointer = processor_display.get_child_at_position (y);
2185
2186                 if (pointer.first && pointer.first->processor()) {
2187                         targets.push_back (pointer.first->processor ());
2188                 }
2189         }
2190 */
2191
2192         if ((op == ProcessorsDelete) && targets.empty()) {
2193                 return false;  //nothing to delete.  return false so the editor-mixer, because the user was probably intending to delete something in the editor
2194         }
2195
2196         switch (op) {
2197         case ProcessorsSelectAll:
2198                 processor_display.select_all ();
2199                 break;
2200
2201         case ProcessorsSelectNone:
2202                 processor_display.select_none ();
2203                 break;
2204
2205         case ProcessorsCopy:
2206                 copy_processors (targets);
2207                 break;
2208
2209         case ProcessorsCut:
2210                 cut_processors (targets);
2211                 break;
2212
2213         case ProcessorsPaste:
2214                 // some processors are not selectable (e.g fader, meter), target is empty.
2215                 if (targets.empty() && _placement >= 0) {
2216                         assert (_route);
2217                         boost::shared_ptr<Processor> proc = _route->before_processor_for_index (_placement);
2218                         if (proc) {
2219                                 targets.push_back (proc);
2220                         }
2221                 }
2222                 if (targets.empty()) {
2223                         paste_processors ();
2224                 } else {
2225                         paste_processors (targets.front());
2226                 }
2227                 break;
2228
2229         case ProcessorsDelete:
2230                 delete_processors (targets);
2231                 break;
2232
2233         case ProcessorsToggleActive:
2234                 for (ProcSelection::iterator i = targets.begin(); i != targets.end(); ++i) {
2235                         if ((*i)->active()) {
2236                                 (*i)->deactivate ();
2237                         } else {
2238                                 (*i)->activate ();
2239                         }
2240                 }
2241                 break;
2242
2243         case ProcessorsAB:
2244                 ab_plugins ();
2245                 break;
2246
2247         default:
2248                 break;
2249         }
2250
2251         return true;
2252 }
2253
2254 ProcessorWindowProxy*
2255 ProcessorBox::find_window_proxy (boost::shared_ptr<Processor> processor) const
2256 {
2257         return  processor->window_proxy();
2258 }
2259
2260
2261 bool
2262 ProcessorBox::processor_button_press_event (GdkEventButton *ev, ProcessorEntry* child)
2263 {
2264         boost::shared_ptr<Processor> processor;
2265         if (child) {
2266                 processor = child->processor ();
2267         }
2268
2269         int ret = false;
2270         bool selected = processor_display.selected (child);
2271
2272         if (processor && (Keyboard::is_edit_event (ev) || (ev->button == 1 && ev->type == GDK_2BUTTON_PRESS))) {
2273
2274                 if (_session->engine().connected()) {
2275                         /* XXX giving an error message here is hard, because we may be in the midst of a button press */
2276
2277                         if (!one_processor_can_be_edited ()) {
2278                                 return true;
2279                         }
2280
2281                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::SecondaryModifier)) {
2282                                 generic_edit_processor (processor);
2283                         } else {
2284                                 edit_processor (processor);
2285                         }
2286                 }
2287
2288                 ret = true;
2289
2290         } else if (Keyboard::is_context_menu_event (ev)) {
2291
2292                 show_processor_menu (ev->time);
2293
2294                 ret = true;
2295
2296         } else if (processor && ev->button == 1 && selected) {
2297
2298                 // this is purely informational but necessary for route params UI
2299                 ProcessorSelected (processor); // emit
2300
2301         } else if (!processor && ev->button == 1 && ev->type == GDK_2BUTTON_PRESS) {
2302
2303                 choose_plugin ();
2304                 _get_plugin_selector()->show_manager ();
2305         }
2306
2307         return ret;
2308 }
2309
2310 bool
2311 ProcessorBox::processor_button_release_event (GdkEventButton *ev, ProcessorEntry* child)
2312 {
2313         boost::shared_ptr<Processor> processor;
2314         if (child) {
2315                 processor = child->processor ();
2316         }
2317
2318         if (processor && Keyboard::is_delete_event (ev)) {
2319
2320                 Glib::signal_idle().connect (sigc::bind (
2321                                 sigc::mem_fun(*this, &ProcessorBox::idle_delete_processor),
2322                                 boost::weak_ptr<Processor>(processor)));
2323
2324         } else if (processor && Keyboard::is_button2_event (ev)
2325 #ifndef __APPLE__
2326                    && (Keyboard::no_modifier_keys_pressed (ev) && ((ev->state & Gdk::BUTTON2_MASK) == Gdk::BUTTON2_MASK))
2327 #endif
2328                 ) {
2329
2330                 /* button2-click with no/appropriate modifiers */
2331
2332                 if (processor->active()) {
2333                         processor->deactivate ();
2334                 } else {
2335                         processor->activate ();
2336                 }
2337         }
2338
2339         return false;
2340 }
2341
2342 Menu *
2343 ProcessorBox::build_processor_menu ()
2344 {
2345         processor_menu = dynamic_cast<Gtk::Menu*>(ActionManager::get_widget("/ProcessorMenu") );
2346         processor_menu->set_name ("ArdourContextMenu");
2347         return processor_menu;
2348 }
2349
2350 void
2351 ProcessorBox::select_all_processors ()
2352 {
2353         processor_display.select_all ();
2354 }
2355
2356 void
2357 ProcessorBox::deselect_all_processors ()
2358 {
2359         processor_display.select_none ();
2360 }
2361
2362 void
2363 ProcessorBox::choose_plugin ()
2364 {
2365         _get_plugin_selector()->set_interested_object (*this);
2366 }
2367
2368 /** @return true if an error occurred, otherwise false */
2369 bool
2370 ProcessorBox::choose_lua ()
2371 {
2372         LuaScriptInfoPtr spi;
2373
2374         ScriptSelector ss (_("Add Lua DSP Processor"), LuaScriptInfo::DSP);
2375         switch (ss.run ()) {
2376                 case Gtk::RESPONSE_ACCEPT:
2377                         spi = ss.script();
2378                         break;
2379                 default:
2380                         return true;
2381         }
2382         ss.hide ();
2383
2384         PluginPtr p;
2385         try {
2386                 LuaPluginInfoPtr lpi (new LuaPluginInfo(spi));
2387                 p = (lpi->load (*_session));
2388         } catch (...) {
2389                 string msg = _(
2390                                 "Failed to instantiate Lua DSP Processor,\n"
2391                                 "probably because the script is invalid (no dsp function).");
2392                 MessageDialog am (msg);
2393                 am.run ();
2394                 return true;
2395         }
2396
2397         boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
2398
2399         Route::ProcessorStreams err_streams;
2400         if (_route->add_processor_by_index (processor, _placement, &err_streams, Config->get_new_plugins_active ())) {
2401                 string msg = _(
2402                                 "Failed to add Lua DSP Processor at the given position,\n"
2403                                 "probably because the I/O configuration of the plugins\n"
2404                                 "could not match the configuration of this track.");
2405                 MessageDialog am (msg);
2406                 am.run ();
2407         }
2408         return false;
2409 }
2410
2411 /** @return true if an error occurred, otherwise false */
2412 bool
2413 ProcessorBox::use_plugins (const SelectedPlugins& plugins)
2414 {
2415         for (SelectedPlugins::const_iterator p = plugins.begin(); p != plugins.end(); ++p) {
2416
2417                 boost::shared_ptr<Processor> processor (new PluginInsert (*_session, *p));
2418
2419                 Route::ProcessorStreams err_streams;
2420
2421                 if (_route->add_processor_by_index (processor, _placement, &err_streams, Config->get_new_plugins_active ())) {
2422                         weird_plugin_dialog (**p, err_streams);
2423                         return true;
2424                         // XXX SHAREDPTR delete plugin here .. do we even need to care?
2425                 } else if (plugins.size() == 1 && UIConfiguration::instance().get_open_gui_after_adding_plugin()) {
2426                         if (boost::dynamic_pointer_cast<PluginInsert>(processor)->plugin()->has_inline_display() && UIConfiguration::instance().get_prefer_inline_over_gui()) {
2427                                 ;
2428                         } else if (_session->engine().connected () && processor_can_be_edited (processor)) {
2429                                 if ((*p)->has_editor ()) {
2430                                         edit_processor (processor);
2431                                 } else {
2432                                         generic_edit_processor (processor);
2433                                 }
2434                         }
2435                 }
2436         }
2437
2438         return false;
2439 }
2440
2441 void
2442 ProcessorBox::weird_plugin_dialog (Plugin& p, Route::ProcessorStreams streams)
2443 {
2444         ArdourDialog dialog (_("Plugin Incompatibility"));
2445         Label label;
2446
2447         string text = string_compose(_("You attempted to add the plugin \"%1\" in slot %2.\n"),
2448                         p.name(), streams.index);
2449
2450         bool has_midi  = streams.count.n_midi() > 0 || p.get_info()->n_inputs.n_midi() > 0;
2451         bool has_audio = streams.count.n_audio() > 0 || p.get_info()->n_inputs.n_audio() > 0;
2452
2453         text += _("\nThis plugin has:\n");
2454         if (has_midi) {
2455                 uint32_t const n = p.get_info()->n_inputs.n_midi ();
2456                 text += string_compose (ngettext ("\t%1 MIDI input\n", "\t%1 MIDI inputs\n", n), n);
2457         }
2458         if (has_audio) {
2459                 uint32_t const n = p.get_info()->n_inputs.n_audio ();
2460                 text += string_compose (ngettext ("\t%1 audio input\n", "\t%1 audio inputs\n", n), n);
2461         }
2462
2463         text += _("\nbut at the insertion point, there are:\n");
2464         if (has_midi) {
2465                 uint32_t const n = streams.count.n_midi ();
2466                 text += string_compose (ngettext ("\t%1 MIDI channel\n", "\t%1 MIDI channels\n", n), n);
2467         }
2468         if (has_audio) {
2469                 uint32_t const n = streams.count.n_audio ();
2470                 text += string_compose (ngettext ("\t%1 audio channel\n", "\t%1 audio channels\n", n), n);
2471         }
2472
2473         text += string_compose (_("\n%1 is unable to insert this plugin here.\n"), PROGRAM_NAME);
2474         label.set_text(text);
2475
2476         dialog.get_vbox()->pack_start (label);
2477         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
2478
2479         dialog.set_name (X_("PluginIODialog"));
2480         dialog.set_modal (true);
2481         dialog.show_all ();
2482
2483         dialog.run ();
2484 }
2485
2486 void
2487 ProcessorBox::choose_insert ()
2488 {
2489         boost::shared_ptr<Processor> processor (new PortInsert (*_session, _route->pannable(), _route->mute_master()));
2490         _route->add_processor_by_index (processor, _placement);
2491 }
2492
2493 /* Caller must not hold process lock */
2494 void
2495 ProcessorBox::choose_send ()
2496 {
2497         boost::shared_ptr<Send> send (new Send (*_session, _route->pannable (), _route->mute_master()));
2498
2499         /* make an educated guess at the initial number of outputs for the send */
2500         ChanCount outs = (_session->master_out())
2501                         ? _session->master_out()->n_outputs()
2502                         : _route->n_outputs();
2503
2504         /* XXX need processor lock on route */
2505         try {
2506                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
2507                 send->output()->ensure_io (outs, false, this);
2508         } catch (AudioEngine::PortRegistrationFailure& err) {
2509                 error << string_compose (_("Cannot set up new send: %1"), err.what()) << endmsg;
2510                 return;
2511         }
2512
2513         /* let the user adjust the IO setup before creation.
2514
2515            Note: this dialog is NOT modal - we just leave it to run and it will
2516            return when its Finished signal is emitted - typically when the window
2517            is closed.
2518          */
2519
2520         IOSelectorWindow *ios = new IOSelectorWindow (_session, send->output(), true);
2521         ios->show ();
2522
2523         /* keep a reference to the send so it doesn't get deleted while
2524            the IOSelectorWindow is doing its stuff
2525         */
2526         _processor_being_created = send;
2527
2528         ios->selector().Finished.connect (sigc::bind (
2529                         sigc::mem_fun(*this, &ProcessorBox::send_io_finished),
2530                         boost::weak_ptr<Processor>(send), ios));
2531
2532 }
2533
2534 void
2535 ProcessorBox::send_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
2536 {
2537         boost::shared_ptr<Processor> processor (weak_processor.lock());
2538
2539         /* drop our temporary reference to the new send */
2540         _processor_being_created.reset ();
2541
2542         if (!processor) {
2543                 return;
2544         }
2545
2546         switch (r) {
2547         case IOSelector::Cancelled:
2548                 // processor will go away when all shared_ptrs to it vanish
2549                 break;
2550
2551         case IOSelector::Accepted:
2552                 _route->add_processor_by_index (processor, _placement);
2553                 break;
2554         }
2555
2556         delete_when_idle (ios);
2557 }
2558
2559 void
2560 ProcessorBox::return_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
2561 {
2562         boost::shared_ptr<Processor> processor (weak_processor.lock());
2563
2564         /* drop our temporary reference to the new return */
2565         _processor_being_created.reset ();
2566
2567         if (!processor) {
2568                 return;
2569         }
2570
2571         switch (r) {
2572         case IOSelector::Cancelled:
2573                 // processor will go away when all shared_ptrs to it vanish
2574                 break;
2575
2576         case IOSelector::Accepted:
2577                 _route->add_processor_by_index (processor, _placement);
2578                 break;
2579         }
2580
2581         delete_when_idle (ios);
2582 }
2583
2584 void
2585 ProcessorBox::choose_aux (boost::weak_ptr<Route> wr)
2586 {
2587         if (!_route) {
2588                 return;
2589         }
2590
2591         boost::shared_ptr<Route> target = wr.lock();
2592
2593         if (!target) {
2594                 return;
2595         }
2596
2597         _session->add_internal_send (target, _placement, _route);
2598 }
2599
2600 void
2601 ProcessorBox::route_processors_changed (RouteProcessorChange c)
2602 {
2603         if (c.type == RouteProcessorChange::MeterPointChange && c.meter_visibly_changed == false) {
2604                 /* the meter has moved, but it was and still is invisible to the user, so nothing to do */
2605                 return;
2606         }
2607
2608         redisplay_processors ();
2609 }
2610
2611 void
2612 ProcessorBox::redisplay_processors ()
2613 {
2614         ENSURE_GUI_THREAD (*this, &ProcessorBox::redisplay_processors);
2615         bool     fader_seen;
2616
2617         if (no_processor_redisplay) {
2618                 return;
2619         }
2620
2621         processor_display.clear ();
2622
2623         _visible_prefader_processors = 0;
2624         fader_seen = false;
2625
2626         _route->foreach_processor (sigc::bind (sigc::mem_fun (*this, &ProcessorBox::help_count_visible_prefader_processors),
2627                                                &_visible_prefader_processors, &fader_seen));
2628
2629         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::add_processor_to_display));
2630         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::maybe_add_processor_to_ui_list));
2631         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::maybe_add_processor_pin_mgr));
2632
2633         setup_entry_positions ();
2634 }
2635
2636 /** Add a ProcessorWindowProxy for a processor to our list, if that processor does
2637  *  not already have one.
2638  */
2639 void
2640 ProcessorBox::maybe_add_processor_to_ui_list (boost::weak_ptr<Processor> w)
2641 {
2642         boost::shared_ptr<Processor> p = w.lock ();
2643         if (!p) {
2644                 return;
2645         }
2646         if (p->window_proxy()) {
2647                 return;
2648         }
2649
2650         /* not on the list; add it */
2651
2652         string loc;
2653 #if 0 // is this still needed? Why?
2654         if (_parent_strip) {
2655                 if (_parent_strip->mixer_owned()) {
2656                         loc = X_("M");
2657                 } else {
2658                         loc = X_("R");
2659                 }
2660         } else {
2661                 loc = X_("P");
2662         }
2663 #else
2664         loc = X_("P");
2665 #endif
2666
2667         ProcessorWindowProxy* wp = new ProcessorWindowProxy (
2668                 string_compose ("%1-%2-%3", loc, _route->id(), p->id()),
2669                 this,
2670                 w);
2671
2672         const XMLNode* ui_xml = _session->extra_xml (X_("UI"));
2673
2674         if (ui_xml) {
2675                 wp->set_state (*ui_xml, 0);
2676         }
2677
2678         void* existing_ui = p->get_ui ();
2679
2680         if (existing_ui) {
2681                 wp->use_window (*(reinterpret_cast<Gtk::Window*>(existing_ui)));
2682         }
2683
2684         p->set_window_proxy (wp);
2685         WM::Manager::instance().register_window (wp);
2686 }
2687
2688 void
2689 ProcessorBox::maybe_add_processor_pin_mgr (boost::weak_ptr<Processor> w)
2690 {
2691         boost::shared_ptr<Processor> p = w.lock ();
2692         if (!p || p->pinmgr_proxy ()) {
2693                 return;
2694         }
2695
2696         PluginPinWindowProxy* wp = new PluginPinWindowProxy (
2697                         string_compose ("PM-%2-%3", _route->id(), p->id()), w);
2698         wp->set_session (_session);
2699
2700         const XMLNode* ui_xml = _session->extra_xml (X_("UI"));
2701         if (ui_xml) {
2702                 wp->set_state (*ui_xml, 0);
2703         }
2704
2705         void* existing_ui = p->get_ui ();
2706
2707         if (existing_ui) {
2708                 wp->use_window (*(reinterpret_cast<Gtk::Window*>(existing_ui)));
2709         }
2710
2711         p->set_pingmgr_proxy (wp);
2712         WM::Manager::instance().register_window (wp);
2713 }
2714 void
2715 ProcessorBox::help_count_visible_prefader_processors (boost::weak_ptr<Processor> p, uint32_t* cnt, bool* amp_seen)
2716 {
2717         boost::shared_ptr<Processor> processor (p.lock ());
2718
2719         if (processor && ( processor->display_to_user()
2720 #ifndef NDEBUG
2721                             || show_all_processors
2722 #endif
2723                          )
2724            ) {
2725
2726                 if (boost::dynamic_pointer_cast<Amp>(processor) &&
2727                     boost::dynamic_pointer_cast<Amp>(processor)->gain_control()->parameter().type() == GainAutomation) {
2728                         *amp_seen = true;
2729                 } else {
2730                         if (!*amp_seen) {
2731                                 (*cnt)++;
2732                         }
2733                 }
2734         }
2735 }
2736
2737 void
2738 ProcessorBox::add_processor_to_display (boost::weak_ptr<Processor> p)
2739 {
2740         boost::shared_ptr<Processor> processor (p.lock ());
2741
2742         if (!processor || ( !processor->display_to_user()
2743 #ifndef NDEBUG
2744                             && !show_all_processors
2745 #endif
2746                           )
2747            ) {
2748                 return;
2749         }
2750
2751         boost::shared_ptr<PluginInsert> plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor);
2752
2753         ProcessorEntry* e = 0;
2754         if (plugin_insert) {
2755                 e = new PluginInsertProcessorEntry (this, plugin_insert, _width);
2756         } else {
2757                 e = new ProcessorEntry (this, processor, _width);
2758         }
2759
2760         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
2761         boost::shared_ptr<PortInsert> ext = boost::dynamic_pointer_cast<PortInsert> (processor);
2762         boost::shared_ptr<UnknownProcessor> stub = boost::dynamic_pointer_cast<UnknownProcessor> (processor);
2763
2764         //faders and meters are not deletable, copy/paste-able, so they shouldn't be selectable
2765         if (!send && !plugin_insert && !ext && !stub)
2766                 e->set_selectable(false);
2767
2768         bool mark_send_visible = false;
2769         if (send && _parent_strip) {
2770                 /* show controls of new sends by default */
2771                 GUIObjectState& st = _parent_strip->gui_object_state ();
2772                 XMLNode* strip = st.get_or_add_node (_parent_strip->state_id ());
2773                 assert (strip);
2774                 /* check if state exists, if not it must be a new send */
2775                 if (!st.get_node(strip, e->state_id())) {
2776                         mark_send_visible = true;
2777                 }
2778         }
2779
2780         /* Set up this entry's state from the GUIObjectState */
2781         XMLNode* proc = entry_gui_object_state (e);
2782         if (proc) {
2783                 e->set_control_state (proc);
2784         }
2785
2786         if (mark_send_visible) {
2787                 e->show_all_controls ();
2788         }
2789
2790         if (plugin_insert
2791 #ifdef MIXBUS
2792                         && !plugin_insert->plugin(0)->is_channelstrip()
2793 #endif
2794                  )
2795         {
2796                 processor_display.add_child (e, drag_targets());
2797         } else {
2798                 processor_display.add_child (e, drag_targets_noplugin());
2799         }
2800 }
2801
2802 void
2803 ProcessorBox::reordered ()
2804 {
2805         compute_processor_sort_keys ();
2806         setup_entry_positions ();
2807 }
2808
2809 void
2810 ProcessorBox::setup_routing_feeds ()
2811 {
2812         list<ProcessorEntry*> children = processor_display.children ();
2813         /* first set the i/o maps for every processor */
2814         list<ProcessorEntry*>::iterator prev = children.begin();
2815
2816         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2817                 boost::shared_ptr<ARDOUR::Processor> p = (*i)->processor();
2818                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (p);
2819
2820                 list<ProcessorEntry*>::iterator next = i;
2821                 next++;
2822
2823                 if (pi) {
2824                         ChanCount sinks = pi->natural_input_streams ();
2825                         ChanCount sources = pi->natural_output_streams ();
2826                         uint32_t count = pi->get_count ();
2827                         ChanCount in, out;
2828                         pi->configured_io (in, out);
2829
2830                         ChanCount midi_thru;
2831                         ChanCount midi_bypass;
2832                         ChanMapping input_map (pi->input_map ());
2833                         if (pi->has_midi_thru ()) {
2834                                  midi_thru.set(DataType::MIDI, 1);
2835                                  input_map.set (DataType::MIDI, 0, 0);
2836                         }
2837                         if (pi->has_midi_bypass ()) {
2838                                  midi_bypass.set(DataType::MIDI, 1);
2839                         }
2840
2841                         (*i)->input_icon.set_ports (sinks * count + midi_thru);
2842                         (*i)->output_icon.set_ports (sources * count + midi_bypass);
2843
2844                         (*i)->routing_icon.set (
2845                                         in, out,
2846                                         sinks * count + midi_thru,
2847                                         sources * count + midi_bypass,
2848                                         input_map,
2849                                         pi->output_map (),
2850                                         pi->thru_map ());
2851
2852                         if (next != children.end()) {
2853                                 (*next)->routing_icon.set_fed_by (out, sources * count + midi_bypass,
2854                                                 pi->output_map (), pi->thru_map ());
2855                         }
2856
2857                         if (prev != i) {
2858                                 (*prev)->routing_icon.set_feeding (in, sinks * count + midi_thru,
2859                                                 pi->input_map (), pi->thru_map ());
2860                         }
2861
2862                 } else {
2863                         (*i)->input_icon.set_ports (p->input_streams());
2864                         (*i)->output_icon.set_ports (p->output_streams());
2865                         ChanMapping inmap (p->input_streams ());
2866                         ChanMapping outmap (p->input_streams ());
2867                         ChanMapping thrumap;
2868                         (*i)->routing_icon.set (
2869                                         p->input_streams(),
2870                                         p->output_streams(),
2871                                         p->input_streams(),
2872                                         p->output_streams(),
2873                                         inmap, outmap, thrumap);
2874
2875                         if (next != children.end()) {
2876                                 (*next)->routing_icon.set_fed_by (
2877                                                 p->output_streams(),
2878                                                 p->output_streams(),
2879                                                 outmap, thrumap);
2880                         }
2881                         if (prev != i) {
2882                                 (*prev)->routing_icon.set_feeding (
2883                                                 p->input_streams(),
2884                                                 p->output_streams(),
2885                                                 inmap, thrumap);
2886                         }
2887                 }
2888
2889                 if (i == children.begin()) {
2890                         (*i)->routing_icon.unset_fed_by ();
2891                 }
2892                 prev = i;
2893                 (*i)->input_icon.hide();
2894         }
2895
2896         /* now set which icons need to be displayed */
2897         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2898                 (*i)->output_routing_icon.copy_state ((*i)->routing_icon);
2899
2900                 if ((*i)->routing_icon.in_identity ()) {
2901                         (*i)->routing_icon.hide();
2902                         if (i == children.begin()) {
2903                                 (*i)->input_icon.show();
2904                         }
2905                 } else {
2906                         (*i)->routing_icon.show();
2907                         (*i)->routing_icon.queue_draw();
2908                         (*i)->input_icon.show();
2909                 }
2910
2911                 list<ProcessorEntry*>::iterator next = i;
2912                 if (++next == children.end()) {
2913                         // last processor in the chain
2914                         (*i)->output_routing_icon.set_terminal(true);
2915                         (*i)->output_routing_icon.unset_feeding ();
2916                         if ((*i)->routing_icon.out_identity ()) {
2917                                 (*i)->output_routing_icon.hide();
2918                         } else {
2919                                 (*i)->output_routing_icon.show();
2920                                 (*i)->output_routing_icon.queue_draw();
2921                         }
2922                 } else {
2923                         (*i)->output_routing_icon.set_terminal(false);
2924                         if (!(*i)->routing_icon.out_identity ()
2925                                         && !(*i)->routing_icon.in_identity ()
2926                                         && (*i)->routing_icon.can_coalesce ()) {
2927                                 (*i)->output_routing_icon.hide();
2928                         } else if (!(*i)->routing_icon.out_identity ()) {
2929                                 (*i)->output_routing_icon.show();
2930                                 (*i)->output_routing_icon.queue_draw();
2931                                 (*next)->input_icon.show();
2932                         } else {
2933                                 (*i)->output_routing_icon.hide();
2934                         }
2935                 }
2936         }
2937 }
2938
2939 void
2940 ProcessorBox::setup_entry_positions ()
2941 {
2942         list<ProcessorEntry*> children = processor_display.children ();
2943         bool pre_fader = true;
2944
2945         uint32_t num = 0;
2946         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2947                 if (boost::dynamic_pointer_cast<Amp>((*i)->processor()) &&
2948                     boost::dynamic_pointer_cast<Amp>((*i)->processor())->gain_control()->parameter().type() == GainAutomation) {
2949                         pre_fader = false;
2950                         (*i)->set_position (ProcessorEntry::Fader, num++);
2951                 } else {
2952                         if (pre_fader) {
2953                                 (*i)->set_position (ProcessorEntry::PreFader, num++);
2954                         } else {
2955                                 (*i)->set_position (ProcessorEntry::PostFader, num++);
2956                         }
2957                 }
2958         }
2959         setup_routing_feeds ();
2960 }
2961
2962 void
2963 ProcessorBox::compute_processor_sort_keys ()
2964 {
2965         list<ProcessorEntry*> children = processor_display.children ();
2966         Route::ProcessorList our_processors;
2967
2968         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2969                 if ((*i)->processor()) {
2970                         our_processors.push_back ((*i)->processor ());
2971                 }
2972         }
2973
2974         if (_route->reorder_processors (our_processors)) {
2975                 /* Reorder failed, so report this to the user.  As far as I can see this must be done
2976                    in an idle handler: it seems that the redisplay_processors() that happens below destroys
2977                    widgets that were involved in the drag-and-drop on the processor list, which causes problems
2978                    when the drag is torn down after this handler function is finished.
2979                 */
2980                 Glib::signal_idle().connect_once (sigc::mem_fun (*this, &ProcessorBox::report_failed_reorder));
2981         }
2982 }
2983
2984 void
2985 ProcessorBox::report_failed_reorder ()
2986 {
2987         /* reorder failed, so redisplay */
2988
2989         redisplay_processors ();
2990
2991         /* now tell them about the problem */
2992
2993         ArdourDialog dialog (_("Plugin Incompatibility"));
2994         Label label;
2995
2996         label.set_text (_("\
2997 You cannot reorder these plugins/sends/inserts\n\
2998 in that way because the inputs and\n\
2999 outputs will not work correctly."));
3000
3001         dialog.get_vbox()->set_border_width (12);
3002         dialog.get_vbox()->pack_start (label);
3003         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
3004
3005         dialog.set_name (X_("PluginIODialog"));
3006         dialog.set_modal (true);
3007         dialog.show_all ();
3008
3009         dialog.run ();
3010 }
3011
3012 void
3013 ProcessorBox::rename_processors ()
3014 {
3015         ProcSelection to_be_renamed;
3016
3017         get_selected_processors (to_be_renamed);
3018
3019         if (to_be_renamed.empty()) {
3020                 return;
3021         }
3022
3023         for (ProcSelection::iterator i = to_be_renamed.begin(); i != to_be_renamed.end(); ++i) {
3024                 rename_processor (*i);
3025         }
3026 }
3027
3028 bool
3029 ProcessorBox::can_cut () const
3030 {
3031         vector<boost::shared_ptr<Processor> > sel;
3032
3033         get_selected_processors (sel);
3034
3035         /* cut_processors () does not cut inserts */
3036
3037         for (vector<boost::shared_ptr<Processor> >::const_iterator i = sel.begin (); i != sel.end (); ++i) {
3038
3039                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
3040                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
3041                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
3042                         return true;
3043                 }
3044         }
3045
3046         return false;
3047 }
3048
3049 bool
3050 ProcessorBox::stub_processor_selected () const
3051 {
3052         vector<boost::shared_ptr<Processor> > sel;
3053
3054         get_selected_processors (sel);
3055
3056         for (vector<boost::shared_ptr<Processor> >::const_iterator i = sel.begin (); i != sel.end (); ++i) {
3057                 if (boost::dynamic_pointer_cast<UnknownProcessor>((*i)) != 0) {
3058                         return true;
3059                 }
3060         }
3061
3062         return false;
3063 }
3064
3065 void
3066 ProcessorBox::cut_processors (const ProcSelection& to_be_removed)
3067 {
3068         if (to_be_removed.empty()) {
3069                 return;
3070         }
3071
3072         XMLNode* node = new XMLNode (X_("cut"));
3073         Route::ProcessorList to_cut;
3074
3075         no_processor_redisplay = true;
3076         for (ProcSelection::const_iterator i = to_be_removed.begin(); i != to_be_removed.end(); ++i) {
3077                 // Cut only plugins, sends and returns
3078                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
3079                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
3080                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
3081
3082                         Window* w = get_processor_ui (*i);
3083
3084                         if (w) {
3085                                 w->hide ();
3086                         }
3087
3088                         XMLNode& child ((*i)->get_state());
3089                         node->add_child_nocopy (child);
3090                         to_cut.push_back (*i);
3091                 }
3092         }
3093
3094         if (_route->remove_processors (to_cut) != 0) {
3095                 delete node;
3096                 no_processor_redisplay = false;
3097                 return;
3098         }
3099
3100         _rr_selection.set (node);
3101
3102         no_processor_redisplay = false;
3103         redisplay_processors ();
3104 }
3105
3106 void
3107 ProcessorBox::copy_processors (const ProcSelection& to_be_copied)
3108 {
3109         if (to_be_copied.empty()) {
3110                 return;
3111         }
3112
3113         XMLNode* node = new XMLNode (X_("copy"));
3114
3115         for (ProcSelection::const_iterator i = to_be_copied.begin(); i != to_be_copied.end(); ++i) {
3116                 // Copy only plugins, sends, returns
3117                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
3118                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
3119                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
3120                         node->add_child_nocopy ((*i)->get_state());
3121                 }
3122         }
3123
3124         _rr_selection.set (node);
3125 }
3126
3127 void
3128 ProcessorBox::delete_processors (const ProcSelection& targets)
3129 {
3130         if (targets.empty()) {
3131                 return;
3132         }
3133
3134         no_processor_redisplay = true;
3135
3136         for (ProcSelection::const_iterator i = targets.begin(); i != targets.end(); ++i) {
3137
3138                 Window* w = get_processor_ui (*i);
3139
3140                 if (w) {
3141                         w->hide ();
3142                 }
3143
3144                 _route->remove_processor(*i);
3145         }
3146
3147         no_processor_redisplay = false;
3148         redisplay_processors ();
3149 }
3150
3151 void
3152 ProcessorBox::delete_dragged_processors (const list<boost::shared_ptr<Processor> >& procs)
3153 {
3154         list<boost::shared_ptr<Processor> >::const_iterator x;
3155
3156         no_processor_redisplay = true;
3157         for (x = procs.begin(); x != procs.end(); ++x) {
3158
3159                 Window* w = get_processor_ui (*x);
3160
3161                 if (w) {
3162                         w->hide ();
3163                 }
3164
3165                 _route->remove_processor(*x);
3166         }
3167
3168         no_processor_redisplay = false;
3169         redisplay_processors ();
3170 }
3171
3172 gint
3173 ProcessorBox::idle_delete_processor (boost::weak_ptr<Processor> weak_processor)
3174 {
3175         boost::shared_ptr<Processor> processor (weak_processor.lock());
3176
3177         if (!processor) {
3178                 return false;
3179         }
3180
3181         /* NOT copied to _mixer.selection() */
3182
3183         no_processor_redisplay = true;
3184         _route->remove_processor (processor);
3185         no_processor_redisplay = false;
3186         redisplay_processors ();
3187
3188         return false;
3189 }
3190
3191 void
3192 ProcessorBox::rename_processor (boost::shared_ptr<Processor> processor)
3193 {
3194         ArdourPrompter name_prompter (true);
3195         string result;
3196         name_prompter.set_title (_("Rename Processor"));
3197         name_prompter.set_prompt (_("New name:"));
3198         name_prompter.set_initial_text (processor->name());
3199         name_prompter.add_button (_("Rename"), Gtk::RESPONSE_ACCEPT);
3200         name_prompter.set_response_sensitive (Gtk::RESPONSE_ACCEPT, false);
3201         name_prompter.show_all ();
3202
3203         switch (name_prompter.run ()) {
3204
3205         case Gtk::RESPONSE_ACCEPT:
3206                 name_prompter.get_result (result);
3207                 if (result.length()) {
3208
3209                        int tries = 0;
3210                        string test = result;
3211
3212                        while (tries < 100) {
3213                                if (_session->io_name_is_legal (test)) {
3214                                        result = test;
3215                                        break;
3216                                }
3217                                tries++;
3218
3219                                test = string_compose ("%1-%2", result, tries);
3220                        }
3221
3222                        if (tries < 100) {
3223                                processor->set_name (result);
3224                        } else {
3225                                /* unlikely! */
3226                                ARDOUR_UI::instance()->popup_error
3227                                        (string_compose (_("At least 100 IO objects exist with a name like %1 - name not changed"), result));
3228                        }
3229                 }
3230                 break;
3231         }
3232
3233         return;
3234 }
3235
3236 void
3237 ProcessorBox::paste_processors ()
3238 {
3239         if (_rr_selection.processors.empty()) {
3240                 return;
3241         }
3242
3243         paste_processor_state (_rr_selection.processors.get_node().children(), boost::shared_ptr<Processor>());
3244 }
3245
3246 void
3247 ProcessorBox::paste_processors (boost::shared_ptr<Processor> before)
3248 {
3249
3250         if (_rr_selection.processors.empty()) {
3251                 return;
3252         }
3253
3254         paste_processor_state (_rr_selection.processors.get_node().children(), before);
3255 }
3256
3257 void
3258 ProcessorBox::paste_processor_state (const XMLNodeList& nlist, boost::shared_ptr<Processor> p)
3259 {
3260         XMLNodeConstIterator niter;
3261         list<boost::shared_ptr<Processor> > copies;
3262
3263         if (nlist.empty()) {
3264                 return;
3265         }
3266
3267         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3268
3269                 XMLProperty const * type = (*niter)->property ("type");
3270                 XMLProperty const * role = (*niter)->property ("role");
3271                 assert (type);
3272
3273                 boost::shared_ptr<Processor> p;
3274                 try {
3275                         if (type->value() == "meter" ||
3276                             type->value() == "main-outs" ||
3277                             type->value() == "amp" ||
3278                             type->value() == "intreturn") {
3279                                 /* do not paste meter, main outs, amp or internal returns */
3280                                 continue;
3281
3282                         } else if (type->value() == "intsend") {
3283
3284                                 /* aux sends are OK, but those used for
3285                                  * other purposes, are not.
3286                                  */
3287
3288                                 assert (role);
3289
3290                                 if (role->value() != "Aux") {
3291                                         continue;
3292                                 }
3293
3294                                 boost::shared_ptr<Pannable> sendpan(new Pannable (*_session));
3295                                 XMLNode n (**niter);
3296                                 InternalSend* s = new InternalSend (*_session, sendpan, _route->mute_master(),
3297                                                 _route, boost::shared_ptr<Route>(), Delivery::Aux);
3298
3299                                 IOProcessor::prepare_for_reset (n, s->name());
3300
3301                                 if (s->set_state (n, Stateful::loading_state_version)) {
3302                                         delete s;
3303                                         return;
3304                                 }
3305
3306                                 p.reset (s);
3307
3308                         } else if (type->value() == "send") {
3309
3310                                 boost::shared_ptr<Pannable> sendpan(new Pannable (*_session));
3311                                 XMLNode n (**niter);
3312
3313                                 Send* s = new Send (*_session, _route->pannable(), _route->mute_master());
3314
3315                                 IOProcessor::prepare_for_reset (n, s->name());
3316
3317                                 if (s->set_state (n, Stateful::loading_state_version)) {
3318                                         delete s;
3319                                         return;
3320                                 }
3321
3322                                 p.reset (s);
3323
3324                         } else if (type->value() == "return") {
3325
3326                                 XMLNode n (**niter);
3327                                 Return* r = new Return (*_session);
3328
3329                                 IOProcessor::prepare_for_reset (n, r->name());
3330
3331                                 if (r->set_state (n, Stateful::loading_state_version)) {
3332                                         delete r;
3333                                         return;
3334                                 }
3335
3336                                 p.reset (r);
3337
3338                         } else if (type->value() == "port") {
3339
3340                                 XMLNode n (**niter);
3341                                 PortInsert* pi = new PortInsert (*_session, _route->pannable (), _route->mute_master ());
3342
3343                                 IOProcessor::prepare_for_reset (n, pi->name());
3344
3345                                 if (pi->set_state (n, Stateful::loading_state_version)) {
3346                                         return;
3347                                 }
3348
3349                                 p.reset (pi);
3350                         } else {
3351                                 /* XXX its a bit limiting to assume that everything else
3352                                    is a plugin.
3353                                 */
3354                                 p.reset (new PluginInsert (*_session));
3355                                 /* we can't use RAII Stateful::ForceIDRegeneration
3356                                  * because that'd void copying the state and wrongly bump
3357                                  * the state-version counter.
3358                                  * we need to load the state (incl external files) first and
3359                                  * only then update the ID)
3360                                  */
3361                                 PBD::ID id = p->id();
3362                                 /* strip side-chain state (processor inside processor must be a side-chain)
3363                                  * otherwise we'll end up with duplicate ports-names.
3364                                  * (this needs a better solution which retains connections)
3365                                  * We really would want Stateful::ForceIDRegeneration here :(
3366                                  */
3367                                 XMLNode state (**niter);
3368                                 state.remove_nodes ("Processor");
3369
3370                                 p->set_state (state, Stateful::current_state_version);
3371                                 boost::dynamic_pointer_cast<PluginInsert>(p)->update_id (id);
3372                         }
3373
3374                         copies.push_back (p);
3375                 }
3376
3377                 catch (...) {
3378                         error << _("plugin insert constructor failed") << endmsg;
3379                 }
3380         }
3381
3382         if (copies.empty()) {
3383                 return;
3384         }
3385
3386         if (_route->add_processors (copies, p)) {
3387
3388                 string msg = _(
3389                         "Copying the set of processors on the clipboard failed,\n\
3390 probably because the I/O configuration of the plugins\n\
3391 could not match the configuration of this track.");
3392                 MessageDialog am (msg);
3393                 am.run ();
3394         }
3395 }
3396
3397 void
3398 ProcessorBox::get_selected_processors (ProcSelection& processors) const
3399 {
3400         const list<ProcessorEntry*> selection = processor_display.selection ();
3401         for (list<ProcessorEntry*>::const_iterator i = selection.begin(); i != selection.end(); ++i) {
3402                 processors.push_back ((*i)->processor ());
3403         }
3404 }
3405
3406 void
3407 ProcessorBox::for_selected_processors (void (ProcessorBox::*method)(boost::shared_ptr<Processor>))
3408 {
3409         list<ProcessorEntry*> selection = processor_display.selection ();
3410         for (list<ProcessorEntry*>::iterator i = selection.begin(); i != selection.end(); ++i) {
3411                 (this->*method) ((*i)->processor ());
3412         }
3413 }
3414
3415 void
3416 ProcessorBox::all_visible_processors_active (bool state)
3417 {
3418         _route->all_visible_processors_active (state);
3419 }
3420
3421 void
3422 ProcessorBox::ab_plugins ()
3423 {
3424         _route->ab_plugins (ab_direction);
3425         ab_direction = !ab_direction;
3426 }
3427
3428
3429 void
3430 ProcessorBox::clear_processors ()
3431 {
3432         string prompt;
3433         vector<string> choices;
3434
3435         prompt = string_compose (_("Do you really want to remove all processors from %1?\n"
3436                                    "(this cannot be undone)"), _route->name());
3437
3438         choices.push_back (_("Cancel"));
3439         choices.push_back (_("Yes, remove them all"));
3440
3441         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
3442
3443         if (prompter.run () == 1) {
3444                 _route->clear_processors (PreFader);
3445                 _route->clear_processors (PostFader);
3446         }
3447 }
3448
3449 void
3450 ProcessorBox::clear_processors (Placement p)
3451 {
3452         string prompt;
3453         vector<string> choices;
3454
3455         if (p == PreFader) {
3456                 prompt = string_compose (_("Do you really want to remove all pre-fader processors from %1?\n"
3457                                            "(this cannot be undone)"), _route->name());
3458         } else {
3459                 prompt = string_compose (_("Do you really want to remove all post-fader processors from %1?\n"
3460                                            "(this cannot be undone)"), _route->name());
3461         }
3462
3463         choices.push_back (_("Cancel"));
3464         choices.push_back (_("Yes, remove them all"));
3465
3466         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
3467
3468         if (prompter.run () == 1) {
3469                 _route->clear_processors (p);
3470         }
3471 }
3472
3473 bool
3474 ProcessorBox::processor_can_be_edited (boost::shared_ptr<Processor> processor)
3475 {
3476         boost::shared_ptr<AudioTrack> at = boost::dynamic_pointer_cast<AudioTrack> (_route);
3477         if (at && at->freeze_state() == AudioTrack::Frozen) {
3478                 return false;
3479         }
3480
3481         if (
3482                 boost::dynamic_pointer_cast<Send> (processor) ||
3483                 boost::dynamic_pointer_cast<Return> (processor) ||
3484                 boost::dynamic_pointer_cast<PluginInsert> (processor) ||
3485                 boost::dynamic_pointer_cast<PortInsert> (processor)
3486                 ) {
3487                 return true;
3488         }
3489
3490         return false;
3491 }
3492
3493 bool
3494 ProcessorBox::one_processor_can_be_edited ()
3495 {
3496         list<ProcessorEntry*> selection = processor_display.selection ();
3497         list<ProcessorEntry*>::iterator i = selection.begin();
3498         while (i != selection.end() && processor_can_be_edited ((*i)->processor()) == false) {
3499                 ++i;
3500         }
3501
3502         return (i != selection.end());
3503 }
3504
3505 Gtk::Window*
3506 ProcessorBox::get_editor_window (boost::shared_ptr<Processor> processor, bool use_custom)
3507 {
3508         boost::shared_ptr<Send> send;
3509         boost::shared_ptr<InternalSend> internal_send;
3510         boost::shared_ptr<Return> retrn;
3511         boost::shared_ptr<PluginInsert> plugin_insert;
3512         boost::shared_ptr<PortInsert> port_insert;
3513         Window* gidget = 0;
3514
3515         /* This method may or may not return a Window, but if it does not it
3516          * will modify the parent mixer strip appearance layout to allow
3517          * "editing" the @param processor that was passed in.
3518          *
3519          * So for example, if the processor is an Amp (gain), the parent strip
3520          * will be forced back into a model where the fader controls the main gain.
3521          * If the processor is a send, then we map the send controls onto the
3522          * strip.
3523          *
3524          * Plugins and others will return a window for control.
3525          */
3526
3527         if (boost::dynamic_pointer_cast<AudioTrack>(_route) != 0) {
3528
3529                 if (boost::dynamic_pointer_cast<AudioTrack> (_route)->freeze_state() == AudioTrack::Frozen) {
3530                         return 0;
3531                 }
3532         }
3533
3534         if (boost::dynamic_pointer_cast<Amp> (processor) && boost::dynamic_pointer_cast<Amp> (processor)->gain_control()->parameter().type() == GainAutomation) {
3535
3536                 if (_parent_strip) {
3537                         _parent_strip->revert_to_default_display ();
3538                 }
3539
3540         } else if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
3541
3542                 if (!_session->engine().connected()) {
3543                         return 0;
3544                 }
3545
3546                 if (boost::dynamic_pointer_cast<InternalSend> (processor) == 0) {
3547
3548                         gidget = new SendUIWindow (send, _session);
3549                 }
3550
3551         } else if ((retrn = boost::dynamic_pointer_cast<Return> (processor)) != 0) {
3552
3553                 if (boost::dynamic_pointer_cast<InternalReturn> (retrn)) {
3554                         /* no GUI for these */
3555                         return 0;
3556                 }
3557
3558                 if (!_session->engine().connected()) {
3559                         return 0;
3560                 }
3561
3562                 boost::shared_ptr<Return> retrn = boost::dynamic_pointer_cast<Return> (processor);
3563
3564                 ReturnUIWindow *return_ui;
3565                 Window* w = get_processor_ui (retrn);
3566
3567                 if (w == 0) {
3568
3569                         return_ui = new ReturnUIWindow (retrn, _session);
3570                         return_ui->set_title (retrn->name ());
3571                         set_processor_ui (send, return_ui);
3572
3573                 } else {
3574                         return_ui = dynamic_cast<ReturnUIWindow *> (w);
3575                 }
3576
3577                 gidget = return_ui;
3578
3579         } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
3580
3581                 PluginUIWindow *plugin_ui;
3582
3583                 /* these are both allowed to be null */
3584
3585                 Window* w = get_processor_ui (plugin_insert);
3586
3587                 if (w == 0) {
3588                         plugin_ui = new PluginUIWindow (plugin_insert, false, use_custom);
3589                         plugin_ui->set_title (generate_processor_title (plugin_insert));
3590                         set_processor_ui (plugin_insert, plugin_ui);
3591
3592                 } else {
3593                         plugin_ui = dynamic_cast<PluginUIWindow *> (w);
3594                 }
3595
3596                 gidget = plugin_ui;
3597
3598         } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (processor)) != 0) {
3599
3600                 if (!_session->engine().connected()) {
3601                         MessageDialog msg ( _("Not connected to audio engine - no I/O changes are possible"));
3602                         msg.run ();
3603                         return 0;
3604                 }
3605
3606                 PortInsertWindow *io_selector;
3607
3608                 Window* w = get_processor_ui (port_insert);
3609
3610                 if (w == 0) {
3611                         io_selector = new PortInsertWindow (_session, port_insert);
3612                         set_processor_ui (port_insert, io_selector);
3613
3614                 } else {
3615                         io_selector = dynamic_cast<PortInsertWindow *> (w);
3616                 }
3617
3618                 gidget = io_selector;
3619         }
3620
3621         return gidget;
3622 }
3623
3624 Gtk::Window*
3625 ProcessorBox::get_generic_editor_window (boost::shared_ptr<Processor> processor)
3626 {
3627         boost::shared_ptr<PluginInsert> plugin_insert
3628                 = boost::dynamic_pointer_cast<PluginInsert>(processor);
3629
3630         if (!plugin_insert) {
3631                 return 0;
3632         }
3633
3634         PluginUIWindow* win = new PluginUIWindow (plugin_insert, true, false);
3635         win->set_title (generate_processor_title (plugin_insert));
3636
3637         return win;
3638 }
3639
3640 void
3641 ProcessorBox::register_actions ()
3642 {
3643         processor_box_actions = myactions.create_action_group (X_("ProcessorMenu"));
3644
3645         Glib::RefPtr<Action> act;
3646
3647         /* new stuff */
3648         myactions.register_action (processor_box_actions, X_("newplugin"), _("New Plugin"),
3649                         sigc::ptr_fun (ProcessorBox::rb_choose_plugin));
3650
3651         act = myactions.register_action (processor_box_actions, X_("newlua"), _("New Lua DSP"),
3652                         sigc::ptr_fun (ProcessorBox::rb_choose_lua));
3653         act = myactions.register_action (processor_box_actions, X_("newinsert"), _("New Insert"),
3654                         sigc::ptr_fun (ProcessorBox::rb_choose_insert));
3655         ActionManager::engine_sensitive_actions.push_back (act);
3656         act = myactions.register_action (processor_box_actions, X_("newsend"), _("New External Send ..."),
3657                         sigc::ptr_fun (ProcessorBox::rb_choose_send));
3658         ActionManager::engine_sensitive_actions.push_back (act);
3659
3660         myactions.register_action (processor_box_actions, X_("newaux"), _("New Aux Send ..."));
3661
3662         myactions.register_action (processor_box_actions, X_("controls"), _("Controls"));
3663         myactions.register_action (processor_box_actions, X_("send_options"), _("Send Options"));
3664
3665         myactions.register_action (processor_box_actions, X_("clear"), _("Clear (all)"),
3666                         sigc::ptr_fun (ProcessorBox::rb_clear));
3667         myactions.register_action (processor_box_actions, X_("clear_pre"), _("Clear (pre-fader)"),
3668                         sigc::ptr_fun (ProcessorBox::rb_clear_pre));
3669         myactions.register_action (processor_box_actions, X_("clear_post"), _("Clear (post-fader)"),
3670                         sigc::ptr_fun (ProcessorBox::rb_clear_post));
3671
3672         /* standard editing stuff */
3673
3674         cut_action = myactions.register_action (processor_box_actions, X_("cut"), _("Cut"),
3675                                                             sigc::ptr_fun (ProcessorBox::rb_cut));
3676         copy_action = myactions.register_action (processor_box_actions, X_("copy"), _("Copy"),
3677                                                              sigc::ptr_fun (ProcessorBox::rb_copy));
3678         delete_action = myactions.register_action (processor_box_actions, X_("delete"), _("Delete"),
3679                                                                sigc::ptr_fun (ProcessorBox::rb_delete));
3680
3681         ActionManager::plugin_selection_sensitive_actions.push_back (cut_action);
3682         ActionManager::plugin_selection_sensitive_actions.push_back (copy_action);
3683         ActionManager::plugin_selection_sensitive_actions.push_back (delete_action);
3684
3685         paste_action = myactions.register_action (processor_box_actions, X_("paste"), _("Paste"),
3686                         sigc::ptr_fun (ProcessorBox::rb_paste));
3687         rename_action = myactions.register_action (processor_box_actions, X_("rename"), _("Rename"),
3688                         sigc::ptr_fun (ProcessorBox::rb_rename));
3689         myactions.register_action (processor_box_actions, X_("selectall"), _("Select All"),
3690                         sigc::ptr_fun (ProcessorBox::rb_select_all));
3691         myactions.register_action (processor_box_actions, X_("deselectall"), _("Deselect All"),
3692                         sigc::ptr_fun (ProcessorBox::rb_deselect_all));
3693
3694         /* activation etc. */
3695
3696         myactions.register_action (processor_box_actions, X_("activate_all"), _("Activate All"),
3697                         sigc::ptr_fun (ProcessorBox::rb_activate_all));
3698         myactions.register_action (processor_box_actions, X_("deactivate_all"), _("Deactivate All"),
3699                         sigc::ptr_fun (ProcessorBox::rb_deactivate_all));
3700         myactions.register_action (processor_box_actions, X_("ab_plugins"), _("A/B Plugins"),
3701                         sigc::ptr_fun (ProcessorBox::rb_ab_plugins));
3702
3703         manage_pins_action = myactions.register_action (
3704                 processor_box_actions, X_("manage-pins"), _("Pin Connections..."),
3705                 sigc::ptr_fun (ProcessorBox::rb_manage_pins));
3706
3707         /* show editors */
3708         edit_action = myactions.register_action (
3709                 processor_box_actions, X_("edit"), _("Edit..."),
3710                 sigc::ptr_fun (ProcessorBox::rb_edit));
3711
3712         edit_generic_action = myactions.register_action (
3713                 processor_box_actions, X_("edit-generic"), _("Edit with generic controls..."),
3714                 sigc::ptr_fun (ProcessorBox::rb_edit_generic));
3715
3716         load_bindings ();
3717 }
3718
3719 void
3720 ProcessorBox::rb_edit_generic ()
3721 {
3722         if (_current_processor_box == 0) {
3723                 return;
3724         }
3725
3726         _current_processor_box->for_selected_processors (&ProcessorBox::generic_edit_processor);
3727 }
3728
3729 void
3730 ProcessorBox::rb_ab_plugins ()
3731 {
3732         if (_current_processor_box == 0) {
3733                 return;
3734         }
3735
3736         _current_processor_box->ab_plugins ();
3737 }
3738
3739 void
3740 ProcessorBox::rb_manage_pins ()
3741 {
3742         if (_current_processor_box == 0) {
3743                 return;
3744         }
3745
3746         _current_processor_box->for_selected_processors (&ProcessorBox::manage_pins);
3747 }
3748 void
3749 ProcessorBox::rb_choose_plugin ()
3750 {
3751         if (_current_processor_box == 0) {
3752                 return;
3753         }
3754         _current_processor_box->choose_plugin ();
3755 }
3756
3757 void
3758 ProcessorBox::rb_choose_lua ()
3759 {
3760         if (_current_processor_box == 0) {
3761                 return;
3762         }
3763         _current_processor_box->choose_lua ();
3764 }
3765
3766 void
3767 ProcessorBox::rb_choose_insert ()
3768 {
3769         if (_current_processor_box == 0) {
3770                 return;
3771         }
3772         _current_processor_box->choose_insert ();
3773 }
3774
3775 void
3776 ProcessorBox::rb_choose_send ()
3777 {
3778         if (_current_processor_box == 0) {
3779                 return;
3780         }
3781         _current_processor_box->choose_send ();
3782 }
3783
3784 void
3785 ProcessorBox::rb_choose_aux (boost::weak_ptr<Route> wr)
3786 {
3787         if (_current_processor_box == 0) {
3788                 return;
3789         }
3790
3791         _current_processor_box->choose_aux (wr);
3792 }
3793
3794 void
3795 ProcessorBox::rb_clear ()
3796 {
3797         if (_current_processor_box == 0) {
3798                 return;
3799         }
3800
3801         _current_processor_box->clear_processors ();
3802 }
3803
3804
3805 void
3806 ProcessorBox::rb_clear_pre ()
3807 {
3808         if (_current_processor_box == 0) {
3809                 return;
3810         }
3811
3812         _current_processor_box->clear_processors (PreFader);
3813 }
3814
3815
3816 void
3817 ProcessorBox::rb_clear_post ()
3818 {
3819         if (_current_processor_box == 0) {
3820                 return;
3821         }
3822
3823         _current_processor_box->clear_processors (PostFader);
3824 }
3825
3826 void
3827 ProcessorBox::rb_cut ()
3828 {
3829         if (_current_processor_box == 0) {
3830                 return;
3831         }
3832
3833         _current_processor_box->processor_operation (ProcessorsCut);
3834 }
3835
3836 void
3837 ProcessorBox::rb_delete ()
3838 {
3839         if (_current_processor_box == 0) {
3840                 return;
3841         }
3842
3843         _current_processor_box->processor_operation (ProcessorsDelete);
3844 }
3845
3846 void
3847 ProcessorBox::rb_copy ()
3848 {
3849         if (_current_processor_box == 0) {
3850                 return;
3851         }
3852         _current_processor_box->processor_operation (ProcessorsCopy);
3853 }
3854
3855 void
3856 ProcessorBox::rb_paste ()
3857 {
3858         if (_current_processor_box == 0) {
3859                 return;
3860         }
3861
3862         _current_processor_box->processor_operation (ProcessorsPaste);
3863 }
3864
3865 void
3866 ProcessorBox::rb_rename ()
3867 {
3868         if (_current_processor_box == 0) {
3869                 return;
3870         }
3871         _current_processor_box->rename_processors ();
3872 }
3873
3874 void
3875 ProcessorBox::rb_select_all ()
3876 {
3877         if (_current_processor_box == 0) {
3878                 return;
3879         }
3880
3881         _current_processor_box->processor_operation (ProcessorsSelectAll);
3882 }
3883
3884 void
3885 ProcessorBox::rb_deselect_all ()
3886 {
3887         if (_current_processor_box == 0) {
3888                 return;
3889         }
3890
3891         _current_processor_box->deselect_all_processors ();
3892 }
3893
3894 void
3895 ProcessorBox::rb_activate_all ()
3896 {
3897         if (_current_processor_box == 0) {
3898                 return;
3899         }
3900
3901         _current_processor_box->all_visible_processors_active (true);
3902 }
3903
3904 void
3905 ProcessorBox::rb_deactivate_all ()
3906 {
3907         if (_current_processor_box == 0) {
3908                 return;
3909         }
3910         _current_processor_box->all_visible_processors_active (false);
3911 }
3912
3913 void
3914 ProcessorBox::rb_edit ()
3915 {
3916         if (_current_processor_box == 0) {
3917                 return;
3918         }
3919
3920         _current_processor_box->for_selected_processors (&ProcessorBox::edit_processor);
3921 }
3922
3923 bool
3924 ProcessorBox::edit_aux_send (boost::shared_ptr<Processor> processor)
3925 {
3926         if (boost::dynamic_pointer_cast<InternalSend> (processor) == 0) {
3927                 return false;
3928         }
3929
3930         if (_parent_strip) {
3931                 boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
3932                 if (_parent_strip->current_delivery() == send) {
3933                         _parent_strip->revert_to_default_display ();
3934                 } else {
3935                         _parent_strip->show_send(send);
3936                 }
3937         }
3938         return true;
3939 }
3940
3941 void
3942 ProcessorBox::edit_processor (boost::shared_ptr<Processor> processor)
3943 {
3944         if (!processor) {
3945                 return;
3946         }
3947         if (edit_aux_send (processor)) {
3948                 return;
3949         }
3950
3951         ProcessorWindowProxy* proxy = find_window_proxy (processor);
3952
3953         if (proxy) {
3954                 proxy->set_custom_ui_mode (true);
3955                 proxy->show_the_right_window ();
3956         }
3957 }
3958
3959 void
3960 ProcessorBox::generic_edit_processor (boost::shared_ptr<Processor> processor)
3961 {
3962         if (!processor) {
3963                 return;
3964         }
3965         if (edit_aux_send (processor)) {
3966                 return;
3967         }
3968
3969         ProcessorWindowProxy* proxy = find_window_proxy (processor);
3970
3971         if (proxy) {
3972                 proxy->set_custom_ui_mode (false);
3973                 proxy->show_the_right_window ();
3974         }
3975 }
3976
3977 void
3978 ProcessorBox::manage_pins (boost::shared_ptr<Processor> processor)
3979 {
3980         if (!processor) {
3981                 return;
3982         }
3983         PluginPinWindowProxy* proxy = processor->pinmgr_proxy ();
3984         if (proxy) {
3985                 proxy->get (true);
3986                 proxy->present();
3987         }
3988 }
3989
3990
3991 void
3992 ProcessorBox::route_property_changed (const PropertyChange& what_changed)
3993 {
3994         if (!what_changed.contains (ARDOUR::Properties::name)) {
3995                 return;
3996         }
3997
3998         ENSURE_GUI_THREAD (*this, &ProcessorBox::route_property_changed, what_changed);
3999
4000         boost::shared_ptr<Processor> processor;
4001         boost::shared_ptr<PluginInsert> plugin_insert;
4002         boost::shared_ptr<Send> send;
4003
4004         list<ProcessorEntry*> children = processor_display.children();
4005
4006         for (list<ProcessorEntry*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
4007
4008                 processor = (*iter)->processor ();
4009
4010                 if (!processor) {
4011                         continue;
4012                 }
4013
4014                 Window* w = get_processor_ui (processor);
4015
4016                 if (!w) {
4017                         continue;
4018                 }
4019
4020                 /* rename editor windows for sends and plugins */
4021
4022                 if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
4023                         w->set_title (send->name ());
4024                 } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
4025                         w->set_title (generate_processor_title (plugin_insert));
4026                 }
4027         }
4028 }
4029
4030 string
4031 ProcessorBox::generate_processor_title (boost::shared_ptr<PluginInsert> pi)
4032 {
4033         string maker = pi->plugin()->maker() ? pi->plugin()->maker() : "";
4034         string::size_type email_pos;
4035
4036         if ((email_pos = maker.find_first_of ('<')) != string::npos) {
4037                 maker = maker.substr (0, email_pos - 1);
4038         }
4039
4040         if (maker.length() > 32) {
4041                 maker = maker.substr (0, 32);
4042                 maker += " ...";
4043         }
4044
4045         SessionObject* owner = pi->owner();
4046
4047         if (owner) {
4048                 return string_compose(_("%1: %2 (by %3)"), owner->name(), pi->name(), maker);
4049         } else {
4050                 return string_compose(_("%1 (by %2)"), pi->name(), maker);
4051         }
4052 }
4053
4054 /** @param p Processor.
4055  *  @return the UI window for \a p.
4056  */
4057 Window *
4058 ProcessorBox::get_processor_ui (boost::shared_ptr<Processor> p) const
4059 {
4060         ProcessorWindowProxy* wp = p->window_proxy();
4061         if (wp) {
4062                 return wp->get ();
4063         }
4064         return 0;
4065 }
4066
4067 /** Make a note of the UI window that a processor is using.
4068  *  @param p Processor.
4069  *  @param w UI window.
4070  */
4071 void
4072 ProcessorBox::set_processor_ui (boost::shared_ptr<Processor> p, Gtk::Window* w)
4073 {
4074         assert (p->window_proxy());
4075         p->set_ui (w);
4076         p->window_proxy()->use_window (*w);
4077 }
4078
4079 void
4080 ProcessorBox::mixer_strip_delivery_changed (boost::weak_ptr<Delivery> w)
4081 {
4082         boost::shared_ptr<Delivery> d = w.lock ();
4083         if (!d) {
4084                 return;
4085         }
4086
4087         list<ProcessorEntry*> children = processor_display.children ();
4088         list<ProcessorEntry*>::const_iterator i = children.begin();
4089         while (i != children.end() && (*i)->processor() != d) {
4090                 ++i;
4091         }
4092
4093         if (i == children.end()) {
4094                 processor_display.set_active (0);
4095         } else {
4096                 processor_display.set_active (*i);
4097         }
4098 }
4099
4100 /** Called to repair the damage of Editor::show_window doing a show_all() */
4101 void
4102 ProcessorBox::hide_things ()
4103 {
4104         list<ProcessorEntry*> c = processor_display.children ();
4105         for (list<ProcessorEntry*>::iterator i = c.begin(); i != c.end(); ++i) {
4106                 (*i)->hide_things ();
4107         }
4108 }
4109
4110 void
4111 ProcessorBox::processor_menu_unmapped ()
4112 {
4113         processor_display.remove_placeholder ();
4114         /* make all possibly-desensitized actions sensitive again so that
4115            they be activated by other means (e.g. bindings)
4116         */
4117         ActionManager::set_sensitive (ActionManager::plugin_selection_sensitive_actions, true);
4118 }
4119
4120 XMLNode *
4121 ProcessorBox::entry_gui_object_state (ProcessorEntry* entry)
4122 {
4123         if (!_parent_strip) {
4124                 return 0;
4125         }
4126
4127         GUIObjectState& st = _parent_strip->gui_object_state ();
4128
4129         XMLNode* strip = st.get_or_add_node (_parent_strip->state_id ());
4130         assert (strip);
4131         return st.get_or_add_node (strip, entry->state_id());
4132 }
4133
4134 void
4135 ProcessorBox::update_gui_object_state (ProcessorEntry* entry)
4136 {
4137         XMLNode* proc = entry_gui_object_state (entry);
4138         if (!proc) {
4139                 return;
4140         }
4141
4142         /* XXX: this is a bit inefficient; we just remove all child nodes and re-add them */
4143         proc->remove_nodes_and_delete (X_("Object"));
4144         entry->add_control_state (proc);
4145 }
4146
4147 bool
4148 ProcessorBox::is_editor_mixer_strip() const
4149 {
4150         return _parent_strip && !_parent_strip->mixer_owned();
4151 }
4152
4153 ProcessorWindowProxy::ProcessorWindowProxy (string const & name, ProcessorBox* box, boost::weak_ptr<Processor> processor)
4154         : WM::ProxyBase (name, string())
4155         , _processor_box (box)
4156         , _processor (processor)
4157         , is_custom (false)
4158         , want_custom (false)
4159 {
4160         boost::shared_ptr<Processor> p = _processor.lock ();
4161         if (!p) {
4162                 return;
4163         }
4164         p->DropReferences.connect (going_away_connection, MISSING_INVALIDATOR, boost::bind (&ProcessorWindowProxy::processor_going_away, this), gui_context());
4165 }
4166
4167 ProcessorWindowProxy::~ProcessorWindowProxy()
4168 {
4169         /* processor window proxies do not own the windows they create with
4170          * ::get(), so set _window to null before the normal WindowProxy method
4171          * deletes it.
4172          */
4173         _window = 0;
4174 }
4175
4176 void
4177 ProcessorWindowProxy::processor_going_away ()
4178 {
4179         delete _window;
4180         _window = 0;
4181         WM::Manager::instance().remove (this);
4182         /* should be no real reason to do this, since the object that would
4183            send DropReferences is about to be deleted, but lets do it anyway.
4184         */
4185         going_away_connection.disconnect();
4186 }
4187
4188 ARDOUR::SessionHandlePtr*
4189 ProcessorWindowProxy::session_handle()
4190 {
4191         /* we don't care */
4192         return 0;
4193 }
4194
4195 XMLNode&
4196 ProcessorWindowProxy::get_state ()
4197 {
4198         XMLNode *node;
4199         node = &ProxyBase::get_state();
4200         node->add_property (X_("custom-ui"), is_custom? X_("yes") : X_("no"));
4201         return *node;
4202 }
4203
4204 int
4205 ProcessorWindowProxy::set_state (const XMLNode& node, int /*version*/)
4206 {
4207         XMLNodeList children = node.children ();
4208         XMLNodeList::const_iterator i = children.begin ();
4209         while (i != children.end()) {
4210                 XMLProperty* prop = (*i)->property (X_("name"));
4211                 if ((*i)->name() == X_("Window") && prop && prop->value() == _name) {
4212                         break;
4213                 }
4214                 ++i;
4215         }
4216
4217         if (i != children.end()) {
4218                 XMLProperty* prop;
4219                 if ((prop = (*i)->property (X_("custom-ui"))) != 0) {
4220                         want_custom = PBD::string_is_affirmative (prop->value ());
4221                 }
4222         }
4223
4224         return ProxyBase::set_state (node, 0);
4225 }
4226
4227 Gtk::Window*
4228 ProcessorWindowProxy::get (bool create)
4229 {
4230         boost::shared_ptr<Processor> p = _processor.lock ();
4231
4232         if (!p) {
4233                 return 0;
4234         }
4235         if (_window && (is_custom != want_custom)) {
4236                 /* drop existing window - wrong type */
4237                 drop_window ();
4238         }
4239
4240         if (!_window) {
4241                 if (!create) {
4242                         return 0;
4243                 }
4244
4245                 is_custom = want_custom;
4246                 _window = _processor_box->get_editor_window (p, is_custom);
4247
4248                 if (_window) {
4249                         setup ();
4250                 }
4251         }
4252         _window->show_all ();
4253         return _window;
4254 }
4255
4256 void
4257 ProcessorWindowProxy::show_the_right_window ()
4258 {
4259         if (_window && (is_custom != want_custom)) {
4260                 /* drop existing window - wrong type */
4261                 drop_window ();
4262                 get (true);
4263                 setup ();
4264                 assert (_window);
4265                 is_custom = want_custom;
4266         }
4267
4268         toggle ();
4269 }
4270
4271
4272 PluginPinWindowProxy::PluginPinWindowProxy(std::string const &name, boost::weak_ptr<ARDOUR::Processor> processor)
4273         : WM::ProxyBase (name, string())
4274         , _processor (processor)
4275 {
4276         boost::shared_ptr<Processor> p = _processor.lock ();
4277         if (!p) {
4278                 return;
4279         }
4280         p->DropReferences.connect (going_away_connection, MISSING_INVALIDATOR, boost::bind (&PluginPinWindowProxy::processor_going_away, this), gui_context());
4281 }
4282
4283 PluginPinWindowProxy::~PluginPinWindowProxy()
4284 {
4285         _window = 0;
4286 }
4287
4288 ARDOUR::SessionHandlePtr*
4289 PluginPinWindowProxy::session_handle ()
4290 {
4291         ArdourWindow* aw = dynamic_cast<ArdourWindow*> (_window);
4292         if (aw) { return aw; }
4293         return 0;
4294 }
4295
4296 Gtk::Window*
4297 PluginPinWindowProxy::get (bool create)
4298 {
4299         boost::shared_ptr<Processor> p = _processor.lock ();
4300         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (p);
4301         if (!p || !pi) {
4302                 return 0;
4303         }
4304
4305         if (!_window) {
4306                 if (!create) {
4307                         return 0;
4308                 }
4309                 _window = new PluginPinDialog (pi);
4310                 ArdourWindow* aw = dynamic_cast<ArdourWindow*> (_window);
4311                 if (aw) {
4312                         aw->set_session (_session);
4313                 }
4314         }
4315
4316         _window->show_all ();
4317         return _window;
4318 }
4319
4320 void
4321 PluginPinWindowProxy::processor_going_away ()
4322 {
4323         delete _window;
4324         _window = 0;
4325         WM::Manager::instance().remove (this);
4326         going_away_connection.disconnect();
4327 }
4328
4329 void
4330 ProcessorBox::load_bindings ()
4331 {
4332         bindings = Bindings::get_bindings (X_("Processor Box"), myactions);
4333 }