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