do not add master to Mixer_UI's TreeModel - explicitly pack it and never unpack it
[ardour.git] / gtk2_ardour / mixer_ui.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 <algorithm>
25 #include <map>
26 #include <sigc++/bind.h>
27
28 #include <gtkmm/accelmap.h>
29
30 #include "pbd/convert.h"
31 #include "pbd/stacktrace.h"
32 #include "pbd/unwind.h"
33
34 #include <glibmm/threads.h>
35
36 #include <gtkmm2ext/gtk_ui.h>
37 #include <gtkmm2ext/keyboard.h>
38 #include <gtkmm2ext/utils.h>
39 #include <gtkmm2ext/tearoff.h>
40 #include <gtkmm2ext/window_title.h>
41 #include <gtkmm2ext/doi.h>
42
43 #include "ardour/amp.h"
44 #include "ardour/debug.h"
45 #include "ardour/audio_track.h"
46 #include "ardour/midi_track.h"
47 #include "ardour/plugin_manager.h"
48 #include "ardour/route_group.h"
49 #include "ardour/session.h"
50 #include "ardour/vca.h"
51 #include "ardour/vca_manager.h"
52
53 #include "keyboard.h"
54 #include "mixer_ui.h"
55 #include "mixer_strip.h"
56 #include "monitor_section.h"
57 #include "plugin_selector.h"
58 #include "public_editor.h"
59 #include "mouse_cursors.h"
60 #include "ardour_ui.h"
61 #include "prompter.h"
62 #include "utils.h"
63 #include "route_sorter.h"
64 #include "actions.h"
65 #include "gui_thread.h"
66 #include "mixer_group_tabs.h"
67 #include "route_sorter.h"
68 #include "timers.h"
69 #include "ui_config.h"
70 #include "vca_master_strip.h"
71
72 #include "i18n.h"
73
74 using namespace ARDOUR;
75 using namespace ARDOUR_UI_UTILS;
76 using namespace PBD;
77 using namespace Gtk;
78 using namespace Glib;
79 using namespace Gtkmm2ext;
80 using namespace std;
81
82 using PBD::atoi;
83 using PBD::Unwinder;
84
85 Mixer_UI* Mixer_UI::_instance = 0;
86
87 Mixer_UI*
88 Mixer_UI::instance ()
89 {
90         if (!_instance) {
91                 _instance  = new Mixer_UI;
92         }
93
94         return _instance;
95 }
96
97 Mixer_UI::Mixer_UI ()
98         : Tabbable (_content, _("Mixer"))
99         , no_track_list_redisplay (false)
100         , in_group_row_change (false)
101         , track_menu (0)
102         , _monitor_section (0)
103         , _plugin_selector (0)
104         , _strip_width (UIConfiguration::instance().get_default_narrow_ms() ? Narrow : Wide)
105         , ignore_reorder (false)
106         , _in_group_rebuild_or_clear (false)
107         , _route_deletion_in_progress (false)
108         , _following_editor_selection (false)
109         , _maximised (false)
110         , _show_mixer_list (true)
111 {
112         PresentationInfo::Change.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::sync_treeview_from_presentation_info, this), gui_context());
113
114         /* bindings was already set in MixerActor constructor */
115
116         _content.set_data ("ardour-bindings", bindings);
117
118         scroller.set_can_default (true);
119         // set_default (scroller);
120
121         scroller_base.set_flags (Gtk::CAN_FOCUS);
122         scroller_base.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
123         scroller_base.set_name ("MixerWindow");
124         scroller_base.signal_button_release_event().connect (sigc::mem_fun(*this, &Mixer_UI::strip_scroller_button_release));
125
126         /* set up drag-n-drop */
127         vector<TargetEntry> target_table;
128         target_table.push_back (TargetEntry ("PluginFavoritePtr"));
129         scroller_base.drag_dest_set (target_table);
130         scroller_base.signal_drag_data_received().connect (sigc::mem_fun(*this, &Mixer_UI::scroller_drag_data_received));
131
132         // add as last item of strip packer
133         strip_packer.pack_end (scroller_base, true, true);
134
135         _group_tabs = new MixerGroupTabs (this);
136         VBox* b = manage (new VBox);
137         b->pack_start (*_group_tabs, PACK_SHRINK);
138         b->pack_start (strip_packer);
139         b->show_all ();
140
141         scroller.add (*b);
142         scroller.set_policy (Gtk::POLICY_ALWAYS, Gtk::POLICY_AUTOMATIC);
143
144         setup_track_display ();
145
146         group_model = ListStore::create (group_columns);
147         group_display.set_model (group_model);
148         group_display.append_column (_("Group"), group_columns.text);
149         group_display.append_column (_("Show"), group_columns.visible);
150         group_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
151         group_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
152         group_display.get_column (0)->set_expand(true);
153         group_display.get_column (1)->set_expand(false);
154         group_display.set_name ("EditGroupList");
155         group_display.get_selection()->set_mode (Gtk::SELECTION_SINGLE);
156         group_display.set_reorderable (true);
157         group_display.set_headers_visible (true);
158         group_display.set_rules_hint (true);
159         group_display.set_can_focus(false);
160
161         /* name is directly editable */
162
163         CellRendererText* name_cell = dynamic_cast<CellRendererText*>(group_display.get_column_cell_renderer (0));
164         name_cell->property_editable() = true;
165         name_cell->signal_edited().connect (sigc::mem_fun (*this, &Mixer_UI::route_group_name_edit));
166
167         /* use checkbox for the active column */
168
169         CellRendererToggle* active_cell = dynamic_cast<CellRendererToggle*>(group_display.get_column_cell_renderer (1));
170         active_cell->property_activatable() = true;
171         active_cell->property_radio() = false;
172
173         group_model->signal_row_changed().connect (sigc::mem_fun (*this, &Mixer_UI::route_group_row_change));
174         /* We use this to notice drag-and-drop reorders of the group list */
175         group_model->signal_row_deleted().connect (sigc::mem_fun (*this, &Mixer_UI::route_group_row_deleted));
176         group_display.signal_button_press_event().connect (sigc::mem_fun (*this, &Mixer_UI::group_display_button_press), false);
177
178         group_display_scroller.add (group_display);
179         group_display_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
180
181         HBox* route_group_display_button_box = manage (new HBox());
182
183         Button* route_group_add_button = manage (new Button ());
184         Button* route_group_remove_button = manage (new Button ());
185
186         Widget* w;
187
188         w = manage (new Image (Stock::ADD, ICON_SIZE_BUTTON));
189         w->show();
190         route_group_add_button->add (*w);
191
192         w = manage (new Image (Stock::REMOVE, ICON_SIZE_BUTTON));
193         w->show();
194         route_group_remove_button->add (*w);
195
196         route_group_display_button_box->set_homogeneous (true);
197
198         route_group_add_button->signal_clicked().connect (sigc::mem_fun (*this, &Mixer_UI::new_route_group));
199         route_group_remove_button->signal_clicked().connect (sigc::mem_fun (*this, &Mixer_UI::remove_selected_route_group));
200
201         route_group_display_button_box->add (*route_group_add_button);
202         route_group_display_button_box->add (*route_group_remove_button);
203
204         group_display_vbox.pack_start (group_display_scroller, true, true);
205         group_display_vbox.pack_start (*route_group_display_button_box, false, false);
206
207         group_display_frame.set_name ("BaseFrame");
208         group_display_frame.set_shadow_type (Gtk::SHADOW_IN);
209         group_display_frame.add (group_display_vbox);
210
211
212         list<TargetEntry> target_list;
213         target_list.push_back (TargetEntry ("PluginPresetPtr"));
214
215         favorite_plugins_model = PluginTreeStore::create (favorite_plugins_columns);
216         favorite_plugins_display.set_model (favorite_plugins_model);
217         favorite_plugins_display.append_column (_("Favorite Plugins"), favorite_plugins_columns.name);
218         favorite_plugins_display.set_name ("EditGroupList");
219         favorite_plugins_display.get_selection()->set_mode (Gtk::SELECTION_SINGLE);
220         favorite_plugins_display.set_reorderable (false);
221         favorite_plugins_display.set_headers_visible (true);
222         favorite_plugins_display.set_rules_hint (true);
223         favorite_plugins_display.set_can_focus (false);
224         favorite_plugins_display.add_object_drag (favorite_plugins_columns.plugin.index(), "PluginFavoritePtr");
225         favorite_plugins_display.set_drag_column (favorite_plugins_columns.name.index());
226         favorite_plugins_display.add_drop_targets (target_list);
227         favorite_plugins_display.signal_row_activated().connect (sigc::mem_fun (*this, &Mixer_UI::plugin_row_activated));
228         favorite_plugins_display.signal_button_press_event().connect (sigc::mem_fun (*this, &Mixer_UI::plugin_row_button_press), false);
229         favorite_plugins_display.signal_drop.connect (sigc::mem_fun (*this, &Mixer_UI::plugin_drop));
230         favorite_plugins_display.signal_row_expanded().connect (sigc::mem_fun (*this, &Mixer_UI::save_favorite_ui_state));
231         favorite_plugins_display.signal_row_collapsed().connect (sigc::mem_fun (*this, &Mixer_UI::save_favorite_ui_state));
232         favorite_plugins_model->signal_row_has_child_toggled().connect (sigc::mem_fun (*this, &Mixer_UI::sync_treeview_favorite_ui_state));
233
234         favorite_plugins_scroller.add (favorite_plugins_display);
235         favorite_plugins_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
236
237         favorite_plugins_frame.set_name ("BaseFrame");
238         favorite_plugins_frame.set_shadow_type (Gtk::SHADOW_IN);
239         favorite_plugins_frame.add (favorite_plugins_scroller);
240
241         rhs_pane1.add (favorite_plugins_frame);
242         rhs_pane1.add (track_display_frame);
243         rhs_pane2.add (rhs_pane1);
244         rhs_pane2.add (group_display_frame);
245
246         list_vpacker.pack_start (rhs_pane2, true, true);
247
248         string vca_text = _("Control Masters");
249         Gtk::HBox* vca_top_padding = manage (new Gtk::HBox);
250         vca_top_padding->set_size_request (-1, 2);
251         vca_vpacker.pack_start (*vca_top_padding, false, false);
252
253         vca_label.set_text (vca_text);
254         vca_label_bar.set_size_request (-1, 16); /* must match height in GroupTabs::set_size_request() */
255
256         vca_label_bar.set_name (X_("VCALabelBar"));
257         vca_label_bar.add (vca_label);
258
259         vca_vpacker.pack_start (vca_label_bar, false, false);
260
261         vca_scroller_base.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
262         vca_scroller_base.set_name (X_("MixerWindow"));
263         vca_scroller_base.signal_button_release_event().connect (sigc::mem_fun(*this, &Mixer_UI::masters_scroller_button_release), false);
264         vca_hpacker.pack_end (vca_scroller_base, true, true);
265
266         vca_scroller.add (vca_hpacker);
267         vca_scroller.set_policy (Gtk::POLICY_ALWAYS, Gtk::POLICY_AUTOMATIC);
268         vca_scroller.signal_button_release_event().connect (sigc::mem_fun(*this, &Mixer_UI::strip_scroller_button_release));
269
270         vca_vpacker.pack_start (vca_scroller, true, true);
271
272         inner_pane.add (scroller);
273         inner_pane.add (vca_vpacker);
274
275         global_hpacker.pack_start (inner_pane, true, true);
276         global_hpacker.pack_start (out_packer, false, false);
277
278         list_hpane.add (list_vpacker);
279         list_hpane.add (global_hpacker);
280
281
282         XMLNode const * settings = ARDOUR_UI::instance()->mixer_settings();
283         XMLProperty const * prop;
284         float fract;
285
286         {
287                 LocaleGuard lg;
288
289                 if (!settings || ((prop = settings->property ("mixer-rhs-pane1-pos")) == 0) || ((fract = atof (prop->value())) > 1.0)) {
290                         rhs_pane1.set_divider (0, 0.6f);
291                 } else {
292                         rhs_pane1.set_divider (0, fract);
293                 }
294                 if (!settings || ((prop = settings->property ("mixer-rhs-pane2-pos")) == 0) || ((fract = atof (prop->value())) > 1.0)) {
295                         rhs_pane2.set_divider (0, 0.7f);
296                 } else {
297                         rhs_pane2.set_divider (0, fract);
298                 }
299                 if (!settings || ((prop = settings->property ("mixer-list-hpane-pos")) == 0) || ((fract = atof (prop->value())) > 1.0)) {
300                         list_hpane.set_divider (0, 0.2f);
301                 } else {
302                         list_hpane.set_divider (0, fract);
303                 }
304                 if (!settings || ((prop = settings->property ("mixer-inner-pane-pos")) == 0)  || ((fract = atof (prop->value())) > 1.0)) {
305                         inner_pane.set_divider (0, 0.8f);
306                 } else {
307                         inner_pane.set_divider (0, atof (prop->value()));
308                 }
309         }
310
311         rhs_pane1.set_drag_cursor (*PublicEditor::instance().cursors()->expand_up_down);
312         rhs_pane2.set_drag_cursor (*PublicEditor::instance().cursors()->expand_up_down);
313         list_hpane.set_drag_cursor (*PublicEditor::instance().cursors()->expand_left_right);
314         inner_pane.set_drag_cursor (*PublicEditor::instance().cursors()->expand_left_right);
315
316         _content.pack_start (list_hpane, true, true);
317
318         update_title ();
319
320         route_group_display_button_box->show();
321         route_group_add_button->show();
322         route_group_remove_button->show();
323
324         _content.show ();
325         _content.set_name ("MixerWindow");
326
327         global_hpacker.show();
328         scroller.show();
329         scroller_base.show();
330         scroller_hpacker.show();
331         mixer_scroller_vpacker.show();
332         list_vpacker.show();
333         group_display_button_label.show();
334         group_display_button.show();
335         group_display_scroller.show();
336         favorite_plugins_scroller.show();
337         group_display_vbox.show();
338         group_display_frame.show();
339         favorite_plugins_frame.show();
340         rhs_pane1.show();
341         rhs_pane2.show();
342         strip_packer.show();
343         inner_pane.show();
344         vca_top_padding->show ();
345         vca_scroller.show();
346         vca_vpacker.show();
347         vca_hpacker.show();
348         vca_label_bar.show();
349         vca_label.show();
350         vca_scroller_base.show();
351         out_packer.show();
352         list_hpane.show();
353         group_display.show();
354         favorite_plugins_display.show();
355
356         MixerStrip::CatchDeletion.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::remove_strip, this, _1), gui_context());
357
358         /* handle escape */
359
360         ARDOUR_UI::instance()->Escape.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::escape, this), gui_context());
361
362 #ifndef DEFER_PLUGIN_SELECTOR_LOAD
363         _plugin_selector = new PluginSelector (PluginManager::instance ());
364 #else
365 #error implement deferred Plugin-Favorite list
366 #endif
367         PluginManager::instance ().PluginListChanged.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::refill_favorite_plugins, this), gui_context());
368         PluginManager::instance ().PluginStatusesChanged.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::refill_favorite_plugins, this), gui_context());
369         ARDOUR::Plugin::PresetsChanged.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::refill_favorite_plugins, this), gui_context());
370 }
371
372 Mixer_UI::~Mixer_UI ()
373 {
374         if (_monitor_section) {
375                 monitor_section_detached ();
376                 delete _monitor_section;
377         }
378         delete _plugin_selector;
379 }
380
381 void
382 Mixer_UI::escape ()
383 {
384         select_none ();
385 }
386
387 void
388 Mixer_UI::track_editor_selection ()
389 {
390         PublicEditor::instance().get_selection().TracksChanged.connect (sigc::mem_fun (*this, &Mixer_UI::follow_editor_selection));
391 }
392
393 Gtk::Window*
394 Mixer_UI::use_own_window (bool and_fill_it)
395 {
396         bool new_window = !own_window();
397
398         Gtk::Window* win = Tabbable::use_own_window (and_fill_it);
399
400
401         if (win && new_window) {
402                 win->set_name ("MixerWindow");
403                 ARDOUR_UI::instance()->setup_toplevel_window (*win, _("Mixer"), this);
404                 win->signal_scroll_event().connect (sigc::mem_fun (*this, &Mixer_UI::on_scroll_event), false);
405                 win->signal_event().connect (sigc::bind (sigc::ptr_fun (&Keyboard::catch_user_event_for_pre_dialog_focus), win));
406                 win->set_data ("ardour-bindings", bindings);
407                 update_title ();
408         }
409
410         return win;
411 }
412
413 void
414 Mixer_UI::show_window ()
415 {
416         Tabbable::show_window ();
417
418         /* show/hide group tabs as required */
419         parameter_changed ("show-group-tabs");
420
421         /* now reset each strips width so the right widgets are shown */
422
423         TreeModel::Children rows = track_model->children();
424         TreeModel::Children::iterator ri;
425
426         for (ri = rows.begin(); ri != rows.end(); ++ri) {
427                 AxisView* av = (*ri)[stripable_columns.strip];
428                 MixerStrip* ms = dynamic_cast<MixerStrip*> (av);
429                 if (!ms) {
430                         continue;
431                 }
432                 ms->set_width_enum (ms->get_width_enum (), ms->width_owner());
433                 /* Fix visibility of mixer strip stuff */
434                 ms->parameter_changed (X_("mixer-element-visibility"));
435         }
436
437         /* force focus into main area */
438         scroller_base.grab_focus ();
439 }
440
441 void
442 Mixer_UI::remove_master (VCAMasterStrip* vms)
443 {
444         if (_session && _session->deletion_in_progress()) {
445                 /* its all being taken care of */
446                 return;
447         }
448
449         TreeModel::Children rows = track_model->children();
450         TreeModel::Children::iterator ri;
451
452         for (ri = rows.begin(); ri != rows.end(); ++ri) {
453                 if ((*ri)[stripable_columns.strip] == vms) {
454                         PBD::Unwinder<bool> uw (_route_deletion_in_progress, true);
455                         track_model->erase (ri);
456                         break;
457                 }
458         }
459 }
460
461 bool
462 Mixer_UI::masters_scroller_button_release (GdkEventButton* ev)
463 {
464         using namespace Menu_Helpers;
465
466         if (Keyboard::is_context_menu_event (ev)) {
467                 ARDOUR_UI::instance()->add_route ();
468                 return true;
469         }
470
471         return false;
472 }
473
474 void
475 Mixer_UI::add_masters (VCAList& vlist)
476 {
477         StripableList sl;
478
479         for (VCAList::iterator v = vlist.begin(); v != vlist.end(); ++v) {
480                 sl.push_back (boost::dynamic_pointer_cast<Stripable> (*v));
481         }
482
483         add_stripables (sl);
484 }
485
486 void
487 Mixer_UI::add_routes (RouteList& rlist)
488 {
489         StripableList sl;
490
491         for (RouteList::iterator r = rlist.begin(); r != rlist.end(); ++r) {
492                 sl.push_back (*r);
493         }
494
495         add_stripables (sl);
496 }
497
498 void
499 Mixer_UI::add_stripables (StripableList& slist)
500 {
501         Gtk::TreeModel::Children::iterator insert_iter = track_model->children().end();
502         bool from_scratch = (track_model->children().size() == 0);
503         uint32_t nroutes = 0;
504
505         slist.sort (StripablePresentationInfoSorter());
506
507         for (Gtk::TreeModel::Children::iterator it = track_model->children().begin(); it != track_model->children().end(); ++it) {
508                 boost::shared_ptr<Stripable> s = (*it)[stripable_columns.stripable];
509
510                 if (!s) {
511                         continue;
512                 }
513
514                 nroutes++;
515
516                 if (s->presentation_info().order() == (slist.front()->presentation_info().order() + slist.size())) {
517                         insert_iter = it;
518                         break;
519                 }
520         }
521
522         MixerStrip* strip;
523
524
525         try {
526                 PBD::Unwinder<bool> uw (no_track_list_redisplay, true);
527
528                 track_display.set_model (Glib::RefPtr<ListStore>());
529
530                 for (StripableList::iterator s = slist.begin(); s != slist.end(); ++s) {
531
532                         boost::shared_ptr<Route> route;
533                         boost::shared_ptr<VCA> vca;
534
535                         if ((vca  = boost::dynamic_pointer_cast<VCA> (*s))) {
536
537                                 VCAMasterStrip* vms = new VCAMasterStrip (_session, vca);
538
539                                 TreeModel::Row row = *(track_model->append());
540
541                                 row[stripable_columns.text] = vca->name();
542                                 row[stripable_columns.visible] = vms->marked_for_display ();
543                                 row[stripable_columns.strip] = vms;
544                                 row[stripable_columns.stripable] = vca;
545
546                                 vms->CatchDeletion.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::remove_master, this, _1), gui_context());
547
548                         } else if ((route = boost::dynamic_pointer_cast<Route> (*s))) {
549
550                                 if (route->is_auditioner()) {
551                                         continue;
552                                 }
553
554                                 if (route->is_monitor()) {
555
556                                         if (!_monitor_section) {
557                                                 _monitor_section = new MonitorSection (_session);
558
559                                                 XMLNode* mnode = ARDOUR_UI::instance()->tearoff_settings (X_("monitor-section"));
560                                                 if (mnode) {
561                                                         _monitor_section->tearoff().set_state (*mnode);
562                                                 }
563                                         }
564
565                                         out_packer.pack_end (_monitor_section->tearoff(), false, false);
566                                         _monitor_section->set_session (_session);
567                                         _monitor_section->tearoff().show_all ();
568
569                                         _monitor_section->tearoff().Detach.connect (sigc::mem_fun(*this, &Mixer_UI::monitor_section_detached));
570                                         _monitor_section->tearoff().Attach.connect (sigc::mem_fun(*this, &Mixer_UI::monitor_section_attached));
571
572                                         monitor_section_attached ();
573
574                                         route->DropReferences.connect (*this, invalidator(*this), boost::bind (&Mixer_UI::monitor_section_going_away, this), gui_context());
575
576                                         /* no regular strip shown for control out */
577
578                                         continue;
579                                 }
580
581                                 strip = new MixerStrip (*this, _session, route);
582                                 strips.push_back (strip);
583
584                                 UIConfiguration::instance().get_default_narrow_ms() ? _strip_width = Narrow : _strip_width = Wide;
585
586                                 if (strip->width_owner() != strip) {
587                                         strip->set_width_enum (_strip_width, this);
588                                 }
589
590                                 show_strip (strip);
591
592                                 if (!route->is_master()) {
593
594                                         TreeModel::Row row = *(track_model->insert (insert_iter));
595
596                                         row[stripable_columns.text] = route->name();
597                                         row[stripable_columns.visible] = strip->marked_for_display();
598                                         row[stripable_columns.stripable] = route;
599                                         row[stripable_columns.strip] = strip;
600
601                                         if (nroutes != 0) {
602                                                 _selection.add (strip);
603                                         }
604
605                                 } else {
606
607                                         out_packer.pack_start (*strip, false, false);
608                                         strip->set_packed (true);
609                                 }
610
611                                 strip->WidthChanged.connect (sigc::mem_fun(*this, &Mixer_UI::strip_width_changed));
612                                 strip->signal_button_release_event().connect (sigc::bind (sigc::mem_fun(*this, &Mixer_UI::strip_button_release_event), strip));
613                         }
614
615                         (*s)->presentation_info().PropertyChanged.connect (*this, invalidator(*this), boost::bind (&Mixer_UI::stripable_property_changed, this, _1, boost::weak_ptr<Stripable>(*s)), gui_context());
616                         (*s)->PropertyChanged.connect (*this, invalidator(*this), boost::bind (&Mixer_UI::stripable_property_changed, this, _1, boost::weak_ptr<Stripable>(*s)), gui_context());
617                                                 }
618
619         } catch (const std::exception& e) {
620                 error << string_compose (_("Error adding GUI elements for new tracks/busses %1"), e.what()) << endmsg;
621         }
622
623         track_display.set_model (track_model);
624
625         if (!from_scratch) {
626                 sync_presentation_info_from_treeview ();
627         }
628
629         redisplay_track_list ();
630 }
631
632 void
633 Mixer_UI::deselect_all_strip_processors ()
634 {
635         for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
636                 (*i)->deselect_all_processors();
637         }
638 }
639
640 void
641 Mixer_UI::select_strip (MixerStrip& ms, bool add)
642 {
643         if (add) {
644                 _selection.add (&ms);
645         } else {
646                 _selection.set (&ms);
647         }
648 }
649
650 void
651 Mixer_UI::select_none ()
652 {
653         _selection.clear_routes();
654         deselect_all_strip_processors();
655 }
656
657 void
658 Mixer_UI::delete_processors ()
659 {
660         for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
661                 (*i)->delete_processors();
662         }
663 }
664
665
666 void
667 Mixer_UI::remove_strip (MixerStrip* strip)
668 {
669         if (_session && _session->deletion_in_progress()) {
670                 /* its all being taken care of */
671                 return;
672         }
673
674         TreeModel::Children rows = track_model->children();
675         TreeModel::Children::iterator ri;
676         list<MixerStrip *>::iterator i;
677
678         if ((i = find (strips.begin(), strips.end(), strip)) != strips.end()) {
679                 strips.erase (i);
680         }
681
682         for (ri = rows.begin(); ri != rows.end(); ++ri) {
683                 if ((*ri)[stripable_columns.strip] == strip) {
684                         PBD::Unwinder<bool> uw (_route_deletion_in_progress, true);
685                         track_model->erase (ri);
686                         break;
687                 }
688         }
689 }
690
691 void
692 Mixer_UI::sync_presentation_info_from_treeview ()
693 {
694         if (ignore_reorder || !_session || _session->deletion_in_progress()) {
695                 return;
696         }
697
698         TreeModel::Children rows = track_model->children();
699
700         if (rows.empty()) {
701                 return;
702         }
703
704         DEBUG_TRACE (DEBUG::OrderKeys, "mixer sync presentation info from treeview\n");
705
706         TreeModel::Children::iterator ri;
707         bool change = false;
708         uint32_t order = 0;
709
710         for (ri = rows.begin(); ri != rows.end(); ++ri) {
711                 bool visible = (*ri)[stripable_columns.visible];
712                 boost::shared_ptr<Stripable> stripable = (*ri)[stripable_columns.stripable];
713
714                 if (!stripable) {
715                         continue;
716                 }
717
718                 /* Monitor and Auditioner do not get their presentation
719                  * info reset here.
720                  */
721
722                 if (stripable->is_monitor() || stripable->is_auditioner()) {
723                         continue;
724                 }
725
726                 /* Master also doesn't get set here but since the editor allows
727                  * it to be reordered, we need to preserve its ordering.
728                  */
729
730                 stripable->presentation_info().set_hidden (!visible);
731
732                 if (order != stripable->presentation_info().order()) {
733                         stripable->set_presentation_order_explicit (order);
734                         change = true;
735                 }
736
737                 ++order;
738         }
739
740         if (change) {
741                 DEBUG_TRACE (DEBUG::OrderKeys, "... notify PI change from mixer GUI\n");
742                 _session->notify_presentation_info_change ();
743         }
744 }
745
746 void
747 Mixer_UI::sync_treeview_from_presentation_info ()
748 {
749         if (!_session || _session->deletion_in_progress()) {
750                 return;
751         }
752
753         DEBUG_TRACE (DEBUG::OrderKeys, "mixer sync model from presentation info.\n");
754
755         /* we could get here after either a change in the Mixer or Editor sort
756          * order, but either way, the mixer order keys reflect the intended
757          * order for the GUI, so reorder the treeview model to match it.
758          */
759
760         vector<int> neworder;
761         TreeModel::Children rows = track_model->children();
762         uint32_t old_order = 0;
763         bool changed = false;
764
765         if (rows.empty()) {
766                 return;
767         }
768
769         OrderingKeys sorted;
770
771         for (TreeModel::Children::iterator ri = rows.begin(); ri != rows.end(); ++ri, ++old_order) {
772                 boost::shared_ptr<Stripable> stripable = (*ri)[stripable_columns.stripable];
773                 sorted.push_back (OrderKeys (old_order, stripable->presentation_info().order()));
774         }
775
776         SortByNewDisplayOrder cmp;
777
778         sort (sorted.begin(), sorted.end(), cmp);
779         neworder.assign (sorted.size(), 0);
780
781         uint32_t n = 0;
782
783         for (OrderingKeys::iterator sr = sorted.begin(); sr != sorted.end(); ++sr, ++n) {
784
785                 neworder[n] = sr->old_display_order;
786
787                 if (sr->old_display_order != n) {
788                         changed = true;
789                 }
790         }
791
792         if (changed) {
793                 Unwinder<bool> uw (ignore_reorder, true);
794                 track_model->reorder (neworder);
795         }
796
797         redisplay_track_list ();
798 }
799
800 void
801 Mixer_UI::follow_editor_selection ()
802 {
803         if (_following_editor_selection) {
804                 return;
805         }
806
807         _following_editor_selection = true;
808         _selection.block_routes_changed (true);
809
810         TrackSelection& s (PublicEditor::instance().get_selection().tracks);
811
812         _selection.clear_routes ();
813
814         for (TrackViewList::iterator i = s.begin(); i != s.end(); ++i) {
815                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*i);
816                 if (rtav) {
817                         MixerStrip* ms = strip_by_route (rtav->route());
818                         if (ms) {
819                                 _selection.add (ms);
820                         }
821                 }
822         }
823
824         _following_editor_selection = false;
825         _selection.block_routes_changed (false);
826 }
827
828
829 MixerStrip*
830 Mixer_UI::strip_by_route (boost::shared_ptr<Route> r)
831 {
832         for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
833                 if ((*i)->route() == r) {
834                         return (*i);
835                 }
836         }
837
838         return 0;
839 }
840
841 bool
842 Mixer_UI::strip_button_release_event (GdkEventButton *ev, MixerStrip *strip)
843 {
844         if (ev->button == 1) {
845                 if (_selection.selected (strip)) {
846                         /* primary-click: toggle selection state of strip */
847                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
848                                 _selection.remove (strip);
849                         } else if (_selection.routes.size() > 1) {
850                                 /* de-select others */
851                                 _selection.set (strip);
852                         }
853                 } else {
854                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
855                                 _selection.add (strip);
856                         } else if (Keyboard::modifier_state_equals (ev->state, Keyboard::RangeSelectModifier)) {
857
858                                 /* extend selection */
859
860                                 vector<MixerStrip*> tmp;
861                                 bool accumulate = false;
862                                 bool found_another = false;
863
864                                 tmp.push_back (strip);
865
866                                 for (list<MixerStrip*>::iterator i = strips.begin(); i != strips.end(); ++i) {
867                                         if ((*i) == strip) {
868                                                 /* hit clicked strip, start accumulating till we hit the first
869                                                    selected strip
870                                                 */
871                                                 if (accumulate) {
872                                                         /* done */
873                                                         break;
874                                                 } else {
875                                                         accumulate = true;
876                                                 }
877                                         } else if (_selection.selected (*i)) {
878                                                 /* hit selected strip. if currently accumulating others,
879                                                    we're done. if not accumulating others, start doing so.
880                                                 */
881                                                 found_another = true;
882                                                 if (accumulate) {
883                                                         /* done */
884                                                         break;
885                                                 } else {
886                                                         accumulate = true;
887                                                 }
888                                         } else {
889                                                 if (accumulate) {
890                                                         tmp.push_back (*i);
891                                                 }
892                                         }
893                                 }
894
895                                 if (found_another) {
896                                         for (vector<MixerStrip*>::iterator i = tmp.begin(); i != tmp.end(); ++i) {
897                                                 _selection.add (*i);
898                                         }
899                                 } else
900                                         _selection.set (strip);  //user wants to start a range selection, but there aren't any others selected yet
901                         } else {
902                                 _selection.set (strip);
903                         }
904                 }
905         }
906
907         return true;
908 }
909
910 void
911 Mixer_UI::set_session (Session* sess)
912 {
913         SessionHandlePtr::set_session (sess);
914
915         if (_plugin_selector) {
916                 _plugin_selector->set_session (_session);
917         }
918
919         _group_tabs->set_session (sess);
920
921         if (!_session) {
922                 return;
923         }
924
925         refill_favorite_plugins();
926
927         XMLNode* node = ARDOUR_UI::instance()->mixer_settings();
928         set_state (*node, 0);
929
930         update_title ();
931
932         initial_track_display ();
933
934         _session->RouteAdded.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::add_routes, this, _1), gui_context());
935         _session->route_group_added.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::add_route_group, this, _1), gui_context());
936         _session->route_group_removed.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::route_groups_changed, this), gui_context());
937         _session->route_groups_reordered.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::route_groups_changed, this), gui_context());
938         _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::parameter_changed, this, _1), gui_context());
939         _session->DirtyChanged.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::update_title, this), gui_context());
940         _session->StateSaved.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::update_title, this), gui_context());
941
942         _session->vca_manager().VCAAdded.connect (_session_connections, invalidator (*this), boost::bind (&Mixer_UI::add_masters, this, _1), gui_context());
943
944         Config->ParameterChanged.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::parameter_changed, this, _1), gui_context ());
945
946         route_groups_changed ();
947
948         if (_visible) {
949                 show_window();
950         }
951         start_updating ();
952 }
953
954 void
955 Mixer_UI::session_going_away ()
956 {
957         ENSURE_GUI_THREAD (*this, &Mixer_UI::session_going_away);
958
959         _in_group_rebuild_or_clear = true;
960         group_model->clear ();
961         _in_group_rebuild_or_clear = false;
962
963         _selection.clear ();
964         track_model->clear ();
965
966         for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
967                 delete (*i);
968         }
969
970         if (_monitor_section) {
971                 _monitor_section->tearoff().hide_visible ();
972         }
973
974         monitor_section_detached ();
975
976         strips.clear ();
977
978         stop_updating ();
979
980         SessionHandlePtr::session_going_away ();
981
982         _session = 0;
983         update_title ();
984 }
985
986 void
987 Mixer_UI::track_visibility_changed (std::string const & path)
988 {
989         if (_session && _session->deletion_in_progress()) {
990                 return;
991         }
992
993         TreeIter iter;
994
995         if ((iter = track_model->get_iter (path))) {
996
997                 AxisView* av = (*iter)[stripable_columns.strip];
998                 bool visible = (*iter)[stripable_columns.visible];
999
1000                 if (av->set_marked_for_display (!visible)) {
1001                         update_track_visibility ();
1002                 }
1003         }
1004 }
1005
1006 void
1007 Mixer_UI::update_track_visibility ()
1008 {
1009         TreeModel::Children rows = track_model->children();
1010         TreeModel::Children::iterator i;
1011
1012         {
1013                 Unwinder<bool> uw (no_track_list_redisplay, true);
1014
1015                 for (i = rows.begin(); i != rows.end(); ++i) {
1016                         AxisView* av = (*i)[stripable_columns.strip];
1017                         (*i)[stripable_columns.visible] = av->marked_for_display ();
1018                 }
1019
1020                 /* force presentation catch up with visibility changes
1021                  */
1022
1023                 sync_presentation_info_from_treeview ();
1024         }
1025
1026         redisplay_track_list ();
1027 }
1028
1029 void
1030 Mixer_UI::show_strip (MixerStrip* ms)
1031 {
1032         TreeModel::Children rows = track_model->children();
1033         TreeModel::Children::iterator i;
1034
1035         for (i = rows.begin(); i != rows.end(); ++i) {
1036
1037                 AxisView* av = (*i)[stripable_columns.strip];
1038                 MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1039                 if (strip == ms) {
1040                         (*i)[stripable_columns.visible] = true;
1041                         redisplay_track_list ();
1042                         break;
1043                 }
1044         }
1045 }
1046
1047 void
1048 Mixer_UI::hide_strip (MixerStrip* ms)
1049 {
1050         TreeModel::Children rows = track_model->children();
1051         TreeModel::Children::iterator i;
1052
1053         for (i = rows.begin(); i != rows.end(); ++i) {
1054
1055                 AxisView* av = (*i)[stripable_columns.strip];
1056                 MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1057                 if (strip == ms) {
1058                         (*i)[stripable_columns.visible] = false;
1059                         redisplay_track_list ();
1060                         break;
1061                 }
1062         }
1063 }
1064
1065 gint
1066 Mixer_UI::start_updating ()
1067 {
1068     fast_screen_update_connection = Timers::super_rapid_connect (sigc::mem_fun(*this, &Mixer_UI::fast_update_strips));
1069     return 0;
1070 }
1071
1072 gint
1073 Mixer_UI::stop_updating ()
1074 {
1075     fast_screen_update_connection.disconnect();
1076     return 0;
1077 }
1078
1079 void
1080 Mixer_UI::fast_update_strips ()
1081 {
1082         if (_content.is_mapped () && _session) {
1083                 for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
1084                         (*i)->fast_update ();
1085                 }
1086         }
1087 }
1088
1089 void
1090 Mixer_UI::set_all_strips_visibility (bool yn)
1091 {
1092         TreeModel::Children rows = track_model->children();
1093         TreeModel::Children::iterator i;
1094
1095         {
1096                 Unwinder<bool> uw (no_track_list_redisplay, true);
1097
1098                 for (i = rows.begin(); i != rows.end(); ++i) {
1099
1100                         AxisView* av = (*i)[stripable_columns.strip];
1101                         MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1102
1103                         if (!strip) {
1104                                 continue;
1105                         }
1106
1107                         if (strip->route()->is_master() || strip->route()->is_monitor()) {
1108                                 continue;
1109                         }
1110
1111                         (*i)[stripable_columns.visible] = yn;
1112                 }
1113         }
1114
1115         redisplay_track_list ();
1116 }
1117
1118
1119 void
1120 Mixer_UI::set_all_audio_midi_visibility (int tracks, bool yn)
1121 {
1122         TreeModel::Children rows = track_model->children();
1123         TreeModel::Children::iterator i;
1124
1125         {
1126                 Unwinder<bool> uw (no_track_list_redisplay, true);
1127
1128                 for (i = rows.begin(); i != rows.end(); ++i) {
1129
1130                         AxisView* av = (*i)[stripable_columns.strip];
1131                         MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1132
1133                         if (!strip) {
1134                                 continue;
1135                         }
1136
1137                         if (strip->route()->is_master() || strip->route()->is_monitor()) {
1138                                 continue;
1139                         }
1140
1141                         boost::shared_ptr<AudioTrack> at = strip->audio_track();
1142                         boost::shared_ptr<MidiTrack> mt = strip->midi_track();
1143
1144                         switch (tracks) {
1145                         case 0:
1146                                 (*i)[stripable_columns.visible] = yn;
1147                                 break;
1148
1149                         case 1:
1150                                 if (at) { /* track */
1151                                         (*i)[stripable_columns.visible] = yn;
1152                                 }
1153                                 break;
1154
1155                         case 2:
1156                                 if (!at && !mt) { /* bus */
1157                                         (*i)[stripable_columns.visible] = yn;
1158                                 }
1159                                 break;
1160
1161                         case 3:
1162                                 if (mt) { /* midi-track */
1163                                         (*i)[stripable_columns.visible] = yn;
1164                                 }
1165                                 break;
1166                         }
1167                 }
1168         }
1169
1170         redisplay_track_list ();
1171 }
1172
1173 void
1174 Mixer_UI::hide_all_routes ()
1175 {
1176         set_all_strips_visibility (false);
1177 }
1178
1179 void
1180 Mixer_UI::show_all_routes ()
1181 {
1182         set_all_strips_visibility (true);
1183 }
1184
1185 void
1186 Mixer_UI::show_all_audiobus ()
1187 {
1188         set_all_audio_midi_visibility (2, true);
1189 }
1190 void
1191 Mixer_UI::hide_all_audiobus ()
1192 {
1193         set_all_audio_midi_visibility (2, false);
1194 }
1195
1196 void
1197 Mixer_UI::show_all_audiotracks()
1198 {
1199         set_all_audio_midi_visibility (1, true);
1200 }
1201 void
1202 Mixer_UI::hide_all_audiotracks ()
1203 {
1204         set_all_audio_midi_visibility (1, false);
1205 }
1206
1207 void
1208 Mixer_UI::show_all_miditracks()
1209 {
1210         set_all_audio_midi_visibility (3, true);
1211 }
1212 void
1213 Mixer_UI::hide_all_miditracks ()
1214 {
1215         set_all_audio_midi_visibility (3, false);
1216 }
1217
1218 void
1219 Mixer_UI::track_list_reorder (const TreeModel::Path&, const TreeModel::iterator&, int* /*new_order*/)
1220 {
1221         DEBUG_TRACE (DEBUG::OrderKeys, "mixer UI treeview reordered\n");
1222         sync_presentation_info_from_treeview ();
1223 }
1224
1225 void
1226 Mixer_UI::track_list_delete (const Gtk::TreeModel::Path&)
1227 {
1228         /* this happens as the second step of a DnD within the treeview as well
1229            as when a row/route is actually deleted.
1230
1231            if it was a deletion then we have to force a redisplay because
1232            order keys may not have changed.
1233         */
1234
1235         DEBUG_TRACE (DEBUG::OrderKeys, "mixer UI treeview row deleted\n");
1236         sync_presentation_info_from_treeview ();
1237
1238         if (_route_deletion_in_progress) {
1239                 redisplay_track_list ();
1240         }
1241 }
1242
1243 void
1244 Mixer_UI::spill_redisplay (boost::shared_ptr<VCA> vca)
1245 {
1246         TreeModel::Children rows = track_model->children();
1247
1248         for (TreeModel::Children::iterator i = rows.begin(); i != rows.end(); ++i) {
1249
1250                 AxisView* av = (*i)[stripable_columns.strip];
1251                 MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1252
1253                 if (!strip) {
1254                         /* we're in the middle of changing a row, don't worry */
1255                         continue;
1256                 }
1257
1258                 if (!strip->route()) {
1259                         /* non-route element */
1260                         continue;
1261                 }
1262
1263                 if (strip->route()->is_master() || strip->route()->is_monitor()) {
1264                         continue;
1265                 }
1266
1267                 if (strip->route()->slaved_to (vca)) {
1268
1269                         if (strip->packed()) {
1270                                 strip_packer.reorder_child (*strip, -1); /* put at end */
1271                         } else {
1272                                 strip_packer.pack_start (*strip, false, false);
1273                                 strip->set_packed (true);
1274                         }
1275
1276                 } else {
1277
1278                         if (strip->packed()) {
1279                                 strip_packer.remove (*strip);
1280                                 strip->set_packed (false);
1281                         }
1282                 }
1283         }
1284 }
1285
1286 void
1287 Mixer_UI::redisplay_track_list ()
1288 {
1289         if (no_track_list_redisplay) {
1290                 return;
1291         }
1292
1293         boost::shared_ptr<VCA> sv = spilled_vca.lock ();
1294
1295         if (sv) {
1296                 spill_redisplay (sv);
1297                 return;
1298         }
1299
1300         TreeModel::Children rows = track_model->children();
1301         TreeModel::Children::iterator i;
1302         uint32_t n_masters = 0;
1303
1304         container_clear (vca_hpacker);
1305         vca_hpacker.pack_end (vca_scroller_base, true, true);
1306
1307         for (i = rows.begin(); i != rows.end(); ++i) {
1308
1309                 AxisView* s = (*i)[stripable_columns.strip];
1310                 bool const visible = (*i)[stripable_columns.visible];
1311                 boost::shared_ptr<Stripable> stripable = (*i)[stripable_columns.stripable];
1312
1313                 if (!s) {
1314                         /* we're in the middle of changing a row, don't worry */
1315                         continue;
1316                 }
1317
1318                 VCAMasterStrip* vms;
1319
1320                 if ((vms = dynamic_cast<VCAMasterStrip*> (s))) {
1321                         if (visible) {
1322                                 vca_hpacker.pack_start (*vms, false, false);
1323                                 vms->show ();
1324                                 n_masters++;
1325                         }
1326                         continue;
1327                 }
1328
1329                 MixerStrip* strip = dynamic_cast<MixerStrip*> (s);
1330
1331                 if (!strip) {
1332                         continue;
1333                 }
1334
1335                 if (visible) {
1336
1337                         if (strip->packed()) {
1338                                 strip_packer.reorder_child (*strip, -1); /* put at end */
1339                         } else {
1340                                 strip_packer.pack_start (*strip, false, false);
1341                                 strip->set_packed (true);
1342                         }
1343
1344                 } else {
1345
1346                         if (stripable->is_master() || stripable->is_monitor()) {
1347                                 /* do nothing, these cannot be hidden */
1348                         } else {
1349                                 if (strip->packed()) {
1350                                         strip_packer.remove (*strip);
1351                                         strip->set_packed (false);
1352                                 }
1353                         }
1354                 }
1355         }
1356
1357         /* update visibility of VCA assign buttons */
1358
1359         if (n_masters == 0) {
1360                 UIConfiguration::instance().set_mixer_strip_visibility (VisibilityGroup::remove_element (UIConfiguration::instance().get_mixer_strip_visibility(), X_("VCA")));
1361                 vca_scroller.hide ();
1362         } else {
1363                 UIConfiguration::instance().set_mixer_strip_visibility (VisibilityGroup::add_element (UIConfiguration::instance().get_mixer_strip_visibility(), X_("VCA")));
1364                 vca_scroller.show ();
1365         }
1366
1367         _group_tabs->set_dirty ();
1368 }
1369
1370 void
1371 Mixer_UI::strip_width_changed ()
1372 {
1373         _group_tabs->set_dirty ();
1374
1375 #ifdef __APPLE__
1376         TreeModel::Children rows = track_model->children();
1377         TreeModel::Children::iterator i;
1378         long order;
1379
1380         for (order = 0, i = rows.begin(); i != rows.end(); ++i, ++order) {
1381                 AxisView* av = (*i)[stripable_columns.strip];
1382                 MixerStrip* strip = dynamic_cast<MixerStrip*> (av);
1383
1384                 if (strip == 0) {
1385                         continue;
1386                 }
1387
1388                 bool visible = (*i)[stripable_columns.visible];
1389
1390                 if (visible) {
1391                         strip->queue_draw();
1392                 }
1393         }
1394 #endif
1395
1396 }
1397
1398 struct PresentationInfoMixerSorter
1399 {
1400         bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
1401                 if (a->is_master()) {
1402                         /* master after everything else */
1403                         return false;
1404                 } else if (b->is_master()) {
1405                         /* everything else before master */
1406                         return true;
1407                 }
1408                 return a->presentation_info().order () < b->presentation_info().order ();
1409         }
1410 };
1411
1412 void
1413 Mixer_UI::initial_track_display ()
1414 {
1415         StripableList sl;
1416
1417         boost::shared_ptr<RouteList> routes = _session->get_routes();
1418
1419         for (RouteList::iterator r = routes->begin(); r != routes->end(); ++r) {
1420                 sl.push_back (*r);
1421         }
1422
1423         VCAList vcas = _session->vca_manager().vcas();
1424
1425         for (VCAList::iterator v = vcas.begin(); v != vcas.end(); ++v) {
1426                 sl.push_back (boost::dynamic_pointer_cast<Stripable> (*v));
1427         }
1428
1429         sl.sort (PresentationInfoMixerSorter());
1430
1431         {
1432                 /* These are also used inside ::add_stripables() but we need
1433                  *  them here because we're going to clear the track_model also.
1434                  */
1435                 Unwinder<bool> uw1 (no_track_list_redisplay, true);
1436                 Unwinder<bool> uw2 (ignore_reorder, true);
1437
1438                 track_model->clear ();
1439                 add_stripables (sl);
1440         }
1441
1442         redisplay_track_list ();
1443 }
1444
1445 void
1446 Mixer_UI::show_track_list_menu ()
1447 {
1448         if (track_menu == 0) {
1449                 build_track_menu ();
1450         }
1451
1452         track_menu->popup (1, gtk_get_current_event_time());
1453 }
1454
1455 bool
1456 Mixer_UI::track_display_button_press (GdkEventButton* ev)
1457 {
1458         if (Keyboard::is_context_menu_event (ev)) {
1459                 show_track_list_menu ();
1460                 return true;
1461         }
1462
1463         return false;
1464 }
1465
1466 void
1467 Mixer_UI::build_track_menu ()
1468 {
1469         using namespace Menu_Helpers;
1470         using namespace Gtk;
1471
1472         track_menu = new Menu;
1473         track_menu->set_name ("ArdourContextMenu");
1474         MenuList& items = track_menu->items();
1475
1476         items.push_back (MenuElem (_("Show All"), sigc::mem_fun(*this, &Mixer_UI::show_all_routes)));
1477         items.push_back (MenuElem (_("Hide All"), sigc::mem_fun(*this, &Mixer_UI::hide_all_routes)));
1478         items.push_back (MenuElem (_("Show All Audio Tracks"), sigc::mem_fun(*this, &Mixer_UI::show_all_audiotracks)));
1479         items.push_back (MenuElem (_("Hide All Audio Tracks"), sigc::mem_fun(*this, &Mixer_UI::hide_all_audiotracks)));
1480         items.push_back (MenuElem (_("Show All Audio Busses"), sigc::mem_fun(*this, &Mixer_UI::show_all_audiobus)));
1481         items.push_back (MenuElem (_("Hide All Audio Busses"), sigc::mem_fun(*this, &Mixer_UI::hide_all_audiobus)));
1482         items.push_back (MenuElem (_("Show All Midi Tracks"), sigc::mem_fun (*this, &Mixer_UI::show_all_miditracks)));
1483         items.push_back (MenuElem (_("Hide All Midi Tracks"), sigc::mem_fun (*this, &Mixer_UI::hide_all_miditracks)));
1484
1485 }
1486
1487 void
1488 Mixer_UI::stripable_property_changed (const PropertyChange& what_changed, boost::weak_ptr<Stripable> ws)
1489 {
1490         if (!what_changed.contains (ARDOUR::Properties::hidden) && !what_changed.contains (ARDOUR::Properties::name)) {
1491                 return;
1492         }
1493
1494         boost::shared_ptr<Stripable> s = ws.lock ();
1495
1496         if (!s) {
1497                 return;
1498         }
1499
1500         TreeModel::Children rows = track_model->children();
1501         TreeModel::Children::iterator i;
1502
1503         for (i = rows.begin(); i != rows.end(); ++i) {
1504                 boost::shared_ptr<Stripable> ss = (*i)[stripable_columns.stripable];
1505
1506                 if (s == ss) {
1507
1508                         if (what_changed.contains (ARDOUR::Properties::name)) {
1509                                 (*i)[stripable_columns.text] = s->name();
1510                         }
1511
1512                         if (what_changed.contains (ARDOUR::Properties::hidden)) {
1513                                 (*i)[stripable_columns.visible] = !s->presentation_info().hidden();
1514                                 redisplay_track_list ();
1515                         }
1516
1517                         return;
1518                 }
1519         }
1520
1521         error << _("track display list item for renamed strip not found!") << endmsg;
1522 }
1523
1524 bool
1525 Mixer_UI::group_display_button_press (GdkEventButton* ev)
1526 {
1527         TreeModel::Path path;
1528         TreeViewColumn* column;
1529         int cellx;
1530         int celly;
1531
1532         if (!group_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
1533                 _group_tabs->get_menu(0)->popup (1, ev->time);
1534                 return true;
1535         }
1536
1537         TreeIter iter = group_model->get_iter (path);
1538         if (!iter) {
1539                 _group_tabs->get_menu(0)->popup (1, ev->time);
1540                 return true;
1541         }
1542
1543         RouteGroup* group = (*iter)[group_columns.group];
1544
1545         if (Keyboard::is_context_menu_event (ev)) {
1546                 _group_tabs->get_menu(group)->popup (1, ev->time);
1547                 return true;
1548         }
1549
1550         switch (GPOINTER_TO_UINT (column->get_data (X_("colnum")))) {
1551         case 0:
1552                 if (Keyboard::is_edit_event (ev)) {
1553                         if (group) {
1554                                 // edit_route_group (group);
1555 #ifdef __APPLE__
1556                                 group_display.queue_draw();
1557 #endif
1558                                 return true;
1559                         }
1560                 }
1561                 break;
1562
1563         case 1:
1564         {
1565                 bool visible = (*iter)[group_columns.visible];
1566                 (*iter)[group_columns.visible] = !visible;
1567 #ifdef __APPLE__
1568                 group_display.queue_draw();
1569 #endif
1570                 return true;
1571         }
1572
1573         default:
1574                 break;
1575         }
1576
1577         return false;
1578  }
1579
1580 void
1581 Mixer_UI::activate_all_route_groups ()
1582 {
1583         _session->foreach_route_group (sigc::bind (sigc::mem_fun (*this, &Mixer_UI::set_route_group_activation), true));
1584 }
1585
1586 void
1587 Mixer_UI::disable_all_route_groups ()
1588 {
1589         _session->foreach_route_group (sigc::bind (sigc::mem_fun (*this, &Mixer_UI::set_route_group_activation), false));
1590 }
1591
1592 void
1593 Mixer_UI::route_groups_changed ()
1594 {
1595         ENSURE_GUI_THREAD (*this, &Mixer_UI::route_groups_changed);
1596
1597         _in_group_rebuild_or_clear = true;
1598
1599         /* just rebuild the while thing */
1600
1601         group_model->clear ();
1602
1603 #if 0
1604         /* this is currently not used,
1605          * Mixer_UI::group_display_button_press() has a case for it,
1606          * and a commented edit_route_group() but that's n/a since 2011.
1607          *
1608          * This code is left as reminder that
1609          * row[group_columns.group] = 0 has special meaning.
1610          */
1611         {
1612                 TreeModel::Row row;
1613                 row = *(group_model->append());
1614                 row[group_columns.visible] = true;
1615                 row[group_columns.text] = (_("-all-"));
1616                 row[group_columns.group] = 0;
1617         }
1618 #endif
1619
1620         _session->foreach_route_group (sigc::mem_fun (*this, &Mixer_UI::add_route_group));
1621
1622         _group_tabs->set_dirty ();
1623         _in_group_rebuild_or_clear = false;
1624 }
1625
1626 void
1627 Mixer_UI::new_route_group ()
1628 {
1629         RouteList rl;
1630
1631         _group_tabs->run_new_group_dialog (rl, false);
1632 }
1633
1634 void
1635 Mixer_UI::remove_selected_route_group ()
1636 {
1637         Glib::RefPtr<TreeSelection> selection = group_display.get_selection();
1638         TreeView::Selection::ListHandle_Path rows = selection->get_selected_rows ();
1639
1640         if (rows.empty()) {
1641                 return;
1642         }
1643
1644         TreeView::Selection::ListHandle_Path::iterator i = rows.begin();
1645         TreeIter iter;
1646
1647         /* selection mode is single, so rows.begin() is it */
1648
1649         if ((iter = group_model->get_iter (*i))) {
1650
1651                 RouteGroup* rg = (*iter)[group_columns.group];
1652
1653                 if (rg) {
1654                         _session->remove_route_group (*rg);
1655                 }
1656         }
1657 }
1658
1659 void
1660 Mixer_UI::route_group_property_changed (RouteGroup* group, const PropertyChange& change)
1661 {
1662         if (in_group_row_change) {
1663                 return;
1664         }
1665
1666         /* force an update of any mixer strips that are using this group,
1667            otherwise mix group names don't change in mixer strips
1668         */
1669
1670         for (list<MixerStrip *>::iterator i = strips.begin(); i != strips.end(); ++i) {
1671                 if ((*i)->route_group() == group) {
1672                         (*i)->route_group_changed();
1673                 }
1674         }
1675
1676         TreeModel::iterator i;
1677         TreeModel::Children rows = group_model->children();
1678         Glib::RefPtr<TreeSelection> selection = group_display.get_selection();
1679
1680         in_group_row_change = true;
1681
1682         for (i = rows.begin(); i != rows.end(); ++i) {
1683                 if ((*i)[group_columns.group] == group) {
1684                         (*i)[group_columns.visible] = !group->is_hidden ();
1685                         (*i)[group_columns.text] = group->name ();
1686                         break;
1687                 }
1688         }
1689
1690         in_group_row_change = false;
1691
1692         if (change.contains (Properties::name)) {
1693                 _group_tabs->set_dirty ();
1694         }
1695
1696         for (list<MixerStrip*>::iterator j = strips.begin(); j != strips.end(); ++j) {
1697                 if ((*j)->route_group() == group) {
1698                         if (group->is_hidden ()) {
1699                                 hide_strip (*j);
1700                         } else {
1701                                 show_strip (*j);
1702                         }
1703                 }
1704         }
1705 }
1706
1707 void
1708 Mixer_UI::show_mixer_list (bool yn)
1709 {
1710         if (yn) {
1711                 list_vpacker.show ();
1712         } else {
1713                 list_vpacker.hide ();
1714         }
1715
1716         _show_mixer_list = yn;
1717 }
1718
1719 void
1720 Mixer_UI::show_monitor_section (bool yn)
1721 {
1722         if (!monitor_section()) {
1723                 return;
1724         }
1725         if (monitor_section()->tearoff().torn_off()) {
1726                 return;
1727         }
1728
1729         if (yn) {
1730                 monitor_section()->tearoff().show();
1731         } else {
1732                 monitor_section()->tearoff().hide();
1733         }
1734 }
1735
1736 void
1737 Mixer_UI::route_group_name_edit (const std::string& path, const std::string& new_text)
1738 {
1739         RouteGroup* group;
1740         TreeIter iter;
1741
1742         if ((iter = group_model->get_iter (path))) {
1743
1744                 if ((group = (*iter)[group_columns.group]) == 0) {
1745                         return;
1746                 }
1747
1748                 if (new_text != group->name()) {
1749                         group->set_name (new_text);
1750                 }
1751         }
1752 }
1753
1754 void
1755 Mixer_UI::route_group_row_change (const Gtk::TreeModel::Path&, const Gtk::TreeModel::iterator& iter)
1756 {
1757         RouteGroup* group;
1758
1759         if (in_group_row_change) {
1760                 return;
1761         }
1762
1763         if ((group = (*iter)[group_columns.group]) == 0) {
1764                 return;
1765         }
1766
1767         std::string name = (*iter)[group_columns.text];
1768
1769         if (name != group->name()) {
1770                 group->set_name (name);
1771         }
1772
1773         bool hidden = !(*iter)[group_columns.visible];
1774
1775         if (hidden != group->is_hidden ()) {
1776                 group->set_hidden (hidden, this);
1777         }
1778 }
1779
1780 /** Called when a group model row is deleted, but also when the model is
1781  *  reordered by a user drag-and-drop; the latter is what we are
1782  *  interested in here.
1783  */
1784 void
1785 Mixer_UI::route_group_row_deleted (Gtk::TreeModel::Path const &)
1786 {
1787         if (_in_group_rebuild_or_clear) {
1788                 return;
1789         }
1790
1791         /* Re-write the session's route group list so that the new order is preserved */
1792
1793         list<RouteGroup*> new_list;
1794
1795         Gtk::TreeModel::Children children = group_model->children();
1796         for (Gtk::TreeModel::Children::iterator i = children.begin(); i != children.end(); ++i) {
1797                 RouteGroup* g = (*i)[group_columns.group];
1798                 if (g) {
1799                         new_list.push_back (g);
1800                 }
1801         }
1802
1803         _session->reorder_route_groups (new_list);
1804 }
1805
1806
1807 void
1808 Mixer_UI::add_route_group (RouteGroup* group)
1809 {
1810         ENSURE_GUI_THREAD (*this, &Mixer_UI::add_route_group, group)
1811         bool focus = false;
1812
1813         in_group_row_change = true;
1814
1815         TreeModel::Row row = *(group_model->append());
1816         row[group_columns.visible] = !group->is_hidden ();
1817         row[group_columns.group] = group;
1818         if (!group->name().empty()) {
1819                 row[group_columns.text] = group->name();
1820         } else {
1821                 row[group_columns.text] = _("unnamed");
1822                 focus = true;
1823         }
1824
1825         group->PropertyChanged.connect (*this, invalidator (*this), boost::bind (&Mixer_UI::route_group_property_changed, this, group, _1), gui_context());
1826
1827         if (focus) {
1828                 TreeViewColumn* col = group_display.get_column (0);
1829                 CellRendererText* name_cell = dynamic_cast<CellRendererText*>(group_display.get_column_cell_renderer (0));
1830                 group_display.set_cursor (group_model->get_path (row), *col, *name_cell, true);
1831         }
1832
1833         _group_tabs->set_dirty ();
1834
1835         in_group_row_change = false;
1836 }
1837
1838 bool
1839 Mixer_UI::strip_scroller_button_release (GdkEventButton* ev)
1840 {
1841         using namespace Menu_Helpers;
1842
1843         if (Keyboard::is_context_menu_event (ev)) {
1844                 ARDOUR_UI::instance()->add_route ();
1845                 return true;
1846         }
1847
1848         return false;
1849 }
1850
1851 void
1852 Mixer_UI::scroller_drag_data_received (const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& data, guint info, guint time)
1853 {
1854         printf ("Mixer_UI::scroller_drag_data_received\n");
1855         if (data.get_target() != "PluginFavoritePtr") {
1856                 context->drag_finish (false, false, time);
1857                 return;
1858         }
1859
1860         const void * d = data.get_data();
1861         const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>* tv = reinterpret_cast<const Gtkmm2ext::DnDTreeView<ARDOUR::PluginPresetPtr>*>(d);
1862
1863         PluginPresetList nfos;
1864         TreeView* source;
1865         tv->get_object_drag_data (nfos, &source);
1866
1867         Route::ProcessorList pl;
1868         bool ok = false;
1869
1870         for (list<PluginPresetPtr>::const_iterator i = nfos.begin(); i != nfos.end(); ++i) {
1871                 PluginPresetPtr ppp = (*i);
1872                 PluginInfoPtr pip = ppp->_pip;
1873                 if (!pip->is_instrument ()) {
1874                         continue;
1875                 }
1876                 ARDOUR_UI::instance()->session_add_midi_track ((RouteGroup*) 0, 1, _("MIDI"), Config->get_strict_io (), pip, ppp->_preset.valid ? &ppp->_preset : 0, PresentationInfo::max_order);
1877                 ok = true;
1878         }
1879
1880         context->drag_finish (ok, false, time);
1881 }
1882
1883 void
1884 Mixer_UI::set_strip_width (Width w, bool save)
1885 {
1886         _strip_width = w;
1887
1888         for (list<MixerStrip*>::iterator i = strips.begin(); i != strips.end(); ++i) {
1889                 (*i)->set_width_enum (w, save ? (*i)->width_owner() : this);
1890         }
1891 }
1892
1893
1894 struct PluginStateSorter {
1895 public:
1896         bool operator() (PluginInfoPtr a, PluginInfoPtr b) const {
1897                 std::list<std::string>::const_iterator aiter = std::find(_user.begin(), _user.end(), (*a).unique_id);
1898                 std::list<std::string>::const_iterator biter = std::find(_user.begin(), _user.end(), (*b).unique_id);
1899                 if (aiter != _user.end() && biter != _user.end()) {
1900                         return std::distance (_user.begin(), aiter)  < std::distance (_user.begin(), biter);
1901                 }
1902                 if (aiter != _user.end()) {
1903                         return true;
1904                 }
1905                 if (biter != _user.end()) {
1906                         return false;
1907                 }
1908                 return ARDOUR::cmp_nocase((*a).name, (*b).name) == -1;
1909         }
1910
1911         PluginStateSorter(std::list<std::string> user) : _user (user)  {}
1912 private:
1913         std::list<std::string> _user;
1914 };
1915
1916 int
1917 Mixer_UI::set_state (const XMLNode& node, int version)
1918 {
1919         XMLProperty const * prop;
1920         LocaleGuard lg;
1921
1922         Tabbable::set_state (node, version);
1923
1924         if ((prop = node.property ("narrow-strips"))) {
1925                 if (string_is_affirmative (prop->value())) {
1926                         set_strip_width (Narrow);
1927                 } else {
1928                         set_strip_width (Wide);
1929                 }
1930         }
1931
1932         if ((prop = node.property ("show-mixer"))) {
1933                 if (string_is_affirmative (prop->value())) {
1934                        _visible = true;
1935                 }
1936         }
1937
1938         if ((prop = node.property ("maximised"))) {
1939                 bool yn = string_is_affirmative (prop->value());
1940                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Common"), X_("ToggleMaximalMixer"));
1941                 assert (act);
1942                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
1943                 bool fs = tact && tact->get_active();
1944                 if (yn ^ fs) {
1945                         ActionManager::do_action ("Common", "ToggleMaximalMixer");
1946                 }
1947         }
1948
1949         if ((prop = node.property ("show-mixer-list"))) {
1950                 bool yn = string_is_affirmative (prop->value());
1951                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Common"), X_("ToggleMixerList"));
1952                 assert (act);
1953                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
1954
1955                 /* do it twice to force the change */
1956                 tact->set_active (!yn);
1957                 tact->set_active (yn);
1958         }
1959
1960
1961         XMLNode* plugin_order;
1962         if ((plugin_order = find_named_node (node, "PluginOrder")) != 0) {
1963                 store_current_favorite_order ();
1964                 std::list<string> order;
1965                 const XMLNodeList& kids = plugin_order->children("PluginInfo");
1966                 XMLNodeConstIterator i;
1967                 for (i = kids.begin(); i != kids.end(); ++i) {
1968                         if ((prop = (*i)->property ("unique-id"))) {
1969                                 std::string unique_id = prop->value();
1970                                 order.push_back (unique_id);
1971                                 if ((prop = (*i)->property ("expanded"))) {
1972                                         favorite_ui_state[unique_id] = string_is_affirmative (prop->value());
1973                                 }
1974                         }
1975                 }
1976                 PluginStateSorter cmp (order);
1977                 favorite_order.sort (cmp);
1978                 sync_treeview_from_favorite_order ();
1979         }
1980         return 0;
1981 }
1982
1983 XMLNode&
1984 Mixer_UI::get_state ()
1985 {
1986         XMLNode* node = new XMLNode (X_("Mixer"));
1987         char buf[128];
1988         LocaleGuard lg;
1989
1990         node->add_child_nocopy (Tabbable::get_state());
1991
1992         snprintf(buf,sizeof(buf), "%f", rhs_pane1.get_divider());
1993         node->add_property(X_("mixer-rhs-pane1-pos"), string(buf));
1994         snprintf(buf,sizeof(buf), "%f", rhs_pane2.get_divider());
1995         node->add_property(X_("mixer-rhs_pane2-pos"), string(buf));
1996         snprintf(buf,sizeof(buf), "%f", list_hpane.get_divider());
1997         node->add_property(X_("mixer-list-hpane-pos"), string(buf));
1998         snprintf(buf,sizeof(buf), "%f", inner_pane.get_divider());
1999         node->add_property(X_("mixer-inner-pane-pos"), string(buf));
2000
2001         node->add_property ("narrow-strips", _strip_width == Narrow ? "yes" : "no");
2002         node->add_property ("show-mixer", _visible ? "yes" : "no");
2003         node->add_property ("show-mixer-list", _show_mixer_list ? "yes" : "no");
2004         node->add_property ("maximised", _maximised ? "yes" : "no");
2005
2006         store_current_favorite_order ();
2007         XMLNode* plugin_order = new XMLNode ("PluginOrder");
2008         int cnt = 0;
2009         for (PluginInfoList::const_iterator i = favorite_order.begin(); i != favorite_order.end(); ++i, ++cnt) {
2010                 XMLNode* p = new XMLNode ("PluginInfo");
2011                 p->add_property ("sort", cnt);
2012                 p->add_property ("unique-id", (*i)->unique_id);
2013                 if (favorite_ui_state.find ((*i)->unique_id) != favorite_ui_state.end ()) {
2014                         p->add_property ("expanded", favorite_ui_state[(*i)->unique_id]);
2015                 }
2016                 plugin_order->add_child_nocopy (*p);
2017         }
2018         node->add_child_nocopy (*plugin_order);
2019
2020         return *node;
2021 }
2022
2023 void
2024 Mixer_UI::scroll_left ()
2025 {
2026         if (!scroller.get_hscrollbar()) return;
2027         Adjustment* adj = scroller.get_hscrollbar()->get_adjustment();
2028         /* stupid GTK: can't rely on clamping across versions */
2029         scroller.get_hscrollbar()->set_value (max (adj->get_lower(), adj->get_value() - adj->get_step_increment()));
2030 }
2031
2032 void
2033 Mixer_UI::scroll_right ()
2034 {
2035         if (!scroller.get_hscrollbar()) return;
2036         Adjustment* adj = scroller.get_hscrollbar()->get_adjustment();
2037         /* stupid GTK: can't rely on clamping across versions */
2038         scroller.get_hscrollbar()->set_value (min (adj->get_upper(), adj->get_value() + adj->get_step_increment()));
2039 }
2040
2041 bool
2042 Mixer_UI::on_scroll_event (GdkEventScroll* ev)
2043 {
2044         switch (ev->direction) {
2045         case GDK_SCROLL_LEFT:
2046                 scroll_left ();
2047                 return true;
2048         case GDK_SCROLL_UP:
2049                 if (ev->state & Keyboard::TertiaryModifier) {
2050                         scroll_left ();
2051                         return true;
2052                 }
2053                 return false;
2054
2055         case GDK_SCROLL_RIGHT:
2056                 scroll_right ();
2057                 return true;
2058
2059         case GDK_SCROLL_DOWN:
2060                 if (ev->state & Keyboard::TertiaryModifier) {
2061                         scroll_right ();
2062                         return true;
2063                 }
2064                 return false;
2065         }
2066
2067         return false;
2068 }
2069
2070
2071 void
2072 Mixer_UI::parameter_changed (string const & p)
2073 {
2074         if (p == "show-group-tabs") {
2075                 bool const s = _session->config.get_show_group_tabs ();
2076                 if (s) {
2077                         _group_tabs->show ();
2078                 } else {
2079                         _group_tabs->hide ();
2080                 }
2081         } else if (p == "default-narrow_ms") {
2082                 bool const s = UIConfiguration::instance().get_default_narrow_ms ();
2083                 for (list<MixerStrip*>::iterator i = strips.begin(); i != strips.end(); ++i) {
2084                         (*i)->set_width_enum (s ? Narrow : Wide, this);
2085                 }
2086         } else if (p == "use-monitor-bus") {
2087                 if (_session && !_session->monitor_out()) {
2088                         monitor_section_detached ();
2089                 }
2090         }
2091 }
2092
2093 void
2094 Mixer_UI::set_route_group_activation (RouteGroup* g, bool a)
2095 {
2096         g->set_active (a, this);
2097 }
2098
2099 PluginSelector*
2100 Mixer_UI::plugin_selector()
2101 {
2102 #ifdef DEFER_PLUGIN_SELECTOR_LOAD
2103         if (!_plugin_selector)
2104                 _plugin_selector = new PluginSelector (PluginManager::instance());
2105 #endif
2106
2107         return _plugin_selector;
2108 }
2109
2110 void
2111 Mixer_UI::setup_track_display ()
2112 {
2113         track_model = ListStore::create (stripable_columns);
2114         track_display.set_model (track_model);
2115         track_display.append_column (_("Strips"), stripable_columns.text);
2116         track_display.append_column (_("Show"), stripable_columns.visible);
2117         track_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
2118         track_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
2119         track_display.get_column (0)->set_expand(true);
2120         track_display.get_column (1)->set_expand(false);
2121         track_display.get_column (0)->set_sizing (Gtk::TREE_VIEW_COLUMN_FIXED);
2122         track_display.set_name (X_("EditGroupList"));
2123         track_display.get_selection()->set_mode (Gtk::SELECTION_NONE);
2124         track_display.set_reorderable (true);
2125         track_display.set_headers_visible (true);
2126         track_display.set_can_focus(false);
2127
2128         track_model->signal_row_deleted().connect (sigc::mem_fun (*this, &Mixer_UI::track_list_delete));
2129         track_model->signal_rows_reordered().connect (sigc::mem_fun (*this, &Mixer_UI::track_list_reorder));
2130
2131         CellRendererToggle* track_list_visible_cell = dynamic_cast<CellRendererToggle*>(track_display.get_column_cell_renderer (1));
2132         track_list_visible_cell->property_activatable() = true;
2133         track_list_visible_cell->property_radio() = false;
2134         track_list_visible_cell->signal_toggled().connect (sigc::mem_fun (*this, &Mixer_UI::track_visibility_changed));
2135
2136         track_display.signal_button_press_event().connect (sigc::mem_fun (*this, &Mixer_UI::track_display_button_press), false);
2137
2138         track_display_scroller.add (track_display);
2139         track_display_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
2140
2141         VBox* v = manage (new VBox);
2142         v->show ();
2143         v->pack_start (track_display_scroller, true, true);
2144
2145         Button* b = manage (new Button);
2146         b->show ();
2147         Widget* w = manage (new Image (Stock::ADD, ICON_SIZE_BUTTON));
2148         w->show ();
2149         b->add (*w);
2150
2151         b->signal_clicked().connect (sigc::mem_fun (*this, &Mixer_UI::new_track_or_bus));
2152
2153         v->pack_start (*b, false, false);
2154
2155         track_display_frame.set_name("BaseFrame");
2156         track_display_frame.set_shadow_type (Gtk::SHADOW_IN);
2157         track_display_frame.add (*v);
2158
2159         track_display_scroller.show();
2160         track_display_frame.show();
2161         track_display.show();
2162 }
2163
2164 void
2165 Mixer_UI::new_track_or_bus ()
2166 {
2167         ARDOUR_UI::instance()->add_route ();
2168 }
2169
2170 void
2171 Mixer_UI::update_title ()
2172 {
2173         if (!own_window()) {
2174                 return;
2175         }
2176
2177         if (_session) {
2178                 string n;
2179
2180                 if (_session->snap_name() != _session->name()) {
2181                         n = _session->snap_name ();
2182                 } else {
2183                         n = _session->name ();
2184                 }
2185
2186                 if (_session->dirty ()) {
2187                         n = "*" + n;
2188                 }
2189
2190                 WindowTitle title (n);
2191                 title += S_("Window|Mixer");
2192                 title += Glib::get_application_name ();
2193                 own_window()->set_title (title.get_string());
2194
2195         } else {
2196
2197                 WindowTitle title (S_("Window|Mixer"));
2198                 title += Glib::get_application_name ();
2199                 own_window()->set_title (title.get_string());
2200         }
2201 }
2202
2203 MixerStrip*
2204 Mixer_UI::strip_by_x (int x)
2205 {
2206         for (list<MixerStrip*>::iterator i = strips.begin(); i != strips.end(); ++i) {
2207                 int x1, x2, y;
2208
2209                 (*i)->translate_coordinates (_content, 0, 0, x1, y);
2210                 x2 = x1 + (*i)->get_width();
2211
2212                 if (x >= x1 && x <= x2) {
2213                         return (*i);
2214                 }
2215         }
2216
2217         return 0;
2218 }
2219
2220 void
2221 Mixer_UI::set_route_targets_for_operation ()
2222 {
2223         _route_targets.clear ();
2224
2225         if (!_selection.empty()) {
2226                 _route_targets = _selection.routes;
2227                 return;
2228         }
2229
2230 //  removed "implicit" selections of strips, after discussion on IRC
2231
2232 }
2233
2234 void
2235 Mixer_UI::monitor_section_going_away ()
2236 {
2237         if (_monitor_section) {
2238                 monitor_section_detached ();
2239                 out_packer.remove (_monitor_section->tearoff());
2240                 _monitor_section->set_session (0);
2241                 delete _monitor_section;
2242                 _monitor_section = 0;
2243         }
2244 }
2245
2246 void
2247 Mixer_UI::toggle_midi_input_active (bool flip_others)
2248 {
2249         boost::shared_ptr<RouteList> rl (new RouteList);
2250         bool onoff = false;
2251
2252         set_route_targets_for_operation ();
2253
2254         for (RouteUISelection::iterator r = _route_targets.begin(); r != _route_targets.end(); ++r) {
2255                 boost::shared_ptr<MidiTrack> mt = (*r)->midi_track();
2256
2257                 if (mt) {
2258                         rl->push_back ((*r)->route());
2259                         onoff = !mt->input_active();
2260                 }
2261         }
2262
2263         _session->set_exclusive_input_active (rl, onoff, flip_others);
2264 }
2265
2266 void
2267 Mixer_UI::maximise_mixer_space ()
2268 {
2269         if (!own_window()) {
2270                 return;
2271         }
2272
2273         if (_maximised) {
2274                 return;
2275         }
2276
2277         _window->fullscreen ();
2278         _maximised = true;
2279 }
2280
2281 void
2282 Mixer_UI::restore_mixer_space ()
2283 {
2284         if (!own_window()) {
2285                 return;
2286         }
2287
2288         if (!_maximised) {
2289                 return;
2290         }
2291
2292         own_window()->unfullscreen();
2293         _maximised = false;
2294 }
2295
2296 void
2297 Mixer_UI::monitor_section_attached ()
2298 {
2299         Glib::RefPtr<Action> act = ActionManager::get_action ("Common", "ToggleMonitorSection");
2300         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2301         act->set_sensitive (true);
2302         tact->set_active ();
2303 }
2304
2305 void
2306 Mixer_UI::monitor_section_detached ()
2307 {
2308         Glib::RefPtr<Action> act = ActionManager::get_action ("Common", "ToggleMonitorSection");
2309         act->set_sensitive (false);
2310 }
2311
2312 void
2313 Mixer_UI::store_current_favorite_order ()
2314 {
2315         typedef Gtk::TreeModel::Children type_children;
2316         type_children children = favorite_plugins_model->children();
2317         favorite_order.clear();
2318         for(type_children::iterator iter = children.begin(); iter != children.end(); ++iter)
2319         {
2320                 Gtk::TreeModel::Row row = *iter;
2321                 ARDOUR::PluginPresetPtr ppp = row[favorite_plugins_columns.plugin];
2322                 favorite_order.push_back (ppp->_pip);
2323                 std::string name = row[favorite_plugins_columns.name];
2324                 favorite_ui_state[(*ppp->_pip).unique_id] = favorite_plugins_display.row_expanded (favorite_plugins_model->get_path(iter));
2325         }
2326 }
2327
2328 void
2329 Mixer_UI::save_favorite_ui_state (const TreeModel::iterator& iter, const TreeModel::Path& path)
2330 {
2331         Gtk::TreeModel::Row row = *iter;
2332         ARDOUR::PluginPresetPtr ppp = row[favorite_plugins_columns.plugin];
2333         assert (ppp);
2334         favorite_ui_state[(*ppp->_pip).unique_id] = favorite_plugins_display.row_expanded (favorite_plugins_model->get_path(iter));
2335 }
2336
2337 void
2338 Mixer_UI::refiller (PluginInfoList& result, const PluginInfoList& plugs)
2339 {
2340         PluginManager& manager (PluginManager::instance());
2341         for (PluginInfoList::const_iterator i = plugs.begin(); i != plugs.end(); ++i) {
2342                 if (manager.get_status (*i) != PluginManager::Favorite) {
2343                         continue;
2344                 }
2345                 result.push_back (*i);
2346         }
2347 }
2348
2349 struct PluginCustomSorter {
2350 public:
2351         bool operator() (PluginInfoPtr a, PluginInfoPtr b) const {
2352                 PluginInfoList::const_iterator aiter = _user.begin();
2353                 PluginInfoList::const_iterator biter = _user.begin();
2354                 while (aiter != _user.end()) { if ((*aiter)->unique_id == a->unique_id) { break; } ++aiter; }
2355                 while (biter != _user.end()) { if ((*biter)->unique_id == b->unique_id) { break; } ++biter; }
2356
2357                 if (aiter != _user.end() && biter != _user.end()) {
2358                         return std::distance (_user.begin(), aiter) < std::distance (_user.begin(), biter);
2359                 }
2360                 if (aiter != _user.end()) {
2361                         return true;
2362                 }
2363                 if (biter != _user.end()) {
2364                         return false;
2365                 }
2366                 return ARDOUR::cmp_nocase((*a).name, (*b).name) == -1;
2367         }
2368         PluginCustomSorter(PluginInfoList user) : _user (user)  {}
2369 private:
2370         PluginInfoList _user;
2371 };
2372
2373 void
2374 Mixer_UI::refill_favorite_plugins ()
2375 {
2376         PluginInfoList plugs;
2377         PluginManager& mgr (PluginManager::instance());
2378
2379 #ifdef LV2_SUPPORT
2380         refiller (plugs, mgr.lv2_plugin_info ());
2381 #endif
2382 #ifdef WINDOWS_VST_SUPPORT
2383         refiller (plugs, mgr.windows_vst_plugin_info ());
2384 #endif
2385 #ifdef LXVST_SUPPORT
2386         refiller (plugs, mgr.lxvst_plugin_info ());
2387 #endif
2388 #ifdef AUDIOUNIT_SUPPORT
2389         refiller (plugs, mgr.au_plugin_info ());
2390 #endif
2391         refiller (plugs, mgr.ladspa_plugin_info ());
2392         refiller (plugs, mgr.lua_plugin_info ());
2393
2394         store_current_favorite_order ();
2395
2396         PluginCustomSorter cmp (favorite_order);
2397         plugs.sort (cmp);
2398
2399         favorite_order = plugs;
2400
2401         sync_treeview_from_favorite_order ();
2402 }
2403
2404 void
2405 Mixer_UI::sync_treeview_favorite_ui_state (const TreeModel::Path& path, const TreeModel::iterator&)
2406 {
2407         TreeIter iter;
2408         if (!(iter = favorite_plugins_model->get_iter (path))) {
2409                 return;
2410         }
2411         ARDOUR::PluginPresetPtr ppp = (*iter)[favorite_plugins_columns.plugin];
2412         if (!ppp) {
2413                 return;
2414         }
2415         PluginInfoPtr pip = ppp->_pip;
2416         if (favorite_ui_state.find (pip->unique_id) != favorite_ui_state.end ()) {
2417                 if (favorite_ui_state[pip->unique_id]) {
2418                         favorite_plugins_display.expand_row (path, true);
2419                 }
2420         }
2421 }
2422
2423 void
2424 Mixer_UI::sync_treeview_from_favorite_order ()
2425 {
2426         favorite_plugins_model->clear ();
2427         for (PluginInfoList::const_iterator i = favorite_order.begin(); i != favorite_order.end(); ++i) {
2428                 PluginInfoPtr pip = (*i);
2429
2430                 TreeModel::Row newrow = *(favorite_plugins_model->append());
2431                 newrow[favorite_plugins_columns.name] = (*i)->name;
2432                 newrow[favorite_plugins_columns.plugin] = PluginPresetPtr (new PluginPreset(pip));
2433                 if (!_session) {
2434                         continue;
2435                 }
2436
2437                 vector<ARDOUR::Plugin::PresetRecord> presets = (*i)->get_presets (true);
2438                 for (vector<ARDOUR::Plugin::PresetRecord>::const_iterator j = presets.begin(); j != presets.end(); ++j) {
2439                         Gtk::TreeModel::Row child_row = *(favorite_plugins_model->append (newrow.children()));
2440                         child_row[favorite_plugins_columns.name] = (*j).label;
2441                         child_row[favorite_plugins_columns.plugin] = PluginPresetPtr (new PluginPreset(pip, &(*j)));
2442                 }
2443                 if (favorite_ui_state.find (pip->unique_id) != favorite_ui_state.end ()) {
2444                         if (favorite_ui_state[pip->unique_id]) {
2445                                 favorite_plugins_display.expand_row (favorite_plugins_model->get_path(newrow), true);
2446                         }
2447                 }
2448         }
2449 }
2450
2451 void
2452 Mixer_UI::popup_note_context_menu (GdkEventButton *ev)
2453 {
2454         using namespace Gtk::Menu_Helpers;
2455
2456         Gtk::Menu* m = manage (new Menu);
2457         MenuList& items = m->items ();
2458
2459         if (_selection.routes.empty()) {
2460                 items.push_back (MenuElem (_("No Track/Bus is selected.")));
2461         } else {
2462                 items.push_back (MenuElem (_("Add at the top"),
2463                                         sigc::bind (sigc::mem_fun (*this, &Mixer_UI::add_selected_processor), AddTop)));
2464                 items.push_back (MenuElem (_("Add Pre-Fader"),
2465                                         sigc::bind (sigc::mem_fun (*this, &Mixer_UI::add_selected_processor), AddPreFader)));
2466                 items.push_back (MenuElem (_("Add Post-Fader"),
2467                                         sigc::bind (sigc::mem_fun (*this, &Mixer_UI::add_selected_processor), AddPostFader)));
2468                 items.push_back (MenuElem (_("Add at the end"),
2469                                         sigc::bind (sigc::mem_fun (*this, &Mixer_UI::add_selected_processor), AddBottom)));
2470         }
2471
2472         items.push_back (SeparatorElem());
2473
2474         items.push_back (MenuElem (_("Remove from favorites"), sigc::mem_fun (*this, &Mixer_UI::remove_selected_from_favorites)));
2475
2476         ARDOUR::PluginPresetPtr ppp = selected_plugin();
2477         if (ppp && ppp->_preset.valid && ppp->_preset.user) {
2478                 // we cannot currently delete AU presets
2479                 if (!ppp->_pip || ppp->_pip->type != AudioUnit) {
2480                         items.push_back (MenuElem (_("Delete Preset"), sigc::mem_fun (*this, &Mixer_UI::delete_selected_preset)));
2481                 }
2482         }
2483
2484         m->popup (ev->button, ev->time);
2485 }
2486
2487 bool
2488 Mixer_UI::plugin_row_button_press (GdkEventButton *ev)
2489 {
2490         if ((ev->type == GDK_BUTTON_PRESS) && (ev->button == 3) ) {
2491                 TreeModel::Path path;
2492                 TreeViewColumn* column;
2493                 int cellx, celly;
2494                 if (favorite_plugins_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
2495                         Glib::RefPtr<Gtk::TreeView::Selection> selection = favorite_plugins_display.get_selection();
2496                         if (selection) {
2497                                 selection->unselect_all();
2498                                 selection->select(path);
2499                         }
2500                 }
2501                 ARDOUR::PluginPresetPtr ppp = selected_plugin();
2502                 if (ppp) {
2503                         popup_note_context_menu (ev);
2504                 }
2505         }
2506         return false;
2507 }
2508
2509
2510 PluginPresetPtr
2511 Mixer_UI::selected_plugin ()
2512 {
2513         Glib::RefPtr<Gtk::TreeView::Selection> selection = favorite_plugins_display.get_selection();
2514         if (!selection) {
2515                 return PluginPresetPtr();
2516         }
2517         Gtk::TreeModel::iterator iter = selection->get_selected();
2518         if (!iter) {
2519                 return PluginPresetPtr();
2520         }
2521         return (*iter)[favorite_plugins_columns.plugin];
2522 }
2523
2524 void
2525 Mixer_UI::add_selected_processor (ProcessorPosition pos)
2526 {
2527         ARDOUR::PluginPresetPtr ppp = selected_plugin();
2528         if (ppp) {
2529                 add_favorite_processor (ppp, pos);
2530         }
2531 }
2532
2533 void
2534 Mixer_UI::delete_selected_preset ()
2535 {
2536         if (!_session) {
2537                 return;
2538         }
2539         ARDOUR::PluginPresetPtr ppp = selected_plugin();
2540         if (!ppp || !ppp->_preset.valid || !ppp->_preset.user) {
2541                 return;
2542         }
2543         PluginPtr plugin = ppp->_pip->load (*_session);
2544         plugin->get_presets();
2545         plugin->remove_preset (ppp->_preset.label);
2546 }
2547
2548 void
2549 Mixer_UI::remove_selected_from_favorites ()
2550 {
2551         ARDOUR::PluginPresetPtr ppp = selected_plugin();
2552         if (!ppp) {
2553                 return;
2554         }
2555         PluginManager::PluginStatusType status = PluginManager::Normal;
2556         PluginManager& manager (PluginManager::instance());
2557
2558         manager.set_status (ppp->_pip->type, ppp->_pip->unique_id, status);
2559         manager.save_statuses ();
2560 }
2561
2562 void
2563 Mixer_UI::plugin_row_activated (const TreeModel::Path& path, TreeViewColumn* column)
2564 {
2565         TreeIter iter;
2566         if (!(iter = favorite_plugins_model->get_iter (path))) {
2567                 return;
2568         }
2569         ARDOUR::PluginPresetPtr ppp = (*iter)[favorite_plugins_columns.plugin];
2570         add_favorite_processor (ppp, AddPreFader); // TODO: preference?!
2571 }
2572
2573 void
2574 Mixer_UI::add_favorite_processor (ARDOUR::PluginPresetPtr ppp, ProcessorPosition pos)
2575 {
2576         if (!_session || _selection.routes.empty()) {
2577                 return;
2578         }
2579
2580         PluginInfoPtr pip = ppp->_pip;
2581         for (RouteUISelection::iterator i = _selection.routes.begin(); i != _selection.routes.end(); ++i) {
2582                 boost::shared_ptr<ARDOUR::Route> rt = (*i)->route();
2583                 if (!rt) { continue; }
2584
2585                 PluginPtr p = pip->load (*_session);
2586                 if (!p) { continue; }
2587
2588                 if (ppp->_preset.valid) {
2589                         p->load_preset (ppp->_preset);
2590                 }
2591
2592                 Route::ProcessorStreams err;
2593                 boost::shared_ptr<Processor> processor (new PluginInsert (*_session, p));
2594
2595                 switch (pos) {
2596                         case AddTop:
2597                                 rt->add_processor_by_index (processor, 0, &err, Config->get_new_plugins_active ());
2598                                 break;
2599                         case AddPreFader:
2600                                 rt->add_processor (processor, PreFader, &err, Config->get_new_plugins_active ());
2601                                 break;
2602                         case AddPostFader:
2603                                 {
2604                                         int idx = 0;
2605                                         int pos = 0;
2606                                         for (;;++idx) {
2607                                                 boost::shared_ptr<Processor> np = rt->nth_processor (idx);
2608                                                 if (!np) {
2609                                                         break;
2610                                                 }
2611                                                 if (!np->display_to_user()) {
2612                                                         continue;
2613                                                 }
2614                                                 if (boost::dynamic_pointer_cast<Amp> (np) && // Fader, not Trim
2615                                                                 boost::dynamic_pointer_cast<Amp> (np)->gain_control()->parameter().type() == GainAutomation) {
2616                                                         break;
2617                                                 }
2618                                                 ++pos;
2619                                         }
2620                                         rt->add_processor_by_index (processor, ++pos, &err, Config->get_new_plugins_active ());
2621                                 }
2622                                 break;
2623                         case AddBottom:
2624                                 rt->add_processor_by_index (processor, -1, &err, Config->get_new_plugins_active ());
2625                                 break;
2626                 }
2627         }
2628 }
2629
2630 bool
2631 PluginTreeStore::row_drop_possible_vfunc(const Gtk::TreeModel::Path& dest, const Gtk::SelectionData& data) const
2632 {
2633         if (data.get_target() != "GTK_TREE_MODEL_ROW") {
2634                 return false;
2635         }
2636
2637         // only allow to re-order top-level items
2638         TreePath src;
2639         if (TreePath::get_from_selection_data (data, src)) {
2640                 if (src.up() && src.up()) {
2641                         return false;
2642                 }
2643         }
2644
2645         // don't allow to drop as child-rows.
2646         Gtk::TreeModel::Path _dest = dest; // un const
2647         const bool is_child = _dest.up (); // explicit bool for clang
2648         if (!is_child || _dest.empty ()) {
2649                 return true;
2650         }
2651         return false;
2652 }
2653
2654 void
2655 Mixer_UI::plugin_drop (const Glib::RefPtr<Gdk::DragContext>&, const Gtk::SelectionData& data)
2656 {
2657         if (data.get_target() != "PluginPresetPtr") {
2658                 return;
2659         }
2660         if (data.get_length() != sizeof (PluginPresetPtr)) {
2661                 return;
2662         }
2663         const void *d = data.get_data();
2664         const PluginPresetPtr ppp = *(static_cast<const PluginPresetPtr*> (d));
2665
2666         PluginManager::PluginStatusType status = PluginManager::Favorite;
2667         PluginManager& manager (PluginManager::instance());
2668
2669         manager.set_status (ppp->_pip->type, ppp->_pip->unique_id, status);
2670         manager.save_statuses ();
2671 }
2672
2673 void
2674 Mixer_UI::do_vca_assign (boost::shared_ptr<VCA> vca)
2675 {
2676         /* call protected MixerActor:: method */
2677         vca_assign (vca);
2678 }
2679
2680 void
2681 Mixer_UI::do_vca_unassign (boost::shared_ptr<VCA> vca)
2682 {
2683         /* call protected MixerActor:: method */
2684         vca_unassign (vca);
2685 }
2686
2687 void
2688 Mixer_UI::show_vca_slaves (boost::shared_ptr<VCA> vca)
2689 {
2690         boost::shared_ptr<VCA> v = spilled_vca.lock();
2691         if (v != vca) {
2692                 spilled_vca = vca;
2693                 show_vca_change (vca); /* EMIT SIGNAL */
2694                 redisplay_track_list ();
2695         }
2696 }
2697
2698 bool
2699 Mixer_UI::showing_vca_slaves_for (boost::shared_ptr<VCA> vca) const
2700 {
2701        return vca == spilled_vca.lock();
2702 }