new_grid: Rewrite of Snap and Grid. (squashed commit)
[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         /* 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         ArdourWidgets::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         //maybe update the grid here
520         PropertyChange grid_interests;
521         grid_interests.add (ARDOUR::Properties::position);
522         grid_interests.add (ARDOUR::Properties::length);
523         grid_interests.add (ARDOUR::Properties::sync_position);
524         if (what_changed.contains (grid_interests)) {
525                 _editor->mark_region_boundary_cache_dirty();
526         }
527
528         PropertyChange our_interests;
529
530         our_interests.add (ARDOUR::Properties::name);
531         our_interests.add (ARDOUR::Properties::position);
532         our_interests.add (ARDOUR::Properties::length);
533         our_interests.add (ARDOUR::Properties::start);
534         our_interests.add (ARDOUR::Properties::sync_position);
535         our_interests.add (ARDOUR::Properties::locked);
536         our_interests.add (ARDOUR::Properties::position_lock_style);
537         our_interests.add (ARDOUR::Properties::muted);
538         our_interests.add (ARDOUR::Properties::opaque);
539         our_interests.add (ARDOUR::Properties::fade_in);
540         our_interests.add (ARDOUR::Properties::fade_out);
541         our_interests.add (ARDOUR::Properties::fade_in_active);
542         our_interests.add (ARDOUR::Properties::fade_out_active);
543
544         if (what_changed.contains (our_interests)) {
545                 if (last_row != 0) {
546
547                         TreeModel::iterator j = _model->get_iter (last_row.get_path());
548                         boost::shared_ptr<Region> c = (*j)[_columns.region];
549
550                         if (c == r) {
551                                 populate_row (r, (*j), what_changed);
552
553                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
554                                         redisplay ();
555                                 }
556
557                                 return;
558                         }
559                 }
560
561                 RegionRowMap::iterator it;
562
563                 it = region_row_map.find (r);
564
565                 if (it != region_row_map.end()){
566
567                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
568                         boost::shared_ptr<Region> c = (*j)[_columns.region];
569
570                         if (c == r) {
571                                 populate_row (r, (*j), what_changed);
572
573                                 if (what_changed.contains (ARDOUR::Properties::hidden)) {
574                                         redisplay ();
575                                 }
576
577                                 return;
578                         }
579                 }
580         }
581
582         if (what_changed.contains (ARDOUR::Properties::hidden)) {
583                 redisplay ();
584         }
585 }
586
587 void
588 EditorRegions::selection_changed ()
589 {
590         if (ignore_region_list_selection_change) {
591                 return;
592         }
593
594         _editor->_region_selection_change_updates_region_list = false;
595
596         if (_display.get_selection()->count_selected_rows() > 0) {
597
598                 TreeIter iter;
599                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
600
601                 _editor->get_selection().clear_regions ();
602
603                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
604
605                         if ((iter = _model->get_iter (*i))) {
606
607                                 boost::shared_ptr<Region> region = (*iter)[_columns.region];
608
609                                 // they could have clicked on a row that is just a placeholder, like "Hidden"
610                                 // although that is not allowed by our selection filter. check it anyway
611                                 // since we need a region ptr.
612
613                                 if (region) {
614
615                                         _change_connection.block (true);
616                                         _editor->set_selected_regionview_from_region_list (region, Selection::Add);
617                                         _change_connection.block (false);
618                                 }
619                         }
620
621                 }
622         } else {
623                 _editor->get_selection().clear_regions ();
624         }
625
626         _editor->_region_selection_change_updates_region_list = true;
627 }
628
629 void
630 EditorRegions::set_selected (RegionSelection& regions)
631 {
632         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
633
634                 boost::shared_ptr<Region> r ((*i)->region());
635
636                 RegionRowMap::iterator it;
637
638                 it = region_row_map.find (r);
639
640                 if (it != region_row_map.end()){
641                         TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
642                         _display.get_selection()->select(*j);
643                 }
644         }
645 }
646
647 void
648 EditorRegions::redisplay ()
649 {
650         if (_no_redisplay || !_session) {
651                 return;
652         }
653
654         bool tree_expanded = false;
655
656         /* If the list was expanded prior to rebuilding, expand it again afterwards */
657         if (toggle_full_action()->get_active()) {
658                 tree_expanded = true;
659         }
660
661         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
662         _model->clear ();
663         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
664
665
666         region_row_map.clear();
667         parent_regions_sources_map.clear();
668
669         /* now add everything we have, via a temporary list used to help with sorting */
670
671         const RegionFactory::RegionMap& regions (RegionFactory::regions());
672
673         for (RegionFactory::RegionMap::const_iterator i = regions.begin(); i != regions.end(); ++i) {
674
675                 if ( i->second->whole_file()) {
676                         /* add automatic regions first so that children can find their parents as we add them */
677                         add_region (i->second);
678                         continue;
679                 }
680
681                 tmp_region_list.push_front (i->second);
682         }
683
684         for (list<boost::shared_ptr<Region> >::iterator r = tmp_region_list.begin(); r != tmp_region_list.end(); ++r) {
685                 add_region (*r);
686         }
687
688         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
689         _display.set_model (_model);
690
691         tmp_region_list.clear();
692
693         if (tree_expanded) {
694                 _display.expand_all();
695         }
696 }
697
698 void
699 EditorRegions::update_row (boost::shared_ptr<Region> region)
700 {
701         if (!region || !_session) {
702                 return;
703         }
704
705         RegionRowMap::iterator it;
706
707         it = region_row_map.find (region);
708
709         if (it != region_row_map.end()){
710                 PropertyChange c;
711                 TreeModel::iterator j = _model->get_iter ((*it).second.get_path());
712                 populate_row(region, (*j), c);
713         }
714 }
715
716 void
717 EditorRegions::update_all_rows ()
718 {
719         if (!_session) {
720                 return;
721         }
722
723         RegionRowMap::iterator i;
724
725         for (i = region_row_map.begin(); i != region_row_map.end(); ++i) {
726
727                 TreeModel::iterator j = _model->get_iter ((*i).second.get_path());
728
729                 boost::shared_ptr<Region> region = (*j)[_columns.region];
730
731                 if (!region->automatic()) {
732                         PropertyChange c;
733                         populate_row(region, (*j), c);
734                 }
735         }
736 }
737
738 void
739 EditorRegions::format_position (samplepos_t pos, char* buf, size_t bufsize, bool onoff)
740 {
741         Timecode::BBT_Time bbt;
742         Timecode::Time timecode;
743
744         if (pos < 0) {
745                 error << string_compose (_("EditorRegions::format_position: negative timecode position: %1"), pos) << endmsg;
746                 snprintf (buf, bufsize, "invalid");
747                 return;
748         }
749
750         switch (ARDOUR_UI::instance()->secondary_clock->mode ()) {
751         case AudioClock::BBT:
752                 bbt = _session->tempo_map().bbt_at_sample (pos);
753                 if (onoff) {
754                         snprintf (buf, bufsize, "%03d|%02d|%04d" , bbt.bars, bbt.beats, bbt.ticks);
755                 } else {
756                         snprintf (buf, bufsize, "(%03d|%02d|%04d)" , bbt.bars, bbt.beats, bbt.ticks);
757                 }
758                 break;
759
760         case AudioClock::MinSec:
761                 samplepos_t left;
762                 int hrs;
763                 int mins;
764                 float secs;
765
766                 left = pos;
767                 hrs = (int) floor (left / (_session->sample_rate() * 60.0f * 60.0f));
768                 left -= (samplecnt_t) floor (hrs * _session->sample_rate() * 60.0f * 60.0f);
769                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
770                 left -= (samplecnt_t) floor (mins * _session->sample_rate() * 60.0f);
771                 secs = left / (float) _session->sample_rate();
772                 if (onoff) {
773                         snprintf (buf, bufsize, "%02d:%02d:%06.3f", hrs, mins, secs);
774                 } else {
775                         snprintf (buf, bufsize, "(%02d:%02d:%06.3f)", hrs, mins, secs);
776                 }
777                 break;
778
779         case AudioClock::Seconds:
780                 if (onoff) {
781                         snprintf (buf, bufsize, "%.1f", pos / (float)_session->sample_rate());
782                 } else {
783                         snprintf (buf, bufsize, "(%.1f)", pos / (float)_session->sample_rate());
784                 }
785                 break;
786
787         case AudioClock::Samples:
788                 if (onoff) {
789                         snprintf (buf, bufsize, "%" PRId64, pos);
790                 } else {
791                         snprintf (buf, bufsize, "(%" PRId64 ")", pos);
792                 }
793                 break;
794
795         case AudioClock::Timecode:
796         default:
797                 _session->timecode_time (pos, timecode);
798                 if (onoff) {
799                         snprintf (buf, bufsize, "%02d:%02d:%02d:%02d", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
800                 } else {
801                         snprintf (buf, bufsize, "(%02d:%02d:%02d:%02d)", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
802                 }
803                 break;
804         }
805 }
806
807 void
808 EditorRegions::populate_row (boost::shared_ptr<Region> region, TreeModel::Row const &row, PBD::PropertyChange const &what_changed)
809 {
810         boost::shared_ptr<AudioRegion> audioregion = boost::dynamic_pointer_cast<AudioRegion>(region);
811         //uint32_t used = _session->playlists->region_use_count (region);
812         /* Presently a region is only used once so let's save on the sequential scan to determine use count */
813         uint32_t used = 1;
814
815         PropertyChange c;
816         const bool all = what_changed == c;
817
818         if (all || what_changed.contains (Properties::position)) {
819                 populate_row_position (region, row, used);
820         }
821         if (all || what_changed.contains (Properties::start) || what_changed.contains (Properties::sync_position)) {
822                 populate_row_sync (region, row, used);
823         }
824         if (all || what_changed.contains (Properties::fade_in)) {
825                 populate_row_fade_in (region, row, used, audioregion);
826         }
827         if (all || what_changed.contains (Properties::fade_out)) {
828                 populate_row_fade_out (region, row, used, audioregion);
829         }
830         if (all || what_changed.contains (Properties::locked)) {
831                 populate_row_locked (region, row, used);
832         }
833         if (all || what_changed.contains (Properties::position_lock_style)) {
834                 populate_row_glued (region, row, used);
835         }
836         if (all || what_changed.contains (Properties::muted)) {
837                 populate_row_muted (region, row, used);
838         }
839         if (all || what_changed.contains (Properties::opaque)) {
840                 populate_row_opaque (region, row, used);
841         }
842         if (all || what_changed.contains (Properties::length)) {
843                 populate_row_end (region, row, used);
844                 populate_row_length (region, row);
845         }
846         if (all) {
847                 populate_row_source (region, row);
848         }
849         if (all || what_changed.contains (Properties::name)) {
850                 populate_row_name (region, row);
851         }
852         if (all) {
853                 populate_row_used (region, row, used);
854         }
855 }
856
857 #if 0
858         if (audioRegion && fades_in_seconds) {
859
860                 samplepos_t left;
861                 int mins;
862                 int millisecs;
863
864                 left = audioRegion->fade_in()->back()->when;
865                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
866                 left -= (samplepos_t) floor (mins * _session->sample_rate() * 60.0f);
867                 millisecs = (int) floor ((left * 1000.0f) / _session->sample_rate());
868
869                 if (audioRegion->fade_in()->back()->when >= _session->sample_rate()) {
870                         sprintf (fadein_str, "%01dM %01dmS", mins, millisecs);
871                 } else {
872                         sprintf (fadein_str, "%01dmS", millisecs);
873                 }
874
875                 left = audioRegion->fade_out()->back()->when;
876                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
877                 left -= (samplepos_t) floor (mins * _session->sample_rate() * 60.0f);
878                 millisecs = (int) floor ((left * 1000.0f) / _session->sample_rate());
879
880                 if (audioRegion->fade_out()->back()->when >= _session->sample_rate()) {
881                         sprintf (fadeout_str, "%01dM %01dmS", mins, millisecs);
882                 } else {
883                         sprintf (fadeout_str, "%01dmS", millisecs);
884                 }
885         }
886 #endif
887
888 void
889 EditorRegions::populate_row_used (boost::shared_ptr<Region>, TreeModel::Row const& row, uint32_t used)
890 {
891         char buf[8];
892         snprintf (buf, sizeof (buf), "%4d" , used);
893         row[_columns.used] = buf;
894 }
895
896 void
897 EditorRegions::populate_row_length (boost::shared_ptr<Region> region, TreeModel::Row const &row)
898 {
899         char buf[16];
900
901         if (ARDOUR_UI::instance()->secondary_clock->mode () == AudioClock::BBT) {
902                 TempoMap& map (_session->tempo_map());
903                 Timecode::BBT_Time bbt = map.bbt_at_beat (map.beat_at_sample (region->last_sample()) - map.beat_at_sample (region->first_sample()));
904                 snprintf (buf, sizeof (buf), "%03d|%02d|%04d" , bbt.bars, bbt.beats, bbt.ticks);
905         } else {
906                 format_position (region->length(), buf, sizeof (buf));
907         }
908
909         row[_columns.length] = buf;
910 }
911
912 void
913 EditorRegions::populate_row_end (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
914 {
915         if (region->whole_file()) {
916                 row[_columns.end] = "";
917         } else if (used > 1) {
918                 row[_columns.end] = _("Mult.");
919         } else if (region->last_sample() >= region->first_sample()) {
920                 char buf[16];
921                 format_position (region->last_sample(), buf, sizeof (buf));
922                 row[_columns.end] = buf;
923         } else {
924                 row[_columns.end] = "empty";
925         }
926 }
927
928 void
929 EditorRegions::populate_row_position (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
930 {
931         if (region->whole_file()) {
932                 row[_columns.position] = "";
933         } else if (used > 1) {
934                 row[_columns.position] = _("Mult.");
935         } else {
936                 char buf[16];
937                 format_position (region->position(), buf, sizeof (buf));
938                 row[_columns.position] = buf;
939         }
940 }
941
942 void
943 EditorRegions::populate_row_sync (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
944 {
945         if (region->whole_file()) {
946                 row[_columns.sync] = "";
947         } else if (used > 1) {
948                 row[_columns.sync] = _("Mult."); /* translators: a short phrase for "multiple" as in "many" */
949         } else {
950                 if (region->sync_position() == region->position()) {
951                         row[_columns.sync] = _("Start");
952                 } else if (region->sync_position() == (region->last_sample())) {
953                         row[_columns.sync] = _("End");
954                 } else {
955                         char buf[16];
956                         format_position (region->sync_position(), buf, sizeof (buf));
957                         row[_columns.sync] = buf;
958                 }
959         }
960 }
961
962 void
963 EditorRegions::populate_row_fade_in (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
964 {
965         if (!audioregion || region->whole_file()) {
966                 row[_columns.fadein] = "";
967         } else {
968                 if (used > 1) {
969                         row[_columns.fadein] = _("Multiple");
970                 } else {
971                         char buf[32];
972                         format_position (audioregion->fade_in()->back()->when, buf, sizeof (buf), audioregion->fade_in_active());
973                         row[_columns.fadein] = buf;
974                 }
975         }
976 }
977
978 void
979 EditorRegions::populate_row_fade_out (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used, boost::shared_ptr<AudioRegion> audioregion)
980 {
981         if (!audioregion || region->whole_file()) {
982                 row[_columns.fadeout] = "";
983         } else {
984                 if (used > 1) {
985                         row[_columns.fadeout] = _("Multiple");
986                 } else {
987                         char buf[32];
988                         format_position (audioregion->fade_out()->back()->when, buf, sizeof (buf), audioregion->fade_out_active());
989                         row[_columns.fadeout] = buf;
990                 }
991         }
992 }
993
994 void
995 EditorRegions::populate_row_locked (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
996 {
997         if (region->whole_file()) {
998                 row[_columns.locked] = false;
999         } else if (used > 1) {
1000                 row[_columns.locked] = false;
1001         } else {
1002                 row[_columns.locked] = region->locked();
1003         }
1004 }
1005
1006 void
1007 EditorRegions::populate_row_glued (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
1008 {
1009         if (region->whole_file() || used > 1) {
1010                 row[_columns.glued] = false;
1011         } else {
1012                 if (region->position_lock_style() == MusicTime) {
1013                         row[_columns.glued] = true;
1014                 } else {
1015                         row[_columns.glued] = false;
1016                 }
1017         }
1018 }
1019
1020 void
1021 EditorRegions::populate_row_muted (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
1022 {
1023         if (region->whole_file() || used > 1) {
1024                 row[_columns.muted] = false;
1025         } else {
1026                 row[_columns.muted] = region->muted();
1027         }
1028 }
1029
1030 void
1031 EditorRegions::populate_row_opaque (boost::shared_ptr<Region> region, TreeModel::Row const &row, uint32_t used)
1032 {
1033         if (region->whole_file() || used > 1) {
1034                 row[_columns.opaque] = false;
1035         } else {
1036                 row[_columns.opaque] = region->opaque();
1037         }
1038 }
1039
1040 void
1041 EditorRegions::populate_row_name (boost::shared_ptr<Region> region, TreeModel::Row const &row)
1042 {
1043         if (region->n_channels() > 1) {
1044                 row[_columns.name] = string_compose("%1  [%2]", Gtkmm2ext::markup_escape_text (region->name()), region->n_channels());
1045         } else {
1046                 row[_columns.name] = Gtkmm2ext::markup_escape_text (region->name());
1047         }
1048 }
1049
1050 void
1051 EditorRegions::populate_row_source (boost::shared_ptr<Region> region, TreeModel::Row const &row)
1052 {
1053         if (boost::dynamic_pointer_cast<SilentFileSource>(region->source())) {
1054                 row[_columns.path] = _("MISSING ") + Gtkmm2ext::markup_escape_text (region->source()->name());
1055         } else {
1056                 row[_columns.path] = Gtkmm2ext::markup_escape_text (region->source()->name());
1057         }
1058 }
1059
1060 void
1061 EditorRegions::toggle_show_auto_regions ()
1062 {
1063         _show_automatic_regions = toggle_show_auto_regions_action()->get_active();
1064         redisplay ();
1065 }
1066
1067 void
1068 EditorRegions::toggle_full ()
1069 {
1070         set_full (toggle_full_action()->get_active ());
1071 }
1072
1073 void
1074 EditorRegions::set_full (bool f)
1075 {
1076         if (f) {
1077                 _display.expand_all ();
1078                 expanded = true;
1079         } else {
1080                 _display.collapse_all ();
1081                 expanded = false;
1082         }
1083 }
1084
1085 void
1086 EditorRegions::show_context_menu (int button, int time)
1087 {
1088         if (_menu == 0) {
1089                 _menu = dynamic_cast<Menu*> (ActionManager::get_widget ("/RegionListMenu"));
1090         }
1091
1092         if (_display.get_selection()->count_selected_rows() > 0) {
1093                 ActionManager::set_sensitive (ActionManager::region_list_selection_sensitive_actions, true);
1094         } else {
1095                 ActionManager::set_sensitive (ActionManager::region_list_selection_sensitive_actions, false);
1096         }
1097
1098         /* Enable the "Show" option if any selected regions are hidden, and vice versa for "Hide" */
1099
1100         bool have_shown = false;
1101         bool have_hidden = false;
1102
1103         TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
1104         for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
1105                 TreeIter t = _model->get_iter (*i);
1106                 boost::shared_ptr<Region> r = (*t)[_columns.region];
1107                 if (r) {
1108                         if (r->hidden ()) {
1109                                 have_hidden = true;
1110                         } else {
1111                                 have_shown = true;
1112                         }
1113                 }
1114         }
1115
1116         hide_action()->set_sensitive (have_shown);
1117         show_action()->set_sensitive (have_hidden);
1118
1119         _menu->popup (button, time);
1120 }
1121
1122 bool
1123 EditorRegions::key_press (GdkEventKey* ev)
1124 {
1125         TreeViewColumn *col;
1126
1127         switch (ev->keyval) {
1128         case GDK_Tab:
1129         case GDK_ISO_Left_Tab:
1130
1131                 if (name_editable) {
1132                         name_editable->editing_done ();
1133                         name_editable = 0;
1134                 }
1135
1136                 col = _display.get_column (0); // select&focus on name column
1137
1138                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
1139                         treeview_select_previous (_display, _model, col);
1140                 } else {
1141                         treeview_select_next (_display, _model, col);
1142                 }
1143
1144                 return true;
1145                 break;
1146
1147         default:
1148                 break;
1149         }
1150
1151         return false;
1152 }
1153
1154 bool
1155 EditorRegions::button_press (GdkEventButton *ev)
1156 {
1157         boost::shared_ptr<Region> region;
1158         TreeIter iter;
1159         TreeModel::Path path;
1160         TreeViewColumn* column;
1161         int cellx;
1162         int celly;
1163
1164         if (_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
1165                 if ((iter = _model->get_iter (path))) {
1166                         region = (*iter)[_columns.region];
1167                 }
1168         }
1169
1170         if (Keyboard::is_context_menu_event (ev)) {
1171                 show_context_menu (ev->button, ev->time);
1172                 return false;
1173         }
1174
1175         if (region != 0 && Keyboard::is_button2_event (ev)) {
1176                 // start/stop audition
1177                 if (!Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1178                         _editor->consider_auditioning (region);
1179                 }
1180                 return true;
1181         }
1182
1183         return false;
1184 }
1185
1186 int
1187 EditorRegions::sorter (TreeModel::iterator a, TreeModel::iterator b)
1188 {
1189         int cmp = 0;
1190
1191         boost::shared_ptr<Region> r1 = (*a)[_columns.region];
1192         boost::shared_ptr<Region> r2 = (*b)[_columns.region];
1193
1194         /* handle rows without regions, like "Hidden" */
1195
1196         if (r1 == 0) {
1197                 return -1;
1198         }
1199
1200         if (r2 == 0) {
1201                 return 1;
1202         }
1203
1204         boost::shared_ptr<AudioRegion> region1 = boost::dynamic_pointer_cast<AudioRegion> (r1);
1205         boost::shared_ptr<AudioRegion> region2 = boost::dynamic_pointer_cast<AudioRegion> (r2);
1206
1207         if (region1 == 0 || region2 == 0) {
1208                 std::string s1;
1209                 std::string s2;
1210                 switch (_sort_type) {
1211                 case ByName:
1212                         s1 = (*a)[_columns.name];
1213                         s2 = (*b)[_columns.name];
1214                         return (s1.compare (s2));
1215                 default:
1216                         return 0;
1217                 }
1218         }
1219
1220         switch (_sort_type) {
1221         case ByName:
1222                 cmp = region1->name().compare(region2->name());
1223                 break;
1224
1225         case ByLength:
1226                 cmp = region1->length() - region2->length();
1227                 break;
1228
1229         case ByPosition:
1230                 cmp = region1->position() - region2->position();
1231                 break;
1232
1233         case ByTimestamp:
1234                 cmp = region1->source()->timestamp() - region2->source()->timestamp();
1235                 break;
1236
1237         case ByStartInFile:
1238                 cmp = region1->start() - region2->start();
1239                 break;
1240
1241         case ByEndInFile:
1242                 // cerr << "Compare " << (region1->start() + region1->length()) << " and " << (region2->start() + region2->length()) << endl;
1243                 cmp = (region1->start() + region1->length()) - (region2->start() + region2->length());
1244                 break;
1245
1246         case BySourceFileName:
1247                 cmp = region1->source()->name().compare(region2->source()->name());
1248                 break;
1249
1250         case BySourceFileLength:
1251                 cmp = region1->source_length(0) - region2->source_length(0);
1252                 break;
1253
1254         case BySourceFileCreationDate:
1255                 cmp = region1->source()->timestamp() - region2->source()->timestamp();
1256                 break;
1257
1258         case BySourceFileFS:
1259                 if (region1->source()->name() == region2->source()->name()) {
1260                         cmp = region1->name().compare(region2->name());
1261                 } else {
1262                         cmp = region1->source()->name().compare(region2->source()->name());
1263                 }
1264                 break;
1265         }
1266
1267         // cerr << "Comparison on " << enum_2_string (_sort_type) << " gives " << cmp << endl;
1268
1269         if (cmp < 0) {
1270                 return -1;
1271         } else if (cmp > 0) {
1272                 return 1;
1273         } else {
1274                 return 0;
1275         }
1276 }
1277
1278 void
1279 EditorRegions::reset_sort_type (RegionListSortType type, bool force)
1280 {
1281         if (type != _sort_type || force) {
1282                 _sort_type = type;
1283                 _model->set_sort_func (0, (sigc::mem_fun (*this, &EditorRegions::sorter)));
1284         }
1285 }
1286
1287 void
1288 EditorRegions::reset_sort_direction (bool up)
1289 {
1290         _model->set_sort_column (0, up ? SORT_ASCENDING : SORT_DESCENDING);
1291 }
1292
1293 void
1294 EditorRegions::selection_mapover (sigc::slot<void,boost::shared_ptr<Region> > sl)
1295 {
1296         Glib::RefPtr<TreeSelection> selection = _display.get_selection();
1297         TreeView::Selection::ListHandle_Path rows = selection->get_selected_rows ();
1298         TreeView::Selection::ListHandle_Path::iterator i = rows.begin();
1299
1300         if (selection->count_selected_rows() == 0 || _session == 0) {
1301                 return;
1302         }
1303
1304         for (; i != rows.end(); ++i) {
1305                 TreeIter iter;
1306
1307                 if ((iter = _model->get_iter (*i))) {
1308
1309                         /* some rows don't have a region associated with them, but can still be
1310                            selected (XXX maybe prevent them from being selected)
1311                         */
1312
1313                         boost::shared_ptr<Region> r = (*iter)[_columns.region];
1314
1315                         if (r) {
1316                                 sl (r);
1317                         }
1318                 }
1319         }
1320 }
1321
1322
1323 void
1324 EditorRegions::drag_data_received (const RefPtr<Gdk::DragContext>& context,
1325                                    int x, int y,
1326                                    const SelectionData& data,
1327                                    guint info, guint time)
1328 {
1329         vector<string> paths;
1330
1331         if (data.get_target() == "GTK_TREE_MODEL_ROW") {
1332                 /* something is being dragged over the region list */
1333                 _editor->_drags->abort ();
1334                 _display.on_drag_data_received (context, x, y, data, info, time);
1335                 return;
1336         }
1337
1338         if (_editor->convert_drop_to_paths (paths, context, x, y, data, info, time) == 0) {
1339                 samplepos_t pos = 0;
1340                 bool copy = ((context->get_actions() & (Gdk::ACTION_COPY | Gdk::ACTION_LINK | Gdk::ACTION_MOVE)) == Gdk::ACTION_COPY);
1341
1342                 if (UIConfiguration::instance().get_only_copy_imported_files() || copy) {
1343                         _editor->do_import (paths, Editing::ImportDistinctFiles, Editing::ImportAsRegion,
1344                                             SrcBest, SMFTrackName, SMFTempoIgnore, pos);
1345                 } else {
1346                         _editor->do_embed (paths, Editing::ImportDistinctFiles, ImportAsRegion, pos);
1347                 }
1348                 context->drag_finish (true, false, time);
1349         }
1350 }
1351
1352 bool
1353 EditorRegions::selection_filter (const RefPtr<TreeModel>& model, const TreeModel::Path& path, bool already_selected)
1354 {
1355         /* not possible to select rows that do not represent regions, like "Hidden" */
1356
1357         if (already_selected) {
1358                 /* deselecting anything is OK with us */
1359                 return true;
1360         }
1361
1362         TreeModel::iterator iter = model->get_iter (path);
1363
1364         if (iter) {
1365                 boost::shared_ptr<Region> r =(*iter)[_columns.region];
1366                 if (!r) {
1367                         return false;
1368                 }
1369         }
1370
1371         return true;
1372 }
1373
1374 void
1375 EditorRegions::name_editing_started (CellEditable* ce, const Glib::ustring& path)
1376 {
1377         name_editable = ce;
1378
1379         /* give it a special name */
1380
1381         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
1382
1383         if (e) {
1384                 e->set_name (X_("RegionNameEditorEntry"));
1385
1386                 TreeIter iter;
1387                 if ((iter = _model->get_iter (path))) {
1388                         boost::shared_ptr<Region> region = (*iter)[_columns.region];
1389
1390                         if(region) {
1391                                 e->set_text(region->name());
1392                         }
1393                 }
1394         }
1395 }
1396
1397 void
1398 EditorRegions::name_edit (const std::string& path, const std::string& new_text)
1399 {
1400         name_editable = 0;
1401
1402         boost::shared_ptr<Region> region;
1403         TreeIter row_iter;
1404
1405         if ((row_iter = _model->get_iter (path))) {
1406                 region = (*row_iter)[_columns.region];
1407                 (*row_iter)[_columns.name] = new_text;
1408         }
1409
1410         /* now mapover everything */
1411
1412         if (region) {
1413                 vector<RegionView*> equivalents;
1414                 _editor->get_regions_corresponding_to (region, equivalents, false);
1415
1416                 for (vector<RegionView*>::iterator i = equivalents.begin(); i != equivalents.end(); ++i) {
1417                         if (new_text != (*i)->region()->name()) {
1418                                 (*i)->region()->set_name (new_text);
1419                         }
1420                 }
1421
1422                 populate_row_name (region, (*row_iter));
1423         }
1424 }
1425
1426 /** @return Region that has been dragged out of the list, or 0 */
1427 boost::shared_ptr<Region>
1428 EditorRegions::get_dragged_region ()
1429 {
1430         list<boost::shared_ptr<Region> > regions;
1431         TreeView* source;
1432         _display.get_object_drag_data (regions, &source);
1433
1434         if (regions.empty()) {
1435                 return boost::shared_ptr<Region> ();
1436         }
1437
1438         assert (regions.size() == 1);
1439         return regions.front ();
1440 }
1441
1442 void
1443 EditorRegions::clear ()
1444 {
1445         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1446         _model->clear ();
1447         _display.set_model (_model);
1448
1449         /* Clean up the maps */
1450         region_row_map.clear();
1451         parent_regions_sources_map.clear();
1452 }
1453
1454 boost::shared_ptr<Region>
1455 EditorRegions::get_single_selection ()
1456 {
1457         Glib::RefPtr<TreeSelection> selected = _display.get_selection();
1458
1459         if (selected->count_selected_rows() != 1) {
1460                 return boost::shared_ptr<Region> ();
1461         }
1462
1463         TreeView::Selection::ListHandle_Path rows = selected->get_selected_rows ();
1464
1465         /* only one row selected, so rows.begin() is it */
1466
1467         TreeIter iter = _model->get_iter (*rows.begin());
1468
1469         if (!iter) {
1470                 return boost::shared_ptr<Region> ();
1471         }
1472
1473         return (*iter)[_columns.region];
1474 }
1475
1476 void
1477 EditorRegions::freeze_tree_model (){
1478
1479         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
1480         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
1481
1482 }
1483
1484 void
1485 EditorRegions::thaw_tree_model (){
1486
1487         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
1488         _display.set_model (_model);
1489
1490         if (toggle_full_action()->get_active()) {
1491                 _display.expand_all();
1492         }
1493 }
1494
1495 void
1496 EditorRegions::locked_changed (std::string const & path)
1497 {
1498         TreeIter i = _model->get_iter (path);
1499         if (i) {
1500                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1501                 if (region) {
1502                         region->set_locked (!(*i)[_columns.locked]);
1503                 }
1504         }
1505 }
1506
1507 void
1508 EditorRegions::glued_changed (std::string const & path)
1509 {
1510         TreeIter i = _model->get_iter (path);
1511         if (i) {
1512                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1513                 if (region) {
1514                         /* `glued' means MusicTime, and we're toggling here */
1515                         region->set_position_lock_style ((*i)[_columns.glued] ? AudioTime : MusicTime);
1516                 }
1517         }
1518
1519 }
1520
1521 void
1522 EditorRegions::muted_changed (std::string const & path)
1523 {
1524         TreeIter i = _model->get_iter (path);
1525         if (i) {
1526                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1527                 if (region) {
1528                         region->set_muted (!(*i)[_columns.muted]);
1529                 }
1530         }
1531
1532 }
1533
1534 void
1535 EditorRegions::opaque_changed (std::string const & path)
1536 {
1537         TreeIter i = _model->get_iter (path);
1538         if (i) {
1539                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1540                 if (region) {
1541                         region->set_opaque (!(*i)[_columns.opaque]);
1542                 }
1543         }
1544
1545 }
1546
1547 XMLNode &
1548 EditorRegions::get_state () const
1549 {
1550         XMLNode* node = new XMLNode (X_("RegionList"));
1551
1552         node->set_property (X_("sort-type"), _sort_type);
1553
1554         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1555         bool const ascending = RefPtr<RadioAction>::cast_dynamic(act)->get_active ();
1556         node->set_property (X_("sort-ascending"), ascending);
1557         node->set_property (X_("show-all"), toggle_full_action()->get_active());
1558         node->set_property (X_("show-automatic-regions"), _show_automatic_regions);
1559
1560         return *node;
1561 }
1562
1563 void
1564 EditorRegions::set_state (const XMLNode & node)
1565 {
1566         bool changed = false;
1567
1568         if (node.name() != X_("RegionList")) {
1569                 return;
1570         }
1571
1572         Editing::RegionListSortType t;
1573         if (node.get_property (X_("sort-type"), t)) {
1574
1575                 if (_sort_type != t) {
1576                         changed = true;
1577                 }
1578
1579                 reset_sort_type (t, true);
1580                 RefPtr<RadioAction> ract = sort_type_action (t);
1581                 ract->set_active ();
1582         }
1583
1584         bool yn;
1585         if (node.get_property (X_("sort-ascending"), yn)) {
1586                 SortType old_sort_type;
1587                 int old_sort_column;
1588
1589                 _model->get_sort_column_id (old_sort_column, old_sort_type);
1590
1591                 if (old_sort_type != (yn ? SORT_ASCENDING : SORT_DESCENDING)) {
1592                         changed = true;
1593                 }
1594
1595                 reset_sort_direction (yn);
1596                 RefPtr<Action> act;
1597
1598                 if (yn) {
1599                         act = ActionManager::get_action (X_("RegionList"), X_("SortAscending"));
1600                 } else {
1601                         act = ActionManager::get_action (X_("RegionList"), X_("SortDescending"));
1602                 }
1603
1604                 RefPtr<RadioAction>::cast_dynamic(act)->set_active ();
1605         }
1606
1607         if (node.get_property (X_("show-all"), yn)) {
1608                 if (expanded != yn) {
1609                         changed = true;
1610                 }
1611
1612                 set_full (yn);
1613                 toggle_full_action()->set_active (yn);
1614         }
1615
1616         if (node.get_property (X_("show-automatic-regions"), yn)) {
1617                 if (yn != _show_automatic_regions) {
1618                         _show_automatic_regions = yn;
1619                         toggle_show_auto_regions_action()->set_active (yn);
1620                         changed = true;
1621                 }
1622         }
1623
1624         if (changed) {
1625                 redisplay ();
1626         }
1627 }
1628
1629 RefPtr<RadioAction>
1630 EditorRegions::sort_type_action (Editing::RegionListSortType t) const
1631 {
1632         const char* action = 0;
1633
1634         switch (t) {
1635         case Editing::ByName:
1636                 action = X_("SortByRegionName");
1637                 break;
1638         case Editing::ByLength:
1639                 action = X_("SortByRegionLength");
1640                 break;
1641         case Editing::ByPosition:
1642                 action = X_("SortByRegionPosition");
1643                 break;
1644         case Editing::ByTimestamp:
1645                 action = X_("SortByRegionTimestamp");
1646                 break;
1647         case Editing::ByStartInFile:
1648                 action = X_("SortByRegionStartinFile");
1649                 break;
1650         case Editing::ByEndInFile:
1651                 action = X_("SortByRegionEndinFile");
1652                 break;
1653         case Editing::BySourceFileName:
1654                 action = X_("SortBySourceFileName");
1655                 break;
1656         case Editing::BySourceFileLength:
1657                 action = X_("SortBySourceFileLength");
1658                 break;
1659         case Editing::BySourceFileCreationDate:
1660                 action = X_("SortBySourceFileCreationDate");
1661                 break;
1662         case Editing::BySourceFileFS:
1663                 action = X_("SortBySourceFilesystem");
1664                 break;
1665         default:
1666                 fatal << string_compose (_("programming error: %1: %2"), "EditorRegions: impossible sort type", (int) t) << endmsg;
1667                 abort(); /*NOTREACHED*/
1668         }
1669
1670         RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), action);
1671         assert (act);
1672
1673         return RefPtr<RadioAction>::cast_dynamic (act);
1674 }
1675
1676 RefPtr<Action>
1677 EditorRegions::hide_action () const
1678 {
1679         return ActionManager::get_action (X_("RegionList"), X_("rlHide"));
1680
1681 }
1682
1683 RefPtr<Action>
1684 EditorRegions::show_action () const
1685 {
1686         return ActionManager::get_action (X_("RegionList"), X_("rlShow"));
1687 }
1688
1689 RefPtr<Action>
1690 EditorRegions::remove_unused_regions_action () const
1691 {
1692         return ActionManager::get_action (X_("RegionList"), X_("removeUnusedRegions"));
1693 }
1694
1695 RefPtr<ToggleAction>
1696 EditorRegions::toggle_full_action () const
1697 {
1698         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAll"));
1699         assert (act);
1700         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1701 }
1702
1703 RefPtr<ToggleAction>
1704 EditorRegions::toggle_show_auto_regions_action () const
1705 {
1706         Glib::RefPtr<Action> act = ActionManager::get_action (X_("RegionList"), X_("rlShowAuto"));
1707         assert (act);
1708         return Glib::RefPtr<ToggleAction>::cast_dynamic (act);
1709 }