Vkeybd: add a mod-wheel
[ardour.git] / gtk2_ardour / editor_sources.cc
1 /*
2  * Copyright (C) 2018-2019 Ben Loftis <ben@harrisonconsoles.com>
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 along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <cstdlib>
20 #include <cmath>
21 #include <algorithm>
22 #include <string>
23 #include <sstream>
24
25 #include "pbd/basename.h"
26 #include "pbd/enumwriter.h"
27 #include "pbd/file_utils.h"
28
29 #include "ardour/audioregion.h"
30 #include "ardour/source.h"
31 #include "ardour/audiofilesource.h"
32 #include "ardour/silentfilesource.h"
33 #include "ardour/smf_source.h"
34 #include "ardour/region_factory.h"
35 #include "ardour/session.h"
36 #include "ardour/session_directory.h"
37 #include "ardour/profile.h"
38
39 #include "gtkmm2ext/treeutils.h"
40 #include "gtkmm2ext/utils.h"
41
42 #include "widgets/choice.h"
43 #include "widgets/tooltips.h"
44
45 #include "audio_clock.h"
46 #include "context_menu_helper.h"
47 #include "editor.h"
48 #include "editing.h"
49 #include "editing_convert.h"
50 #include "keyboard.h"
51 #include "ardour_ui.h"
52 #include "gui_thread.h"
53 #include "actions.h"
54 #include "region_view.h"
55 #include "utils.h"
56 #include "editor_drag.h"
57 #include "main_clock.h"
58 #include "ui_config.h"
59
60 #include "pbd/i18n.h"
61
62 #include "editor_sources.h"
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace ArdourWidgets;
67 using namespace ARDOUR_UI_UTILS;
68 using namespace PBD;
69 using namespace Gtk;
70 using namespace Glib;
71 using namespace Editing;
72 using Gtkmm2ext::Keyboard;
73
74 struct ColumnInfo {
75         int         index;
76         const char* label;
77         const char* tooltip;
78 };
79
80 EditorSources::EditorSources (Editor* e)
81         : EditorComponent (e)
82         , old_focus (0)
83         , tags_editable (0)
84         , _menu (0)
85         , _selection (0)
86         , _no_redisplay (false)
87 {
88         _display.set_size_request (100, -1);
89         _display.set_rules_hint (true);
90         _display.set_name ("SourcesList");
91         _display.set_fixed_height_mode (true);
92
93         /* Try to prevent single mouse presses from initiating edits.
94            This relies on a hack in gtktreeview.c:gtk_treeview_button_press()
95         */
96         _display.set_data ("mouse-edits-require-mod1", (gpointer) 0x1);
97
98         _model = TreeStore::create (_columns);
99         _model->set_sort_column (0, SORT_ASCENDING);
100
101         /* column widths */
102         int bbt_width, date_width, height;
103
104         Glib::RefPtr<Pango::Layout> layout = _display.create_pango_layout (X_("000|000|000"));
105         Gtkmm2ext::get_pixel_size (layout, bbt_width, height);
106
107         Glib::RefPtr<Pango::Layout> layout2 = _display.create_pango_layout (X_("2018-10-14 12:12:30"));
108         Gtkmm2ext::get_pixel_size (layout2, date_width, height);
109
110         TreeViewColumn* col_name = manage (new TreeViewColumn ("", _columns.name));
111         col_name->set_fixed_width (bbt_width*2);
112         col_name->set_sizing (TREE_VIEW_COLUMN_FIXED);
113         col_name->set_sort_column(0);
114
115         TreeViewColumn* col_tags = manage (new TreeViewColumn ("", _columns.tags));
116         col_tags->set_fixed_width (bbt_width*2);
117         col_tags->set_sizing (TREE_VIEW_COLUMN_FIXED);
118
119         TreeViewColumn* col_take_id = manage (new TreeViewColumn ("", _columns.take_id));
120         col_take_id->set_fixed_width (date_width);
121         col_take_id->set_sizing (TREE_VIEW_COLUMN_FIXED);
122         col_take_id->set_sort_column(1);
123
124         TreeViewColumn* col_nat_pos = manage (new TreeViewColumn ("", _columns.natural_pos));
125         col_nat_pos->set_fixed_width (bbt_width);
126         col_nat_pos->set_sizing (TREE_VIEW_COLUMN_FIXED);
127         col_nat_pos->set_sort_column(6);
128
129         TreeViewColumn* col_path = manage (new TreeViewColumn ("", _columns.path));
130         col_path->set_fixed_width (bbt_width);
131         col_path->set_sizing (TREE_VIEW_COLUMN_FIXED);
132         col_path->set_sort_column(3);
133
134         _display.append_column (*col_name);
135         _display.append_column (*col_tags);
136         _display.append_column (*col_take_id);
137         _display.append_column (*col_nat_pos);
138         _display.append_column (*col_path);
139
140         TreeViewColumn* col;
141         Gtk::Label* l;
142
143         ColumnInfo ci[] = {
144                 { 0,   _("Source"),    _("Source name, with number of channels in []'s") },
145                 { 1,   _("Tags"),      _("Tags") },
146                 { 2,   _("Take ID"),   _("Take ID") },
147                 { 3,   _("Orig Pos"),  _("Original Position of the file on timeline, when it was recorded") },
148                 { 4,   _("Path"),      _("Path (folder) of the file locationlosition of end of region") },
149                 { -1, 0, 0 }
150         };
151
152         for (int i = 0; ci[i].index >= 0; ++i) {
153                 col = _display.get_column (ci[i].index);
154                 l = manage (new Label (ci[i].label));
155                 set_tooltip (*l, ci[i].tooltip);
156                 col->set_widget (*l);
157                 l->show ();
158         }
159         _display.set_model (_model);
160
161         _display.set_headers_visible (true);
162         _display.set_rules_hint ();
163
164         //set the color of the name field
165         TreeViewColumn* tv_col = _display.get_column(0);
166         CellRendererText* renderer = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (0));
167         tv_col->add_attribute(renderer->property_text(), _columns.name);
168         tv_col->add_attribute(renderer->property_foreground_gdk(), _columns.color_);
169
170         //Tags cell: make editable
171         CellRendererText* region_tags_cell = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (1));
172         region_tags_cell->property_editable() = true;
173         region_tags_cell->signal_edited().connect (sigc::mem_fun (*this, &EditorSources::tag_edit));
174         region_tags_cell->signal_editing_started().connect (sigc::mem_fun (*this, &EditorSources::tag_editing_started));
175
176         //right-align the Natural Pos column
177         TreeViewColumn* nat_col = _display.get_column(3);
178         nat_col->set_alignment (ALIGN_RIGHT);
179         renderer = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (3));
180         if (renderer) {
181                 renderer->property_xalign() = ( 1.0 );
182         }
183
184         //the PATH field should expand when the pane is opened wider
185         tv_col = _display.get_column(4);
186         renderer = dynamic_cast<CellRendererText*>(_display.get_column_cell_renderer (4));
187         tv_col->add_attribute(renderer->property_text(), _columns.path);
188         tv_col->set_expand (true);
189
190         _display.get_selection()->set_mode (SELECTION_MULTIPLE);
191         _display.add_object_drag (_columns.region.index(), "regions");
192         _display.set_drag_column (_columns.name.index());
193
194         /* setup DnD handling */
195
196         list<TargetEntry> source_list_target_table;
197
198         source_list_target_table.push_back (TargetEntry ("text/plain"));
199         source_list_target_table.push_back (TargetEntry ("text/uri-list"));
200         source_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
201
202         _display.add_drop_targets (source_list_target_table);
203         _display.signal_drag_data_received().connect (sigc::mem_fun(*this, &EditorSources::drag_data_received));
204
205         _scroller.add (_display);
206         _scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
207
208         _display.signal_button_press_event().connect (sigc::mem_fun(*this, &EditorSources::button_press), false);
209         _change_connection = _display.get_selection()->signal_changed().connect (sigc::mem_fun(*this, &EditorSources::selection_changed));
210
211         _scroller.signal_key_press_event().connect (sigc::mem_fun(*this, &EditorSources::key_press), false);
212         _scroller.signal_focus_in_event().connect (sigc::mem_fun (*this, &EditorSources::focus_in), false);
213         _scroller.signal_focus_out_event().connect (sigc::mem_fun (*this, &EditorSources::focus_out));
214
215         _display.signal_enter_notify_event().connect (sigc::mem_fun (*this, &EditorSources::enter_notify), false);
216         _display.signal_leave_notify_event().connect (sigc::mem_fun (*this, &EditorSources::leave_notify), false);
217
218         ARDOUR_UI::instance()->primary_clock->mode_changed.connect (sigc::mem_fun(*this, &EditorSources::clock_format_changed));
219
220         e->EditorFreeze.connect (editor_freeze_connection, MISSING_INVALIDATOR, boost::bind (&EditorSources::freeze_tree_model, this), gui_context());
221         e->EditorThaw.connect (editor_thaw_connection, MISSING_INVALIDATOR, boost::bind (&EditorSources::thaw_tree_model, this), gui_context());
222 }
223
224 bool
225 EditorSources::focus_in (GdkEventFocus*)
226 {
227         Window* win = dynamic_cast<Window*> (_scroller.get_toplevel ());
228
229         if (win) {
230                 old_focus = win->get_focus ();
231         } else {
232                 old_focus = 0;
233         }
234
235         tags_editable = 0;
236
237         /* try to do nothing on focus in (doesn't work, hence selection_count nonsense) */
238         return true;
239 }
240
241 bool
242 EditorSources::focus_out (GdkEventFocus*)
243 {
244         if (old_focus) {
245                 old_focus->grab_focus ();
246                 old_focus = 0;
247         }
248
249         tags_editable = 0;
250
251         return false;
252 }
253
254 bool
255 EditorSources::enter_notify (GdkEventCrossing*)
256 {
257         if (tags_editable) {
258                 return true;
259         }
260
261         Keyboard::magic_widget_grab_focus ();
262         return false;
263 }
264
265 bool
266 EditorSources::leave_notify (GdkEventCrossing*)
267 {
268         if (old_focus) {
269                 old_focus->grab_focus ();
270                 old_focus = 0;
271         }
272
273         Keyboard::magic_widget_drop_focus ();
274         return false;
275 }
276
277 void
278 EditorSources::set_session (ARDOUR::Session* s)
279 {
280         SessionHandlePtr::set_session (s);
281
282         if (s) {
283
284                 /*  Currently, none of the displayed properties are mutable, so there is no reason to register for changes
285                  * ARDOUR::Region::RegionPropertyChanged.connect (source_property_connection, MISSING_INVALIDATOR, boost::bind (&EditorSources::source_changed, this, _1, _2), gui_context());
286                 */
287                 
288                 ARDOUR::RegionFactory::CheckNewRegion.connect (add_source_connection, MISSING_INVALIDATOR, boost::bind (&EditorSources::add_source, this, _1), gui_context());
289
290                 s->SourceRemoved.connect (remove_source_connection, MISSING_INVALIDATOR, boost::bind (&EditorSources::remove_source, this, _1), gui_context());
291
292                 redisplay();
293
294         } else {
295                 clear();
296         }
297 }
298
299 void
300 EditorSources::remove_source (boost::shared_ptr<ARDOUR::Source> source)
301 {
302         TreeModel::iterator i;
303         TreeModel::Children rows = _model->children();
304         for (i = rows.begin(); i != rows.end(); ++i) {
305                 boost::shared_ptr<ARDOUR::Region> rr = (*i)[_columns.region];
306                 if (rr->source() == source) {
307                         _model->erase(i);
308                         break;
309                 }
310         }
311 }
312
313 void
314 EditorSources::populate_row (TreeModel::Row row, boost::shared_ptr<ARDOUR::Region> region)
315 {
316         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed, row, region);
317
318         if (!region) {
319                 return;
320         }
321
322         boost::shared_ptr<ARDOUR::Source> source = region->source();  //ToDo:  is it OK to use only the first source?
323
324         //COLOR  (for missing files)
325         Gdk::Color c;
326         bool missing_source = boost::dynamic_pointer_cast<SilentFileSource>(source) != NULL;
327         if (missing_source) {
328                 set_color_from_rgba (c, UIConfiguration::instance().color ("region list missing source"));
329         } else {
330                 set_color_from_rgba (c, UIConfiguration::instance().color ("region list whole file"));
331         }
332         row[_columns.color_] = c;
333
334         //NAME
335         std::string str = region->name();
336         //if a multichannel region, show the number of channels  ToDo:  make a sortable column for this?
337         if ( region->n_channels() > 1 ) {
338                 str += string_compose("[%1]", region->n_channels());
339         }
340         row[_columns.name] = str;
341
342         //TAGS
343         row[_columns.tags] = region->tags();
344
345         row[_columns.region] = region;
346         row[_columns.take_id] = source->take_id();
347
348         //PATH
349         string pathstr = source->name();
350         if (missing_source) {
351                 pathstr = _("(MISSING) ") + Gtkmm2ext::markup_escape_text (source->name());
352         } else {
353
354                 //is it a file?
355                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource>(source);
356                 if (!fs) {
357                         pathstr = Gtkmm2ext::markup_escape_text (source->name());  //someday:  sequence region(?)
358                 } else {
359         
360                         //audio file?
361                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source);
362                         if (afs) {
363                                 const string audio_directory = _session->session_directory().sound_path();
364                                 if ( !PBD::path_is_within(audio_directory, fs->path())) {
365                                         pathstr = Gtkmm2ext::markup_escape_text (fs->path());
366                                 }
367                         }
368                         
369                         //midi file?
370                         boost::shared_ptr<SMFSource> mfs = boost::dynamic_pointer_cast<SMFSource>(source);
371                         if (mfs) {
372                                 const string midi_directory = _session->session_directory().midi_path();
373                                 if ( !PBD::path_is_within(midi_directory, fs->path())) {
374                                         pathstr = Gtkmm2ext::markup_escape_text (fs->path());
375                                 }
376                         }
377                         
378                 }
379         }
380         
381         row[_columns.path] = pathstr;
382
383         //Natural Position (samples, an invisible column for sorting)
384         row[_columns.natural_s] = source->natural_position();
385
386         //Natural Position (text representation)
387         if (source->have_natural_position()) {
388                 char buf[64];
389                 format_position (source->natural_position(), buf, sizeof (buf));
390                 row[_columns.natural_pos] = buf;
391         } else {
392                 row[_columns.natural_pos] = X_("--");
393         }
394 }
395
396 void
397 EditorSources::redisplay ()
398 {
399         if (_no_redisplay || !_session) {
400                 return;
401         }
402
403         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
404         _model->clear ();
405         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
406
407         //Ask the region factory to fill our list of whole-file regions
408         RegionFactory::foreach_region (sigc::mem_fun (*this, &EditorSources::add_source));
409
410         _model->set_sort_column (0, SORT_ASCENDING); // re-enable sorting
411         _display.set_model (_model);
412 }
413
414 void
415 EditorSources::add_source (boost::shared_ptr<ARDOUR::Region> region)
416 {
417         if (!region || !_session ) {
418                 return;
419         }
420
421         //by definition, the Source List only shows whole-file regions
422         //this roughly equates to Source objects, but preserves the stereo-ness (or multichannel-ness) of a stereo source file.
423         if ( !region->whole_file() ) {
424                 return;
425         }
426         
427         //we only show files-on-disk.  if there's some other kind of source, we ignore it (for now)
428         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (region->source());
429         if (!fs || fs->empty()) {
430                 return;
431         }
432
433         TreeModel::Row row = *(_model->append());
434         populate_row (row, region);
435 }
436
437 void
438 EditorSources::source_changed (boost::shared_ptr<ARDOUR::Region> region)
439 {
440         /* Currently never reached .. we have no mutable properties shown in the list*/
441         
442         TreeModel::iterator i;
443         TreeModel::Children rows = _model->children();
444
445         for (i = rows.begin(); i != rows.end(); ++i) {
446                 boost::shared_ptr<ARDOUR::Region> rr = (*i)[_columns.region];
447                 if (region == rr) {
448                         populate_row(*i, region);
449                         break;
450                 }
451         }
452 }
453
454 void
455 EditorSources::selection_changed ()
456 {
457
458         if (_display.get_selection()->count_selected_rows() > 0) {
459
460                 TreeIter iter;
461                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
462
463                 _editor->get_selection().clear_regions ();
464
465                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
466
467                         if ((iter = _model->get_iter (*i))) {
468
469                                 //highlight any regions in the editor that use this region's source
470                                 boost::shared_ptr<ARDOUR::Region> region = (*iter)[_columns.region];
471                                 if (!region) continue;
472
473                                 boost::shared_ptr<ARDOUR::Source> source = region->source();
474                                 if (source) {
475
476                                         set<boost::shared_ptr<Region> > regions;
477                                         RegionFactory::get_regions_using_source ( source, regions );
478
479                                         for (set<boost::shared_ptr<Region> >::iterator region = regions.begin(); region != regions.end(); region++ ) {
480                                                 _change_connection.block (true);
481                                                 _editor->set_selected_regionview_from_region_list (*region, Selection::Add);
482                                                 _change_connection.block (false);
483
484                                         }
485                                 }
486                         }
487                 }
488         } else {
489                 _editor->get_selection().clear_regions ();
490         }
491
492 }
493
494 void
495 EditorSources::clock_format_changed ()
496 {
497         TreeModel::iterator i;
498         TreeModel::Children rows = _model->children();
499         for (i = rows.begin(); i != rows.end(); ++i) {
500                 boost::shared_ptr<ARDOUR::Region> rr = (*i)[_columns.region];
501                 populate_row(*i, rr);
502         }
503 }
504
505 void
506 EditorSources::format_position (samplepos_t pos, char* buf, size_t bufsize, bool onoff)
507 {
508         Timecode::BBT_Time bbt;
509         Timecode::Time timecode;
510
511         if (pos < 0) {
512                 error << string_compose (_("EditorSources::format_position: negative timecode position: %1"), pos) << endmsg;
513                 snprintf (buf, bufsize, "invalid");
514                 return;
515         }
516
517         switch (ARDOUR_UI::instance()->primary_clock->mode ()) {
518         case AudioClock::BBT:
519                 bbt = _session->tempo_map().bbt_at_sample (pos);
520                 if (onoff) {
521                         snprintf (buf, bufsize, "%03d|%02d|%04d" , bbt.bars, bbt.beats, bbt.ticks);
522                 } else {
523                         snprintf (buf, bufsize, "(%03d|%02d|%04d)" , bbt.bars, bbt.beats, bbt.ticks);
524                 }
525                 break;
526
527         case AudioClock::MinSec:
528                 samplepos_t left;
529                 int hrs;
530                 int mins;
531                 float secs;
532
533                 left = pos;
534                 hrs = (int) floor (left / (_session->sample_rate() * 60.0f * 60.0f));
535                 left -= (samplecnt_t) floor (hrs * _session->sample_rate() * 60.0f * 60.0f);
536                 mins = (int) floor (left / (_session->sample_rate() * 60.0f));
537                 left -= (samplecnt_t) floor (mins * _session->sample_rate() * 60.0f);
538                 secs = left / (float) _session->sample_rate();
539                 if (onoff) {
540                         snprintf (buf, bufsize, "%02d:%02d:%06.3f", hrs, mins, secs);
541                 } else {
542                         snprintf (buf, bufsize, "(%02d:%02d:%06.3f)", hrs, mins, secs);
543                 }
544                 break;
545
546         case AudioClock::Seconds:
547                 if (onoff) {
548                         snprintf (buf, bufsize, "%.1f", pos / (float)_session->sample_rate());
549                 } else {
550                         snprintf (buf, bufsize, "(%.1f)", pos / (float)_session->sample_rate());
551                 }
552                 break;
553
554         case AudioClock::Samples:
555                 if (onoff) {
556                         snprintf (buf, bufsize, "%" PRId64, pos);
557                 } else {
558                         snprintf (buf, bufsize, "(%" PRId64 ")", pos);
559                 }
560                 break;
561
562         case AudioClock::Timecode:
563         default:
564                 _session->timecode_time (pos, timecode);
565                 if (onoff) {
566                         snprintf (buf, bufsize, "%02d:%02d:%02d:%02d", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
567                 } else {
568                         snprintf (buf, bufsize, "(%02d:%02d:%02d:%02d)", timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
569                 }
570                 break;
571         }
572 }
573
574 void
575 EditorSources::show_context_menu (int button, int time)
576 {
577         using namespace Gtk::Menu_Helpers;
578         Gtk::Menu* menu = ARDOUR_UI_UTILS::shared_popup_menu ();
579         MenuList&  items = menu->items();
580 #ifdef RECOVER_REGIONS_IS_WORKING
581         items.push_back(MenuElem(_("Recover the selected Sources to their original Track & Position"),
582                                                          sigc::mem_fun(*this, &EditorSources::recover_selected_sources)));
583 #endif
584         items.push_back(MenuElem(_("Remove the selected Sources"),
585                                                          sigc::mem_fun(*this, &EditorSources::remove_selected_sources)));
586         menu->popup(1, time);
587 }
588
589 void
590 EditorSources::recover_selected_sources ()
591 {
592         ARDOUR::RegionList to_be_recovered;
593         
594         if (_display.get_selection()->count_selected_rows() > 0) {
595
596                 TreeIter iter;
597                 TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
598                 for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
599                         if ((iter = _model->get_iter (*i))) {
600                                 boost::shared_ptr<ARDOUR::Region> region = (*iter)[_columns.region];
601                                 if (region) {
602                                         to_be_recovered.push_back(region);
603                                 }
604                         }
605                 }
606         }
607
608
609         /* ToDo */
610         _editor->recover_regions(to_be_recovered);  //this operation should be undo-able
611 }
612
613
614 void
615 EditorSources::remove_selected_sources ()
616 {
617         vector<string> choices;
618         string prompt;
619
620         prompt  = _("Do you want to remove the selected Sources?"
621                                 "\nThis operation cannot be undone."
622                                 "\nThe source files will not actually be deleted until you execute Session->Cleanup.");
623
624         choices.push_back (_("No, do nothing."));
625         choices.push_back (_("Only remove the Regions that use these Sources."));
626         choices.push_back (_("Yes, remove the Regions and Sources (cannot be undone!"));
627
628         Choice prompter (_("Remove selected Sources"), prompt, choices);
629
630         int opt = prompter.run ();
631
632         if ( opt >= 1) {
633                 
634                 std::list<boost::weak_ptr<ARDOUR::Source> > to_be_removed;
635                 
636                 if (_display.get_selection()->count_selected_rows() > 0) {
637
638                         TreeIter iter;
639                         TreeView::Selection::ListHandle_Path rows = _display.get_selection()->get_selected_rows ();
640
641                         _editor->get_selection().clear_regions ();
642
643                         for (TreeView::Selection::ListHandle_Path::iterator i = rows.begin(); i != rows.end(); ++i) {
644
645                                 if ((iter = _model->get_iter (*i))) {
646
647                                         boost::shared_ptr<ARDOUR::Region> region = (*iter)[_columns.region];
648         
649                                         if (!region) continue;
650
651                                         boost::shared_ptr<ARDOUR::Source> source = region->source();
652                                         if (source) {
653                                                 set<boost::shared_ptr<Region> > regions;
654                                                 RegionFactory::get_regions_using_source ( source, regions );
655
656                                                 for (set<boost::shared_ptr<Region> >::iterator region = regions.begin(); region != regions.end(); region++ ) {
657                                                         _change_connection.block (true);
658                                                         _editor->set_selected_regionview_from_region_list (*region, Selection::Add);
659                                                         _change_connection.block (false);
660                                                 }
661                                                 
662                                                 to_be_removed.push_back(source);
663                                         }
664                                 }
665
666                         }
667
668                         _editor->remove_selected_regions();  //this operation is undo-able
669
670                         if (opt==2) {   
671                                 for (std::list<boost::weak_ptr<ARDOUR::Source> >::iterator i = to_be_removed.begin(); i != to_be_removed.end(); ++i) {
672                                                 _session->remove_source(*i);  //this operation is (currently) not undo-able
673                                 }
674                         }
675                 }
676         }
677
678 }
679
680
681 bool
682 EditorSources::key_press (GdkEventKey* ev)
683 {
684         TreeViewColumn *col;
685
686         switch (ev->keyval) {
687         case GDK_Tab:
688         case GDK_ISO_Left_Tab:
689
690                 if (tags_editable) {
691                         tags_editable->editing_done ();
692                         tags_editable = 0;
693                 }
694
695                 col = _display.get_column (1); // select&focus on tags column
696
697                 if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
698                         treeview_select_previous (_display, _model, col);
699                 } else {
700                         treeview_select_next (_display, _model, col);
701                 }
702
703                 return true;
704                 break;
705
706         case GDK_BackSpace:
707                 remove_selected_sources();
708                 return true; 
709
710         default:
711                 break;
712         }
713
714         return false;
715 }
716
717 bool
718 EditorSources::button_press (GdkEventButton *ev)
719 {
720         boost::shared_ptr<ARDOUR::Region> region;
721         TreeIter iter;
722         TreeModel::Path path;
723         TreeViewColumn* column;
724         int cellx;
725         int celly;
726
727         if (_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
728                 if ((iter = _model->get_iter (path))) {
729                         region = (*iter)[_columns.region];
730                 }
731         }
732
733         if (Keyboard::is_context_menu_event (ev)) {
734                 show_context_menu (ev->button, ev->time);
735                 return false;
736         }
737
738         return false;
739 }
740
741 void
742 EditorSources::tag_editing_started (CellEditable* ce, const Glib::ustring& path)
743 {
744         tags_editable = ce;
745
746         /* give it a special name */
747
748         Gtk::Entry *e = dynamic_cast<Gtk::Entry*> (ce);
749
750         if (e) {
751                 e->set_name (X_("SourceTagEditorEntry"));
752
753                 TreeIter iter;
754                 if ((iter = _model->get_iter (path))) {
755                         boost::shared_ptr<Region> region = (*iter)[_columns.region];
756
757                         if(region) {
758                                 e->set_text(region->tags());
759                         }
760                 }
761         }
762 }
763
764 void
765 EditorSources::tag_edit (const std::string& path, const std::string& new_text)
766 {
767         tags_editable = 0;
768
769         boost::shared_ptr<Region> region;
770         TreeIter row_iter;
771
772         if ((row_iter = _model->get_iter (path))) {
773                 region = (*row_iter)[_columns.region];
774                 (*row_iter)[_columns.tags] = new_text;
775         }
776
777         if (region) {
778                 region->set_tags (new_text);
779
780                 _session->set_dirty();  //whole-file regions aren't in a playlist to catch property changes, so we need to explicitly set the session dirty
781
782                 populate_row ((*row_iter), region);
783         }
784 }
785
786
787 void
788 EditorSources::selection_mapover (sigc::slot<void,boost::shared_ptr<Region> > sl)
789 {
790
791 }
792
793
794 void
795 EditorSources::drag_data_received (const RefPtr<Gdk::DragContext>& context,
796                                    int x, int y,
797                                    const SelectionData& data,
798                                    guint info, guint time)
799 {
800         /* ToDo:  allow dropping files/loops into the source list?  */
801 }
802
803 /** @return Region that has been dragged out of the list, or 0 */
804 boost::shared_ptr<ARDOUR::Region>
805 EditorSources::get_dragged_region ()
806 {
807         list<boost::shared_ptr<ARDOUR::Region> > regions;
808         TreeView* region;
809         _display.get_object_drag_data (regions, &region);
810
811         if (regions.empty()) {
812                 return boost::shared_ptr<ARDOUR::Region> ();
813         }
814
815         assert (regions.size() == 1);
816         return regions.front ();
817 }
818
819 void
820 EditorSources::clear ()
821 {
822         _display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
823         _model->clear ();
824         _display.set_model (_model);
825 }
826
827 boost::shared_ptr<ARDOUR::Region>
828 EditorSources::get_single_selection ()
829 {
830         Glib::RefPtr<TreeSelection> selected = _display.get_selection();
831
832         if (selected->count_selected_rows() != 1) {
833                 return boost::shared_ptr<ARDOUR::Region> ();
834         }
835
836         TreeView::Selection::ListHandle_Path rows = selected->get_selected_rows ();
837
838         /* only one row selected, so rows.begin() is it */
839
840         TreeIter iter = _model->get_iter (*rows.begin());
841
842         if (!iter) {
843                 return boost::shared_ptr<ARDOUR::Region> ();
844         }
845
846         return (*iter)[_columns.region];
847 }
848
849 void
850 EditorSources::freeze_tree_model ()
851 {
852         _display.set_model (Glib::RefPtr<Gtk::TreeStore>(0));
853         _model->set_sort_column (-2, SORT_ASCENDING); //Disable sorting to gain performance
854 }
855
856 void
857 EditorSources::thaw_tree_model (){
858
859         _model->set_sort_column (0, SORT_ASCENDING); // renabale sorting
860         _display.set_model (_model);
861 }
862
863 XMLNode &
864 EditorSources::get_state () const
865 {
866         XMLNode* node = new XMLNode (X_("SourcesList"));
867
868         //TODO:  save sort state?
869
870         return *node;
871 }
872
873 void
874 EditorSources::set_state (const XMLNode & node)
875 {
876
877 }