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