towards an Instrument Setup/Replace workflow
[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                 }
715
716                 if ((*x)->is_midi_track()) {
717                         boost::shared_ptr<MidiTrack> t = boost::dynamic_pointer_cast<MidiTrack> ((*x)->route());
718                         t->StepEditStatusChange.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_rec_display, this), gui_context());
719                         t->InputActiveChanged.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_input_active_display, this), gui_context());
720                 }
721
722                 (*x)->route()->mute_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_mute_display, this), gui_context());
723                 (*x)->route()->solo_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_display, this), gui_context());
724                 (*x)->route()->listen_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_display, this), gui_context());
725                 (*x)->route()->solo_isolated_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_isolate_display, this), gui_context());
726                 (*x)->route()->solo_safe_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_solo_safe_display, this), gui_context());
727                 (*x)->route()->active_changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&EditorRoutes::update_active_display, this), gui_context ());
728
729         }
730
731         update_rec_display ();
732         update_mute_display ();
733         update_solo_display ();
734         update_solo_isolate_display ();
735         update_solo_safe_display ();
736         update_input_active_display ();
737         update_active_display ();
738
739         _display.set_model (_model);
740
741         /* now update route order keys from the treeview/track display order */
742         if (!from_scratch) {
743                 sync_order_keys_from_treeview ();
744         }
745 }
746
747 void
748 EditorRoutes::handle_gui_changes (string const & what, void*)
749 {
750         if (_adding_routes) {
751                 return;
752         }
753
754         if (what == "track_height") {
755                 /* Optional :make tracks change height while it happens, instead
756                    of on first-idle
757                 */
758                 redisplay ();
759         }
760
761         if (what == "visible_tracks") {
762                 redisplay ();
763         }
764 }
765
766 void
767 EditorRoutes::route_removed (TimeAxisView *tv)
768 {
769         ENSURE_GUI_THREAD (*this, &EditorRoutes::route_removed, tv)
770
771         TreeModel::Children rows = _model->children();
772         TreeModel::Children::iterator ri;
773
774         for (ri = rows.begin(); ri != rows.end(); ++ri) {
775                 if ((*ri)[_columns.tv] == tv) {
776                         PBD::Unwinder<bool> uw (_route_deletion_in_progress, true);
777                         _model->erase (ri);
778                         break;
779                 }
780         }
781
782         /* the deleted signal for the treeview/model will take
783            care of any updates.
784         */
785 }
786
787 void
788 EditorRoutes::route_property_changed (const PropertyChange& what_changed, boost::weak_ptr<Route> r)
789 {
790         if (!what_changed.contains (ARDOUR::Properties::name)) {
791                 return;
792         }
793
794         ENSURE_GUI_THREAD (*this, &EditorRoutes::route_name_changed, r)
795
796         boost::shared_ptr<Route> route = r.lock ();
797
798         if (!route) {
799                 return;
800         }
801
802         TreeModel::Children rows = _model->children();
803         TreeModel::Children::iterator i;
804
805         for (i = rows.begin(); i != rows.end(); ++i) {
806                 boost::shared_ptr<Route> t = (*i)[_columns.route];
807                 if (t == route) {
808                         (*i)[_columns.text] = route->name();
809                         break;
810                 }
811         }
812 }
813
814 void
815 EditorRoutes::update_active_display ()
816 {
817         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
818                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
819         }
820 }
821
822 void
823 EditorRoutes::update_visibility ()
824 {
825         TreeModel::Children rows = _model->children();
826         TreeModel::Children::iterator i;
827
828         DisplaySuspender ds;
829
830         for (i = rows.begin(); i != rows.end(); ++i) {
831                 TimeAxisView *tv = (*i)[_columns.tv];
832                 (*i)[_columns.visible] = tv->marked_for_display ();
833         }
834
835         /* force route order keys catch up with visibility changes
836          */
837
838         sync_order_keys_from_treeview ();
839 }
840
841 void
842 EditorRoutes::hide_track_in_display (TimeAxisView& tv)
843 {
844         TreeModel::Children rows = _model->children();
845         TreeModel::Children::iterator i;
846
847         for (i = rows.begin(); i != rows.end(); ++i) {
848                 if ((*i)[_columns.tv] == &tv) {
849                         tv.set_marked_for_display (false);
850                         (*i)[_columns.visible] = false;
851                         redisplay ();
852                         break;
853                 }
854         }
855 }
856
857 void
858 EditorRoutes::show_track_in_display (TimeAxisView& tv)
859 {
860         TreeModel::Children rows = _model->children();
861         TreeModel::Children::iterator i;
862
863
864         for (i = rows.begin(); i != rows.end(); ++i) {
865                 if ((*i)[_columns.tv] == &tv) {
866                         tv.set_marked_for_display (true);
867                         (*i)[_columns.visible] = true;
868                         redisplay ();
869                         break;
870                 }
871         }
872 }
873
874 void
875 EditorRoutes::reset_remote_control_ids ()
876 {
877         if (Config->get_remote_model() == UserOrdered || !_session || _session->deletion_in_progress()) {
878                 return;
879         }
880
881         TreeModel::Children rows = _model->children();
882
883         if (rows.empty()) {
884                 return;
885         }
886
887
888         DEBUG_TRACE (DEBUG::OrderKeys, "editor reset remote control ids\n");
889
890         TreeModel::Children::iterator ri;
891         bool rid_change = false;
892         uint32_t rid = 1;
893         uint32_t invisible_key = UINT32_MAX;
894
895         for (ri = rows.begin(); ri != rows.end(); ++ri) {
896
897                 /* skip two special values */
898
899                 if (rid == Route::MasterBusRemoteControlID) {
900                         rid++;
901                 }
902
903                 if (rid == Route::MonitorBusRemoteControlID) {
904                         rid++;
905                 }
906
907                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
908                 bool visible = (*ri)[_columns.visible];
909
910                 if (!route->is_master() && !route->is_monitor()) {
911
912                         uint32_t new_rid = (visible ? rid : invisible_key--);
913
914                         if (new_rid != route->remote_control_id()) {
915                                 route->set_remote_control_id_explicit (new_rid);
916                                 rid_change = true;
917                         }
918
919                         if (visible) {
920                                 rid++;
921                         }
922
923                 }
924         }
925
926         if (rid_change) {
927                 /* tell the world that we changed the remote control IDs */
928                 _session->notify_remote_id_change ();
929         }
930 }
931
932
933 void
934 EditorRoutes::sync_order_keys_from_treeview ()
935 {
936         if (_ignore_reorder || !_session || _session->deletion_in_progress()) {
937                 return;
938         }
939
940         TreeModel::Children rows = _model->children();
941
942         if (rows.empty()) {
943                 return;
944         }
945
946
947         DEBUG_TRACE (DEBUG::OrderKeys, "editor sync order keys from treeview\n");
948
949         TreeModel::Children::iterator ri;
950         bool changed = false;
951         bool rid_change = false;
952         uint32_t order = 0;
953         uint32_t rid = 1;
954         uint32_t invisible_key = UINT32_MAX;
955
956         for (ri = rows.begin(); ri != rows.end(); ++ri) {
957
958                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
959                 bool visible = (*ri)[_columns.visible];
960
961                 uint32_t old_key = route->order_key ();
962
963                 if (order != old_key) {
964                         route->set_order_key (order);
965
966                         changed = true;
967                 }
968
969                 if ((Config->get_remote_model() == MixerOrdered) && !route->is_master() && !route->is_monitor()) {
970
971                         uint32_t new_rid = (visible ? rid : invisible_key--);
972
973                         if (new_rid != route->remote_control_id()) {
974                                 route->set_remote_control_id_explicit (new_rid);
975                                 rid_change = true;
976                         }
977
978                         if (visible) {
979                                 rid++;
980                         }
981
982                 }
983
984                 ++order;
985         }
986
987         if (changed) {
988                 /* tell the world that we changed the editor sort keys */
989                 _session->sync_order_keys ();
990         }
991
992         if (rid_change) {
993                 /* tell the world that we changed the remote control IDs */
994                 _session->notify_remote_id_change ();
995         }
996 }
997
998 void
999 EditorRoutes::sync_treeview_from_order_keys ()
1000 {
1001         /* Some route order key(s) have been changed, make sure that
1002            we update out tree/list model and GUI to reflect the change.
1003         */
1004
1005         if (_ignore_reorder || !_session || _session->deletion_in_progress()) {
1006                 return;
1007         }
1008
1009         DEBUG_TRACE (DEBUG::OrderKeys, "editor sync model from order keys.\n");
1010
1011         /* we could get here after either a change in the Mixer or Editor sort
1012          * order, but either way, the mixer order keys reflect the intended
1013          * order for the GUI, so reorder the treeview model to match it.
1014          */
1015
1016         vector<int> neworder;
1017         TreeModel::Children rows = _model->children();
1018         uint32_t old_order = 0;
1019         bool changed = false;
1020
1021         if (rows.empty()) {
1022                 return;
1023         }
1024
1025         OrderKeySortedRoutes sorted_routes;
1026
1027         for (TreeModel::Children::iterator ri = rows.begin(); ri != rows.end(); ++ri, ++old_order) {
1028                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
1029                 sorted_routes.push_back (RoutePlusOrderKey (route, old_order, route->order_key ()));
1030         }
1031
1032         SortByNewDisplayOrder cmp;
1033
1034         sort (sorted_routes.begin(), sorted_routes.end(), cmp);
1035         neworder.assign (sorted_routes.size(), 0);
1036
1037         uint32_t n = 0;
1038
1039         for (OrderKeySortedRoutes::iterator sr = sorted_routes.begin(); sr != sorted_routes.end(); ++sr, ++n) {
1040
1041                 neworder[n] = sr->old_display_order;
1042
1043                 if (sr->old_display_order != n) {
1044                         changed = true;
1045                 }
1046
1047                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("EDITOR change order for %1 from %2 to %3\n",
1048                                                                sr->route->name(), sr->old_display_order, n));
1049         }
1050
1051         if (changed) {
1052                 Unwinder<bool> uw (_ignore_reorder, true);
1053                 _model->reorder (neworder);
1054         }
1055
1056         redisplay ();
1057 }
1058
1059 void
1060 EditorRoutes::hide_all_tracks (bool /*with_select*/)
1061 {
1062         TreeModel::Children rows = _model->children();
1063         TreeModel::Children::iterator i;
1064
1065         DisplaySuspender ds;
1066
1067         for (i = rows.begin(); i != rows.end(); ++i) {
1068
1069                 TreeModel::Row row = (*i);
1070                 TimeAxisView *tv = row[_columns.tv];
1071
1072                 if (tv == 0) {
1073                         continue;
1074                 }
1075
1076                 row[_columns.visible] = false;
1077         }
1078 }
1079
1080 void
1081 EditorRoutes::set_all_tracks_visibility (bool yn)
1082 {
1083         TreeModel::Children rows = _model->children();
1084         TreeModel::Children::iterator i;
1085
1086         DisplaySuspender ds;
1087
1088         for (i = rows.begin(); i != rows.end(); ++i) {
1089
1090                 TreeModel::Row row = (*i);
1091                 TimeAxisView* tv = row[_columns.tv];
1092
1093                 if (tv == 0) {
1094                         continue;
1095                 }
1096
1097                 tv->set_marked_for_display (yn);
1098                 (*i)[_columns.visible] = yn;
1099         }
1100
1101         /* force route order keys catch up with visibility changes
1102          */
1103
1104         sync_order_keys_from_treeview ();
1105 }
1106
1107 void
1108 EditorRoutes::set_all_audio_midi_visibility (int tracks, bool yn)
1109 {
1110         TreeModel::Children rows = _model->children();
1111         TreeModel::Children::iterator i;
1112
1113         DisplaySuspender ds;
1114
1115         for (i = rows.begin(); i != rows.end(); ++i) {
1116
1117                 TreeModel::Row row = (*i);
1118                 TimeAxisView* tv = row[_columns.tv];
1119
1120                 AudioTimeAxisView* atv;
1121                 MidiTimeAxisView* mtv;
1122
1123                 if (tv == 0) {
1124                         continue;
1125                 }
1126
1127                 if ((atv = dynamic_cast<AudioTimeAxisView*>(tv)) != 0) {
1128                         switch (tracks) {
1129                         case 0:
1130                                 atv->set_marked_for_display (yn);
1131                                 (*i)[_columns.visible] = yn;
1132                                 break;
1133
1134                         case 1:
1135                                 if (atv->is_audio_track()) {
1136                                         atv->set_marked_for_display (yn);
1137                                         (*i)[_columns.visible] = yn;
1138                                 }
1139                                 break;
1140
1141                         case 2:
1142                                 if (!atv->is_audio_track()) {
1143                                         atv->set_marked_for_display (yn);
1144                                         (*i)[_columns.visible] = yn;
1145                                 }
1146                                 break;
1147                         }
1148                 }
1149                 else if ((mtv = dynamic_cast<MidiTimeAxisView*>(tv)) != 0) {
1150                         switch (tracks) {
1151                         case 0:
1152                                 mtv->set_marked_for_display (yn);
1153                                 (*i)[_columns.visible] = yn;
1154                                 break;
1155
1156                         case 3:
1157                                 if (mtv->is_midi_track()) {
1158                                         mtv->set_marked_for_display (yn);
1159                                         (*i)[_columns.visible] = yn;
1160                                 }
1161                                 break;
1162                         }
1163                 }
1164         }
1165
1166         /* force route order keys catch up with visibility changes
1167          */
1168
1169         sync_order_keys_from_treeview ();
1170 }
1171
1172 void
1173 EditorRoutes::hide_all_routes ()
1174 {
1175         set_all_tracks_visibility (false);
1176 }
1177
1178 void
1179 EditorRoutes::show_all_routes ()
1180 {
1181         set_all_tracks_visibility (true);
1182 }
1183
1184 void
1185 EditorRoutes::show_all_audiotracks()
1186 {
1187         set_all_audio_midi_visibility (1, true);
1188 }
1189 void
1190 EditorRoutes::hide_all_audiotracks ()
1191 {
1192         set_all_audio_midi_visibility (1, false);
1193 }
1194
1195 void
1196 EditorRoutes::show_all_audiobus ()
1197 {
1198         set_all_audio_midi_visibility (2, true);
1199 }
1200 void
1201 EditorRoutes::hide_all_audiobus ()
1202 {
1203         set_all_audio_midi_visibility (2, false);
1204 }
1205
1206 void
1207 EditorRoutes::show_all_miditracks()
1208 {
1209         set_all_audio_midi_visibility (3, true);
1210 }
1211 void
1212 EditorRoutes::hide_all_miditracks ()
1213 {
1214         set_all_audio_midi_visibility (3, false);
1215 }
1216
1217 bool
1218 EditorRoutes::key_press (GdkEventKey* ev)
1219 {
1220         TreeViewColumn *col;
1221         boost::shared_ptr<RouteList> rl (new RouteList);
1222         TreePath path;
1223
1224         switch (ev->keyval) {
1225                 case GDK_Tab:
1226                 case GDK_ISO_Left_Tab:
1227
1228                         /* If we appear to be editing something, leave that cleanly and appropriately. */
1229                         if (name_editable) {
1230                                 name_editable->editing_done ();
1231                                 name_editable = 0;
1232                         }
1233
1234                         col = _display.get_column (_name_column); // select&focus on name column
1235
1236                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
1237                                 treeview_select_previous (_display, _model, col);
1238                         } else {
1239                                 treeview_select_next (_display, _model, col);
1240                         }
1241
1242                         return true;
1243                         break;
1244
1245                 case 'm':
1246                         if (get_relevant_routes (rl)) {
1247                                 _session->set_mute (rl, !rl->front()->muted(), Session::rt_cleanup);
1248                         }
1249                         return true;
1250                         break;
1251
1252                 case 's':
1253                         if (get_relevant_routes (rl)) {
1254                                 if (Config->get_solo_control_is_listen_control()) {
1255                                         _session->set_listen (rl, !rl->front()->listening_via_monitor(), Session::rt_cleanup);
1256                                 } else {
1257                                         _session->set_solo (rl, !rl->front()->self_soloed(), Session::rt_cleanup);
1258                                 }
1259                         }
1260                         return true;
1261                         break;
1262
1263                 case 'r':
1264                         if (get_relevant_routes (rl)) {
1265                                 _session->set_record_enabled (rl, !rl->front()->record_enabled(), Session::rt_cleanup);
1266                         }
1267                         break;
1268
1269                 default:
1270                         break;
1271         }
1272
1273         return false;
1274 }
1275
1276 bool
1277 EditorRoutes::get_relevant_routes (boost::shared_ptr<RouteList> rl)
1278 {
1279         TimeAxisView* tv;
1280         RouteTimeAxisView* rtv;
1281         RefPtr<TreeSelection> selection = _display.get_selection();
1282         TreePath path;
1283         TreeIter iter;
1284
1285         if (selection->count_selected_rows() != 0) {
1286
1287                 /* use selection */
1288
1289                 RefPtr<TreeModel> tm = RefPtr<TreeModel>::cast_dynamic (_model);
1290                 iter = selection->get_selected (tm);
1291
1292         } else {
1293                 /* use mouse pointer */
1294
1295                 int x, y;
1296                 int bx, by;
1297
1298                 _display.get_pointer (x, y);
1299                 _display.convert_widget_to_bin_window_coords (x, y, bx, by);
1300
1301                 if (_display.get_path_at_pos (bx, by, path)) {
1302                         iter = _model->get_iter (path);
1303                 }
1304         }
1305
1306         if (iter) {
1307                 tv = (*iter)[_columns.tv];
1308                 if (tv) {
1309                         rtv = dynamic_cast<RouteTimeAxisView*>(tv);
1310                         if (rtv) {
1311                                 rl->push_back (rtv->route());
1312                         }
1313                 }
1314         }
1315
1316         return !rl->empty();
1317 }
1318
1319 bool
1320 EditorRoutes::button_press (GdkEventButton* ev)
1321 {
1322         if (Keyboard::is_context_menu_event (ev)) {
1323                 show_menu ();
1324                 return true;
1325         }
1326
1327         TreeModel::Path path;
1328         TreeViewColumn *tvc;
1329         int cell_x;
1330         int cell_y;
1331
1332         if (!_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, tvc, cell_x, cell_y)) {
1333                 /* cancel selection */
1334                 _display.get_selection()->unselect_all ();
1335                 /* end any editing by grabbing focus */
1336                 _display.grab_focus ();
1337                 return true;
1338         }
1339
1340         //Scroll editor canvas to selected track
1341         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1342
1343                 Gtk::TreeModel::Row row = *_model->get_iter (path);
1344                 TimeAxisView *tv = row[_columns.tv];
1345
1346                 if (tv) {
1347                         _editor->ensure_time_axis_view_is_visible (*tv, true);
1348                 }
1349         }
1350
1351         return false;
1352 }
1353
1354 void
1355 EditorRoutes::selection_changed ()
1356 {
1357         _editor->begin_reversible_selection_op (X_("Select Track from Route List"));
1358
1359         if (_display.get_selection()->count_selected_rows() > 0) {
1360
1361                 TreeIter iter;
1362                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
1363                 TrackViewList selected;
1364
1365                 _editor->get_selection().clear_regions ();
1366
1367                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
1368
1369                         if ((iter = _model->get_iter (*i))) {
1370
1371                                 TimeAxisView* tv = (*iter)[_columns.tv];
1372                                 selected.push_back (tv);
1373                         }
1374
1375                 }
1376
1377                 _editor->get_selection().set (selected);
1378                 _editor->ensure_time_axis_view_is_visible (*(selected.front()), true);
1379
1380         } else {
1381                 _editor->get_selection().clear_tracks ();
1382         }
1383
1384         _editor->commit_reversible_selection_op ();
1385 }
1386
1387 bool
1388 EditorRoutes::selection_filter (Glib::RefPtr<TreeModel> const &, TreeModel::Path const&, bool /*selected*/)
1389 {
1390         if (selection_countdown) {
1391                 if (--selection_countdown == 0) {
1392                         return true;
1393                 } else {
1394                         /* no selection yet ... */
1395                         return false;
1396                 }
1397         }
1398         return true;
1399 }
1400
1401 struct EditorOrderRouteSorter
1402 {
1403         bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
1404                 if (a->is_master()) {
1405                         /* master before everything else */
1406                         return true;
1407                 } else if (b->is_master()) {
1408                         /* everything else before master */
1409                         return false;
1410                 }
1411                 return a->order_key () < b->order_key ();
1412         }
1413 };
1414
1415 void
1416 EditorRoutes::initial_display ()
1417 {
1418         DisplaySuspender ds;
1419         _model->clear ();
1420
1421         if (!_session) {
1422                 return;
1423         }
1424
1425         RouteList r (*_session->get_routes());
1426
1427         r.sort (EditorOrderRouteSorter ());
1428         _editor->add_routes (r);
1429 }
1430
1431 void
1432 EditorRoutes::display_drag_data_received (const RefPtr<Gdk::DragContext>& context,
1433                                              int x, int y,
1434                                              const SelectionData& data,
1435                                              guint info, guint time)
1436 {
1437         if (data.get_target() == "GTK_TREE_MODEL_ROW") {
1438                 _display.on_drag_data_received (context, x, y, data, info, time);
1439                 return;
1440         }
1441
1442         context->drag_finish (true, false, time);
1443 }
1444
1445 void
1446 EditorRoutes::move_selected_tracks (bool up)
1447 {
1448         if (_editor->selection->tracks.empty()) {
1449                 return;
1450         }
1451
1452         typedef std::pair<TimeAxisView*,boost::shared_ptr<Route> > ViewRoute;
1453         std::list<ViewRoute> view_routes;
1454         std::vector<int> neworder;
1455         TreeModel::Children rows = _model->children();
1456         TreeModel::Children::iterator ri;
1457
1458         for (ri = rows.begin(); ri != rows.end(); ++ri) {
1459                 TimeAxisView* tv = (*ri)[_columns.tv];
1460                 boost::shared_ptr<Route> route = (*ri)[_columns.route];
1461
1462                 view_routes.push_back (ViewRoute (tv, route));
1463         }
1464
1465         list<ViewRoute>::iterator trailing;
1466         list<ViewRoute>::iterator leading;
1467
1468         if (up) {
1469
1470                 trailing = view_routes.begin();
1471                 leading = view_routes.begin();
1472
1473                 ++leading;
1474
1475                 while (leading != view_routes.end()) {
1476                         if (_editor->selection->selected (leading->first)) {
1477                                 view_routes.insert (trailing, ViewRoute (leading->first, leading->second));
1478                                 leading = view_routes.erase (leading);
1479                         } else {
1480                                 ++leading;
1481                                 ++trailing;
1482                         }
1483                 }
1484
1485         } else {
1486
1487                 /* if we could use reverse_iterator in list::insert, this code
1488                    would be a beautiful reflection of the code above. but we can't
1489                    and so it looks like a bit of a mess.
1490                 */
1491
1492                 trailing = view_routes.end();
1493                 leading = view_routes.end();
1494
1495                 --leading; if (leading == view_routes.begin()) { return; }
1496                 --leading;
1497                 --trailing;
1498
1499                 while (1) {
1500
1501                         if (_editor->selection->selected (leading->first)) {
1502                                 list<ViewRoute>::iterator tmp;
1503
1504                                 /* need to insert *after* trailing, not *before* it,
1505                                    which is what insert (iter, val) normally does.
1506                                 */
1507
1508                                 tmp = trailing;
1509                                 tmp++;
1510
1511                                 view_routes.insert (tmp, ViewRoute (leading->first, leading->second));
1512
1513                                 /* can't use iter = cont.erase (iter); form here, because
1514                                    we need iter to move backwards.
1515                                 */
1516
1517                                 tmp = leading;
1518                                 --tmp;
1519
1520                                 bool done = false;
1521
1522                                 if (leading == view_routes.begin()) {
1523                                         /* the one we've just inserted somewhere else
1524                                            was the first in the list. erase this copy,
1525                                            and then break, because we're done.
1526                                         */
1527                                         done = true;
1528                                 }
1529
1530                                 view_routes.erase (leading);
1531
1532                                 if (done) {
1533                                         break;
1534                                 }
1535
1536                                 leading = tmp;
1537
1538                         } else {
1539                                 if (leading == view_routes.begin()) {
1540                                         break;
1541                                 }
1542                                 --leading;
1543                                 --trailing;
1544                         }
1545                 };
1546         }
1547
1548         for (leading = view_routes.begin(); leading != view_routes.end(); ++leading) {
1549                 uint32_t order = leading->second->order_key ();
1550                 neworder.push_back (order);
1551         }
1552
1553 #ifndef NDEBUG
1554         DEBUG_TRACE (DEBUG::OrderKeys, "New order after moving tracks:\n");
1555         for (vector<int>::iterator i = neworder.begin(); i != neworder.end(); ++i) {
1556                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("\t%1\n", *i));
1557         }
1558         DEBUG_TRACE (DEBUG::OrderKeys, "-------\n");
1559
1560         for (vector<int>::iterator i = neworder.begin(); i != neworder.end(); ++i) {
1561                 if (*i >= (int) neworder.size()) {
1562                         cerr << "Trying to move something to " << *i << " of " << neworder.size() << endl;
1563                 }
1564                 assert (*i < (int) neworder.size ());
1565         }
1566 #endif
1567
1568         _model->reorder (neworder);
1569 }
1570
1571 void
1572 EditorRoutes::update_input_active_display ()
1573 {
1574         TreeModel::Children rows = _model->children();
1575         TreeModel::Children::iterator i;
1576
1577         for (i = rows.begin(); i != rows.end(); ++i) {
1578                 boost::shared_ptr<Route> route = (*i)[_columns.route];
1579
1580                 if (boost::dynamic_pointer_cast<Track> (route)) {
1581                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
1582
1583                         if (mt) {
1584                                 (*i)[_columns.is_input_active] = mt->input_active();
1585                         }
1586                 }
1587         }
1588 }
1589
1590 void
1591 EditorRoutes::update_rec_display ()
1592 {
1593         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1594                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1595         }
1596 }
1597
1598 bool
1599 EditorRoutes::idle_update_mute_rec_solo_etc()
1600 {
1601         g_atomic_int_set (const_cast<gint*>(&_queue_tv_update), 0);
1602         TreeModel::Children rows = _model->children();
1603         TreeModel::Children::iterator i;
1604
1605         for (i = rows.begin(); i != rows.end(); ++i) {
1606                 boost::shared_ptr<Route> route = (*i)[_columns.route];
1607                 (*i)[_columns.mute_state] = RouteUI::mute_active_state (_session, route);
1608                 (*i)[_columns.solo_state] = RouteUI::solo_active_state (route);
1609                 (*i)[_columns.solo_isolate_state] = RouteUI::solo_isolate_active_state (route) ? 1 : 0;
1610                 (*i)[_columns.solo_safe_state] = RouteUI::solo_safe_active_state (route) ? 1 : 0;
1611                 (*i)[_columns.active] = route->active ();
1612                 if (boost::dynamic_pointer_cast<Track> (route)) {
1613                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
1614
1615                         if (route->record_enabled()) {
1616                                 if (_session->record_status() == Session::Recording) {
1617                                         (*i)[_columns.rec_state] = 1;
1618                                 } else {
1619                                         (*i)[_columns.rec_state] = 2;
1620                                 }
1621                         } else if (mt && mt->step_editing()) {
1622                                 (*i)[_columns.rec_state] = 3;
1623                         } else {
1624                                 (*i)[_columns.rec_state] = 0;
1625                         }
1626
1627                         (*i)[_columns.name_editable] = !route->record_enabled ();
1628                 }
1629         }
1630
1631         return false; // do not call again (until needed)
1632 }
1633
1634
1635 void
1636 EditorRoutes::update_mute_display ()
1637 {
1638         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1639                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1640         }
1641 }
1642
1643 void
1644 EditorRoutes::update_solo_display ()
1645 {
1646         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1647                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1648         }
1649 }
1650
1651 void
1652 EditorRoutes::update_solo_isolate_display ()
1653 {
1654         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1655                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1656         }
1657 }
1658
1659 void
1660 EditorRoutes::update_solo_safe_display ()
1661 {
1662         if (g_atomic_int_compare_and_exchange (const_cast<gint*>(&_queue_tv_update), 0, 1)) {
1663                 Glib::signal_idle().connect (sigc::mem_fun (*this, &EditorRoutes::idle_update_mute_rec_solo_etc));
1664         }
1665 }
1666
1667 list<TimeAxisView*>
1668 EditorRoutes::views () const
1669 {
1670         list<TimeAxisView*> v;
1671         for (TreeModel::Children::iterator i = _model->children().begin(); i != _model->children().end(); ++i) {
1672                 v.push_back ((*i)[_columns.tv]);
1673         }
1674
1675         return v;
1676 }
1677
1678 void
1679 EditorRoutes::clear ()
1680 {
1681         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1682         _model->clear ();
1683         _display.set_model (_model);
1684 }
1685
1686 void
1687 EditorRoutes::name_edit_started (CellEditable* ce, const Glib::ustring&)
1688 {
1689         name_editable = ce;
1690
1691         /* give it a special name */
1692
1693         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
1694
1695         if (e) {
1696                 e->set_name (X_("RouteNameEditorEntry"));
1697         }
1698 }
1699
1700 void
1701 EditorRoutes::name_edit (std::string const & path, std::string const & new_text)
1702 {
1703         name_editable = 0;
1704
1705         TreeIter iter = _model->get_iter (path);
1706
1707         if (!iter) {
1708                 return;
1709         }
1710
1711         boost::shared_ptr<Route> route = (*iter)[_columns.route];
1712
1713         if (route && route->name() != new_text) {
1714                 route->set_name (new_text);
1715         }
1716 }
1717
1718 void
1719 EditorRoutes::solo_changed_so_update_mute ()
1720 {
1721         update_mute_display ();
1722 }
1723
1724 void
1725 EditorRoutes::show_tracks_with_regions_at_playhead ()
1726 {
1727         boost::shared_ptr<RouteList> const r = _session->get_routes_with_regions_at (_session->transport_frame ());
1728
1729         set<TimeAxisView*> show;
1730         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
1731                 TimeAxisView* tav = _editor->axis_view_from_route (*i);
1732                 if (tav) {
1733                         show.insert (tav);
1734                 }
1735         }
1736
1737         DisplaySuspender ds;
1738
1739         TreeModel::Children rows = _model->children ();
1740         for (TreeModel::Children::iterator i = rows.begin(); i != rows.end(); ++i) {
1741                 TimeAxisView* tv = (*i)[_columns.tv];
1742                 bool to_show = (show.find (tv) != show.end());
1743
1744                 tv->set_marked_for_display (to_show);
1745                 (*i)[_columns.visible] = to_show;
1746         }
1747
1748         /* force route order keys catch up with visibility changes
1749          */
1750
1751         sync_order_keys_from_treeview ();
1752 }
1753
1754 int
1755 EditorRoutes::plugin_setup (boost::shared_ptr<Route> r, boost::shared_ptr<PluginInsert> pi, ARDOUR::Route::PluginSetupOptions flags)
1756 {
1757         PluginSetupDialog psd (r, pi, flags);
1758         return psd.run ();
1759 }