5273ba051393c9b7233e05bcf62b24e4d3dd6911
[ardour.git] / gtk2_ardour / editor_routes.cc
1 /*
2     Copyright (C) 2000-2009 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 #include <cstdlib>
21 #include <cassert>
22 #include <cmath>
23 #include <list>
24 #include <vector>
25 #include <algorithm>
26
27 #include "pbd/unknown_type.h"
28 #include "pbd/unwind.h"
29
30 #include "ardour/debug.h"
31 #include "ardour/midi_track.h"
32 #include "ardour/route.h"
33 #include "ardour/session.h"
34
35 #include "gtkmm2ext/cell_renderer_pixbuf_multi.h"
36 #include "gtkmm2ext/cell_renderer_pixbuf_toggle.h"
37 #include "gtkmm2ext/treeutils.h"
38
39 #include "actions.h"
40 #include "ardour_ui.h"
41 #include "audio_time_axis.h"
42 #include "editor.h"
43 #include "editor_group_tabs.h"
44 #include "editor_routes.h"
45 #include "gui_thread.h"
46 #include "keyboard.h"
47 #include "midi_time_axis.h"
48 #include "mixer_strip.h"
49 #include "plugin_setup_dialog.h"
50 #include "route_sorter.h"
51 #include "tooltips.h"
52 #include "utils.h"
53
54 #include "i18n.h"
55
56 using namespace std;
57 using namespace ARDOUR;
58 using namespace ARDOUR_UI_UTILS;
59 using namespace PBD;
60 using namespace Gtk;
61 using namespace Gtkmm2ext;
62 using namespace Glib;
63 using Gtkmm2ext::Keyboard;
64
65 struct ColumnInfo {
66         int         index;
67         const char* label;
68         const char* tooltip;
69 };
70
71 EditorRoutes::EditorRoutes (Editor* e)
72         : EditorComponent (e)
73         , _ignore_reorder (false)
74         , _no_redisplay (false)
75         , _adding_routes (false)
76         , _route_deletion_in_progress (false)
77         , _redisplay_on_resume (false)
78         , _redisplay_active (0)
79         , _queue_tv_update (0)
80         , _menu (0)
81         , old_focus (0)
82         , selection_countdown (0)
83         , name_editable (0)
84 {
85         static const int column_width = 22;
86
87         _scroller.add (_display);
88         _scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
89
90         _model = ListStore::create (_columns);
91         _display.set_model (_model);
92
93         // Record enable toggle
94         CellRendererPixbufMulti* rec_col_renderer = manage (new CellRendererPixbufMulti());
95
96         rec_col_renderer->set_pixbuf (0, ::get_icon("record-normal-disabled"));
97         rec_col_renderer->set_pixbuf (1, ::get_icon("record-normal-in-progress"));
98         rec_col_renderer->set_pixbuf (2, ::get_icon("record-normal-enabled"));
99         rec_col_renderer->set_pixbuf (3, ::get_icon("record-step"));
100         rec_col_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_tv_rec_enable_changed));
101
102         TreeViewColumn* rec_state_column = manage (new TreeViewColumn("R", *rec_col_renderer));
103
104         rec_state_column->add_attribute(rec_col_renderer->property_state(), _columns.rec_state);
105         rec_state_column->add_attribute(rec_col_renderer->property_visible(), _columns.is_track);
106
107         rec_state_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
108         rec_state_column->set_alignment(ALIGN_CENTER);
109         rec_state_column->set_expand(false);
110         rec_state_column->set_fixed_width(column_width);
111
112         // MIDI Input Active
113
114         CellRendererPixbufMulti* input_active_col_renderer = manage (new CellRendererPixbufMulti());
115         input_active_col_renderer->set_pixbuf (0, ::get_icon("midi-input-inactive"));
116         input_active_col_renderer->set_pixbuf (1, ::get_icon("midi-input-active"));
117         input_active_col_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_input_active_changed));
118
119         TreeViewColumn* input_active_column = manage (new TreeViewColumn ("I", *input_active_col_renderer));
120
121         input_active_column->add_attribute(input_active_col_renderer->property_state(), _columns.is_input_active);
122         input_active_column->add_attribute (input_active_col_renderer->property_visible(), _columns.is_midi);
123
124         input_active_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
125         input_active_column->set_alignment(ALIGN_CENTER);
126         input_active_column->set_expand(false);
127         input_active_column->set_fixed_width(column_width);
128
129         // Mute enable toggle
130         CellRendererPixbufMulti* mute_col_renderer = manage (new CellRendererPixbufMulti());
131
132         mute_col_renderer->set_pixbuf (Gtkmm2ext::Off, ::get_icon("mute-disabled"));
133         mute_col_renderer->set_pixbuf (Gtkmm2ext::ImplicitActive, ::get_icon("muted-by-others"));
134         mute_col_renderer->set_pixbuf (Gtkmm2ext::ExplicitActive, ::get_icon("mute-enabled"));
135         mute_col_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_tv_mute_enable_toggled));
136
137         TreeViewColumn* mute_state_column = manage (new TreeViewColumn("M", *mute_col_renderer));
138
139         mute_state_column->add_attribute(mute_col_renderer->property_state(), _columns.mute_state);
140         mute_state_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
141         mute_state_column->set_alignment(ALIGN_CENTER);
142         mute_state_column->set_expand(false);
143         mute_state_column->set_fixed_width(15);
144
145         // Solo enable toggle
146         CellRendererPixbufMulti* solo_col_renderer = manage (new CellRendererPixbufMulti());
147
148         solo_col_renderer->set_pixbuf (Gtkmm2ext::Off, ::get_icon("solo-disabled"));
149         solo_col_renderer->set_pixbuf (Gtkmm2ext::ExplicitActive, ::get_icon("solo-enabled"));
150         solo_col_renderer->set_pixbuf (Gtkmm2ext::ImplicitActive, ::get_icon("soloed-by-others"));
151         solo_col_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_tv_solo_enable_toggled));
152
153         TreeViewColumn* solo_state_column = manage (new TreeViewColumn("S", *solo_col_renderer));
154
155         solo_state_column->add_attribute(solo_col_renderer->property_state(), _columns.solo_state);
156         solo_state_column->add_attribute(solo_col_renderer->property_visible(), _columns.solo_visible);
157         solo_state_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
158         solo_state_column->set_alignment(ALIGN_CENTER);
159         solo_state_column->set_expand(false);
160         solo_state_column->set_fixed_width(column_width);
161
162         // Solo isolate toggle
163         CellRendererPixbufMulti* solo_iso_renderer = manage (new CellRendererPixbufMulti());
164
165         solo_iso_renderer->set_pixbuf (0, ::get_icon("solo-isolate-disabled"));
166         solo_iso_renderer->set_pixbuf (1, ::get_icon("solo-isolate-enabled"));
167         solo_iso_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_tv_solo_isolate_toggled));
168
169         TreeViewColumn* solo_isolate_state_column = manage (new TreeViewColumn("SI", *solo_iso_renderer));
170
171         solo_isolate_state_column->add_attribute(solo_iso_renderer->property_state(), _columns.solo_isolate_state);
172         solo_isolate_state_column->add_attribute(solo_iso_renderer->property_visible(), _columns.solo_visible);
173         solo_isolate_state_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
174         solo_isolate_state_column->set_alignment(ALIGN_CENTER);
175         solo_isolate_state_column->set_expand(false);
176         solo_isolate_state_column->set_fixed_width(column_width);
177
178         // Solo safe toggle
179         CellRendererPixbufMulti* solo_safe_renderer = manage (new CellRendererPixbufMulti ());
180
181         solo_safe_renderer->set_pixbuf (0, ::get_icon("solo-safe-disabled"));
182         solo_safe_renderer->set_pixbuf (1, ::get_icon("solo-safe-enabled"));
183         solo_safe_renderer->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::on_tv_solo_safe_toggled));
184
185         TreeViewColumn* solo_safe_state_column = manage (new TreeViewColumn(_("SS"), *solo_safe_renderer));
186         solo_safe_state_column->add_attribute(solo_safe_renderer->property_state(), _columns.solo_safe_state);
187         solo_safe_state_column->add_attribute(solo_safe_renderer->property_visible(), _columns.solo_visible);
188         solo_safe_state_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
189         solo_safe_state_column->set_alignment(ALIGN_CENTER);
190         solo_safe_state_column->set_expand(false);
191         solo_safe_state_column->set_fixed_width(column_width);
192
193         _name_column = _display.append_column ("", _columns.text) - 1;
194         _visible_column = _display.append_column ("", _columns.visible) - 1;
195         _active_column = _display.append_column ("", _columns.active) - 1;
196
197         _display.append_column (*input_active_column);
198         _display.append_column (*rec_state_column);
199         _display.append_column (*mute_state_column);
200         _display.append_column (*solo_state_column);
201         _display.append_column (*solo_isolate_state_column);
202         _display.append_column (*solo_safe_state_column);
203
204
205         TreeViewColumn* col;
206         Gtk::Label* l;
207
208         ColumnInfo ci[] = {
209                 { 0,  _("Name"),        _("Track/Bus Name") },
210                 { 1, S_("Visible|V"),   _("Track/Bus visible ?") },
211                 { 2, S_("Active|A"),    _("Track/Bus active ?") },
212                 { 3, S_("MidiInput|I"), _("MIDI input enabled") },
213                 { 4, S_("Rec|R"),       _("Record enabled") },
214                 { 5, S_("Mute|M"),      _("Muted") },
215                 { 6, S_("Solo|S"),      _("Soloed") },
216                 { 7, S_("SoloIso|SI"),  _("Solo Isolated") },
217                 { 8, S_("SoloLock|SS"), _("Solo Safe (Locked)") },
218                 { -1, 0, 0 }
219         };
220
221         for (int i = 0; ci[i].index >= 0; ++i) {
222                 col = _display.get_column (ci[i].index);
223                 l = manage (new Label (ci[i].label));
224                 set_tooltip (*l, ci[i].tooltip);
225                 col->set_widget (*l);
226                 l->show ();
227         }
228
229         _display.set_headers_visible (true);
230         _display.get_selection()->set_mode (SELECTION_SINGLE);
231         _display.get_selection()->set_select_function (sigc::mem_fun (*this, &EditorRoutes::selection_filter));
232         _display.get_selection()->signal_changed().connect (sigc::mem_fun (*this, &EditorRoutes::selection_changed));
233         _display.set_reorderable (true);
234         _display.set_name (X_("EditGroupList"));
235         _display.set_rules_hint (true);
236         _display.set_size_request (100, -1);
237         _display.add_object_drag (_columns.route.index(), "routes");
238
239         CellRendererText* name_cell = dynamic_cast<CellRendererText*> (_display.get_column_cell_renderer (_name_column));
240
241         assert (name_cell);
242         name_cell->signal_editing_started().connect (sigc::mem_fun (*this, &EditorRoutes::name_edit_started));
243
244         TreeViewColumn* name_column = _display.get_column (_name_column);
245
246         assert (name_column);
247
248         name_column->add_attribute (name_cell->property_editable(), _columns.name_editable);
249         name_column->set_sizing(TREE_VIEW_COLUMN_FIXED);
250         name_column->set_expand(true);
251         name_column->set_min_width(50);
252
253         name_cell->property_editable() = true;
254         name_cell->signal_edited().connect (sigc::mem_fun (*this, &EditorRoutes::name_edit));
255
256         // Set the visible column cell renderer to radio toggle
257         CellRendererToggle* visible_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (_visible_column));
258
259         visible_cell->property_activatable() = true;
260         visible_cell->property_radio() = false;
261         visible_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRoutes::visible_changed));
262
263         TreeViewColumn* visible_col = dynamic_cast<TreeViewColumn*> (_display.get_column (_visible_column));
264         visible_col->set_expand(false);
265         visible_col->set_sizing(TREE_VIEW_COLUMN_FIXED);
266         visible_col->set_fixed_width(30);
267         visible_col->set_alignment(ALIGN_CENTER);
268
269         CellRendererToggle* active_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (_active_column));
270
271         active_cell->property_activatable() = true;
272         active_cell->property_radio() = false;
273         active_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRoutes::active_changed));
274
275         TreeViewColumn* active_col = dynamic_cast<TreeViewColumn*> (_display.get_column (_active_column));
276         active_col->set_expand (false);
277         active_col->set_sizing (TREE_VIEW_COLUMN_FIXED);
278         active_col->set_fixed_width (30);
279         active_col->set_alignment (ALIGN_CENTER);
280
281         _model->signal_row_deleted().connect (sigc::mem_fun (*this, &EditorRoutes::row_deleted));
282         _model->signal_rows_reordered().connect (sigc::mem_fun (*this, &EditorRoutes::reordered));
283
284         _display.signal_button_press_event().connect (sigc::mem_fun (*this, &EditorRoutes::button_press), false);
285         _scroller.signal_key_press_event().connect (sigc::mem_fun(*this, &EditorRoutes::key_press), false);
286
287         _scroller.signal_focus_in_event().connect (sigc::mem_fun (*this, &EditorRoutes::focus_in), false);
288         _scroller.signal_focus_out_event().connect (sigc::mem_fun (*this, &EditorRoutes::focus_out));
289
290         _display.signal_enter_notify_event().connect (sigc::mem_fun (*this, &EditorRoutes::enter_notify), false);
291         _display.signal_leave_notify_event().connect (sigc::mem_fun (*this, &EditorRoutes::leave_notify), false);
292
293         _display.set_enable_search (false);
294
295         Route::SyncOrderKeys.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::sync_treeview_from_order_keys, this), gui_context());
296         Route::PluginSetup.connect_same_thread (*this, boost::bind (&EditorRoutes::plugin_setup, this, _1, _2, _3));
297
298 }
299
300 bool
301 EditorRoutes::focus_in (GdkEventFocus*)
302 {
303         Window* win = dynamic_cast<Window*> (_scroller.get_toplevel ());
304
305         if (win) {
306                 old_focus = win->get_focus ();
307         } else {
308                 old_focus = 0;
309         }
310
311         name_editable = 0;
312
313         /* try to do nothing on focus in (doesn't work, hence selection_count nonsense) */
314         return true;
315 }
316
317 bool
318 EditorRoutes::focus_out (GdkEventFocus*)
319 {
320         if (old_focus) {
321                 old_focus->grab_focus ();
322                 old_focus = 0;
323         }
324
325         return false;
326 }
327
328 bool
329 EditorRoutes::enter_notify (GdkEventCrossing*)
330 {
331         if (name_editable) {
332                 return true;
333         }
334
335         /* arm counter so that ::selection_filter() will deny selecting anything for the
336          * next two attempts to change selection status.
337          */
338         selection_countdown = 2;
339         _scroller.grab_focus ();
340         Keyboard::magic_widget_grab_focus ();
341         return false;
342 }
343
344 bool
345 EditorRoutes::leave_notify (GdkEventCrossing*)
346 {
347         selection_countdown = 0;
348
349         if (old_focus) {
350                 old_focus->grab_focus ();
351                 old_focus = 0;
352         }
353
354         Keyboard::magic_widget_drop_focus ();
355         return false;
356 }
357
358 void
359 EditorRoutes::set_session (Session* s)
360 {
361         SessionHandlePtr::set_session (s);
362
363         initial_display ();
364
365         if (_session) {
366                 _session->SoloChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::solo_changed_so_update_mute, this), gui_context());
367                 _session->RecordStateChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_rec_display, this), gui_context());
368
369                 /* TODO: check if these needs to be tied in with DisplaySuspender
370                  * Given that the UI is single-threaded and DisplaySuspender is only used
371                  * in loops in the UI thread all should be fine.
372                  */
373                 _session->BatchUpdateStart.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::suspend_redisplay, this), gui_context());
374                 _session->BatchUpdateEnd.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::resume_redisplay, this), gui_context());
375         }
376 }
377
378 void
379 EditorRoutes::on_input_active_changed (std::string const & path_string)
380 {
381         // Get the model row that has been toggled.
382         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
383
384         TimeAxisView* tv = row[_columns.tv];
385         RouteTimeAxisView *rtv = dynamic_cast<RouteTimeAxisView*> (tv);
386
387         if (rtv) {
388                 boost::shared_ptr<MidiTrack> mt;
389                 mt = rtv->midi_track();
390                 if (mt) {
391                         mt->set_input_active (!mt->input_active());
392                 }
393         }
394 }
395
396 void
397 EditorRoutes::on_tv_rec_enable_changed (std::string const & path_string)
398 {
399         DisplaySuspender ds;
400         // Get the model row that has been toggled.
401         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
402
403         TimeAxisView* tv = row[_columns.tv];
404         RouteTimeAxisView *rtv = dynamic_cast<RouteTimeAxisView*> (tv);
405
406         if (rtv && rtv->track()) {
407                 boost::shared_ptr<RouteList> rl (new RouteList);
408                 rl->push_back (rtv->route());
409                 _session->set_record_enabled (rl, !rtv->track()->record_enabled(), Session::rt_cleanup);
410         }
411 }
412
413 void
414 EditorRoutes::on_tv_mute_enable_toggled (std::string const & path_string)
415 {
416         // Get the model row that has been toggled.
417         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
418
419         TimeAxisView *tv = row[_columns.tv];
420         RouteTimeAxisView *rtv = dynamic_cast<RouteTimeAxisView*> (tv);
421
422         if (rtv != 0) {
423                 boost::shared_ptr<RouteList> rl (new RouteList);
424                 rl->push_back (rtv->route());
425                 _session->set_mute (rl, !rtv->route()->muted(), Session::rt_cleanup);
426         }
427 }
428
429 void
430 EditorRoutes::on_tv_solo_enable_toggled (std::string const & path_string)
431 {
432         // Get the model row that has been toggled.
433         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
434
435         TimeAxisView *tv = row[_columns.tv];
436         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
437
438         if (rtv != 0) {
439                 boost::shared_ptr<RouteList> rl (new RouteList);
440                 rl->push_back (rtv->route());
441                 if (Config->get_solo_control_is_listen_control()) {
442                         _session->set_listen (rl, !rtv->route()->listening_via_monitor(), Session::rt_cleanup);
443                 } else {
444                         _session->set_solo (rl, !rtv->route()->self_soloed(), Session::rt_cleanup);
445                 }
446         }
447 }
448
449 void
450 EditorRoutes::on_tv_solo_isolate_toggled (std::string const & path_string)
451 {
452         // Get the model row that has been toggled.
453         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
454
455         TimeAxisView *tv = row[_columns.tv];
456         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
457
458         if (rtv) {
459                 rtv->route()->set_solo_isolated (!rtv->route()->solo_isolated(), Controllable::UseGroup);
460         }
461 }
462
463 void
464 EditorRoutes::on_tv_solo_safe_toggled (std::string const & path_string)
465 {
466         // Get the model row that has been toggled.
467         Gtk::TreeModel::Row row = *_model->get_iter (Gtk::TreeModel::Path (path_string));
468
469         TimeAxisView *tv = row[_columns.tv];
470         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
471
472         if (rtv) {
473                 rtv->route()->set_solo_safe (!rtv->route()->solo_safe(), Controllable::UseGroup);
474         }
475 }
476
477 void
478 EditorRoutes::build_menu ()
479 {
480         using namespace Menu_Helpers;
481         using namespace Gtk;
482
483         _menu = new Menu;
484
485         MenuList& items = _menu->items();
486         _menu->set_name ("ArdourContextMenu");
487
488         items.push_back (MenuElem (_("Show All"), sigc::mem_fun (*this, &EditorRoutes::show_all_routes)));
489         items.push_back (MenuElem (_("Hide All"), sigc::mem_fun (*this, &EditorRoutes::hide_all_routes)));
490         items.push_back (MenuElem (_("Show All Audio Tracks"), sigc::mem_fun (*this, &EditorRoutes::show_all_audiotracks)));
491         items.push_back (MenuElem (_("Hide All Audio Tracks"), sigc::mem_fun (*this, &EditorRoutes::hide_all_audiotracks)));
492         items.push_back (MenuElem (_("Show All Audio Busses"), sigc::mem_fun (*this, &EditorRoutes::show_all_audiobus)));
493         items.push_back (MenuElem (_("Hide All Audio Busses"), sigc::mem_fun (*this, &EditorRoutes::hide_all_audiobus)));
494         items.push_back (MenuElem (_("Show All Midi Tracks"), sigc::mem_fun (*this, &EditorRoutes::show_all_miditracks)));
495         items.push_back (MenuElem (_("Hide All Midi Tracks"), sigc::mem_fun (*this, &EditorRoutes::hide_all_miditracks)));
496         items.push_back (MenuElem (_("Only Show Tracks with Regions Under Playhead"), sigc::mem_fun (*this, &EditorRoutes::show_tracks_with_regions_at_playhead)));
497 }
498
499 void
500 EditorRoutes::show_menu ()
501 {
502         if (_menu == 0) {
503                 build_menu ();
504         }
505
506         _menu->popup (1, gtk_get_current_event_time());
507 }
508
509 void
510 EditorRoutes::redisplay_real ()
511 {
512         TreeModel::Children rows = _model->children();
513         TreeModel::Children::iterator i;
514         uint32_t position;
515
516         /* n will be the count of tracks plus children (updated by TimeAxisView::show_at),
517          * so we will use that to know where to put things.
518          */
519         int n;
520
521         for (n = 0, position = 0, i = rows.begin(); i != rows.end(); ++i) {
522                 TimeAxisView *tv = (*i)[_columns.tv];
523                 boost::shared_ptr<Route> route = (*i)[_columns.route];
524
525                 if (tv == 0) {
526                         // just a "title" row
527                         continue;
528                 }
529
530                 bool visible = tv->marked_for_display ();
531
532                 /* show or hide the TimeAxisView */
533                 if (visible) {
534                         position += tv->show_at (position, n, &_editor->edit_controls_vbox);
535                 } else {
536                         tv->hide ();
537                 }
538
539                 n++;
540         }
541
542         /* whenever we go idle, update the track view list to reflect the new order.
543          * we can't do this here, because we could mess up something that is traversing
544          * the track order and has caused a redisplay of the list.
545          */
546         Glib::signal_idle().connect (sigc::mem_fun (*_editor, &Editor::sync_track_view_list_and_routes));
547
548         _editor->reset_controls_layout_height (position);
549         _editor->reset_controls_layout_width ();
550         _editor->_full_canvas_height = position;
551
552         if ((_editor->vertical_adjustment.get_value() + _editor->_visible_canvas_height) > _editor->vertical_adjustment.get_upper()) {
553                 /*
554                  * We're increasing the size of the canvas while the bottom is visible.
555                  * We scroll down to keep in step with the controls layout.
556                  */
557                 _editor->vertical_adjustment.set_value (_editor->_full_canvas_height - _editor->_visible_canvas_height);
558         }
559 }
560
561 void
562 EditorRoutes::redisplay ()
563 {
564         if (!_session || _session->deletion_in_progress()) {
565                 return;
566         }
567
568         if (_no_redisplay) {
569                 _redisplay_on_resume = true;
570                 return;
571         }
572
573         // model deprecated g_atomic_int_exchange_and_add(, 1)
574         g_atomic_int_inc(const_cast<gint*>(&_redisplay_active));
575         if (!g_atomic_int_compare_and_exchange (const_cast<gint*>(&_redisplay_active), 1, 1)) {
576                 /* recursive re-display can happen if redisplay shows/hides a TrackView
577                  * which has children and their display status changes as result.
578                  */
579                 return;
580         }
581
582         redisplay_real ();
583
584         while (!g_atomic_int_compare_and_exchange (const_cast<gint*>(&_redisplay_active), 1, 0)) {
585                 g_atomic_int_set(const_cast<gint*>(&_redisplay_active), 1);
586                 redisplay_real ();
587         }
588 }
589
590 void
591 EditorRoutes::row_deleted (Gtk::TreeModel::Path const &)
592 {
593         if (!_session || _session->deletion_in_progress()) {
594                 return;
595         }
596         /* this happens as the second step of a DnD within the treeview, and
597          * when a route is actually removed. we don't differentiate between
598          * the two cases.
599          *
600          * note that the sync_orders_keys() step may not actually change any
601          * RID's (e.g. the last track may be removed, so all other tracks keep
602          * the same RID), which means that no redisplay would happen. so we
603          * have to force a redisplay.
604          */
605
606         DEBUG_TRACE (DEBUG::OrderKeys, "editor routes treeview row deleted\n");
607
608         DisplaySuspender ds;
609         sync_order_keys_from_treeview ();
610 }
611
612 void
613 EditorRoutes::reordered (TreeModel::Path const &, TreeModel::iterator const &, int* /*what*/)
614 {
615         /* reordering implies that RID's will change, so sync_order_keys() will
616            cause a redisplay.
617         */
618
619         DEBUG_TRACE (DEBUG::OrderKeys, "editor routes treeview reordered\n");
620         sync_order_keys_from_treeview ();
621 }
622
623 void
624 EditorRoutes::visible_changed (std::string const & path)
625 {
626         if (_session && _session->deletion_in_progress()) {
627                 return;
628         }
629
630         DisplaySuspender ds;
631         TreeIter iter;
632
633         if ((iter = _model->get_iter (path))) {
634                 TimeAxisView* tv = (*iter)[_columns.tv];
635                 if (tv) {
636                         bool visible = (*iter)[_columns.visible];
637
638                         if (tv->set_marked_for_display (!visible)) {
639                                 update_visibility ();
640                         }
641                 }
642         }
643 }
644
645 void
646 EditorRoutes::active_changed (std::string const & path)
647 {
648         if (_session && _session->deletion_in_progress ()) {
649                 return;
650         }
651
652         Gtk::TreeModel::Row row = *_model->get_iter (path);
653         boost::shared_ptr<Route> route = row[_columns.route];
654         bool const active = row[_columns.active];
655         route->set_active (!active, this);
656 }
657
658 void
659 EditorRoutes::routes_added (list<RouteTimeAxisView*> routes)
660 {
661         PBD::Unwinder<bool> at (_adding_routes, true);
662         bool from_scratch = (_model->children().size() == 0);
663         Gtk::TreeModel::Children::iterator insert_iter = _model->children().end();
664
665         for (Gtk::TreeModel::Children::iterator it = _model->children().begin(); it != _model->children().end(); ++it) {
666                 boost::shared_ptr<Route> r = (*it)[_columns.route];
667
668                 if (r->order_key() == (routes.front()->route()->order_key() + routes.size())) {
669                         insert_iter = it;
670                         break;
671                 }
672         }
673
674         DisplaySuspender ds;
675
676         _display.set_model (Glib::RefPtr<ListStore>());
677
678         for (list<RouteTimeAxisView*>::iterator x = routes.begin(); x != routes.end(); ++x) {
679
680                 boost::shared_ptr<MidiTrack> midi_trk = boost::dynamic_pointer_cast<MidiTrack> ((*x)->route());
681
682                 TreeModel::Row row = *(_model->insert (insert_iter));
683
684                 row[_columns.text] = (*x)->route()->name();
685                 row[_columns.visible] = (*x)->marked_for_display();
686                 row[_columns.active] = (*x)->route()->active ();
687                 row[_columns.tv] = *x;
688                 row[_columns.route] = (*x)->route ();
689                 row[_columns.is_track] = (boost::dynamic_pointer_cast<Track> ((*x)->route()) != 0);
690
691                 if (midi_trk) {
692                         row[_columns.is_input_active] = midi_trk->input_active ();
693                         row[_columns.is_midi] = true;
694                 } else {
695                         row[_columns.is_input_active] = false;
696                         row[_columns.is_midi] = false;
697                 }
698
699                 row[_columns.mute_state] = (*x)->route()->muted() ? Gtkmm2ext::ExplicitActive : Gtkmm2ext::Off;
700                 row[_columns.solo_state] = RouteUI::solo_active_state ((*x)->route());
701                 row[_columns.solo_visible] = !(*x)->route()->is_master ();
702                 row[_columns.solo_isolate_state] = (*x)->route()->solo_isolated();
703                 row[_columns.solo_safe_state] = (*x)->route()->solo_safe();
704                 row[_columns.name_editable] = true;
705
706                 boost::weak_ptr<Route> wr ((*x)->route());
707
708                 (*x)->route()->gui_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::handle_gui_changes, this, _1, _2), gui_context());
709                 (*x)->route()->PropertyChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::route_property_changed, this, _1, wr), gui_context());
710
711                 if ((*x)->is_track()) {
712                         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> ((*x)->route());
713                         t->RecordEnableChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_rec_display, this), gui_context());
714                         t->RecordSafeChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_rec_display, this), gui_context());
715                 }
716
717                 if ((*x)->is_midi_track()) {
718                         boost::shared_ptr<MidiTrack> t = boost::dynamic_pointer_cast<MidiTrack> ((*x)->route());
719                         t->StepEditStatusChange.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_rec_display, this), gui_context());
720                         t->InputActiveChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_input_active_display, this), gui_context());
721                 }
722
723                 (*x)->route()->mute_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_mute_display, this), gui_context());
724                 (*x)->route()->solo_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_display, this), gui_context());
725                 (*x)->route()->listen_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_display, this), gui_context());
726                 (*x)->route()->solo_isolated_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_isolate_display, this), gui_context());
727                 (*x)->route()->solo_safe_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_safe_display, this), gui_context());
728                 (*x)->route()->active_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_active_display, this), gui_context ());
729
730         }
731
732         update_rec_display ();
733         update_mute_display ();
734         update_solo_display ();
735         update_solo_isolate_display ();
736         update_solo_safe_display ();
737         update_input_active_display ();
738         update_active_display ();
739
740         _display.set_model (_model);
741
742         /* now update route order keys from the treeview/track display order */
743         if (!from_scratch) {
744                 sync_order_keys_from_treeview ();
745         }
746 }
747
748 void
749 EditorRoutes::handle_gui_changes (string const & what, void*)
750 {
751         if (_adding_routes) {
752                 return;
753         }
754
755         if (what == "track_height") {
756                 /* Optional :make tracks change height while it happens, instead
757                    of on first-idle
758                 */
759                 redisplay ();
760         }
761
762         if (what == "visible_tracks") {
763                 redisplay ();
764         }
765 }
766
767 void
768 EditorRoutes::route_removed (TimeAxisView *tv)
769 {
770         ENSURE_GUI_THREAD (*this, &EditorRoutes::route_removed, tv)
771
772         TreeModel::Children rows = _model->children();
773         TreeModel::Children::iterator ri;
774
775         for (ri = rows.begin(); ri != rows.end(); ++ri) {
776                 if ((*ri)[_columns.tv] == tv) {
777                         PBD::Unwinder<bool> uw (_route_deletion_in_progress, true);
778                         _model->erase (ri);
779                         break;
780                 }
781         }
782
783         /* the deleted signal for the treeview/model will take
784            care of any updates.
785         */
786 }
787
788 void
789 EditorRoutes::route_property_changed (const PropertyChange& what_changed, boost::weak_ptr<Route> r)
790 {
791         if (!what_changed.contains (ARDOUR::Properties::name)) {
792                 return;
793         }
794
795         ENSURE_GUI_THREAD (*this, &EditorRoutes::route_name_changed, r)
796
797         boost::shared_ptr<Route> route = r.lock ();
798
799         if (!route) {
800                 return;
801         }
802
803         TreeModel::Children rows = _model->children();
804         TreeModel::Children::iterator i;
805
806         for (i = rows.begin(); i != rows.end(); ++i) {
807                 boost::shared_ptr<Route> t = (*i)[_columns.route];
808                 if (t == route) {
809                         (*i)[_columns.text] = route->name();
810                         break;
811                 }
812         }
813 }
814
815 void
816 EditorRoutes::update_active_display ()
817 {
818         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
819                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
820         }
821 }
822
823 void
824 EditorRoutes::update_visibility ()
825 {
826         TreeModel::Children rows = _model->children();
827         TreeModel::Children::iterator i;
828
829         DisplaySuspender ds;
830
831         for (i = rows.begin(); i != rows.end(); ++i) {
832                 TimeAxisView *tv = (*i)[_columns.tv];
833                 (*i)[_columns.visible] = tv->marked_for_display ();
834         }
835
836         /* force route order keys catch up with visibility changes
837          */
838
839         sync_order_keys_from_treeview ();
840 }
841
842 void
843 EditorRoutes::hide_track_in_display (TimeAxisView& tv)
844 {
845         TreeModel::Children rows = _model->children();
846         TreeModel::Children::iterator i;
847
848         for (i = rows.begin(); i != rows.end(); ++i) {
849                 if ((*i)[_columns.tv] == &tv) {
850                         tv.set_marked_for_display (false);
851                         (*i)[_columns.visible] = false;
852                         redisplay ();
853                         break;
854                 }
855         }
856 }
857
858 void
859 EditorRoutes::show_track_in_display (TimeAxisView& tv)
860 {
861         TreeModel::Children rows = _model->children();
862         TreeModel::Children::iterator i;
863
864
865         for (i = rows.begin(); i != rows.end(); ++i) {
866                 if ((*i)[_columns.tv] == &tv) {
867                         tv.set_marked_for_display (true);
868                         (*i)[_columns.visible] = true;
869                         redisplay ();
870                         break;
871                 }
872         }
873 }
874
875 void
876 EditorRoutes::reset_remote_control_ids ()
877 {
878         if (Config->get_remote_model() == UserOrdered || !_session || _session->deletion_in_progress()) {
879                 return;
880         }
881
882         TreeModel::Children rows = _model->children();
883
884         if (rows.empty()) {
885                 return;
886         }
887
888
889         DEBUG_TRACE (DEBUG::OrderKeys, "editor reset remote control ids\n");
890
891         TreeModel::Children::iterator ri;
892         bool rid_change = false;
893         uint32_t rid = 1;
894         uint32_t invisible_key = UINT32_MAX;
895
896         for (ri = rows.begin(); ri != rows.end(); ++ri) {
897
898                 /* skip two special values */
899
900                 if (rid == Route::MasterBusRemoteControlID) {
901                         rid++;
902                 }
903
904                 if (rid == Route::MonitorBusRemoteControlID) {
905                         rid++;
906                 }
907
908                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
909                 bool visible = (*ri)[_columns.visible];
910
911                 if (!route->is_master() && !route->is_monitor()) {
912
913                         uint32_t new_rid = (visible ? rid : invisible_key--);
914
915                         if (new_rid != route->remote_control_id()) {
916                                 route->set_remote_control_id_explicit (new_rid);
917                                 rid_change = true;
918                         }
919
920                         if (visible) {
921                                 rid++;
922                         }
923
924                 }
925         }
926
927         if (rid_change) {
928                 /* tell the world that we changed the remote control IDs */
929                 _session->notify_remote_id_change ();
930         }
931 }
932
933
934 void
935 EditorRoutes::sync_order_keys_from_treeview ()
936 {
937         if (_ignore_reorder || !_session || _session->deletion_in_progress()) {
938                 return;
939         }
940
941         TreeModel::Children rows = _model->children();
942
943         if (rows.empty()) {
944                 return;
945         }
946
947
948         DEBUG_TRACE (DEBUG::OrderKeys, "editor sync order keys from treeview\n");
949
950         TreeModel::Children::iterator ri;
951         bool changed = false;
952         bool rid_change = false;
953         uint32_t order = 0;
954         uint32_t rid = 1;
955         uint32_t invisible_key = UINT32_MAX;
956
957         for (ri = rows.begin(); ri != rows.end(); ++ri) {
958
959                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
960                 bool visible = (*ri)[_columns.visible];
961
962                 uint32_t old_key = route->order_key ();
963
964                 if (order != old_key) {
965                         route->set_order_key (order);
966
967                         changed = true;
968                 }
969
970                 if ((Config->get_remote_model() == MixerOrdered) && !route->is_master() && !route->is_monitor()) {
971
972                         uint32_t new_rid = (visible ? rid : invisible_key--);
973
974                         if (new_rid != route->remote_control_id()) {
975                                 route->set_remote_control_id_explicit (new_rid);
976                                 rid_change = true;
977                         }
978
979                         if (visible) {
980                                 rid++;
981                         }
982
983                 }
984
985                 ++order;
986         }
987
988         if (changed) {
989                 /* tell the world that we changed the editor sort keys */
990                 _session->sync_order_keys ();
991         }
992
993         if (rid_change) {
994                 /* tell the world that we changed the remote control IDs */
995                 _session->notify_remote_id_change ();
996         }
997 }
998
999 void
1000 EditorRoutes::sync_treeview_from_order_keys ()
1001 {
1002         /* Some route order key(s) have been changed, make sure that
1003            we update out tree/list model and GUI to reflect the change.
1004         */
1005
1006         if (_ignore_reorder || !_session || _session->deletion_in_progress()) {
1007                 return;
1008         }
1009
1010         DEBUG_TRACE (DEBUG::OrderKeys, "editor sync model from order keys.\n");
1011
1012         /* we could get here after either a change in the Mixer or Editor sort
1013          * order, but either way, the mixer order keys reflect the intended
1014          * order for the GUI, so reorder the treeview model to match it.
1015          */
1016
1017         vector<int> neworder;
1018         TreeModel::Children rows = _model->children();
1019         uint32_t old_order = 0;
1020         bool changed = false;
1021
1022         if (rows.empty()) {
1023                 return;
1024         }
1025
1026         OrderKeySortedRoutes sorted_routes;
1027
1028         for (TreeModel::Children::iterator ri = rows.begin(); ri != rows.end(); ++ri, ++old_order) {
1029                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
1030                 sorted_routes.push_back (RoutePlusOrderKey (route, old_order, route->order_key ()));
1031         }
1032
1033         SortByNewDisplayOrder cmp;
1034
1035         sort (sorted_routes.begin(), sorted_routes.end(), cmp);
1036         neworder.assign (sorted_routes.size(), 0);
1037
1038         uint32_t n = 0;
1039
1040         for (OrderKeySortedRoutes::iterator sr = sorted_routes.begin(); sr != sorted_routes.end(); ++sr, ++n) {
1041
1042                 neworder[n] = sr->old_display_order;
1043
1044                 if (sr->old_display_order != n) {
1045                         changed = true;
1046                 }
1047
1048                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("EDITOR change order for %1 from %2 to %3\n",
1049                                                                sr->route->name(), sr->old_display_order, n));
1050         }
1051
1052         if (changed) {
1053                 Unwinder<bool> uw (_ignore_reorder, true);
1054                 _model->reorder (neworder);
1055         }
1056
1057         redisplay ();
1058 }
1059
1060 void
1061 EditorRoutes::hide_all_tracks (bool /*with_select*/)
1062 {
1063         TreeModel::Children rows = _model->children();
1064         TreeModel::Children::iterator i;
1065
1066         DisplaySuspender ds;
1067
1068         for (i = rows.begin(); i != rows.end(); ++i) {
1069
1070                 TreeModel::Row row = (*i);
1071                 TimeAxisView *tv = row[_columns.tv];
1072
1073                 if (tv == 0) {
1074                         continue;
1075                 }
1076
1077                 row[_columns.visible] = false;
1078         }
1079 }
1080
1081 void
1082 EditorRoutes::set_all_tracks_visibility (bool yn)
1083 {
1084         TreeModel::Children rows = _model->children();
1085         TreeModel::Children::iterator i;
1086
1087         DisplaySuspender ds;
1088
1089         for (i = rows.begin(); i != rows.end(); ++i) {
1090
1091                 TreeModel::Row row = (*i);
1092                 TimeAxisView* tv = row[_columns.tv];
1093
1094                 if (tv == 0) {
1095                         continue;
1096                 }
1097
1098                 tv->set_marked_for_display (yn);
1099                 (*i)[_columns.visible] = yn;
1100         }
1101
1102         /* force route order keys catch up with visibility changes
1103          */
1104
1105         sync_order_keys_from_treeview ();
1106 }
1107
1108 void
1109 EditorRoutes::set_all_audio_midi_visibility (int tracks, bool yn)
1110 {
1111         TreeModel::Children rows = _model->children();
1112         TreeModel::Children::iterator i;
1113
1114         DisplaySuspender ds;
1115
1116         for (i = rows.begin(); i != rows.end(); ++i) {
1117
1118                 TreeModel::Row row = (*i);
1119                 TimeAxisView* tv = row[_columns.tv];
1120
1121                 AudioTimeAxisView* atv;
1122                 MidiTimeAxisView* mtv;
1123
1124                 if (tv == 0) {
1125                         continue;
1126                 }
1127
1128                 if ((atv = dynamic_cast<AudioTimeAxisView*>(tv)) != 0) {
1129                         switch (tracks) {
1130                         case 0:
1131                                 atv->set_marked_for_display (yn);
1132                                 (*i)[_columns.visible] = yn;
1133                                 break;
1134
1135                         case 1:
1136                                 if (atv->is_audio_track()) {
1137                                         atv->set_marked_for_display (yn);
1138                                         (*i)[_columns.visible] = yn;
1139                                 }
1140                                 break;
1141
1142                         case 2:
1143                                 if (!atv->is_audio_track()) {
1144                                         atv->set_marked_for_display (yn);
1145                                         (*i)[_columns.visible] = yn;
1146                                 }
1147                                 break;
1148                         }
1149                 }
1150                 else if ((mtv = dynamic_cast<MidiTimeAxisView*>(tv)) != 0) {
1151                         switch (tracks) {
1152                         case 0:
1153                                 mtv->set_marked_for_display (yn);
1154                                 (*i)[_columns.visible] = yn;
1155                                 break;
1156
1157                         case 3:
1158                                 if (mtv->is_midi_track()) {
1159                                         mtv->set_marked_for_display (yn);
1160                                         (*i)[_columns.visible] = yn;
1161                                 }
1162                                 break;
1163                         }
1164                 }
1165         }
1166
1167         /* force route order keys catch up with visibility changes
1168          */
1169
1170         sync_order_keys_from_treeview ();
1171 }
1172
1173 void
1174 EditorRoutes::hide_all_routes ()
1175 {
1176         set_all_tracks_visibility (false);
1177 }
1178
1179 void
1180 EditorRoutes::show_all_routes ()
1181 {
1182         set_all_tracks_visibility (true);
1183 }
1184
1185 void
1186 EditorRoutes::show_all_audiotracks()
1187 {
1188         set_all_audio_midi_visibility (1, true);
1189 }
1190 void
1191 EditorRoutes::hide_all_audiotracks ()
1192 {
1193         set_all_audio_midi_visibility (1, false);
1194 }
1195
1196 void
1197 EditorRoutes::show_all_audiobus ()
1198 {
1199         set_all_audio_midi_visibility (2, true);
1200 }
1201 void
1202 EditorRoutes::hide_all_audiobus ()
1203 {
1204         set_all_audio_midi_visibility (2, false);
1205 }
1206
1207 void
1208 EditorRoutes::show_all_miditracks()
1209 {
1210         set_all_audio_midi_visibility (3, true);
1211 }
1212 void
1213 EditorRoutes::hide_all_miditracks ()
1214 {
1215         set_all_audio_midi_visibility (3, false);
1216 }
1217
1218 bool
1219 EditorRoutes::key_press (GdkEventKey* ev)
1220 {
1221         TreeViewColumn *col;
1222         boost::shared_ptr<RouteList> rl (new RouteList);
1223         TreePath path;
1224
1225         switch (ev->keyval) {
1226                 case GDK_Tab:
1227                 case GDK_ISO_Left_Tab:
1228
1229                         /* If we appear to be editing something, leave that cleanly and appropriately. */
1230                         if (name_editable) {
1231                                 name_editable->editing_done ();
1232                                 name_editable = 0;
1233                         }
1234
1235                         col = _display.get_column (_name_column); // select&focus on name column
1236
1237                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
1238                                 treeview_select_previous (_display, _model, col);
1239                         } else {
1240                                 treeview_select_next (_display, _model, col);
1241                         }
1242
1243                         return true;
1244                         break;
1245
1246                 case 'm':
1247                         if (get_relevant_routes (rl)) {
1248                                 _session->set_mute (rl, !rl->front()->muted(), Session::rt_cleanup);
1249                         }
1250                         return true;
1251                         break;
1252
1253                 case 's':
1254                         if (get_relevant_routes (rl)) {
1255                                 if (Config->get_solo_control_is_listen_control()) {
1256                                         _session->set_listen (rl, !rl->front()->listening_via_monitor(), Session::rt_cleanup);
1257                                 } else {
1258                                         _session->set_solo (rl, !rl->front()->self_soloed(), Session::rt_cleanup);
1259                                 }
1260                         }
1261                         return true;
1262                         break;
1263
1264                 case 'r':
1265                         if (get_relevant_routes (rl)) {
1266                                 _session->set_record_enabled (rl, !rl->front()->record_enabled(), Session::rt_cleanup);
1267                         }
1268                         break;
1269
1270                 default:
1271                         break;
1272         }
1273
1274         return false;
1275 }
1276
1277 bool
1278 EditorRoutes::get_relevant_routes (boost::shared_ptr<RouteList> rl)
1279 {
1280         TimeAxisView* tv;
1281         RouteTimeAxisView* rtv;
1282         RefPtr<TreeSelection> selection = _display.get_selection();
1283         TreePath path;
1284         TreeIter iter;
1285
1286         if (selection->count_selected_rows() != 0) {
1287
1288                 /* use selection */
1289
1290                 RefPtr<TreeModel> tm = RefPtr<TreeModel>::cast_dynamic (_model);
1291                 iter = selection->get_selected (tm);
1292
1293         } else {
1294                 /* use mouse pointer */
1295
1296                 int x, y;
1297                 int bx, by;
1298
1299                 _display.get_pointer (x, y);
1300                 _display.convert_widget_to_bin_window_coords (x, y, bx, by);
1301
1302                 if (_display.get_path_at_pos (bx, by, path)) {
1303                         iter = _model->get_iter (path);
1304                 }
1305         }
1306
1307         if (iter) {
1308                 tv = (*iter)[_columns.tv];
1309                 if (tv) {
1310                         rtv = dynamic_cast<RouteTimeAxisView*>(tv);
1311                         if (rtv) {
1312                                 rl->push_back (rtv->route());
1313                         }
1314                 }
1315         }
1316
1317         return !rl->empty();
1318 }
1319
1320 bool
1321 EditorRoutes::button_press (GdkEventButton* ev)
1322 {
1323         if (Keyboard::is_context_menu_event (ev)) {
1324                 show_menu ();
1325                 return true;
1326         }
1327
1328         TreeModel::Path path;
1329         TreeViewColumn *tvc;
1330         int cell_x;
1331         int cell_y;
1332
1333         if (!_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, tvc, cell_x, cell_y)) {
1334                 /* cancel selection */
1335                 _display.get_selection()->unselect_all ();
1336                 /* end any editing by grabbing focus */
1337                 _display.grab_focus ();
1338                 return true;
1339         }
1340
1341         //Scroll editor canvas to selected track
1342         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1343
1344                 Gtk::TreeModel::Row row = *_model->get_iter (path);
1345                 TimeAxisView *tv = row[_columns.tv];
1346
1347                 if (tv) {
1348                         _editor->ensure_time_axis_view_is_visible (*tv, true);
1349                 }
1350         }
1351
1352         return false;
1353 }
1354
1355 void
1356 EditorRoutes::selection_changed ()
1357 {
1358         _editor->begin_reversible_selection_op (X_("Select Track from Route List"));
1359
1360         if (_display.get_selection()->count_selected_rows() > 0) {
1361
1362                 TreeIter iter;
1363                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
1364                 TrackViewList selected;
1365
1366                 _editor->get_selection().clear_regions ();
1367
1368                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
1369
1370                         if ((iter = _model->get_iter (*i))) {
1371
1372                                 TimeAxisView* tv = (*iter)[_columns.tv];
1373                                 selected.push_back (tv);
1374                         }
1375
1376                 }
1377
1378                 _editor->get_selection().set (selected);
1379                 _editor->ensure_time_axis_view_is_visible (*(selected.front()), true);
1380
1381         } else {
1382                 _editor->get_selection().clear_tracks ();
1383         }
1384
1385         _editor->commit_reversible_selection_op ();
1386 }
1387
1388 bool
1389 EditorRoutes::selection_filter (Glib::RefPtr<TreeModel> const &, TreeModel::Path const&, bool /*selected*/)
1390 {
1391         if (selection_countdown) {
1392                 if (--selection_countdown == 0) {
1393                         return true;
1394                 } else {
1395                         /* no selection yet ... */
1396                         return false;
1397                 }
1398         }
1399         return true;
1400 }
1401
1402 struct EditorOrderRouteSorter
1403 {
1404         bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
1405                 if (a->is_master()) {
1406                         /* master before everything else */
1407                         return true;
1408                 } else if (b->is_master()) {
1409                         /* everything else before master */
1410                         return false;
1411                 }
1412                 return a->order_key () < b->order_key ();
1413         }
1414 };
1415
1416 void
1417 EditorRoutes::initial_display ()
1418 {
1419         DisplaySuspender ds;
1420         _model->clear ();
1421
1422         if (!_session) {
1423                 return;
1424         }
1425
1426         RouteList r (*_session->get_routes());
1427
1428         r.sort (EditorOrderRouteSorter ());
1429         _editor->add_routes (r);
1430 }
1431
1432 void
1433 EditorRoutes::display_drag_data_received (const RefPtr<Gdk::DragContext>& context,
1434                                              int x, int y,
1435                                              const SelectionData& data,
1436                                              guint info, guint time)
1437 {
1438         if (data.get_target() == "GTK_TREE_MODEL_ROW") {
1439                 _display.on_drag_data_received (context, x, y, data, info, time);
1440                 return;
1441         }
1442
1443         context->drag_finish (true, false, time);
1444 }
1445
1446 void
1447 EditorRoutes::move_selected_tracks (bool up)
1448 {
1449         if (_editor->selection->tracks.empty()) {
1450                 return;
1451         }
1452
1453         typedef std::pair<TimeAxisView*,boost::shared_ptr<Route> > ViewRoute;
1454         std::list<ViewRoute> view_routes;
1455         std::vector<int> neworder;
1456         TreeModel::Children rows = _model->children();
1457         TreeModel::Children::iterator ri;
1458
1459         for (ri = rows.begin(); ri != rows.end(); ++ri) {
1460                 TimeAxisView* tv = (*ri)[_columns.tv];
1461                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
1462
1463                 view_routes.push_back (ViewRoute (tv, route));
1464         }
1465
1466         list<ViewRoute>::iterator trailing;
1467         list<ViewRoute>::iterator leading;
1468
1469         if (up) {
1470
1471                 trailing = view_routes.begin();
1472                 leading = view_routes.begin();
1473
1474                 ++leading;
1475
1476                 while (leading != view_routes.end()) {
1477                         if (_editor->selection->selected (leading->first)) {
1478                                 view_routes.insert (trailing, ViewRoute (leading->first, leading->second));
1479                                 leading = view_routes.erase (leading);
1480                         } else {
1481                                 ++leading;
1482                                 ++trailing;
1483                         }
1484                 }
1485
1486         } else {
1487
1488                 /* if we could use reverse_iterator in list::insert, this code
1489                    would be a beautiful reflection of the code above. but we can't
1490                    and so it looks like a bit of a mess.
1491                 */
1492
1493                 trailing = view_routes.end();
1494                 leading = view_routes.end();
1495
1496                 --leading; if (leading == view_routes.begin()) { return; }
1497                 --leading;
1498                 --trailing;
1499
1500                 while (1) {
1501
1502                         if (_editor->selection->selected (leading->first)) {
1503                                 list<ViewRoute>::iterator tmp;
1504
1505                                 /* need to insert *after* trailing, not *before* it,
1506                                    which is what insert (iter, val) normally does.
1507                                 */
1508
1509                                 tmp = trailing;
1510                                 tmp++;
1511
1512                                 view_routes.insert (tmp, ViewRoute (leading->first, leading->second));
1513
1514                                 /* can't use iter = cont.erase (iter); form here, because
1515                                    we need iter to move backwards.
1516                                 */
1517
1518                                 tmp = leading;
1519                                 --tmp;
1520
1521                                 bool done = false;
1522
1523                                 if (leading == view_routes.begin()) {
1524                                         /* the one we've just inserted somewhere else
1525                                            was the first in the list. erase this copy,
1526                                            and then break, because we're done.
1527                                         */
1528                                         done = true;
1529                                 }
1530
1531                                 view_routes.erase (leading);
1532
1533                                 if (done) {
1534                                         break;
1535                                 }
1536
1537                                 leading = tmp;
1538
1539                         } else {
1540                                 if (leading == view_routes.begin()) {
1541                                         break;
1542                                 }
1543                                 --leading;
1544                                 --trailing;
1545                         }
1546                 };
1547         }
1548
1549         for (leading = view_routes.begin(); leading != view_routes.end(); ++leading) {
1550                 uint32_t order = leading->second->order_key ();
1551                 neworder.push_back (order);
1552         }
1553
1554 #ifndef NDEBUG
1555         DEBUG_TRACE (DEBUG::OrderKeys, "New order after moving tracks:\n");
1556         for (vector<int>::iterator i = neworder.begin(); i != neworder.end(); ++i) {
1557                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("\t%1\n", *i));
1558         }
1559         DEBUG_TRACE (DEBUG::OrderKeys, "-------\n");
1560
1561         for (vector<int>::iterator i = neworder.begin(); i != neworder.end(); ++i) {
1562                 if (*i >= (int) neworder.size()) {
1563                         cerr << "Trying to move something to " << *i << " of " << neworder.size() << endl;
1564                 }
1565                 assert (*i < (int) neworder.size ());
1566         }
1567 #endif
1568
1569         _model->reorder (neworder);
1570 }
1571
1572 void
1573 EditorRoutes::update_input_active_display ()
1574 {
1575         TreeModel::Children rows = _model->children();
1576         TreeModel::Children::iterator i;
1577
1578         for (i = rows.begin(); i != rows.end(); ++i) {
1579                 boost::shared_ptr<Route> route = (*i)[_columns.route];
1580
1581                 if (boost::dynamic_pointer_cast<Track> (route)) {
1582                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
1583
1584                         if (mt) {
1585                                 (*i)[_columns.is_input_active] = mt->input_active();
1586                         }
1587                 }
1588         }
1589 }
1590
1591 void
1592 EditorRoutes::update_rec_display ()
1593 {
1594         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1595                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1596         }
1597 }
1598
1599 bool
1600 EditorRoutes::idle_update_mute_rec_solo_etc()
1601 {
1602         g_atomic_int_set (const_cast<gint*>(&_queue_tv_update), 0);
1603         TreeModel::Children rows = _model->children();
1604         TreeModel::Children::iterator i;
1605
1606         for (i = rows.begin(); i != rows.end(); ++i) {
1607                 boost::shared_ptr<Route> route = (*i)[_columns.route];
1608                 (*i)[_columns.mute_state] = RouteUI::mute_active_state (_session, route);
1609                 (*i)[_columns.solo_state] = RouteUI::solo_active_state (route);
1610                 (*i)[_columns.solo_isolate_state] = RouteUI::solo_isolate_active_state (route) ? 1 : 0;
1611                 (*i)[_columns.solo_safe_state] = RouteUI::solo_safe_active_state (route) ? 1 : 0;
1612                 (*i)[_columns.active] = route->active ();
1613                 if (boost::dynamic_pointer_cast<Track> (route)) {
1614                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
1615
1616                         if (route->record_enabled()) {
1617                                 if (_session->record_status() == Session::Recording) {
1618                                         (*i)[_columns.rec_state] = 1;
1619                                 } else {
1620                                         (*i)[_columns.rec_state] = 2;
1621                                 }
1622                         } else if (mt && mt->step_editing()) {
1623                                 (*i)[_columns.rec_state] = 3;
1624                         } else {
1625                                 (*i)[_columns.rec_state] = 0;
1626                         }
1627
1628                         // TODO figure out how to make this Cell insensitive
1629                         // and see RouteUI::check_rec_enable_sensitivity()
1630
1631                         (*i)[_columns.name_editable] = !route->record_enabled ();
1632                 }
1633         }
1634
1635         return false; // do not call again (until needed)
1636 }
1637
1638
1639 void
1640 EditorRoutes::update_mute_display ()
1641 {
1642         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1643                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1644         }
1645 }
1646
1647 void
1648 EditorRoutes::update_solo_display ()
1649 {
1650         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1651                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1652         }
1653 }
1654
1655 void
1656 EditorRoutes::update_solo_isolate_display ()
1657 {
1658         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1659                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1660         }
1661 }
1662
1663 void
1664 EditorRoutes::update_solo_safe_display ()
1665 {
1666         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1667                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1668         }
1669 }
1670
1671 list<TimeAxisView*>
1672 EditorRoutes::views () const
1673 {
1674         list<TimeAxisView*> v;
1675         for (TreeModel::Children::iterator i = _model->children().begin(); i != _model->children().end(); ++i) {
1676                 v.push_back ((*i)[_columns.tv]);
1677         }
1678
1679         return v;
1680 }
1681
1682 void
1683 EditorRoutes::clear ()
1684 {
1685         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1686         _model->clear ();
1687         _display.set_model (_model);
1688 }
1689
1690 void
1691 EditorRoutes::name_edit_started (CellEditable* ce, const Glib::ustring&)
1692 {
1693         name_editable = ce;
1694
1695         /* give it a special name */
1696
1697         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
1698
1699         if (e) {
1700                 e->set_name (X_("RouteNameEditorEntry"));
1701         }
1702 }
1703
1704 void
1705 EditorRoutes::name_edit (std::string const & path, std::string const & new_text)
1706 {
1707         name_editable = 0;
1708
1709         TreeIter iter = _model->get_iter (path);
1710
1711         if (!iter) {
1712                 return;
1713         }
1714
1715         boost::shared_ptr<Route> route = (*iter)[_columns.route];
1716
1717         if (route && route->name() != new_text) {
1718                 route->set_name (new_text);
1719         }
1720 }
1721
1722 void
1723 EditorRoutes::solo_changed_so_update_mute ()
1724 {
1725         update_mute_display ();
1726 }
1727
1728 void
1729 EditorRoutes::show_tracks_with_regions_at_playhead ()
1730 {
1731         boost::shared_ptr<RouteList> const r = _session->get_routes_with_regions_at (_session->transport_frame ());
1732
1733         set<TimeAxisView*> show;
1734         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
1735                 TimeAxisView* tav = _editor->axis_view_from_route (*i);
1736                 if (tav) {
1737                         show.insert (tav);
1738                 }
1739         }
1740
1741         DisplaySuspender ds;
1742
1743         TreeModel::Children rows = _model->children ();
1744         for (TreeModel::Children::iterator i = rows.begin(); i != rows.end(); ++i) {
1745                 TimeAxisView* tv = (*i)[_columns.tv];
1746                 bool to_show = (show.find (tv) != show.end());
1747
1748                 tv->set_marked_for_display (to_show);
1749                 (*i)[_columns.visible] = to_show;
1750         }
1751
1752         /* force route order keys catch up with visibility changes
1753          */
1754
1755         sync_order_keys_from_treeview ();
1756 }
1757
1758 int
1759 EditorRoutes::plugin_setup (boost::shared_ptr<Route> r, boost::shared_ptr<PluginInsert> pi, ARDOUR::Route::PluginSetupOptions flags)
1760 {
1761         PluginSetupDialog psd (r, pi, flags);
1762         return psd.run ();
1763 }