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