Add strip GUI first try for foldback bus
[ardour.git] / gtk2_ardour / foldback_strip.cc
1 /*
2     Copyright (C) 2000-2006 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 #include <cmath>
20 #include <list>
21 #include <algorithm>
22
23 #include <sigc++/bind.h>
24
25 #include <gtkmm/messagedialog.h>
26
27 #include "pbd/convert.h"
28 #include "pbd/enumwriter.h"
29 #include "pbd/replace_all.h"
30 #include "pbd/stacktrace.h"
31
32 #include "ardour/amp.h"
33 #include "ardour/audioengine.h"
34 #include "ardour/internal_send.h"
35 #include "ardour/io.h"
36 #include "ardour/pannable.h"
37 #include "ardour/panner.h"
38 #include "ardour/panner_shell.h"
39 #include "ardour/panner_manager.h"
40 #include "ardour/port.h"
41 #include "ardour/profile.h"
42 #include "ardour/route.h"
43 #include "ardour/send.h"
44 #include "ardour/session.h"
45 #include "ardour/types.h"
46 #include "ardour/user_bundle.h"
47
48 #include "gtkmm2ext/gtk_ui.h"
49 #include "gtkmm2ext/menu_elems.h"
50 #include "gtkmm2ext/utils.h"
51 #include "gtkmm2ext/doi.h"
52
53 #include "widgets/tooltips.h"
54
55 #include "ardour_window.h"
56 #include "enums_convert.h"
57 #include "foldback_strip.h"
58 #include "mixer_ui.h"
59 #include "keyboard.h"
60 #include "public_editor.h"
61 #include "send_ui.h"
62 #include "io_selector.h"
63 #include "utils.h"
64 #include "gui_thread.h"
65 #include "ui_config.h"
66
67 #include "pbd/i18n.h"
68
69 using namespace ARDOUR;
70 using namespace ArdourWidgets;
71 using namespace PBD;
72 using namespace Gtk;
73 using namespace Gtkmm2ext;
74 using namespace std;
75
76 FoldbackStrip* FoldbackStrip::_entered_foldback_strip;
77 PBD::Signal1<void,FoldbackStrip*> FoldbackStrip::CatchDeletion;
78
79 FoldbackStrip::FoldbackStrip (Mixer_UI& mx, Session* sess, boost::shared_ptr<Route> rt)
80         : SessionHandlePtr (sess)
81         , RouteUI (sess)
82         , _mixer(mx)
83         , _mixer_owned (true)
84         , panners (sess)
85         , button_size_group (Gtk::SizeGroup::create (Gtk::SIZE_GROUP_HORIZONTAL))
86         , mute_solo_table (1, 2)
87         , bottom_button_table (1, 1)
88         , _comment_button (_("Comments"))
89         , fb_level_control (0)
90 {
91         init ();
92         set_route (rt);
93 }
94
95 void
96 FoldbackStrip::init ()
97 {
98         _entered_foldback_strip= 0;
99         route_ops_menu = 0;
100         route_select_menu = 0;
101         ignore_comment_edit = false;
102         ignore_toggle = false;
103         comment_area = 0;
104         _width_owner = 0;
105
106         /* the length of this string determines the width of the mixer strip when it is set to `wide' */
107         longest_label = "longest label";
108
109         //input_button_box.set_spacing(2);
110
111
112         output_button.set_text (_("Output"));
113         output_button.set_name ("foldback strip button");
114 //      send_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
115 //      send_scroller.add (send_display);
116
117         send_display.set_flags (CAN_FOCUS);
118         send_display.set_name ("ProcessorList");
119         send_display.set_data ("sendbox", this);
120         send_display.set_size_request (48, -1);
121         send_display.set_spacing (0);
122
123
124 //      send_scroller.show ();
125         send_display.show ();
126
127         // TODO implement ArdourKnob::on_size_request properly
128         fb_level_control = new ArdourKnob (ArdourKnob::default_elements, ArdourKnob::Detent);
129
130 #define PX_SCALE(px) std::max((float)px, rintf((float)px * UIConfiguration::instance().get_ui_scale()))
131         fb_level_control->set_size_request (PX_SCALE(65), PX_SCALE(65));
132 #undef PX_SCALE
133         fb_level_control->set_tooltip_prefix (_("Level: "));
134         fb_level_control->set_name ("monitor section knob");
135         fb_level_control->set_no_show_all (true);
136
137         bottom_button_table.attach (*fb_level_control, 0, 1, 0, 1,FILL,FILL,20,20); //EXPAND
138
139
140         mute_solo_table.set_homogeneous (true);
141         mute_solo_table.set_spacings (2);
142
143         show_sends_button->set_text (_("Show Sends"));
144
145         show_sends_box.pack_start (*show_sends_button, true, true);
146         show_sends_button->show();
147
148         bottom_button_table.set_spacings (20);
149         bottom_button_table.set_row_spacings (20);
150         bottom_button_table.set_homogeneous (true);
151
152         name_button.set_name ("monitor section button");
153         name_button.set_text_ellipsize (Pango::ELLIPSIZE_END);
154         name_button.signal_size_allocate().connect (sigc::mem_fun (*this, &FoldbackStrip::name_button_resized));
155
156         _select_button.set_name ("monitor section button");
157         _select_button.set_text (_("Select Foldback Bus"));
158
159
160         _comment_button.set_name (X_("foldback strip button"));
161         _comment_button.set_text_ellipsize (Pango::ELLIPSIZE_END);
162         _comment_button.signal_clicked.connect (sigc::mem_fun (*this, &RouteUI::toggle_comment_editor));
163         _comment_button.signal_size_allocate().connect (sigc::mem_fun (*this, &FoldbackStrip::comment_button_resized));
164
165         global_vpacker.set_border_width (1);
166
167         global_vpacker.set_spacing (4);
168         global_vpacker.pack_start (_select_button, Gtk::PACK_SHRINK);
169         global_vpacker.pack_start (name_button, Gtk::PACK_SHRINK);
170         global_vpacker.pack_start (_invert_button_box, Gtk::PACK_SHRINK);
171         global_vpacker.pack_start (show_sends_box, Gtk::PACK_SHRINK);
172
173 #ifndef MIXBUS
174         //add a spacer underneath the master bus;
175         //this fills the area that is taken up by the scrollbar on the tracks;
176         //and therefore keeps the faders "even" across the bottom
177         int scrollbar_height = 0;
178         {
179                 Gtk::Window window (WINDOW_TOPLEVEL);
180                 HScrollbar scrollbar;
181                 window.add (scrollbar);
182                 scrollbar.set_name ("MixerWindow");
183                 scrollbar.ensure_style();
184                 Gtk::Requisition requisition(scrollbar.size_request ());
185                 scrollbar_height = requisition.height;
186         }
187         spacer.set_size_request (-1, scrollbar_height);
188         global_vpacker.pack_end (spacer, false, false);
189 #endif
190         global_vpacker.pack_end (_comment_button, Gtk::PACK_SHRINK);
191         global_vpacker.pack_end (output_button, Gtk::PACK_SHRINK);
192         global_vpacker.pack_end (mute_solo_table, Gtk::PACK_SHRINK);
193         global_vpacker.pack_end (panners, Gtk::PACK_SHRINK);
194         global_vpacker.pack_end (bottom_button_table, Gtk::PACK_SHRINK);
195
196         global_frame.add (global_vpacker);
197         global_frame.set_shadow_type (Gtk::SHADOW_IN);
198         global_frame.set_name ("BaseFrame");
199
200         add (global_frame);
201
202         /* force setting of visible selected status */
203
204         _selected = true;
205         set_selected (false);
206
207         _packed = false;
208         _embedded = false;
209
210         _session->engine().Stopped.connect (*this, invalidator (*this), boost::bind (&FoldbackStrip::engine_stopped, this), gui_context());
211         _session->engine().Running.connect (*this, invalidator (*this), boost::bind (&FoldbackStrip::engine_running, this), gui_context());
212
213         output_button.set_text_ellipsize (Pango::ELLIPSIZE_MIDDLE);
214
215         output_button.signal_button_press_event().connect (sigc::mem_fun(*this, &FoldbackStrip::output_press), false);
216         output_button.signal_button_release_event().connect (sigc::mem_fun(*this, &FoldbackStrip::output_release), false);
217         output_button.signal_size_allocate().connect (sigc::mem_fun (*this, &FoldbackStrip::output_button_resized));
218
219
220         name_button.signal_button_press_event().connect (sigc::mem_fun(*this, &FoldbackStrip::name_button_button_press), false);
221         _select_button.signal_button_press_event().connect (sigc::mem_fun (*this, &FoldbackStrip::select_button_button_press), false);
222
223         _width = Wide;
224
225
226         /* start off as a passthru strip. we'll correct this, if necessary,
227            in update_diskstream_display().
228         */
229
230
231
232         add_events (Gdk::BUTTON_RELEASE_MASK|
233                     Gdk::ENTER_NOTIFY_MASK|
234                     Gdk::LEAVE_NOTIFY_MASK|
235                     Gdk::KEY_PRESS_MASK|
236                     Gdk::KEY_RELEASE_MASK);
237
238         set_flags (get_flags() | Gtk::CAN_FOCUS);
239
240         AudioEngine::instance()->PortConnectedOrDisconnected.connect (
241                 *this, invalidator (*this), boost::bind (&FoldbackStrip::port_connected_or_disconnected, this, _1, _3), gui_context ()
242                 );
243
244
245         //watch for mouse enter/exit so we can do some stuff
246         signal_enter_notify_event().connect (sigc::mem_fun(*this, &FoldbackStrip::mixer_strip_enter_event ));
247         signal_leave_notify_event().connect (sigc::mem_fun(*this, &FoldbackStrip::mixer_strip_leave_event ));
248
249 }
250
251 FoldbackStrip::~FoldbackStrip ()
252 {
253         CatchDeletion (this);
254         delete fb_level_control;
255         fb_level_control = 0;
256
257         if (this ==_entered_foldback_strip)
258                 _entered_foldback_strip = NULL;
259 }
260
261 bool
262 FoldbackStrip::mixer_strip_enter_event (GdkEventCrossing* /*ev*/)
263 {
264         _entered_foldback_strip = this;
265
266         //although we are triggering on the "enter", to the user it will appear that it is happenin on the "leave"
267         //because the FoldbackStrip control is a parent that encompasses the strip
268         //deselect_all_processors();
269
270         return false;
271 }
272
273 bool
274 FoldbackStrip::mixer_strip_leave_event (GdkEventCrossing *ev)
275 {
276         //if we have moved outside our strip, but not into a child view, then deselect ourselves
277         if ( !(ev->detail == GDK_NOTIFY_INFERIOR) ) {
278                 _entered_foldback_strip= 0;
279
280         }
281
282         return false;
283 }
284
285 string
286 FoldbackStrip::name() const
287 {
288         if (_route) {
289                 return _route->name();
290         }
291         return string();
292 }
293
294 void
295 FoldbackStrip::update_fb_level_control ()
296 {
297         fb_level_control->show ();
298         fb_level_control->set_controllable (_route->gain_control());
299 }
300
301 void
302 FoldbackStrip::set_route (boost::shared_ptr<Route> rt)
303 {
304         /// FIX NO route
305         if (!rt) {
306                 RouteUI::self_delete ();
307 /*      _route.reset (); // drop reference to route, so that it can be cleaned up
308         route_connections.drop_connections ();
309
310         delete solo_menu;
311         delete mute_menu;
312         delete sends_menu;
313         delete record_menu;
314         delete comment_window;
315         delete input_selector;
316         delete output_selector;
317         delete monitor_input_button;
318         delete monitor_disk_button;
319         delete _invert_menu;
320
321         send_blink_connection.disconnect ();
322         rec_blink_connection.disconnect ();*/
323                 return;
324         }
325         //the rec/monitor stuff only shows up for tracks.
326         //the show_sends only shows up for buses.
327         //remove them all here, and we may add them back later
328         if (show_sends_button->get_parent()) {
329                 show_sends_box.remove (*show_sends_button);
330         }
331
332         RouteUI::set_route (rt);
333
334         revert_to_default_display ();
335
336         if (solo_button->get_parent()) {
337                 mute_solo_table.remove (*solo_button);
338         }
339
340         if (mute_button->get_parent()) {
341                 mute_solo_table.remove (*mute_button);
342         }
343
344         mute_solo_table.attach (*mute_button, 0, 1, 0, 1);
345         mute_solo_table.attach (*solo_button, 1, 2, 0, 1);
346         mute_button->show ();
347         solo_button->show ();
348         show_sends_box.show ();
349
350         spacer.show();
351
352         update_fb_level_control();
353
354         show_sends_box.pack_start (*show_sends_button, true, true);
355         show_sends_button->show();
356
357
358         delete route_ops_menu;
359         route_ops_menu = 0;
360
361         delete route_select_menu;
362         route_select_menu = 0;
363
364         _route->output()->changed.connect (*this, invalidator (*this), boost::bind (&FoldbackStrip::update_output_display, this), gui_context());
365
366         _route->io_changed.connect (route_connections, invalidator (*this), boost::bind (&FoldbackStrip::io_changed_proxy, this), gui_context ());
367
368         if (_route->panner_shell()) {
369                 update_panner_choices();
370                 _route->panner_shell()->Changed.connect (route_connections, invalidator (*this), boost::bind (&FoldbackStrip::connect_to_pan, this), gui_context());
371         }
372
373         _route->comment_changed.connect (route_connections, invalidator (*this), boost::bind (&FoldbackStrip::setup_comment_button, this), gui_context());
374
375         set_stuff_from_route ();
376
377         /* now force an update of all the various elements */
378
379         update_mute_display ();
380         update_solo_display ();
381         name_changed ();
382         comment_changed ();
383
384         connect_to_pan ();
385         panners.setup_pan ();
386         panners.show_all ();
387
388         update_output_display ();
389
390         add_events (Gdk::BUTTON_RELEASE_MASK);
391
392         Route::FedBy fed_by = _route->fed_by();
393         for (Route::FedBy::iterator i = fed_by.begin(); i != fed_by.end(); ++i) {
394                 if (i->sends_only) {
395                         boost::shared_ptr<Route> s_rt (i->r.lock());
396                         boost::shared_ptr<Send> snd = s_rt->internal_send_for (_route);
397                         //s_rt->DropReferences.connect (*this, MISSING_INVALIDATOR, boost::bind (&FoldbackStrip::fill_sendbox, this), this);
398                         boost::shared_ptr<Processor> processor (snd);
399                         //boost::shared_ptr<PluginInsert> plugin_insert = boost::dynamic_pointer_cast<PluginInsert> (processor);
400 // Ok we have the info... now we need widgets to put it in... I suspect I need a class or three
401 // this doesn't work... and I need to clear it out and rebuild each time.
402                         ArdourWidgets::ArdourButton _button;
403                         _button.set_distinct_led_click (true);
404                         _button.set_fallthrough_to_parent(true);
405                         _button.set_led_left (true);
406 //                      _button.signal_led_clicked.connect (sigc::mem_fun (*this, &FoldbackStrip::led_clicked));
407                         _button.set_text (s_rt->name ());
408
409                         //Gtk::VBox     snd_entry = NULL;
410                         Gtk::VBox       snd_entry;
411                         snd_entry.set_border_width (1);
412                         snd_entry.set_spacing (4);
413                         snd_entry.pack_start (_button, true, true);
414                         send_display.pack_start (snd_entry, true, true);
415                         _button.show ();
416                         snd_entry.show ();
417
418
419                 }
420         }
421
422
423
424         global_frame.show();
425         global_vpacker.show();
426         mute_solo_table.show();
427         bottom_button_table.show();
428         show_sends_box.show_all();
429         //send_scroller.show ();
430         send_display.show ();
431         output_button.show();
432         name_button.show();
433         _select_button.show();
434         _comment_button.show();
435
436         map_frozen();
437
438         show ();
439 }
440
441 void
442 FoldbackStrip::set_stuff_from_route ()
443 {
444         /* if width is not set, it will be set by the MixerUI or editor */
445
446         Width width;
447         if (get_gui_property ("strip-width", width)) {
448         }
449 }
450
451 void
452 FoldbackStrip::set_packed (bool yn)
453 {
454         _packed = yn;
455         set_gui_property ("visible", _packed);
456 }
457
458
459 struct RouteCompareByName {
460         bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
461                 return a->name().compare (b->name()) < 0;
462         }
463 };
464
465 gint
466 FoldbackStrip::output_release (GdkEventButton *ev)
467 {
468         switch (ev->button) {
469         case 3:
470                 edit_output_configuration ();
471                 break;
472         }
473
474         return false;
475 }
476
477 gint
478 FoldbackStrip::output_press (GdkEventButton *ev)
479 {
480         using namespace Menu_Helpers;
481         if (!_session->engine().connected()) {
482                 MessageDialog msg (_("Not connected to audio engine - no I/O changes are possible"));
483                 msg.run ();
484                 return true;
485         }
486
487         MenuList& citems = output_menu.items();
488         switch (ev->button) {
489
490         case 3:
491                 return false;  //wait for the mouse-up to pop the dialog
492
493         case 1:
494         {
495                 output_menu.set_name ("ArdourContextMenu");
496                 citems.clear ();
497                 output_menu_bundles.clear ();
498
499                 citems.push_back (MenuElem (_("Disconnect"), sigc::mem_fun (*(static_cast<RouteUI*>(this)), &RouteUI::disconnect_output)));
500
501                 citems.push_back (SeparatorElem());
502                 uint32_t const n_with_separator = citems.size ();
503
504                 ARDOUR::BundleList current = _route->output()->bundles_connected ();
505
506                 boost::shared_ptr<ARDOUR::BundleList> b = _session->bundles ();
507
508                 /* guess the user-intended main type of the route output */
509                 DataType intended_type = guess_main_type(false);
510
511                 /* try adding the master bus first */
512                 boost::shared_ptr<Route> master = _session->master_out();
513                 if (master) {
514                         maybe_add_bundle_to_output_menu (master->input()->bundle(), current, intended_type);
515                 }
516
517                 /* then other routes inputs */
518                 RouteList copy = _session->get_routelist ();
519                 copy.sort (RouteCompareByName ());
520                 for (ARDOUR::RouteList::const_iterator i = copy.begin(); i != copy.end(); ++i) {
521                         maybe_add_bundle_to_output_menu ((*i)->input()->bundle(), current, intended_type);
522                 }
523
524                 /* then try adding user bundles, often labeled/grouped physical inputs */
525                 for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
526                         if (boost::dynamic_pointer_cast<UserBundle> (*i)) {
527                                 maybe_add_bundle_to_output_menu (*i, current, intended_type);
528                         }
529                 }
530
531                 /* then all other bundles, including physical outs or other sofware */
532                 for (ARDOUR::BundleList::iterator i = b->begin(); i != b->end(); ++i) {
533                         if (boost::dynamic_pointer_cast<UserBundle> (*i) == 0) {
534                                 maybe_add_bundle_to_output_menu (*i, current, intended_type);
535                         }
536                 }
537
538                 if (citems.size() == n_with_separator) {
539                         /* no routes added; remove the separator */
540                         citems.pop_back ();
541                 }
542
543                 if (!ARDOUR::Profile->get_mixbus()) {
544                         citems.push_back (SeparatorElem());
545
546                         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
547                                 citems.push_back (
548                                                 MenuElem (
549                                                         string_compose (_("Add %1 port"), (*i).to_i18n_string()),
550                                                         sigc::bind (sigc::mem_fun (*this, &FoldbackStrip::add_output_port), *i)
551                                                         )
552                                                 );
553                         }
554                 }
555
556                 citems.push_back (SeparatorElem());
557                 citems.push_back (MenuElem (_("Routing Grid"), sigc::mem_fun (*(static_cast<RouteUI*>(this)), &RouteUI::edit_output_configuration)));
558
559                 Gtkmm2ext::anchored_menu_popup(&output_menu, &output_button, "",
560                                                1, ev->time);
561
562                 break;
563         }
564
565         default:
566                 break;
567         }
568         return TRUE;
569 }
570
571 void
572 FoldbackStrip::bundle_output_chosen (boost::shared_ptr<ARDOUR::Bundle> c)
573 {
574         if (ignore_toggle) {
575                 return;
576         }
577
578         _route->output()->connect_ports_to_bundle (c, true, true, this);
579 }
580
581 void
582 FoldbackStrip::maybe_add_bundle_to_output_menu (boost::shared_ptr<Bundle> b, ARDOUR::BundleList const& /*current*/,
583                                              DataType type)
584 {
585         using namespace Menu_Helpers;
586
587         /* The bundle should be an input one, but not ours */
588         if (b->ports_are_inputs() == false || *b == *_route->input()->bundle()) {
589                 return;
590         }
591
592         /* Don't add the monitor input unless we are Master */
593         boost::shared_ptr<Route> monitor = _session->monitor_out();
594         if ((!_route->is_master()) && monitor && b->has_same_ports (monitor->input()->bundle()))
595                 return;
596
597         /* It should either match exactly our outputs (if |type| is DataType::NIL)
598          * or have the same number of |type| channels than our outputs. */
599         if (type == DataType::NIL) {
600                 if(b->nchannels() != _route->n_outputs())
601                         return;
602         } else {
603                 if (b->nchannels().n(type) != _route->n_outputs().n(type))
604                         return;
605         }
606
607         /* Avoid adding duplicates */
608         list<boost::shared_ptr<Bundle> >::iterator i = output_menu_bundles.begin ();
609         while (i != output_menu_bundles.end() && b->has_same_ports (*i) == false) {
610                 ++i;
611         }
612         if (i != output_menu_bundles.end()) {
613                 return;
614         }
615
616         /* Now add the bundle to the menu */
617         output_menu_bundles.push_back (b);
618
619         MenuList& citems = output_menu.items();
620         citems.push_back (MenuElemNoMnemonic (b->name (), sigc::bind (sigc::mem_fun(*this, &FoldbackStrip::bundle_output_chosen), b)));
621 }
622
623 void
624 FoldbackStrip::connect_to_pan ()
625 {
626         ENSURE_GUI_THREAD (*this, &FoldbackStrip::connect_to_pan)
627
628         panstate_connection.disconnect ();
629         panstyle_connection.disconnect ();
630
631         if (!_route->panner()) {
632                 return;
633         }
634
635         boost::shared_ptr<Pannable> p = _route->pannable ();
636
637         //p->automation_state_changed.connect (panstate_connection, invalidator (*this), boost::bind (&PannerUI::pan_automation_state_changed, &panners), gui_context());
638
639         /* This call reduncant, PannerUI::set_panner() connects to _panshell->Changed itself
640          * However, that only works a panner was previously set.
641          *
642          * PannerUI must remain subscribed to _panshell->Changed() in case
643          * we switch the panner eg. AUX-Send and back
644          * _route->panner_shell()->Changed() vs _panshell->Changed
645          */
646 /*      if (panners._panner == 0) {
647                 panners.panshell_changed ();
648         }
649 */      update_panner_choices();
650 }
651
652 void
653 FoldbackStrip::update_panner_choices ()
654 {
655         ENSURE_GUI_THREAD (*this, &FoldbackStrip::update_panner_choices)
656         if (!_route->panner_shell()) { return; }
657
658         uint32_t in = _route->output()->n_ports().n_audio();
659         uint32_t out = in;
660         if (_route->panner()) {
661                 in = _route->panner()->in().n_audio();
662         }
663
664         panners.set_available_panners(PannerManager::instance().PannerManager::get_available_panners(in, out));
665 }
666
667 DataType
668 FoldbackStrip::guess_main_type(bool for_input, bool favor_connected) const
669 {
670         /* The heuristic follows these principles:
671          *  A) If all ports that the user connected are of the same type, then he
672          *     very probably intends to use the IO with that type. A common subcase
673          *     is when the IO has only ports of the same type (connected or not).
674          *  B) If several types of ports are connected, then we should guess based
675          *     on the likeliness of the user wanting to use a given type.
676          *     We assume that the DataTypes are ordered from the most likely to the
677          *     least likely when iterating or comparing them with "<".
678          *  C) If no port is connected, the same logic can be applied with all ports
679          *     instead of connected ones. TODO: Try other ideas, for instance look at
680          *     the last plugin output when |for_input| is false (note: when StrictIO
681          *     the outs of the last plugin should be the same as the outs of the route
682          *     modulo the panner which forwards non-audio anyway).
683          * All of these constraints are respected by the following algorithm that
684          * just returns the most likely datatype found in connected ports if any, or
685          * available ports if any (since if all ports are of the same type, the most
686          * likely found will be that one obviously). */
687
688         boost::shared_ptr<IO> io = for_input ? _route->input() : _route->output();
689
690         /* Find most likely type among connected ports */
691         if (favor_connected) {
692                 DataType type = DataType::NIL; /* NIL is always last so least likely */
693                 for (PortSet::iterator p = io->ports().begin(); p != io->ports().end(); ++p) {
694                         if (p->connected() && p->type() < type)
695                                 type = p->type();
696                 }
697                 if (type != DataType::NIL) {
698                         /* There has been a connected port (necessarily non-NIL) */
699                         return type;
700                 }
701         }
702
703         /* Find most likely type among available ports.
704          * The iterator stops before NIL. */
705         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
706                 if (io->n_ports().n(*t) > 0)
707                         return *t;
708         }
709
710         /* No port at all, return the most likely datatype by default */
711         return DataType::front();
712 }
713
714 /*
715  * Output port labelling
716  *
717  * Case 1: Each output has one connection, all connections are to system:playback_%i
718  *   out 1 -> system:playback_1
719  *   out 2 -> system:playback_2
720  *   out 3 -> system:playback_3
721  *   Display as: 1/2/3
722  *
723  * Case 2: Each output has one connection, all connections are to ardour:track_x/in 1
724  *   out 1 -> ardour:track_x/in 1
725  *   out 2 -> ardour:track_x/in 2
726  *   Display as: track_x
727  *
728  * Case 3: Each output has one connection, all connections are to Jack client "program x"
729  *   out 1 -> program x:foo
730  *   out 2 -> program x:foo
731  *   Display as: program x
732  *
733  * Case 4: No connections (Disconnected)
734  *   Display as: -
735  *
736  * Default case (unusual routing):
737  *   Display as: *number of connections*
738  *
739  *
740  * Tooltips
741  *
742  * .-----------------------------------------------.
743  * | Mixdown                                       |
744  * | out 1 -> ardour:master/in 1, jamin:input/in 1 |
745  * | out 2 -> ardour:master/in 2, jamin:input/in 2 |
746  * '-----------------------------------------------'
747  * .-----------------------------------------------.
748  * | Guitar SM58                                   |
749  * | Disconnected                                  |
750  * '-----------------------------------------------'
751  */
752
753 void
754 FoldbackStrip::update_io_button ()
755 {
756         ostringstream tooltip;
757         ostringstream label;
758         bool have_label = false;
759
760         uint32_t total_connection_count = 0;
761         uint32_t typed_connection_count = 0;
762         bool each_typed_port_has_one_connection = true;
763
764         DataType dt = guess_main_type(false);
765         boost::shared_ptr<IO> io = _route->output();
766
767         /* Fill in the tooltip. Also count:
768          *  - The total number of connections.
769          *  - The number of main-typed connections.
770          *  - Whether each main-typed port has exactly one connection. */
771
772         tooltip << string_compose (_("<b>OUTPUT</b> from %1"),
773                         Gtkmm2ext::markup_escape_text (_route->name()));
774
775         string arrow = Gtkmm2ext::markup_escape_text(" -> ");
776         vector<string> port_connections;
777         for (PortSet::iterator port = io->ports().begin();
778                                port != io->ports().end();
779                                ++port) {
780                 port_connections.clear();
781                 port->get_connections(port_connections);
782
783                 uint32_t port_connection_count = 0;
784
785                 for (vector<string>::iterator i = port_connections.begin();
786                                               i != port_connections.end();
787                                               ++i) {
788                         ++port_connection_count;
789
790                         if (port_connection_count == 1) {
791                                 tooltip << endl << Gtkmm2ext::markup_escape_text (
792                                                 port->name().substr(port->name().find("/") + 1));
793                                 tooltip << arrow;
794                         } else {
795                                 tooltip << ", ";
796                         }
797
798                         tooltip << Gtkmm2ext::markup_escape_text(*i);
799                 }
800
801                 total_connection_count += port_connection_count;
802                 if (port->type() == dt) {
803                         typed_connection_count += port_connection_count;
804                         each_typed_port_has_one_connection &= (port_connection_count == 1);
805                 }
806
807         }
808
809         if (total_connection_count == 0) {
810                 tooltip << endl << _("Disconnected");
811         }
812
813         if (typed_connection_count == 0) {
814                 label << "-";
815                 have_label = true;
816         }
817
818         /* Are all main-typed channels connected to the same route ? */
819         if (!have_label) {
820                 boost::shared_ptr<ARDOUR::RouteList> routes = _session->get_routes ();
821                 for (ARDOUR::RouteList::const_iterator route = routes->begin();
822                                                        route != routes->end();
823                                                        ++route) {
824                         boost::shared_ptr<IO> dest_io = (*route)->output();
825                         if (io->bundle()->connected_to(dest_io->bundle(),
826                                                        _session->engine(),
827                                                        dt, true)) {
828                                 label << Gtkmm2ext::markup_escape_text ((*route)->name());
829                                 have_label = true;
830                                 break;
831                         }
832                 }
833         }
834
835         /* Are all main-typed channels connected to the same (user) bundle ? */
836         if (!have_label) {
837                 boost::shared_ptr<ARDOUR::BundleList> bundles = _session->bundles ();
838                 for (ARDOUR::BundleList::iterator bundle = bundles->begin();
839                                                   bundle != bundles->end();
840                                                   ++bundle) {
841                         if (boost::dynamic_pointer_cast<UserBundle> (*bundle) == 0)
842                                 continue;
843                         if (io->bundle()->connected_to(*bundle, _session->engine(),
844                                                        dt, true)) {
845                                 label << Gtkmm2ext::markup_escape_text ((*bundle)->name());
846                                 have_label = true;
847                                 break;
848                         }
849                 }
850         }
851
852         /* Is each main-typed channel only connected to a physical output ? */
853         if (!have_label && each_typed_port_has_one_connection) {
854                 ostringstream temp_label;
855                 vector<string> phys;
856                 string playorcapture;
857
858                         _session->engine().get_physical_outputs(dt, phys);
859                         playorcapture = "playback_";
860                 for (PortSet::iterator port = io->ports().begin(dt);
861                                        port != io->ports().end(dt);
862                                        ++port) {
863                         string pn = "";
864                         for (vector<string>::iterator s = phys.begin();
865                                                       s != phys.end();
866                                                       ++s) {
867                                 if (!port->connected_to(*s))
868                                         continue;
869                                 pn = AudioEngine::instance()->get_pretty_name_by_name(*s);
870                                 if (pn.empty()) {
871                                         string::size_type start = (*s).find(playorcapture);
872                                         if (start != string::npos) {
873                                                 pn = (*s).substr(start + playorcapture.size());
874                                         }
875                                 }
876                                 break;
877                         }
878                         if (pn.empty()) {
879                                 temp_label.str(""); /* erase the failed attempt */
880                                 break;
881                         }
882                         if (port != io->ports().begin(dt))
883                                 temp_label << "/";
884                         temp_label << pn;
885                 }
886
887                 if (!temp_label.str().empty()) {
888                         label << temp_label.str();
889                         have_label = true;
890                 }
891         }
892
893         /* Is each main-typed channel connected to a single and different port with
894          * the same client name (e.g. another JACK client) ? */
895         if (!have_label && each_typed_port_has_one_connection) {
896                 string maybe_client = "";
897                 vector<string> connections;
898                 for (PortSet::iterator port = io->ports().begin(dt);
899                                        port != io->ports().end(dt);
900                                        ++port) {
901                         port_connections.clear();
902                         port->get_connections(port_connections);
903                         string connection = port_connections.front();
904
905                         vector<string>::iterator i = connections.begin();
906                         while (i != connections.end() && *i != connection) {
907                                 ++i;
908                         }
909                         if (i != connections.end())
910                                 break; /* duplicate connection */
911                         connections.push_back(connection);
912
913                         connection = connection.substr(0, connection.find(":"));
914                         if (maybe_client.empty())
915                                 maybe_client = connection;
916                         if (maybe_client != connection)
917                                 break;
918                 }
919                 if (connections.size() == io->n_ports().n(dt)) {
920                         label << maybe_client;
921                         have_label = true;
922                 }
923         }
924
925         /* Odd configuration */
926         if (!have_label) {
927                 label << "*" << total_connection_count << "*";
928         }
929
930         if (total_connection_count > typed_connection_count) {
931                 label << "\u2295"; /* circled plus */
932         }
933
934         /* Actually set the properties of the button */
935         char * cstr = new char[tooltip.str().size() + 1];
936         strcpy(cstr, tooltip.str().c_str());
937
938
939                 output_button.set_text (label.str());
940                 set_tooltip (&output_button, cstr);
941
942         delete [] cstr;
943 }
944
945 void
946 FoldbackStrip::update_output_display ()
947 {
948         update_io_button ();
949         panners.setup_pan ();
950
951         if (has_audio_outputs ()) {
952                 panners.show_all ();
953         } else {
954                 panners.hide_all ();
955         }
956 }
957
958 void
959 FoldbackStrip::io_changed_proxy ()
960 {
961         Glib::signal_idle().connect_once (sigc::mem_fun (*this, &FoldbackStrip::update_panner_choices));
962 }
963
964 void
965 FoldbackStrip::port_connected_or_disconnected (boost::weak_ptr<Port> wa, boost::weak_ptr<Port> wb)
966 {
967         boost::shared_ptr<Port> a = wa.lock ();
968         boost::shared_ptr<Port> b = wb.lock ();
969
970         if ((a && _route->output()->has_port (a)) || (b && _route->output()->has_port (b))) {
971                 update_output_display ();
972         }
973 }
974
975 void
976 FoldbackStrip::setup_comment_button ()
977 {
978         std::string comment = _route->comment();
979
980         set_tooltip (_comment_button, comment.empty() ? _("Click to add/edit comments") : _route->comment());
981
982         if (comment.empty ()) {
983                 _comment_button.set_name ("generic button");
984                 _comment_button.set_text (_("Comments"));
985                 return;
986         }
987
988         _comment_button.set_name ("comment button");
989
990         string::size_type pos = comment.find_first_of (" \t\n");
991         if (pos != string::npos) {
992                 comment = comment.substr (0, pos);
993         }
994         if (comment.empty()) {
995                 _comment_button.set_text (_("Comments"));
996         } else {
997                 _comment_button.set_text (comment);
998         }
999 }
1000
1001 void
1002 FoldbackStrip::show_passthru_color ()
1003 {
1004         //reset_strip_style ();
1005 }
1006
1007 void
1008 FoldbackStrip::build_route_ops_menu ()
1009 {
1010         using namespace Menu_Helpers;
1011         route_ops_menu = new Menu;
1012         route_ops_menu->set_name ("ArdourContextMenu");
1013
1014         MenuList& items = route_ops_menu->items();
1015
1016         items.push_back (MenuElem (_("Comments..."), sigc::mem_fun (*this, &RouteUI::open_comment_editor)));
1017
1018         items.push_back (MenuElem (_("Outputs..."), sigc::mem_fun (*this, &RouteUI::edit_output_configuration)));
1019
1020         items.push_back (SeparatorElem());
1021
1022         items.push_back (MenuElem (_("Rename..."), sigc::mem_fun(*this, &RouteUI::route_rename)));
1023
1024         items.push_back (SeparatorElem());
1025         items.push_back (CheckMenuElem (_("Active")));
1026         Gtk::CheckMenuItem* i = dynamic_cast<Gtk::CheckMenuItem *> (&items.back());
1027         i->set_active (_route->active());
1028         i->set_sensitive(! _session->transport_rolling());
1029         i->signal_activate().connect (sigc::bind (sigc::mem_fun (*this, &RouteUI::set_route_active), !_route->active(), false));
1030
1031         items.push_back (SeparatorElem());
1032         items.push_back (CheckMenuElem (_("Protect Against Denormals"), sigc::mem_fun (*this, &RouteUI::toggle_denormal_protection)));
1033         denormal_menu_item = dynamic_cast<Gtk::CheckMenuItem *> (&items.back());
1034         denormal_menu_item->set_active (_route->denormal_protection());
1035
1036         items.push_back (SeparatorElem());
1037         items.push_back (MenuElem (_("Remove"), sigc::mem_fun(*this, &FoldbackStrip::remove_current_fb)));
1038 }
1039
1040 void
1041 FoldbackStrip::build_route_select_menu ()
1042 {
1043         using namespace Menu_Helpers;
1044         route_select_menu = new Menu;
1045         route_select_menu->set_name ("ArdourContextMenu");
1046
1047         MenuList& items = route_select_menu->items();
1048         StripableList fb_list;
1049         _session->get_stripables (fb_list, PresentationInfo::FoldbackBus);
1050         for (StripableList::iterator s = fb_list.begin(); s != fb_list.end(); ++s) {
1051
1052                 boost::shared_ptr<Route> route = boost::dynamic_pointer_cast<Route> ((*s));
1053                 if (route == _route) {
1054                         continue;
1055                 }
1056                 items.push_back (MenuElem (route->name (), sigc::bind (sigc::mem_fun (*this, &FoldbackStrip::set_route), route)));
1057         }
1058
1059 }
1060
1061
1062 gboolean
1063 FoldbackStrip::name_button_button_press (GdkEventButton* ev)
1064 {
1065         if (ev->button == 1 || ev->button == 3) {
1066                 list_route_operations ();
1067
1068                 if (ev->button == 1) {
1069                         Gtkmm2ext::anchored_menu_popup(route_ops_menu, &name_button, "",
1070                                                        1, ev->time);
1071                 } else {
1072                         route_ops_menu->popup (3, ev->time);
1073                 }
1074
1075                 return true;
1076         }
1077
1078         return false;
1079 }
1080
1081 gboolean
1082 FoldbackStrip::select_button_button_press (GdkEventButton* ev)
1083 {
1084         if (ev->button == 1 || ev->button == 3) {
1085                 list_fb_routes ();
1086
1087                 if (ev->button == 1) {
1088                         Gtkmm2ext::anchored_menu_popup(route_select_menu, &_select_button, "",
1089                                                        1, ev->time);
1090                 } else {
1091                         route_select_menu->popup (3, ev->time);
1092                 }
1093
1094                 return true;
1095         }
1096
1097         return false;
1098 }
1099
1100 void
1101 FoldbackStrip::list_route_operations ()
1102 {
1103         delete route_ops_menu;
1104         build_route_ops_menu ();
1105 }
1106
1107 void
1108 FoldbackStrip::list_fb_routes ()
1109 {
1110         delete route_select_menu;
1111         build_route_select_menu ();
1112 }
1113
1114 void
1115 FoldbackStrip::route_property_changed (const PropertyChange& what_changed)
1116 {
1117         if (what_changed.contains (ARDOUR::Properties::name)) {
1118                 name_changed ();
1119         }
1120 }
1121
1122 void
1123 FoldbackStrip::name_changed ()
1124 {
1125
1126         name_button.set_text_ellipsize (Pango::ELLIPSIZE_END);
1127         name_button.set_text (_route->name());
1128
1129         set_tooltip (name_button, Gtkmm2ext::markup_escape_text(_route->name()));
1130
1131 }
1132
1133 void
1134 FoldbackStrip::output_button_resized (Gtk::Allocation& alloc)
1135 {
1136         output_button.set_layout_ellipsize_width (alloc.get_width() * PANGO_SCALE);
1137 }
1138
1139 void
1140 FoldbackStrip::name_button_resized (Gtk::Allocation& alloc)
1141 {
1142         name_button.set_layout_ellipsize_width (20);
1143 }
1144
1145 void
1146 FoldbackStrip::comment_button_resized (Gtk::Allocation& alloc)
1147 {
1148         _comment_button.set_layout_ellipsize_width (alloc.get_width() * PANGO_SCALE);
1149 }
1150
1151 void
1152 FoldbackStrip::set_embedded (bool yn)
1153 {
1154         _embedded = yn;
1155 }
1156
1157 void
1158 FoldbackStrip::map_frozen ()
1159 {
1160         ENSURE_GUI_THREAD (*this, &FoldbackStrip::map_frozen)
1161
1162
1163         RouteUI::map_frozen ();
1164 }
1165
1166 void
1167 FoldbackStrip::hide_redirect_editors ()
1168 {
1169 }
1170
1171 void
1172 FoldbackStrip::reset_strip_style ()
1173 {
1174         set_name ("AudioBusStripBase");
1175 }
1176
1177 void
1178 FoldbackStrip::engine_stopped ()
1179 {
1180 }
1181
1182 void
1183 FoldbackStrip::engine_running ()
1184 {
1185 }
1186
1187 void
1188 FoldbackStrip::drop_send ()
1189 {
1190         boost::shared_ptr<Send> current_send;
1191
1192         if (_current_delivery && ((current_send = boost::dynamic_pointer_cast<Send>(_current_delivery)) != 0)) {
1193                 current_send->set_metering (false);
1194         }
1195
1196         send_gone_connection.disconnect ();
1197         output_button.set_sensitive (true);
1198         set_invert_sensitive (true);
1199         mute_button->set_sensitive (true);
1200         solo_button->set_sensitive (true);
1201         _comment_button.set_sensitive (true);
1202         fb_level_control->set_sensitive (true);
1203         set_button_names (); // update solo button visual state
1204 }
1205
1206 void
1207 FoldbackStrip::set_current_delivery (boost::shared_ptr<Delivery> d)
1208 {
1209         _current_delivery = d;
1210         DeliveryChanged (_current_delivery);
1211 }
1212
1213 void
1214 FoldbackStrip::revert_to_default_display ()
1215 {
1216         drop_send ();
1217
1218         set_current_delivery (_route->main_outs ());
1219
1220         panner_ui().set_panner (_route->main_outs()->panner_shell(), _route->main_outs()->panner());
1221         update_panner_choices();
1222         panner_ui().setup_pan ();
1223         panner_ui().set_send_drawing_mode (false);
1224
1225         if (has_audio_outputs ()) {
1226                 panners.show_all ();
1227         } else {
1228                 panners.hide_all ();
1229         }
1230
1231         reset_strip_style ();
1232 }
1233
1234 void
1235 FoldbackStrip::set_button_names ()
1236 {
1237
1238                 mute_button->set_text (_("Mute"));
1239
1240
1241                 if (_route && _route->solo_safe_control()->solo_safe()) {
1242                         solo_button->set_visual_state (Gtkmm2ext::VisualState (solo_button->visual_state() | Gtkmm2ext::Insensitive));
1243                 } else {
1244                         solo_button->set_visual_state (Gtkmm2ext::VisualState (solo_button->visual_state() & ~Gtkmm2ext::Insensitive));
1245                 }
1246                 if (!Config->get_solo_control_is_listen_control()) {
1247                         solo_button->set_text (_("Solo"));
1248                 } else {
1249                         switch (Config->get_listen_position()) {
1250                         case AfterFaderListen:
1251                                 solo_button->set_text (_("AFL"));
1252                                 break;
1253                         case PreFaderListen:
1254                                 solo_button->set_text (_("PFL"));
1255                                 break;
1256                         }
1257                 }
1258
1259
1260 }
1261
1262 string
1263 FoldbackStrip::state_id () const
1264 {
1265         return string_compose ("strip %1", _route->id().to_s());
1266 }
1267
1268 void
1269 FoldbackStrip::add_output_port (DataType t)
1270 {
1271         _route->output()->add_port ("", this, t);
1272 }
1273
1274 void
1275 FoldbackStrip::route_active_changed ()
1276 {
1277         reset_strip_style ();
1278 }
1279
1280 void
1281 FoldbackStrip::build_sends_menu ()
1282 {
1283         using namespace Menu_Helpers;
1284
1285         sends_menu = new Menu;
1286         sends_menu->set_name ("ArdourContextMenu");
1287         MenuList& items = sends_menu->items();
1288
1289         items.push_back (
1290                 MenuElem(_("Assign all tracks"), sigc::bind (sigc::mem_fun (*this, &RouteUI::create_sends), PreFader, false))
1291                 );
1292
1293         items.push_back (
1294                 MenuElem(_("Assign all tracks and buses (prefader)"), sigc::bind (sigc::mem_fun (*this, &RouteUI::create_sends), PreFader, true))
1295                 );
1296
1297         items.push_back (
1298                 MenuElem(_("Assign selected tracks (prefader)"), sigc::bind (sigc::mem_fun (*this, &RouteUI::create_selected_sends), PreFader, false))
1299                 );
1300
1301         items.push_back (
1302                 MenuElem(_("Assign selected tracks and buses (prefader)"), sigc::bind (sigc::mem_fun (*this, &RouteUI::create_selected_sends), PreFader, true)));
1303
1304         items.push_back (MenuElem(_("Copy track/bus gains to sends"), sigc::mem_fun (*this, &RouteUI::set_sends_gain_from_track)));
1305         items.push_back (MenuElem(_("Set sends gain to -inf"), sigc::mem_fun (*this, &RouteUI::set_sends_gain_to_zero)));
1306         items.push_back (MenuElem(_("Set sends gain to 0dB"), sigc::mem_fun (*this, &RouteUI::set_sends_gain_to_unity)));
1307
1308 }
1309
1310 Gdk::Color
1311 FoldbackStrip::color () const
1312 {
1313         return route_color ();
1314 }
1315 /*
1316 bool
1317 FoldbackStrip::marked_for_display () const
1318 {
1319         return !_route->presentation_info().hidden();
1320 }
1321 */
1322 void
1323 FoldbackStrip::remove_current_fb ()
1324 {
1325         StripableList slist;
1326         boost::shared_ptr<Route> next = boost::shared_ptr<Route> ();
1327         boost::shared_ptr<Route> old_route = _route;
1328         _session->get_stripables (slist, PresentationInfo::FoldbackBus);
1329         if (slist.size ()) {
1330                 for (StripableList::iterator s = slist.begin(); s != slist.end(); ++s) {
1331                         if ((*s) != _route) {
1332                                 next = boost::dynamic_pointer_cast<Route> (*s);
1333                                 break;
1334                         }
1335                 }
1336         }
1337         if (next) {
1338                 set_route (next);
1339         }
1340         _session->remove_route (old_route);
1341
1342
1343 }