2eaeeb83f77a78c6c5d49405618e00910b508acc
[ardour.git] / gtk2_ardour / processor_box.cc
1 /*
2     Copyright (C) 2000-2004 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <cmath>
25 #include <iostream>
26 #include <set>
27
28 #include <sigc++/bind.h>
29
30 #include "pbd/convert.h"
31
32 #include <glibmm/miscutils.h>
33
34 #include <gtkmm/messagedialog.h>
35
36 #include <gtkmm2ext/gtk_ui.h>
37 #include <gtkmm2ext/utils.h>
38 #include <gtkmm2ext/choice.h>
39 #include <gtkmm2ext/utils.h>
40 #include <gtkmm2ext/doi.h>
41
42 #include "ardour/amp.h"
43 #include "ardour/ardour.h"
44 #include "ardour/audio_track.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/internal_send.h"
47 #include "ardour/internal_return.h"
48 #include "ardour/ladspa_plugin.h"
49 #include "ardour/meter.h"
50 #include "ardour/plugin_insert.h"
51 #include "ardour/port_insert.h"
52 #include "ardour/profile.h"
53 #include "ardour/return.h"
54 #include "ardour/route.h"
55 #include "ardour/send.h"
56 #include "ardour/session.h"
57 #include "ardour/dB.h"
58
59 #include "actions.h"
60 #include "ardour_dialog.h"
61 #include "ardour_ui.h"
62 #include "gui_thread.h"
63 #include "io_selector.h"
64 #include "keyboard.h"
65 #include "mixer_ui.h"
66 #include "mixer_strip.h"
67 #include "plugin_selector.h"
68 #include "plugin_ui.h"
69 #include "port_insert_ui.h"
70 #include "processor_box.h"
71 #include "public_editor.h"
72 #include "return_ui.h"
73 #include "route_processor_selection.h"
74 #include "send_ui.h"
75 #include "utils.h"
76
77 #include "i18n.h"
78
79 #ifdef HAVE_AUDIOUNITS
80 class AUPluginUI;
81 #endif
82
83 using namespace std;
84 using namespace ARDOUR;
85 using namespace PBD;
86 using namespace Gtk;
87 using namespace Glib;
88 using namespace Gtkmm2ext;
89
90 ProcessorBox* ProcessorBox::_current_processor_box = 0;
91 RefPtr<Action> ProcessorBox::paste_action;
92 RefPtr<Action> ProcessorBox::cut_action;
93 RefPtr<Action> ProcessorBox::rename_action;
94 RefPtr<Action> ProcessorBox::edit_action;
95 Glib::RefPtr<Gdk::Pixbuf> SendProcessorEntry::_slider;
96
97 ProcessorEntry::ProcessorEntry (boost::shared_ptr<Processor> p, Width w)
98         : _processor (p)
99         , _width (w)
100         , _visual_state (Gtk::STATE_NORMAL)
101         , _position (PreFader)
102 {
103         _hbox.pack_start (_active, false, false);
104         _event_box.add (_name);
105         _hbox.pack_start (_event_box, true, true);
106         _vbox.pack_start (_hbox);
107         _frame.add (_vbox);
108
109         /* without this, the border is mis-drawn on some systems */
110         _vbox.set_border_width (1);
111
112         _name.set_alignment (0, 0.5);
113         _name.set_text (name ());
114         _name.set_padding (2, 2);
115
116         if (boost::dynamic_pointer_cast<Amp> (p)) {
117                 /* Fader processor gets a special look */
118                 _event_box.set_name ("ProcessorFader");
119                 _frame.set_name ("ProcessorFaderFrame");
120                 _name.set_padding (2, 4);
121         }
122
123         _active.set_active (_processor->active ());
124         _active.signal_toggled().connect (sigc::mem_fun (*this, &ProcessorEntry::active_toggled));
125         
126         _processor->ActiveChanged.connect (active_connection, invalidator (*this), boost::bind (&ProcessorEntry::processor_active_changed, this), gui_context());
127         _processor->PropertyChanged.connect (name_connection, invalidator (*this), ui_bind (&ProcessorEntry::processor_property_changed, this, _1), gui_context());
128 }
129
130 EventBox&
131 ProcessorEntry::action_widget ()
132 {
133         return _event_box;
134 }
135
136 Gtk::Widget&
137 ProcessorEntry::widget ()
138 {
139         return _frame;
140 }
141
142 string
143 ProcessorEntry::drag_text () const
144 {
145         return name ();
146 }
147
148 void
149 ProcessorEntry::set_visual_state (Gtk::StateType t)
150 {
151         _visual_state = t;
152         setup_visuals ();
153 }
154
155 void
156 ProcessorEntry::set_position (Position p)
157 {
158         _position = p;
159         setup_visuals ();
160 }
161
162 void
163 ProcessorEntry::setup_visuals ()
164 {
165         switch (_position) {
166         case PreFader:
167                 _event_box.set_name ("ProcessorPreFader");
168                 if (_visual_state == Gtk::STATE_NORMAL) {
169                         _frame.set_name ("ProcessorPreFaderFrame");
170                 }
171                 break;
172
173         case Fader:
174                 _event_box.set_name ("ProcessorFader");
175                 if (_visual_state == Gtk::STATE_NORMAL) {
176                         _frame.set_name ("ProcessorFaderFrame");
177                 }
178                 break;
179
180         case PostFader:
181                 _event_box.set_name ("ProcessorPostFader");
182                 if (_visual_state == Gtk::STATE_NORMAL) {
183                         _frame.set_name ("ProcessorPostFaderFrame");
184                 }
185                 break;
186         }
187
188         switch (_visual_state) {
189         case Gtk::STATE_NORMAL:
190                 /* _frame has been set up above */
191                 _event_box.set_state (Gtk::STATE_NORMAL);
192                 break;
193         case Gtk::STATE_SELECTED:
194                 _frame.set_name ("ProcessorFrameSelected");
195                 /* don't change the background of the box when it is selected */
196                 _event_box.set_state (Gtk::STATE_NORMAL);
197                 break;
198         case Gtk::STATE_ACTIVE:
199                 _frame.set_name ("ProcessorFrameActiveSend");
200                 _event_box.set_state (Gtk::STATE_ACTIVE);
201                 break;
202         default:
203                 break;
204         }
205 }
206         
207
208 boost::shared_ptr<Processor>
209 ProcessorEntry::processor () const
210 {
211         return _processor;
212 }
213
214 void
215 ProcessorEntry::set_enum_width (Width w)
216 {
217         _width = w;
218 }
219
220 void
221 ProcessorEntry::active_toggled ()
222 {
223         if (_active.get_active ()) {
224                 if (!_processor->active ()) {
225                         _processor->activate ();
226                 }
227         } else {
228                 if (_processor->active ()) {
229                         _processor->deactivate ();
230                 }
231         }
232 }
233
234 void
235 ProcessorEntry::processor_active_changed ()
236 {
237         if (_active.get_active () != _processor->active ()) {
238                 _active.set_active (_processor->active ());
239         }
240 }
241
242 void
243 ProcessorEntry::processor_property_changed (const PropertyChange& what_changed)
244 {
245         if (what_changed.contains (ARDOUR::Properties::name)) {
246                 _name.set_text (name ());
247         }
248 }
249
250 string
251 ProcessorEntry::name () const
252 {
253         boost::shared_ptr<Send> send;
254         string name_display;
255         
256         if ((send = boost::dynamic_pointer_cast<Send> (_processor)) != 0 &&
257             !boost::dynamic_pointer_cast<InternalSend>(_processor)) {
258                 
259                 name_display += '>';
260                 
261                 /* grab the send name out of its overall name */
262                 
263                 string::size_type lbracket, rbracket;
264                 lbracket = send->name().find ('[');
265                 rbracket = send->name().find (']');
266                 
267                 switch (_width) {
268                 case Wide:
269                         name_display += send->name().substr (lbracket+1, lbracket-rbracket-1);
270                         break;
271                 case Narrow:
272                         name_display += PBD::short_version (send->name().substr (lbracket+1, lbracket-rbracket-1), 4);
273                         break;
274                 }
275                 
276         } else {
277                 
278                 switch (_width) {
279                 case Wide:
280                         name_display += _processor->display_name();
281                         break;
282                 case Narrow:
283                         name_display += PBD::short_version (_processor->display_name(), 5);
284                         break;
285                 }
286                 
287         }
288         
289         return name_display;
290 }
291
292 SendProcessorEntry::SendProcessorEntry (boost::shared_ptr<Send> s, Width w)
293         : ProcessorEntry (s, w),
294           _send (s),
295           /* set the adjustment to a gain of 0dB so that the fader's default value is right */
296           _adjustment (0.781787, 0, 1, 0.01, 0.1),
297           _fader (_slider, &_adjustment, 0, false),
298           _ignore_gain_change (false)
299 {
300         _fader.set_name ("SendFader");
301         _fader.set_controllable (_send->amp()->gain_control ());
302         _vbox.pack_start (_fader);
303
304         _adjustment.signal_value_changed().connect (sigc::mem_fun (*this, &SendProcessorEntry::gain_adjusted));
305         _send->amp()->gain_control()->Changed.connect (send_gain_connection, invalidator (*this), boost::bind (&SendProcessorEntry::show_gain, this), gui_context());
306         show_gain ();
307 }
308
309 void
310 SendProcessorEntry::setup_slider_pix ()
311 {
312         _slider = ::get_icon ("fader_belt_h_thin");
313         assert (_slider);
314 }
315
316 void
317 SendProcessorEntry::show_gain ()
318 {
319         ENSURE_GUI_THREAD (*this, &SendProcessorEntry::show_gain)
320         
321         float const value = gain_to_slider_position (_send->amp()->gain ());
322
323         if (_adjustment.get_value() != value) {
324                 _ignore_gain_change = true;
325                 _adjustment.set_value (value);
326                 _ignore_gain_change = false;
327
328                 stringstream s;
329                 s.precision (1);
330                 s.setf (ios::fixed, ios::floatfield);
331                 s << accurate_coefficient_to_dB (_send->amp()->gain ()) << _("dB");
332                 _fader.set_tooltip_text (s.str ());
333         }
334 }
335
336 void
337 SendProcessorEntry::gain_adjusted ()
338 {
339         if (_ignore_gain_change) {
340                 return;
341         }
342
343         _send->amp()->set_gain (slider_position_to_gain (_adjustment.get_value()), this);
344 }
345
346 void
347 SendProcessorEntry::set_pixel_width (int p)
348 {
349         _fader.set_fader_length (p);
350 }
351
352 ProcessorBox::ProcessorBox (ARDOUR::Session* sess, boost::function<PluginSelector*()> get_plugin_selector,
353                             RouteRedirectSelection& rsel, MixerStrip* parent, bool owner_is_mixer)
354         : _parent_strip (parent)
355         , _owner_is_mixer (owner_is_mixer)
356         , ab_direction (true)
357         , _get_plugin_selector (get_plugin_selector)
358         , _placement(PreFader)
359         , _rr_selection(rsel)
360 {
361         set_session (sess);
362
363         _width = Wide;
364         processor_menu = 0;
365         send_action_menu = 0;
366         no_processor_redisplay = false;
367
368         processor_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
369         processor_scroller.add (processor_display);
370         pack_start (processor_scroller, true, true);
371
372         processor_display.set_flags (CAN_FOCUS);
373         processor_display.set_name ("ProcessorList");
374         processor_display.set_size_request (48, -1);
375         processor_display.set_data ("processorbox", this);
376         processor_display.set_spacing (2);
377
378         processor_display.signal_enter_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::enter_notify), false);
379         processor_display.signal_leave_notify_event().connect (sigc::mem_fun(*this, &ProcessorBox::leave_notify), false);
380
381         processor_display.signal_key_press_event().connect (sigc::mem_fun(*this, &ProcessorBox::processor_key_press_event));
382         processor_display.signal_key_release_event().connect (sigc::mem_fun(*this, &ProcessorBox::processor_key_release_event));
383
384         processor_display.ButtonPress.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_press_event));
385         processor_display.ButtonRelease.connect (sigc::mem_fun (*this, &ProcessorBox::processor_button_release_event));
386
387         processor_display.Reordered.connect (sigc::mem_fun (*this, &ProcessorBox::reordered));
388         processor_display.DropFromAnotherBox.connect (sigc::mem_fun (*this, &ProcessorBox::object_drop));
389         processor_display.SelectionChanged.connect (sigc::mem_fun (*this, &ProcessorBox::selection_changed));
390
391         if (parent) {
392                 parent->DeliveryChanged.connect (
393                         _mixer_strip_connections, invalidator (*this), ui_bind (&ProcessorBox::mixer_strip_delivery_changed, this, _1), gui_context ()
394                         );
395         }
396 }
397
398 ProcessorBox::~ProcessorBox ()
399 {
400 }
401
402 void
403 ProcessorBox::set_route (boost::shared_ptr<Route> r)
404 {
405         if (_route == r) {
406                 return;
407         }
408         
409         _route_connections.drop_connections();
410
411         /* new route: any existing block on processor redisplay must be meaningless */
412         no_processor_redisplay = false;
413         _route = r;
414
415         _route->processors_changed.connect (
416                 _route_connections, invalidator (*this), ui_bind (&ProcessorBox::route_processors_changed, this, _1), gui_context()
417                 );
418         
419         _route->DropReferences.connect (
420                 _route_connections, invalidator (*this), boost::bind (&ProcessorBox::route_going_away, this), gui_context()
421                 );
422         
423         _route->PropertyChanged.connect (
424                 _route_connections, invalidator (*this), ui_bind (&ProcessorBox::route_property_changed, this, _1), gui_context()
425                 );
426
427         redisplay_processors ();
428 }
429
430 void
431 ProcessorBox::route_going_away ()
432 {
433         /* don't keep updating display as processors are deleted */
434         no_processor_redisplay = true;
435 }
436
437 void
438 ProcessorBox::object_drop(DnDVBox<ProcessorEntry>* source, ProcessorEntry* position, Glib::RefPtr<Gdk::DragContext> const & context)
439 {
440         boost::shared_ptr<Processor> p;
441         if (position) {
442                 p = position->processor ();
443         }
444
445         list<ProcessorEntry*> children = source->selection ();
446         list<boost::shared_ptr<Processor> > procs;
447         for (list<ProcessorEntry*>::const_iterator i = children.begin(); i != children.end(); ++i) {
448                 procs.push_back ((*i)->processor ());
449         }
450
451         for (list<boost::shared_ptr<Processor> >::const_iterator i = procs.begin(); i != procs.end(); ++i) {
452                 XMLNode& state = (*i)->get_state ();
453                 XMLNodeList nlist;
454                 nlist.push_back (&state);
455                 paste_processor_state (nlist, p);
456                 delete &state;
457         }
458
459         /* since the dndvbox doesn't take care of this properly, we have to delete the originals
460            ourselves.
461         */
462
463         if ((context->get_suggested_action() == Gdk::ACTION_MOVE) && source) {
464                 ProcessorBox* other = reinterpret_cast<ProcessorBox*> (source->get_data ("processorbox"));
465                 if (other) {
466                         cerr << "source was another processor box, delete the selected items\n";
467                         other->delete_dragged_processors (procs);
468                 }
469         }
470 }
471
472 void
473 ProcessorBox::update()
474 {
475         redisplay_processors ();
476 }
477
478 void
479 ProcessorBox::set_width (Width w)
480 {
481         if (_width == w) {
482                 return;
483         }
484         
485         _width = w;
486
487         list<ProcessorEntry*> children = processor_display.children ();
488         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
489                 (*i)->set_enum_width (w);
490         }
491
492         redisplay_processors ();
493 }
494
495 void
496 ProcessorBox::build_send_action_menu ()
497 {
498         using namespace Menu_Helpers;
499
500         send_action_menu = new Menu;
501         send_action_menu->set_name ("ArdourContextMenu");
502         MenuList& items = send_action_menu->items();
503
504         items.push_back (MenuElem (_("New send"), sigc::mem_fun(*this, &ProcessorBox::new_send)));
505         items.push_back (MenuElem (_("Show send controls"), sigc::mem_fun(*this, &ProcessorBox::show_send_controls)));
506 }
507
508 Gtk::Menu*
509 ProcessorBox::build_possible_aux_menu ()
510 {
511         boost::shared_ptr<RouteList> rl = _session->get_routes_with_internal_returns();
512
513         if (rl->empty()) {
514                 return 0;
515         }
516
517         using namespace Menu_Helpers;
518         Menu* menu = manage (new Menu);
519         MenuList& items = menu->items();
520
521         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
522                 if (!_route->internal_send_for (*r) && *r != _route) {
523                         items.push_back (MenuElem ((*r)->name(), sigc::bind (sigc::ptr_fun (ProcessorBox::rb_choose_aux), boost::weak_ptr<Route>(*r))));
524                 }
525         }
526
527         return menu;
528 }
529
530 void
531 ProcessorBox::show_send_controls ()
532 {
533 }
534
535 void
536 ProcessorBox::new_send ()
537 {
538 }
539
540 void
541 ProcessorBox::show_processor_menu (gint arg)
542 {
543         if (processor_menu == 0) {
544                 processor_menu = build_processor_menu ();
545         }
546
547         Gtk::MenuItem* plugin_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/processormenu/newplugin"));
548
549         if (plugin_menu_item) {
550                 plugin_menu_item->set_submenu (*_get_plugin_selector()->plugin_menu());
551         }
552
553         Gtk::MenuItem* aux_menu_item = dynamic_cast<Gtk::MenuItem*>(ActionManager::get_widget("/processormenu/newaux"));
554
555         if (aux_menu_item) {
556                 Menu* m = build_possible_aux_menu();
557                 if (m && !m->items().empty()) {
558                         aux_menu_item->set_submenu (*m);
559                         aux_menu_item->set_sensitive (true);
560                 } else {
561                         /* stupid gtkmm: we need to pass a null reference here */
562                         gtk_menu_item_set_submenu (aux_menu_item->gobj(), 0);
563                         aux_menu_item->set_sensitive (false);
564                 }
565         }
566
567         cut_action->set_sensitive (can_cut());
568         paste_action->set_sensitive (!_rr_selection.processors.empty());
569
570         processor_menu->popup (1, arg);
571 }
572
573 bool
574 ProcessorBox::enter_notify (GdkEventCrossing*)
575 {
576         _current_processor_box = this;
577         Keyboard::magic_widget_grab_focus ();
578         processor_display.grab_focus ();
579
580         return false;
581 }
582
583 bool
584 ProcessorBox::leave_notify (GdkEventCrossing* ev)
585 {
586         switch (ev->detail) {
587         case GDK_NOTIFY_INFERIOR:
588                 break;
589         default:
590                 Keyboard::magic_widget_drop_focus ();
591         }
592
593         return false;
594 }
595
596 bool
597 ProcessorBox::processor_key_press_event (GdkEventKey *)
598 {
599         /* do real stuff on key release */
600         return false;
601 }
602
603 bool
604 ProcessorBox::processor_key_release_event (GdkEventKey *ev)
605 {
606         bool ret = false;
607         ProcSelection targets;
608
609         get_selected_processors (targets);
610
611         if (targets.empty()) {
612
613                 int x, y;
614                 processor_display.get_pointer (x, y);
615
616                 pair<ProcessorEntry *, double> const pointer = processor_display.get_child_at_position (y);
617
618                 if (pointer.first) {
619                         targets.push_back (pointer.first->processor ());
620                 }
621         }
622
623
624         switch (ev->keyval) {
625         case GDK_a:
626                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
627                         processor_display.select_all ();
628                         ret = true;
629                 } 
630                 break;
631
632         case GDK_c:
633                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
634                         copy_processors (targets);
635                         ret = true;
636                 }
637                 break;
638
639         case GDK_x:
640                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
641                         cut_processors (targets);
642                         ret = true;
643                 }
644                 break;
645
646         case GDK_v:
647                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
648                         if (targets.empty()) {
649                                 paste_processors ();
650                         } else {
651                                 paste_processors (targets.front());
652                         }
653                         ret = true;
654                 }
655                 break;
656
657         case GDK_Up:
658                 break;
659
660         case GDK_Down:
661                 break;
662
663         case GDK_Delete:
664         case GDK_BackSpace:
665                 delete_processors (targets);
666                 ret = true;
667                 break;
668
669         case GDK_Return:
670                 for (ProcSelection::iterator i = targets.begin(); i != targets.end(); ++i) {
671                         if ((*i)->active()) {
672                                 (*i)->deactivate ();
673                         } else {
674                                 (*i)->activate ();
675                         }
676                 }
677                 ret = true;
678                 break;
679
680         case GDK_slash:
681                 ab_plugins ();
682                 ret = true;
683                 break;
684
685         default:
686                 break;
687         }
688
689         return ret;
690 }
691
692 bool
693 ProcessorBox::processor_button_press_event (GdkEventButton *ev, ProcessorEntry* child)
694 {
695         boost::shared_ptr<Processor> processor;
696         if (child) {
697                 processor = child->processor ();
698         }
699         
700         int ret = false;
701         bool selected = processor_display.selected (child);
702
703         if (processor && (Keyboard::is_edit_event (ev) || (ev->button == 1 && ev->type == GDK_2BUTTON_PRESS))) {
704
705                 if (_session->engine().connected()) {
706                         /* XXX giving an error message here is hard, because we may be in the midst of a button press */
707                         toggle_edit_processor (processor);
708                 }
709                 ret = true;
710
711         } else if (processor && ev->button == 1 && selected) {
712
713                 // this is purely informational but necessary for route params UI
714                 ProcessorSelected (processor); // emit
715
716         } else if (!processor && ev->button == 1 && ev->type == GDK_2BUTTON_PRESS) {
717
718                 choose_plugin ();
719                 _get_plugin_selector()->show_manager ();
720         }
721
722         return ret;
723 }
724
725 bool
726 ProcessorBox::processor_button_release_event (GdkEventButton *ev, ProcessorEntry* child)
727 {
728         boost::shared_ptr<Processor> processor;
729         if (child) {
730                 processor = child->processor ();
731         }
732         
733         int ret = false;
734
735         if (processor && Keyboard::is_delete_event (ev)) {
736
737                 Glib::signal_idle().connect (sigc::bind (
738                                 sigc::mem_fun(*this, &ProcessorBox::idle_delete_processor),
739                                 boost::weak_ptr<Processor>(processor)));
740                 ret = true;
741
742         } else if (Keyboard::is_context_menu_event (ev)) {
743
744                 /* figure out if we are above or below the fader/amp processor,
745                    and set the next insert position appropriately.
746                 */
747
748                 if (processor) {
749                         if (_route->processor_is_prefader (processor)) {
750                                 _placement = PreFader;
751                         } else {
752                                 _placement = PostFader;
753                         }
754                 } else {
755                         _placement = PostFader;
756                 }
757
758                 show_processor_menu (ev->time);
759                 ret = true;
760
761         } else if (processor && Keyboard::is_button2_event (ev)
762 #ifndef GTKOSX
763                    && (Keyboard::no_modifier_keys_pressed (ev) && ((ev->state & Gdk::BUTTON2_MASK) == Gdk::BUTTON2_MASK))
764 #endif
765                 ) {
766
767                 /* button2-click with no/appropriate modifiers */
768
769                 if (processor->active()) {
770                         processor->deactivate ();
771                 } else {
772                         processor->activate ();
773                 }
774                 ret = true;
775
776         }
777
778         return false;
779 }
780
781 Menu *
782 ProcessorBox::build_processor_menu ()
783 {
784         processor_menu = dynamic_cast<Gtk::Menu*>(ActionManager::get_widget("/processormenu") );
785         processor_menu->set_name ("ArdourContextMenu");
786
787         show_all_children();
788
789         return processor_menu;
790 }
791
792 void
793 ProcessorBox::selection_changed ()
794 {
795         bool const sensitive = (processor_display.selection().empty()) ? false : true;
796         ActionManager::set_sensitive (ActionManager::plugin_selection_sensitive_actions, sensitive);
797         edit_action->set_sensitive (one_processor_can_be_edited ());
798
799         /* disallow rename for multiple selections and for plugin inserts */
800         rename_action->set_sensitive (
801                 processor_display.selection().size() == 1 && boost::dynamic_pointer_cast<PluginInsert> (processor_display.selection().front()->processor()) == 0
802                 );
803 }
804
805 void
806 ProcessorBox::select_all_processors ()
807 {
808         processor_display.select_all ();
809 }
810
811 void
812 ProcessorBox::deselect_all_processors ()
813 {
814         processor_display.select_none ();
815 }
816
817 void
818 ProcessorBox::choose_plugin ()
819 {
820         _get_plugin_selector()->set_interested_object (*this);
821 }
822
823 /** @return true if an error occurred, otherwise false */
824 bool
825 ProcessorBox::use_plugins (const SelectedPlugins& plugins)
826 {
827         for (SelectedPlugins::const_iterator p = plugins.begin(); p != plugins.end(); ++p) {
828
829                 boost::shared_ptr<Processor> processor (new PluginInsert (*_session, *p));
830
831                 Route::ProcessorStreams err_streams;
832
833                 if (Config->get_new_plugins_active()) {
834                         processor->activate ();
835                 }
836
837                 if (_route->add_processor (processor, _placement, &err_streams)) {
838                         weird_plugin_dialog (**p, err_streams);
839                         return true;
840                         // XXX SHAREDPTR delete plugin here .. do we even need to care?
841                 } else {
842
843                         if (Profile->get_sae()) {
844                                 processor->activate ();
845                         }
846                 }
847         }
848
849         return false;
850 }
851
852 void
853 ProcessorBox::weird_plugin_dialog (Plugin& p, Route::ProcessorStreams streams)
854 {
855         ArdourDialog dialog (_("Plugin Incompatibility"));
856         Label label;
857
858         string text = string_compose(_("You attempted to add the plugin \"%1\" at index %2.\n"),
859                         p.name(), streams.index);
860
861         bool has_midi  = streams.count.n_midi() > 0 || p.get_info()->n_inputs.n_midi() > 0;
862         bool has_audio = streams.count.n_audio() > 0 || p.get_info()->n_inputs.n_audio() > 0;
863
864         text += _("\nThis plugin has:\n");
865         if (has_midi) {
866                 uint32_t const n = p.get_info()->n_inputs.n_midi ();
867                 text += string_compose (ngettext ("\t%1 MIDI input", "\t%1 MIDI inputs", n), n);
868         }
869         if (has_audio) {
870                 uint32_t const n = p.get_info()->n_inputs.n_audio ();
871                 text += string_compose (ngettext ("\t%1 audio input", "\t%1 audio inputs", n), n);
872         }
873
874         text += _("\nBut at the insertion point, there are:\n");
875         if (has_midi) {
876                 uint32_t const n = streams.count.n_midi ();
877                 text += string_compose (ngettext ("\t%1 MIDI channel\n", "\t%1 MIDI channels\n", n), n);
878         }
879         if (has_audio) {
880                 uint32_t const n = streams.count.n_audio ();
881                 text += string_compose (ngettext ("\t%1 audio channel\n", "\t%1 audio channels\n", n), n);
882         }
883
884         text += string_compose (_("\n%1 is unable to insert this plugin here.\n"), PROGRAM_NAME);
885         label.set_text(text);
886
887         dialog.get_vbox()->pack_start (label);
888         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
889
890         dialog.set_name (X_("PluginIODialog"));
891         dialog.set_position (Gtk::WIN_POS_MOUSE);
892         dialog.set_modal (true);
893         dialog.show_all ();
894
895         dialog.run ();
896 }
897
898 void
899 ProcessorBox::choose_insert ()
900 {
901         boost::shared_ptr<Processor> processor (new PortInsert (*_session, _route->pannable(), _route->mute_master()));
902         _route->add_processor (processor, _placement);
903 }
904
905 /* Caller must not hold process lock */
906 void
907 ProcessorBox::choose_send ()
908 {
909         boost::shared_ptr<Send> send (new Send (*_session, _route->pannable(), _route->mute_master()));
910
911         /* make an educated guess at the initial number of outputs for the send */
912         ChanCount outs = (_session->master_out())
913                         ? _session->master_out()->n_outputs()
914                         : _route->n_outputs();
915
916         /* XXX need processor lock on route */
917         try {
918                 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock());
919                 send->output()->ensure_io (outs, false, this);
920         } catch (AudioEngine::PortRegistrationFailure& err) {
921                 error << string_compose (_("Cannot set up new send: %1"), err.what()) << endmsg;
922                 return;
923         }
924
925         /* let the user adjust the IO setup before creation.
926
927            Note: this dialog is NOT modal - we just leave it to run and it will
928            return when its Finished signal is emitted - typically when the window
929            is closed.
930          */
931
932         IOSelectorWindow *ios = new IOSelectorWindow (_session, send->output(), true);
933         ios->show ();
934
935         /* keep a reference to the send so it doesn't get deleted while
936            the IOSelectorWindow is doing its stuff
937         */
938         _processor_being_created = send;
939
940         ios->selector().Finished.connect (sigc::bind (
941                         sigc::mem_fun(*this, &ProcessorBox::send_io_finished),
942                         boost::weak_ptr<Processor>(send), ios));
943
944 }
945
946 void
947 ProcessorBox::send_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
948 {
949         boost::shared_ptr<Processor> processor (weak_processor.lock());
950
951         /* drop our temporary reference to the new send */
952         _processor_being_created.reset ();
953
954         if (!processor) {
955                 return;
956         }
957
958         switch (r) {
959         case IOSelector::Cancelled:
960                 // processor will go away when all shared_ptrs to it vanish
961                 break;
962
963         case IOSelector::Accepted:
964                 _route->add_processor (processor, _placement);
965                 if (Profile->get_sae()) {
966                         processor->activate ();
967                 }
968                 break;
969         }
970
971         delete_when_idle (ios);
972 }
973
974 void
975 ProcessorBox::return_io_finished (IOSelector::Result r, boost::weak_ptr<Processor> weak_processor, IOSelectorWindow* ios)
976 {
977         boost::shared_ptr<Processor> processor (weak_processor.lock());
978
979         /* drop our temporary reference to the new return */
980         _processor_being_created.reset ();
981
982         if (!processor) {
983                 return;
984         }
985
986         switch (r) {
987         case IOSelector::Cancelled:
988                 // processor will go away when all shared_ptrs to it vanish
989                 break;
990
991         case IOSelector::Accepted:
992                 _route->add_processor (processor, _placement);
993                 if (Profile->get_sae()) {
994                         processor->activate ();
995                 }
996                 break;
997         }
998
999         delete_when_idle (ios);
1000 }
1001
1002 void
1003 ProcessorBox::choose_aux (boost::weak_ptr<Route> wr)
1004 {
1005         if (!_route) {
1006                 return;
1007         }
1008
1009         boost::shared_ptr<Route> target = wr.lock();
1010
1011         if (!target) {
1012                 return;
1013         }
1014
1015         boost::shared_ptr<RouteList> rlist (new RouteList);
1016         rlist->push_back (_route);
1017
1018         _session->add_internal_sends (target, PreFader, rlist);
1019 }
1020
1021 void
1022 ProcessorBox::route_processors_changed (RouteProcessorChange c)
1023 {
1024         if (c.type == RouteProcessorChange::MeterPointChange && c.meter_visibly_changed == false) {
1025                 /* the meter has moved, but it was and still is invisible to the user, so nothing to do */
1026                 return;
1027         }
1028
1029         redisplay_processors ();
1030 }
1031
1032 void
1033 ProcessorBox::redisplay_processors ()
1034 {
1035         ENSURE_GUI_THREAD (*this, &ProcessorBox::redisplay_processors)
1036
1037         if (no_processor_redisplay) {
1038                 return;
1039         }
1040
1041         processor_display.clear ();
1042
1043         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::add_processor_to_display));
1044
1045         build_processor_tooltip (processor_eventbox, _("Inserts, sends & plugins:"));
1046
1047         for (list<ProcessorWindowProxy*>::iterator i = _processor_window_proxies.begin(); i != _processor_window_proxies.end(); ++i) {
1048                 (*i)->marked = false;
1049         }
1050                 
1051         _route->foreach_processor (sigc::mem_fun (*this, &ProcessorBox::maybe_add_processor_to_ui_list));
1052
1053         /* trim dead wood from the processor window proxy list */
1054
1055         list<ProcessorWindowProxy*>::iterator i = _processor_window_proxies.begin();
1056         while (i != _processor_window_proxies.end()) {
1057                 list<ProcessorWindowProxy*>::iterator j = i;
1058                 ++j;
1059
1060                 if (!(*i)->marked) {
1061                         ARDOUR_UI::instance()->remove_window_proxy (*i);
1062                         delete *i;
1063                         _processor_window_proxies.erase (i);
1064                 }
1065
1066                 i = j;
1067         }
1068
1069         setup_entry_positions ();
1070 }
1071
1072 /** Add a ProcessorWindowProxy for a processor to our list, if that processor does
1073  *  not already have one.
1074  */
1075 void
1076 ProcessorBox::maybe_add_processor_to_ui_list (boost::weak_ptr<Processor> w)
1077 {
1078         boost::shared_ptr<Processor> p = w.lock ();
1079         if (!p) {
1080                 return;
1081         }
1082
1083         list<ProcessorWindowProxy*>::iterator i = _processor_window_proxies.begin ();
1084         while (i != _processor_window_proxies.end()) {
1085
1086                 boost::shared_ptr<Processor> t = (*i)->processor().lock ();
1087                 
1088                 if (p == t) {
1089                         /* this processor is already on the list; done */
1090                         (*i)->marked = true;
1091                         return;
1092                 }
1093
1094                 ++i;
1095         }
1096
1097         /* not on the list; add it */
1098
1099         string loc;
1100         if (_parent_strip) {
1101                 if (_parent_strip->mixer_owned()) {
1102                         loc = X_("M");
1103                 } else {
1104                         loc = X_("R");
1105                 }
1106         } else {
1107                 loc = X_("P");
1108         }
1109         
1110         ProcessorWindowProxy* wp = new ProcessorWindowProxy (
1111                 string_compose ("%1-%2-%3", loc, _route->id(), p->id()),
1112                 _session->extra_xml (X_("UI")),
1113                 this,
1114                 w);
1115         
1116         wp->marked = true;
1117         _processor_window_proxies.push_back (wp);
1118         ARDOUR_UI::instance()->add_window_proxy (wp);
1119 }
1120
1121 void
1122 ProcessorBox::add_processor_to_display (boost::weak_ptr<Processor> p)
1123 {
1124         boost::shared_ptr<Processor> processor (p.lock ());
1125
1126         if (!processor || !processor->display_to_user()) {
1127                 return;
1128         }
1129
1130         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
1131         ProcessorEntry* e = 0;
1132         if (send) {
1133                 e = new SendProcessorEntry (send, _width);
1134         } else {
1135                 e = new ProcessorEntry (processor, _width);
1136         }
1137         e->set_pixel_width (get_allocation().get_width());
1138         processor_display.add_child (e);
1139 }
1140
1141
1142 void
1143 ProcessorBox::build_processor_tooltip (EventBox& box, string start)
1144 {
1145         string tip(start);
1146
1147         list<ProcessorEntry*> children = processor_display.children ();
1148         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
1149                 tip += '\n';
1150                 tip += (*i)->processor()->name();
1151         }
1152         
1153         ARDOUR_UI::instance()->set_tip (box, tip);
1154 }
1155
1156 void
1157 ProcessorBox::reordered ()
1158 {
1159         compute_processor_sort_keys ();
1160         setup_entry_positions ();
1161 }
1162
1163 void
1164 ProcessorBox::setup_entry_positions ()
1165 {
1166         list<ProcessorEntry*> children = processor_display.children ();
1167         bool pre_fader = true;
1168         
1169         for (list<ProcessorEntry*>::iterator i = children.begin(); i != children.end(); ++i) {
1170                 if (boost::dynamic_pointer_cast<Amp>((*i)->processor())) {
1171                         pre_fader = false;
1172                         (*i)->set_position (ProcessorEntry::Fader);
1173                 } else {
1174                         if (pre_fader) {
1175                                 (*i)->set_position (ProcessorEntry::PreFader);
1176                         } else {
1177                                 (*i)->set_position (ProcessorEntry::PostFader);
1178                         }
1179                 }
1180         }
1181 }
1182
1183 void
1184 ProcessorBox::compute_processor_sort_keys ()
1185 {
1186         list<ProcessorEntry*> children = processor_display.children ();
1187         Route::ProcessorList our_processors;
1188
1189         for (list<ProcessorEntry*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
1190                 our_processors.push_back ((*iter)->processor ());
1191         }
1192
1193         if (_route->reorder_processors (our_processors)) {
1194                 /* Reorder failed, so report this to the user.  As far as I can see this must be done
1195                    in an idle handler: it seems that the redisplay_processors() that happens below destroys
1196                    widgets that were involved in the drag-and-drop on the processor list, which causes problems
1197                    when the drag is torn down after this handler function is finished.
1198                 */
1199                 Glib::signal_idle().connect_once (sigc::mem_fun (*this, &ProcessorBox::report_failed_reorder));
1200         }
1201 }
1202
1203 void
1204 ProcessorBox::report_failed_reorder ()
1205 {
1206         /* reorder failed, so redisplay */
1207         
1208         redisplay_processors ();
1209         
1210         /* now tell them about the problem */
1211         
1212         ArdourDialog dialog (_("Plugin Incompatibility"));
1213         Label label;
1214         
1215         label.set_text (_("\
1216 You cannot reorder these plugins/sends/inserts\n\
1217 in that way because the inputs and\n\
1218 outputs will not work correctly."));
1219
1220         dialog.get_vbox()->set_border_width (12);
1221         dialog.get_vbox()->pack_start (label);
1222         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
1223         
1224         dialog.set_name (X_("PluginIODialog"));
1225         dialog.set_position (Gtk::WIN_POS_MOUSE);
1226         dialog.set_modal (true);
1227         dialog.show_all ();
1228         
1229         dialog.run ();
1230 }
1231
1232 void
1233 ProcessorBox::rename_processors ()
1234 {
1235         ProcSelection to_be_renamed;
1236
1237         get_selected_processors (to_be_renamed);
1238
1239         if (to_be_renamed.empty()) {
1240                 return;
1241         }
1242
1243         for (ProcSelection::iterator i = to_be_renamed.begin(); i != to_be_renamed.end(); ++i) {
1244                 rename_processor (*i);
1245         }
1246 }
1247
1248 bool
1249 ProcessorBox::can_cut () const
1250 {
1251         vector<boost::shared_ptr<Processor> > sel;
1252
1253         get_selected_processors (sel);
1254         
1255         /* cut_processors () does not cut inserts */
1256
1257         for (vector<boost::shared_ptr<Processor> >::const_iterator i = sel.begin (); i != sel.end (); ++i) {
1258                 
1259                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
1260                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
1261                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
1262                         return true;
1263                 }
1264         }
1265         
1266         return false;
1267 }
1268
1269 void
1270 ProcessorBox::cut_processors ()
1271 {
1272         ProcSelection to_be_removed;
1273
1274         get_selected_processors (to_be_removed);
1275 }
1276
1277 void
1278 ProcessorBox::cut_processors (const ProcSelection& to_be_removed)
1279 {
1280         if (to_be_removed.empty()) {
1281                 return;
1282         }
1283
1284         XMLNode* node = new XMLNode (X_("cut"));
1285         Route::ProcessorList to_cut;
1286
1287         no_processor_redisplay = true;
1288         for (ProcSelection::const_iterator i = to_be_removed.begin(); i != to_be_removed.end(); ++i) {
1289                 // Cut only plugins, sends and returns
1290                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
1291                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
1292                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
1293
1294                         Window* w = get_processor_ui (*i);
1295
1296                         if (w) {
1297                                 w->hide ();
1298                         }
1299
1300                         XMLNode& child ((*i)->get_state());
1301                         node->add_child_nocopy (child);
1302                         to_cut.push_back (*i);
1303                 }
1304         }
1305
1306         if (_route->remove_processors (to_cut) != 0) {
1307                 delete node;
1308                 no_processor_redisplay = false;
1309                 return;
1310         }
1311
1312         _rr_selection.set (node);
1313
1314         no_processor_redisplay = false;
1315         redisplay_processors ();
1316 }
1317
1318 void
1319 ProcessorBox::copy_processors ()
1320 {
1321         ProcSelection to_be_copied;
1322         get_selected_processors (to_be_copied);
1323         copy_processors (to_be_copied);
1324 }
1325
1326 void
1327 ProcessorBox::copy_processors (const ProcSelection& to_be_copied)
1328 {
1329         if (to_be_copied.empty()) {
1330                 return;
1331         }
1332
1333         XMLNode* node = new XMLNode (X_("copy"));
1334
1335         for (ProcSelection::const_iterator i = to_be_copied.begin(); i != to_be_copied.end(); ++i) {
1336                 // Copy only plugins, sends, returns
1337                 if (boost::dynamic_pointer_cast<PluginInsert>((*i)) != 0 ||
1338                     (boost::dynamic_pointer_cast<Send>((*i)) != 0) ||
1339                     (boost::dynamic_pointer_cast<Return>((*i)) != 0)) {
1340                         node->add_child_nocopy ((*i)->get_state());
1341                 }
1342         }
1343
1344         _rr_selection.set (node);
1345 }
1346
1347 void
1348 ProcessorBox::delete_processors ()
1349 {
1350         ProcSelection to_be_deleted;
1351         get_selected_processors (to_be_deleted);
1352         delete_processors (to_be_deleted);
1353 }
1354
1355 void
1356 ProcessorBox::delete_processors (const ProcSelection& targets)
1357 {
1358         if (targets.empty()) {
1359                 return;
1360         }
1361
1362         no_processor_redisplay = true;
1363
1364         for (ProcSelection::const_iterator i = targets.begin(); i != targets.end(); ++i) {
1365
1366                 Window* w = get_processor_ui (*i);
1367
1368                 if (w) {
1369                         w->hide ();
1370                 }
1371
1372                 _route->remove_processor(*i);
1373         }
1374
1375         no_processor_redisplay = false;
1376         redisplay_processors ();
1377 }
1378
1379 void
1380 ProcessorBox::delete_dragged_processors (const list<boost::shared_ptr<Processor> >& procs)
1381 {
1382         list<boost::shared_ptr<Processor> >::const_iterator x;
1383
1384         no_processor_redisplay = true;
1385         for (x = procs.begin(); x != procs.end(); ++x) {
1386
1387                 Window* w = get_processor_ui (*x);
1388
1389                 if (w) {
1390                         w->hide ();
1391                 }
1392
1393                 _route->remove_processor(*x);
1394         }
1395
1396         no_processor_redisplay = false;
1397         redisplay_processors ();
1398 }
1399
1400 gint
1401 ProcessorBox::idle_delete_processor (boost::weak_ptr<Processor> weak_processor)
1402 {
1403         boost::shared_ptr<Processor> processor (weak_processor.lock());
1404
1405         if (!processor) {
1406                 return false;
1407         }
1408
1409         /* NOT copied to _mixer.selection() */
1410
1411         no_processor_redisplay = true;
1412         _route->remove_processor (processor);
1413         no_processor_redisplay = false;
1414         redisplay_processors ();
1415
1416         return false;
1417 }
1418
1419 void
1420 ProcessorBox::rename_processor (boost::shared_ptr<Processor> processor)
1421 {
1422         ArdourPrompter name_prompter (true);
1423         string result;
1424         name_prompter.set_title (_("Rename Processor"));
1425         name_prompter.set_prompt (_("New name:"));
1426         name_prompter.set_initial_text (processor->name());
1427         name_prompter.add_button (_("Rename"), Gtk::RESPONSE_ACCEPT);
1428         name_prompter.set_response_sensitive (Gtk::RESPONSE_ACCEPT, false);
1429         name_prompter.show_all ();
1430
1431         switch (name_prompter.run ()) {
1432
1433         case Gtk::RESPONSE_ACCEPT:
1434                 name_prompter.get_result (result);
1435                 if (result.length()) {
1436
1437                        int tries = 0;
1438                        string test = result;
1439
1440                        while (tries < 100) {
1441                                if (_session->io_name_is_legal (test)) {
1442                                        result = test;
1443                                        break;
1444                                }
1445                                tries++;
1446
1447                                test = string_compose ("%1-%2", result, tries);
1448                        }
1449
1450                        if (tries < 100) {
1451                                processor->set_name (result);
1452                        } else {
1453                                /* unlikely! */
1454                                ARDOUR_UI::instance()->popup_error
1455                                        (string_compose (_("At least 100 IO objects exist with a name like %1 - name not changed"), result));
1456                        }
1457                 }
1458                 break;
1459         }
1460
1461         return;
1462 }
1463
1464 void
1465 ProcessorBox::paste_processors ()
1466 {
1467         if (_rr_selection.processors.empty()) {
1468                 return;
1469         }
1470
1471         paste_processor_state (_rr_selection.processors.get_node().children(), boost::shared_ptr<Processor>());
1472 }
1473
1474 void
1475 ProcessorBox::paste_processors (boost::shared_ptr<Processor> before)
1476 {
1477
1478         if (_rr_selection.processors.empty()) {
1479                 return;
1480         }
1481
1482         paste_processor_state (_rr_selection.processors.get_node().children(), before);
1483 }
1484
1485 void
1486 ProcessorBox::paste_processor_state (const XMLNodeList& nlist, boost::shared_ptr<Processor> p)
1487 {
1488         XMLNodeConstIterator niter;
1489         list<boost::shared_ptr<Processor> > copies;
1490
1491         if (nlist.empty()) {
1492                 return;
1493         }
1494
1495         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1496
1497                 XMLProperty const * type = (*niter)->property ("type");
1498                 assert (type);
1499
1500                 boost::shared_ptr<Processor> p;
1501                 try {
1502                         if (type->value() == "meter" ||
1503                             type->value() == "main-outs" ||
1504                             type->value() == "amp" ||
1505                             type->value() == "intsend" || type->value() == "intreturn") {
1506                                 /* do not paste meter, main outs, amp or internal send/returns */
1507                                 continue;
1508
1509                         } else if (type->value() == "send") {
1510
1511                                 XMLNode n (**niter);
1512                                 Send::make_unique (n, *_session);
1513                                 Send* s = new Send (*_session, _route->pannable(), _route->mute_master());
1514                                 if (s->set_state (n, Stateful::loading_state_version)) {
1515                                         delete s;
1516                                         return;
1517                                 }
1518
1519                                 p.reset (s);
1520                                         
1521
1522                         } else if (type->value() == "return") {
1523
1524                                 XMLNode n (**niter);
1525                                 Return::make_unique (n, *_session);
1526                                 Return* r = new Return (*_session);
1527
1528                                 if (r->set_state (n, Stateful::loading_state_version)) {
1529                                         delete r;
1530                                         return;
1531                                 }
1532
1533                                 p.reset (r);
1534
1535                         } else {
1536                                 /* XXX its a bit limiting to assume that everything else
1537                                    is a plugin.
1538                                 */
1539
1540                                 p.reset (new PluginInsert (*_session));
1541                                 p->set_state (**niter, Stateful::current_state_version);
1542                         }
1543
1544                         copies.push_back (p);
1545                 }
1546
1547                 catch (...) {
1548                         cerr << "plugin insert constructor failed\n";
1549                 }
1550         }
1551
1552         if (copies.empty()) {
1553                 return;
1554         }
1555
1556         if (_route->add_processors (copies, p)) {
1557
1558                 string msg = _(
1559                         "Copying the set of processors on the clipboard failed,\n\
1560 probably because the I/O configuration of the plugins\n\
1561 could not match the configuration of this track.");
1562                 MessageDialog am (msg);
1563                 am.run ();
1564         }
1565 }
1566
1567 void
1568 ProcessorBox::activate_processor (boost::shared_ptr<Processor> r)
1569 {
1570         r->activate ();
1571 }
1572
1573 void
1574 ProcessorBox::deactivate_processor (boost::shared_ptr<Processor> r)
1575 {
1576         r->deactivate ();
1577 }
1578
1579 void
1580 ProcessorBox::get_selected_processors (ProcSelection& processors) const
1581 {
1582         const list<ProcessorEntry*> selection = processor_display.selection ();
1583         for (list<ProcessorEntry*>::const_iterator i = selection.begin(); i != selection.end(); ++i) {
1584                 processors.push_back ((*i)->processor ());
1585         }
1586 }
1587
1588 void
1589 ProcessorBox::for_selected_processors (void (ProcessorBox::*method)(boost::shared_ptr<Processor>))
1590 {
1591         list<ProcessorEntry*> selection = processor_display.selection ();
1592         for (list<ProcessorEntry*>::iterator i = selection.begin(); i != selection.end(); ++i) {
1593                 (this->*method) ((*i)->processor ());
1594         }
1595 }
1596
1597 void
1598 ProcessorBox::all_processors_active (bool state)
1599 {
1600         _route->all_processors_active (_placement, state);
1601 }
1602
1603 void
1604 ProcessorBox::ab_plugins ()
1605 {
1606         _route->ab_plugins (ab_direction);
1607         ab_direction = !ab_direction;
1608 }
1609
1610
1611 void
1612 ProcessorBox::clear_processors ()
1613 {
1614         string prompt;
1615         vector<string> choices;
1616
1617         prompt = string_compose (_("Do you really want to remove all processors from %1?\n"
1618                                    "(this cannot be undone)"), _route->name());
1619
1620         choices.push_back (_("Cancel"));
1621         choices.push_back (_("Yes, remove them all"));
1622
1623         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
1624
1625         if (prompter.run () == 1) {
1626                 _route->clear_processors (PreFader);
1627                 _route->clear_processors (PostFader);
1628         }
1629 }
1630
1631 void
1632 ProcessorBox::clear_processors (Placement p)
1633 {
1634         string prompt;
1635         vector<string> choices;
1636
1637         if (p == PreFader) {
1638                 prompt = string_compose (_("Do you really want to remove all pre-fader processors from %1?\n"
1639                                            "(this cannot be undone)"), _route->name());
1640         } else {
1641                 prompt = string_compose (_("Do you really want to remove all post-fader processors from %1?\n"
1642                                            "(this cannot be undone)"), _route->name());
1643         }
1644
1645         choices.push_back (_("Cancel"));
1646         choices.push_back (_("Yes, remove them all"));
1647
1648         Gtkmm2ext::Choice prompter (_("Remove processors"), prompt, choices);
1649
1650         if (prompter.run () == 1) {
1651                 _route->clear_processors (p);
1652         }
1653 }
1654
1655 bool
1656 ProcessorBox::processor_can_be_edited (boost::shared_ptr<Processor> processor)
1657 {
1658         boost::shared_ptr<AudioTrack> at = boost::dynamic_pointer_cast<AudioTrack> (_route);
1659         if (at && at->freeze_state() == AudioTrack::Frozen) {
1660                 return false;
1661         }
1662
1663         if (
1664                 boost::dynamic_pointer_cast<Send> (processor) ||
1665                 boost::dynamic_pointer_cast<Return> (processor) ||
1666                 boost::dynamic_pointer_cast<PluginInsert> (processor) ||
1667                 boost::dynamic_pointer_cast<PortInsert> (processor)
1668                 ) {
1669                 return true;
1670         }
1671
1672         return false;
1673 }
1674
1675 bool
1676 ProcessorBox::one_processor_can_be_edited ()
1677 {
1678         list<ProcessorEntry*> selection = processor_display.selection ();
1679         list<ProcessorEntry*>::iterator i = selection.begin();
1680         while (i != selection.end() && processor_can_be_edited ((*i)->processor()) == false) {
1681                 ++i;
1682         }
1683
1684         return (i != selection.end());
1685 }
1686
1687 void
1688 ProcessorBox::toggle_edit_processor (boost::shared_ptr<Processor> processor)
1689 {
1690         boost::shared_ptr<Send> send;
1691         boost::shared_ptr<InternalSend> internal_send;
1692         boost::shared_ptr<Return> retrn;
1693         boost::shared_ptr<PluginInsert> plugin_insert;
1694         boost::shared_ptr<PortInsert> port_insert;
1695         Window* gidget = 0;
1696
1697         if (boost::dynamic_pointer_cast<AudioTrack>(_route) != 0) {
1698
1699                 if (boost::dynamic_pointer_cast<AudioTrack> (_route)->freeze_state() == AudioTrack::Frozen) {
1700                         return;
1701                 }
1702         }
1703
1704         if (boost::dynamic_pointer_cast<Amp> (processor)) {
1705
1706                 _parent_strip->revert_to_default_display ();
1707                 
1708         } else if ((internal_send = boost::dynamic_pointer_cast<InternalSend> (processor)) != 0) {
1709
1710                 if (!_session->engine().connected()) {
1711                         return;
1712                 }
1713
1714                 if (_parent_strip) {
1715                         if (boost::dynamic_pointer_cast<Send> (_parent_strip->current_delivery()) == internal_send) {
1716                                 _parent_strip->revert_to_default_display ();
1717                         } else {
1718                                 _parent_strip->show_send (internal_send);
1719                         }
1720                 }
1721
1722         } else if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
1723
1724                 if (!_session->engine().connected()) {
1725                         return;
1726                 }
1727
1728                 SendUIWindow* w = new SendUIWindow (send, _session);
1729                 w->show ();
1730
1731         } else if ((retrn = boost::dynamic_pointer_cast<Return> (processor)) != 0) {
1732
1733                 if (boost::dynamic_pointer_cast<InternalReturn> (retrn)) {
1734                         /* no GUI for these */
1735                         return;
1736                 }
1737
1738                 if (!_session->engine().connected()) {
1739                         return;
1740                 }
1741
1742                 boost::shared_ptr<Return> retrn = boost::dynamic_pointer_cast<Return> (processor);
1743
1744                 ReturnUIWindow *return_ui;
1745                 Window* w = get_processor_ui (retrn);
1746
1747                 if (w == 0) {
1748
1749                         return_ui = new ReturnUIWindow (retrn, _session);
1750                         return_ui->set_title (retrn->name ());
1751                         set_processor_ui (send, return_ui);
1752
1753                 } else {
1754                         return_ui = dynamic_cast<ReturnUIWindow *> (w);
1755                 }
1756
1757                 gidget = return_ui;
1758
1759         } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
1760
1761                 PluginUIWindow *plugin_ui;
1762
1763                 /* these are both allowed to be null */
1764
1765                 Container* toplevel = get_toplevel();
1766                 Window* win = dynamic_cast<Gtk::Window*>(toplevel);
1767
1768                 Window* w = get_processor_ui (plugin_insert);
1769
1770                 if (w == 0) {
1771
1772                         plugin_ui = new PluginUIWindow (win, plugin_insert);
1773                         plugin_ui->set_title (generate_processor_title (plugin_insert));
1774                         set_processor_ui (plugin_insert, plugin_ui);
1775
1776                 } else {
1777                         plugin_ui = dynamic_cast<PluginUIWindow *> (w);
1778                         plugin_ui->set_parent (win);
1779                 }
1780
1781                 gidget = plugin_ui;
1782
1783         } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (processor)) != 0) {
1784
1785                 if (!_session->engine().connected()) {
1786                         MessageDialog msg ( _("Not connected to JACK - no I/O changes are possible"));
1787                         msg.run ();
1788                         return;
1789                 }
1790
1791                 PortInsertWindow *io_selector;
1792
1793                 Window* w = get_processor_ui (port_insert);
1794
1795                 if (w == 0) {
1796                         io_selector = new PortInsertWindow (_session, port_insert);
1797                         set_processor_ui (port_insert, io_selector);
1798
1799                 } else {
1800                         io_selector = dynamic_cast<PortInsertWindow *> (w);
1801                 }
1802
1803                 gidget = io_selector;
1804         }
1805
1806         if (gidget) {
1807                 if (gidget->is_visible()) {
1808                         gidget->hide ();
1809                 } else {
1810                         gidget->show_all ();
1811                         gidget->present ();
1812                 }
1813         }
1814 }
1815
1816 void
1817 ProcessorBox::register_actions ()
1818 {
1819         Glib::RefPtr<Gtk::ActionGroup> popup_act_grp = Gtk::ActionGroup::create(X_("processormenu"));
1820         Glib::RefPtr<Action> act;
1821
1822         /* new stuff */
1823         ActionManager::register_action (popup_act_grp, X_("newplugin"), _("New Plugin"),
1824                         sigc::ptr_fun (ProcessorBox::rb_choose_plugin));
1825
1826         act = ActionManager::register_action (popup_act_grp, X_("newinsert"), _("New Insert"),
1827                         sigc::ptr_fun (ProcessorBox::rb_choose_insert));
1828         ActionManager::jack_sensitive_actions.push_back (act);
1829         act = ActionManager::register_action (popup_act_grp, X_("newsend"), _("New Send ..."),
1830                         sigc::ptr_fun (ProcessorBox::rb_choose_send));
1831         ActionManager::jack_sensitive_actions.push_back (act);
1832
1833         ActionManager::register_action (popup_act_grp, X_("newaux"), _("New Aux Send ..."));
1834
1835         ActionManager::register_action (popup_act_grp, X_("clear"), _("Clear (all)"),
1836                         sigc::ptr_fun (ProcessorBox::rb_clear));
1837         ActionManager::register_action (popup_act_grp, X_("clear_pre"), _("Clear (pre-fader)"),
1838                         sigc::ptr_fun (ProcessorBox::rb_clear_pre));
1839         ActionManager::register_action (popup_act_grp, X_("clear_post"), _("Clear (post-fader)"),
1840                         sigc::ptr_fun (ProcessorBox::rb_clear_post));
1841
1842         /* standard editing stuff */
1843         cut_action = ActionManager::register_action (popup_act_grp, X_("cut"), _("Cut"),
1844                                                      sigc::ptr_fun (ProcessorBox::rb_cut));
1845         ActionManager::plugin_selection_sensitive_actions.push_back(cut_action);
1846         act = ActionManager::register_action (popup_act_grp, X_("copy"), _("Copy"),
1847                         sigc::ptr_fun (ProcessorBox::rb_copy));
1848         ActionManager::plugin_selection_sensitive_actions.push_back(act);
1849
1850         act = ActionManager::register_action (popup_act_grp, X_("delete"), _("Delete"),
1851                         sigc::ptr_fun (ProcessorBox::rb_delete));
1852         ActionManager::plugin_selection_sensitive_actions.push_back(act); // ??
1853
1854         paste_action = ActionManager::register_action (popup_act_grp, X_("paste"), _("Paste"),
1855                         sigc::ptr_fun (ProcessorBox::rb_paste));
1856         rename_action = ActionManager::register_action (popup_act_grp, X_("rename"), _("Rename"),
1857                         sigc::ptr_fun (ProcessorBox::rb_rename));
1858         ActionManager::register_action (popup_act_grp, X_("selectall"), _("Select All"),
1859                         sigc::ptr_fun (ProcessorBox::rb_select_all));
1860         ActionManager::register_action (popup_act_grp, X_("deselectall"), _("Deselect All"),
1861                         sigc::ptr_fun (ProcessorBox::rb_deselect_all));
1862
1863         /* activation etc. */
1864
1865         ActionManager::register_action (popup_act_grp, X_("activate_all"), _("Activate all"),
1866                                         sigc::ptr_fun (ProcessorBox::rb_activate_all));
1867         ActionManager::register_action (popup_act_grp, X_("deactivate_all"), _("Deactivate all"),
1868                                         sigc::ptr_fun (ProcessorBox::rb_deactivate_all));
1869         ActionManager::register_action (popup_act_grp, X_("ab_plugins"), _("A/B Plugins"),
1870                                         sigc::ptr_fun (ProcessorBox::rb_ab_plugins));
1871
1872         /* show editors */
1873         edit_action = ActionManager::register_action (popup_act_grp, X_("edit"), _("Edit..."),
1874                                                       sigc::ptr_fun (ProcessorBox::rb_edit));
1875
1876         ActionManager::add_action_group (popup_act_grp);
1877 }
1878
1879 void
1880 ProcessorBox::rb_ab_plugins ()
1881 {
1882         if (_current_processor_box == 0) {
1883                 return;
1884         }
1885
1886         _current_processor_box->ab_plugins ();
1887 }
1888
1889 void
1890 ProcessorBox::rb_choose_plugin ()
1891 {
1892         if (_current_processor_box == 0) {
1893                 return;
1894         }
1895         _current_processor_box->choose_plugin ();
1896 }
1897
1898 void
1899 ProcessorBox::rb_choose_insert ()
1900 {
1901         if (_current_processor_box == 0) {
1902                 return;
1903         }
1904         _current_processor_box->choose_insert ();
1905 }
1906
1907 void
1908 ProcessorBox::rb_choose_send ()
1909 {
1910         if (_current_processor_box == 0) {
1911                 return;
1912         }
1913         _current_processor_box->choose_send ();
1914 }
1915
1916 void
1917 ProcessorBox::rb_choose_aux (boost::weak_ptr<Route> wr)
1918 {
1919         if (_current_processor_box == 0) {
1920                 return;
1921         }
1922
1923         _current_processor_box->choose_aux (wr);
1924 }
1925
1926 void
1927 ProcessorBox::rb_clear ()
1928 {
1929         if (_current_processor_box == 0) {
1930                 return;
1931         }
1932
1933         _current_processor_box->clear_processors ();
1934 }
1935
1936
1937 void
1938 ProcessorBox::rb_clear_pre ()
1939 {
1940         if (_current_processor_box == 0) {
1941                 return;
1942         }
1943
1944         _current_processor_box->clear_processors (PreFader);
1945 }
1946
1947
1948 void
1949 ProcessorBox::rb_clear_post ()
1950 {
1951         if (_current_processor_box == 0) {
1952                 return;
1953         }
1954
1955         _current_processor_box->clear_processors (PostFader);
1956 }
1957
1958 void
1959 ProcessorBox::rb_cut ()
1960 {
1961         if (_current_processor_box == 0) {
1962                 return;
1963         }
1964
1965         _current_processor_box->cut_processors ();
1966 }
1967
1968 void
1969 ProcessorBox::rb_delete ()
1970 {
1971         if (_current_processor_box == 0) {
1972                 return;
1973         }
1974
1975         _current_processor_box->delete_processors ();
1976 }
1977
1978 void
1979 ProcessorBox::rb_copy ()
1980 {
1981         if (_current_processor_box == 0) {
1982                 return;
1983         }
1984         _current_processor_box->copy_processors ();
1985 }
1986
1987 void
1988 ProcessorBox::rb_paste ()
1989 {
1990         if (_current_processor_box == 0) {
1991                 return;
1992         }
1993
1994         _current_processor_box->paste_processors ();
1995 }
1996
1997 void
1998 ProcessorBox::rb_rename ()
1999 {
2000         if (_current_processor_box == 0) {
2001                 return;
2002         }
2003         _current_processor_box->rename_processors ();
2004 }
2005
2006 void
2007 ProcessorBox::rb_select_all ()
2008 {
2009         if (_current_processor_box == 0) {
2010                 return;
2011         }
2012
2013         _current_processor_box->select_all_processors ();
2014 }
2015
2016 void
2017 ProcessorBox::rb_deselect_all ()
2018 {
2019         if (_current_processor_box == 0) {
2020                 return;
2021         }
2022
2023         _current_processor_box->deselect_all_processors ();
2024 }
2025
2026 void
2027 ProcessorBox::rb_activate_all ()
2028 {
2029         if (_current_processor_box == 0) {
2030                 return;
2031         }
2032
2033         _current_processor_box->all_processors_active (true);
2034 }
2035
2036 void
2037 ProcessorBox::rb_deactivate_all ()
2038 {
2039         if (_current_processor_box == 0) {
2040                 return;
2041         }
2042         _current_processor_box->all_processors_active (false);
2043 }
2044
2045 void
2046 ProcessorBox::rb_edit ()
2047 {
2048         if (_current_processor_box == 0) {
2049                 return;
2050         }
2051
2052         _current_processor_box->for_selected_processors (&ProcessorBox::toggle_edit_processor);
2053 }
2054
2055 void
2056 ProcessorBox::route_property_changed (const PropertyChange& what_changed)
2057 {
2058         if (!what_changed.contains (ARDOUR::Properties::name)) {
2059                 return;
2060         }
2061
2062         ENSURE_GUI_THREAD (*this, &ProcessorBox::route_property_changed, what_changed);
2063
2064         boost::shared_ptr<Processor> processor;
2065         boost::shared_ptr<PluginInsert> plugin_insert;
2066         boost::shared_ptr<Send> send;
2067
2068         list<ProcessorEntry*> children = processor_display.children();
2069
2070         for (list<ProcessorEntry*>::iterator iter = children.begin(); iter != children.end(); ++iter) {
2071
2072                 processor = (*iter)->processor ();
2073
2074                 Window* w = get_processor_ui (processor);
2075
2076                 if (!w) {
2077                         continue;
2078                 }
2079
2080                 /* rename editor windows for sends and plugins */
2081
2082                 if ((send = boost::dynamic_pointer_cast<Send> (processor)) != 0) {
2083                         w->set_title (send->name ());
2084                 } else if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor)) != 0) {
2085                         w->set_title (generate_processor_title (plugin_insert));
2086                 }
2087         }
2088 }
2089
2090 string
2091 ProcessorBox::generate_processor_title (boost::shared_ptr<PluginInsert> pi)
2092 {
2093         string maker = pi->plugin()->maker() ? pi->plugin()->maker() : "";
2094         string::size_type email_pos;
2095
2096         if ((email_pos = maker.find_first_of ('<')) != string::npos) {
2097                 maker = maker.substr (0, email_pos - 1);
2098         }
2099
2100         if (maker.length() > 32) {
2101                 maker = maker.substr (0, 32);
2102                 maker += " ...";
2103         }
2104
2105         return string_compose(_("%1: %2 (by %3)"), _route->name(), pi->name(), maker);
2106 }
2107
2108 void
2109 ProcessorBox::on_size_allocate (Allocation& a)
2110 {
2111         HBox::on_size_allocate (a);
2112
2113         list<ProcessorEntry*> children = processor_display.children ();
2114         for (list<ProcessorEntry*>::const_iterator i = children.begin(); i != children.end(); ++i) {
2115                 (*i)->set_pixel_width (a.get_width ());
2116         }
2117 }
2118
2119 /** @param p Processor.
2120  *  @return the UI window for \a p.
2121  */
2122 Window *
2123 ProcessorBox::get_processor_ui (boost::shared_ptr<Processor> p) const
2124 {
2125         list<ProcessorWindowProxy*>::const_iterator i = _processor_window_proxies.begin ();
2126         while (i != _processor_window_proxies.end()) {
2127                 boost::shared_ptr<Processor> t = (*i)->processor().lock ();
2128                 if (t && t == p) {
2129                         return (*i)->get ();
2130                 }
2131
2132                 ++i;
2133         }
2134
2135         /* we shouldn't get here, because the ProcessorUIList should always contain
2136            an entry for each processor.
2137         */
2138         assert (false);
2139         return 0;
2140 }
2141
2142 /** Make a note of the UI window that a processor is using.
2143  *  @param p Processor.
2144  *  @param w UI window.
2145  */
2146 void
2147 ProcessorBox::set_processor_ui (boost::shared_ptr<Processor> p, Gtk::Window* w)
2148 {
2149         list<ProcessorWindowProxy*>::iterator i = _processor_window_proxies.begin ();
2150         while (i != _processor_window_proxies.end()) {
2151                 boost::shared_ptr<Processor> t = (*i)->processor().lock ();
2152                 if (t && t == p) {
2153                         (*i)->set (w);
2154                         return;
2155                 }
2156
2157                 ++i;
2158         }
2159
2160         /* we shouldn't get here, because the ProcessorUIList should always contain
2161            an entry for each processor.
2162         */
2163         assert (false);
2164 }
2165
2166 void
2167 ProcessorBox::mixer_strip_delivery_changed (boost::weak_ptr<Delivery> w)
2168 {
2169         boost::shared_ptr<Delivery> d = w.lock ();
2170         if (!d) {
2171                 return;
2172         }
2173
2174         list<ProcessorEntry*> children = processor_display.children ();
2175         list<ProcessorEntry*>::const_iterator i = children.begin();
2176         while (i != children.end() && (*i)->processor() != d) {
2177                 ++i;
2178         }
2179
2180         if (i == children.end()) {
2181                 processor_display.set_active (0);
2182         } else {
2183                 processor_display.set_active (*i);
2184         }
2185 }
2186
2187 ProcessorWindowProxy::ProcessorWindowProxy (
2188         string const & name,
2189         XMLNode const * node,
2190         ProcessorBox* box,
2191         boost::weak_ptr<Processor> processor
2192         )
2193         : WindowProxy<Gtk::Window> (name, node)
2194         , marked (false)
2195         , _processor_box (box)
2196         , _processor (processor)
2197 {
2198
2199 }
2200
2201
2202 void
2203 ProcessorWindowProxy::show ()
2204 {
2205         boost::shared_ptr<Processor> p = _processor.lock ();
2206         if (!p) {
2207                 return;
2208         }
2209
2210         _processor_box->toggle_edit_processor (p);
2211 }
2212