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