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