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