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