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