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