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