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