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