cfc56a30823c0dc7d8bf8dbc65dd2306b6990cc4
[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/region_factory.h"
32 #include "ardour/session.h"
33 #include "ardour/session_playlists.h"
34 #include "ardour/silentfilesource.h"
35 #include "ardour/profile.h"
36
37 #include "gtkmm2ext/choice.h"
38 #include "gtkmm2ext/treeutils.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
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57 using namespace Gtk;
58 using namespace Glib;
59 using namespace Editing;
60 using Gtkmm2ext::Keyboard;
61
62 struct ColumnInfo {
63     int         index;
64     const char* label;
65     const char* tooltip;
66 };
67
68 EditorRegions::EditorRegions (Editor* e)
69         : EditorComponent (e)
70         , old_focus (0)
71         , name_editable (0)
72         , _menu (0)
73         , _show_automatic_regions (true)
74         , ignore_region_list_selection_change (false)
75         , ignore_selected_region_change (false)
76         , _no_redisplay (false)
77         , _sort_type ((Editing::RegionListSortType) 0)
78         , expanded (false)
79 {
80         _display.set_size_request (100, -1);
81         _display.set_name ("RegionListDisplay");
82         _display.set_rules_hint (true);
83
84         /* Try to prevent single mouse presses from initiating edits.
85            This relies on a hack in gtktreeview.c:gtk_treeview_button_press()
86         */
87         _display.set_data ("mouse-edits-require-mod1", (gpointer) 0x1);
88
89         _model = TreeStore::create (_columns);
90         _model->set_sort_func (0, sigc::mem_fun (*this, &EditorRegions::sorter));
91         _model->set_sort_column (0, SORT_ASCENDING);
92
93         _display.set_model (_model);
94
95         _display.append_column ("", _columns.name);
96         _display.append_column ("", _columns.position);
97         _display.append_column ("", _columns.end);
98         _display.append_column ("", _columns.length);
99         _display.append_column ("", _columns.sync);
100         _display.append_column ("", _columns.fadein);
101         _display.append_column ("", _columns.fadeout);
102         _display.append_column ("", _columns.locked);
103         _display.append_column ("", _columns.glued);
104         _display.append_column ("", _columns.muted);
105         _display.append_column ("", _columns.opaque);
106
107         TreeViewColumn* col;
108         Gtk::Label* l;
109
110         ColumnInfo ci[] = {
111                 { 0, _("Region"), _("Region name, with number of channels in []'s") },
112                 { 1, _("Position"),  _("Length of the region") },
113                 { 2, _("End"),  _("Length of the region") },
114                 { 3, _("End"),  _("Length of the region") },
115                 { 4, _("Sync"),  _("Position of region sync point, relative to start of the region") },
116                 { 5, _("Sync"),  _("Region fade-in enabled?") },
117                 { 6, _("Fade In"),  _("Region fade-out enabled?") },
118                 { 7, _("L"),  _("Region position locked?") },
119                 { 8, _("G"),  _("Region position glued to Bars|Beats time?") },
120                 { 9, _("M"),  _("Region muted?") },
121                 { 10, _("O"),  _("Region opaque (blocks regions below it from being heard)?") },
122                 { -1, 0, 0 }
123         };
124         
125         for (int i = 0; ci[i].index >= 0; ++i) {
126                 col = _display.get_column (ci[i].index);
127                 l = manage (new Label (ci[i].label));
128                 ARDOUR_UI::instance()->set_tip (*l, ci[i].tooltip);
129                 col->set_widget (*l);
130                 l->show ();
131         }
132
133         _display.set_headers_visible (true);
134         //_display.set_grid_lines (TREE_VIEW_GRID_LINES_BOTH);
135
136         /* show path as the row tooltip */
137         _display.set_tooltip_column (14); /* path */
138
139         CellRendererText* region_name_cell = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (0));
140         region_name_cell->property_editable() = true;
141         region_name_cell->signal_edited().connect (sigc::mem_fun (*this, &EditorRegions::name_edit));
142         region_name_cell->signal_editing_started().connect (sigc::mem_fun (*this, &EditorRegions::name_editing_started));
143
144         _display.get_selection()->set_select_function (sigc::mem_fun (*this, &EditorRegions::selection_filter));
145
146         TreeViewColumn* tv_col = _display.get_column(0);
147         tv_col->set_resizable (true);
148         CellRendererText* renderer = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (0));
149         tv_col->add_attribute(renderer->property_text(), _columns.name);
150         tv_col->add_attribute(renderer->property_foreground_gdk(), _columns.color_);
151
152         CellRendererToggle* locked_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (7));
153         locked_cell->property_activatable() = true;
154         locked_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::locked_changed));
155
156         TreeViewColumn* locked_col = _display.get_column (7);
157         locked_col->add_attribute (locked_cell->property_visible(), _columns.property_toggles_visible);
158
159         CellRendererToggle* glued_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (8));
160         glued_cell->property_activatable() = true;
161         glued_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::glued_changed));
162
163         TreeViewColumn* glued_col = _display.get_column (8);
164         glued_col->add_attribute (glued_cell->property_visible(), _columns.property_toggles_visible);
165
166         CellRendererToggle* muted_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (9));
167         muted_cell->property_activatable() = true;
168         muted_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::muted_changed));
169
170         TreeViewColumn* muted_col = _display.get_column (9);
171         muted_col->add_attribute (muted_cell->property_visible(), _columns.property_toggles_visible);
172
173         CellRendererToggle* opaque_cell = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (10));
174         opaque_cell->property_activatable() = true;
175         opaque_cell->signal_toggled().connect (sigc::mem_fun (*this, &EditorRegions::opaque_changed));
176
177         TreeViewColumn* opaque_col = _display.get_column (10);
178         opaque_col->add_attribute (opaque_cell->property_visible(), _columns.property_toggles_visible);
179
180         _display.get_selection()->set_mode (SELECTION_MULTIPLE);
181         _display.add_object_drag (_columns.region.index(), "regions");
182
183
184         /* only the first column (Region name) is resizable */
185
186         for (int i = 1; ; ++i) {
187                 TreeViewColumn* col = _display.get_column (i);
188                 if (!col) {
189                         break;
190                 } 
191                 col->set_resizable (false);
192         }
193
194         /* setup DnD handling */
195
196         list<TargetEntry> region_list_target_table;
197
198         region_list_target_table.push_back (TargetEntry ("text/plain"));
199         region_list_target_table.push_back (TargetEntry ("text/uri-list"));
200         region_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
201
202         _display.add_drop_targets (region_list_target_table);
203         _display.signal_drag_data_received().connect (sigc::mem_fun(*this, &EditorRegions::drag_data_received));
204
205         _scroller.add (_display);
206         _scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
207
208         _display.signal_button_press_event().connect (sigc::mem_fun(*this, &EditorRegions::button_press), false);
209         _change_connection = _display.get_selection()->signal_changed().connect (sigc::mem_fun(*this, &EditorRegions::selection_changed));
210
211         _scroller.signal_key_press_event().connect (sigc::mem_fun(*this, &EditorRegions::key_press), false);
212         _scroller.signal_focus_in_event().connect (sigc::mem_fun (*this, &EditorRegions::focus_in), false);
213         _scroller.signal_focus_out_event().connect (sigc::mem_fun (*this, &EditorRegions::focus_out));
214
215         _display.signal_enter_notify_event().connect (sigc::mem_fun (*this, &EditorRegions::enter_notify), false);
216         _display.signal_leave_notify_event().connect (sigc::mem_fun (*this, &EditorRegions::leave_notify), false);
217
218         // _display.signal_popup_menu().connect (sigc::bind (sigc::mem_fun (*this, &Editor::show__display_context_menu), 1, 0));
219
220         //ARDOUR_UI::instance()->secondary_clock.mode_changed.connect (sigc::mem_fun(*this, &Editor::redisplay_regions));
221         ARDOUR_UI::instance()->secondary_clock->mode_changed.connect (sigc::mem_fun(*this, &EditorRegions::update_all_rows));
222         ARDOUR::Region::RegionPropertyChanged.connect (region_property_connection, MISSING_INVALIDATOR, ui_bind (&EditorRegions::region_changed, this, _1, _2), gui_context());
223         ARDOUR::RegionFactory::CheckNewRegion.connect (check_new_region_connection, MISSING_INVALIDATOR, ui_bind (&EditorRegions::add_region, this, _1), gui_context());
224
225         e->EditorFreeze.connect (editor_freeze_connection, MISSING_INVALIDATOR, ui_bind (&EditorRegions::freeze_tree_model, this), gui_context());
226         e->EditorThaw.connect (editor_thaw_connection, MISSING_INVALIDATOR, ui_bind (&EditorRegions::thaw_tree_model, this), gui_context());
227 }
228
229 bool
230 EditorRegions::focus_in (GdkEventFocus*)
231 {
232         Window* win = dynamic_cast<Window*> (_scroller.get_toplevel ());
233
234         if (win) {
235                 old_focus = win->get_focus ();
236         } else {
237                 old_focus = 0;
238         }
239
240         name_editable = 0;
241
242         /* try to do nothing on focus in (doesn't work, hence selection_count nonsense) */
243         return true;
244 }
245
246 bool
247 EditorRegions::focus_out (GdkEventFocus*)
248 {
249         if (old_focus) {
250                 old_focus->grab_focus ();
251                 old_focus = 0;
252         }
253
254         name_editable = 0;
255
256         return false;
257 }
258
259 bool
260 EditorRegions::enter_notify (GdkEventCrossing*)
261 {
262         if (name_editable) {
263                 return true;
264         }
265
266         /* arm counter so that ::selection_filter() will deny selecting anything for the
267            next two attempts to change selection status.
268         */
269         _scroller.grab_focus ();
270         Keyboard::magic_widget_grab_focus ();
271         return false;
272 }
273
274 bool
275 EditorRegions::leave_notify (GdkEventCrossing*)
276 {
277         if (old_focus) {
278                 old_focus->grab_focus ();
279                 old_focus = 0;
280         }
281
282         Keyboard::magic_widget_drop_focus ();
283         return false;
284 }
285
286 void
287 EditorRegions::set_session (ARDOUR::Session* s)
288 {
289         SessionHandlePtr::set_session (s);
290         redisplay ();
291 }
292
293 void
294 EditorRegions::add_region (boost::shared_ptr<Region> region)
295 {
296         if (!region || !_session) {
297                 return;
298         }
299
300         string str;
301         TreeModel::Row row;
302         Gdk::Color c;
303         bool missing_source = boost::dynamic_pointer_cast<SilentFileSource>(region->source());
304
305         if (!_show_automatic_regions && region->automatic()) {
306                 return;
307         }
308
309         if (region->hidden()) {
310
311                 TreeModel::iterator iter = _model->get_iter ("0");
312                 TreeModel::Row parent;
313                 TreeModel::Row child;
314
315                 if (!iter) {
316                         parent = *(_model->append());
317                         parent[_columns.name] = _("Hidden");
318                         boost::shared_ptr<Region> proxy = parent[_columns.region];
319                         proxy.reset ();
320                 } else {
321                         string s = (*iter)[_columns.name];
322                         if (s != _("Hidden")) {
323                                 parent = *(_model->insert(iter));
324                                 parent[_columns.name] = _("Hidden");
325                                 boost::shared_ptr<Region> proxy = parent[_columns.region];
326                                 proxy.reset ();
327                         } else {
328                                 parent = *iter;
329                         }
330                 }
331
332                 row = *(_model->append (parent.children()));
333
334         } else if (region->whole_file()) {
335
336                 TreeModel::iterator i;
337                 TreeModel::Children rows = _model->children();
338
339                 for (i = rows.begin(); i != rows.end(); ++i) {
340                         boost::shared_ptr<Region> rr = (*i)[_columns.region];
341
342                         if (rr && region->region_list_equivalent (rr)) {
343                                 return;
344                         }
345                 }
346
347                 row = *(_model->append());
348
349                 if (missing_source) {
350                         c.set_rgb(65535,0,0);     // FIXME: error color from style
351
352                 } else if (region->automatic()){
353                         c.set_rgb(0,65535,0);     // FIXME: error color from style
354
355                 } else {
356                         set_color(c, rgba_from_style ("RegionListWholeFile", 0xff, 0, 0, 0, "fg", Gtk::STATE_NORMAL, false ));
357
358                 }
359
360                 row[_columns.color_] = c;
361
362                 if (region->source()->name()[0] == '/') { // external file
363
364                         if (region->whole_file()) {
365
366                                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(region->source());
367                                 str = ".../";
368
369                                 if (afs) {
370                                         str = region_name_from_path (afs->path(), region->n_channels() > 1);
371                                 } else {
372                                         str += region->source()->name();
373                                 }
374
375                         } else {
376                                 str = region->name();
377                         }
378
379                 } else {
380                         str = region->name();
381                 }
382
383                 if (region->n_channels() > 1) {
384                         std::stringstream foo;
385                         foo << region->n_channels ();
386                         str += " [";
387                         str += foo.str();
388                         str += "]";
389                 }
390
391                 row[_columns.name] = str;
392                 row[_columns.region] = region;
393                 row[_columns.property_toggles_visible] = false;
394
395                 if (missing_source) {
396                         row[_columns.path] = _("(MISSING) ") + region->source()->name();
397
398                 } else {
399                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource>(region->source());
400                         if (fs) {
401                                 row[_columns.path] = fs->path();
402                         } else {
403                                 row[_columns.path] = region->source()->name();
404                         }
405                 }
406
407                 region_row_map.insert(pair<boost::shared_ptr<ARDOUR::Region>, Gtk::TreeModel::RowReference>(region, TreeRowReference(_model, TreePath (row))) );
408                 parent_regions_sources_map.insert(pair<string, Gtk::TreeModel::RowReference>(region->source_string(), TreeRowReference(_model, TreePath (row))) );
409
410                 return;
411
412         } else {
413                 // find parent node, add as new child
414                 TreeModel::iterator i;
415
416                 boost::unordered_map<string, Gtk::TreeModel::RowReference>::iterator it;
417
418                 it = parent_regions_sources_map.find (region->source_string());
419
420                 if (it != parent_regions_sources_map.end()){
421
422                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
423
424                         TreeModel::iterator ii;
425                         TreeModel::Children subrows = (*j).children();
426
427                         /* XXXX: should we be accounting for all regions? */
428                         /*
429                         for (ii = subrows.begin(); ii != subrows.end(); ++ii) {
430                                 boost::shared_ptr<Region> rr = (*ii)[_columns.region];
431
432                                 if (region->region_list_equivalent (rr)) {
433                                         return;
434                                 }
435                         }
436                         */
437
438                         row = *(_model->insert (subrows.end()));
439                         
440                 } else {
441                         row = *(_model->append());
442                 }
443
444                 row[_columns.property_toggles_visible] = true;
445         }
446
447         row[_columns.region] = region;
448
449         region_row_map.insert(pair<boost::shared_ptr<ARDOUR::Region>, Gtk::TreeModel::RowReference>(region, TreeRowReference(_model, TreePath (row))) );
450
451         populate_row(region, (*row));
452 }
453
454 void
455 EditorRegions::remove_unused_regions ()
456 {
457         vector<string> choices;
458         string prompt;
459
460         if (!_session) {
461                 return;
462         }
463
464         prompt  = _("Do you really want to remove unused regions?"
465                     "\n(This is destructive and cannot be undone)");
466
467         choices.push_back (_("No, do nothing."));
468         choices.push_back (_("Yes, remove."));
469
470         Gtkmm2ext::Choice prompter (_("Remove unused regions"), prompt, choices);
471
472         if (prompter.run () == 1) {
473                 _no_redisplay = true;
474                 _session->cleanup_regions ();
475                 _no_redisplay = false;
476                 redisplay ();
477         }
478 }
479
480 void
481 EditorRegions::region_changed (boost::shared_ptr<Region> r, const PropertyChange& what_changed)
482 {
483         PropertyChange our_interests;
484
485         our_interests.add (ARDOUR::Properties::name);
486         our_interests.add (ARDOUR::Properties::position);
487         our_interests.add (ARDOUR::Properties::length);
488         our_interests.add (ARDOUR::Properties::start);
489         our_interests.add (ARDOUR::Properties::locked);
490         our_interests.add (ARDOUR::Properties::position_lock_style);
491         our_interests.add (ARDOUR::Properties::muted);
492         our_interests.add (ARDOUR::Properties::opaque);
493         our_interests.add (ARDOUR::Properties::fade_in);
494         our_interests.add (ARDOUR::Properties::fade_out);
495
496         if (what_changed.contains (our_interests)) {
497
498                 if (last_row != 0) {
499
500                         TreeModel::iterator j = _model->get_iter (last_row.get_path());
501                         boost::shared_ptr<Region> c = (*j)[_columns.region];
502
503                         if (c == r) {
504                                 populate_row (r, (*j));
505
506                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
507                                         redisplay ();
508                                 }
509
510                                 return;
511                         }
512                 }
513
514                 RegionRowMap::iterator it;
515
516                 it = region_row_map.find (r);
517
518                 if (it != region_row_map.end()){
519
520                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
521                         boost::shared_ptr<Region> c = (*j)[_columns.region];
522
523                         if (c == r) {
524                                 populate_row (r, (*j));
525
526                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
527                                         redisplay ();
528                                 }
529
530                                 return;
531                         }
532                 }
533         }
534
535         if (what_changed.contains (ARDOUR::Properties::hidden)) {
536                 redisplay ();
537         }
538 }
539
540 void
541 EditorRegions::selection_changed ()
542 {
543         if (ignore_region_list_selection_change) {
544                 return;
545         }
546
547         _editor->_region_selection_change_updates_region_list = false;
548
549         if (_display.get_selection()->count_selected_rows() > 0) {
550
551                 TreeIter iter;
552                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
553
554                 _editor->get_selection().clear_regions ();
555
556                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
557
558                         if (iter = _model->get_iter (*i)) {
559                                 boost::shared_ptr<Region> region = (*iter)[_columns.region];
560
561                                 // they could have clicked on a row that is just a placeholder, like "Hidden"
562                                 // although that is not allowed by our selection filter. check it anyway
563                                 // since we need a region ptr.
564
565                                 if (region) {
566
567                                         if (region->automatic()) {
568
569                                                 _display.get_selection()->unselect(*i);
570
571                                         } else {
572                                                 _change_connection.block (true);
573                                                 _editor->set_selected_regionview_from_region_list (region, Selection::Add);
574
575                                                 _change_connection.block (false);
576                                         }
577                                 }
578                         }
579                 }
580         } else {
581                 _editor->get_selection().clear_regions ();
582         }
583
584         _editor->_region_selection_change_updates_region_list = true;
585 }
586
587 void
588 EditorRegions::set_selected (RegionSelection& regions)
589 {
590         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
591
592                 boost::shared_ptr<Region> r ((*i)->region());
593
594                 RegionRowMap::iterator it;
595
596                 it = region_row_map.find (r);
597
598                 if (it != region_row_map.end()){
599                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
600                         _display.get_selection()->select(*j);
601                 }
602         }
603 }
604
605 void
606 EditorRegions::redisplay ()
607 {
608         if (_no_redisplay || !_session) {
609                 return;
610         }
611
612         bool tree_expanded = false;
613
614         /* If the list was expanded prior to rebuilding, expand it again afterwards */
615         if (toggle_full_action()->get_active()) {
616                 tree_expanded = true;
617         }
618
619         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
620         _model->clear ();
621         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
622
623
624         region_row_map.clear();
625         parent_regions_sources_map.clear();
626
627         /* now add everything we have, via a temporary list used to help with sorting */
628
629         const RegionFactory::RegionMap& regions (RegionFactory::regions());
630
631         for (RegionFactory::RegionMap::const_iterator i = regions.begin(); i != regions.end(); ++i) {
632
633                 if ( i->second->whole_file()) {
634                         /* add automatic regions first so that children can find their parents as we add them */
635                         add_region (i->second);
636                         continue;
637                 }
638
639                 tmp_region_list.push_front (i->second);
640         }
641
642         for (list<boost::shared_ptr<Region> >::iterator r = tmp_region_list.begin(); r != tmp_region_list.end(); ++r) {
643                 add_region (*r);
644         }
645
646         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
647         _display.set_model (_model);
648
649         tmp_region_list.clear();
650
651         if (tree_expanded) {
652                 _display.expand_all();
653         }
654 }
655
656 void
657 EditorRegions::update_row (boost::shared_ptr<Region> region)
658 {
659         if (!region || !_session) {
660                 return;
661         }
662
663         RegionRowMap::iterator it;
664
665         it = region_row_map.find (region);
666
667         if (it != region_row_map.end()){
668
669                 TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
670                 populate_row(region, (*j));
671         }
672 }
673
674 void
675 EditorRegions::update_all_rows ()
676 {
677         if (!_session) {
678                 return;
679         }
680
681         RegionRowMap::iterator i;
682
683         for (i = region_row_map.begin(); i != region_row_map.end(); ++i) {
684
685                 TreeModel::iterator j = _model->get_iter ((*i).second.get_path());
686
687                 boost::shared_ptr<Region> region = (*j)[_columns.region];
688
689                 if (!region->automatic()) {
690                         populate_row(region, (*j));
691                 }
692         }
693 }
694
695 void
696 EditorRegions::format_position (framepos_t pos, char* buf, size_t bufsize)
697 {
698         Timecode::BBT_Time bbt;
699         Timecode::Time timecode;
700
701         switch (ARDOUR_UI::instance()->secondary_clock->mode ()) {
702         case AudioClock::BBT:
703                 _session->tempo_map().bbt_time (pos, bbt);
704                 snprintf (buf, bufsize, "%03d|%02d|%04d" , bbt.bars, bbt.beats, bbt.ticks);
705                 break;
706
707         case AudioClock::MinSec:
708                 framepos_t left;
709                 int hrs;
710                 int mins;
711                 float secs;
712
713                 left = pos;
714                 hrs = (int) floor (left / (_session->frame_rate() * 60.0f * 60.0f));
715                 left -= (framecnt_t) floor (hrs * _session->frame_rate() * 60.0f * 60.0f);
716                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
717                 left -= (framecnt_t) floor (mins * _session->frame_rate() * 60.0f);
718                 secs = left / (float) _session->frame_rate();
719                 snprintf (buf, bufsize, "%02d:%02d:%06.3f", hrs, mins, secs);
720                 break;
721
722         case AudioClock::Frames:
723                 snprintf (buf, bufsize, "%" PRId64, pos);
724                 break;
725
726         case AudioClock::Timecode:
727         default:
728                 _session->timecode_time (pos, timecode);
729                 snprintf (buf, bufsize, "%02d:%02d:%02d:%02d", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
730                 break;
731         }
732 }
733
734 void
735 EditorRegions::populate_row (boost::shared_ptr<Region> region, TreeModel::Row const &row)
736 {
737         boost::shared_ptr<AudioRegion> audioregion = boost::dynamic_pointer_cast<AudioRegion>(region);
738         //uint32_t used = _session->playlists->region_use_count (region);
739         /* Presently a region is only used once so let's save on the sequential scan to determine use count */
740         uint32_t used = 1;
741
742         populate_row_position (region, row, used);
743         populate_row_end (region, row, used);
744         populate_row_sync (region, row, used);
745         populate_row_fade_in (region, row, used, audioregion);
746         populate_row_fade_out (region, row, used, audioregion);
747         populate_row_locked (region, row, used);
748         populate_row_glued (region, row, used);
749         populate_row_muted (region, row, used);
750         populate_row_opaque (region, row, used);
751         populate_row_length (region, row);
752         populate_row_source (region, row);
753         populate_row_name (region, row);
754         populate_row_used (region, row, used);
755 }
756
757 #if 0
758         if (audioRegion && fades_in_seconds) {
759
760                 framepos_t left;
761                 int mins;
762                 int millisecs;
763
764                 left = audioRegion->fade_in()->back()->when;
765                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
766                 left -= (framepos_t) floor (mins * _session->frame_rate() * 60.0f);
767                 millisecs = (int) floor ((left * 1000.0f) / _session->frame_rate());
768
769                 if (audioRegion->fade_in()->back()->when >= _session->frame_rate()) {
770                         sprintf (fadein_str, "%01dM %01dmS", mins, millisecs);
771                 } else {
772                         sprintf (fadein_str, "%01dmS", millisecs);
773                 }
774
775                 left = audioRegion->fade_out()->back()->when;
776                 mins = (int) floor (left / (_session->frame_rate() * 60.0f));
777                 left -= (framepos_t) floor (mins * _session->frame_rate() * 60.0f);
778                 millisecs = (int) floor ((left * 1000.0f) / _session->frame_rate());
779
780                 if (audioRegion->fade_out()->back()->when >= _session->frame_rate()) {
781                         sprintf (fadeout_str, "%01dM %01dmS", mins, millisecs);
782                 } else {
783                         sprintf (fadeout_str, "%01dmS", millisecs);
784                 }
785         }
786 #endif
787
788 void
789 EditorRegions::populate_row_used (boost::shared_ptr<Region>, TreeModel::Row const& row, uint32_t used)
790 {
791         char buf[8];
792         snprintf (buf, sizeof (buf), "%4d" , used);
793         row[_columns.used] = buf;
794 }
795
796 void
797 EditorRegions::populate_row_length (boost::shared_ptr<Region> region, TreeModel::Row const &row)
798 {
799         char buf[16];
800         format_position (region->length(), buf, sizeof (buf));
801         row[_columns.length] = buf;
802 }
803
804 void
805 EditorRegions::populate_row_end (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
806 {
807         if (region->whole_file()) {
808                 row[_columns.end] = "";
809         } else if (used > 1) {
810                 row[_columns.end] = _("Mult.");
811         } else {
812                 char buf[16];
813                 format_position (region->last_frame(), buf, sizeof (buf));
814                 row[_columns.end] = buf;
815         }
816 }
817
818 void
819 EditorRegions::populate_row_position (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
820 {
821         if (region->whole_file()) {
822                 row[_columns.position] = "";
823         } else if (used > 1) {
824                 row[_columns.position] = _("Mult.");
825         } else {
826                 char buf[16];
827                 format_position (region->position(), buf, sizeof (buf));
828                 row[_columns.position] = buf;
829         }
830 }
831
832 void
833 EditorRegions::populate_row_sync (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
834 {
835         if (region->whole_file()) {
836                 row[_columns.sync] = "";
837         } else if (used > 1) {
838                 row[_columns.sync] = _("Mult."); /* translators: a short phrase for "multiple" as in "many" */
839         } else {
840                 if (region->sync_position() == region->position()) {
841                         row[_columns.sync] = _("Start");
842                 } else if (region->sync_position() == (region->last_frame())) {
843                         row[_columns.sync] = _("End");
844                 } else {
845                         char buf[16];
846                         format_position (region->sync_position(), buf, sizeof (buf));
847                         row[_columns.sync] = buf;
848                 }
849         }
850 }
851
852 void
853 EditorRegions::populate_row_fade_in (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
854 {
855         if (!audioregion || region->whole_file()) {
856                 row[_columns.fadein] = "";
857         } else {
858                 if (used > 1) {
859                         row[_columns.fadein] = _("Multiple");
860                 } else {
861
862                         char buf[16];
863                         format_position (audioregion->fade_in()->back()->when, buf, sizeof (buf));
864                         row[_columns.fadein] = buf;
865
866                         if (audioregion->fade_in_active()) {
867                                 row[_columns.fadein] = string_compose("%1%2%3", " ", buf, " ");
868                         } else {
869                                 row[_columns.fadein] = string_compose("%1%2%3", "(", buf, ")");
870                         }
871                 }
872         }
873 }
874
875 void
876 EditorRegions::populate_row_fade_out (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
877 {
878         if (!audioregion || region->whole_file()) {
879                 row[_columns.fadeout] = "";
880         } else {
881                 if (used > 1) {
882                         row[_columns.fadeout] = _("Multiple");
883                 } else {
884                         char buf[16];
885                         format_position (audioregion->fade_out()->back()->when, buf, sizeof (buf));
886
887                         if (audioregion->fade_out_active()) {
888                                 row[_columns.fadeout] = string_compose("%1%2%3", " ", buf, " ");
889                         } else {
890                                 row[_columns.fadeout] = string_compose("%1%2%3", "(", buf, ")");
891                         }
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]", region->name(), region->n_channels());
947         } else {
948                 row[_columns.name] = 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 ") + region->source()->name();
957         } else {
958                 row[_columns.path] = 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 = strcasecmp (region1->name().c_str(), region2->name().c_str());
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 = strcasecmp (region1->source()->name().c_str(), region2->source()->name().c_str());
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 = strcasecmp (region1->name().c_str(),  region2->name().c_str());
1163                 } else {
1164                         cmp = strcasecmp (region1->source()->name().c_str(),  region2->source()->name().c_str());
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                 if (Profile->get_sae() || Config->get_only_copy_imported_files()) {
1243                         _editor->do_import (paths, Editing::ImportDistinctFiles, Editing::ImportAsRegion, SrcBest, pos);
1244                 } else {
1245                         _editor->do_embed (paths, Editing::ImportDistinctFiles, ImportAsRegion, pos);
1246                 }
1247                 context->drag_finish (true, false, time);
1248         }
1249 }
1250
1251 bool
1252 EditorRegions::selection_filter (const RefPtr<TreeModel>& model, const TreeModel::Path& path, bool already_selected)
1253 {
1254         /* not possible to select rows that do not represent regions, like "Hidden" */
1255
1256         if (already_selected) {
1257                 /* deselecting anything is OK with us */
1258                 return true;
1259         }
1260
1261         TreeModel::iterator iter = model->get_iter (path);
1262
1263         if (iter) {
1264                 boost::shared_ptr<Region> r =(*iter)[_columns.region];
1265                 if (!r) {
1266                         return false;
1267                 }
1268         }
1269
1270         return true;
1271 }
1272
1273 void
1274 EditorRegions::name_editing_started (CellEditable* ce, const Glib::ustring&)
1275 {
1276         name_editable = ce;
1277
1278         /* give it a special name */
1279
1280         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
1281
1282         if (e) {
1283                 e->set_name (X_("RegionNameEditorEntry"));
1284         }
1285 }
1286
1287 void
1288 EditorRegions::name_edit (const std::string& path, const std::string& new_text)
1289 {
1290         name_editable = 0;
1291
1292         boost::shared_ptr<Region> region;
1293         TreeIter iter;
1294
1295         if ((iter = _model->get_iter (path))) {
1296                 region = (*iter)[_columns.region];
1297                 (*iter)[_columns.name] = new_text;
1298         }
1299
1300         /* now mapover everything */
1301
1302         if (region) {
1303                 vector<RegionView*> equivalents;
1304                 _editor->get_regions_corresponding_to (region, equivalents);
1305
1306                 for (vector<RegionView*>::iterator i = equivalents.begin(); i != equivalents.end(); ++i) {
1307                         if (new_text != (*i)->region()->name()) {
1308                                 (*i)->region()->set_name (new_text);
1309                         }
1310                 }
1311         }
1312
1313 }
1314
1315 /** @return Region that has been dragged out of the list, or 0 */
1316 boost::shared_ptr<Region>
1317 EditorRegions::get_dragged_region ()
1318 {
1319         list<boost::shared_ptr<Region> > regions;
1320         TreeView* source;
1321         _display.get_object_drag_data (regions, &source);
1322
1323         if (regions.empty()) {
1324                 return boost::shared_ptr<Region> ();
1325         }
1326
1327         assert (regions.size() == 1);
1328         return regions.front ();
1329 }
1330
1331 void
1332 EditorRegions::clear ()
1333 {
1334         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1335         _model->clear ();
1336         _display.set_model (_model);
1337
1338         /* Clean up the maps */
1339         region_row_map.clear();
1340         parent_regions_sources_map.clear();
1341 }
1342
1343 boost::shared_ptr<Region>
1344 EditorRegions::get_single_selection ()
1345 {
1346         Glib::RefPtr<TreeSelection> selected = _display.get_selection();
1347
1348         if (selected->count_selected_rows() != 1) {
1349                 return boost::shared_ptr<Region> ();
1350         }
1351
1352         TreeView::Selection::ListHandle_Path rows = selected->get_selected_rows ();
1353
1354         /* only one row selected, so rows.begin() is it */
1355
1356         TreeIter iter = _model->get_iter (*rows.begin());
1357
1358         if (!iter) {
1359                 return boost::shared_ptr<Region> ();
1360         }
1361
1362         return (*iter)[_columns.region];
1363 }
1364
1365 void
1366 EditorRegions::freeze_tree_model (){
1367
1368         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
1369         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
1370
1371 }
1372
1373 void
1374 EditorRegions::thaw_tree_model (){
1375
1376         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
1377         _display.set_model (_model);
1378
1379         if (toggle_full_action()->get_active()) {
1380                 _display.expand_all();
1381         }
1382 }
1383
1384 void
1385 EditorRegions::locked_changed (std::string const & path)
1386 {
1387         TreeIter i = _model->get_iter (path);
1388         if (i) {
1389                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1390                 if (region) {
1391                         region->set_locked (!(*i)[_columns.locked]);
1392                 }
1393         }
1394 }
1395
1396 void
1397 EditorRegions::glued_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                         /* `glued' means MusicTime, and we're toggling here */
1404                         region->set_position_lock_style ((*i)[_columns.glued] ? AudioTime : MusicTime);
1405                 }
1406         }
1407
1408 }
1409
1410 void
1411 EditorRegions::muted_changed (std::string const & path)
1412 {
1413         TreeIter i = _model->get_iter (path);
1414         if (i) {
1415                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1416                 if (region) {
1417                         region->set_muted (!(*i)[_columns.muted]);
1418                 }
1419         }
1420
1421 }
1422
1423 void
1424 EditorRegions::opaque_changed (std::string const & path)
1425 {
1426         TreeIter i = _model->get_iter (path);
1427         if (i) {
1428                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1429                 if (region) {
1430                         region->set_opaque (!(*i)[_columns.opaque]);
1431                 }
1432         }
1433
1434 }
1435
1436 XMLNode &
1437 EditorRegions::get_state () const
1438 {
1439         XMLNode* node = new XMLNode (X_("RegionList"));
1440
1441         node->add_property (X_("sort-type"), enum_2_string (_sort_type));
1442
1443         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1444         bool const ascending = RefPtr<RadioAction>::cast_dynamic(act)->get_active ();
1445         node->add_property (X_("sort-ascending"), ascending ? "yes" : "no");
1446         node->add_property (X_("show-all"), toggle_full_action()->get_active() ? "yes" : "no");
1447         node->add_property (X_("show-automatic-regions"), _show_automatic_regions ? "yes" : "no");
1448
1449         return *node;
1450 }
1451
1452 void
1453 EditorRegions::set_state (const XMLNode & node)
1454 {
1455         bool changed = false;
1456
1457         if (node.name() != X_("RegionList")) {
1458                 return;
1459         }
1460
1461         XMLProperty const * p = node.property (X_("sort-type"));
1462
1463         if (p) {
1464                 Editing::RegionListSortType const t = static_cast<Editing::RegionListSortType> (string_2_enum (p->value(), _sort_type));
1465
1466                 if (_sort_type != t) {
1467                         changed = true;
1468                 }
1469
1470                 reset_sort_type (t, true);
1471                 RefPtr<RadioAction> ract = sort_type_action (t);
1472                 ract->set_active ();
1473         }
1474
1475         p = node.property (X_("sort-ascending"));
1476
1477         if (p) {
1478                 bool const yn = string_is_affirmative (p->value ());
1479                 SortType old_sort_type;
1480                 int old_sort_column;
1481
1482                 _model->get_sort_column_id (old_sort_column, old_sort_type);
1483
1484                 if (old_sort_type != (yn ? SORT_ASCENDING : SORT_DESCENDING)) {
1485                         changed = true;
1486                 }
1487
1488                 reset_sort_direction (yn);
1489                 RefPtr<Action> act;
1490
1491                 if (yn) {
1492                         act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1493                 } else {
1494                         act = ActionManager::get_action (X_("RegionList"), X_("SortDescending"));
1495                 }
1496
1497                 RefPtr<RadioAction>::cast_dynamic(act)->set_active ();
1498         }
1499
1500         p = node.property (X_("show-all"));
1501         if (p) {
1502                 bool const yn = string_is_affirmative (p->value ());
1503
1504                 if (expanded != yn) {
1505                         changed = true;
1506                 }
1507
1508                 set_full (yn);
1509                 toggle_full_action()->set_active (yn);
1510         }
1511
1512         p = node.property (X_("show-automatic-regions"));
1513         if (p) {
1514                 bool const yn = string_is_affirmative (p->value ());
1515
1516                 if (yn != _show_automatic_regions) {
1517                         _show_automatic_regions = yn;
1518                         toggle_show_auto_regions_action()->set_active (yn);
1519                         changed = true;
1520                 }
1521         }
1522
1523         if (changed) {
1524                 redisplay ();
1525         }
1526 }
1527
1528 RefPtr<RadioAction>
1529 EditorRegions::sort_type_action (Editing::RegionListSortType t) const
1530 {
1531         const char* action = 0;
1532
1533         switch (t) {
1534         case Editing::ByName:
1535                 action = X_("SortByRegionName");
1536                 break;
1537         case Editing::ByLength:
1538                 action = X_("SortByRegionLength");
1539                 break;
1540         case Editing::ByPosition:
1541                 action = X_("SortByRegionPosition");
1542                 break;
1543         case Editing::ByTimestamp:
1544                 action = X_("SortByRegionTimestamp");
1545                 break;
1546         case Editing::ByStartInFile:
1547                 action = X_("SortByRegionStartinFile");
1548                 break;
1549         case Editing::ByEndInFile:
1550                 action = X_("SortByRegionEndinFile");
1551                 break;
1552         case Editing::BySourceFileName:
1553                 action = X_("SortBySourceFileName");
1554                 break;
1555         case Editing::BySourceFileLength:
1556                 action = X_("SortBySourceFileLength");
1557                 break;
1558         case Editing::BySourceFileCreationDate:
1559                 action = X_("SortBySourceFileCreationDate");
1560                 break;
1561         case Editing::BySourceFileFS:
1562                 action = X_("SortBySourceFilesystem");
1563                 break;
1564         default:
1565                 fatal << string_compose (_("programming error: %1: %2"), "EditorRegions: impossible sort type", (int) t) << endmsg;
1566                 /*NOTREACHED*/
1567         }
1568
1569         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), action);
1570         assert (act);
1571
1572         return RefPtr<RadioAction>::cast_dynamic (act);
1573 }
1574
1575 RefPtr<Action>
1576 EditorRegions::hide_action () const
1577 {
1578         return ActionManager::get_action (X_("RegionList"), X_("rlHide"));
1579
1580 }
1581
1582 RefPtr<Action>
1583 EditorRegions::show_action () const
1584 {
1585         return ActionManager::get_action (X_("RegionList"), X_("rlShow"));
1586 }
1587
1588 RefPtr<Action>
1589 EditorRegions::remove_unused_regions_action () const
1590 {
1591         return ActionManager::get_action (X_("RegionList"), X_("removeUnusedRegions"));
1592 }
1593
1594 RefPtr<ToggleAction>
1595 EditorRegions::toggle_full_action () const
1596 {
1597         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAll"));
1598         assert (act);
1599         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1600 }
1601
1602 RefPtr<ToggleAction>
1603 EditorRegions::toggle_show_auto_regions_action () const
1604 {
1605         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAuto"));
1606         assert (act);
1607         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1608 }