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