extend strict-i/o to include route outputs.
[ardour.git] / gtk2_ardour / editor_regions.cc
1 /*
2     Copyright (C) 2000-2005 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 <cmath>
22 #include <algorithm>
23 #include <string>
24 #include <sstream>
25
26 #include "pbd/basename.h"
27 #include "pbd/enumwriter.h"
28
29 #include "ardour/audioregion.h"
30 #include "ardour/audiofilesource.h"
31 #include "ardour/silentfilesource.h"
32 #include "ardour/region_factory.h"
33 #include "ardour/session.h"
34 #include "ardour/profile.h"
35
36 #include "gtkmm2ext/choice.h"
37 #include "gtkmm2ext/treeutils.h"
38 #include "gtkmm2ext/utils.h"
39
40 #include "audio_clock.h"
41 #include "editor.h"
42 #include "editing.h"
43 #include "keyboard.h"
44 #include "ardour_ui.h"
45 #include "gui_thread.h"
46 #include "actions.h"
47 #include "region_view.h"
48 #include "utils.h"
49 #include "editor_regions.h"
50 #include "editor_drag.h"
51 #include "main_clock.h"
52 #include "tooltips.h"
53 #include "ui_config.h"
54
55 #include "i18n.h"
56
57 using namespace std;
58 using namespace ARDOUR;
59 using namespace ARDOUR_UI_UTILS;
60 using namespace PBD;
61 using namespace Gtk;
62 using namespace Glib;
63 using namespace Editing;
64 using Gtkmm2ext::Keyboard;
65
66 struct ColumnInfo {
67     int         index;
68     const char* label;
69     const char* tooltip;
70 };
71
72 EditorRegions::EditorRegions (Editor* e)
73         : EditorComponent (e)
74         , old_focus (0)
75         , name_editable (0)
76         , _menu (0)
77         , _show_automatic_regions (true)
78         , ignore_region_list_selection_change (false)
79         , ignore_selected_region_change (false)
80         , _no_redisplay (false)
81         , _sort_type ((Editing::RegionListSortType) 0)
82         , expanded (false)
83 {
84         _display.set_size_request (100, -1);
85         _display.set_rules_hint (true);
86         _display.set_name ("EditGroupList");
87
88         /* Try to prevent single mouse presses from initiating edits.
89            This relies on a hack in gtktreeview.c:gtk_treeview_button_press()
90         */
91         _display.set_data ("mouse-edits-require-mod1", (gpointer) 0x1);
92
93         _model = TreeStore::create (_columns);
94         _model->set_sort_func (0, sigc::mem_fun (*this, &EditorRegions::sorter));
95         _model->set_sort_column (0, SORT_ASCENDING);
96
97         _display.set_model (_model);
98
99         _display.append_column ("", _columns.name);
100         _display.append_column ("", _columns.position);
101         _display.append_column ("", _columns.end);
102         _display.append_column ("", _columns.length);
103         _display.append_column ("", _columns.sync);
104         _display.append_column ("", _columns.fadein);
105         _display.append_column ("", _columns.fadeout);
106         _display.append_column ("", _columns.locked);
107         _display.append_column ("", _columns.glued);
108         _display.append_column ("", _columns.muted);
109         _display.append_column ("", _columns.opaque);
110
111         TreeViewColumn* col;
112         Gtk::Label* l;
113
114         ColumnInfo ci[] = {
115                 { 0,   _("Region"),    _("Region name, with number of channels in []'s") },
116                 { 1,   _("Position"),  _("Position of start of region") },
117                 { 2,   _("End"),       _("Position of end of region") },
118                 { 3,   _("Length"),    _("Length of the region") },
119                 { 4,   _("Sync"),      _("Position of region sync point, relative to start of the region") },
120                 { 5,   _("Fade In"),   _("Length of region fade-in (units: secondary clock), () if disabled") },
121                 { 6,   _("Fade Out"),  _("Length of region fade-out (units: secondary clock), () if disabled") },
122                 { 7,  S_("Lock|L"),    _("Region position locked?") },
123                 { 8,  S_("Gain|G"),    _("Region position glued to Bars|Beats time?") },
124                 { 9,  S_("Mute|M"),    _("Region muted?") },
125                 { 10, S_("Opaque|O"),  _("Region opaque (blocks regions below it from being heard)?") },
126                 { -1, 0, 0 }
127         };
128
129         for (int i = 0; ci[i].index >= 0; ++i) {
130                 col = _display.get_column (ci[i].index);
131                 l = manage (new Label (ci[i].label));
132                 set_tooltip (*l, ci[i].tooltip);
133                 col->set_widget (*l);
134                 l->show ();
135
136                 if (ci[i].index > 6) {
137                         col->set_expand (false);
138                         col->set_alignment (ALIGN_CENTER);
139                 }
140         }
141
142         _display.set_headers_visible (true);
143         _display.set_rules_hint ();
144
145         /* show path as the row tooltip */
146         _display.set_tooltip_column (14); /* path */
147
148         CellRendererText* region_name_cell = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (0));
149         region_name_cell->property_editable() = true;
150         region_name_cell->signal_edited().connect (sigc::mem_fun (*this, &EditorRegions::name_edit));
151         region_name_cell->signal_editing_started().connect (sigc::mem_fun (*this, &EditorRegions::name_editing_started));
152
153         _display.get_selection()->set_select_function (sigc::mem_fun (*this, &EditorRegions::selection_filter));
154
155         TreeViewColumn* tv_col = _display.get_column(0);
156         CellRendererText* renderer = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (0));
157         tv_col->add_attribute(renderer->property_text(), _columns.name);
158         tv_col->add_attribute(renderer->property_foreground_gdk(), _columns.color_);
159         tv_col->set_expand (true);
160
161         CellRendererToggle* locked_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (7));
162         locked_cell->property_activatable() = true;
163         locked_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::locked_changed));
164
165         TreeViewColumn* locked_col = _display.get_column (7);
166         locked_col->add_attribute (locked_cell->property_visible(), _columns.property_toggles_visible);
167
168         CellRendererToggle* glued_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (8));
169         glued_cell->property_activatable() = true;
170         glued_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::glued_changed));
171
172         TreeViewColumn* glued_col = _display.get_column (8);
173         glued_col->add_attribute (glued_cell->property_visible(), _columns.property_toggles_visible);
174
175         CellRendererToggle* muted_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (9));
176         muted_cell->property_activatable() = true;
177         muted_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::muted_changed));
178
179         TreeViewColumn* muted_col = _display.get_column (9);
180         muted_col->add_attribute (muted_cell->property_visible(), _columns.property_toggles_visible);
181
182         CellRendererToggle* opaque_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (10));
183         opaque_cell->property_activatable() = true;
184         opaque_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::opaque_changed));
185
186         TreeViewColumn* opaque_col = _display.get_column (10);
187         opaque_col->add_attribute (opaque_cell->property_visible(), _columns.property_toggles_visible);
188
189         _display.get_selection()->set_mode (SELECTION_MULTIPLE);
190         _display.add_object_drag (_columns.region.index(), "regions");
191         _display.set_drag_column (_columns.name.index());
192
193         /* setup DnD handling */
194
195         list<TargetEntry> region_list_target_table;
196
197         region_list_target_table.push_back (TargetEntry ("text/plain"));
198         region_list_target_table.push_back (TargetEntry ("text/uri-list"));
199         region_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
200
201         _display.add_drop_targets (region_list_target_table);
202         _display.signal_drag_data_received().connect (sigc::mem_fun(*this, &EditorRegions::drag_data_received));
203
204         _scroller.add (_display);
205         _scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
206
207         _display.signal_button_press_event().connect (sigc::mem_fun(*this, &EditorRegions::button_press), false);
208         _change_connection = _display.get_selection()->signal_changed().connect (sigc::mem_fun(*this, &EditorRegions::selection_changed));
209
210         _scroller.signal_key_press_event().connect (sigc::mem_fun(*this, &EditorRegions::key_press), false);
211         _scroller.signal_focus_in_event().connect (sigc::mem_fun (*this, &EditorRegions::focus_in), false);
212         _scroller.signal_focus_out_event().connect (sigc::mem_fun (*this, &EditorRegions::focus_out));
213
214         _display.signal_enter_notify_event().connect (sigc::mem_fun (*this, &EditorRegions::enter_notify), false);
215         _display.signal_leave_notify_event().connect (sigc::mem_fun (*this, &EditorRegions::leave_notify), false);
216
217         // _display.signal_popup_menu().connect (sigc::bind (sigc::mem_fun (*this, &Editor::show__display_context_menu), 1, 0));
218
219         //ARDOUR_UI::instance()->secondary_clock.mode_changed.connect (sigc::mem_fun(*this, &Editor::redisplay_regions));
220         ARDOUR_UI::instance()->secondary_clock->mode_changed.connect (sigc::mem_fun(*this, &EditorRegions::update_all_rows));
221         ARDOUR::Region::RegionPropertyChanged.connect (region_property_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::region_changed, this, _1, _2), gui_context());
222         ARDOUR::RegionFactory::CheckNewRegion.connect (check_new_region_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::add_region, this, _1), gui_context());
223
224         e->EditorFreeze.connect (editor_freeze_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::freeze_tree_model, this), gui_context());
225         e->EditorThaw.connect (editor_thaw_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::thaw_tree_model, this), gui_context());
226 }
227
228 bool
229 EditorRegions::focus_in (GdkEventFocus*)
230 {
231         Window* win = dynamic_cast<Window*> (_scroller.get_toplevel ());
232
233         if (win) {
234                 old_focus = win->get_focus ();
235         } else {
236                 old_focus = 0;
237         }
238
239         name_editable = 0;
240
241         /* try to do nothing on focus in (doesn't work, hence selection_count nonsense) */
242         return true;
243 }
244
245 bool
246 EditorRegions::focus_out (GdkEventFocus*)
247 {
248         if (old_focus) {
249                 old_focus->grab_focus ();
250                 old_focus = 0;
251         }
252
253         name_editable = 0;
254
255         return false;
256 }
257
258 bool
259 EditorRegions::enter_notify (GdkEventCrossing*)
260 {
261         if (name_editable) {
262                 return true;
263         }
264
265         /* arm counter so that ::selection_filter() will deny selecting anything for the
266            next two attempts to change selection status.
267         */
268         _scroller.grab_focus ();
269         Keyboard::magic_widget_grab_focus ();
270         return false;
271 }
272
273 bool
274 EditorRegions::leave_notify (GdkEventCrossing*)
275 {
276         if (old_focus) {
277                 old_focus->grab_focus ();
278                 old_focus = 0;
279         }
280
281         Keyboard::magic_widget_drop_focus ();
282         return false;
283 }
284
285 void
286 EditorRegions::set_session (ARDOUR::Session* s)
287 {
288         SessionHandlePtr::set_session (s);
289         redisplay ();
290 }
291
292 void
293 EditorRegions::add_region (boost::shared_ptr<Region> region)
294 {
295         if (!region || !_session) {
296                 return;
297         }
298
299         string str;
300         TreeModel::Row row;
301         Gdk::Color c;
302         bool missing_source = boost::dynamic_pointer_cast<SilentFileSource>(region->source()) != NULL;
303
304         if (!_show_automatic_regions && region->automatic()) {
305                 return;
306         }
307
308         if (region->hidden()) {
309
310                 TreeModel::iterator iter = _model->get_iter ("0");
311                 TreeModel::Row parent;
312
313                 if (!iter) {
314                         parent = *(_model->append());
315                         parent[_columns.name] = _("Hidden");
316                         boost::shared_ptr<Region> proxy = parent[_columns.region];
317                         proxy.reset ();
318                 } else {
319                         string s = (*iter)[_columns.name];
320                         if (s != _("Hidden")) {
321                                 parent = *(_model->insert(iter));
322                                 parent[_columns.name] = _("Hidden");
323                                 boost::shared_ptr<Region> proxy = parent[_columns.region];
324                                 proxy.reset ();
325                         } else {
326                                 parent = *iter;
327                         }
328                 }
329
330                 row = *(_model->append (parent.children()));
331
332         } else if (region->whole_file()) {
333
334                 TreeModel::iterator i;
335                 TreeModel::Children rows = _model->children();
336
337                 for (i = rows.begin(); i != rows.end(); ++i) {
338                         boost::shared_ptr<Region> rr = (*i)[_columns.region];
339
340                         if (rr && region->region_list_equivalent (rr)) {
341                                 return;
342                         }
343                 }
344
345                 row = *(_model->append());
346
347                 if (missing_source) {
348                         // c.set_rgb(65535,0,0);     // FIXME: error color from style
349                         set_color_from_rgba (c, UIConfiguration::instance().color ("region list missing source"));
350
351                 } else if (region->automatic()){
352                         // c.set_rgb(0,65535,0);     // FIXME: error color from style
353                         set_color_from_rgba (c, UIConfiguration::instance().color ("region list automatic"));
354
355                 } else {
356                         set_color_from_rgba (c, UIConfiguration::instance().color ("region list whole file"));
357                 }
358
359                 row[_columns.color_] = c;
360
361                 if (region->source()->name()[0] == '/') { // external file
362
363                         if (region->whole_file()) {
364
365                                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(region->source());
366                                 str = ".../";
367
368                                 if (afs) {
369                                         str = region_name_from_path (afs->path(), region->n_channels() > 1);
370                                 } else {
371                                         str += region->source()->name();
372                                 }
373
374                         } else {
375                                 str = region->name();
376                         }
377
378                 } else {
379                         str = region->name();
380                 }
381
382                 populate_row_name (region, row);
383                 row[_columns.region] = region;
384                 row[_columns.property_toggles_visible] = false;
385
386                 if (missing_source) {
387                         row[_columns.path] = _("(MISSING) ") + Gtkmm2ext::markup_escape_text (region->source()->name());
388
389                 } else {
390                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource>(region->source());
391                         if (fs) {
392                                 row[_columns.path] = Gtkmm2ext::markup_escape_text (fs->path());
393                         } else {
394                                 row[_columns.path] = Gtkmm2ext::markup_escape_text (region->source()->name());
395                         }
396                 }
397
398                 region_row_map.insert(pair<boost::shared_ptr<ARDOUR::Region>, Gtk::TreeModel::RowReference>(region, TreeRowReference(_model, TreePath (row))) );
399                 parent_regions_sources_map.insert(pair<string, Gtk::TreeModel::RowReference>(region->source_string(), TreeRowReference(_model, TreePath (row))) );
400
401                 return;
402
403         } else {
404                 // find parent node, add as new child
405                 TreeModel::iterator i;
406
407                 boost::unordered_map<string, Gtk::TreeModel::RowReference>::iterator it;
408
409                 it = parent_regions_sources_map.find (region->source_string());
410
411                 if (it != parent_regions_sources_map.end()){
412
413                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
414
415                         TreeModel::iterator ii;
416                         TreeModel::Children subrows = (*j).children();
417
418                         /* XXXX: should we be accounting for all regions? */
419                         /*
420                         for (ii = subrows.begin(); ii != subrows.end(); ++ii) {
421                                 boost::shared_ptr<Region> rr = (*ii)[_columns.region];
422
423                                 if (region->region_list_equivalent (rr)) {
424                                         return;
425                                 }
426                         }
427                         */
428
429                         row = *(_model->insert (subrows.end()));
430
431                 } else {
432                         row = *(_model->append());
433                 }
434
435                 row[_columns.property_toggles_visible] = true;
436         }
437
438         row[_columns.region] = region;
439
440         region_row_map.insert(pair<boost::shared_ptr<ARDOUR::Region>, Gtk::TreeModel::RowReference>(region, TreeRowReference(_model, TreePath (row))) );
441
442         populate_row(region, (*row));
443 }
444
445 void
446 EditorRegions::remove_unused_regions ()
447 {
448         vector<string> choices;
449         string prompt;
450
451         if (!_session) {
452                 return;
453         }
454
455         prompt  = _("Do you really want to remove unused regions?"
456                     "\n(This is destructive and cannot be undone)");
457
458         choices.push_back (_("No, do nothing."));
459         choices.push_back (_("Yes, remove."));
460
461         Gtkmm2ext::Choice prompter (_("Remove unused regions"), prompt, choices);
462
463         if (prompter.run () == 1) {
464                 _no_redisplay = true;
465                 _session->cleanup_regions ();
466                 _no_redisplay = false;
467                 redisplay ();
468         }
469 }
470
471 void
472 EditorRegions::region_changed (boost::shared_ptr<Region> r, const PropertyChange& what_changed)
473 {
474         PropertyChange our_interests;
475
476         our_interests.add (ARDOUR::Properties::name);
477         our_interests.add (ARDOUR::Properties::position);
478         our_interests.add (ARDOUR::Properties::length);
479         our_interests.add (ARDOUR::Properties::start);
480         our_interests.add (ARDOUR::Properties::locked);
481         our_interests.add (ARDOUR::Properties::position_lock_style);
482         our_interests.add (ARDOUR::Properties::muted);
483         our_interests.add (ARDOUR::Properties::opaque);
484         our_interests.add (ARDOUR::Properties::fade_in);
485         our_interests.add (ARDOUR::Properties::fade_out);
486         our_interests.add (ARDOUR::Properties::fade_in_active);
487         our_interests.add (ARDOUR::Properties::fade_out_active);
488
489         if (what_changed.contains (our_interests)) {
490
491                 if (last_row != 0) {
492
493                         TreeModel::iterator j = _model->get_iter (last_row.get_path());
494                         boost::shared_ptr<Region> c = (*j)[_columns.region];
495
496                         if (c == r) {
497                                 populate_row (r, (*j));
498
499                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
500                                         redisplay ();
501                                 }
502
503                                 return;
504                         }
505                 }
506
507                 RegionRowMap::iterator it;
508
509                 it = region_row_map.find (r);
510
511                 if (it != region_row_map.end()){
512
513                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
514                         boost::shared_ptr<Region> c = (*j)[_columns.region];
515
516                         if (c == r) {
517                                 populate_row (r, (*j));
518
519                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
520                                         redisplay ();
521                                 }
522
523                                 return;
524                         }
525                 }
526         }
527
528         if (what_changed.contains (ARDOUR::Properties::hidden)) {
529                 redisplay ();
530         }
531 }
532
533 void
534 EditorRegions::selection_changed ()
535 {
536         if (ignore_region_list_selection_change) {
537                 return;
538         }
539
540         _editor->_region_selection_change_updates_region_list = false;
541
542         if (_display.get_selection()->count_selected_rows() > 0) {
543
544                 TreeIter iter;
545                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
546
547                 _editor->get_selection().clear_regions ();
548
549                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
550
551                         if ((iter = _model->get_iter (*i))) {
552
553                                 boost::shared_ptr<Region> region = (*iter)[_columns.region];
554
555                                 // they could have clicked on a row that is just a placeholder, like "Hidden"
556                                 // although that is not allowed by our selection filter. check it anyway
557                                 // since we need a region ptr.
558
559                                 if (region) {
560
561                                         _change_connection.block (true);
562                                         _editor->set_selected_regionview_from_region_list (region, Selection::Add);
563                                         _change_connection.block (false);
564                                 }
565                         }
566
567                 }
568         } else {
569                 _editor->get_selection().clear_regions ();
570         }
571
572         _editor->_region_selection_change_updates_region_list = true;
573 }
574
575 void
576 EditorRegions::set_selected (RegionSelection& regions)
577 {
578         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
579
580                 boost::shared_ptr<Region> r ((*i)->region());
581
582                 RegionRowMap::iterator it;
583
584                 it = region_row_map.find (r);
585
586                 if (it != region_row_map.end()){
587                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
588                         _display.get_selection()->select(*j);
589                 }
590         }
591 }
592
593 void
594 EditorRegions::redisplay ()
595 {
596         if (_no_redisplay || !_session) {
597                 return;
598         }
599
600         bool tree_expanded = false;
601
602         /* If the list was expanded prior to rebuilding, expand it again afterwards */
603         if (toggle_full_action()->get_active()) {
604                 tree_expanded = true;
605         }
606
607         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
608         _model->clear ();
609         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
610
611
612         region_row_map.clear();
613         parent_regions_sources_map.clear();
614
615         /* now add everything we have, via a temporary list used to help with sorting */
616
617         const RegionFactory::RegionMap& regions (RegionFactory::regions());
618
619         for (RegionFactory::RegionMap::const_iterator i = regions.begin(); i != regions.end(); ++i) {
620
621                 if ( i->second->whole_file()) {
622                         /* add automatic regions first so that children can find their parents as we add them */
623                         add_region (i->second);
624                         continue;
625                 }
626
627                 tmp_region_list.push_front (i->second);
628         }
629
630         for (list<boost::shared_ptr<Region> >::iterator r = tmp_region_list.begin(); r != tmp_region_list.end(); ++r) {
631                 add_region (*r);
632         }
633
634         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
635         _display.set_model (_model);
636
637         tmp_region_list.clear();
638
639         if (tree_expanded) {
640                 _display.expand_all();
641         }
642 }
643
644 void
645 EditorRegions::update_row (boost::shared_ptr<Region> region)
646 {
647         if (!region || !_session) {
648                 return;
649         }
650
651         RegionRowMap::iterator it;
652
653         it = region_row_map.find (region);
654
655         if (it != region_row_map.end()){
656
657                 TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
658                 populate_row(region, (*j));
659         }
660 }
661
662 void
663 EditorRegions::update_all_rows ()
664 {
665         if (!_session) {
666                 return;
667         }
668
669         RegionRowMap::iterator i;
670
671         for (i = region_row_map.begin(); i != region_row_map.end(); ++i) {
672
673                 TreeModel::iterator j = _model->get_iter ((*i).second.get_path());
674
675                 boost::shared_ptr<Region> region = (*j)[_columns.region];
676
677                 if (!region->automatic()) {
678                         populate_row(region, (*j));
679                 }
680         }
681 }
682
683 void
684 EditorRegions::format_position (framepos_t pos, char* buf, size_t bufsize, bool onoff)
685 {
686         Timecode::BBT_Time bbt;
687         Timecode::Time timecode;
688
689         if (pos < 0) {
690                 error << string_compose (_("EditorRegions::format_position: negative timecode position: %1"), pos) << endmsg;
691                 snprintf (buf, bufsize, "invalid");
692                 return;
693         }
694
695         switch (ARDOUR_UI::instance()->secondary_clock->mode ()) {
696         case AudioClock::BBT:
697                 _session->tempo_map().bbt_time (pos, bbt);
698                 if (onoff) {
699                         snprintf (buf, bufsize, "%03d|%02d|%04d" , bbt.bars, bbt.beats, bbt.ticks);
700                 } else {
701                         snprintf (buf, bufsize, "(%03d|%02d|%04d)" , bbt.bars, bbt.beats, bbt.ticks);
702                 }
703                 break;
704
705         case AudioClock::MinSec:
706                 framepos_t left;
707                 int hrs;
708                 int mins;
709                 float secs;
710
711                 left = pos;
712                 hrs = (int) floor (left / (_session->frame_rate() * 60.0f * 60.0f));
713                 left -= (framecnt_t) floor (hrs * _session->frame_rate() * 60.0f * 60.0f);
714                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
715                 left -= (framecnt_t) floor (mins * _session->frame_rate() * 60.0f);
716                 secs = left / (float) _session->frame_rate();
717                 if (onoff) {
718                         snprintf (buf, bufsize, "%02d:%02d:%06.3f", hrs, mins, secs);
719                 } else {
720                         snprintf (buf, bufsize, "(%02d:%02d:%06.3f)", hrs, mins, secs);
721                 }
722                 break;
723
724         case AudioClock::Frames:
725                 if (onoff) {
726                         snprintf (buf, bufsize, "%" PRId64, pos);
727                 } else {
728                         snprintf (buf, bufsize, "(%" PRId64 ")", pos);
729                 }
730                 break;
731
732         case AudioClock::Timecode:
733         default:
734                 _session->timecode_time (pos, timecode);
735                 if (onoff) {
736                         snprintf (buf, bufsize, "%02d:%02d:%02d:%02d", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
737                 } else {
738                         snprintf (buf, bufsize, "(%02d:%02d:%02d:%02d)", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
739                 }
740                 break;
741         }
742 }
743
744 void
745 EditorRegions::populate_row (boost::shared_ptr<Region> region, TreeModel::Row const &row)
746 {
747         boost::shared_ptr<AudioRegion> audioregion = boost::dynamic_pointer_cast<AudioRegion>(region);
748         //uint32_t used = _session->playlists->region_use_count (region);
749         /* Presently a region is only used once so let's save on the sequential scan to determine use count */
750         uint32_t used = 1;
751
752         populate_row_position (region, row, used);
753         populate_row_end (region, row, used);
754         populate_row_sync (region, row, used);
755         populate_row_fade_in (region, row, used, audioregion);
756         populate_row_fade_out (region, row, used, audioregion);
757         populate_row_locked (region, row, used);
758         populate_row_glued (region, row, used);
759         populate_row_muted (region, row, used);
760         populate_row_opaque (region, row, used);
761         populate_row_length (region, row);
762         populate_row_source (region, row);
763         populate_row_name (region, row);
764         populate_row_used (region, row, used);
765 }
766
767 #if 0
768         if (audioRegion && fades_in_seconds) {
769
770                 framepos_t left;
771                 int mins;
772                 int millisecs;
773
774                 left = audioRegion->fade_in()->back()->when;
775                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
776                 left -= (framepos_t) floor (mins * _session->frame_rate() * 60.0f);
777                 millisecs = (int) floor ((left * 1000.0f) / _session->frame_rate());
778
779                 if (audioRegion->fade_in()->back()->when >= _session->frame_rate()) {
780                         sprintf (fadein_str, "%01dM %01dmS", mins, millisecs);
781                 } else {
782                         sprintf (fadein_str, "%01dmS", millisecs);
783                 }
784
785                 left = audioRegion->fade_out()->back()->when;
786                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
787                 left -= (framepos_t) floor (mins * _session->frame_rate() * 60.0f);
788                 millisecs = (int) floor ((left * 1000.0f) / _session->frame_rate());
789
790                 if (audioRegion->fade_out()->back()->when >= _session->frame_rate()) {
791                         sprintf (fadeout_str, "%01dM %01dmS", mins, millisecs);
792                 } else {
793                         sprintf (fadeout_str, "%01dmS", millisecs);
794                 }
795         }
796 #endif
797
798 void
799 EditorRegions::populate_row_used (boost::shared_ptr<Region>, TreeModel::Row const& row, uint32_t used)
800 {
801         char buf[8];
802         snprintf (buf, sizeof (buf), "%4d" , used);
803         row[_columns.used] = buf;
804 }
805
806 void
807 EditorRegions::populate_row_length (boost::shared_ptr<Region> region, TreeModel::Row const &row)
808 {
809         char buf[16];
810         format_position (region->length(), buf, sizeof (buf));
811         row[_columns.length] = buf;
812 }
813
814 void
815 EditorRegions::populate_row_end (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
816 {
817         if (region->whole_file()) {
818                 row[_columns.end] = "";
819         } else if (used > 1) {
820                 row[_columns.end] = _("Mult.");
821         } else if (region->last_frame() >= region->first_frame()) {
822                 char buf[16];
823                 format_position (region->last_frame(), buf, sizeof (buf));
824                 row[_columns.end] = buf;
825         } else {
826                 row[_columns.end] = "empty";
827         }
828 }
829
830 void
831 EditorRegions::populate_row_position (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
832 {
833         if (region->whole_file()) {
834                 row[_columns.position] = "";
835         } else if (used > 1) {
836                 row[_columns.position] = _("Mult.");
837         } else {
838                 char buf[16];
839                 format_position (region->position(), buf, sizeof (buf));
840                 row[_columns.position] = buf;
841         }
842 }
843
844 void
845 EditorRegions::populate_row_sync (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
846 {
847         if (region->whole_file()) {
848                 row[_columns.sync] = "";
849         } else if (used > 1) {
850                 row[_columns.sync] = _("Mult."); /* translators: a short phrase for "multiple" as in "many" */
851         } else {
852                 if (region->sync_position() == region->position()) {
853                         row[_columns.sync] = _("Start");
854                 } else if (region->sync_position() == (region->last_frame())) {
855                         row[_columns.sync] = _("End");
856                 } else {
857                         char buf[16];
858                         format_position (region->sync_position(), buf, sizeof (buf));
859                         row[_columns.sync] = buf;
860                 }
861         }
862 }
863
864 void
865 EditorRegions::populate_row_fade_in (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
866 {
867         if (!audioregion || region->whole_file()) {
868                 row[_columns.fadein] = "";
869         } else {
870                 if (used > 1) {
871                         row[_columns.fadein] = _("Multiple");
872                 } else {
873                         char buf[32];
874                         format_position (audioregion->fade_in()->back()->when, buf, sizeof (buf), audioregion->fade_in_active());
875                         row[_columns.fadein] = buf;
876                 }
877         }
878 }
879
880 void
881 EditorRegions::populate_row_fade_out (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
882 {
883         if (!audioregion || region->whole_file()) {
884                 row[_columns.fadeout] = "";
885         } else {
886                 if (used > 1) {
887                         row[_columns.fadeout] = _("Multiple");
888                 } else {
889                         char buf[32];
890                         format_position (audioregion->fade_out()->back()->when, buf, sizeof (buf), audioregion->fade_out_active());
891                         row[_columns.fadeout] = buf;
892                 }
893         }
894 }
895
896 void
897 EditorRegions::populate_row_locked (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
898 {
899         if (region->whole_file()) {
900                 row[_columns.locked] = false;
901         } else if (used > 1) {
902                 row[_columns.locked] = false;
903         } else {
904                 row[_columns.locked] = region->locked();
905         }
906 }
907
908 void
909 EditorRegions::populate_row_glued (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
910 {
911         if (region->whole_file() || used > 1) {
912                 row[_columns.glued] = false;
913         } else {
914                 if (region->position_lock_style() == MusicTime) {
915                         row[_columns.glued] = true;
916                 } else {
917                         row[_columns.glued] = false;
918                 }
919         }
920 }
921
922 void
923 EditorRegions::populate_row_muted (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
924 {
925         if (region->whole_file() || used > 1) {
926                 row[_columns.muted] = false;
927         } else {
928                 row[_columns.muted] = region->muted();
929         }
930 }
931
932 void
933 EditorRegions::populate_row_opaque (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
934 {
935         if (region->whole_file() || used > 1) {
936                 row[_columns.opaque] = false;
937         } else {
938                 row[_columns.opaque] = region->opaque();
939         }
940 }
941
942 void
943 EditorRegions::populate_row_name (boost::shared_ptr<Region> region, TreeModel::Row const &row)
944 {
945         if (region->n_channels() > 1) {
946                 row[_columns.name] = string_compose("%1  [%2]", Gtkmm2ext::markup_escape_text (region->name()), region->n_channels());
947         } else {
948                 row[_columns.name] = Gtkmm2ext::markup_escape_text (region->name());
949         }
950 }
951
952 void
953 EditorRegions::populate_row_source (boost::shared_ptr<Region> region, TreeModel::Row const &row)
954 {
955         if (boost::dynamic_pointer_cast<SilentFileSource>(region->source())) {
956                 row[_columns.path] = _("MISSING ") + Gtkmm2ext::markup_escape_text (region->source()->name());
957         } else {
958                 row[_columns.path] = Gtkmm2ext::markup_escape_text (region->source()->name());
959         }
960 }
961
962 void
963 EditorRegions::toggle_show_auto_regions ()
964 {
965         _show_automatic_regions = toggle_show_auto_regions_action()->get_active();
966         redisplay ();
967 }
968
969 void
970 EditorRegions::toggle_full ()
971 {
972         set_full (toggle_full_action()->get_active ());
973 }
974
975 void
976 EditorRegions::set_full (bool f)
977 {
978         if (f) {
979                 _display.expand_all ();
980                 expanded = true;
981         } else {
982                 _display.collapse_all ();
983                 expanded = false;
984         }
985 }
986
987 void
988 EditorRegions::show_context_menu (int button, int time)
989 {
990         if (_menu == 0) {
991                 _menu = dynamic_cast<Menu*> (ActionManager::get_widget ("/RegionListMenu"));
992         }
993
994         if (_display.get_selection()->count_selected_rows() > 0) {
995                 ActionManager::set_sensitive (ActionManager::region_list_selection_sensitive_actions, true);
996         } else {
997                 ActionManager::set_sensitive (ActionManager::region_list_selection_sensitive_actions, false);
998         }
999
1000         /* Enable the "Show" option if any selected regions are hidden, and vice versa for "Hide" */
1001
1002         bool have_shown = false;
1003         bool have_hidden = false;
1004
1005         TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
1006         for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
1007                 TreeIter t = _model->get_iter (*i);
1008                 boost::shared_ptr<Region> r = (*t)[_columns.region];
1009                 if (r) {
1010                         if (r->hidden ()) {
1011                                 have_hidden = true;
1012                         } else {
1013                                 have_shown = true;
1014                         }
1015                 }
1016         }
1017
1018         hide_action()->set_sensitive (have_shown);
1019         show_action()->set_sensitive (have_hidden);
1020
1021         _menu->popup (button, time);
1022 }
1023
1024 bool
1025 EditorRegions::key_press (GdkEventKey* ev)
1026 {
1027         TreeViewColumn *col;
1028
1029         switch (ev->keyval) {
1030         case GDK_Tab:
1031         case GDK_ISO_Left_Tab:
1032
1033                 if (name_editable) {
1034                         name_editable->editing_done ();
1035                         name_editable = 0;
1036                 }
1037
1038                 col = _display.get_column (0); // select&focus on name column
1039
1040                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
1041                         treeview_select_previous (_display, _model, col);
1042                 } else {
1043                         treeview_select_next (_display, _model, col);
1044                 }
1045
1046                 return true;
1047                 break;
1048
1049         default:
1050                 break;
1051         }
1052
1053         return false;
1054 }
1055
1056 bool
1057 EditorRegions::button_press (GdkEventButton *ev)
1058 {
1059         boost::shared_ptr<Region> region;
1060         TreeIter iter;
1061         TreeModel::Path path;
1062         TreeViewColumn* column;
1063         int cellx;
1064         int celly;
1065
1066         if (_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
1067                 if ((iter = _model->get_iter (path))) {
1068                         region = (*iter)[_columns.region];
1069                 }
1070         }
1071
1072         if (Keyboard::is_context_menu_event (ev)) {
1073                 show_context_menu (ev->button, ev->time);
1074                 return false;
1075         }
1076
1077         if (region != 0 && Keyboard::is_button2_event (ev)) {
1078                 // start/stop audition
1079                 if (!Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1080                         _editor->consider_auditioning (region);
1081                 }
1082                 return true;
1083         }
1084
1085         return false;
1086 }
1087
1088 int
1089 EditorRegions::sorter (TreeModel::iterator a, TreeModel::iterator b)
1090 {
1091         int cmp = 0;
1092
1093         boost::shared_ptr<Region> r1 = (*a)[_columns.region];
1094         boost::shared_ptr<Region> r2 = (*b)[_columns.region];
1095
1096         /* handle rows without regions, like "Hidden" */
1097
1098         if (r1 == 0) {
1099                 return -1;
1100         }
1101
1102         if (r2 == 0) {
1103                 return 1;
1104         }
1105
1106         boost::shared_ptr<AudioRegion> region1 = boost::dynamic_pointer_cast<AudioRegion> (r1);
1107         boost::shared_ptr<AudioRegion> region2 = boost::dynamic_pointer_cast<AudioRegion> (r2);
1108
1109         if (region1 == 0 || region2 == 0) {
1110                 std::string s1;
1111                 std::string s2;
1112                 switch (_sort_type) {
1113                 case ByName:
1114                         s1 = (*a)[_columns.name];
1115                         s2 = (*b)[_columns.name];
1116                         return (s1.compare (s2));
1117                 default:
1118                         return 0;
1119                 }
1120         }
1121
1122         switch (_sort_type) {
1123         case ByName:
1124                 cmp = region1->name().compare(region2->name());
1125                 break;
1126
1127         case ByLength:
1128                 cmp = region1->length() - region2->length();
1129                 break;
1130
1131         case ByPosition:
1132                 cmp = region1->position() - region2->position();
1133                 break;
1134
1135         case ByTimestamp:
1136                 cmp = region1->source()->timestamp() - region2->source()->timestamp();
1137                 break;
1138
1139         case ByStartInFile:
1140                 cmp = region1->start() - region2->start();
1141                 break;
1142
1143         case ByEndInFile:
1144                 // cerr << "Compare " << (region1->start() + region1->length()) << " and " << (region2->start() + region2->length()) << endl;
1145                 cmp = (region1->start() + region1->length()) - (region2->start() + region2->length());
1146                 break;
1147
1148         case BySourceFileName:
1149                 cmp = region1->source()->name().compare(region2->source()->name());
1150                 break;
1151
1152         case BySourceFileLength:
1153                 cmp = region1->source_length(0) - region2->source_length(0);
1154                 break;
1155
1156         case BySourceFileCreationDate:
1157                 cmp = region1->source()->timestamp() - region2->source()->timestamp();
1158                 break;
1159
1160         case BySourceFileFS:
1161                 if (region1->source()->name() == region2->source()->name()) {
1162                         cmp = region1->name().compare(region2->name());
1163                 } else {
1164                         cmp = region1->source()->name().compare(region2->source()->name());
1165                 }
1166                 break;
1167         }
1168
1169         // cerr << "Comparison on " << enum_2_string (_sort_type) << " gives " << cmp << endl;
1170
1171         if (cmp < 0) {
1172                 return -1;
1173         } else if (cmp > 0) {
1174                 return 1;
1175         } else {
1176                 return 0;
1177         }
1178 }
1179
1180 void
1181 EditorRegions::reset_sort_type (RegionListSortType type, bool force)
1182 {
1183         if (type != _sort_type || force) {
1184                 _sort_type = type;
1185                 _model->set_sort_func (0, (sigc::mem_fun (*this, &EditorRegions::sorter)));
1186         }
1187 }
1188
1189 void
1190 EditorRegions::reset_sort_direction (bool up)
1191 {
1192         _model->set_sort_column (0, up ? SORT_ASCENDING : SORT_DESCENDING);
1193 }
1194
1195 void
1196 EditorRegions::selection_mapover (sigc::slot<void,boost::shared_ptr<Region> > sl)
1197 {
1198         Glib::RefPtr<TreeSelection> selection = _display.get_selection();
1199         TreeView::Selection::ListHandle_Path rows = selection->get_selected_rows ();
1200         TreeView::Selection::ListHandle_Path::iterator i = rows.begin();
1201
1202         if (selection->count_selected_rows() == 0 || _session == 0) {
1203                 return;
1204         }
1205
1206         for (; i != rows.end(); ++i) {
1207                 TreeIter iter;
1208
1209                 if ((iter = _model->get_iter (*i))) {
1210
1211                         /* some rows don't have a region associated with them, but can still be
1212                            selected (XXX maybe prevent them from being selected)
1213                         */
1214
1215                         boost::shared_ptr<Region> r = (*iter)[_columns.region];
1216
1217                         if (r) {
1218                                 sl (r);
1219                         }
1220                 }
1221         }
1222 }
1223
1224
1225 void
1226 EditorRegions::drag_data_received (const RefPtr<Gdk::DragContext>& context,
1227                                    int x, int y,
1228                                    const SelectionData& data,
1229                                    guint info, guint time)
1230 {
1231         vector<string> paths;
1232
1233         if (data.get_target() == "GTK_TREE_MODEL_ROW") {
1234                 /* something is being dragged over the region list */
1235                 _editor->_drags->abort ();
1236                 _display.on_drag_data_received (context, x, y, data, info, time);
1237                 return;
1238         }
1239
1240         if (_editor->convert_drop_to_paths (paths, context, x, y, data, info, time) == 0) {
1241                 framepos_t pos = 0;
1242                 bool copy = ((context->get_actions() & (Gdk::ACTION_COPY | Gdk::ACTION_LINK | Gdk::ACTION_MOVE)) == Gdk::ACTION_COPY);
1243
1244                 if (UIConfiguration::instance().get_only_copy_imported_files() || copy) {
1245                         _editor->do_import (paths, Editing::ImportDistinctFiles, Editing::ImportAsRegion, SrcBest, pos);
1246                 } else {
1247                         _editor->do_embed (paths, Editing::ImportDistinctFiles, ImportAsRegion, pos);
1248                 }
1249                 context->drag_finish (true, false, time);
1250         }
1251 }
1252
1253 bool
1254 EditorRegions::selection_filter (const RefPtr<TreeModel>& model, const TreeModel::Path& path, bool already_selected)
1255 {
1256         /* not possible to select rows that do not represent regions, like "Hidden" */
1257
1258         if (already_selected) {
1259                 /* deselecting anything is OK with us */
1260                 return true;
1261         }
1262
1263         TreeModel::iterator iter = model->get_iter (path);
1264
1265         if (iter) {
1266                 boost::shared_ptr<Region> r =(*iter)[_columns.region];
1267                 if (!r) {
1268                         return false;
1269                 }
1270         }
1271
1272         return true;
1273 }
1274
1275 void
1276 EditorRegions::name_editing_started (CellEditable* ce, const Glib::ustring& path)
1277 {
1278         name_editable = ce;
1279
1280         /* give it a special name */
1281
1282         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
1283
1284         if (e) {
1285                 e->set_name (X_("RegionNameEditorEntry"));
1286
1287                 TreeIter iter;
1288                 if ((iter = _model->get_iter (path))) {
1289                         boost::shared_ptr<Region> region = (*iter)[_columns.region];
1290
1291                         if(region) {
1292                                 e->set_text(region->name());
1293                         }
1294                 }
1295         }
1296 }
1297
1298 void
1299 EditorRegions::name_edit (const std::string& path, const std::string& new_text)
1300 {
1301         name_editable = 0;
1302
1303         boost::shared_ptr<Region> region;
1304         TreeIter row_iter;
1305
1306         if ((row_iter = _model->get_iter (path))) {
1307                 region = (*row_iter)[_columns.region];
1308                 (*row_iter)[_columns.name] = new_text;
1309         }
1310
1311         /* now mapover everything */
1312
1313         if (region) {
1314                 vector<RegionView*> equivalents;
1315                 _editor->get_regions_corresponding_to (region, equivalents, false);
1316
1317                 for (vector<RegionView*>::iterator i = equivalents.begin(); i != equivalents.end(); ++i) {
1318                         if (new_text != (*i)->region()->name()) {
1319                                 (*i)->region()->set_name (new_text);
1320                         }
1321                 }
1322
1323                 populate_row_name (region, (*row_iter));
1324         }
1325 }
1326
1327 /** @return Region that has been dragged out of the list, or 0 */
1328 boost::shared_ptr<Region>
1329 EditorRegions::get_dragged_region ()
1330 {
1331         list<boost::shared_ptr<Region> > regions;
1332         TreeView* source;
1333         _display.get_object_drag_data (regions, &source);
1334
1335         if (regions.empty()) {
1336                 return boost::shared_ptr<Region> ();
1337         }
1338
1339         assert (regions.size() == 1);
1340         return regions.front ();
1341 }
1342
1343 void
1344 EditorRegions::clear ()
1345 {
1346         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1347         _model->clear ();
1348         _display.set_model (_model);
1349
1350         /* Clean up the maps */
1351         region_row_map.clear();
1352         parent_regions_sources_map.clear();
1353 }
1354
1355 boost::shared_ptr<Region>
1356 EditorRegions::get_single_selection ()
1357 {
1358         Glib::RefPtr<TreeSelection> selected = _display.get_selection();
1359
1360         if (selected->count_selected_rows() != 1) {
1361                 return boost::shared_ptr<Region> ();
1362         }
1363
1364         TreeView::Selection::ListHandle_Path rows = selected->get_selected_rows ();
1365
1366         /* only one row selected, so rows.begin() is it */
1367
1368         TreeIter iter = _model->get_iter (*rows.begin());
1369
1370         if (!iter) {
1371                 return boost::shared_ptr<Region> ();
1372         }
1373
1374         return (*iter)[_columns.region];
1375 }
1376
1377 void
1378 EditorRegions::freeze_tree_model (){
1379
1380         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
1381         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
1382
1383 }
1384
1385 void
1386 EditorRegions::thaw_tree_model (){
1387
1388         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
1389         _display.set_model (_model);
1390
1391         if (toggle_full_action()->get_active()) {
1392                 _display.expand_all();
1393         }
1394 }
1395
1396 void
1397 EditorRegions::locked_changed (std::string const & path)
1398 {
1399         TreeIter i = _model->get_iter (path);
1400         if (i) {
1401                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1402                 if (region) {
1403                         region->set_locked (!(*i)[_columns.locked]);
1404                 }
1405         }
1406 }
1407
1408 void
1409 EditorRegions::glued_changed (std::string const & path)
1410 {
1411         TreeIter i = _model->get_iter (path);
1412         if (i) {
1413                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1414                 if (region) {
1415                         /* `glued' means MusicTime, and we're toggling here */
1416                         region->set_position_lock_style ((*i)[_columns.glued] ? AudioTime : MusicTime);
1417                 }
1418         }
1419
1420 }
1421
1422 void
1423 EditorRegions::muted_changed (std::string const & path)
1424 {
1425         TreeIter i = _model->get_iter (path);
1426         if (i) {
1427                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1428                 if (region) {
1429                         region->set_muted (!(*i)[_columns.muted]);
1430                 }
1431         }
1432
1433 }
1434
1435 void
1436 EditorRegions::opaque_changed (std::string const & path)
1437 {
1438         TreeIter i = _model->get_iter (path);
1439         if (i) {
1440                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1441                 if (region) {
1442                         region->set_opaque (!(*i)[_columns.opaque]);
1443                 }
1444         }
1445
1446 }
1447
1448 XMLNode &
1449 EditorRegions::get_state () const
1450 {
1451         XMLNode* node = new XMLNode (X_("RegionList"));
1452
1453         node->add_property (X_("sort-type"), enum_2_string (_sort_type));
1454
1455         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1456         bool const ascending = RefPtr<RadioAction>::cast_dynamic(act)->get_active ();
1457         node->add_property (X_("sort-ascending"), ascending ? "yes" : "no");
1458         node->add_property (X_("show-all"), toggle_full_action()->get_active() ? "yes" : "no");
1459         node->add_property (X_("show-automatic-regions"), _show_automatic_regions ? "yes" : "no");
1460
1461         return *node;
1462 }
1463
1464 void
1465 EditorRegions::set_state (const XMLNode & node)
1466 {
1467         bool changed = false;
1468
1469         if (node.name() != X_("RegionList")) {
1470                 return;
1471         }
1472
1473         XMLProperty const * p = node.property (X_("sort-type"));
1474
1475         if (p) {
1476                 Editing::RegionListSortType const t = static_cast<Editing::RegionListSortType> (string_2_enum (p->value(), _sort_type));
1477
1478                 if (_sort_type != t) {
1479                         changed = true;
1480                 }
1481
1482                 reset_sort_type (t, true);
1483                 RefPtr<RadioAction> ract = sort_type_action (t);
1484                 ract->set_active ();
1485         }
1486
1487         p = node.property (X_("sort-ascending"));
1488
1489         if (p) {
1490                 bool const yn = string_is_affirmative (p->value ());
1491                 SortType old_sort_type;
1492                 int old_sort_column;
1493
1494                 _model->get_sort_column_id (old_sort_column, old_sort_type);
1495
1496                 if (old_sort_type != (yn ? SORT_ASCENDING : SORT_DESCENDING)) {
1497                         changed = true;
1498                 }
1499
1500                 reset_sort_direction (yn);
1501                 RefPtr<Action> act;
1502
1503                 if (yn) {
1504                         act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1505                 } else {
1506                         act = ActionManager::get_action (X_("RegionList"), X_("SortDescending"));
1507                 }
1508
1509                 RefPtr<RadioAction>::cast_dynamic(act)->set_active ();
1510         }
1511
1512         p = node.property (X_("show-all"));
1513         if (p) {
1514                 bool const yn = string_is_affirmative (p->value ());
1515
1516                 if (expanded != yn) {
1517                         changed = true;
1518                 }
1519
1520                 set_full (yn);
1521                 toggle_full_action()->set_active (yn);
1522         }
1523
1524         p = node.property (X_("show-automatic-regions"));
1525         if (p) {
1526                 bool const yn = string_is_affirmative (p->value ());
1527
1528                 if (yn != _show_automatic_regions) {
1529                         _show_automatic_regions = yn;
1530                         toggle_show_auto_regions_action()->set_active (yn);
1531                         changed = true;
1532                 }
1533         }
1534
1535         if (changed) {
1536                 redisplay ();
1537         }
1538 }
1539
1540 RefPtr<RadioAction>
1541 EditorRegions::sort_type_action (Editing::RegionListSortType t) const
1542 {
1543         const char* action = 0;
1544
1545         switch (t) {
1546         case Editing::ByName:
1547                 action = X_("SortByRegionName");
1548                 break;
1549         case Editing::ByLength:
1550                 action = X_("SortByRegionLength");
1551                 break;
1552         case Editing::ByPosition:
1553                 action = X_("SortByRegionPosition");
1554                 break;
1555         case Editing::ByTimestamp:
1556                 action = X_("SortByRegionTimestamp");
1557                 break;
1558         case Editing::ByStartInFile:
1559                 action = X_("SortByRegionStartinFile");
1560                 break;
1561         case Editing::ByEndInFile:
1562                 action = X_("SortByRegionEndinFile");
1563                 break;
1564         case Editing::BySourceFileName:
1565                 action = X_("SortBySourceFileName");
1566                 break;
1567         case Editing::BySourceFileLength:
1568                 action = X_("SortBySourceFileLength");
1569                 break;
1570         case Editing::BySourceFileCreationDate:
1571                 action = X_("SortBySourceFileCreationDate");
1572                 break;
1573         case Editing::BySourceFileFS:
1574                 action = X_("SortBySourceFilesystem");
1575                 break;
1576         default:
1577                 fatal << string_compose (_("programming error: %1: %2"), "EditorRegions: impossible sort type", (int) t) << endmsg;
1578                 abort(); /*NOTREACHED*/
1579         }
1580
1581         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), action);
1582         assert (act);
1583
1584         return RefPtr<RadioAction>::cast_dynamic (act);
1585 }
1586
1587 RefPtr<Action>
1588 EditorRegions::hide_action () const
1589 {
1590         return ActionManager::get_action (X_("RegionList"), X_("rlHide"));
1591
1592 }
1593
1594 RefPtr<Action>
1595 EditorRegions::show_action () const
1596 {
1597         return ActionManager::get_action (X_("RegionList"), X_("rlShow"));
1598 }
1599
1600 RefPtr<Action>
1601 EditorRegions::remove_unused_regions_action () const
1602 {
1603         return ActionManager::get_action (X_("RegionList"), X_("removeUnusedRegions"));
1604 }
1605
1606 RefPtr<ToggleAction>
1607 EditorRegions::toggle_full_action () const
1608 {
1609         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAll"));
1610         assert (act);
1611         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1612 }
1613
1614 RefPtr<ToggleAction>
1615 EditorRegions::toggle_show_auto_regions_action () const
1616 {
1617         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAuto"));
1618         assert (act);
1619         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1620 }