Amend 8a5cbb8: fix variable-names and comments
[ardour.git] / gtk2_ardour / editor_regions.cc
1 /*
2  * Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
3  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
4  * Copyright (C) 2009-2018 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
6  * Copyright (C) 2015-2016 Tim Mayberry <mojofunk@gmail.com>
7  * Copyright (C) 2016 Nick Mainsbridge <mainsbridge@gmail.com>
8  * Copyright (C) 2018-2019 Ben Loftis <ben@harrisonconsoles.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include <algorithm>
26 #include <cmath>
27 #include <cstdlib>
28 #include <sstream>
29 #include <string>
30
31 #include "pbd/basename.h"
32 #include "pbd/enumwriter.h"
33
34 #include "ardour/audiofilesource.h"
35 #include "ardour/audioregion.h"
36 #include "ardour/profile.h"
37 #include "ardour/region_factory.h"
38 #include "ardour/session.h"
39 #include "ardour/session_playlist.h"
40 #include "ardour/silentfilesource.h"
41
42 #include "gtkmm2ext/treeutils.h"
43 #include "gtkmm2ext/utils.h"
44
45 #include "widgets/choice.h"
46 #include "widgets/tooltips.h"
47
48 #include "actions.h"
49 #include "ardour_ui.h"
50 #include "audio_clock.h"
51 #include "editing.h"
52 #include "editing_convert.h"
53 #include "editor.h"
54 #include "editor_drag.h"
55 #include "editor_regions.h"
56 #include "gui_thread.h"
57 #include "keyboard.h"
58 #include "main_clock.h"
59 #include "region_view.h"
60 #include "ui_config.h"
61 #include "utils.h"
62
63 #include "pbd/i18n.h"
64
65 using namespace std;
66 using namespace ARDOUR;
67 using namespace ArdourWidgets;
68 using namespace ARDOUR_UI_UTILS;
69 using namespace PBD;
70 using namespace Gtk;
71 using namespace Glib;
72 using namespace Editing;
73 using Gtkmm2ext::Keyboard;
74
75 struct ColumnInfo {
76         int                index;
77         int                sort_idx;
78         Gtk::AlignmentEnum al;
79         const char*        label;
80         const char*        tooltip;
81 };
82
83 //#define SHOW_REGION_EXTRAS
84
85 EditorRegions::EditorRegions (Editor* e)
86         : EditorComponent (e)
87         , old_focus (0)
88         , name_editable (0)
89         , tags_editable (0)
90         , _menu (0)
91         , _no_redisplay (false)
92 {
93         _display.set_size_request (100, -1);
94         _display.set_rules_hint (true);
95         _display.set_name ("RegionList");
96         _display.set_fixed_height_mode (true);
97         _display.set_reorderable (false);
98
99         /* Try to prevent single mouse presses from initiating edits.
100          * This relies on a hack in gtktreeview.c:gtk_treeview_button_press() */
101         _display.set_data ("mouse-edits-require-mod1", (gpointer)0x1);
102
103         _model = TreeStore::create (_columns);
104         _model->set_sort_column (0, SORT_ASCENDING);
105
106         /* column widths */
107         int bbt_width, date_width, check_width, height;
108
109         Glib::RefPtr<Pango::Layout> layout = _display.create_pango_layout (X_ ("000|000|000"));
110         Gtkmm2ext::get_pixel_size (layout, bbt_width, height);
111
112         Glib::RefPtr<Pango::Layout> layout2 = _display.create_pango_layout (X_ ("2099-10-10 10:10:30"));
113         Gtkmm2ext::get_pixel_size (layout2, date_width, height);
114
115         check_width = 20;
116
117         TreeViewColumn* col_name = manage (new TreeViewColumn ("", _columns.name));
118         col_name->set_fixed_width (120);
119         col_name->set_sizing (TREE_VIEW_COLUMN_FIXED);
120         TreeViewColumn* col_tags = manage (new TreeViewColumn ("", _columns.tags));
121         col_tags->set_fixed_width (date_width);
122         col_tags->set_sizing (TREE_VIEW_COLUMN_FIXED);
123         TreeViewColumn* col_start = manage (new TreeViewColumn ("", _columns.start));
124         col_start->set_fixed_width (bbt_width);
125         col_start->set_sizing (TREE_VIEW_COLUMN_FIXED);
126         TreeViewColumn* col_end = manage (new TreeViewColumn ("", _columns.end));
127         col_end->set_fixed_width (bbt_width);
128         col_end->set_sizing (TREE_VIEW_COLUMN_FIXED);
129         TreeViewColumn* col_length = manage (new TreeViewColumn ("", _columns.length));
130         col_length->set_fixed_width (bbt_width);
131         col_length->set_sizing (TREE_VIEW_COLUMN_FIXED);
132         TreeViewColumn* col_sync = manage (new TreeViewColumn ("", _columns.sync));
133         col_sync->set_fixed_width (bbt_width);
134         col_sync->set_sizing (TREE_VIEW_COLUMN_FIXED);
135         TreeViewColumn* col_fadein = manage (new TreeViewColumn ("", _columns.fadein));
136         col_fadein->set_fixed_width (bbt_width);
137         col_fadein->set_sizing (TREE_VIEW_COLUMN_FIXED);
138         TreeViewColumn* col_fadeout = manage (new TreeViewColumn ("", _columns.fadeout));
139         col_fadeout->set_fixed_width (bbt_width);
140         col_fadeout->set_sizing (TREE_VIEW_COLUMN_FIXED);
141         TreeViewColumn* col_locked = manage (new TreeViewColumn ("", _columns.locked));
142         col_locked->set_fixed_width (check_width);
143         col_locked->set_sizing (TREE_VIEW_COLUMN_FIXED);
144         TreeViewColumn* col_glued = manage (new TreeViewColumn ("", _columns.glued));
145         col_glued->set_fixed_width (check_width);
146         col_glued->set_sizing (TREE_VIEW_COLUMN_FIXED);
147         TreeViewColumn* col_muted = manage (new TreeViewColumn ("", _columns.muted));
148         col_muted->set_fixed_width (check_width);
149         col_muted->set_sizing (TREE_VIEW_COLUMN_FIXED);
150         TreeViewColumn* col_opaque = manage (new TreeViewColumn ("", _columns.opaque));
151         col_opaque->set_fixed_width (check_width);
152         col_opaque->set_sizing (TREE_VIEW_COLUMN_FIXED);
153
154         _display.append_column (*col_name);
155         _display.append_column (*col_tags);
156         _display.append_column (*col_start);
157         _display.append_column (*col_length);
158         _display.append_column (*col_locked);
159         _display.append_column (*col_glued);
160         _display.append_column (*col_muted);
161         _display.append_column (*col_opaque);
162
163 #ifdef SHOW_REGION_EXTRAS
164         _display.append_column (*col_end);
165         _display.append_column (*col_sync);
166         _display.append_column (*col_fadein);
167         _display.append_column (*col_fadeout);
168 #endif
169
170         TreeViewColumn* col;
171         Gtk::Label*     l;
172
173         /* clang-format off */
174         ColumnInfo ci[] = {
175                 { 0,  0,  ALIGN_LEFT,    _("Region"),    _("Region name, with number of channels in []'s") },
176                 { 1,  1,  ALIGN_LEFT,    _("Tags"),      _("Tags") },
177                 { 2, 15,  ALIGN_RIGHT,   _("Start"),     _("Position of start of region") },
178                 { 3,  3,  ALIGN_RIGHT,   _("Length"),    _("Length of the region") },
179                 { 4, -1,  ALIGN_CENTER, S_("Lock|L"),    _("Region position locked?") },
180                 { 5, -1,  ALIGN_CENTER, S_("Glued|G"),   _("Region position glued to Bars|Beats time?") },
181                 { 6, -1,  ALIGN_CENTER, S_("Mute|M"),    _("Region muted?") },
182                 { 7, -1,  ALIGN_CENTER, S_("Opaque|O"),  _("Region opaque (blocks regions below it from being heard)?") },
183 #ifdef SHOW_REGION_EXTRAS
184                 { 8,  4,  ALIGN_RIGHT,  _("End"),       _("Position of end of region") },
185                 { 9, -1,  ALIGN_RIGHT,  _("Sync"),      _("Position of region sync point, relative to start of the region") },
186                 { 10,-1,  ALIGN_RIGHT,  _("Fade In"),   _("Length of region fade-in (units: secondary clock), () if disabled") },
187                 { 11,-1,  ALIGN_RIGHT,  _("Fade Out"),  _("Length of region fade-out (units: secondary clock), () if disabled") },
188 #endif
189                 { -1,-1,  ALIGN_CENTER, 0, 0 }
190         };
191         /* clang-format on */
192
193         for (int i = 0; ci[i].index >= 0; ++i) {
194                 col = _display.get_column (ci[i].index);
195
196                 /* add the label */
197                 l = manage (new Label (ci[i].label));
198                 l->set_alignment (ci[i].al);
199                 set_tooltip (*l, ci[i].tooltip);
200                 col->set_widget (*l);
201                 l->show ();
202
203                 col->set_sort_column (ci[i].sort_idx);
204
205                 col->set_expand (false);
206
207                 /* this sets the alignment of the column header... */
208                 col->set_alignment (ci[i].al);
209
210                 /* ...and this sets the alignment for the data cells */
211                 CellRendererText* renderer = dynamic_cast<CellRendererText*> (_display.get_column_cell_renderer (i));
212                 if (renderer) {
213                         renderer->property_xalign () = (ci[i].al == ALIGN_RIGHT ? 1.0 : (ci[i].al == ALIGN_LEFT ? 0.0 : 0.5));
214                 }
215         }
216
217         _display.set_model (_model);
218
219         _display.set_headers_visible (true);
220         _display.set_rules_hint ();
221
222         if (UIConfiguration::instance ().get_use_tooltips ()) {
223                 /* show path as the row tooltip */
224                 _display.set_tooltip_column (12); /* path */
225         }
226         _display.get_selection ()->set_select_function (sigc::mem_fun (*this, &EditorRegions::selection_filter));
227
228         /* Name cell: make editable */
229         CellRendererText* region_name_cell     = dynamic_cast<CellRendererText*> (_display.get_column_cell_renderer (0));
230         region_name_cell->property_editable () = true;
231         region_name_cell->signal_edited ().connect (sigc::mem_fun (*this, &EditorRegions::name_edit));
232         region_name_cell->signal_editing_started ().connect (sigc::mem_fun (*this, &EditorRegions::name_editing_started));
233
234         /* Region Name: color turns red if source is missing. */
235         TreeViewColumn*   tv_col   = _display.get_column (0);
236         CellRendererText* renderer = dynamic_cast<CellRendererText*> (_display.get_column_cell_renderer (0));
237         tv_col->add_attribute (renderer->property_text (), _columns.name);
238         tv_col->add_attribute (renderer->property_foreground_gdk (), _columns.color_);
239         tv_col->set_expand (true);
240
241         /* Tags cell: make editable */
242         CellRendererText* region_tags_cell     = dynamic_cast<CellRendererText*> (_display.get_column_cell_renderer (1));
243         region_tags_cell->property_editable () = true;
244         region_tags_cell->signal_edited ().connect (sigc::mem_fun (*this, &EditorRegions::tag_edit));
245         region_tags_cell->signal_editing_started ().connect (sigc::mem_fun (*this, &EditorRegions::tag_editing_started));
246
247         /* checkbox cells */
248         int check_start_col = 4;
249
250         CellRendererToggle* locked_cell      = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (check_start_col++));
251         locked_cell->property_activatable () = true;
252         locked_cell->signal_toggled ().connect (sigc::mem_fun (*this, &EditorRegions::locked_changed));
253
254         CellRendererToggle* glued_cell      = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (check_start_col++));
255         glued_cell->property_activatable () = true;
256         glued_cell->signal_toggled ().connect (sigc::mem_fun (*this, &EditorRegions::glued_changed));
257
258         CellRendererToggle* muted_cell      = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (check_start_col++));
259         muted_cell->property_activatable () = true;
260         muted_cell->signal_toggled ().connect (sigc::mem_fun (*this, &EditorRegions::muted_changed));
261
262         CellRendererToggle* opaque_cell      = dynamic_cast<CellRendererToggle*> (_display.get_column_cell_renderer (check_start_col));
263         opaque_cell->property_activatable () = true;
264         opaque_cell->signal_toggled ().connect (sigc::mem_fun (*this, &EditorRegions::opaque_changed));
265
266         _display.get_selection ()->set_mode (SELECTION_MULTIPLE);
267         _display.add_object_drag (_columns.region.index (), "regions");
268         _display.set_drag_column (_columns.name.index ());
269
270         /* setup DnD handling */
271
272         list<TargetEntry> region_list_target_table;
273
274         region_list_target_table.push_back (TargetEntry ("text/uri-list"));
275         region_list_target_table.push_back (TargetEntry ("text/plain"));
276         region_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
277
278         _display.add_drop_targets (region_list_target_table);
279         _display.signal_drag_data_received ().connect (sigc::mem_fun (*this, &EditorRegions::drag_data_received));
280
281         _scroller.add (_display);
282         _scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
283
284         _display.signal_button_press_event ().connect (sigc::mem_fun (*this, &EditorRegions::button_press), false);
285         _change_connection = _display.get_selection ()->signal_changed ().connect (sigc::mem_fun (*this, &EditorRegions::selection_changed));
286
287         _scroller.signal_key_press_event ().connect (sigc::mem_fun (*this, &EditorRegions::key_press), false);
288         _scroller.signal_focus_in_event ().connect (sigc::mem_fun (*this, &EditorRegions::focus_in), false);
289         _scroller.signal_focus_out_event ().connect (sigc::mem_fun (*this, &EditorRegions::focus_out));
290
291         _display.signal_enter_notify_event ().connect (sigc::mem_fun (*this, &EditorRegions::enter_notify), false);
292         _display.signal_leave_notify_event ().connect (sigc::mem_fun (*this, &EditorRegions::leave_notify), false);
293
294         ARDOUR_UI::instance ()->primary_clock->mode_changed.connect (sigc::mem_fun (*this, &EditorRegions::clock_format_changed));
295
296         e->EditorFreeze.connect (editor_freeze_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::freeze_tree_model, this), gui_context ());
297         e->EditorThaw.connect (editor_thaw_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::thaw_tree_model, this), gui_context ());
298 }
299
300 bool
301 EditorRegions::focus_in (GdkEventFocus*)
302 {
303         Window* win = dynamic_cast<Window*> (_scroller.get_toplevel ());
304
305         if (win) {
306                 old_focus = win->get_focus ();
307         } else {
308                 old_focus = 0;
309         }
310
311         name_editable = 0;
312         tags_editable = 0;
313
314         /* try to do nothing on focus in (doesn't work, hence selection_count nonsense) */
315         return true;
316 }
317
318 bool
319 EditorRegions::focus_out (GdkEventFocus*)
320 {
321         if (old_focus) {
322                 old_focus->grab_focus ();
323                 old_focus = 0;
324         }
325
326         name_editable = 0;
327         tags_editable = 0;
328
329         return false;
330 }
331
332 bool
333 EditorRegions::enter_notify (GdkEventCrossing*)
334 {
335         if (name_editable || tags_editable) {
336                 return true;
337         }
338
339         Keyboard::magic_widget_grab_focus ();
340         return false;
341 }
342
343 bool
344 EditorRegions::leave_notify (GdkEventCrossing*)
345 {
346         if (old_focus) {
347                 old_focus->grab_focus ();
348                 old_focus = 0;
349         }
350
351         Keyboard::magic_widget_drop_focus ();
352         return false;
353 }
354
355 void
356 EditorRegions::set_session (ARDOUR::Session* s)
357 {
358         SessionHandlePtr::set_session (s);
359
360         ARDOUR::Region::RegionPropertyChanged.connect (region_property_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::region_changed, this, _1, _2), gui_context ());
361         ARDOUR::RegionFactory::CheckNewRegion.connect (check_new_region_connection, MISSING_INVALIDATOR, boost::bind (&EditorRegions::add_region, this, _1), gui_context ());
362
363         redisplay ();
364 }
365
366 void
367 EditorRegions::add_region (boost::shared_ptr<Region> region)
368 {
369         if (!region || !_session) {
370                 return;
371         }
372
373         /* whole-file regions are shown in the Source List */
374         if (region->whole_file ()) {
375                 return;
376         }
377
378         PropertyChange pc;
379         region_changed (region, pc);
380 }
381
382 void
383 EditorRegions::destroy_region (boost::shared_ptr<ARDOUR::Region> region)
384 {
385         //UNTESTED
386         //At the time of writing, the only way to remove regions is "cleanup"
387         //by definition, "cleanup" only removes regions that aren't on the timeline
388         //so this would be a no-op anyway
389         //perhaps someday we will allow users to manually destroy regions.
390         RegionRowMap::iterator map_it = region_row_map.find (region);
391         if (map_it != region_row_map.end ()) {
392                 region_row_map.erase (map_it);
393                 _model->erase (map_it->second);
394         }
395 }
396
397 void
398 EditorRegions::remove_unused_regions ()
399 {
400         vector<string> choices;
401         string         prompt;
402
403         if (!_session) {
404                 return;
405         }
406
407         prompt = _ ("Do you really want to remove unused regions?"
408                     "\n(This is destructive and cannot be undone)");
409
410         choices.push_back (_ ("No, do nothing."));
411         choices.push_back (_ ("Yes, remove."));
412
413         ArdourWidgets::Choice prompter (_ ("Remove unused regions"), prompt, choices);
414
415         if (prompter.run () == 1) {
416                 _no_redisplay = true;
417                 _session->cleanup_regions ();
418                 _no_redisplay = false;
419                 redisplay ();
420         }
421 }
422
423 void
424 EditorRegions::region_changed (boost::shared_ptr<Region> r, const PropertyChange& what_changed)
425 {
426         RegionRowMap::iterator map_it = region_row_map.find (r);
427
428         boost::shared_ptr<ARDOUR::Playlist> pl = r->playlist ();
429         if (!(pl && _session && _session->playlist_is_active (pl))) {
430                 /* this region is not on an active playlist
431                  * maybe it got deleted, or whatever */
432                 if (map_it != region_row_map.end ()) {
433                         region_row_map.erase (map_it);
434                         _model->erase (map_it->second);
435                 }
436                 return;
437         }
438
439         if (map_it != region_row_map.end ()) {
440                 /* found the region, update its row properties */
441                 TreeModel::Row row = *(map_it->second);
442                 populate_row (r, row, what_changed);
443
444         } else {
445                 /* new region, add it to the list */
446                 TreeModel::iterator iter = _model->append ();
447                 TreeModel::Row      row  = *iter;
448                 region_row_map.insert (pair<boost::shared_ptr<ARDOUR::Region>, Gtk::TreeModel::iterator> (r, iter));
449
450                 /* set the properties that don't change */
451                 row[_columns.region] = r;
452
453                 /* now populate the properties that might change... */
454                 populate_row (r, row, PropertyChange ());
455         }
456 }
457
458 void
459 EditorRegions::selection_changed ()
460 {
461         _editor->_region_selection_change_updates_region_list = false;
462
463         if (_display.get_selection ()->count_selected_rows () > 0) {
464                 TreeIter                             iter;
465                 TreeView::Selection::ListHandle_Path rows = _display.get_selection ()->get_selected_rows ();
466
467                 _editor->get_selection ().clear_regions ();
468
469                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin (); i != rows.end (); ++i) {
470                         if ((iter = _model->get_iter (*i))) {
471                                 boost::shared_ptr<Region> region = (*iter)[_columns.region];
472
473                                 // they could have clicked on a row that is just a placeholder, like "Hidden"
474                                 // although that is not allowed by our selection filter. check it anyway
475                                 // since we need a region ptr.
476
477                                 if (region) {
478                                         _change_connection.block (true);
479                                         _editor->set_selected_regionview_from_region_list (region, Selection::Add);
480                                         _change_connection.block (false);
481                                 }
482                         }
483                 }
484         } else {
485                 _editor->get_selection ().clear_regions ();
486         }
487
488         _editor->_region_selection_change_updates_region_list = true;
489 }
490
491 void
492 EditorRegions::set_selected (RegionSelection& regions)
493 {
494         for (RegionSelection::iterator i = regions.begin (); i != regions.end (); ++i) {
495                 boost::shared_ptr<Region> r ((*i)->region ());
496
497                 RegionRowMap::iterator it;
498
499                 it = region_row_map.find (r);
500
501                 if (it != region_row_map.end ()) {
502                         TreeModel::iterator j = it->second;
503                         _display.get_selection ()->select (*j);
504                 }
505         }
506 }
507
508 void
509 EditorRegions::redisplay ()
510 {
511         if (_no_redisplay || !_session) {
512                 return;
513         }
514
515         /* store sort column id and type for later */
516         int sort_col_id;
517         Gtk::SortType sort_type;
518         _model->get_sort_column_id (sort_col_id, sort_type);
519
520         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
521         _model->clear ();
522         /* Disable sorting to gain performance */
523         _model->set_sort_column (-2, SORT_ASCENDING);
524
525         region_row_map.clear ();
526
527         RegionFactory::foreach_region (sigc::mem_fun (*this, &EditorRegions::add_region));
528
529         _model->set_sort_column (sort_col_id, sort_type); // re-enabale sorting
530         _display.set_model (_model);
531 }
532
533 void
534 EditorRegions::update_row (boost::shared_ptr<Region> region)
535 {
536         if (!region || !_session) {
537                 return;
538         }
539
540         RegionRowMap::iterator it;
541
542         it = region_row_map.find (region);
543
544         if (it != region_row_map.end ()) {
545                 PropertyChange      c;
546                 TreeModel::iterator j = it->second;
547                 populate_row (region, (*j), c);
548         }
549 }
550
551 void
552 EditorRegions::clock_format_changed ()
553 {
554         if (!_session) {
555                 return;
556         }
557
558         PropertyChange change;
559         change.add (ARDOUR::Properties::start);
560         change.add (ARDOUR::Properties::length);
561         change.add (ARDOUR::Properties::position);
562         change.add (ARDOUR::Properties::sync_position);
563         change.add (ARDOUR::Properties::fade_in);
564         change.add (ARDOUR::Properties::fade_out);
565
566         RegionRowMap::iterator i;
567
568         for (i = region_row_map.begin (); i != region_row_map.end (); ++i) {
569                 TreeModel::iterator j = i->second;
570
571                 boost::shared_ptr<Region> region = (*j)[_columns.region];
572
573                 populate_row (region, (*j), change);
574         }
575 }
576
577 void
578 EditorRegions::format_position (samplepos_t pos, char* buf, size_t bufsize, bool onoff)
579 {
580         Timecode::BBT_Time bbt;
581         Timecode::Time     timecode;
582
583         if (pos < 0) {
584                 error << string_compose (_ ("EditorRegions::format_position: negative timecode position: %1"), pos) << endmsg;
585                 snprintf (buf, bufsize, "invalid");
586                 return;
587         }
588
589         switch (ARDOUR_UI::instance ()->primary_clock->mode ()) {
590                 case AudioClock::BBT:
591                         bbt = _session->tempo_map ().bbt_at_sample (pos);
592                         if (onoff) {
593                                 snprintf (buf, bufsize, "%03d|%02d|%04d", bbt.bars, bbt.beats, bbt.ticks);
594                         } else {
595                                 snprintf (buf, bufsize, "(%03d|%02d|%04d)", bbt.bars, bbt.beats, bbt.ticks);
596                         }
597                         break;
598
599                 case AudioClock::MinSec:
600                         samplepos_t left;
601                         int         hrs;
602                         int         mins;
603                         float       secs;
604
605                         left = pos;
606                         hrs  = (int)floor (left / (_session->sample_rate () * 60.0f * 60.0f));
607                         left -= (samplecnt_t)floor (hrs * _session->sample_rate () * 60.0f * 60.0f);
608                         mins = (int)floor (left / (_session->sample_rate () * 60.0f));
609                         left -= (samplecnt_t)floor (mins * _session->sample_rate () * 60.0f);
610                         secs = left / (float)_session->sample_rate ();
611                         if (onoff) {
612                                 snprintf (buf, bufsize, "%02d:%02d:%06.3f", hrs, mins, secs);
613                         } else {
614                                 snprintf (buf, bufsize, "(%02d:%02d:%06.3f)", hrs, mins, secs);
615                         }
616                         break;
617
618                 case AudioClock::Seconds:
619                         if (onoff) {
620                                 snprintf (buf, bufsize, "%.1f", pos / (float)_session->sample_rate ());
621                         } else {
622                                 snprintf (buf, bufsize, "(%.1f)", pos / (float)_session->sample_rate ());
623                         }
624                         break;
625
626                 case AudioClock::Samples:
627                         if (onoff) {
628                                 snprintf (buf, bufsize, "%" PRId64, pos);
629                         } else {
630                                 snprintf (buf, bufsize, "(%" PRId64 ")", pos);
631                         }
632                         break;
633
634                 case AudioClock::Timecode:
635                 default:
636                         _session->timecode_time (pos, timecode);
637                         if (onoff) {
638                                 snprintf (buf, bufsize, "%02d:%02d:%02d:%02d", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
639                         } else {
640                                 snprintf (buf, bufsize, "(%02d:%02d:%02d:%02d)", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
641                         }
642                         break;
643         }
644 }
645
646 void
647 EditorRegions::populate_row (boost::shared_ptr<Region> region, TreeModel::Row const& row, PBD::PropertyChange const& what_changed)
648 {
649         /* the grid is most interested in the regions that are *visible* in the editor.
650          * this is a convenient place to flag changes to the grid cache, on a visible region */
651         PropertyChange grid_interests;
652         grid_interests.add (ARDOUR::Properties::position);
653         grid_interests.add (ARDOUR::Properties::length);
654         grid_interests.add (ARDOUR::Properties::sync_position);
655         if (what_changed.contains (grid_interests)) {
656                 _editor->mark_region_boundary_cache_dirty ();
657         }
658
659         {
660                 Gdk::Color c;
661                 bool       missing_source = boost::dynamic_pointer_cast<SilentFileSource> (region->source ()) != NULL;
662                 if (missing_source) {
663                         set_color_from_rgba (c, UIConfiguration::instance ().color ("region list missing source"));
664                 } else {
665                         set_color_from_rgba (c, UIConfiguration::instance ().color ("region list whole file"));
666                 }
667                 row[_columns.color_] = c;
668         }
669
670         boost::shared_ptr<AudioRegion> audioregion = boost::dynamic_pointer_cast<AudioRegion> (region);
671
672         PropertyChange c;
673         const bool     all = what_changed == c;
674
675         if (all || what_changed.contains (Properties::position)) {
676                 populate_row_position (region, row);
677         }
678         if (all || what_changed.contains (Properties::start) || what_changed.contains (Properties::sync_position)) {
679                 populate_row_sync (region, row);
680         }
681         if (all || what_changed.contains (Properties::fade_in)) {
682                 populate_row_fade_in (region, row, audioregion);
683         }
684         if (all || what_changed.contains (Properties::fade_out)) {
685                 populate_row_fade_out (region, row, audioregion);
686         }
687         if (all || what_changed.contains (Properties::locked)) {
688                 populate_row_locked (region, row);
689         }
690         if (all || what_changed.contains (Properties::position_lock_style)) {
691                 populate_row_glued (region, row);
692         }
693         if (all || what_changed.contains (Properties::muted)) {
694                 populate_row_muted (region, row);
695         }
696         if (all || what_changed.contains (Properties::opaque)) {
697                 populate_row_opaque (region, row);
698         }
699         if (all || what_changed.contains (Properties::length)) {
700                 populate_row_end (region, row);
701                 populate_row_length (region, row);
702         }
703         if (all) {
704                 populate_row_source (region, row);
705         }
706         if (all || what_changed.contains (Properties::name) || what_changed.contains (Properties::tags)) {
707                 populate_row_name (region, row);
708         }
709 }
710
711 #if 0
712         if (audioRegion && fades_in_seconds) {
713
714                 samplepos_t left;
715                 int mins;
716                 int millisecs;
717
718                 left = audioRegion->fade_in()->back()->when;
719                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
720                 left -= (samplepos_t) floor (mins * _session->sample_rate() * 60.0f);
721                 millisecs = (int) floor ((left * 1000.0f) / _session->sample_rate());
722
723                 if (audioRegion->fade_in()->back()->when >= _session->sample_rate()) {
724                         sprintf (fadein_str, "%01dM %01dmS", mins, millisecs);
725                 } else {
726                         sprintf (fadein_str, "%01dmS", millisecs);
727                 }
728
729                 left = audioRegion->fade_out()->back()->when;
730                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
731                 left -= (samplepos_t) floor (mins * _session->sample_rate() * 60.0f);
732                 millisecs = (int) floor ((left * 1000.0f) / _session->sample_rate());
733
734                 if (audioRegion->fade_out()->back()->when >= _session->sample_rate()) {
735                         sprintf (fadeout_str, "%01dM %01dmS", mins, millisecs);
736                 } else {
737                         sprintf (fadeout_str, "%01dmS", millisecs);
738                 }
739         }
740 #endif
741
742 void
743 EditorRegions::populate_row_length (boost::shared_ptr<Region> region, TreeModel::Row const& row)
744 {
745         char buf[16];
746
747         if (ARDOUR_UI::instance ()->primary_clock->mode () == AudioClock::BBT) {
748                 TempoMap&          map (_session->tempo_map ());
749                 Timecode::BBT_Time bbt = map.bbt_at_beat (map.beat_at_sample (region->last_sample ()) - map.beat_at_sample (region->first_sample ()));
750                 snprintf (buf, sizeof (buf), "%03d|%02d|%04d", bbt.bars, bbt.beats, bbt.ticks);
751         } else {
752                 format_position (region->length (), buf, sizeof (buf));
753         }
754
755         row[_columns.length] = buf;
756 }
757
758 void
759 EditorRegions::populate_row_end (boost::shared_ptr<Region> region, TreeModel::Row const& row)
760 {
761 #ifndef SHOW_REGION_EXTRAS
762         return;
763 #endif
764
765         if (region->last_sample () >= region->first_sample ()) {
766                 char buf[16];
767                 format_position (region->last_sample (), buf, sizeof (buf));
768                 row[_columns.end] = buf;
769         } else {
770                 row[_columns.end] = "empty";
771         }
772 }
773
774 void
775 EditorRegions::populate_row_position (boost::shared_ptr<Region> region, TreeModel::Row const& row)
776 {
777         row[_columns.position] = region->position ();
778
779         char buf[16];
780         format_position (region->position (), buf, sizeof (buf));
781         row[_columns.start] = buf;
782 }
783
784 void
785 EditorRegions::populate_row_sync (boost::shared_ptr<Region> region, TreeModel::Row const& row)
786 {
787 #ifndef SHOW_REGION_EXTRAS
788         return;
789 #endif
790         if (region->sync_position () == region->position ()) {
791                 row[_columns.sync] = _ ("Start");
792         } else if (region->sync_position () == (region->last_sample ())) {
793                 row[_columns.sync] = _ ("End");
794         } else {
795                 char buf[16];
796                 format_position (region->sync_position (), buf, sizeof (buf));
797                 row[_columns.sync] = buf;
798         }
799 }
800
801 void
802 EditorRegions::populate_row_fade_in (boost::shared_ptr<Region> region, TreeModel::Row const& row, boost::shared_ptr<AudioRegion> audioregion)
803 {
804 #ifndef SHOW_REGION_EXTRAS
805         return;
806 #endif
807         if (!audioregion) {
808                 row[_columns.fadein] = "";
809         } else {
810                 char buf[32];
811                 format_position (audioregion->fade_in ()->back ()->when, buf, sizeof (buf), audioregion->fade_in_active ());
812                 row[_columns.fadein] = buf;
813         }
814 }
815
816 void
817 EditorRegions::populate_row_fade_out (boost::shared_ptr<Region> region, TreeModel::Row const& row, boost::shared_ptr<AudioRegion> audioregion)
818 {
819 #ifndef SHOW_REGION_EXTRAS
820         return;
821 #endif
822         if (!audioregion) {
823                 row[_columns.fadeout] = "";
824         } else {
825                 char buf[32];
826                 format_position (audioregion->fade_out ()->back ()->when, buf, sizeof (buf), audioregion->fade_out_active ());
827                 row[_columns.fadeout] = buf;
828         }
829 }
830
831 void
832 EditorRegions::populate_row_locked (boost::shared_ptr<Region> region, TreeModel::Row const& row)
833 {
834         row[_columns.locked] = region->locked ();
835 }
836
837 void
838 EditorRegions::populate_row_glued (boost::shared_ptr<Region> region, TreeModel::Row const& row)
839 {
840         if (region->position_lock_style () == MusicTime) {
841                 row[_columns.glued] = true;
842         } else {
843                 row[_columns.glued] = false;
844         }
845 }
846
847 void
848 EditorRegions::populate_row_muted (boost::shared_ptr<Region> region, TreeModel::Row const& row)
849 {
850         row[_columns.muted] = region->muted ();
851 }
852
853 void
854 EditorRegions::populate_row_opaque (boost::shared_ptr<Region> region, TreeModel::Row const& row)
855 {
856         row[_columns.opaque] = region->opaque ();
857 }
858
859 void
860 EditorRegions::populate_row_name (boost::shared_ptr<Region> region, TreeModel::Row const& row)
861 {
862         if (region->n_channels () > 1) {
863                 row[_columns.name] = string_compose ("%1  [%2]", Gtkmm2ext::markup_escape_text (region->name ()), region->n_channels ());
864         } else {
865                 row[_columns.name] = Gtkmm2ext::markup_escape_text (region->name ());
866         }
867
868         row[_columns.tags] = region->tags ();
869 }
870
871 void
872 EditorRegions::populate_row_source (boost::shared_ptr<Region> region, TreeModel::Row const& row)
873 {
874         if (boost::dynamic_pointer_cast<SilentFileSource> (region->source ())) {
875                 row[_columns.path] = _ ("MISSING ") + Gtkmm2ext::markup_escape_text (region->source ()->name ());
876         } else {
877                 row[_columns.path] = Gtkmm2ext::markup_escape_text (region->source ()->name ());
878         }
879 }
880
881 void
882 EditorRegions::show_context_menu (int button, int time)
883 {
884         using namespace Gtk::Menu_Helpers;
885         Gtk::Menu* menu = dynamic_cast<Menu*> (ActionManager::get_widget (X_ ("/PopupRegionMenu")));
886         menu->popup (button, time);
887 }
888
889 bool
890 EditorRegions::key_press (GdkEventKey* ev)
891 {
892         TreeViewColumn* col;
893
894         switch (ev->keyval) {
895                 case GDK_Tab:
896                 case GDK_ISO_Left_Tab:
897
898                         if (name_editable) {
899                                 name_editable->editing_done ();
900                                 name_editable = 0;
901                         }
902
903                         if (tags_editable) {
904                                 tags_editable->editing_done ();
905                                 tags_editable = 0;
906                         }
907
908                         col = _display.get_column (0); // select&focus on name column
909
910                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
911                                 treeview_select_previous (_display, _model, col);
912                         } else {
913                                 treeview_select_next (_display, _model, col);
914                         }
915
916                         return true;
917                         break;
918
919                 default:
920                         break;
921         }
922
923         return false;
924 }
925
926 bool
927 EditorRegions::button_press (GdkEventButton* ev)
928 {
929         boost::shared_ptr<Region> region;
930         TreeIter                  iter;
931         TreeModel::Path           path;
932         TreeViewColumn*           column;
933         int                       cellx;
934         int                       celly;
935
936         if (_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
937                 if ((iter = _model->get_iter (path))) {
938                         region = (*iter)[_columns.region];
939                 }
940         }
941
942         if (Keyboard::is_context_menu_event (ev)) {
943                 show_context_menu (ev->button, ev->time);
944                 return true;
945         }
946
947         if (region != 0 && Keyboard::is_button2_event (ev)) {
948                 /* start/stop audition */
949                 if (!Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
950                         _editor->consider_auditioning (region);
951                 }
952                 return true;
953         }
954
955         return false;
956 }
957
958 void
959 EditorRegions::selection_mapover (sigc::slot<void, boost::shared_ptr<Region> > sl)
960 {
961         Glib::RefPtr<TreeSelection>                    selection = _display.get_selection ();
962         TreeView::Selection::ListHandle_Path           rows      = selection->get_selected_rows ();
963         TreeView::Selection::ListHandle_Path::iterator i         = rows.begin ();
964
965         if (selection->count_selected_rows () == 0 || _session == 0) {
966                 return;
967         }
968
969         for (; i != rows.end (); ++i) {
970                 TreeIter iter;
971
972                 if ((iter = _model->get_iter (*i))) {
973                         /* some rows don't have a region associated with them, but can still be
974                            selected (XXX maybe prevent them from being selected)
975                         */
976
977                         boost::shared_ptr<Region> r = (*iter)[_columns.region];
978
979                         if (r) {
980                                 sl (r);
981                         }
982                 }
983         }
984 }
985
986 void
987 EditorRegions::drag_data_received (const RefPtr<Gdk::DragContext>& context,
988                                    int x, int y,
989                                    const SelectionData& data,
990                                    guint info, guint time)
991 {
992         vector<string> paths;
993
994         if (data.get_target () == "GTK_TREE_MODEL_ROW") {
995                 /* something is being dragged over the region list */
996                 _editor->_drags->abort ();
997                 _display.on_drag_data_received (context, x, y, data, info, time);
998                 return;
999         }
1000
1001         if (_editor->convert_drop_to_paths (paths, context, x, y, data, info, time) == 0) {
1002                 samplepos_t pos  = 0;
1003                 bool        copy = ((context->get_actions () & (Gdk::ACTION_COPY | Gdk::ACTION_LINK | Gdk::ACTION_MOVE)) == Gdk::ACTION_COPY);
1004
1005                 if (UIConfiguration::instance ().get_only_copy_imported_files () || copy) {
1006                         _editor->do_import (paths, Editing::ImportDistinctFiles, Editing::ImportAsRegion,
1007                                             SrcBest, SMFTrackName, SMFTempoIgnore, pos);
1008                 } else {
1009                         _editor->do_embed (paths, Editing::ImportDistinctFiles, ImportAsRegion, pos);
1010                 }
1011                 context->drag_finish (true, false, time);
1012         }
1013 }
1014
1015 bool
1016 EditorRegions::selection_filter (const RefPtr<TreeModel>& model, const TreeModel::Path& path, bool already_selected)
1017 {
1018         if (already_selected) {
1019                 /* deselecting path, if it is selected, is OK */
1020                 return true;
1021         }
1022
1023         /* not possible to select rows that do not represent regions, like "Hidden" */
1024         TreeModel::iterator iter = model->get_iter (path);
1025         if (iter) {
1026                 boost::shared_ptr<Region> r = (*iter)[_columns.region];
1027                 if (!r) {
1028                         return false;
1029                 }
1030         }
1031
1032         return true;
1033 }
1034
1035 void
1036 EditorRegions::name_editing_started (CellEditable* ce, const Glib::ustring& path)
1037 {
1038         name_editable = ce;
1039
1040         /* give it a special name */
1041
1042         Gtk::Entry* e = dynamic_cast<Gtk::Entry*> (ce);
1043
1044         if (e) {
1045                 e->set_name (X_ ("RegionNameEditorEntry"));
1046
1047                 TreeIter iter;
1048                 if ((iter = _model->get_iter (path))) {
1049                         boost::shared_ptr<Region> region = (*iter)[_columns.region];
1050
1051                         if (region) {
1052                                 e->set_text (region->name ());
1053                         }
1054                 }
1055         }
1056 }
1057
1058 void
1059 EditorRegions::name_edit (const std::string& path, const std::string& new_text)
1060 {
1061         name_editable = 0;
1062
1063         boost::shared_ptr<Region> region;
1064         TreeIter                  row_iter;
1065
1066         if ((row_iter = _model->get_iter (path))) {
1067                 region                     = (*row_iter)[_columns.region];
1068                 (*row_iter)[_columns.name] = new_text;
1069         }
1070
1071         if (region) {
1072                 region->set_name (new_text);
1073
1074                 populate_row_name (region, (*row_iter));
1075         }
1076 }
1077
1078 void
1079 EditorRegions::tag_editing_started (CellEditable* ce, const Glib::ustring& path)
1080 {
1081         tags_editable = ce;
1082
1083         /* give it a special name */
1084
1085         Gtk::Entry* e = dynamic_cast<Gtk::Entry*> (ce);
1086
1087         if (e) {
1088                 e->set_name (X_ ("RegionTagEditorEntry"));
1089
1090                 TreeIter iter;
1091                 if ((iter = _model->get_iter (path))) {
1092                         boost::shared_ptr<Region> region = (*iter)[_columns.region];
1093
1094                         if (region) {
1095                                 e->set_text (region->tags ());
1096                         }
1097                 }
1098         }
1099 }
1100
1101 void
1102 EditorRegions::tag_edit (const std::string& path, const std::string& new_text)
1103 {
1104         tags_editable = 0;
1105
1106         boost::shared_ptr<Region> region;
1107         TreeIter                  row_iter;
1108
1109         if ((row_iter = _model->get_iter (path))) {
1110                 region                     = (*row_iter)[_columns.region];
1111                 (*row_iter)[_columns.tags] = new_text;
1112         }
1113
1114         if (region) {
1115                 region->set_tags (new_text);
1116
1117                 populate_row_name (region, (*row_iter));
1118         }
1119 }
1120
1121 /** @return Region that has been dragged out of the list, or 0 */
1122 boost::shared_ptr<Region>
1123 EditorRegions::get_dragged_region ()
1124 {
1125         list<boost::shared_ptr<Region> > regions;
1126         TreeView*                        source;
1127         _display.get_object_drag_data (regions, &source);
1128
1129         if (regions.empty ()) {
1130                 return boost::shared_ptr<Region> ();
1131         }
1132
1133         assert (regions.size () == 1);
1134         return regions.front ();
1135 }
1136
1137 void
1138 EditorRegions::clear ()
1139 {
1140         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1141         _model->clear ();
1142         _display.set_model (_model);
1143
1144         /* Clean up the maps */
1145         region_row_map.clear ();
1146 }
1147
1148 boost::shared_ptr<Region>
1149 EditorRegions::get_single_selection ()
1150 {
1151         Glib::RefPtr<TreeSelection> selected = _display.get_selection ();
1152
1153         if (selected->count_selected_rows () != 1) {
1154                 return boost::shared_ptr<Region> ();
1155         }
1156
1157         TreeView::Selection::ListHandle_Path rows = selected->get_selected_rows ();
1158
1159         /* only one row selected, so rows.begin() is it */
1160
1161         TreeIter iter = _model->get_iter (*rows.begin ());
1162
1163         if (!iter) {
1164                 return boost::shared_ptr<Region> ();
1165         }
1166
1167         return (*iter)[_columns.region];
1168 }
1169
1170 void
1171 EditorRegions::freeze_tree_model ()
1172 {
1173         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
1174         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
1175 }
1176
1177 void
1178 EditorRegions::thaw_tree_model ()
1179 {
1180         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
1181         _display.set_model (_model);
1182 }
1183
1184 void
1185 EditorRegions::locked_changed (std::string const& path)
1186 {
1187         TreeIter i = _model->get_iter (path);
1188         if (i) {
1189                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1190                 if (region) {
1191                         region->set_locked (!(*i)[_columns.locked]);
1192                 }
1193         }
1194 }
1195
1196 void
1197 EditorRegions::glued_changed (std::string const& path)
1198 {
1199         TreeIter i = _model->get_iter (path);
1200         if (i) {
1201                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1202                 if (region) {
1203                         /* `glued' means MusicTime, and we're toggling here */
1204                         region->set_position_lock_style ((*i)[_columns.glued] ? AudioTime : MusicTime);
1205                 }
1206         }
1207 }
1208
1209 void
1210 EditorRegions::muted_changed (std::string const& path)
1211 {
1212         TreeIter i = _model->get_iter (path);
1213         if (i) {
1214                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1215                 if (region) {
1216                         region->set_muted (!(*i)[_columns.muted]);
1217                 }
1218         }
1219 }
1220
1221 void
1222 EditorRegions::opaque_changed (std::string const& path)
1223 {
1224         TreeIter i = _model->get_iter (path);
1225         if (i) {
1226                 boost::shared_ptr<ARDOUR::Region> region = (*i)[_columns.region];
1227                 if (region) {
1228                         region->set_opaque (!(*i)[_columns.opaque]);
1229                 }
1230         }
1231 }
1232
1233 XMLNode&
1234 EditorRegions::get_state () const
1235 {
1236         XMLNode* node = new XMLNode (X_ ("RegionList"));
1237
1238         //TODO:  save sort state?
1239         //      node->set_property (X_("sort-col"), _sort_type);
1240         //      node->set_property (X_("sort-asc"), _sort_type);
1241
1242         return *node;
1243 }
1244
1245 void
1246 EditorRegions::set_state (const XMLNode& node)
1247 {
1248         bool changed = false;
1249
1250         if (node.name () != X_ ("RegionList")) {
1251                 return;
1252         }
1253
1254         if (changed) {
1255                 redisplay ();
1256         }
1257 }
1258
1259 RefPtr<Action>
1260 EditorRegions::remove_unused_regions_action () const
1261 {
1262         return ActionManager::get_action (X_ ("RegionList"), X_ ("removeUnusedRegions"));
1263 }