more changes to Bindings, Keyboard APIs
[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
32 #include <glibmm/miscutils.h>
33
34 #include <gtkmm/messagedialog.h>
35
36 #include <gtkmm2ext/gtk_ui.h>
37 #include <gtkmm2ext/utils.h>
38 #include <gtkmm2ext/choice.h>
39 #include <gtkmm2ext/utils.h>
40 #include <gtkmm2ext/doi.h>
41 #include <gtkmm2ext/rgb_macros.h>
42
43 #include "ardour/amp.h"
44 #include "ardour/audio_track.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/internal_return.h"
47 #include "ardour/internal_send.h"
48 #include "ardour/meter.h"
49 #include "ardour/panner_shell.h"
50 #include "ardour/plugin_insert.h"
51 #include "ardour/pannable.h"
52 #include "ardour/port_insert.h"
53 #include "ardour/profile.h"
54 #include "ardour/return.h"
55 #include "ardour/route.h"
56 #include "ardour/send.h"
57 #include "ardour/session.h"
58 #include "ardour/types.h"
59
60 #include "actions.h"
61 #include "ardour_dialog.h"
62 #include "ardour_ui.h"
63 #include "gui_thread.h"
64 #include "io_selector.h"
65 #include "keyboard.h"
66 #include "mixer_ui.h"
67 #include "mixer_strip.h"
68 #include "plugin_selector.h"
69 #include "plugin_ui.h"
70 #include "port_insert_ui.h"
71 #include "processor_box.h"
72 #include "public_editor.h"
73 #include "return_ui.h"
74 #include "route_processor_selection.h"
75 #include "send_ui.h"
76 #include "timers.h"
77 #include "tooltips.h"
78 #include "new_plugin_preset_dialog.h"
79
80 #include "i18n.h"
81
82 #ifdef AUDIOUNIT_SUPPORT
83 class AUPluginUI;
84 #endif
85
86 #ifndef NDEBUG
87 bool ProcessorBox::show_all_processors = false;
88 #endif
89
90 using namespace std;
91 using namespace ARDOUR;
92 using namespace PBD;
93 using namespace Gtk;
94 using namespace Glib;
95 using namespace Gtkmm2ext;
96
97 ProcessorBox*  ProcessorBox::_current_processor_box = 0;
98 RefPtr<Action> ProcessorBox::paste_action;
99 RefPtr<Action> ProcessorBox::cut_action;
100 RefPtr<Action> ProcessorBox::copy_action;
101 RefPtr<Action> ProcessorBox::rename_action;
102 RefPtr<Action> ProcessorBox::delete_action;
103 RefPtr<Action> ProcessorBox::edit_action;
104 RefPtr<Action> ProcessorBox::edit_generic_action;
105 ActionMap      ProcessorBox::processor_box_actions;
106
107 static const uint32_t audio_port_color = 0x4A8A0EFF; // Green
108 static const uint32_t midi_port_color = 0x960909FF; //Red
109
110 ProcessorEntry::ProcessorEntry (ProcessorBox* parent, boost::shared_ptr<Processor> p, Width w)
111         : _button (ArdourButton::led_default_elements)
112         , _position (PreFader)
113         , _position_num(0)
114         , _selectable(true)
115         , _unknown_processor(false)
116         , _parent (parent)
117         , _processor (p)
118         , _width (w)
119         , _input_icon(true)
120         , _output_icon(false)
121 {
122         _vbox.show ();
123
124         _button.set_distinct_led_click (true);
125         _button.set_fallthrough_to_parent(true);
126         _button.set_led_left (true);
127         _button.signal_led_clicked.connect (sigc::mem_fun (*this, &ProcessorEntry::led_clicked));
128         _button.set_text (name (_width));
129
130         if (boost::dynamic_pointer_cast<PeakMeter> (_processor)) {
131                 _button.set_elements(ArdourButton::Element(_button.elements() & ~ArdourButton::Indicator));
132         }
133         if (boost::dynamic_pointer_cast<UnknownProcessor> (_processor)) {
134                 _button.set_elements(ArdourButton::Element(_button.elements() & ~ArdourButton::Indicator));
135                 _unknown_processor = true;
136         }
137         {
138                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
139                 if (pi && pi->plugin()) {
140                         _plugin_preset_pointer = PluginPresetPtr (new PluginPreset (pi->plugin()->get_info()));
141                 }
142         }
143         if (_processor) {
144
145                 _vbox.pack_start (_routing_icon);
146                 _vbox.pack_start (_input_icon);
147                 _vbox.pack_start (_button, true, true);
148                 _vbox.pack_end (_output_icon);
149
150                 _button.set_active (_processor->active());
151
152                 _routing_icon.set_no_show_all(true);
153                 _input_icon.set_no_show_all(true);
154
155                 _button.show ();
156                 _routing_icon.set_visible(false);
157                 _input_icon.hide();
158                 _output_icon.show();
159
160                 _processor->ActiveChanged.connect (active_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_active_changed, this), gui_context());
161                 _processor->PropertyChanged.connect (name_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_property_changed, this, _1), gui_context());
162                 _processor->ConfigurationChanged.connect (config_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_configuration_changed, this, _1, _2), gui_context());
163
164                 set<Evoral::Parameter> p = _processor->what_can_be_automated ();
165                 for (set<Evoral::Parameter>::iterator i = p.begin(); i != p.end(); ++i) {
166
167                         std::string label = _processor->describe_parameter (*i);
168
169                         if (boost::dynamic_pointer_cast<Send> (_processor)) {
170                                 label = _("Send");
171                         } else if (boost::dynamic_pointer_cast<Return> (_processor)) {
172                                 label = _("Return");
173                         }
174
175                         Control* c = new Control (_processor->automation_control (*i), label);
176
177                         _controls.push_back (c);
178
179                         if (boost::dynamic_pointer_cast<Amp> (_processor) == 0) {
180                                 /* Add non-Amp (Fader & Trim) controls to the processor box */
181                                 _vbox.pack_start (c->box);
182                         }
183                 }
184
185                 _input_icon.set_ports(_processor->input_streams());
186                 _output_icon.set_ports(_processor->output_streams());
187
188                 _routing_icon.set_sources(_processor->input_streams());
189                 _routing_icon.set_sinks(_processor->output_streams());
190
191                 setup_tooltip ();
192                 setup_visuals ();
193         } else {
194                 _vbox.set_size_request (-1, _button.size_request().height);
195         }
196 }
197
198 ProcessorEntry::~ProcessorEntry ()
199 {
200         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
201                 delete *i;
202         }
203 }
204
205 EventBox&
206 ProcessorEntry::action_widget ()
207 {
208         return _button;
209 }
210
211 Gtk::Widget&
212 ProcessorEntry::widget ()
213 {
214         return _vbox;
215 }
216
217 string
218 ProcessorEntry::drag_text () const
219 {
220         return name (Wide);
221 }
222 bool
223 ProcessorEntry::drag_data_get (Glib::RefPtr<Gdk::DragContext> const, Gtk::SelectionData &data)
224 {
225         if (data.get_target() == "PluginPresetPtr") {
226                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
227
228                 if (!_plugin_preset_pointer || !pi) {
229                         data.set (data.get_target(), 8, NULL, 0);
230                         return true;
231                 }
232
233                 boost::shared_ptr<ARDOUR::Plugin> plugin = pi->plugin();
234                 assert (plugin);
235
236                 PluginManager& manager (PluginManager::instance());
237                 bool fav = manager.get_status (_plugin_preset_pointer->_pip) == PluginManager::Favorite;
238
239                 NewPluginPresetDialog d (plugin,
240                                 string_compose(_("New Favorite Preset for \"%1\""),_plugin_preset_pointer->_pip->name), !fav);
241
242                 _plugin_preset_pointer->_preset.valid = false;
243
244                 switch (d.run ()) {
245                         case Gtk::RESPONSE_CANCEL:
246                                 data.set (data.get_target(), 8, NULL, 0);
247                                 return true;
248                                 break;
249
250                         case Gtk::RESPONSE_NO:
251                                 break;
252
253                         case Gtk::RESPONSE_ACCEPT:
254                                 if (d.name().empty()) {
255                                         break;
256                                 }
257
258                                 if (d.replace ()) {
259                                         plugin->remove_preset (d.name ());
260                                 }
261
262                                 Plugin::PresetRecord const r = plugin->save_preset (d.name());
263
264                                 if (!r.uri.empty ()) {
265                                         _plugin_preset_pointer->_preset.uri   = r.uri;
266                                         _plugin_preset_pointer->_preset.label = r.label;
267                                         _plugin_preset_pointer->_preset.user  = r.user;
268                                         _plugin_preset_pointer->_preset.valid = r.valid;
269                                 }
270                 }
271                 data.set (data.get_target(), 8, (const guchar *) &_plugin_preset_pointer, sizeof (PluginPresetPtr));
272                 return true;
273         }
274         return false;
275 }
276
277 void
278 ProcessorEntry::set_position (Position p, uint32_t num)
279 {
280         _position = p;
281         _position_num = num;
282
283         if (_position_num == 0 || _routing_icon.get_visible()) {
284                 _input_icon.show();
285         } else {
286                 _input_icon.hide();
287         }
288
289         setup_visuals ();
290 }
291
292 void
293 ProcessorEntry::set_visual_state (Gtkmm2ext::VisualState s, bool yn)
294 {
295         if (yn) {
296                 _button.set_visual_state (Gtkmm2ext::VisualState (_button.visual_state() | s));
297         } else {
298                 _button.set_visual_state (Gtkmm2ext::VisualState (_button.visual_state() & ~s));
299         }
300 }
301
302 void
303 ProcessorEntry::setup_visuals ()
304 {
305         if (_unknown_processor) {
306                 _button.set_name ("processor stub");
307                 return;
308         }
309
310         switch (_position) {
311         case PreFader:
312                 _button.set_name ("processor prefader");
313                 break;
314
315         case Fader:
316                 _button.set_name ("processor fader");
317                 break;
318
319         case PostFader:
320                 _button.set_name ("processor postfader");
321                 break;
322         }
323 }
324
325
326 boost::shared_ptr<Processor>
327 ProcessorEntry::processor () const
328 {
329         return _processor;
330 }
331
332 void
333 ProcessorEntry::set_enum_width (Width w)
334 {
335         _width = w;
336         _button.set_text (name (_width));
337 }
338
339 void
340 ProcessorEntry::led_clicked(GdkEventButton *ev)
341 {
342         bool ctrl_shift_pressed = false;
343         Keyboard::ModifierMask ctrl_shift_mask = Keyboard::ModifierMask (Keyboard::PrimaryModifier|Keyboard::TertiaryModifier);
344
345         if (Keyboard::modifier_state_equals (ev->state, ctrl_shift_mask)) {
346                 ctrl_shift_pressed = true;
347         }
348
349         if (_processor) {
350                 if (_button.get_active ()) {
351                         if (ctrl_shift_pressed) {
352                                 _parent->all_visible_processors_active(false);
353
354                                 if (_position == Fader) {
355                                         _processor->deactivate ();
356                                 }
357                         }
358                         else {
359                                 _processor->deactivate ();
360                         }
361
362                 } else {
363                         if (ctrl_shift_pressed) {
364                                 _parent->all_visible_processors_active(true);
365
366                                 if (_position == Fader) {
367                                         _processor->activate ();
368                                 }
369                         }
370                         else {
371                                 _processor->activate ();
372                         }
373                 }
374         }
375 }
376
377 void
378 ProcessorEntry::processor_active_changed ()
379 {
380         if (_processor) {
381                 _button.set_active (_processor->active());
382         }
383 }
384
385 void
386 ProcessorEntry::processor_property_changed (const PropertyChange& what_changed)
387 {
388         if (what_changed.contains (ARDOUR::Properties::name)) {
389                 _button.set_text (name (_width));
390                 setup_tooltip ();
391         }
392 }
393
394 void
395 ProcessorEntry::processor_configuration_changed (const ChanCount in, const ChanCount out)
396 {
397         _input_icon.set_ports(in);
398         _output_icon.set_ports(out);
399         _routing_icon.set_sources(in);
400         _routing_icon.set_sinks(out);
401         _input_icon.queue_draw();
402         _output_icon.queue_draw();
403         _routing_icon.queue_draw();
404 }
405
406 void
407 ProcessorEntry::setup_tooltip ()
408 {
409         if (_processor) {
410                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (_processor);
411                 if (pi) {
412                         std::string postfix = "";
413                         uint32_t replicated;
414                         if ((replicated = pi->get_count()) > 1) {
415                                 postfix = string_compose(_("\nThis mono plugin has been replicated %1 times."), replicated);
416                         }
417                         if (pi->plugin()->has_editor()) {
418                                 ARDOUR_UI_UTILS::set_tooltip (_button,
419                                                 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));
420                         } else {
421                                 ARDOUR_UI_UTILS::set_tooltip (_button,
422                                                 string_compose (_("<b>%1</b>\nDouble-click to show generic GUI.%2"), name (Wide), postfix));
423                         }
424                         return;
425                 }
426                 if(boost::dynamic_pointer_cast<UnknownProcessor> (_processor)) {
427                         ARDOUR_UI::instance()->set_tip (_button,
428                                         string_compose (_("<b>%1</b>\nThe Plugin is not available on this system\nand has been replaced by a stub."), name (Wide)));
429                         return;
430                 }
431         }
432         ARDOUR_UI_UTILS::set_tooltip (_button, string_compose ("<b>%1</b>", name (Wide)));
433 }
434
435 string
436 ProcessorEntry::name (Width w) const
437 {
438         boost::shared_ptr<Send> send;
439         string name_display;
440
441         if (!_processor) {
442                 return string();
443         }
444
445         if ((send = boost::dynamic_pointer_cast<Send> (_processor)) != 0 &&
446             !boost::dynamic_pointer_cast<InternalSend>(_processor)) {
447
448                 name_display += '>';
449
450                 /* grab the send name out of its overall name */
451
452                 string::size_type lbracket, rbracket;
453                 lbracket = send->name().find ('[');
454                 rbracket = send->name().find (']');
455
456                 switch (w) {
457                 case Wide:
458                         name_display += send->name().substr (lbracket+1, lbracket-rbracket-1);
459                         break;
460                 case Narrow:
461                         name_display += PBD::short_version (send->name().substr (lbracket+1, lbracket-rbracket-1), 4);
462                         break;
463                 }
464
465         } else {
466                 boost::shared_ptr<ARDOUR::PluginInsert> pi;
467                 uint32_t replicated;
468                 if ((pi = boost::dynamic_pointer_cast<ARDOUR::PluginInsert> (_processor)) != 0
469                                 && (replicated = pi->get_count()) > 1)
470                 {
471                         name_display += string_compose(_("(%1x1) "), replicated);
472                 }
473
474                 switch (w) {
475                 case Wide:
476                         name_display += _processor->display_name();
477                         break;
478                 case Narrow:
479                         name_display += PBD::short_version (_processor->display_name(), 5);
480                         break;
481                 }
482
483         }
484
485         return name_display;
486 }
487
488 void
489 ProcessorEntry::show_all_controls ()
490 {
491         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
492                 (*i)->set_visible (true);
493         }
494
495         _parent->update_gui_object_state (this);
496 }
497
498 void
499 ProcessorEntry::hide_all_controls ()
500 {
501         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
502                 (*i)->set_visible (false);
503         }
504
505         _parent->update_gui_object_state (this);
506 }
507
508 void
509 ProcessorEntry::add_control_state (XMLNode* node) const
510 {
511         for (list<Control*>::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
512                 (*i)->add_state (node);
513         }
514 }
515
516 void
517 ProcessorEntry::set_control_state (XMLNode const * node)
518 {
519         for (list<Control*>::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
520                 (*i)->set_state (node);
521         }
522 }
523
524 string
525 ProcessorEntry::state_id () const
526 {
527         return string_compose ("processor %1", _processor->id().to_s());
528 }
529
530 void
531 ProcessorEntry::hide_things ()
532 {
533         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
534                 (*i)->hide_things ();
535         }
536 }
537
538
539 Menu *
540 ProcessorEntry::build_controls_menu ()
541 {
542         using namespace Menu_Helpers;
543         Menu* menu = manage (new Menu);
544         MenuList& items = menu->items ();
545
546         items.push_back (
547                 MenuElem (_("Show All Controls"), sigc::mem_fun (*this, &ProcessorEntry::show_all_controls))
548                 );
549
550         items.push_back (
551                 MenuElem (_("Hide All Controls"), sigc::mem_fun (*this, &ProcessorEntry::hide_all_controls))
552                 );
553
554         if (!_controls.empty ()) {
555                 items.push_back (SeparatorElem ());
556         }
557
558         for (list<Control*>::iterator i = _controls.begin(); i != _controls.end(); ++i) {
559                 items.push_back (CheckMenuElem ((*i)->name ()));
560                 Gtk::CheckMenuItem* c = dynamic_cast<Gtk::CheckMenuItem*> (&items.back ());
561                 c->set_active ((*i)->visible ());
562                 c->signal_toggled().connect (sigc::bind (sigc::mem_fun (*this, &ProcessorEntry::toggle_control_visibility), *i));
563         }
564
565         return menu;
566 }
567
568 void
569 ProcessorEntry::toggle_control_visibility (Control* c)
570 {
571         c->set_visible (!c->visible ());
572         _parent->update_gui_object_state (this);
573 }
574
575 Menu *
576 ProcessorEntry::build_send_options_menu ()
577 {
578         using namespace Menu_Helpers;
579         Menu* menu = manage (new Menu);
580         MenuList& items = menu->items ();
581
582         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (_processor);
583         if (send) {
584
585                 items.push_back (CheckMenuElem (_("Link panner controls")));
586                 Gtk::CheckMenuItem* c = dynamic_cast<Gtk::CheckMenuItem*> (&items.back ());
587                 c->set_active (send->panner_shell()->is_linked_to_route());
588                 c->signal_toggled().connect (sigc::mem_fun (*this, &ProcessorEntry::toggle_panner_link));
589
590         }
591         return menu;
592 }
593
594 void
595 ProcessorEntry::toggle_panner_link ()
596 {
597         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (_processor);
598         if (send) {
599                 send->panner_shell()->set_linked_to_route(!send->panner_shell()->is_linked_to_route());
600         }
601 }
602
603 ProcessorEntry::Control::Control (boost::shared_ptr<AutomationControl> c, string const & n)
604         : _control (c)
605         , _adjustment (gain_to_slider_position_with_max (1.0, Config->get_max_gain()), 0, 1, 0.01, 0.1)
606         , _slider (&_adjustment, boost::shared_ptr<PBD::Controllable>(), 0, max(13.f, rintf(13.f * UIConfiguration::instance().get_ui_scale())))
607         , _slider_persistant_tooltip (&_slider)
608         , _button (ArdourButton::led_default_elements)
609         , _ignore_ui_adjustment (false)
610         , _visible (false)
611         , _name (n)
612 {
613         _slider.set_controllable (c);
614         box.set_padding(0, 0, 4, 4);
615
616         if (c->toggled()) {
617                 _button.set_text (_name);
618                 _button.set_led_left (true);
619                 _button.set_name ("processor control button");
620                 box.add (_button);
621                 _button.show ();
622
623                 _button.signal_clicked.connect (sigc::mem_fun (*this, &Control::button_clicked));
624                 _button.signal_led_clicked.connect (sigc::mem_fun (*this, &Control::button_clicked_event));
625                 // dup. currently timers are used :(
626                 //c->Changed.connect (_connection, MISSING_INVALIDATOR, boost::bind (&Control::control_changed, this), gui_context ());
627
628         } else {
629
630                 _slider.set_name ("ProcessorControlSlider");
631                 _slider.set_text (_name);
632
633                 box.add (_slider);
634                 _slider.show ();
635
636                 const ARDOUR::ParameterDescriptor& desc = c->desc();
637                 double const lo = c->internal_to_interface(desc.lower);
638                 double const up = c->internal_to_interface(desc.upper);
639                 double const normal = c->internal_to_interface(desc.normal);
640                 double smallstep = desc.smallstep;
641                 double largestep = desc.largestep;
642
643                 if (smallstep == 0.0) {
644                         smallstep = up / 1000.;
645                 } else {
646                         smallstep = c->internal_to_interface(desc.lower + smallstep);
647                 }
648
649                 if (largestep == 0.0) {
650                         largestep = up / 40.;
651                 } else {
652                         largestep = c->internal_to_interface(desc.lower + largestep);
653                 }
654
655                 _adjustment.set_lower (lo);
656                 _adjustment.set_upper (up);
657                 _adjustment.set_step_increment (smallstep);
658                 _adjustment.set_page_increment (largestep);
659                 _slider.set_default_value (normal);
660
661                 _adjustment.signal_value_changed().connect (sigc::mem_fun (*this, &Control::slider_adjusted));
662                 // dup. currently timers are used :(
663                 //c->Changed.connect (_connection, MISSING_INVALIDATOR, boost::bind (&Control::control_changed, this), gui_context ());
664         }
665
666         // yuck, do we really need to do this?
667         // according to c404374 this is only needed for send automation
668         timer_connection = Timers::rapid_connect (sigc::mem_fun (*this, &Control::control_changed));
669
670         control_changed ();
671         set_tooltip ();
672
673         /* We're providing our own PersistentTooltip */
674         set_no_tooltip_whatsoever (_slider);
675 }
676
677 ProcessorEntry::Control::~Control ()
678 {
679         timer_connection.disconnect ();
680 }
681
682 void
683 ProcessorEntry::Control::set_tooltip ()
684 {
685         boost::shared_ptr<AutomationControl> c = _control.lock ();
686
687         if (!c) {
688                 return;
689         }
690         char tmp[256];
691         if (c->toggled ()) {
692                 snprintf (tmp, sizeof(tmp), "%s: %s", _name.c_str(), c->get_value() > 0.5 ? _("on") : _("off"));
693         } else {
694                 snprintf (tmp, sizeof(tmp), "%s: %.2f", _name.c_str(), c->internal_to_user (c->get_value ()));
695         }
696
697         string sm = Gtkmm2ext::markup_escape_text (tmp);
698         _slider_persistant_tooltip.set_tip (sm);
699         ARDOUR_UI_UTILS::set_tooltip (_button, sm);
700 }
701
702 void
703 ProcessorEntry::Control::slider_adjusted ()
704 {
705         if (_ignore_ui_adjustment) {
706                 return;
707         }
708
709         boost::shared_ptr<AutomationControl> c = _control.lock ();
710
711         if (!c) {
712                 return;
713         }
714
715         c->set_value ( c->interface_to_internal(_adjustment.get_value ()) , Controllable::NoGroup);
716         set_tooltip ();
717 }
718
719 void
720 ProcessorEntry::Control::button_clicked ()
721 {
722         boost::shared_ptr<AutomationControl> c = _control.lock ();
723
724         if (!c) {
725                 return;
726         }
727
728         bool const n = _button.get_active ();
729
730         c->set_value (n ? 0 : 1, Controllable::NoGroup);
731         _button.set_active (!n);
732         set_tooltip ();
733 }
734
735 void
736 ProcessorEntry::Control::button_clicked_event (GdkEventButton *ev)
737 {
738         (void) ev;
739
740         button_clicked ();
741 }
742
743 void
744 ProcessorEntry::Control::control_changed ()
745 {
746         boost::shared_ptr<AutomationControl> c = _control.lock ();
747         if (!c) {
748                 return;
749         }
750
751         _ignore_ui_adjustment = true;
752
753         if (c->toggled ()) {
754
755                 _button.set_active (c->get_value() > 0.5);
756
757         } else {
758                 // as long as rapid timers are used, only update the tooltip
759                 // if the value has changed.
760                 const double nval = c->internal_to_interface (c->get_value ());
761                 if (_adjustment.get_value() != nval) {
762                         _adjustment.set_value (nval);
763                         set_tooltip ();
764                 }
765         }
766
767         _ignore_ui_adjustment = false;
768 }
769
770 void
771 ProcessorEntry::Control::add_state (XMLNode* node) const
772 {
773         XMLNode* c = new XMLNode (X_("Object"));
774         c->add_property (X_("id"), state_id ());
775         c->add_property (X_("visible"), _visible);
776         node->add_child_nocopy (*c);
777 }
778
779 void
780 ProcessorEntry::Control::set_state (XMLNode const * node)
781 {
782         XMLNode* n = GUIObjectState::get_node (node, state_id ());
783         if (n) {
784                 XMLProperty* p = n->property (X_("visible"));
785                 set_visible (p && string_is_affirmative (p->value ()));
786         } else {
787                 set_visible (false);
788         }
789 }
790
791 void
792 ProcessorEntry::Control::set_visible (bool v)
793 {
794         if (v) {
795                 box.show ();
796         } else {
797                 box.hide ();
798         }
799
800         _visible = v;
801 }
802
803 /** Called when the Editor might have re-shown things that
804     we want hidden.
805 */
806 void
807 ProcessorEntry::Control::hide_things ()
808 {
809         if (!_visible) {
810                 box.hide ();
811         }
812 }
813
814 string
815 ProcessorEntry::Control::state_id () const
816 {
817         boost::shared_ptr<AutomationControl> c = _control.lock ();
818         assert (c);
819
820         return string_compose (X_("control %1"), c->id().to_s ());
821 }
822
823 PluginInsertProcessorEntry::PluginInsertProcessorEntry (ProcessorBox* b, boost::shared_ptr<ARDOUR::PluginInsert> p, Width w)
824         : ProcessorEntry (b, p, w)
825         , _plugin_insert (p)
826 {
827         p->PluginIoReConfigure.connect (
828                 _splitting_connection, invalidator (*this), boost::bind (&PluginInsertProcessorEntry::plugin_insert_splitting_changed, this), gui_context()
829                 );
830
831         plugin_insert_splitting_changed ();
832 }
833
834 void
835 PluginInsertProcessorEntry::plugin_insert_splitting_changed ()
836 {
837         ChanCount in, out; // actual configured i/o
838         _plugin_insert->configured_io (in, out);
839
840         /* get number of input ports */
841         ChanCount sinks = _plugin_insert->natural_input_streams();
842         if (!_plugin_insert->splitting () && _plugin_insert->get_count() > 1) {
843                 /* replicated instances */
844                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
845                         sinks.set(*t, sinks.get(*t) * _plugin_insert->get_count());
846                 }
847         }
848         /* MIDI bypass */
849         if (_plugin_insert->natural_output_streams().n_midi() == 0 &&
850                         _plugin_insert->output_streams().n_midi() == 1) {
851                 in.set(DataType::MIDI, 1);
852                 out.set(DataType::MIDI, 1);
853                 sinks.set(DataType::MIDI, 1);
854         }
855
856         /* the Input streams available (*valid* outputs from prev. plugin)
857          * this will be <= sinks. Some input-ports of this processor
858          * may be unconnected.
859          */
860         _routing_icon.set_sources(in);
861
862         /* the actual input ports of this processor */
863         _input_icon.set_ports(sinks);
864         _routing_icon.set_sinks(sinks);
865
866         /* set/override plugin-output ports to actual outputs-streams.
867          *
868          * This plugin may have unconnected output-ports (currently only in Mixbus,
869          * e.g channelstrip-EQ at the top of a MIDI-channel before the synth).
870          *
871          * The *next* processor below this one will only see the
872          * actual available streams (it cannot know the real outputs
873          * of this plugin).
874          *
875          * There is currently no API to query the ports of the previous (or next)
876          * processor.
877          *
878          * (normally - iff configuration succeeds - this is set during
879          * ProcessorEntry::processor_configuration_changed() and should
880          * equal _plugin_insert->output_streams())
881          */
882         _output_icon.set_ports(out);
883 #ifndef NDEBUG
884         if (out != _plugin_insert->output_streams()) {
885                 std::cerr << "Processor Wiring: " <<  processor()->name()
886                         << " out-ports: " << _plugin_insert->output_streams() // NB. does not include midi-bypass
887                         << " out-connections: " << out
888                         << endmsg;
889         }
890 #endif
891
892         _routing_icon.set_splitting(_plugin_insert->splitting ());
893
894         if (_plugin_insert->splitting () ||  in != sinks)
895         {
896                 _routing_icon.set_size_request (-1, std::max (7.f, rintf(7.f * UIConfiguration::instance().get_ui_scale())));
897                 _routing_icon.set_visible(true);
898                 _input_icon.show();
899         } else {
900                 _routing_icon.set_visible(false);
901                 if (_position_num != 0) {
902                         _input_icon.hide();
903                 }
904         }
905
906         _input_icon.queue_draw();
907         _output_icon.queue_draw();
908         _routing_icon.queue_draw();
909 }
910
911 void
912 PluginInsertProcessorEntry::hide_things ()
913 {
914         ProcessorEntry::hide_things ();
915         plugin_insert_splitting_changed ();
916 }
917
918 ProcessorEntry::PortIcon::PortIcon(bool input) {
919         _input = input;
920         _ports = ARDOUR::ChanCount(ARDOUR::DataType::AUDIO, 1);
921         set_size_request (-1, std::max (2.f, rintf(2.f * UIConfiguration::instance().get_ui_scale())));
922 }
923
924 bool
925 ProcessorEntry::PortIcon::on_expose_event (GdkEventExpose* ev)
926 {
927         cairo_t* cr = gdk_cairo_create (get_window()->gobj());
928
929         cairo_rectangle (cr, ev->area.x, ev->area.y, ev->area.width, ev->area.height);
930         cairo_clip (cr);
931
932         Gtk::Allocation a = get_allocation();
933         double const width = a.get_width();
934         double const height = a.get_height();
935
936         Gdk::Color const bg = get_style()->get_bg (STATE_NORMAL);
937         cairo_set_source_rgb (cr, bg.get_red_p (), bg.get_green_p (), bg.get_blue_p ());
938
939         cairo_rectangle (cr, 0, 0, width, height);
940         cairo_fill (cr);
941
942         const double dx = rint(max(2., 2. * UIConfiguration::instance().get_ui_scale()));
943         if (_ports.n_total() > 1) {
944                 for (uint32_t i = 0; i < _ports.n_total(); ++i) {
945                         if (i < _ports.n_midi()) {
946                                 cairo_set_source_rgb (cr,
947                                                 UINT_RGBA_R_FLT(midi_port_color),
948                                                 UINT_RGBA_G_FLT(midi_port_color),
949                                                 UINT_RGBA_B_FLT(midi_port_color));
950                         } else {
951                                 cairo_set_source_rgb (cr,
952                                                 UINT_RGBA_R_FLT(audio_port_color),
953                                                 UINT_RGBA_G_FLT(audio_port_color),
954                                                 UINT_RGBA_B_FLT(audio_port_color));
955                         }
956                         const float x = rintf(width * (.2f + .6f * i / (_ports.n_total() - 1.f)));
957                         cairo_rectangle (cr, x-dx * .5, 0, 1+dx, height);
958                         cairo_fill(cr);
959                 }
960         } else if (_ports.n_total() == 1) {
961                 if (_ports.n_midi() == 1) {
962                         cairo_set_source_rgb (cr,
963                                         UINT_RGBA_R_FLT(midi_port_color),
964                                         UINT_RGBA_G_FLT(midi_port_color),
965                                         UINT_RGBA_B_FLT(midi_port_color));
966                 } else {
967                         cairo_set_source_rgb (cr,
968                                         UINT_RGBA_R_FLT(audio_port_color),
969                                         UINT_RGBA_G_FLT(audio_port_color),
970                                         UINT_RGBA_B_FLT(audio_port_color));
971                 }
972                 const float x = rintf(width * .5);
973                 cairo_rectangle (cr, x-dx * .5, 0, 1+dx, height);
974                 cairo_fill(cr);
975                 cairo_stroke(cr);
976         }
977
978         cairo_destroy(cr);
979         return true;
980 }
981
982 bool
983 ProcessorEntry::RoutingIcon::on_expose_event (GdkEventExpose* ev)
984 {
985         cairo_t* cr = gdk_cairo_create (get_window()->gobj());
986
987         cairo_rectangle (cr, ev->area.x, ev->area.y, ev->area.width, ev->area.height);
988         cairo_clip (cr);
989
990         cairo_set_line_width (cr, max (1.f, UIConfiguration::instance().get_ui_scale()));
991         cairo_set_line_cap (cr, CAIRO_LINE_CAP_ROUND);
992
993         Gtk::Allocation a = get_allocation();
994         double const width = a.get_width();
995         double const height = a.get_height();
996
997         Gdk::Color const bg = get_style()->get_bg (STATE_NORMAL);
998         cairo_set_source_rgb (cr, bg.get_red_p (), bg.get_green_p (), bg.get_blue_p ());
999
1000         cairo_rectangle (cr, 0, 0, width, height);
1001         cairo_fill (cr);
1002
1003         Gdk::Color const fg = get_style()->get_fg (STATE_NORMAL);
1004         cairo_set_source_rgb (cr, fg.get_red_p (), fg.get_green_p (), fg.get_blue_p ());
1005
1006         const uint32_t sources = _sources.n_total();
1007         const uint32_t sinks = _sinks.n_total();
1008
1009         const uint32_t midi_sources = _sources.n_midi();
1010         const uint32_t midi_sinks = _sinks.n_midi();
1011         const uint32_t audio_sources = _sources.n_audio();
1012         const uint32_t audio_sinks = _sinks.n_audio();
1013
1014         /* MIDI */
1015         cairo_set_source_rgb (cr,
1016                         UINT_RGBA_R_FLT(midi_port_color),
1017                         UINT_RGBA_G_FLT(midi_port_color),
1018                         UINT_RGBA_B_FLT(midi_port_color));
1019         if (midi_sources > 0 && midi_sinks > 0 && sinks > 1 && sources > 1) {
1020                 for (uint32_t i = 0 ; i < midi_sources; ++i) {
1021                         const float si_x  = rintf(width * (.2f + .6f * i  / (sinks - 1.f))) + .5f;
1022                         const float si_x0 = rintf(width * (.2f + .6f * i / (sources - 1.f))) + .5f;
1023                         cairo_move_to (cr, si_x, height);
1024                         cairo_curve_to (cr, si_x, 0, si_x0, height, si_x0, 0);
1025                         cairo_stroke (cr);
1026                 }
1027         } else if (midi_sources == 1 && midi_sinks == 1 && sinks == 1 && sources == 1) {
1028                 const float si_x = rintf(width * .5f) + .5f;
1029                 cairo_move_to (cr, si_x, height);
1030                 cairo_line_to (cr, si_x, 0);
1031                 cairo_stroke (cr);
1032         } else if (midi_sources == 1 && midi_sinks == 1) {
1033                 /* unusual cases -- removed synth, midi-track w/audio plugins */
1034                 const float si_x  = rintf(width * (sinks   > 1 ? .2f : .5f)) + .5f;
1035                 const float si_x0 = rintf(width * (sources > 1 ? .2f : .5f)) + .5f;
1036                 cairo_move_to (cr, si_x, height);
1037                 cairo_curve_to (cr, si_x, 0, si_x0, height, si_x0, 0);
1038                 cairo_stroke (cr);
1039         } else if (midi_sources == 0 && midi_sinks == 1) {
1040                 const double dx = 1 + rint(max(2., 2. * UIConfiguration::instance().get_ui_scale()));
1041                 // draw "T"
1042                 //  TODO connect back to track-input of last midi-out if any, otherwise draw "X"
1043                 const float si_x  = rintf(width * .2f) + .5f;
1044                 cairo_move_to (cr, si_x, height);
1045                 cairo_line_to (cr, si_x, height * .66);
1046                 cairo_move_to (cr, si_x - dx, height * .66);
1047                 cairo_line_to (cr, si_x + dx, height * .66);
1048                 cairo_stroke (cr);
1049 #ifndef NDEBUG
1050         } else if (midi_sources != 0 && midi_sinks != 0) {
1051                 PBD::warning << string_compose("Programming error: midi routing display: A %1 -> %2 | M %3 -> %4 | T %5 -> %6",
1052                                 audio_sources, audio_sinks, midi_sources, midi_sinks, sources, sinks) << endmsg;
1053 #endif
1054         }
1055
1056         /* AUDIO */
1057         cairo_set_source_rgb (cr,
1058                         UINT_RGBA_R_FLT(audio_port_color),
1059                         UINT_RGBA_G_FLT(audio_port_color),
1060                         UINT_RGBA_B_FLT(audio_port_color));
1061
1062         if (_splitting) {
1063                 assert(audio_sources < 2);
1064                 assert(audio_sinks > 1);
1065                 /* assume there is only ever one MIDI port */
1066                 const float si_x0 = rintf(width * (midi_sources > 0 ? .8f : .5f)) + .5f;
1067                 for (uint32_t i = midi_sinks; i < sinks; ++i) {
1068                         const float si_x = rintf(width * (.2f + .6f * i / (sinks - 1.f))) + .5f;
1069                         cairo_move_to (cr, si_x, height);
1070                         cairo_curve_to (cr, si_x, 0, si_x0, height, si_x0, 0);
1071                         cairo_stroke (cr);
1072                 }
1073         } else if (audio_sources > 1 && sinks > 1) {
1074                 for (uint32_t i = 0 ; i < audio_sources; ++i) {
1075                         const float si_x = rintf(width * (.2f + .6f * (i + midi_sinks) / (sinks - 1.f))) + .5f;
1076                         const float si_x0 = rintf(width * (.2f + .6f * (i + midi_sources) / (sources - 1.f))) + .5f;
1077                         cairo_move_to (cr, si_x, height);
1078                         cairo_curve_to (cr, si_x, 0, si_x0, height, si_x0, 0);
1079                         cairo_stroke (cr);
1080                 }
1081         } else if (audio_sources == 1 && audio_sinks > 0) {
1082                 float si_x, si_x0;
1083                 if (sinks == 1) {
1084                         si_x = rintf(width * .5f) + .5f;
1085                 } else {
1086                         si_x = rintf(width * (.2f + .6f * midi_sinks / (sinks - 1.f))) + .5f;
1087                 }
1088                 if (sources == 1) {
1089                         si_x0 = rintf(width * .5f) + .5f;
1090                 } else {
1091                         si_x0 = rintf(width * (.2f + .6f * midi_sources / (sources - 1.f))) + .5f;
1092                 }
1093                 cairo_move_to (cr, si_x, height);
1094                 cairo_curve_to (cr, si_x, 0, si_x0, height, si_x0, 0);
1095                 cairo_stroke (cr);
1096 #ifndef NDEBUG
1097         } else if (audio_sources != 0 && audio_sinks != 0) {
1098                 PBD::warning << string_compose("Programming error: audio routing display: A %1 -> %2 | M %3 -> %4 | T %5 -> %6",
1099                                 audio_sources, audio_sinks, midi_sources, midi_sinks, sources, sinks) << endmsg;
1100 #endif
1101         }
1102         cairo_destroy(cr);
1103         return true;
1104 }
1105
1106 static std::list<Gtk::TargetEntry> drop_targets()
1107 {
1108         std::list<Gtk::TargetEntry> tmp;
1109         tmp.push_back (Gtk::TargetEntry ("processor")); // from processor-box to processor-box
1110         tmp.push_back (Gtk::TargetEntry ("PluginInfoPtr")); // from plugin-manager
1111         tmp.push_back (Gtk::TargetEntry ("PluginPresetPtr")); // from sidebar
1112         return tmp;
1113 }
1114
1115 static std::list<Gtk::TargetEntry> drag_targets()
1116 {
1117         std::list<Gtk::TargetEntry> tmp;
1118         tmp.push_back (Gtk::TargetEntry ("PluginPresetPtr")); // to sidebar (optional preset)
1119         tmp.push_back (Gtk::TargetEntry ("processor")); // to processor-box (copy)
1120         return tmp;
1121 }
1122
1123 static std::list<Gtk::TargetEntry> drag_targets_noplugin()
1124 {
1125         std::list<Gtk::TargetEntry> tmp;
1126         tmp.push_back (Gtk::TargetEntry ("processor")); // to processor box (sends, faders re-order)
1127         return tmp;
1128 }
1129
1130 ProcessorBox::ProcessorBox (ARDOUR::Session* sess, boost::function<PluginSelector*()> get_plugin_selector,
1131                             RouteProcessorSelection& rsel, MixerStrip* parent, bool owner_is_mixer)
1132         : _parent_strip (parent)
1133         , _owner_is_mixer (owner_is_mixer)
1134         , ab_direction (true)
1135         , _get_plugin_selector (get_plugin_selector)
1136         , _placement (-1)
1137         , _visible_prefader_processors (0)
1138         , _rr_selection(rsel)
1139         , processor_display (drop_targets())
1140         , _redisplay_pending (false)
1141
1142 {
1143         set_session (sess);
1144
1145         _width = Wide;
1146         processor_menu = 0;
1147         no_processor_redisplay = false;
1148
1149         processor_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1150         processor_scroller.add (processor_display);
1151         pack_start (processor_scroller, true, true);
1152
1153         processor_display.set_flags (CAN_FOCUS);
1154         processor_display.set_name ("ProcessorList");
1155         processor_display.set_data ("processorbox", this);
1156         processor_display.set_size_request (48, -1);
1157         processor_display.set_spacing (0);
1158
1159         processor_display.signal_enter_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::enter_notify), false);
1160         processor_display.signal_leave_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::leave_notify), false);
1161
1162         processor_display.ButtonPress.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_press_event));
1163         processor_display.ButtonRelease.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_release_event));
1164
1165         processor_display.Reordered.connect (sigc::mem_fun (*this, &ProcessorBox::reordered));
1166         processor_display.DropFromAnotherBox.connect (sigc::mem_fun (*this, &ProcessorBox::object_drop));
1167         processor_display.DropFromExternal.connect (sigc::mem_fun (*this, &ProcessorBox::plugin_drop));
1168
1169         processor_scroller.show ();
1170         processor_display.show ();
1171
1172         if (parent) {
1173                 parent->DeliveryChanged.connect (
1174                         _mixer_strip_connections, invalidator (*this), boost::bind (&ProcessorBox::mixer_strip_delivery_changed, this, _1), gui_context ()
1175                         );
1176         }
1177
1178         ARDOUR_UI_UTILS::set_tooltip (processor_display, _("Right-click to add/remove/edit\nplugins,inserts,sends and more"));
1179 }
1180
1181 ProcessorBox::~ProcessorBox ()
1182 {
1183         /* it may appear as if we should delete processor_menu but that is a
1184          * pointer to a widget owned by the UI Manager, and has potentially
1185          * be returned to many other ProcessorBoxes. GTK doesn't really make
1186          * clear the ownership of this widget, which is a menu and thus is
1187          * never packed into any container other than an implict GtkWindow.
1188          *
1189          * For now, until or if we ever get clarification over the ownership
1190          * story just let it continue to exist. At worst, its a small memory leak.
1191          */
1192 }
1193
1194 void
1195 ProcessorBox::set_route (boost::shared_ptr<Route> r)
1196 {
1197         if (_route == r) {
1198                 return;
1199         }
1200
1201         _route_connections.drop_connections();
1202
1203         /* new route: any existing block on processor redisplay must be meaningless */
1204         no_processor_redisplay = false;
1205         _route = r;
1206
1207         _route->processors_changed.connect (
1208                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_processors_changed, this, _1), gui_context()
1209                 );
1210
1211         _route->DropReferences.connect (
1212                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_going_away, this), gui_context()
1213                 );
1214
1215         _route->PropertyChanged.connect (
1216                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_property_changed, this, _1), gui_context()
1217                 );
1218
1219         redisplay_processors ();
1220 }
1221
1222 void
1223 ProcessorBox::route_going_away ()
1224 {
1225         /* don't keep updating display as processors are deleted */
1226         no_processor_redisplay = true;
1227         _route.reset ();
1228 }
1229
1230 boost::shared_ptr<Processor>
1231 ProcessorBox::find_drop_position (ProcessorEntry* position)
1232 {
1233         boost::shared_ptr<Processor> p;
1234         if (position) {
1235                 p = position->processor ();
1236                 if (!p) {
1237                         /* dropped on the blank entry (which will be before the
1238                                  fader), so use the first non-blank child as our
1239                                  `dropped on' processor */
1240                         list<ProcessorEntry*> c = processor_display.children ();
1241                         list<ProcessorEntry*>::iterator i = c.begin ();
1242
1243                         assert (i != c.end ());
1244                         p = (*i)->processor ();
1245                         assert (p);
1246                 }
1247         }
1248         return p;
1249 }
1250
1251 void
1252 ProcessorBox::_drop_plugin_preset (Gtk::SelectionData const &data, Route::ProcessorList &pl)
1253 {
1254                 const void * d = data.get_data();
1255                 const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>* tv = reinterpret_cast<const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>*>(d);
1256
1257                 PluginPresetList nfos;
1258                 TreeView* source;
1259                 tv->get_object_drag_data (nfos, &source);
1260
1261                 for (list<PluginPresetPtr>::const_iterator i = nfos.begin(); i != nfos.end(); ++i) {
1262                         PluginPresetPtr ppp = (*i);
1263                         PluginInfoPtr pip = ppp->_pip;
1264                         PluginPtr p = pip->load (*_session);
1265                         if (!p) {
1266                                 continue;
1267                         }
1268
1269                         if (ppp->_preset.valid) {
1270                                 p->load_preset (ppp->_preset);
1271                         }
1272
1273                         boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
1274                         if (Config->get_new_plugins_active ()) {
1275                                 processor->activate ();
1276                         }
1277                         pl.push_back (processor);
1278                 }
1279 }
1280
1281 void
1282 ProcessorBox::_drop_plugin (Gtk::SelectionData const &data, Route::ProcessorList &pl)
1283 {
1284                 const void * d = data.get_data();
1285                 const Gtkmm2ext::DnDTreeView<ARDOUR::PluginInfoPtr>* tv = reinterpret_cast<const Gtkmm2ext::DnDTreeView<ARDOUR::PluginInfoPtr>*>(d);
1286                 PluginInfoList nfos;
1287
1288                 TreeView* source;
1289                 tv->get_object_drag_data (nfos, &source);
1290
1291                 for (list<PluginInfoPtr>::const_iterator i = nfos.begin(); i != nfos.end(); ++i) {
1292                         PluginPtr p = (*i)->load (*_session);
1293                         if (!p) {
1294                                 continue;
1295                         }
1296                         boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
1297                         if (Config->get_new_plugins_active ()) {
1298                                 processor->activate ();
1299                         }
1300                         pl.push_back (processor);
1301                 }
1302 }
1303
1304 void
1305 ProcessorBox::plugin_drop (Gtk::SelectionData const &data, ProcessorEntry* position, Glib::RefPtr<Gdk::DragContext> const & context)
1306 {
1307         if (!_session) {
1308                 return;
1309         }
1310
1311         boost::shared_ptr<Processor> p = find_drop_position (position);
1312         Route::ProcessorList pl;
1313
1314         if (data.get_target() == "PluginInfoPtr") {
1315                 _drop_plugin (data, pl);
1316         }
1317         else if (data.get_target() == "PluginPresetPtr") {
1318                 _drop_plugin_preset (data, pl);
1319         }
1320         else {
1321                 return;
1322         }
1323
1324         Route::ProcessorStreams err;
1325         if (_route->add_processors (pl, p, &err)) {
1326                 string msg = _(
1327                                 "Processor Drag/Drop failed. Probably because\n\
1328 the I/O configuration of the plugins could\n\
1329 not match the configuration of this track.");
1330                 MessageDialog am (msg);
1331                 am.run ();
1332         }
1333 }
1334
1335 void
1336 ProcessorBox::object_drop (DnDVBox<ProcessorEntry>* source, ProcessorEntry* position, Glib::RefPtr<Gdk::DragContext> const & context)
1337 {
1338         boost::shared_ptr<Processor> p = find_drop_position (position);
1339
1340         list<ProcessorEntry*> children = source->selection ();
1341         list<boost::shared_ptr<Processor> > procs;
1342         for (list<ProcessorEntry*>::const_iterator i = children.begin(); i != children.end(); ++i) {
1343                 if ((*i)->processor ()) {
1344                         if (boost::dynamic_pointer_cast<UnknownProcessor> ((*i)->processor())) {
1345                                 continue;
1346                         }
1347                         procs.push_back ((*i)->processor ());
1348                 }
1349         }
1350
1351         for (list<boost::shared_ptr<Processor> >::const_iterator i = procs.begin(); i != procs.end(); ++i) {
1352                 XMLNode& state = (*i)->get_state ();
1353                 XMLNodeList nlist;
1354                 nlist.push_back (&state);
1355                 paste_processor_state (nlist, p);
1356                 delete &state;
1357         }
1358
1359         /* since the dndvbox doesn't take care of this properly, we have to delete the originals
1360            ourselves.
1361         */
1362
1363         if ((context->get_suggested_action() == Gdk::ACTION_MOVE) && source) {
1364                 ProcessorBox* other = reinterpret_cast<ProcessorBox*> (source->get_data ("processorbox"));
1365                 if (other) {
1366                         other->delete_dragged_processors (procs);
1367                 }
1368         }
1369 }
1370
1371 void
1372 ProcessorBox::set_width (Width w)
1373 {
1374         if (_width == w) {
1375                 return;
1376         }
1377
1378         _width = w;
1379
1380         list<ProcessorEntry*> children = processor_display.children ();
1381         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
1382                 (*i)->set_enum_width (w);
1383         }
1384
1385         queue_resize ();
1386 }
1387
1388 Gtk::Menu*
1389 ProcessorBox::build_possible_aux_menu ()
1390 {
1391         boost::shared_ptr<RouteList> rl = _session->get_routes_with_internal_returns();
1392
1393         if (rl->empty()) {
1394                 /* No aux sends if there are no busses */
1395                 return 0;
1396         }
1397
1398         if (_route->is_monitor ()) {
1399                 return 0;
1400         }
1401
1402         using namespace Menu_Helpers;
1403         Menu* menu = manage (new Menu);
1404         MenuList& items = menu->items();
1405
1406         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
1407                 if (!_route->internal_send_for (*r) && *r != _route) {
1408                         items.push_back (MenuElem ((*r)->name(), sigc::bind (sigc::ptr_fun (ProcessorBox::rb_choose_aux), boost::weak_ptr<Route>(*r))));
1409                 }
1410         }
1411
1412         return menu;
1413 }
1414
1415 void
1416 ProcessorBox::show_processor_menu (int arg)
1417 {
1418         if (processor_menu == 0) {
1419                 processor_menu = build_processor_menu ();
1420                 processor_menu->signal_unmap().connect (sigc::mem_fun (*this, &ProcessorBox::processor_menu_unmapped));
1421         }
1422
1423         /* Sort out the plugin submenu */
1424
1425         Gtk::MenuItem* plugin_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/newplugin"));
1426
1427         if (plugin_menu_item) {
1428                 plugin_menu_item->set_submenu (*_get_plugin_selector()->plugin_menu());
1429         }
1430
1431         /* And the aux submenu */
1432
1433         Gtk::MenuItem* aux_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/newaux"));
1434
1435         if (aux_menu_item) {
1436                 Menu* m = build_possible_aux_menu();
1437                 if (m && !m->items().empty()) {
1438                         aux_menu_item->set_submenu (*m);
1439                         aux_menu_item->set_sensitive (true);
1440                 } else {
1441                         /* stupid gtkmm: we need to pass a null reference here */
1442                         gtk_menu_item_set_submenu (aux_menu_item->gobj(), 0);
1443                         aux_menu_item->set_sensitive (false);
1444                 }
1445         }
1446
1447         ActionManager::get_action (X_("ProcessorMenu"), "newinsert")->set_sensitive (!_route->is_monitor ());
1448         ActionManager::get_action (X_("ProcessorMenu"), "newsend")->set_sensitive (!_route->is_monitor ());
1449
1450         ProcessorEntry* single_selection = 0;
1451         if (processor_display.selection().size() == 1) {
1452                 single_selection = processor_display.selection().front();
1453         }
1454
1455         /* And the controls submenu */
1456
1457         Gtk::MenuItem* controls_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/controls"));
1458
1459         if (controls_menu_item) {
1460                 if (single_selection) {
1461                         Menu* m = single_selection->build_controls_menu ();
1462                         if (m && !m->items().empty()) {
1463                                 controls_menu_item->set_submenu (*m);
1464                                 controls_menu_item->set_sensitive (true);
1465                         } else {
1466                                 gtk_menu_item_set_submenu (controls_menu_item->gobj(), 0);
1467                                 controls_menu_item->set_sensitive (false);
1468                         }
1469                 } else {
1470                         controls_menu_item->set_sensitive (false);
1471                 }
1472         }
1473
1474         Gtk::MenuItem* send_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/ProcessorMenu/send_options"));
1475         if (send_menu_item) {
1476                 if (single_selection && !_route->is_monitor()) {
1477                         Menu* m = single_selection->build_send_options_menu ();
1478                         if (m && !m->items().empty()) {
1479                                 send_menu_item->set_submenu (*m);
1480                                 send_menu_item->set_sensitive (true);
1481                         } else {
1482                                 gtk_menu_item_set_submenu (send_menu_item->gobj(), 0);
1483                                 send_menu_item->set_sensitive (false);
1484                         }
1485                 } else {
1486                         send_menu_item->set_sensitive (false);
1487                 }
1488         }
1489
1490         /* Sensitise actions as approprioate */
1491
1492
1493         const bool sensitive = !processor_display.selection().empty() && ! stub_processor_selected ();
1494
1495         paste_action->set_sensitive (!_rr_selection.processors.empty());
1496         cut_action->set_sensitive (sensitive && can_cut ());
1497         copy_action->set_sensitive (sensitive);
1498         delete_action->set_sensitive (sensitive || stub_processor_selected ());
1499
1500         edit_action->set_sensitive (one_processor_can_be_edited ());
1501         edit_generic_action->set_sensitive (one_processor_can_be_edited ());
1502
1503         boost::shared_ptr<PluginInsert> pi;
1504         if (single_selection) {
1505                 pi = boost::dynamic_pointer_cast<PluginInsert> (single_selection->processor ());
1506         }
1507
1508         /* allow editing with an Ardour-generated UI for plugin inserts with editors */
1509         edit_action->set_sensitive (pi && pi->plugin()->has_editor ());
1510
1511         /* disallow rename for multiple selections, for plugin inserts and for the fader */
1512         rename_action->set_sensitive (single_selection
1513                         && !pi
1514                         && !boost::dynamic_pointer_cast<Amp> (single_selection->processor ())
1515                         && !boost::dynamic_pointer_cast<UnknownProcessor> (single_selection->processor ()));
1516
1517         processor_menu->popup (1, arg);
1518
1519         /* Add a placeholder gap to the processor list to indicate where a processor would be
1520            inserted were one chosen from the menu.
1521         */
1522         int x, y;
1523         processor_display.get_pointer (x, y);
1524         _placement = processor_display.add_placeholder (y);
1525
1526         if (_visible_prefader_processors == 0 && _placement > 0) {
1527                 --_placement;
1528         }
1529 }
1530
1531 bool
1532 ProcessorBox::enter_notify (GdkEventCrossing*)
1533 {
1534         _current_processor_box = this;
1535         return false;
1536 }
1537
1538 bool
1539 ProcessorBox::leave_notify (GdkEventCrossing*)
1540 {
1541         return false;
1542 }
1543
1544 bool
1545 ProcessorBox::processor_operation (ProcessorOperation op)
1546 {
1547         ProcSelection targets;
1548
1549         get_selected_processors (targets);
1550
1551 /*      if (targets.empty()) {
1552
1553                 int x, y;
1554                 processor_display.get_pointer (x, y);
1555
1556                 pair<ProcessorEntry *, double> const pointer = processor_display.get_child_at_position (y);
1557
1558                 if (pointer.first && pointer.first->processor()) {
1559                         targets.push_back (pointer.first->processor ());
1560                 }
1561         }
1562 */
1563
1564         if ( (op == ProcessorsDelete) && targets.empty() )
1565                 return false;  //nothing to delete.  return false so the editor-mixer, because the user was probably intending to delete something in the editor
1566
1567         switch (op) {
1568         case ProcessorsSelectAll:
1569                 processor_display.select_all ();
1570                 break;
1571
1572         case ProcessorsSelectNone:
1573                 processor_display.select_none ();
1574                 break;
1575
1576         case ProcessorsCopy:
1577                 copy_processors (targets);
1578                 break;
1579
1580         case ProcessorsCut:
1581                 cut_processors (targets);
1582                 break;
1583
1584         case ProcessorsPaste:
1585                 // some processors are not selectable (e.g fader, meter), target is empty.
1586                 if (targets.empty() && _placement >= 0) {
1587                         assert (_route);
1588                         boost::shared_ptr<Processor> proc = _route->before_processor_for_index (_placement);
1589                         if (proc) {
1590                                 targets.push_back (proc);
1591                         }
1592                 }
1593                 if (targets.empty()) {
1594                         paste_processors ();
1595                 } else {
1596                         paste_processors (targets.front());
1597                 }
1598                 break;
1599
1600         case ProcessorsDelete:
1601                 delete_processors (targets);
1602                 break;
1603
1604         case ProcessorsToggleActive:
1605                 for (ProcSelection::iterator i = targets.begin(); i != targets.end(); ++i) {
1606                         if ((*i)->active()) {
1607                                 (*i)->deactivate ();
1608                         } else {
1609                                 (*i)->activate ();
1610                         }
1611                 }
1612                 break;
1613
1614         case ProcessorsAB:
1615                 ab_plugins ();
1616                 break;
1617
1618         default:
1619                 break;
1620         }
1621
1622         return true;
1623 }
1624
1625 ProcessorWindowProxy*
1626 ProcessorBox::find_window_proxy (boost::shared_ptr<Processor> processor) const
1627 {
1628         return  processor->window_proxy();
1629 }
1630
1631
1632 bool
1633 ProcessorBox::processor_button_press_event (GdkEventButton *ev, ProcessorEntry* child)
1634 {
1635         boost::shared_ptr<Processor> processor;
1636         if (child) {
1637                 processor = child->processor ();
1638         }
1639
1640         int ret = false;
1641         bool selected = processor_display.selected (child);
1642
1643         if (processor && (Keyboard::is_edit_event (ev) || (ev->button == 1 && ev->type == GDK_2BUTTON_PRESS))) {
1644
1645                 if (_session->engine().connected()) {
1646                         /* XXX giving an error message here is hard, because we may be in the midst of a button press */
1647
1648                         if (!one_processor_can_be_edited ()) {
1649                                 return true;
1650                         }
1651
1652                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::SecondaryModifier)) {
1653                                 generic_edit_processor (processor);
1654                         } else {
1655                                 edit_processor (processor);
1656                         }
1657                 }
1658
1659                 ret = true;
1660
1661         } else if (Keyboard::is_context_menu_event (ev)) {
1662
1663                 show_processor_menu (ev->time);
1664
1665                 ret = true;
1666
1667         } else if (processor && ev->button == 1 && selected) {
1668
1669                 // this is purely informational but necessary for route params UI
1670                 ProcessorSelected (processor); // emit
1671
1672         } else if (!processor && ev->button == 1 && ev->type == GDK_2BUTTON_PRESS) {
1673
1674                 choose_plugin ();
1675                 _get_plugin_selector()->show_manager ();
1676         }
1677
1678         return ret;
1679 }
1680
1681 bool
1682 ProcessorBox::processor_button_release_event (GdkEventButton *ev, ProcessorEntry* child)
1683 {
1684         boost::shared_ptr<Processor> processor;
1685         if (child) {
1686                 processor = child->processor ();
1687         }
1688
1689         if (processor && Keyboard::is_delete_event (ev)) {
1690
1691                 Glib::signal_idle().connect (sigc::bind (
1692                                 sigc::mem_fun(*this, &ProcessorBox::idle_delete_processor),
1693                                 boost::weak_ptr<Processor>(processor)));
1694
1695         } else if (processor && Keyboard::is_button2_event (ev)
1696 #ifndef GTKOSX
1697                    && (Keyboard::no_modifier_keys_pressed (ev) && ((ev->state & Gdk::BUTTON2_MASK) == Gdk::BUTTON2_MASK))
1698 #endif
1699                 ) {
1700
1701                 /* button2-click with no/appropriate modifiers */
1702
1703                 if (processor->active()) {
1704                         processor->deactivate ();
1705                 } else {
1706                         processor->activate ();
1707                 }
1708         }
1709
1710         return false;
1711 }
1712
1713 Menu *
1714 ProcessorBox::build_processor_menu ()
1715 {
1716         processor_menu = dynamic_cast<Gtk::Menu*>(ActionManager::get_widget("/ProcessorMenu") );
1717         processor_menu->set_name ("ArdourContextMenu");
1718         return processor_menu;
1719 }
1720
1721 void
1722 ProcessorBox::select_all_processors ()
1723 {
1724         processor_display.select_all ();
1725 }
1726
1727 void
1728 ProcessorBox::deselect_all_processors ()
1729 {
1730         processor_display.select_none ();
1731 }
1732
1733 void
1734 ProcessorBox::choose_plugin ()
1735 {
1736         _get_plugin_selector()->set_interested_object (*this);
1737 }
1738
1739 /** @return true if an error occurred, otherwise false */
1740 bool
1741 ProcessorBox::use_plugins (const SelectedPlugins& plugins)
1742 {
1743         for (SelectedPlugins::const_iterator p = plugins.begin(); p != plugins.end(); ++p) {
1744
1745                 boost::shared_ptr<Processor> processor (new PluginInsert (*_session, *p));
1746
1747                 Route::ProcessorStreams err_streams;
1748
1749                 if (_route->add_processor_by_index (processor, _placement, &err_streams, Config->get_new_plugins_active ())) {
1750                         weird_plugin_dialog (**p, err_streams);
1751                         return true;
1752                         // XXX SHAREDPTR delete plugin here .. do we even need to care?
1753                 } else if (plugins.size() == 1 && Config->get_open_gui_after_adding_plugin()) {
1754                         if (_session->engine().connected () && processor_can_be_edited (processor)) {
1755                                 if ((*p)->has_editor ()) {
1756                                         edit_processor (processor);
1757                                 } else {
1758                                         generic_edit_processor (processor);
1759                                 }
1760                         }
1761                 }
1762         }
1763
1764         return false;
1765 }
1766
1767 void
1768 ProcessorBox::weird_plugin_dialog (Plugin& p, Route::ProcessorStreams streams)
1769 {
1770         ArdourDialog dialog (_("Plugin Incompatibility"));
1771         Label label;
1772
1773         string text = string_compose(_("You attempted to add the plugin \"%1\" in slot %2.\n"),
1774                         p.name(), streams.index);
1775
1776         bool has_midi  = streams.count.n_midi() > 0 || p.get_info()->n_inputs.n_midi() > 0;
1777         bool has_audio = streams.count.n_audio() > 0 || p.get_info()->n_inputs.n_audio() > 0;
1778
1779         text += _("\nThis plugin has:\n");
1780         if (has_midi) {
1781                 uint32_t const n = p.get_info()->n_inputs.n_midi ();
1782                 text += string_compose (ngettext ("\t%1 MIDI input\n", "\t%1 MIDI inputs\n", n), n);
1783         }
1784         if (has_audio) {
1785                 uint32_t const n = p.get_info()->n_inputs.n_audio ();
1786                 text += string_compose (ngettext ("\t%1 audio input\n", "\t%1 audio inputs\n", n), n);
1787         }
1788
1789         text += _("\nbut at the insertion point, there are:\n");
1790         if (has_midi) {
1791                 uint32_t const n = streams.count.n_midi ();
1792                 text += string_compose (ngettext ("\t%1 MIDI channel\n", "\t%1 MIDI channels\n", n), n);
1793         }
1794         if (has_audio) {
1795                 uint32_t const n = streams.count.n_audio ();
1796                 text += string_compose (ngettext ("\t%1 audio channel\n", "\t%1 audio channels\n", n), n);
1797         }
1798
1799         text += string_compose (_("\n%1 is unable to insert this plugin here.\n"), PROGRAM_NAME);
1800         label.set_text(text);
1801
1802         dialog.get_vbox()->pack_start (label);
1803         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
1804
1805         dialog.set_name (X_("PluginIODialog"));
1806         dialog.set_modal (true);
1807         dialog.show_all ();
1808
1809         dialog.run ();
1810 }
1811
1812 void
1813 ProcessorBox::choose_insert ()
1814 {
1815         boost::shared_ptr<Processor> processor (new PortInsert (*_session, _route->pannable(), _route->mute_master()));
1816         _route->add_processor_by_index (processor, _placement);
1817 }
1818
1819 /* Caller must not hold process lock */
1820 void
1821 ProcessorBox::choose_send ()
1822 {
1823         boost::shared_ptr<Pannable> sendpan(new Pannable (*_session));
1824         boost::shared_ptr<Send> send (new Send (*_session, sendpan, _route->mute_master()));
1825
1826         /* make an educated guess at the initial number of outputs for the send */
1827         ChanCount outs = (_session->master_out())
1828                         ? _session->master_out()->n_outputs()
1829                         : _route->n_outputs();
1830
1831         /* XXX need processor lock on route */
1832         try {
1833                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
1834                 send->output()->ensure_io (outs, false, this);
1835         } catch (AudioEngine::PortRegistrationFailure& err) {
1836                 error << string_compose (_("Cannot set up new send: %1"), err.what()) << endmsg;
1837                 return;
1838         }
1839
1840         /* let the user adjust the IO setup before creation.
1841
1842            Note: this dialog is NOT modal - we just leave it to run and it will
1843            return when its Finished signal is emitted - typically when the window
1844            is closed.
1845          */
1846
1847         IOSelectorWindow *ios = new IOSelectorWindow (_session, send->output(), true);
1848         ios->show ();
1849
1850         /* keep a reference to the send so it doesn't get deleted while
1851            the IOSelectorWindow is doing its stuff
1852         */
1853         _processor_being_created = send;
1854
1855         ios->selector().Finished.connect (sigc::bind (
1856                         sigc::mem_fun(*this, &ProcessorBox::send_io_finished),
1857                         boost::weak_ptr<Processor>(send), ios));
1858
1859 }
1860
1861 void
1862 ProcessorBox::send_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
1863 {
1864         boost::shared_ptr<Processor> processor (weak_processor.lock());
1865
1866         /* drop our temporary reference to the new send */
1867         _processor_being_created.reset ();
1868
1869         if (!processor) {
1870                 return;
1871         }
1872
1873         switch (r) {
1874         case IOSelector::Cancelled:
1875                 // processor will go away when all shared_ptrs to it vanish
1876                 break;
1877
1878         case IOSelector::Accepted:
1879                 _route->add_processor_by_index (processor, _placement);
1880                 if (Profile->get_sae()) {
1881                         processor->activate ();
1882                 }
1883                 break;
1884         }
1885
1886         delete_when_idle (ios);
1887 }
1888
1889 void
1890 ProcessorBox::return_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
1891 {
1892         boost::shared_ptr<Processor> processor (weak_processor.lock());
1893
1894         /* drop our temporary reference to the new return */
1895         _processor_being_created.reset ();
1896
1897         if (!processor) {
1898                 return;
1899         }
1900
1901         switch (r) {
1902         case IOSelector::Cancelled:
1903                 // processor will go away when all shared_ptrs to it vanish
1904                 break;
1905
1906         case IOSelector::Accepted:
1907                 _route->add_processor_by_index (processor, _placement);
1908                 if (Profile->get_sae()) {
1909                         processor->activate ();
1910                 }
1911                 break;
1912         }
1913
1914         delete_when_idle (ios);
1915 }
1916
1917 void
1918 ProcessorBox::choose_aux (boost::weak_ptr<Route> wr)
1919 {
1920         if (!_route) {
1921                 return;
1922         }
1923
1924         boost::shared_ptr<Route> target = wr.lock();
1925
1926         if (!target) {
1927                 return;
1928         }
1929
1930         _session->add_internal_send (target, _placement, _route);
1931 }
1932
1933 void
1934 ProcessorBox::route_processors_changed (RouteProcessorChange c)
1935 {
1936         if (c.type == RouteProcessorChange::MeterPointChange && c.meter_visibly_changed == false) {
1937                 /* the meter has moved, but it was and still is invisible to the user, so nothing to do */
1938                 return;
1939         }
1940
1941         redisplay_processors ();
1942 }
1943
1944 void
1945 ProcessorBox::redisplay_processors ()
1946 {
1947         ENSURE_GUI_THREAD (*this, &ProcessorBox::redisplay_processors);
1948         bool     fader_seen;
1949
1950         if (no_processor_redisplay) {
1951                 return;
1952         }
1953
1954         processor_display.clear ();
1955
1956         _visible_prefader_processors = 0;
1957         fader_seen = false;
1958
1959         _route->foreach_processor (sigc::bind (sigc::mem_fun (*this, &ProcessorBox::help_count_visible_prefader_processors),
1960                                                &_visible_prefader_processors, &fader_seen));
1961
1962         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::add_processor_to_display));
1963         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::maybe_add_processor_to_ui_list));
1964         setup_entry_positions ();
1965 }
1966
1967 /** Add a ProcessorWindowProxy for a processor to our list, if that processor does
1968  *  not already have one.
1969  */
1970 void
1971 ProcessorBox::maybe_add_processor_to_ui_list (boost::weak_ptr<Processor> w)
1972 {
1973         boost::shared_ptr<Processor> p = w.lock ();
1974         if (!p) {
1975                 return;
1976         }
1977         if (p->window_proxy()) {
1978                 return;
1979         }
1980
1981         /* not on the list; add it */
1982
1983         string loc;
1984 #if 0 // is this still needed? Why?
1985         if (_parent_strip) {
1986                 if (_parent_strip->mixer_owned()) {
1987                         loc = X_("M");
1988                 } else {
1989                         loc = X_("R");
1990                 }
1991         } else {
1992                 loc = X_("P");
1993         }
1994 #else
1995         loc = X_("P");
1996 #endif
1997
1998         ProcessorWindowProxy* wp = new ProcessorWindowProxy (
1999                 string_compose ("%1-%2-%3", loc, _route->id(), p->id()),
2000                 this,
2001                 w);
2002
2003         const XMLNode* ui_xml = _session->extra_xml (X_("UI"));
2004
2005         if (ui_xml) {
2006                 wp->set_state (*ui_xml, 0);
2007         }
2008
2009         void* existing_ui = p->get_ui ();
2010
2011         if (existing_ui) {
2012                 wp->use_window (*(reinterpret_cast<Gtk::Window*>(existing_ui)));
2013         }
2014
2015         p->set_window_proxy (wp);
2016         WM::Manager::instance().register_window (wp);
2017 }
2018
2019 void
2020 ProcessorBox::help_count_visible_prefader_processors (boost::weak_ptr<Processor> p, uint32_t* cnt, bool* amp_seen)
2021 {
2022         boost::shared_ptr<Processor> processor (p.lock ());
2023
2024         if (processor && ( processor->display_to_user()
2025 #ifndef NDEBUG
2026                             || show_all_processors
2027 #endif
2028                          )
2029            ) {
2030
2031                 if (boost::dynamic_pointer_cast<Amp>(processor) && 
2032                     boost::dynamic_pointer_cast<Amp>(processor)->gain_control()->parameter().type() == GainAutomation) {
2033                         *amp_seen = true;
2034                 } else {
2035                         if (!*amp_seen) {
2036                                 (*cnt)++;
2037                         }
2038                 }
2039         }
2040 }
2041
2042 void
2043 ProcessorBox::add_processor_to_display (boost::weak_ptr<Processor> p)
2044 {
2045         boost::shared_ptr<Processor> processor (p.lock ());
2046
2047         if (!processor || ( !processor->display_to_user()
2048 #ifndef NDEBUG
2049                             && !show_all_processors
2050 #endif
2051                           )
2052            ) {
2053                 return;
2054         }
2055
2056         boost::shared_ptr<PluginInsert> plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor);
2057
2058         ProcessorEntry* e = 0;
2059         if (plugin_insert) {
2060                 e = new PluginInsertProcessorEntry (this, plugin_insert, _width);
2061         } else {
2062                 e = new ProcessorEntry (this, processor, _width);
2063         }
2064
2065         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
2066         boost::shared_ptr<PortInsert> ext = boost::dynamic_pointer_cast<PortInsert> (processor);
2067         boost::shared_ptr<UnknownProcessor> stub = boost::dynamic_pointer_cast<UnknownProcessor> (processor);
2068
2069         //faders and meters are not deletable, copy/paste-able, so they shouldn't be selectable
2070         if (!send && !plugin_insert && !ext && !stub)
2071                 e->set_selectable(false);
2072
2073         bool mark_send_visible = false;
2074         if (send && _parent_strip) {
2075                 /* show controls of new sends by default */
2076                 GUIObjectState& st = _parent_strip->gui_object_state ();
2077                 XMLNode* strip = st.get_or_add_node (_parent_strip->state_id ());
2078                 assert (strip);
2079                 /* check if state exists, if not it must be a new send */
2080                 if (!st.get_node(strip, e->state_id())) {
2081                         mark_send_visible = true;
2082                 }
2083         }
2084
2085         /* Set up this entry's state from the GUIObjectState */
2086         XMLNode* proc = entry_gui_object_state (e);
2087         if (proc) {
2088                 e->set_control_state (proc);
2089         }
2090
2091         if (mark_send_visible) {
2092                 e->show_all_controls ();
2093         }
2094
2095         if (plugin_insert
2096 #ifdef MIXBUS
2097                         && !plugin_insert->plugin(0)->is_channelstrip()
2098 #endif
2099                  )
2100         {
2101                 processor_display.add_child (e, drag_targets());
2102         } else {
2103                 processor_display.add_child (e, drag_targets_noplugin());
2104         }
2105 }
2106
2107 void
2108 ProcessorBox::reordered ()
2109 {
2110         compute_processor_sort_keys ();
2111         setup_entry_positions ();
2112 }
2113
2114 void
2115 ProcessorBox::setup_entry_positions ()
2116 {
2117         list<ProcessorEntry*> children = processor_display.children ();
2118         bool pre_fader = true;
2119
2120         uint32_t num = 0;
2121         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2122                 if (boost::dynamic_pointer_cast<Amp>((*i)->processor()) && 
2123                     boost::dynamic_pointer_cast<Amp>((*i)->processor())->gain_control()->parameter().type() == GainAutomation) {
2124                         pre_fader = false;
2125                         (*i)->set_position (ProcessorEntry::Fader, num++);
2126                 } else {
2127                         if (pre_fader) {
2128                                 (*i)->set_position (ProcessorEntry::PreFader, num++);
2129                         } else {
2130                                 (*i)->set_position (ProcessorEntry::PostFader, num++);
2131                         }
2132                 }
2133         }
2134 }
2135
2136 void
2137 ProcessorBox::compute_processor_sort_keys ()
2138 {
2139         list<ProcessorEntry*> children = processor_display.children ();
2140         Route::ProcessorList our_processors;
2141
2142         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
2143                 if ((*i)->processor()) {
2144                         our_processors.push_back ((*i)->processor ());
2145                 }
2146         }
2147
2148         if (_route->reorder_processors (our_processors)) {
2149                 /* Reorder failed, so report this to the user.  As far as I can see this must be done
2150                    in an idle handler: it seems that the redisplay_processors() that happens below destroys
2151                    widgets that were involved in the drag-and-drop on the processor list, which causes problems
2152                    when the drag is torn down after this handler function is finished.
2153                 */
2154                 Glib::signal_idle().connect_once (sigc::mem_fun (*this, &ProcessorBox::report_failed_reorder));
2155         }
2156 }
2157
2158 void
2159 ProcessorBox::report_failed_reorder ()
2160 {
2161         /* reorder failed, so redisplay */
2162
2163         redisplay_processors ();
2164
2165         /* now tell them about the problem */
2166
2167         ArdourDialog dialog (_("Plugin Incompatibility"));
2168         Label label;
2169
2170         label.set_text (_("\
2171 You cannot reorder these plugins/sends/inserts\n\
2172 in that way because the inputs and\n\
2173 outputs will not work correctly."));
2174
2175         dialog.get_vbox()->set_border_width (12);
2176         dialog.get_vbox()->pack_start (label);
2177         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
2178
2179         dialog.set_name (X_("PluginIODialog"));
2180         dialog.set_modal (true);
2181         dialog.show_all ();
2182
2183         dialog.run ();
2184 }
2185
2186 void
2187 ProcessorBox::rename_processors ()
2188 {
2189         ProcSelection to_be_renamed;
2190
2191         get_selected_processors (to_be_renamed);
2192
2193         if (to_be_renamed.empty()) {
2194                 return;
2195         }
2196
2197         for (ProcSelection::iterator i = to_be_renamed.begin(); i != to_be_renamed.end(); ++i) {
2198                 rename_processor (*i);
2199         }
2200 }
2201
2202 bool
2203 ProcessorBox::can_cut () const
2204 {
2205         vector<boost::shared_ptr<Processor> > sel;
2206
2207         get_selected_processors (sel);
2208
2209         /* cut_processors () does not cut inserts */
2210
2211         for (vector<boost::shared_ptr<Processor> >::const_iterator i = sel.begin (); i != sel.end (); ++i) {
2212
2213                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
2214                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
2215                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
2216                         return true;
2217                 }
2218         }
2219
2220         return false;
2221 }
2222
2223 bool
2224 ProcessorBox::stub_processor_selected () const
2225 {
2226         vector<boost::shared_ptr<Processor> > sel;
2227
2228         get_selected_processors (sel);
2229
2230         for (vector<boost::shared_ptr<Processor> >::const_iterator i = sel.begin (); i != sel.end (); ++i) {
2231                 if (boost::dynamic_pointer_cast<UnknownProcessor>((*i)) != 0) {
2232                         return true;
2233                 }
2234         }
2235
2236         return false;
2237 }
2238
2239 void
2240 ProcessorBox::cut_processors (const ProcSelection& to_be_removed)
2241 {
2242         if (to_be_removed.empty()) {
2243                 return;
2244         }
2245
2246         XMLNode* node = new XMLNode (X_("cut"));
2247         Route::ProcessorList to_cut;
2248
2249         no_processor_redisplay = true;
2250         for (ProcSelection::const_iterator i = to_be_removed.begin(); i != to_be_removed.end(); ++i) {
2251                 // Cut only plugins, sends and returns
2252                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
2253                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
2254                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
2255
2256                         Window* w = get_processor_ui (*i);
2257
2258                         if (w) {
2259                                 w->hide ();
2260                         }
2261
2262                         XMLNode& child ((*i)->get_state());
2263                         node->add_child_nocopy (child);
2264                         to_cut.push_back (*i);
2265                 }
2266         }
2267
2268         if (_route->remove_processors (to_cut) != 0) {
2269                 delete node;
2270                 no_processor_redisplay = false;
2271                 return;
2272         }
2273
2274         _rr_selection.set (node);
2275
2276         no_processor_redisplay = false;
2277         redisplay_processors ();
2278 }
2279
2280 void
2281 ProcessorBox::copy_processors (const ProcSelection& to_be_copied)
2282 {
2283         if (to_be_copied.empty()) {
2284                 return;
2285         }
2286
2287         XMLNode* node = new XMLNode (X_("copy"));
2288
2289         for (ProcSelection::const_iterator i = to_be_copied.begin(); i != to_be_copied.end(); ++i) {
2290                 // Copy only plugins, sends, returns
2291                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
2292                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
2293                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
2294                         node->add_child_nocopy ((*i)->get_state());
2295                 }
2296         }
2297
2298         _rr_selection.set (node);
2299 }
2300
2301 void
2302 ProcessorBox::delete_processors (const ProcSelection& targets)
2303 {
2304         if (targets.empty()) {
2305                 return;
2306         }
2307
2308         no_processor_redisplay = true;
2309
2310         for (ProcSelection::const_iterator i = targets.begin(); i != targets.end(); ++i) {
2311
2312                 Window* w = get_processor_ui (*i);
2313
2314                 if (w) {
2315                         w->hide ();
2316                 }
2317
2318                 _route->remove_processor(*i);
2319         }
2320
2321         no_processor_redisplay = false;
2322         redisplay_processors ();
2323 }
2324
2325 void
2326 ProcessorBox::delete_dragged_processors (const list<boost::shared_ptr<Processor> >& procs)
2327 {
2328         list<boost::shared_ptr<Processor> >::const_iterator x;
2329
2330         no_processor_redisplay = true;
2331         for (x = procs.begin(); x != procs.end(); ++x) {
2332
2333                 Window* w = get_processor_ui (*x);
2334
2335                 if (w) {
2336                         w->hide ();
2337                 }
2338
2339                 _route->remove_processor(*x);
2340         }
2341
2342         no_processor_redisplay = false;
2343         redisplay_processors ();
2344 }
2345
2346 gint
2347 ProcessorBox::idle_delete_processor (boost::weak_ptr<Processor> weak_processor)
2348 {
2349         boost::shared_ptr<Processor> processor (weak_processor.lock());
2350
2351         if (!processor) {
2352                 return false;
2353         }
2354
2355         /* NOT copied to _mixer.selection() */
2356
2357         no_processor_redisplay = true;
2358         _route->remove_processor (processor);
2359         no_processor_redisplay = false;
2360         redisplay_processors ();
2361
2362         return false;
2363 }
2364
2365 void
2366 ProcessorBox::rename_processor (boost::shared_ptr<Processor> processor)
2367 {
2368         ArdourPrompter name_prompter (true);
2369         string result;
2370         name_prompter.set_title (_("Rename Processor"));
2371         name_prompter.set_prompt (_("New name:"));
2372         name_prompter.set_initial_text (processor->name());
2373         name_prompter.add_button (_("Rename"), Gtk::RESPONSE_ACCEPT);
2374         name_prompter.set_response_sensitive (Gtk::RESPONSE_ACCEPT, false);
2375         name_prompter.show_all ();
2376
2377         switch (name_prompter.run ()) {
2378
2379         case Gtk::RESPONSE_ACCEPT:
2380                 name_prompter.get_result (result);
2381                 if (result.length()) {
2382
2383                        int tries = 0;
2384                        string test = result;
2385
2386                        while (tries < 100) {
2387                                if (_session->io_name_is_legal (test)) {
2388                                        result = test;
2389                                        break;
2390                                }
2391                                tries++;
2392
2393                                test = string_compose ("%1-%2", result, tries);
2394                        }
2395
2396                        if (tries < 100) {
2397                                processor->set_name (result);
2398                        } else {
2399                                /* unlikely! */
2400                                ARDOUR_UI::instance()->popup_error
2401                                        (string_compose (_("At least 100 IO objects exist with a name like %1 - name not changed"), result));
2402                        }
2403                 }
2404                 break;
2405         }
2406
2407         return;
2408 }
2409
2410 void
2411 ProcessorBox::paste_processors ()
2412 {
2413         if (_rr_selection.processors.empty()) {
2414                 return;
2415         }
2416
2417         paste_processor_state (_rr_selection.processors.get_node().children(), boost::shared_ptr<Processor>());
2418 }
2419
2420 void
2421 ProcessorBox::paste_processors (boost::shared_ptr<Processor> before)
2422 {
2423
2424         if (_rr_selection.processors.empty()) {
2425                 return;
2426         }
2427
2428         paste_processor_state (_rr_selection.processors.get_node().children(), before);
2429 }
2430
2431 void
2432 ProcessorBox::paste_processor_state (const XMLNodeList& nlist, boost::shared_ptr<Processor> p)
2433 {
2434         XMLNodeConstIterator niter;
2435         list<boost::shared_ptr<Processor> > copies;
2436
2437         if (nlist.empty()) {
2438                 return;
2439         }
2440
2441         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2442
2443                 XMLProperty const * type = (*niter)->property ("type");
2444                 XMLProperty const * role = (*niter)->property ("role");
2445                 assert (type);
2446
2447                 boost::shared_ptr<Processor> p;
2448                 try {
2449                         if (type->value() == "meter" ||
2450                             type->value() == "main-outs" ||
2451                             type->value() == "amp" ||
2452                             type->value() == "intreturn") {
2453                                 /* do not paste meter, main outs, amp or internal returns */
2454                                 continue;
2455
2456                         } else if (type->value() == "intsend") {
2457
2458                                 /* aux sends are OK, but those used for
2459                                  * other purposes, are not.
2460                                  */
2461
2462                                 assert (role);
2463
2464                                 if (role->value() != "Aux") {
2465                                         continue;
2466                                 }
2467
2468                                 boost::shared_ptr<Pannable> sendpan(new Pannable (*_session));
2469                                 XMLNode n (**niter);
2470                                 InternalSend* s = new InternalSend (*_session, sendpan, _route->mute_master(),
2471                                                 _route, boost::shared_ptr<Route>(), Delivery::Aux);
2472
2473                                 IOProcessor::prepare_for_reset (n, s->name());
2474
2475                                 if (s->set_state (n, Stateful::loading_state_version)) {
2476                                         delete s;
2477                                         return;
2478                                 }
2479
2480                                 p.reset (s);
2481
2482                         } else if (type->value() == "send") {
2483
2484                                 boost::shared_ptr<Pannable> sendpan(new Pannable (*_session));
2485                                 XMLNode n (**niter);
2486
2487                                 Send* s = new Send (*_session, _route->pannable(), _route->mute_master());
2488
2489                                 IOProcessor::prepare_for_reset (n, s->name());
2490
2491                                 if (s->set_state (n, Stateful::loading_state_version)) {
2492                                         delete s;
2493                                         return;
2494                                 }
2495
2496                                 p.reset (s);
2497
2498                         } else if (type->value() == "return") {
2499
2500                                 XMLNode n (**niter);
2501                                 Return* r = new Return (*_session);
2502
2503                                 IOProcessor::prepare_for_reset (n, r->name());
2504
2505                                 if (r->set_state (n, Stateful::loading_state_version)) {
2506                                         delete r;
2507                                         return;
2508                                 }
2509
2510                                 p.reset (r);
2511
2512                         } else if (type->value() == "port") {
2513
2514                                 XMLNode n (**niter);
2515                                 PortInsert* pi = new PortInsert (*_session, _route->pannable (), _route->mute_master ());
2516
2517                                 IOProcessor::prepare_for_reset (n, pi->name());
2518
2519                                 if (pi->set_state (n, Stateful::loading_state_version)) {
2520                                         return;
2521                                 }
2522
2523                                 p.reset (pi);
2524
2525                         } else {
2526                                 /* XXX its a bit limiting to assume that everything else
2527                                    is a plugin.
2528                                 */
2529                                 p.reset (new PluginInsert (*_session));
2530                                 PBD::ID id = p->id();
2531                                 p->set_state (**niter, Stateful::current_state_version);
2532                                 boost::dynamic_pointer_cast<PluginInsert>(p)->update_id (id);
2533                         }
2534
2535                         copies.push_back (p);
2536                 }
2537
2538                 catch (...) {
2539                         error << _("plugin insert constructor failed") << endmsg;
2540                 }
2541         }
2542
2543         if (copies.empty()) {
2544                 return;
2545         }
2546
2547         if (_route->add_processors (copies, p)) {
2548
2549                 string msg = _(
2550                         "Copying the set of processors on the clipboard failed,\n\
2551 probably because the I/O configuration of the plugins\n\
2552 could not match the configuration of this track.");
2553                 MessageDialog am (msg);
2554                 am.run ();
2555         }
2556 }
2557
2558 void
2559 ProcessorBox::get_selected_processors (ProcSelection& processors) const
2560 {
2561         const list<ProcessorEntry*> selection = processor_display.selection ();
2562         for (list<ProcessorEntry*>::const_iterator i = selection.begin(); i != selection.end(); ++i) {
2563                 processors.push_back ((*i)->processor ());
2564         }
2565 }
2566
2567 void
2568 ProcessorBox::for_selected_processors (void (ProcessorBox::*method)(boost::shared_ptr<Processor>))
2569 {
2570         list<ProcessorEntry*> selection = processor_display.selection ();
2571         for (list<ProcessorEntry*>::iterator i = selection.begin(); i != selection.end(); ++i) {
2572                 (this->*method) ((*i)->processor ());
2573         }
2574 }
2575
2576 void
2577 ProcessorBox::all_visible_processors_active (bool state)
2578 {
2579         _route->all_visible_processors_active (state);
2580 }
2581
2582 void
2583 ProcessorBox::ab_plugins ()
2584 {
2585         _route->ab_plugins (ab_direction);
2586         ab_direction = !ab_direction;
2587 }
2588
2589
2590 void
2591 ProcessorBox::clear_processors ()
2592 {
2593         string prompt;
2594         vector<string> choices;
2595
2596         prompt = string_compose (_("Do you really want to remove all processors from %1?\n"
2597                                    "(this cannot be undone)"), _route->name());
2598
2599         choices.push_back (_("Cancel"));
2600         choices.push_back (_("Yes, remove them all"));
2601
2602         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
2603
2604         if (prompter.run () == 1) {
2605                 _route->clear_processors (PreFader);
2606                 _route->clear_processors (PostFader);
2607         }
2608 }
2609
2610 void
2611 ProcessorBox::clear_processors (Placement p)
2612 {
2613         string prompt;
2614         vector<string> choices;
2615
2616         if (p == PreFader) {
2617                 prompt = string_compose (_("Do you really want to remove all pre-fader processors from %1?\n"
2618                                            "(this cannot be undone)"), _route->name());
2619         } else {
2620                 prompt = string_compose (_("Do you really want to remove all post-fader processors from %1?\n"
2621                                            "(this cannot be undone)"), _route->name());
2622         }
2623
2624         choices.push_back (_("Cancel"));
2625         choices.push_back (_("Yes, remove them all"));
2626
2627         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
2628
2629         if (prompter.run () == 1) {
2630                 _route->clear_processors (p);
2631         }
2632 }
2633
2634 bool
2635 ProcessorBox::processor_can_be_edited (boost::shared_ptr<Processor> processor)
2636 {
2637         boost::shared_ptr<AudioTrack> at = boost::dynamic_pointer_cast<AudioTrack> (_route);
2638         if (at && at->freeze_state() == AudioTrack::Frozen) {
2639                 return false;
2640         }
2641
2642         if (
2643                 boost::dynamic_pointer_cast<Send> (processor) ||
2644                 boost::dynamic_pointer_cast<Return> (processor) ||
2645                 boost::dynamic_pointer_cast<PluginInsert> (processor) ||
2646                 boost::dynamic_pointer_cast<PortInsert> (processor)
2647                 ) {
2648                 return true;
2649         }
2650
2651         return false;
2652 }
2653
2654 bool
2655 ProcessorBox::one_processor_can_be_edited ()
2656 {
2657         list<ProcessorEntry*> selection = processor_display.selection ();
2658         list<ProcessorEntry*>::iterator i = selection.begin();
2659         while (i != selection.end() && processor_can_be_edited ((*i)->processor()) == false) {
2660                 ++i;
2661         }
2662
2663         return (i != selection.end());
2664 }
2665
2666 Gtk::Window*
2667 ProcessorBox::get_editor_window (boost::shared_ptr<Processor> processor, bool use_custom)
2668 {
2669         boost::shared_ptr<Send> send;
2670         boost::shared_ptr<InternalSend> internal_send;
2671         boost::shared_ptr<Return> retrn;
2672         boost::shared_ptr<PluginInsert> plugin_insert;
2673         boost::shared_ptr<PortInsert> port_insert;
2674         Window* gidget = 0;
2675
2676         /* This method may or may not return a Window, but if it does not it
2677          * will modify the parent mixer strip appearance layout to allow
2678          * "editing" the @param processor that was passed in.
2679          *
2680          * So for example, if the processor is an Amp (gain), the parent strip
2681          * will be forced back into a model where the fader controls the main gain.
2682          * If the processor is a send, then we map the send controls onto the
2683          * strip.
2684          *
2685          * Plugins and others will return a window for control.
2686          */
2687
2688         if (boost::dynamic_pointer_cast<AudioTrack>(_route) != 0) {
2689
2690                 if (boost::dynamic_pointer_cast<AudioTrack> (_route)->freeze_state() == AudioTrack::Frozen) {
2691                         return 0;
2692                 }
2693         }
2694
2695         if (boost::dynamic_pointer_cast<Amp> (processor) && boost::dynamic_pointer_cast<Amp> (processor)->gain_control()->parameter().type() == GainAutomation) {
2696
2697                 if (_parent_strip) {
2698                         _parent_strip->revert_to_default_display ();
2699                 }
2700
2701         } else if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
2702
2703                 if (!_session->engine().connected()) {
2704                         return 0;
2705                 }
2706
2707                 if (boost::dynamic_pointer_cast<InternalSend> (processor) == 0) {
2708
2709                         gidget = new SendUIWindow (send, _session);
2710                 }
2711
2712         } else if ((retrn = boost::dynamic_pointer_cast<Return> (processor)) != 0) {
2713
2714                 if (boost::dynamic_pointer_cast<InternalReturn> (retrn)) {
2715                         /* no GUI for these */
2716                         return 0;
2717                 }
2718
2719                 if (!_session->engine().connected()) {
2720                         return 0;
2721                 }
2722
2723                 boost::shared_ptr<Return> retrn = boost::dynamic_pointer_cast<Return> (processor);
2724
2725                 ReturnUIWindow *return_ui;
2726                 Window* w = get_processor_ui (retrn);
2727
2728                 if (w == 0) {
2729
2730                         return_ui = new ReturnUIWindow (retrn, _session);
2731                         return_ui->set_title (retrn->name ());
2732                         set_processor_ui (send, return_ui);
2733
2734                 } else {
2735                         return_ui = dynamic_cast<ReturnUIWindow *> (w);
2736                 }
2737
2738                 gidget = return_ui;
2739
2740         } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
2741
2742                 PluginUIWindow *plugin_ui;
2743
2744                 /* these are both allowed to be null */
2745
2746                 Window* w = get_processor_ui (plugin_insert);
2747
2748                 if (w == 0) {
2749                         plugin_ui = new PluginUIWindow (plugin_insert, false, use_custom);
2750                         plugin_ui->set_title (generate_processor_title (plugin_insert));
2751                         set_processor_ui (plugin_insert, plugin_ui);
2752
2753                 } else {
2754                         plugin_ui = dynamic_cast<PluginUIWindow *> (w);
2755                 }
2756
2757                 gidget = plugin_ui;
2758
2759         } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (processor)) != 0) {
2760
2761                 if (!_session->engine().connected()) {
2762                         MessageDialog msg ( _("Not connected to audio engine - no I/O changes are possible"));
2763                         msg.run ();
2764                         return 0;
2765                 }
2766
2767                 PortInsertWindow *io_selector;
2768
2769                 Window* w = get_processor_ui (port_insert);
2770
2771                 if (w == 0) {
2772                         io_selector = new PortInsertWindow (_session, port_insert);
2773                         set_processor_ui (port_insert, io_selector);
2774
2775                 } else {
2776                         io_selector = dynamic_cast<PortInsertWindow *> (w);
2777                 }
2778
2779                 gidget = io_selector;
2780         }
2781
2782         return gidget;
2783 }
2784
2785 Gtk::Window*
2786 ProcessorBox::get_generic_editor_window (boost::shared_ptr<Processor> processor)
2787 {
2788         boost::shared_ptr<PluginInsert> plugin_insert
2789                 = boost::dynamic_pointer_cast<PluginInsert>(processor);
2790
2791         if (!plugin_insert) {
2792                 return 0;
2793         }
2794
2795         PluginUIWindow* win = new PluginUIWindow (plugin_insert, true, false);
2796         win->set_title (generate_processor_title (plugin_insert));
2797
2798         return win;
2799 }
2800
2801 void
2802 ProcessorBox::register_actions ()
2803 {
2804         Glib::RefPtr<Gtk::ActionGroup> popup_act_grp = processor_box_actions.create_action_group (X_("ProcessorMenu"));
2805         Glib::RefPtr<Action> act;
2806
2807         /* new stuff */
2808         processor_box_actions.register_action (popup_act_grp, X_("newplugin"), _("New Plugin"),
2809                         sigc::ptr_fun (ProcessorBox::rb_choose_plugin));
2810
2811         act = processor_box_actions.register_action (popup_act_grp, X_("newinsert"), _("New Insert"),
2812                         sigc::ptr_fun (ProcessorBox::rb_choose_insert));
2813         ActionManager::engine_sensitive_actions.push_back (act);
2814         act = processor_box_actions.register_action (popup_act_grp, X_("newsend"), _("New External Send ..."),
2815                         sigc::ptr_fun (ProcessorBox::rb_choose_send));
2816         ActionManager::engine_sensitive_actions.push_back (act);
2817
2818         processor_box_actions.register_action (popup_act_grp, X_("newaux"), _("New Aux Send ..."));
2819
2820         processor_box_actions.register_action (popup_act_grp, X_("controls"), _("Controls"));
2821         processor_box_actions.register_action (popup_act_grp, X_("send_options"), _("Send Options"));
2822
2823         processor_box_actions.register_action (popup_act_grp, X_("clear"), _("Clear (all)"),
2824                         sigc::ptr_fun (ProcessorBox::rb_clear));
2825         processor_box_actions.register_action (popup_act_grp, X_("clear_pre"), _("Clear (pre-fader)"),
2826                         sigc::ptr_fun (ProcessorBox::rb_clear_pre));
2827         processor_box_actions.register_action (popup_act_grp, X_("clear_post"), _("Clear (post-fader)"),
2828                         sigc::ptr_fun (ProcessorBox::rb_clear_post));
2829
2830         /* standard editing stuff */
2831
2832         cut_action = Actions.register_action (popup_act_grp, X_("cut"), _("Cut"),
2833                                                             sigc::ptr_fun (ProcessorBox::rb_cut));
2834         copy_action = Actions.register_action (popup_act_grp, X_("copy"), _("Copy"),
2835                                                              sigc::ptr_fun (ProcessorBox::rb_copy));
2836         delete_action = Actions.register_action (popup_act_grp, X_("delete"), _("Delete"),
2837                                                                sigc::ptr_fun (ProcessorBox::rb_delete));
2838         
2839         ActionManager::plugin_selection_sensitive_actions.push_back (cut_action);
2840         ActionManager::plugin_selection_sensitive_actions.push_back (copy_action);
2841         ActionManager::plugin_selection_sensitive_actions.push_back (delete_action);
2842         
2843         paste_action = processor_box_actions.register_action (popup_act_grp, X_("paste"), _("Paste"),
2844                         sigc::ptr_fun (ProcessorBox::rb_paste));
2845         rename_action = processor_box_actions.register_action (popup_act_grp, X_("rename"), _("Rename"),
2846                         sigc::ptr_fun (ProcessorBox::rb_rename));
2847         processor_box_actions.register_action (popup_act_grp, X_("selectall"), _("Select All"),
2848                         sigc::ptr_fun (ProcessorBox::rb_select_all));
2849         processor_box_actions.register_action (popup_act_grp, X_("deselectall"), _("Deselect All"),
2850                         sigc::ptr_fun (ProcessorBox::rb_deselect_all));
2851
2852         /* activation etc. */
2853
2854         processor_box_actions.register_action (popup_act_grp, X_("activate_all"), _("Activate All"),
2855                         sigc::ptr_fun (ProcessorBox::rb_activate_all));
2856         processor_box_actions.register_action (popup_act_grp, X_("deactivate_all"), _("Deactivate All"),
2857                         sigc::ptr_fun (ProcessorBox::rb_deactivate_all));
2858         processor_box_actions.register_action (popup_act_grp, X_("ab_plugins"), _("A/B Plugins"),
2859                         sigc::ptr_fun (ProcessorBox::rb_ab_plugins));
2860
2861         /* show editors */
2862         edit_action = processor_box_actions.register_action (
2863                 popup_act_grp, X_("edit"), _("Edit..."),
2864                 sigc::ptr_fun (ProcessorBox::rb_edit));
2865
2866         edit_generic_action = processor_box_actions.register_action (
2867                 popup_act_grp, X_("edit-generic"), _("Edit with generic controls..."),
2868                 sigc::ptr_fun (ProcessorBox::rb_edit_generic));
2869 }
2870
2871 void
2872 ProcessorBox::rb_edit_generic ()
2873 {
2874         if (_current_processor_box == 0) {
2875                 return;
2876         }
2877
2878         _current_processor_box->for_selected_processors (&ProcessorBox::generic_edit_processor);
2879 }
2880
2881 void
2882 ProcessorBox::rb_ab_plugins ()
2883 {
2884         if (_current_processor_box == 0) {
2885                 return;
2886         }
2887
2888         _current_processor_box->ab_plugins ();
2889 }
2890
2891 void
2892 ProcessorBox::rb_choose_plugin ()
2893 {
2894         if (_current_processor_box == 0) {
2895                 return;
2896         }
2897         _current_processor_box->choose_plugin ();
2898 }
2899
2900 void
2901 ProcessorBox::rb_choose_insert ()
2902 {
2903         if (_current_processor_box == 0) {
2904                 return;
2905         }
2906         _current_processor_box->choose_insert ();
2907 }
2908
2909 void
2910 ProcessorBox::rb_choose_send ()
2911 {
2912         if (_current_processor_box == 0) {
2913                 return;
2914         }
2915         _current_processor_box->choose_send ();
2916 }
2917
2918 void
2919 ProcessorBox::rb_choose_aux (boost::weak_ptr<Route> wr)
2920 {
2921         if (_current_processor_box == 0) {
2922                 return;
2923         }
2924
2925         _current_processor_box->choose_aux (wr);
2926 }
2927
2928 void
2929 ProcessorBox::rb_clear ()
2930 {
2931         if (_current_processor_box == 0) {
2932                 return;
2933         }
2934
2935         _current_processor_box->clear_processors ();
2936 }
2937
2938
2939 void
2940 ProcessorBox::rb_clear_pre ()
2941 {
2942         if (_current_processor_box == 0) {
2943                 return;
2944         }
2945
2946         _current_processor_box->clear_processors (PreFader);
2947 }
2948
2949
2950 void
2951 ProcessorBox::rb_clear_post ()
2952 {
2953         if (_current_processor_box == 0) {
2954                 return;
2955         }
2956
2957         _current_processor_box->clear_processors (PostFader);
2958 }
2959
2960 void
2961 ProcessorBox::rb_cut ()
2962 {
2963         if (_current_processor_box == 0) {
2964                 return;
2965         }
2966
2967         _current_processor_box->processor_operation (ProcessorsCut);
2968 }
2969
2970 void
2971 ProcessorBox::rb_delete ()
2972 {
2973         if (_current_processor_box == 0) {
2974                 return;
2975         }
2976
2977         _current_processor_box->processor_operation (ProcessorsDelete);
2978 }
2979
2980 void
2981 ProcessorBox::rb_copy ()
2982 {
2983         if (_current_processor_box == 0) {
2984                 return;
2985         }
2986         _current_processor_box->processor_operation (ProcessorsCopy);
2987 }
2988
2989 void
2990 ProcessorBox::rb_paste ()
2991 {
2992         if (_current_processor_box == 0) {
2993                 return;
2994         }
2995
2996         _current_processor_box->processor_operation (ProcessorsPaste);
2997 }
2998
2999 void
3000 ProcessorBox::rb_rename ()
3001 {
3002         if (_current_processor_box == 0) {
3003                 return;
3004         }
3005         _current_processor_box->rename_processors ();
3006 }
3007
3008 void
3009 ProcessorBox::rb_select_all ()
3010 {
3011         if (_current_processor_box == 0) {
3012                 return;
3013         }
3014
3015         _current_processor_box->processor_operation (ProcessorsSelectAll);
3016 }
3017
3018 void
3019 ProcessorBox::rb_deselect_all ()
3020 {
3021         if (_current_processor_box == 0) {
3022                 return;
3023         }
3024
3025         _current_processor_box->deselect_all_processors ();
3026 }
3027
3028 void
3029 ProcessorBox::rb_activate_all ()
3030 {
3031         if (_current_processor_box == 0) {
3032                 return;
3033         }
3034
3035         _current_processor_box->all_visible_processors_active (true);
3036 }
3037
3038 void
3039 ProcessorBox::rb_deactivate_all ()
3040 {
3041         if (_current_processor_box == 0) {
3042                 return;
3043         }
3044         _current_processor_box->all_visible_processors_active (false);
3045 }
3046
3047 void
3048 ProcessorBox::rb_edit ()
3049 {
3050         if (_current_processor_box == 0) {
3051                 return;
3052         }
3053
3054         _current_processor_box->for_selected_processors (&ProcessorBox::edit_processor);
3055 }
3056
3057 bool
3058 ProcessorBox::edit_aux_send (boost::shared_ptr<Processor> processor)
3059 {
3060         if (boost::dynamic_pointer_cast<InternalSend> (processor) == 0) {
3061                 return false;
3062         }
3063
3064         if (_parent_strip) {
3065                 boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
3066                 if (_parent_strip->current_delivery() == send) {
3067                         _parent_strip->revert_to_default_display ();
3068                 } else {
3069                         _parent_strip->show_send(send);
3070                 }
3071         }
3072         return true;
3073 }
3074
3075 void
3076 ProcessorBox::edit_processor (boost::shared_ptr<Processor> processor)
3077 {
3078         if (!processor) {
3079                 return;
3080         }
3081         if (edit_aux_send (processor)) {
3082                 return;
3083         }
3084
3085         ProcessorWindowProxy* proxy = find_window_proxy (processor);
3086
3087         if (proxy) {
3088                 proxy->set_custom_ui_mode (true);
3089                 proxy->show_the_right_window ();
3090         }
3091 }
3092
3093 void
3094 ProcessorBox::generic_edit_processor (boost::shared_ptr<Processor> processor)
3095 {
3096         if (!processor) {
3097                 return;
3098         }
3099         if (edit_aux_send (processor)) {
3100                 return;
3101         }
3102
3103         ProcessorWindowProxy* proxy = find_window_proxy (processor);
3104
3105         if (proxy) {
3106                 proxy->set_custom_ui_mode (false);
3107                 proxy->show_the_right_window ();
3108         }
3109 }
3110
3111 void
3112 ProcessorBox::route_property_changed (const PropertyChange& what_changed)
3113 {
3114         if (!what_changed.contains (ARDOUR::Properties::name)) {
3115                 return;
3116         }
3117
3118         ENSURE_GUI_THREAD (*this, &ProcessorBox::route_property_changed, what_changed);
3119
3120         boost::shared_ptr<Processor> processor;
3121         boost::shared_ptr<PluginInsert> plugin_insert;
3122         boost::shared_ptr<Send> send;
3123
3124         list<ProcessorEntry*> children = processor_display.children();
3125
3126         for (list<ProcessorEntry*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
3127
3128                 processor = (*iter)->processor ();
3129
3130                 if (!processor) {
3131                         continue;
3132                 }
3133
3134                 Window* w = get_processor_ui (processor);
3135
3136                 if (!w) {
3137                         continue;
3138                 }
3139
3140                 /* rename editor windows for sends and plugins */
3141
3142                 if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
3143                         w->set_title (send->name ());
3144                 } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
3145                         w->set_title (generate_processor_title (plugin_insert));
3146                 }
3147         }
3148 }
3149
3150 string
3151 ProcessorBox::generate_processor_title (boost::shared_ptr<PluginInsert> pi)
3152 {
3153         string maker = pi->plugin()->maker() ? pi->plugin()->maker() : "";
3154         string::size_type email_pos;
3155
3156         if ((email_pos = maker.find_first_of ('<')) != string::npos) {
3157                 maker = maker.substr (0, email_pos - 1);
3158         }
3159
3160         if (maker.length() > 32) {
3161                 maker = maker.substr (0, 32);
3162                 maker += " ...";
3163         }
3164
3165         SessionObject* owner = pi->owner();
3166
3167         if (owner) {
3168                 return string_compose(_("%1: %2 (by %3)"), owner->name(), pi->name(), maker);
3169         } else {
3170                 return string_compose(_("%1 (by %2)"), pi->name(), maker);
3171         }
3172 }
3173
3174 /** @param p Processor.
3175  *  @return the UI window for \a p.
3176  */
3177 Window *
3178 ProcessorBox::get_processor_ui (boost::shared_ptr<Processor> p) const
3179 {
3180         ProcessorWindowProxy* wp = p->window_proxy();
3181         if (wp) {
3182                 return wp->get ();
3183         }
3184         return 0;
3185 }
3186
3187 /** Make a note of the UI window that a processor is using.
3188  *  @param p Processor.
3189  *  @param w UI window.
3190  */
3191 void
3192 ProcessorBox::set_processor_ui (boost::shared_ptr<Processor> p, Gtk::Window* w)
3193 {
3194         assert (p->window_proxy());
3195         p->set_ui (w);
3196         p->window_proxy()->use_window (*w);
3197 }
3198
3199 void
3200 ProcessorBox::mixer_strip_delivery_changed (boost::weak_ptr<Delivery> w)
3201 {
3202         boost::shared_ptr<Delivery> d = w.lock ();
3203         if (!d) {
3204                 return;
3205         }
3206
3207         list<ProcessorEntry*> children = processor_display.children ();
3208         list<ProcessorEntry*>::const_iterator i = children.begin();
3209         while (i != children.end() && (*i)->processor() != d) {
3210                 ++i;
3211         }
3212
3213         if (i == children.end()) {
3214                 processor_display.set_active (0);
3215         } else {
3216                 processor_display.set_active (*i);
3217         }
3218 }
3219
3220 /** Called to repair the damage of Editor::show_window doing a show_all() */
3221 void
3222 ProcessorBox::hide_things ()
3223 {
3224         list<ProcessorEntry*> c = processor_display.children ();
3225         for (list<ProcessorEntry*>::iterator i = c.begin(); i != c.end(); ++i) {
3226                 (*i)->hide_things ();
3227         }
3228 }
3229
3230 void
3231 ProcessorBox::processor_menu_unmapped ()
3232 {
3233         processor_display.remove_placeholder ();
3234 }
3235
3236 XMLNode *
3237 ProcessorBox::entry_gui_object_state (ProcessorEntry* entry)
3238 {
3239         if (!_parent_strip) {
3240                 return 0;
3241         }
3242
3243         GUIObjectState& st = _parent_strip->gui_object_state ();
3244
3245         XMLNode* strip = st.get_or_add_node (_parent_strip->state_id ());
3246         assert (strip);
3247         return st.get_or_add_node (strip, entry->state_id());
3248 }
3249
3250 void
3251 ProcessorBox::update_gui_object_state (ProcessorEntry* entry)
3252 {
3253         XMLNode* proc = entry_gui_object_state (entry);
3254         if (!proc) {
3255                 return;
3256         }
3257
3258         /* XXX: this is a bit inefficient; we just remove all child nodes and re-add them */
3259         proc->remove_nodes_and_delete (X_("Object"));
3260         entry->add_control_state (proc);
3261 }
3262
3263 bool
3264 ProcessorBox::is_editor_mixer_strip() const
3265 {
3266         return _parent_strip && !_parent_strip->mixer_owned();
3267 }
3268
3269 ProcessorWindowProxy::ProcessorWindowProxy (string const & name, ProcessorBox* box, boost::weak_ptr<Processor> processor)
3270         : WM::ProxyBase (name, string())
3271         , _processor_box (box)
3272         , _processor (processor)
3273         , is_custom (false)
3274         , want_custom (false)
3275 {
3276         boost::shared_ptr<Processor> p = _processor.lock ();
3277         if (!p) {
3278                 return;
3279         }
3280         p->DropReferences.connect (going_away_connection, MISSING_INVALIDATOR, boost::bind (&ProcessorWindowProxy::processor_going_away, this), gui_context());
3281 }
3282
3283 ProcessorWindowProxy::~ProcessorWindowProxy()
3284 {
3285         /* processor window proxies do not own the windows they create with
3286          * ::get(), so set _window to null before the normal WindowProxy method
3287          * deletes it.
3288          */
3289         _window = 0;
3290 }
3291
3292 void
3293 ProcessorWindowProxy::processor_going_away ()
3294 {
3295         delete _window;
3296         _window = 0;
3297         WM::Manager::instance().remove (this);
3298         /* should be no real reason to do this, since the object that would
3299            send DropReferences is about to be deleted, but lets do it anyway.
3300         */
3301         going_away_connection.disconnect();
3302 }
3303
3304 ARDOUR::SessionHandlePtr*
3305 ProcessorWindowProxy::session_handle()
3306 {
3307         /* we don't care */
3308         return 0;
3309 }
3310
3311 XMLNode&
3312 ProcessorWindowProxy::get_state ()
3313 {
3314         XMLNode *node;
3315         node = &ProxyBase::get_state();
3316         node->add_property (X_("custom-ui"), is_custom? X_("yes") : X_("no"));
3317         return *node;
3318 }
3319
3320 int
3321 ProcessorWindowProxy::set_state (const XMLNode& node, int /*version*/)
3322 {
3323         XMLNodeList children = node.children ();
3324         XMLNodeList::const_iterator i = children.begin ();
3325         while (i != children.end()) {
3326                 XMLProperty* prop = (*i)->property (X_("name"));
3327                 if ((*i)->name() == X_("Window") && prop && prop->value() == _name) {
3328                         break;
3329                 }
3330                 ++i;
3331         }
3332
3333         if (i != children.end()) {
3334                 XMLProperty* prop;
3335                 if ((prop = (*i)->property (X_("custom-ui"))) != 0) {
3336                         want_custom = PBD::string_is_affirmative (prop->value ());
3337                 }
3338         }
3339
3340         return ProxyBase::set_state (node, 0);
3341 }
3342
3343 Gtk::Window*
3344 ProcessorWindowProxy::get (bool create)
3345 {
3346         boost::shared_ptr<Processor> p = _processor.lock ();
3347
3348         if (!p) {
3349                 return 0;
3350         }
3351         if (_window && (is_custom != want_custom)) {
3352                 /* drop existing window - wrong type */
3353                 drop_window ();
3354         }
3355
3356         if (!_window) {
3357                 if (!create) {
3358                         return 0;
3359                 }
3360
3361                 is_custom = want_custom;
3362                 _window = _processor_box->get_editor_window (p, is_custom);
3363
3364                 if (_window) {
3365                         setup ();
3366                 }
3367         }
3368
3369         return _window;
3370 }
3371
3372 void
3373 ProcessorWindowProxy::show_the_right_window ()
3374 {
3375         if (_window && (is_custom != want_custom)) {
3376                 /* drop existing window - wrong type */
3377                 drop_window ();
3378                 get (true);
3379                 setup ();
3380                 assert (_window);
3381                 is_custom = want_custom;
3382         }
3383
3384         toggle ();
3385 }