Fix crash on clear current playlists (#3524).
[ardour.git] / gtk2_ardour / editor_ops.cc
1 /*
2     Copyright (C) 2000-2004 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 /* Note: public Editor methods are documented in public_editor.h */
21
22 #include <unistd.h>
23
24 #include <cstdlib>
25 #include <cmath>
26 #include <string>
27 #include <map>
28 #include <set>
29
30 #include "pbd/error.h"
31 #include "pbd/basename.h"
32 #include "pbd/pthread_utils.h"
33 #include "pbd/memento_command.h"
34 #include "pbd/whitespace.h"
35 #include "pbd/stateful_diff_command.h"
36
37 #include <gtkmm2ext/utils.h>
38 #include <gtkmm2ext/choice.h>
39 #include <gtkmm2ext/popup.h>
40
41 #include "ardour/audioengine.h"
42 #include "ardour/session.h"
43 #include "ardour/audioplaylist.h"
44 #include "ardour/audioregion.h"
45 #include "ardour/audio_diskstream.h"
46 #include "ardour/utils.h"
47 #include "ardour/location.h"
48 #include "ardour/audio_track.h"
49 #include "ardour/audioplaylist.h"
50 #include "ardour/region_factory.h"
51 #include "ardour/playlist_factory.h"
52 #include "ardour/reverse.h"
53 #include "ardour/transient_detector.h"
54 #include "ardour/dB.h"
55 #include "ardour/quantize.h"
56 #include "ardour/strip_silence.h"
57 #include "ardour/route_group.h"
58
59 #include "ardour_ui.h"
60 #include "editor.h"
61 #include "time_axis_view.h"
62 #include "route_time_axis.h"
63 #include "audio_time_axis.h"
64 #include "automation_time_axis.h"
65 #include "streamview.h"
66 #include "audio_streamview.h"
67 #include "audio_region_view.h"
68 #include "midi_region_view.h"
69 #include "rgb_macros.h"
70 #include "selection_templates.h"
71 #include "selection.h"
72 #include "editing.h"
73 #include "gtk-custom-hruler.h"
74 #include "gui_thread.h"
75 #include "keyboard.h"
76 #include "utils.h"
77 #include "editor_drag.h"
78 #include "strip_silence_dialog.h"
79 #include "editor_routes.h"
80 #include "editor_regions.h"
81 #include "quantize_dialog.h"
82 #include "interthread_progress_window.h"
83 #include "insert_time_dialog.h"
84 #include "normalize_dialog.h"
85
86 #include "i18n.h"
87
88 using namespace std;
89 using namespace ARDOUR;
90 using namespace PBD;
91 using namespace Gtk;
92 using namespace Gtkmm2ext;
93 using namespace Editing;
94 using Gtkmm2ext::Keyboard;
95
96 /***********************************************************************
97   Editor operations
98  ***********************************************************************/
99
100 void
101 Editor::undo (uint32_t n)
102 {
103         if (_session) {
104                 _session->undo (n);
105         }
106 }
107
108 void
109 Editor::redo (uint32_t n)
110 {
111         if (_session) {
112                 _session->redo (n);
113         }
114 }
115
116 void
117 Editor::split_regions_at (framepos_t where, RegionSelection& regions)
118 {
119         list <boost::shared_ptr<Playlist > > used_playlists;
120
121         if (regions.empty()) {
122                 return;
123         }
124
125         begin_reversible_command (_("split"));
126
127         // if splitting a single region, and snap-to is using
128         // region boundaries, don't pay attention to them
129
130         if (regions.size() == 1) {
131                 switch (_snap_type) {
132                 case SnapToRegionStart:
133                 case SnapToRegionSync:
134                 case SnapToRegionEnd:
135                         break;
136                 default:
137                         snap_to (where);
138                 }
139         } else {
140                 snap_to (where);
141         }
142
143         for (RegionSelection::iterator a = regions.begin(); a != regions.end(); ) {
144
145                 RegionSelection::iterator tmp;
146
147                 /* XXX this test needs to be more complicated, to make sure we really
148                    have something to split.
149                 */
150
151                 if (!(*a)->region()->covers (where)) {
152                         ++a;
153                         continue;
154                 }
155
156                 tmp = a;
157                 ++tmp;
158
159                 boost::shared_ptr<Playlist> pl = (*a)->region()->playlist();
160
161                 if (!pl) {
162                         a = tmp;
163                         continue;
164                 }
165
166                 if (!pl->frozen()) {
167                         /* we haven't seen this playlist before */
168
169                         /* remember used playlists so we can thaw them later */
170                         used_playlists.push_back(pl);
171                         pl->freeze();
172                 }
173
174                 if (pl) {
175                         pl->clear_changes ();
176                         pl->split_region ((*a)->region(), where);
177                         _session->add_command (new StatefulDiffCommand (pl));
178                 }
179
180                 a = tmp;
181         }
182
183         while (used_playlists.size() > 0) {
184                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
185                 (*i)->thaw();
186                 used_playlists.pop_front();
187         }
188
189         commit_reversible_command ();
190 }
191
192 boost::shared_ptr<Region>
193 Editor::select_region_for_operation (int /*dir*/, TimeAxisView **tv)
194 {
195         RegionView* rv;
196         boost::shared_ptr<Region> region;
197         framepos_t start = 0;
198
199         if (selection->time.start () == selection->time.end_frame ()) {
200
201                 /* no current selection-> is there a selected regionview? */
202
203                 if (selection->regions.empty()) {
204                         return region;
205                 }
206
207         }
208
209         if (!selection->regions.empty()) {
210
211                 rv = *(selection->regions.begin());
212                 (*tv) = &rv->get_time_axis_view();
213                 region = rv->region();
214
215         } else if (!selection->tracks.empty()) {
216
217                 (*tv) = selection->tracks.front();
218
219                 RouteTimeAxisView* rtv;
220
221                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*tv)) != 0) {
222                         boost::shared_ptr<Playlist> pl;
223
224                         if ((pl = rtv->playlist()) == 0) {
225                                 return region;
226                         }
227
228                         region = pl->top_region_at (start);
229                 }
230         }
231
232         return region;
233 }
234
235 void
236 Editor::extend_selection_to_end_of_region (bool next)
237 {
238         TimeAxisView *tv;
239         boost::shared_ptr<Region> region;
240         framepos_t start;
241
242         if ((region = select_region_for_operation (next ? 1 : 0, &tv)) == 0) {
243                 return;
244         }
245
246         if (region && selection->time.start () == selection->time.end_frame ()) {
247                 start = region->position();
248         } else {
249                 start = selection->time.start ();
250         }
251
252         begin_reversible_command (_("extend selection"));
253         selection->set (start, region->position() + region->length());
254         commit_reversible_command ();
255 }
256
257 void
258 Editor::extend_selection_to_start_of_region (bool previous)
259 {
260         TimeAxisView *tv;
261         boost::shared_ptr<Region> region;
262         framepos_t end;
263
264         if ((region = select_region_for_operation (previous ? -1 : 0, &tv)) == 0) {
265                 return;
266         }
267
268         if (region && selection->time.start () == selection->time.end_frame ()) {
269                 end = region->position() + region->length();
270         } else {
271                 end = selection->time.end_frame ();
272         }
273
274         /* Try to leave the selection with the same route if possible */
275
276         begin_reversible_command (_("extend selection"));
277         selection->set (region->position(), end);
278         commit_reversible_command ();
279 }
280
281 bool
282 Editor::nudge_forward_release (GdkEventButton* ev)
283 {
284         if (ev->state & Keyboard::PrimaryModifier) {
285                 nudge_forward (false, true);
286         } else {
287                 nudge_forward (false, false);
288         }
289         return false;
290 }
291
292 bool
293 Editor::nudge_backward_release (GdkEventButton* ev)
294 {
295         if (ev->state & Keyboard::PrimaryModifier) {
296                 nudge_backward (false, true);
297         } else {
298                 nudge_backward (false, false);
299         }
300         return false;
301 }
302
303
304 void
305 Editor::nudge_forward (bool next, bool force_playhead)
306 {
307         framepos_t distance;
308         framepos_t next_distance;
309
310         if (!_session) {
311                 return;
312         }
313
314         RegionSelection rs = get_regions_from_selection_and_entered ();
315
316         if (!force_playhead && !rs.empty()) {
317
318                 begin_reversible_command (_("nudge regions forward"));
319
320                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
321                         boost::shared_ptr<Region> r ((*i)->region());
322
323                         distance = get_nudge_distance (r->position(), next_distance);
324
325                         if (next) {
326                                 distance = next_distance;
327                         }
328
329                         r->clear_changes ();
330                         r->set_position (r->position() + distance, this);
331                         _session->add_command (new StatefulDiffCommand (r));
332                 }
333
334                 commit_reversible_command ();
335
336
337         } else if (!force_playhead && !selection->markers.empty()) {
338
339                 bool is_start;
340
341                 begin_reversible_command (_("nudge location forward"));
342
343                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
344
345                         Location* loc = find_location_from_marker ((*i), is_start);
346
347                         if (loc) {
348
349                                 XMLNode& before (loc->get_state());
350
351                                 if (is_start) {
352                                         distance = get_nudge_distance (loc->start(), next_distance);
353                                         if (next) {
354                                                 distance = next_distance;
355                                         }
356                                         if (max_framepos - distance > loc->start() + loc->length()) {
357                                                 loc->set_start (loc->start() + distance);
358                                         } else {
359                                                 loc->set_start (max_framepos - loc->length());
360                                         }
361                                 } else {
362                                         distance = get_nudge_distance (loc->end(), next_distance);
363                                         if (next) {
364                                                 distance = next_distance;
365                                         }
366                                         if (max_framepos - distance > loc->end()) {
367                                                 loc->set_end (loc->end() + distance);
368                                         } else {
369                                                 loc->set_end (max_framepos);
370                                         }
371                                 }
372                                 XMLNode& after (loc->get_state());
373                                 _session->add_command (new MementoCommand<Location>(*loc, &before, &after));
374                         }
375                 }
376
377                 commit_reversible_command ();
378
379         } else {
380                 distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
381                 _session->request_locate (playhead_cursor->current_frame + distance);
382         }
383 }
384
385 void
386 Editor::nudge_backward (bool next, bool force_playhead)
387 {
388         framepos_t distance;
389         framepos_t next_distance;
390
391         if (!_session) {
392                 return;
393         }
394
395         RegionSelection rs = get_regions_from_selection_and_entered ();
396
397         if (!force_playhead && !rs.empty()) {
398
399                 begin_reversible_command (_("nudge regions backward"));
400
401                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
402                         boost::shared_ptr<Region> r ((*i)->region());
403
404                         distance = get_nudge_distance (r->position(), next_distance);
405
406                         if (next) {
407                                 distance = next_distance;
408                         }
409                         
410                         r->clear_changes ();
411
412                         if (r->position() > distance) {
413                                 r->set_position (r->position() - distance, this);
414                         } else {
415                                 r->set_position (0, this);
416                         }
417                         _session->add_command (new StatefulDiffCommand (r));
418                 }
419
420                 commit_reversible_command ();
421
422         } else if (!force_playhead && !selection->markers.empty()) {
423
424                 bool is_start;
425
426                 begin_reversible_command (_("nudge location forward"));
427
428                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
429
430                         Location* loc = find_location_from_marker ((*i), is_start);
431
432                         if (loc) {
433
434                                 XMLNode& before (loc->get_state());
435
436                                 if (is_start) {
437                                         distance = get_nudge_distance (loc->start(), next_distance);
438                                         if (next) {
439                                                 distance = next_distance;
440                                         }
441                                         if (distance < loc->start()) {
442                                                 loc->set_start (loc->start() - distance);
443                                         } else {
444                                                 loc->set_start (0);
445                                         }
446                                 } else {
447                                         distance = get_nudge_distance (loc->end(), next_distance);
448
449                                         if (next) {
450                                                 distance = next_distance;
451                                         }
452
453                                         if (distance < loc->end() - loc->length()) {
454                                                 loc->set_end (loc->end() - distance);
455                                         } else {
456                                                 loc->set_end (loc->length());
457                                         }
458                                 }
459
460                                 XMLNode& after (loc->get_state());
461                                 _session->add_command (new MementoCommand<Location>(*loc, &before, &after));
462                         }
463                 }
464
465                 commit_reversible_command ();
466
467         } else {
468
469                 distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
470
471                 if (playhead_cursor->current_frame > distance) {
472                         _session->request_locate (playhead_cursor->current_frame - distance);
473                 } else {
474                         _session->goto_start();
475                 }
476         }
477 }
478
479 void
480 Editor::nudge_forward_capture_offset ()
481 {
482         RegionSelection rs = get_regions_from_selection_and_entered ();
483         
484         if (!_session || rs.empty()) {
485                 return;
486         }
487
488         begin_reversible_command (_("nudge forward"));
489         
490         framepos_t const distance = _session->worst_output_latency();
491         
492         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
493                 boost::shared_ptr<Region> r ((*i)->region());
494                 
495                 r->clear_changes ();
496                 r->set_position (r->position() + distance, this);
497                 _session->add_command(new StatefulDiffCommand (r));
498         }
499         
500         commit_reversible_command ();
501 }
502
503 void
504 Editor::nudge_backward_capture_offset ()
505 {
506         RegionSelection rs = get_regions_from_selection_and_entered ();
507
508         if (!_session || rs.empty()) {
509                 return;
510         }
511
512         begin_reversible_command (_("nudge forward"));
513         
514         framepos_t const distance = _session->worst_output_latency();
515
516         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
517                 boost::shared_ptr<Region> r ((*i)->region());
518                 
519                 r->clear_changes ();
520                 
521                 if (r->position() > distance) {
522                         r->set_position (r->position() - distance, this);
523                 } else {
524                         r->set_position (0, this);
525                 }
526                 _session->add_command(new StatefulDiffCommand (r));
527         }
528         
529         commit_reversible_command ();
530 }
531
532 /* DISPLAY MOTION */
533
534 void
535 Editor::move_to_start ()
536 {
537         _session->goto_start ();
538 }
539
540 void
541 Editor::move_to_end ()
542 {
543
544         _session->request_locate (_session->current_end_frame());
545 }
546
547 void
548 Editor::build_region_boundary_cache ()
549 {
550         framepos_t pos = 0;
551         vector<RegionPoint> interesting_points;
552         boost::shared_ptr<Region> r;
553         TrackViewList tracks;
554         bool at_end = false;
555
556         region_boundary_cache.clear ();
557
558         if (_session == 0) {
559                 return;
560         }
561
562         switch (_snap_type) {
563         case SnapToRegionStart:
564                 interesting_points.push_back (Start);
565                 break;
566         case SnapToRegionEnd:
567                 interesting_points.push_back (End);
568                 break;
569         case SnapToRegionSync:
570                 interesting_points.push_back (SyncPoint);
571                 break;
572         case SnapToRegionBoundary:
573                 interesting_points.push_back (Start);
574                 interesting_points.push_back (End);
575                 break;
576         default:
577                 fatal << string_compose (_("build_region_boundary_cache called with snap_type = %1"), _snap_type) << endmsg;
578                 /*NOTREACHED*/
579                 return;
580         }
581
582         TimeAxisView *ontrack = 0;
583         TrackViewList tlist;
584
585         if (!selection->tracks.empty()) {
586                 tlist = selection->tracks;
587         } else {
588                 tlist = track_views;
589         }
590
591         while (pos < _session->current_end_frame() && !at_end) {
592
593                 framepos_t rpos;
594                 framepos_t lpos = max_framepos;
595
596                 for (vector<RegionPoint>::iterator p = interesting_points.begin(); p != interesting_points.end(); ++p) {
597
598                         if ((r = find_next_region (pos, *p, 1, tlist, &ontrack)) == 0) {
599                                 if (*p == interesting_points.back()) {
600                                         at_end = true;
601                                 }
602                                 /* move to next point type */
603                                 continue;
604                         }
605
606                         switch (*p) {
607                         case Start:
608                                 rpos = r->first_frame();
609                                 break;
610
611                         case End:
612                                 rpos = r->last_frame();
613                                 break;
614
615                         case SyncPoint:
616                                 rpos = r->sync_position ();
617                                 break;
618
619                         default:
620                                 break;
621                         }
622
623                         float speed = 1.0f;
624                         RouteTimeAxisView *rtav;
625
626                         if (ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0 ) {
627                                 if (rtav->track() != 0) {
628                                         speed = rtav->track()->speed();
629                                 }
630                         }
631
632                         rpos = track_frame_to_session_frame (rpos, speed);
633
634                         if (rpos < lpos) {
635                                 lpos = rpos;
636                         }
637
638                         /* prevent duplicates, but we don't use set<> because we want to be able
639                            to sort later.
640                         */
641
642                         vector<framepos_t>::iterator ri;
643
644                         for (ri = region_boundary_cache.begin(); ri != region_boundary_cache.end(); ++ri) {
645                                 if (*ri == rpos) {
646                                         break;
647                                 }
648                         }
649
650                         if (ri == region_boundary_cache.end()) {
651                                 region_boundary_cache.push_back (rpos);
652                         }
653                 }
654
655                 pos = lpos + 1;
656         }
657
658         /* finally sort to be sure that the order is correct */
659
660         sort (region_boundary_cache.begin(), region_boundary_cache.end());
661 }
662
663 boost::shared_ptr<Region>
664 Editor::find_next_region (framepos_t frame, RegionPoint point, int32_t dir, TrackViewList& tracks, TimeAxisView **ontrack)
665 {
666         TrackViewList::iterator i;
667         framepos_t closest = max_framepos;
668         boost::shared_ptr<Region> ret;
669         framepos_t rpos = 0;
670
671         float track_speed;
672         framepos_t track_frame;
673         RouteTimeAxisView *rtav;
674
675         for (i = tracks.begin(); i != tracks.end(); ++i) {
676
677                 framecnt_t distance;
678                 boost::shared_ptr<Region> r;
679
680                 track_speed = 1.0f;
681                 if ( (rtav = dynamic_cast<RouteTimeAxisView*>(*i)) != 0 ) {
682                         if (rtav->track()!=0)
683                                 track_speed = rtav->track()->speed();
684                 }
685
686                 track_frame = session_frame_to_track_frame(frame, track_speed);
687
688                 if ((r = (*i)->find_next_region (track_frame, point, dir)) == 0) {
689                         continue;
690                 }
691
692                 switch (point) {
693                 case Start:
694                         rpos = r->first_frame ();
695                         break;
696
697                 case End:
698                         rpos = r->last_frame ();
699                         break;
700
701                 case SyncPoint:
702                         rpos = r->sync_position ();
703                         break;
704                 }
705
706                 // rpos is a "track frame", converting it to "_session frame"
707                 rpos = track_frame_to_session_frame(rpos, track_speed);
708
709                 if (rpos > frame) {
710                         distance = rpos - frame;
711                 } else {
712                         distance = frame - rpos;
713                 }
714
715                 if (distance < closest) {
716                         closest = distance;
717                         if (ontrack != 0)
718                                 *ontrack = (*i);
719                         ret = r;
720                 }
721         }
722
723         return ret;
724 }
725
726 framepos_t
727 Editor::find_next_region_boundary (framepos_t pos, int32_t dir, const TrackViewList& tracks)
728 {
729         framecnt_t distance = max_framepos;
730         framepos_t current_nearest = -1;
731
732         for (TrackViewList::const_iterator i = tracks.begin(); i != tracks.end(); ++i) {
733                 framepos_t contender;
734                 framecnt_t d;
735                 
736                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
737
738                 if (!rtv) {
739                         continue;
740                 }
741
742                 if ((contender = rtv->find_next_region_boundary (pos, dir)) < 0) {
743                         continue;
744                 }
745
746                 d = ::llabs (pos - contender);
747
748                 if (d < distance) {
749                         current_nearest = contender;
750                         distance = d;
751                 }
752         }
753
754         return current_nearest;
755 }
756
757 framepos_t
758 Editor::get_region_boundary (framepos_t pos, int32_t dir, bool with_selection, bool only_onscreen)
759 {
760         framepos_t target;
761         TrackViewList tvl;
762
763         if (with_selection && Config->get_region_boundaries_from_selected_tracks()) {
764
765                 if (!selection->tracks.empty()) {
766
767                         target = find_next_region_boundary (pos, dir, selection->tracks);
768
769                 } else {
770
771                         if (only_onscreen || Config->get_region_boundaries_from_onscreen_tracks()) {
772                                 get_onscreen_tracks (tvl);
773                                 target = find_next_region_boundary (pos, dir, tvl);
774                         } else {
775                                 target = find_next_region_boundary (pos, dir, track_views);
776                         }
777                 }
778
779         } else {
780
781                 if (only_onscreen || Config->get_region_boundaries_from_onscreen_tracks()) {
782                         get_onscreen_tracks (tvl);
783                         target = find_next_region_boundary (pos, dir, tvl);
784                 } else {
785                         target = find_next_region_boundary (pos, dir, track_views);
786                 }
787         }
788
789         return target;
790 }
791
792 void
793 Editor::cursor_to_region_boundary (bool with_selection, int32_t dir)
794 {
795         framepos_t pos = playhead_cursor->current_frame;
796         framepos_t target;
797
798         if (!_session) {
799                 return;
800         }
801
802         // so we don't find the current region again..
803         if (dir > 0 || pos > 0) {
804                 pos += dir;
805         }
806
807         if ((target = get_region_boundary (pos, dir, with_selection, false)) < 0) {
808                 return;
809         }
810
811         _session->request_locate (target);
812 }
813
814 void
815 Editor::cursor_to_next_region_boundary (bool with_selection)
816 {
817         cursor_to_region_boundary (with_selection, 1);
818 }
819
820 void
821 Editor::cursor_to_previous_region_boundary (bool with_selection)
822 {
823         cursor_to_region_boundary (with_selection, -1);
824 }
825
826 void
827 Editor::cursor_to_region_point (EditorCursor* cursor, RegionPoint point, int32_t dir)
828 {
829         boost::shared_ptr<Region> r;
830         framepos_t pos = cursor->current_frame;
831
832         if (!_session) {
833                 return;
834         }
835
836         TimeAxisView *ontrack = 0;
837
838         // so we don't find the current region again..
839         if (dir>0 || pos>0)
840                 pos+=dir;
841
842         if (!selection->tracks.empty()) {
843
844                 r = find_next_region (pos, point, dir, selection->tracks, &ontrack);
845
846         } else if (clicked_axisview) {
847
848                 TrackViewList t;
849                 t.push_back (clicked_axisview);
850
851                 r = find_next_region (pos, point, dir, t, &ontrack);
852
853         } else {
854
855                 r = find_next_region (pos, point, dir, track_views, &ontrack);
856         }
857
858         if (r == 0) {
859                 return;
860         }
861
862         switch (point){
863         case Start:
864                 pos = r->first_frame ();
865                 break;
866
867         case End:
868                 pos = r->last_frame ();
869                 break;
870
871         case SyncPoint:
872                 pos = r->sync_position ();
873                 break;
874         }
875
876         float speed = 1.0f;
877         RouteTimeAxisView *rtav;
878
879         if ( ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0 ) {
880                 if (rtav->track() != 0) {
881                         speed = rtav->track()->speed();
882                 }
883         }
884
885         pos = track_frame_to_session_frame(pos, speed);
886
887         if (cursor == playhead_cursor) {
888                 _session->request_locate (pos);
889         } else {
890                 cursor->set_position (pos);
891         }
892 }
893
894 void
895 Editor::cursor_to_next_region_point (EditorCursor* cursor, RegionPoint point)
896 {
897         cursor_to_region_point (cursor, point, 1);
898 }
899
900 void
901 Editor::cursor_to_previous_region_point (EditorCursor* cursor, RegionPoint point)
902 {
903         cursor_to_region_point (cursor, point, -1);
904 }
905
906 void
907 Editor::cursor_to_selection_start (EditorCursor *cursor)
908 {
909         framepos_t pos = 0;
910
911         switch (mouse_mode) {
912         case MouseObject:
913                 if (!selection->regions.empty()) {
914                         pos = selection->regions.start();
915                 }
916                 break;
917
918         case MouseRange:
919                 if (!selection->time.empty()) {
920                         pos = selection->time.start ();
921                 }
922                 break;
923
924         default:
925                 return;
926         }
927
928         if (cursor == playhead_cursor) {
929                 _session->request_locate (pos);
930         } else {
931                 cursor->set_position (pos);
932         }
933 }
934
935 void
936 Editor::cursor_to_selection_end (EditorCursor *cursor)
937 {
938         framepos_t pos = 0;
939
940         switch (mouse_mode) {
941         case MouseObject:
942                 if (!selection->regions.empty()) {
943                         pos = selection->regions.end_frame();
944                 }
945                 break;
946
947         case MouseRange:
948                 if (!selection->time.empty()) {
949                         pos = selection->time.end_frame ();
950                 }
951                 break;
952
953         default:
954                 return;
955         }
956
957         if (cursor == playhead_cursor) {
958                 _session->request_locate (pos);
959         } else {
960                 cursor->set_position (pos);
961         }
962 }
963
964 void
965 Editor::selected_marker_to_region_boundary (bool with_selection, int32_t dir)
966 {
967         framepos_t target;
968         Location* loc;
969         bool ignored;
970
971         if (!_session) {
972                 return;
973         }
974
975         if (selection->markers.empty()) {
976                 framepos_t mouse;
977                 bool ignored;
978
979                 if (!mouse_frame (mouse, ignored)) {
980                         return;
981                 }
982
983                 add_location_mark (mouse);
984         }
985
986         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
987                 return;
988         }
989
990         framepos_t pos = loc->start();
991
992         // so we don't find the current region again..
993         if (dir > 0 || pos > 0) {
994                 pos += dir;
995         }
996
997         if ((target = get_region_boundary (pos, dir, with_selection, false)) < 0) {
998                 return;
999         }
1000
1001         loc->move_to (target);
1002 }
1003
1004 void
1005 Editor::selected_marker_to_next_region_boundary (bool with_selection)
1006 {
1007         selected_marker_to_region_boundary (with_selection, 1);
1008 }
1009
1010 void
1011 Editor::selected_marker_to_previous_region_boundary (bool with_selection)
1012 {
1013         selected_marker_to_region_boundary (with_selection, -1);
1014 }
1015
1016 void
1017 Editor::selected_marker_to_region_point (RegionPoint point, int32_t dir)
1018 {
1019         boost::shared_ptr<Region> r;
1020         framepos_t pos;
1021         Location* loc;
1022         bool ignored;
1023
1024         if (!_session || selection->markers.empty()) {
1025                 return;
1026         }
1027
1028         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1029                 return;
1030         }
1031
1032         TimeAxisView *ontrack = 0;
1033
1034         pos = loc->start();
1035
1036         // so we don't find the current region again..
1037         if (dir>0 || pos>0)
1038                 pos+=dir;
1039
1040         if (!selection->tracks.empty()) {
1041
1042                 r = find_next_region (pos, point, dir, selection->tracks, &ontrack);
1043
1044         } else {
1045
1046                 r = find_next_region (pos, point, dir, track_views, &ontrack);
1047         }
1048
1049         if (r == 0) {
1050                 return;
1051         }
1052
1053         switch (point){
1054         case Start:
1055                 pos = r->first_frame ();
1056                 break;
1057
1058         case End:
1059                 pos = r->last_frame ();
1060                 break;
1061
1062         case SyncPoint:
1063                 pos = r->adjust_to_sync (r->first_frame());
1064                 break;
1065         }
1066
1067         float speed = 1.0f;
1068         RouteTimeAxisView *rtav;
1069
1070         if (ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0) {
1071                 if (rtav->track() != 0) {
1072                         speed = rtav->track()->speed();
1073                 }
1074         }
1075
1076         pos = track_frame_to_session_frame(pos, speed);
1077
1078         loc->move_to (pos);
1079 }
1080
1081 void
1082 Editor::selected_marker_to_next_region_point (RegionPoint point)
1083 {
1084         selected_marker_to_region_point (point, 1);
1085 }
1086
1087 void
1088 Editor::selected_marker_to_previous_region_point (RegionPoint point)
1089 {
1090         selected_marker_to_region_point (point, -1);
1091 }
1092
1093 void
1094 Editor::selected_marker_to_selection_start ()
1095 {
1096         framepos_t pos = 0;
1097         Location* loc;
1098         bool ignored;
1099
1100         if (!_session || selection->markers.empty()) {
1101                 return;
1102         }
1103
1104         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1105                 return;
1106         }
1107
1108         switch (mouse_mode) {
1109         case MouseObject:
1110                 if (!selection->regions.empty()) {
1111                         pos = selection->regions.start();
1112                 }
1113                 break;
1114
1115         case MouseRange:
1116                 if (!selection->time.empty()) {
1117                         pos = selection->time.start ();
1118                 }
1119                 break;
1120
1121         default:
1122                 return;
1123         }
1124
1125         loc->move_to (pos);
1126 }
1127
1128 void
1129 Editor::selected_marker_to_selection_end ()
1130 {
1131         framepos_t pos = 0;
1132         Location* loc;
1133         bool ignored;
1134
1135         if (!_session || selection->markers.empty()) {
1136                 return;
1137         }
1138
1139         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1140                 return;
1141         }
1142
1143         switch (mouse_mode) {
1144         case MouseObject:
1145                 if (!selection->regions.empty()) {
1146                         pos = selection->regions.end_frame();
1147                 }
1148                 break;
1149
1150         case MouseRange:
1151                 if (!selection->time.empty()) {
1152                         pos = selection->time.end_frame ();
1153                 }
1154                 break;
1155
1156         default:
1157                 return;
1158         }
1159
1160         loc->move_to (pos);
1161 }
1162
1163 void
1164 Editor::scroll_playhead (bool forward)
1165 {
1166         framepos_t pos = playhead_cursor->current_frame;
1167         framecnt_t delta = (framecnt_t) floor (current_page_frames() / 0.8);
1168
1169         if (forward) {
1170                 if (pos == max_framepos) {
1171                         return;
1172                 }
1173
1174                 if (pos < max_framepos - delta) {
1175                         pos += delta ;
1176                 } else {
1177                         pos = max_framepos;
1178                 }
1179
1180         } else {
1181
1182                 if (pos == 0) {
1183                         return;
1184                 }
1185
1186                 if (pos > delta) {
1187                         pos -= delta;
1188                 } else {
1189                         pos = 0;
1190                 }
1191         }
1192
1193         _session->request_locate (pos);
1194 }
1195
1196 void
1197 Editor::playhead_backward ()
1198 {
1199         framepos_t pos;
1200         framepos_t cnt;
1201         float prefix;
1202         bool was_floating;
1203
1204         if (get_prefix (prefix, was_floating)) {
1205                 cnt = 1;
1206         } else {
1207                 if (was_floating) {
1208                         cnt = (framepos_t) floor (prefix * _session->frame_rate ());
1209                 } else {
1210                         cnt = (framepos_t) prefix;
1211                 }
1212         }
1213
1214         pos = playhead_cursor->current_frame;
1215
1216         if ((framepos_t) pos < cnt) {
1217                 pos = 0;
1218         } else {
1219                 pos -= cnt;
1220         }
1221
1222         /* XXX this is completely insane. with the current buffering
1223            design, we'll force a complete track buffer flush and
1224            reload, just to move 1 sample !!!
1225         */
1226
1227         _session->request_locate (pos);
1228 }
1229
1230 void
1231 Editor::playhead_forward ()
1232 {
1233         framepos_t pos;
1234         framepos_t cnt;
1235         bool was_floating;
1236         float prefix;
1237
1238         if (get_prefix (prefix, was_floating)) {
1239                 cnt = 1;
1240         } else {
1241                 if (was_floating) {
1242                         cnt = (framepos_t) floor (prefix * _session->frame_rate ());
1243                 } else {
1244                         cnt = (framepos_t) floor (prefix);
1245                 }
1246         }
1247
1248         pos = playhead_cursor->current_frame;
1249
1250         /* XXX this is completely insane. with the current buffering
1251            design, we'll force a complete track buffer flush and
1252            reload, just to move 1 sample !!!
1253         */
1254
1255         _session->request_locate (pos+cnt);
1256 }
1257
1258 void
1259 Editor::cursor_align (bool playhead_to_edit)
1260 {
1261         if (!_session) {
1262                 return;
1263         }
1264
1265         if (playhead_to_edit) {
1266
1267                 if (selection->markers.empty()) {
1268                         return;
1269                 }
1270
1271                 _session->request_locate (selection->markers.front()->position(), _session->transport_rolling());
1272
1273         } else {
1274                 /* move selected markers to playhead */
1275
1276                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
1277                         bool ignored;
1278
1279                         Location* loc = find_location_from_marker (*i, ignored);
1280
1281                         if (loc->is_mark()) {
1282                                 loc->set_start (playhead_cursor->current_frame);
1283                         } else {
1284                                 loc->set (playhead_cursor->current_frame,
1285                                           playhead_cursor->current_frame + loc->length());
1286                         }
1287                 }
1288         }
1289 }
1290
1291 void
1292 Editor::edit_cursor_backward ()
1293 {
1294         framepos_t pos;
1295         framepos_t cnt;
1296         float prefix;
1297         bool was_floating;
1298
1299         if (get_prefix (prefix, was_floating)) {
1300                 cnt = 1;
1301         } else {
1302                 if (was_floating) {
1303                         cnt = (framepos_t) floor (prefix * _session->frame_rate ());
1304                 } else {
1305                         cnt = (framepos_t) prefix;
1306                 }
1307         }
1308
1309         if ((pos = get_preferred_edit_position()) < 0) {
1310                 return;
1311         }
1312
1313         if (pos < cnt) {
1314                 pos = 0;
1315         } else {
1316                 pos -= cnt;
1317         }
1318
1319         // EDIT CURSOR edit_cursor->set_position (pos);
1320 }
1321
1322 void
1323 Editor::edit_cursor_forward ()
1324 {
1325         //framepos_t pos;
1326         framepos_t cnt;
1327         bool was_floating;
1328         float prefix;
1329
1330         if (get_prefix (prefix, was_floating)) {
1331                 cnt = 1;
1332         } else {
1333                 if (was_floating) {
1334                         cnt = (framepos_t) floor (prefix * _session->frame_rate ());
1335                 } else {
1336                         cnt = (framepos_t) floor (prefix);
1337                 }
1338         }
1339
1340         // pos = edit_cursor->current_frame;
1341         // EDIT CURSOR edit_cursor->set_position (pos+cnt);
1342 }
1343
1344 void
1345 Editor::goto_frame ()
1346 {
1347         float prefix;
1348         bool was_floating;
1349         framepos_t frame;
1350
1351         if (get_prefix (prefix, was_floating)) {
1352                 return;
1353         }
1354
1355         if (was_floating) {
1356                 frame = (framepos_t) floor (prefix * _session->frame_rate());
1357         } else {
1358                 frame = (framepos_t) floor (prefix);
1359         }
1360
1361         _session->request_locate (frame);
1362 }
1363
1364 void
1365 Editor::scroll_backward (float pages)
1366 {
1367         framepos_t frame;
1368         framepos_t one_page = (framepos_t) rint (_canvas_width * frames_per_unit);
1369         bool was_floating;
1370         float prefix;
1371         framepos_t cnt;
1372
1373         if (get_prefix (prefix, was_floating)) {
1374                 cnt = (framepos_t) floor (pages * one_page);
1375         } else {
1376                 if (was_floating) {
1377                         cnt = (framepos_t) floor (prefix * _session->frame_rate());
1378                 } else {
1379                         cnt = (framepos_t) floor (prefix * one_page);
1380                 }
1381         }
1382
1383         if (leftmost_frame < cnt) {
1384                 frame = 0;
1385         } else {
1386                 frame = leftmost_frame - cnt;
1387         }
1388
1389         reset_x_origin (frame);
1390 }
1391
1392 void
1393 Editor::scroll_forward (float pages)
1394 {
1395         framepos_t frame;
1396         framepos_t one_page = (framepos_t) rint (_canvas_width * frames_per_unit);
1397         bool was_floating;
1398         float prefix;
1399         framepos_t cnt;
1400
1401         if (get_prefix (prefix, was_floating)) {
1402                 cnt = (framepos_t) floor (pages * one_page);
1403         } else {
1404                 if (was_floating) {
1405                         cnt = (framepos_t) floor (prefix * _session->frame_rate());
1406                 } else {
1407                         cnt = (framepos_t) floor (prefix * one_page);
1408                 }
1409         }
1410
1411         if (max_framepos - cnt < leftmost_frame) {
1412                 frame = max_framepos - cnt;
1413         } else {
1414                 frame = leftmost_frame + cnt;
1415         }
1416
1417         reset_x_origin (frame);
1418 }
1419
1420 void
1421 Editor::scroll_tracks_down ()
1422 {
1423         float prefix;
1424         bool was_floating;
1425         int cnt;
1426
1427         if (get_prefix (prefix, was_floating)) {
1428                 cnt = 1;
1429         } else {
1430                 cnt = (int) floor (prefix);
1431         }
1432
1433         double vert_value = vertical_adjustment.get_value() + (cnt *
1434                 vertical_adjustment.get_page_size());
1435         if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
1436                 vert_value = vertical_adjustment.get_upper() - _canvas_height;
1437         }
1438         vertical_adjustment.set_value (vert_value);
1439 }
1440
1441 void
1442 Editor::scroll_tracks_up ()
1443 {
1444         float prefix;
1445         bool was_floating;
1446         int cnt;
1447
1448         if (get_prefix (prefix, was_floating)) {
1449                 cnt = 1;
1450         } else {
1451                 cnt = (int) floor (prefix);
1452         }
1453
1454         vertical_adjustment.set_value (vertical_adjustment.get_value() - (cnt * vertical_adjustment.get_page_size()));
1455 }
1456
1457 void
1458 Editor::scroll_tracks_down_line ()
1459 {
1460         double vert_value = vertical_adjustment.get_value() + 60;
1461
1462         if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
1463                 vert_value = vertical_adjustment.get_upper() - _canvas_height;
1464         }
1465         
1466         vertical_adjustment.set_value (vert_value);
1467 }
1468
1469 void
1470 Editor::scroll_tracks_up_line ()
1471 {
1472         reset_y_origin (vertical_adjustment.get_value() - 60);
1473 }
1474
1475 /* ZOOM */
1476
1477 void
1478 Editor::tav_zoom_step (bool coarser)
1479 {
1480         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
1481
1482         _routes->suspend_redisplay ();
1483
1484         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1485                 TimeAxisView *tv = (static_cast<TimeAxisView*>(*i));
1486                         tv->step_height (coarser);
1487         }
1488
1489         _routes->resume_redisplay ();
1490 }
1491
1492 void
1493 Editor::temporal_zoom_step (bool coarser)
1494 {
1495         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
1496
1497         double nfpu;
1498
1499         nfpu = frames_per_unit;
1500
1501         if (coarser) {
1502                 nfpu *= 1.61803399;
1503         } else {
1504                 nfpu = max(1.0,(nfpu/1.61803399));
1505         }
1506
1507         temporal_zoom (nfpu);
1508 }
1509
1510 void
1511 Editor::temporal_zoom (gdouble fpu)
1512 {
1513         if (!_session) return;
1514
1515         framepos_t current_page = current_page_frames();
1516         framepos_t current_leftmost = leftmost_frame;
1517         framepos_t current_rightmost;
1518         framepos_t current_center;
1519         framepos_t new_page_size;
1520         framepos_t half_page_size;
1521         framepos_t leftmost_after_zoom = 0;
1522         framepos_t where;
1523         bool in_track_canvas;
1524         double nfpu;
1525         double l;
1526
1527         /* XXX this limit is also in ::set_frames_per_unit() */
1528
1529         if (frames_per_unit <= 1.0 && fpu <= frames_per_unit) {
1530                 return;
1531         }
1532
1533         nfpu = fpu;
1534
1535         new_page_size = (framepos_t) floor (_canvas_width * nfpu);
1536         half_page_size = new_page_size / 2;
1537
1538         switch (zoom_focus) {
1539         case ZoomFocusLeft:
1540                 leftmost_after_zoom = current_leftmost;
1541                 break;
1542
1543         case ZoomFocusRight:
1544                 current_rightmost = leftmost_frame + current_page;
1545                 if (current_rightmost < new_page_size) {
1546                         leftmost_after_zoom = 0;
1547                 } else {
1548                         leftmost_after_zoom = current_rightmost - new_page_size;
1549                 }
1550                 break;
1551
1552         case ZoomFocusCenter:
1553                 current_center = current_leftmost + (current_page/2);
1554                 if (current_center < half_page_size) {
1555                         leftmost_after_zoom = 0;
1556                 } else {
1557                         leftmost_after_zoom = current_center - half_page_size;
1558                 }
1559                 break;
1560
1561         case ZoomFocusPlayhead:
1562                 /* centre playhead */
1563                 l = playhead_cursor->current_frame - (new_page_size * 0.5);
1564
1565                 if (l < 0) {
1566                         leftmost_after_zoom = 0;
1567                 } else if (l > max_framepos) {
1568                         leftmost_after_zoom = max_framepos - new_page_size;
1569                 } else {
1570                         leftmost_after_zoom = (framepos_t) l;
1571                 }
1572                 break;
1573
1574         case ZoomFocusMouse:
1575                 /* try to keep the mouse over the same point in the display */
1576
1577                 if (!mouse_frame (where, in_track_canvas)) {
1578                         /* use playhead instead */
1579                         where = playhead_cursor->current_frame;
1580
1581                         if (where < half_page_size) {
1582                                 leftmost_after_zoom = 0;
1583                         } else {
1584                                 leftmost_after_zoom = where - half_page_size;
1585                         }
1586
1587                 } else {
1588
1589                         l = - ((new_page_size * ((where - current_leftmost)/(double)current_page)) - where);
1590
1591                         if (l < 0) {
1592                                 leftmost_after_zoom = 0;
1593                         } else if (l > max_framepos) {
1594                                 leftmost_after_zoom = max_framepos - new_page_size;
1595                         } else {
1596                                 leftmost_after_zoom = (framepos_t) l;
1597                         }
1598                 }
1599
1600                 break;
1601
1602         case ZoomFocusEdit:
1603                 /* try to keep the edit point in the same place */
1604                 where = get_preferred_edit_position ();
1605
1606                 if (where > 0) {
1607
1608                         double l = - ((new_page_size * ((where - current_leftmost)/(double)current_page)) - where);
1609
1610                         if (l < 0) {
1611                                 leftmost_after_zoom = 0;
1612                         } else if (l > max_framepos) {
1613                                 leftmost_after_zoom = max_framepos - new_page_size;
1614                         } else {
1615                                 leftmost_after_zoom = (framepos_t) l;
1616                         }
1617
1618                 } else {
1619                         /* edit point not defined */
1620                         return;
1621                 }
1622                 break;
1623
1624         }
1625
1626         // leftmost_after_zoom = min (leftmost_after_zoom, _session->current_end_frame());
1627
1628         reposition_and_zoom (leftmost_after_zoom, nfpu);
1629 }
1630
1631 void
1632 Editor::temporal_zoom_region (bool both_axes)
1633 {
1634         framepos_t start = max_framepos;
1635         framepos_t end = 0;
1636         set<TimeAxisView*> tracks;
1637
1638         RegionSelection rs = get_regions_from_selection_and_entered ();
1639
1640         if (rs.empty()) {
1641                 return;
1642         }
1643
1644         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
1645
1646                 if ((*i)->region()->position() < start) {
1647                         start = (*i)->region()->position();
1648                 }
1649
1650                 if ((*i)->region()->last_frame() + 1 > end) {
1651                         end = (*i)->region()->last_frame() + 1;
1652                 }
1653
1654                 tracks.insert (&((*i)->get_time_axis_view()));
1655         }
1656
1657         /* now comes an "interesting" hack ... make sure we leave a little space
1658            at each end of the editor so that the zoom doesn't fit the region
1659            precisely to the screen.
1660         */
1661
1662         GdkScreen* screen = gdk_screen_get_default ();
1663         gint pixwidth = gdk_screen_get_width (screen);
1664         gint mmwidth = gdk_screen_get_width_mm (screen);
1665         double pix_per_mm = (double) pixwidth/ (double) mmwidth;
1666         double one_centimeter_in_pixels = pix_per_mm * 10.0;
1667
1668         if ((start == 0 && end == 0) || end < start) {
1669                 return;
1670         }
1671
1672         framepos_t range = end - start;
1673         double new_fpu = (double)range / (double)_canvas_width;
1674         framepos_t extra_samples = (framepos_t) floor (one_centimeter_in_pixels * new_fpu);
1675
1676         if (start > extra_samples) {
1677                 start -= extra_samples;
1678         } else {
1679                 start = 0;
1680         }
1681
1682         if (max_framepos - extra_samples > end) {
1683                 end += extra_samples;
1684         } else {
1685                 end = max_framepos;
1686         }
1687
1688         if (both_axes) {
1689                 /* save visual state with track states included, and prevent
1690                    set_frames_per_unit() from doing it again.
1691                 */
1692                 undo_visual_stack.push_back (current_visual_state(true));
1693                 no_save_visual = true;
1694         }
1695
1696         temporal_zoom_by_frame (start, end, "zoom to region");
1697
1698         if (both_axes) {
1699                 uint32_t per_track_height = (uint32_t) floor ((_canvas_height - canvas_timebars_vsize - 10.0) / tracks.size());
1700
1701                 /* set visible track heights appropriately */
1702
1703                 for (set<TimeAxisView*>::iterator t = tracks.begin(); t != tracks.end(); ++t) {
1704                         (*t)->set_height (per_track_height);
1705                 }
1706
1707                 /* hide irrelevant tracks */
1708
1709                 _routes->suspend_redisplay ();
1710
1711                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1712                         if (find (tracks.begin(), tracks.end(), (*i)) == tracks.end()) {
1713                                 hide_track_in_display (*i, true);
1714                         }
1715                 }
1716
1717                 _routes->resume_redisplay ();
1718
1719                 vertical_adjustment.set_value (0.0);
1720                 no_save_visual = false;
1721         }
1722
1723         redo_visual_stack.push_back (current_visual_state());
1724 }
1725
1726 void
1727 Editor::zoom_to_region (bool both_axes)
1728 {
1729         temporal_zoom_region (both_axes);
1730 }
1731
1732 void
1733 Editor::temporal_zoom_selection ()
1734 {
1735         if (!selection) return;
1736
1737         if (selection->time.empty()) {
1738                 return;
1739         }
1740
1741         framepos_t start = selection->time[clicked_selection].start;
1742         framepos_t end = selection->time[clicked_selection].end;
1743
1744         temporal_zoom_by_frame (start, end, "zoom to selection");
1745 }
1746
1747 void
1748 Editor::temporal_zoom_session ()
1749 {
1750         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_session)
1751
1752         if (_session) {
1753                 nframes_t const l = _session->current_end_frame() - _session->current_start_frame();
1754                 double s = _session->current_start_frame() - l * 0.01;
1755                 if (s < 0) {
1756                         s = 0;
1757                 }
1758                 nframes_t const e = _session->current_end_frame() + l * 0.01;
1759                 temporal_zoom_by_frame (nframes_t (s), e, "zoom to _session");
1760         }
1761 }
1762
1763 void
1764 Editor::temporal_zoom_by_frame (framepos_t start, framepos_t end, const string & /*op*/)
1765 {
1766         if (!_session) return;
1767
1768         if ((start == 0 && end == 0) || end < start) {
1769                 return;
1770         }
1771
1772         framepos_t range = end - start;
1773
1774         double new_fpu = (double)range / (double)_canvas_width;
1775
1776         framepos_t new_page = (framepos_t) floor (_canvas_width * new_fpu);
1777         framepos_t middle = (framepos_t) floor( (double)start + ((double)range / 2.0f ));
1778         framepos_t new_leftmost = (framepos_t) floor( (double)middle - ((double)new_page/2.0f));
1779
1780         if (new_leftmost > middle) {
1781                 new_leftmost = 0;
1782         }
1783
1784         reposition_and_zoom (new_leftmost, new_fpu);
1785 }
1786
1787 void
1788 Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
1789 {
1790         if (!_session) {
1791                 return;
1792         }
1793         double range_before = frame - leftmost_frame;
1794         double new_fpu;
1795
1796         new_fpu = frames_per_unit;
1797
1798         if (coarser) {
1799                 new_fpu *= 1.61803399;
1800                 range_before *= 1.61803399;
1801         } else {
1802                 new_fpu = max(1.0,(new_fpu/1.61803399));
1803                 range_before /= 1.61803399;
1804         }
1805
1806         if (new_fpu == frames_per_unit)  {
1807                 return;
1808         }
1809
1810         framepos_t new_leftmost = frame - (framepos_t)range_before;
1811
1812         if (new_leftmost > frame) {
1813                 new_leftmost = 0;
1814         }
1815 //      begin_reversible_command (_("zoom to frame"));
1816 //      _session->add_undo (sigc::bind (sigc::mem_fun(*this, &Editor::reposition_and_zoom), leftmost_frame, frames_per_unit));
1817 //      _session->add_redo (sigc::bind (sigc::mem_fun(*this, &Editor::reposition_and_zoom), new_leftmost, new_fpu));
1818 //      commit_reversible_command ();
1819
1820         reposition_and_zoom (new_leftmost, new_fpu);
1821 }
1822
1823
1824 bool
1825 Editor::choose_new_marker_name(string &name) {
1826
1827         if (!Config->get_name_new_markers()) {
1828                 /* don't prompt user for a new name */
1829                 return true;
1830         }
1831
1832         ArdourPrompter dialog (true);
1833
1834         dialog.set_prompt (_("New Name:"));
1835
1836         dialog.set_title (_("New Location Marker"));
1837
1838         dialog.set_name ("MarkNameWindow");
1839         dialog.set_size_request (250, -1);
1840         dialog.set_position (Gtk::WIN_POS_MOUSE);
1841
1842         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
1843         dialog.set_initial_text (name);
1844
1845         dialog.show ();
1846
1847         switch (dialog.run ()) {
1848         case RESPONSE_ACCEPT:
1849                 break;
1850         default:
1851                 return false;
1852         }
1853
1854         dialog.get_result(name);
1855         return true;
1856
1857 }
1858
1859
1860 void
1861 Editor::add_location_from_selection ()
1862 {
1863         string rangename;
1864
1865         if (selection->time.empty()) {
1866                 return;
1867         }
1868
1869         if (_session == 0 || clicked_axisview == 0) {
1870                 return;
1871         }
1872
1873         framepos_t start = selection->time[clicked_selection].start;
1874         framepos_t end = selection->time[clicked_selection].end;
1875
1876         _session->locations()->next_available_name(rangename,"selection");
1877         Location *location = new Location (*_session, start, end, rangename, Location::IsRangeMarker);
1878
1879         _session->begin_reversible_command (_("add marker"));
1880         XMLNode &before = _session->locations()->get_state();
1881         _session->locations()->add (location, true);
1882         XMLNode &after = _session->locations()->get_state();
1883         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1884         _session->commit_reversible_command ();
1885 }
1886
1887 void
1888 Editor::add_location_mark (framepos_t where)
1889 {
1890         string markername;
1891
1892         select_new_marker = true;
1893
1894         _session->locations()->next_available_name(markername,"mark");
1895         if (!choose_new_marker_name(markername)) {
1896                 return;
1897         }
1898         Location *location = new Location (*_session, where, where, markername, Location::IsMark);
1899         _session->begin_reversible_command (_("add marker"));
1900         XMLNode &before = _session->locations()->get_state();
1901         _session->locations()->add (location, true);
1902         XMLNode &after = _session->locations()->get_state();
1903         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1904         _session->commit_reversible_command ();
1905 }
1906
1907 void
1908 Editor::add_location_from_playhead_cursor ()
1909 {
1910         add_location_mark (_session->audible_frame());
1911 }
1912
1913 /** Add a range marker around each selected region */
1914 void
1915 Editor::add_locations_from_region ()
1916 {
1917         RegionSelection rs = get_regions_from_selection_and_entered ();
1918         
1919         if (rs.empty()) {
1920                 return;
1921         }
1922
1923         _session->begin_reversible_command (selection->regions.size () > 1 ? _("add markers") : _("add marker"));
1924         XMLNode &before = _session->locations()->get_state();
1925
1926         for (RegionSelection::iterator i = rs.begin (); i != rs.end (); ++i) {
1927
1928                 boost::shared_ptr<Region> region = (*i)->region ();
1929
1930                 Location *location = new Location (*_session, region->position(), region->last_frame(), region->name(), Location::IsRangeMarker);
1931
1932                 _session->locations()->add (location, true);
1933         }
1934
1935         XMLNode &after = _session->locations()->get_state();
1936         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1937         _session->commit_reversible_command ();
1938 }
1939
1940 /** Add a single range marker around all selected regions */
1941 void
1942 Editor::add_location_from_region ()
1943 {
1944         RegionSelection rs = get_regions_from_selection_and_entered ();
1945         
1946         if (rs.empty()) {
1947                 return;
1948         }
1949
1950         _session->begin_reversible_command (_("add marker"));
1951         XMLNode &before = _session->locations()->get_state();
1952
1953         string markername;
1954
1955         if (rs.size() > 1) {
1956                 _session->locations()->next_available_name(markername, "regions");
1957         } else {
1958                 RegionView* rv = *(rs.begin());
1959                 boost::shared_ptr<Region> region = rv->region();
1960                 markername = region->name();
1961         }
1962
1963         if (!choose_new_marker_name(markername)) {
1964                 return;
1965         }
1966
1967         // single range spanning all selected
1968         Location *location = new Location (*_session, selection->regions.start(), selection->regions.end_frame(), markername, Location::IsRangeMarker);
1969         _session->locations()->add (location, true);
1970
1971         XMLNode &after = _session->locations()->get_state();
1972         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1973         _session->commit_reversible_command ();
1974 }
1975
1976 void
1977 Editor::amplitude_zoom_step (bool in)
1978 {
1979         gdouble zoom = 1.0;
1980
1981         if (in) {
1982                 zoom *= 2.0;
1983         } else {
1984                 if (zoom > 2.0) {
1985                         zoom /= 2.0;
1986                 } else {
1987                         zoom = 1.0;
1988                 }
1989         }
1990
1991 #ifdef FIX_FOR_CANVAS
1992         /* XXX DO SOMETHING */
1993 #endif
1994 }
1995
1996
1997 /* DELETION */
1998
1999
2000 void
2001 Editor::delete_sample_forward ()
2002 {
2003 }
2004
2005 void
2006 Editor::delete_sample_backward ()
2007 {
2008 }
2009
2010 void
2011 Editor::delete_screen ()
2012 {
2013 }
2014
2015 /* SEARCH */
2016
2017 void
2018 Editor::search_backwards ()
2019 {
2020         /* what ? */
2021 }
2022
2023 void
2024 Editor::search_forwards ()
2025 {
2026         /* what ? */
2027 }
2028
2029 /* MARKS */
2030
2031 void
2032 Editor::jump_forward_to_mark ()
2033 {
2034         if (!_session) {
2035                 return;
2036         }
2037
2038         Location *location = _session->locations()->first_location_after (playhead_cursor->current_frame);
2039
2040         if (location) {
2041                 _session->request_locate (location->start(), _session->transport_rolling());
2042         } else {
2043                 _session->request_locate (_session->current_end_frame());
2044         }
2045 }
2046
2047 void
2048 Editor::jump_backward_to_mark ()
2049 {
2050         if (!_session) {
2051                 return;
2052         }
2053
2054         Location *location = _session->locations()->first_location_before (playhead_cursor->current_frame);
2055
2056         if (location) {
2057                 _session->request_locate (location->start(), _session->transport_rolling());
2058         } else {
2059                 _session->goto_start ();
2060         }
2061 }
2062
2063 void
2064 Editor::set_mark ()
2065 {
2066         framepos_t pos;
2067         float prefix;
2068         bool was_floating;
2069         string markername;
2070
2071         if (get_prefix (prefix, was_floating)) {
2072                 pos = _session->audible_frame ();
2073         } else {
2074                 if (was_floating) {
2075                         pos = (framepos_t) floor (prefix * _session->frame_rate ());
2076                 } else {
2077                         pos = (framepos_t) floor (prefix);
2078                 }
2079         }
2080
2081         _session->locations()->next_available_name(markername,"mark");
2082         if (!choose_new_marker_name(markername)) {
2083                 return;
2084         }
2085         _session->locations()->add (new Location (*_session, pos, 0, markername, Location::IsMark), true);
2086 }
2087
2088 void
2089 Editor::clear_markers ()
2090 {
2091         if (_session) {
2092                 _session->begin_reversible_command (_("clear markers"));
2093                 XMLNode &before = _session->locations()->get_state();
2094                 _session->locations()->clear_markers ();
2095                 XMLNode &after = _session->locations()->get_state();
2096                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2097                 _session->commit_reversible_command ();
2098         }
2099 }
2100
2101 void
2102 Editor::clear_ranges ()
2103 {
2104         if (_session) {
2105                 _session->begin_reversible_command (_("clear ranges"));
2106                 XMLNode &before = _session->locations()->get_state();
2107
2108                 Location * looploc = _session->locations()->auto_loop_location();
2109                 Location * punchloc = _session->locations()->auto_punch_location();
2110
2111                 _session->locations()->clear_ranges ();
2112                 // re-add these
2113                 if (looploc) _session->locations()->add (looploc);
2114                 if (punchloc) _session->locations()->add (punchloc);
2115
2116                 XMLNode &after = _session->locations()->get_state();
2117                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2118                 _session->commit_reversible_command ();
2119         }
2120 }
2121
2122 void
2123 Editor::clear_locations ()
2124 {
2125         _session->begin_reversible_command (_("clear locations"));
2126         XMLNode &before = _session->locations()->get_state();
2127         _session->locations()->clear ();
2128         XMLNode &after = _session->locations()->get_state();
2129         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2130         _session->commit_reversible_command ();
2131         _session->locations()->clear ();
2132 }
2133
2134 void
2135 Editor::unhide_markers ()
2136 {
2137         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
2138                 Location *l = (*i).first;
2139                 if (l->is_hidden() && l->is_mark()) {
2140                         l->set_hidden(false, this);
2141                 }
2142         }
2143 }
2144
2145 void
2146 Editor::unhide_ranges ()
2147 {
2148         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
2149                 Location *l = (*i).first;
2150                 if (l->is_hidden() && l->is_range_marker()) {
2151                         l->set_hidden(false, this);
2152                 }
2153         }
2154 }
2155
2156 /* INSERT/REPLACE */
2157
2158 void
2159 Editor::insert_region_list_drag (boost::shared_ptr<Region> region, int x, int y)
2160 {
2161         double wx, wy;
2162         double cx, cy;
2163         framepos_t where;
2164         RouteTimeAxisView *rtv = 0;
2165         boost::shared_ptr<Playlist> playlist;
2166
2167         track_canvas->window_to_world (x, y, wx, wy);
2168
2169         GdkEvent event;
2170         event.type = GDK_BUTTON_RELEASE;
2171         event.button.x = wx;
2172         event.button.y = wy;
2173
2174         where = event_frame (&event, &cx, &cy);
2175
2176         if (where < leftmost_frame || where > leftmost_frame + current_page_frames()) {
2177                 /* clearly outside canvas area */
2178                 return;
2179         }
2180
2181         std::pair<TimeAxisView*, int> tv = trackview_by_y_position (cy);
2182         if (tv.first == 0) {
2183                 return;
2184         }
2185
2186         if ((rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
2187                 return;
2188         }
2189
2190         if ((playlist = rtv->playlist()) == 0) {
2191                 return;
2192         }
2193
2194         snap_to (where);
2195
2196         begin_reversible_command (_("insert dragged region"));
2197         playlist->clear_changes ();
2198         playlist->add_region (RegionFactory::create (region, true), where, 1.0);
2199         _session->add_command(new StatefulDiffCommand (playlist));
2200         commit_reversible_command ();
2201 }
2202
2203 void
2204 Editor::insert_route_list_drag (boost::shared_ptr<Route> route, int x, int y)
2205 {
2206         double wx, wy;
2207         double cx, cy;
2208         nframes_t where;
2209         RouteTimeAxisView *dest_rtv = 0;
2210         RouteTimeAxisView *source_rtv = 0;
2211
2212         track_canvas->window_to_world (x, y, wx, wy);
2213         wx += horizontal_position ();
2214         wy += vertical_adjustment.get_value();
2215
2216         GdkEvent event;
2217         event.type = GDK_BUTTON_RELEASE;
2218         event.button.x = wx;
2219         event.button.y = wy;
2220
2221         where = event_frame (&event, &cx, &cy);
2222
2223         std::pair<TimeAxisView*, int> const tv = trackview_by_y_position (cy);
2224         if (tv.first == 0) {
2225                 return;
2226         }
2227
2228         if ((dest_rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
2229                 return;
2230         }
2231
2232         /* use this drag source to add underlay to a track. But we really don't care
2233            about the Route, only the view of the route, so find it first */
2234         for(TrackViewList::iterator it = track_views.begin(); it != track_views.end(); ++it) {
2235                 if((source_rtv = dynamic_cast<RouteTimeAxisView*>(*it)) == 0) {
2236                         continue;
2237                 }
2238
2239                 if(source_rtv->route() == route && source_rtv != dest_rtv) {
2240                         dest_rtv->add_underlay(source_rtv->view());
2241                         break;
2242                 }
2243         }
2244 }
2245
2246 void
2247 Editor::insert_region_list_selection (float times)
2248 {
2249         RouteTimeAxisView *tv = 0;
2250         boost::shared_ptr<Playlist> playlist;
2251
2252         if (clicked_routeview != 0) {
2253                 tv = clicked_routeview;
2254         } else if (!selection->tracks.empty()) {
2255                 if ((tv = dynamic_cast<RouteTimeAxisView*>(selection->tracks.front())) == 0) {
2256                         return;
2257                 }
2258         } else if (entered_track != 0) {
2259                 if ((tv = dynamic_cast<RouteTimeAxisView*>(entered_track)) == 0) {
2260                         return;
2261                 }
2262         } else {
2263                 return;
2264         }
2265
2266         if ((playlist = tv->playlist()) == 0) {
2267                 return;
2268         }
2269
2270         boost::shared_ptr<Region> region = _regions->get_single_selection ();
2271         if (region == 0) {
2272                 return;
2273         }
2274
2275         begin_reversible_command (_("insert region"));
2276         playlist->clear_changes ();
2277         playlist->add_region ((RegionFactory::create (region, true)), get_preferred_edit_position(), times);
2278         _session->add_command(new StatefulDiffCommand (playlist));
2279         commit_reversible_command ();
2280 }
2281
2282 /* BUILT-IN EFFECTS */
2283
2284 void
2285 Editor::reverse_selection ()
2286 {
2287
2288 }
2289
2290 /* GAIN ENVELOPE EDITING */
2291
2292 void
2293 Editor::edit_envelope ()
2294 {
2295 }
2296
2297 /* PLAYBACK */
2298
2299 void
2300 Editor::transition_to_rolling (bool fwd)
2301 {
2302         if (!_session) {
2303                 return;
2304         }
2305
2306         if (_session->config.get_external_sync()) {
2307                 switch (_session->config.get_sync_source()) {
2308                 case JACK:
2309                         break;
2310                 default:
2311                         /* transport controlled by the master */
2312                         return;
2313                 }
2314         }
2315
2316         if (_session->is_auditioning()) {
2317                 _session->cancel_audition ();
2318                 return;
2319         }
2320
2321         _session->request_transport_speed (fwd ? 1.0f : -1.0f);
2322 }
2323
2324 void
2325 Editor::play_from_start ()
2326 {
2327         _session->request_locate (_session->current_start_frame(), true);
2328 }
2329
2330 void
2331 Editor::play_from_edit_point ()
2332 {
2333         _session->request_locate (get_preferred_edit_position(), true);
2334 }
2335
2336 void
2337 Editor::play_from_edit_point_and_return ()
2338 {
2339         framepos_t start_frame;
2340         framepos_t return_frame;
2341
2342         start_frame = get_preferred_edit_position (true);
2343
2344         if (_session->transport_rolling()) {
2345                 _session->request_locate (start_frame, false);
2346                 return;
2347         }
2348
2349         /* don't reset the return frame if its already set */
2350
2351         if ((return_frame = _session->requested_return_frame()) < 0) {
2352                 return_frame = _session->audible_frame();
2353         }
2354
2355         if (start_frame >= 0) {
2356                 _session->request_roll_at_and_return (start_frame, return_frame);
2357         }
2358 }
2359
2360 void
2361 Editor::play_selection ()
2362 {
2363         if (selection->time.empty()) {
2364                 return;
2365         }
2366
2367         _session->request_play_range (&selection->time, true);
2368 }
2369
2370 void
2371 Editor::play_location (Location& location)
2372 {
2373         if (location.start() <= location.end()) {
2374                 return;
2375         }
2376
2377         _session->request_bounded_roll (location.start(), location.end());
2378 }
2379
2380 void
2381 Editor::loop_location (Location& location)
2382 {
2383         if (location.start() <= location.end()) {
2384                 return;
2385         }
2386
2387         Location* tll;
2388
2389         if ((tll = transport_loop_location()) != 0) {
2390                 tll->set (location.start(), location.end());
2391
2392                 // enable looping, reposition and start rolling
2393                 _session->request_play_loop (true);
2394                 _session->request_locate (tll->start(), true);
2395         }
2396 }
2397
2398 void
2399 Editor::raise_region ()
2400 {
2401         selection->foreach_region (&Region::raise);
2402 }
2403
2404 void
2405 Editor::raise_region_to_top ()
2406 {
2407         selection->foreach_region (&Region::raise_to_top);
2408 }
2409
2410 void
2411 Editor::lower_region ()
2412 {
2413         selection->foreach_region (&Region::lower);
2414 }
2415
2416 void
2417 Editor::lower_region_to_bottom ()
2418 {
2419         selection->foreach_region (&Region::lower_to_bottom);
2420 }
2421
2422 /** Show the region editor for the selected regions */
2423 void
2424 Editor::show_region_properties ()
2425 {
2426         selection->foreach_regionview (&RegionView::show_region_editor);
2427 }
2428
2429 /** Show the midi list editor for the selected MIDI regions */
2430 void
2431 Editor::show_midi_list_editor ()
2432 {
2433         selection->foreach_midi_regionview (&MidiRegionView::show_list_editor);
2434 }
2435
2436 void
2437 Editor::rename_region ()
2438 {
2439         RegionSelection rs = get_regions_from_selection_and_entered ();
2440         
2441         if (rs.empty()) {
2442                 return;
2443         }
2444
2445         ArdourDialog d (*this, _("Rename Region"), true, false);
2446         Entry entry;
2447         Label label (_("New name:"));
2448         HBox hbox;
2449
2450         hbox.set_spacing (6);
2451         hbox.pack_start (label, false, false);
2452         hbox.pack_start (entry, true, true);
2453
2454         d.get_vbox()->set_border_width (12);
2455         d.get_vbox()->pack_start (hbox, false, false);
2456
2457         d.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2458         d.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
2459
2460         d.set_size_request (300, -1);
2461         d.set_position (Gtk::WIN_POS_MOUSE);
2462
2463         entry.set_text (selection->regions.front()->region()->name());
2464         entry.select_region (0, -1);
2465
2466         entry.signal_activate().connect (sigc::bind (sigc::mem_fun (d, &Dialog::response), RESPONSE_OK));
2467
2468         d.show_all ();
2469
2470         entry.grab_focus();
2471
2472         int const ret = d.run();
2473
2474         d.hide ();
2475
2476         if (ret != RESPONSE_OK) {
2477                 return;
2478         }
2479         
2480         std::string str = entry.get_text();
2481         strip_whitespace_edges (str);
2482         if (!str.empty()) {
2483                 rs.front()->region()->set_name (str);
2484                 _regions->redisplay ();
2485         }
2486 }
2487
2488 void
2489 Editor::audition_playlist_region_via_route (boost::shared_ptr<Region> region, Route& route)
2490 {
2491         if (_session->is_auditioning()) {
2492                 _session->cancel_audition ();
2493         }
2494
2495         // note: some potential for creativity here, because region doesn't
2496         // have to belong to the playlist that Route is handling
2497
2498         // bool was_soloed = route.soloed();
2499
2500         route.set_solo (true, this);
2501
2502         _session->request_bounded_roll (region->position(), region->position() + region->length());
2503
2504         /* XXX how to unset the solo state ? */
2505 }
2506
2507 /** Start an audition of the first selected region */
2508 void
2509 Editor::play_edit_range ()
2510 {
2511         framepos_t start, end;
2512
2513         if (get_edit_op_range (start, end)) {
2514                 _session->request_bounded_roll (start, end);
2515         }
2516 }
2517
2518 void
2519 Editor::play_selected_region ()
2520 {
2521         framepos_t start = max_framepos;
2522         framepos_t end = 0;
2523
2524         RegionSelection rs = get_regions_from_selection_and_entered ();
2525         
2526         if (rs.empty()) {
2527                 return;
2528         }
2529
2530         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2531                 if ((*i)->region()->position() < start) {
2532                         start = (*i)->region()->position();
2533                 }
2534                 if ((*i)->region()->last_frame() + 1 > end) {
2535                         end = (*i)->region()->last_frame() + 1;
2536                 }
2537         }
2538
2539         _session->request_bounded_roll (start, end);
2540 }
2541
2542 void
2543 Editor::audition_playlist_region_standalone (boost::shared_ptr<Region> region)
2544 {
2545         _session->audition_region (region);
2546 }
2547
2548 void
2549 Editor::region_from_selection ()
2550 {
2551         if (clicked_axisview == 0) {
2552                 return;
2553         }
2554
2555         if (selection->time.empty()) {
2556                 return;
2557         }
2558
2559         framepos_t start = selection->time[clicked_selection].start;
2560         framepos_t end = selection->time[clicked_selection].end;
2561
2562         TrackViewList tracks = get_tracks_for_range_action ();
2563
2564         framepos_t selection_cnt = end - start + 1;
2565
2566         for (TrackSelection::iterator i = tracks.begin(); i != tracks.end(); ++i) {
2567                 boost::shared_ptr<Region> current;
2568                 boost::shared_ptr<Playlist> pl;
2569                 framepos_t internal_start;
2570                 string new_name;
2571
2572                 if ((pl = (*i)->playlist()) == 0) {
2573                         continue;
2574                 }
2575
2576                 if ((current = pl->top_region_at (start)) == 0) {
2577                         continue;
2578                 }
2579
2580                 internal_start = start - current->position();
2581                 RegionFactory::region_name (new_name, current->name(), true);
2582
2583                 PropertyList plist; 
2584                 
2585                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2586                 plist.add (ARDOUR::Properties::length, selection_cnt);
2587                 plist.add (ARDOUR::Properties::name, new_name);
2588                 plist.add (ARDOUR::Properties::layer, 0);
2589
2590                 boost::shared_ptr<Region> region (RegionFactory::create (current, plist));
2591         }
2592 }
2593
2594 void
2595 Editor::create_region_from_selection (vector<boost::shared_ptr<Region> >& new_regions)
2596 {
2597         if (selection->time.empty() || selection->tracks.empty()) {
2598                 return;
2599         }
2600
2601         framepos_t start = selection->time[clicked_selection].start;
2602         framepos_t end = selection->time[clicked_selection].end;
2603
2604         sort_track_selection ();
2605
2606         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
2607                 boost::shared_ptr<Region> current;
2608                 boost::shared_ptr<Playlist> playlist;
2609                 framepos_t internal_start;
2610                 string new_name;
2611
2612                 if ((playlist = (*i)->playlist()) == 0) {
2613                         continue;
2614                 }
2615
2616                 if ((current = playlist->top_region_at(start)) == 0) {
2617                         continue;
2618                 }
2619
2620                 internal_start = start - current->position();
2621                 RegionFactory::region_name (new_name, current->name(), true);
2622
2623                 PropertyList plist; 
2624                 
2625                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2626                 plist.add (ARDOUR::Properties::length, end - start + 1);
2627                 plist.add (ARDOUR::Properties::name, new_name);
2628
2629                 new_regions.push_back (RegionFactory::create (current, plist));
2630         }
2631 }
2632
2633 void
2634 Editor::split_multichannel_region ()
2635 {
2636         RegionSelection rs = get_regions_from_selection_and_entered ();
2637         
2638         if (rs.empty()) {
2639                 return;
2640         }
2641
2642         vector< boost::shared_ptr<Region> > v;
2643
2644         for (list<RegionView*>::iterator x = rs.begin(); x != rs.end(); ++x) {
2645                 (*x)->region()->separate_by_channel (*_session, v);
2646         }
2647 }
2648
2649 void
2650 Editor::new_region_from_selection ()
2651 {
2652         region_from_selection ();
2653         cancel_selection ();
2654 }
2655
2656 static void
2657 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
2658 {
2659         switch (rv->region()->coverage (ar->start, ar->end - 1)) {
2660         case OverlapNone:
2661                 break;
2662         default:
2663                 rs->push_back (rv);
2664         }
2665 }
2666
2667 /** Return either:
2668  *    - selected tracks, or if there are none...
2669  *    - tracks containing selected regions, or if there are none...
2670  *    - all tracks
2671  * @return tracks.
2672  */
2673 TrackViewList
2674 Editor::get_tracks_for_range_action () const
2675 {
2676         TrackViewList t;
2677
2678         if (selection->tracks.empty()) {
2679
2680                 /* use tracks with selected regions */
2681
2682                 RegionSelection rs = selection->regions;
2683
2684                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2685                         TimeAxisView* tv = &(*i)->get_time_axis_view();
2686
2687                         if (!t.contains (tv)) {
2688                                 t.push_back (tv);
2689                         }
2690                 }
2691
2692                 if (t.empty()) {
2693                         /* no regions and no tracks: use all tracks */
2694                         t = track_views;
2695                 }
2696
2697         } else {
2698
2699                 t = selection->tracks;
2700         }
2701
2702         return t;
2703 }
2704
2705 void
2706 Editor::separate_regions_between (const TimeSelection& ts)
2707 {
2708         bool in_command = false;
2709         boost::shared_ptr<Playlist> playlist;
2710         RegionSelection new_selection;
2711
2712         TrackViewList tmptracks = get_tracks_for_range_action ();
2713         sort_track_selection (&tmptracks);
2714
2715         for (TrackSelection::iterator i = tmptracks.begin(); i != tmptracks.end(); ++i) {
2716
2717                 RouteTimeAxisView* rtv;
2718
2719                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2720
2721                         if (rtv->is_track()) {
2722
2723                                 /* no edits to destructive tracks */
2724
2725                                 if (rtv->track()->destructive()) {
2726                                         continue;
2727                                 }
2728
2729                                 if ((playlist = rtv->playlist()) != 0) {
2730
2731                                         playlist->clear_changes ();
2732
2733                                         /* XXX need to consider musical time selections here at some point */
2734
2735                                         double speed = rtv->track()->speed();
2736
2737
2738                                         for (list<AudioRange>::const_iterator t = ts.begin(); t != ts.end(); ++t) {
2739
2740                                                 sigc::connection c = rtv->view()->RegionViewAdded.connect (
2741                                                                 sigc::mem_fun(*this, &Editor::collect_new_region_view));
2742
2743                                                 latest_regionviews.clear ();
2744
2745                                                 playlist->partition ((framepos_t)((*t).start * speed),
2746                                                                 (framepos_t)((*t).end * speed), false);
2747
2748                                                 c.disconnect ();
2749
2750                                                 if (!latest_regionviews.empty()) {
2751
2752                                                         rtv->view()->foreach_regionview (sigc::bind (
2753                                                                                 sigc::ptr_fun (add_if_covered),
2754                                                                                 &(*t), &new_selection));
2755                                                         
2756                                                         if (!in_command) {
2757                                                                 begin_reversible_command (_("separate"));
2758                                                                 in_command = true;
2759                                                         }
2760                                                         
2761                                                         /* pick up changes to existing regions */
2762
2763                                                         vector<Command*> cmds;
2764                                                         playlist->rdiff (cmds);
2765                                                         _session->add_commands (cmds);
2766
2767                                                         /* pick up changes to the playlist itself (adds/removes)
2768                                                          */
2769
2770                                                         _session->add_command(new StatefulDiffCommand (playlist));
2771                                                 }
2772                                         }
2773                                 }
2774                         }
2775                 }
2776         }
2777
2778         if (in_command) {
2779                 selection->set (new_selection);
2780                 set_mouse_mode (MouseObject);
2781
2782                 commit_reversible_command ();
2783         }
2784 }
2785
2786 struct PlaylistState {
2787     boost::shared_ptr<Playlist> playlist;
2788     XMLNode*  before;
2789 };
2790
2791 /** Take tracks from get_tracks_for_range_action and cut any regions
2792  *  on those tracks so that the tracks are empty over the time
2793  *  selection.
2794  */
2795 void
2796 Editor::separate_region_from_selection ()
2797 {
2798         /* preferentially use *all* ranges in the time selection if we're in range mode
2799            to allow discontiguous operation, since get_edit_op_range() currently
2800            returns a single range.
2801         */
2802
2803         if (mouse_mode == MouseRange && !selection->time.empty()) {
2804
2805                 separate_regions_between (selection->time);
2806
2807         } else {
2808
2809                 framepos_t start;
2810                 framepos_t end;
2811
2812                 if (get_edit_op_range (start, end)) {
2813
2814                         AudioRange ar (start, end, 1);
2815                         TimeSelection ts;
2816                         ts.push_back (ar);
2817
2818                         separate_regions_between (ts);
2819                 }
2820         }
2821 }
2822
2823 void
2824 Editor::separate_region_from_punch ()
2825 {
2826         Location* loc  = _session->locations()->auto_punch_location();
2827         if (loc) {
2828                 separate_regions_using_location (*loc);
2829         }
2830 }
2831
2832 void
2833 Editor::separate_region_from_loop ()
2834 {
2835         Location* loc  = _session->locations()->auto_loop_location();
2836         if (loc) {
2837                 separate_regions_using_location (*loc);
2838         }
2839 }
2840
2841 void
2842 Editor::separate_regions_using_location (Location& loc)
2843 {
2844         if (loc.is_mark()) {
2845                 return;
2846         }
2847
2848         AudioRange ar (loc.start(), loc.end(), 1);
2849         TimeSelection ts;
2850
2851         ts.push_back (ar);
2852
2853         separate_regions_between (ts);
2854 }
2855
2856 /** Separate regions under the selected region */
2857 void
2858 Editor::separate_under_selected_regions ()
2859 {
2860         vector<PlaylistState> playlists;
2861
2862         RegionSelection rs = get_regions_from_selection_and_entered ();
2863
2864         if (!_session || rs.empty()) {
2865                 return;
2866         }
2867
2868         begin_reversible_command (_("separate region under"));
2869
2870         list<boost::shared_ptr<Region> > regions_to_remove;
2871
2872         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2873                 // we can't just remove the region(s) in this loop because
2874                 // this removes them from the RegionSelection, and they thus
2875                 // disappear from underneath the iterator, and the ++i above
2876                 // SEGVs in a puzzling fashion.
2877
2878                 // so, first iterate over the regions to be removed from rs and
2879                 // add them to the regions_to_remove list, and then
2880                 // iterate over the list to actually remove them.
2881
2882                 regions_to_remove.push_back ((*i)->region());
2883         }
2884
2885         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
2886
2887                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
2888
2889                 if (!playlist) {
2890                         // is this check necessary?
2891                         continue;
2892                 }
2893
2894                 vector<PlaylistState>::iterator i;
2895
2896                 //only take state if this is a new playlist.
2897                 for (i = playlists.begin(); i != playlists.end(); ++i) {
2898                         if ((*i).playlist == playlist) {
2899                                 break;
2900                         }
2901                 }
2902
2903                 if (i == playlists.end()) {
2904
2905                         PlaylistState before;
2906                         before.playlist = playlist;
2907                         before.before = &playlist->get_state();
2908
2909                         playlist->freeze ();
2910                         playlists.push_back(before);
2911                 }
2912
2913                 //Partition on the region bounds
2914                 playlist->partition ((*rl)->first_frame() - 1, (*rl)->last_frame() + 1, true);
2915                 
2916                 //Re-add region that was just removed due to the partition operation
2917                 playlist->add_region( (*rl), (*rl)->first_frame() );
2918         }
2919
2920         vector<PlaylistState>::iterator pl;
2921
2922         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
2923                 (*pl).playlist->thaw ();
2924                 _session->add_command(new MementoCommand<Playlist>(*(*pl).playlist, (*pl).before, &(*pl).playlist->get_state()));
2925         }
2926
2927         commit_reversible_command ();
2928 }
2929
2930 void
2931 Editor::crop_region_to_selection ()
2932 {
2933         if (!selection->time.empty()) {
2934
2935                 crop_region_to (selection->time.start(), selection->time.end_frame());
2936
2937         } else {
2938
2939                 framepos_t start;
2940                 framepos_t end;
2941
2942                 if (get_edit_op_range (start, end)) {
2943                         crop_region_to (start, end);
2944                 }
2945         }
2946
2947 }
2948
2949 void
2950 Editor::crop_region_to (framepos_t start, framepos_t end)
2951 {
2952         vector<boost::shared_ptr<Playlist> > playlists;
2953         boost::shared_ptr<Playlist> playlist;
2954         TrackViewList* ts;
2955
2956         if (selection->tracks.empty()) {
2957                 ts = &track_views;
2958         } else {
2959                 sort_track_selection ();
2960                 ts = &selection->tracks;
2961         }
2962
2963         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
2964
2965                 RouteTimeAxisView* rtv;
2966
2967                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2968
2969                         boost::shared_ptr<Track> t = rtv->track();
2970
2971                         if (t != 0 && ! t->destructive()) {
2972
2973                                 if ((playlist = rtv->playlist()) != 0) {
2974                                         playlists.push_back (playlist);
2975                                 }
2976                         }
2977                 }
2978         }
2979
2980         if (playlists.empty()) {
2981                 return;
2982         }
2983
2984         framepos_t the_start;
2985         framepos_t the_end;
2986         framepos_t cnt;
2987
2988         begin_reversible_command (_("trim to selection"));
2989
2990         for (vector<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2991
2992                 boost::shared_ptr<Region> region;
2993
2994                 the_start = start;
2995
2996                 if ((region = (*i)->top_region_at(the_start)) == 0) {
2997                         continue;
2998                 }
2999
3000                 /* now adjust lengths to that we do the right thing
3001                    if the selection extends beyond the region
3002                 */
3003
3004                 the_start = max (the_start, (framepos_t) region->position());
3005                 if (max_framepos - the_start < region->length()) {
3006                         the_end = the_start + region->length() - 1;
3007                 } else {
3008                         the_end = max_framepos;
3009                 }
3010                 the_end = min (end, the_end);
3011                 cnt = the_end - the_start + 1;
3012
3013                 region->clear_changes ();
3014                 region->trim_to (the_start, cnt, this);
3015                 _session->add_command (new StatefulDiffCommand (region));
3016         }
3017
3018         commit_reversible_command ();
3019 }
3020
3021 void
3022 Editor::region_fill_track ()
3023 {
3024         RegionSelection rs = get_regions_from_selection_and_entered ();
3025
3026         if (!_session || rs.empty()) {
3027                 return;
3028         }
3029
3030         framepos_t const end = _session->current_end_frame ();
3031
3032         begin_reversible_command (_("region fill"));
3033
3034         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3035
3036                 boost::shared_ptr<Region> region ((*i)->region());
3037
3038                 boost::shared_ptr<Playlist> pl = region->playlist();
3039
3040                 if (end <= region->last_frame()) {
3041                         return;
3042                 }
3043
3044                 double times = (double) (end - region->last_frame()) / (double) region->length();
3045
3046                 if (times == 0) {
3047                         return;
3048                 }
3049
3050                 pl->clear_changes ();
3051                 pl->add_region (RegionFactory::create (region, true), region->last_frame(), times);
3052                 _session->add_command (new StatefulDiffCommand (pl));
3053         }
3054
3055         commit_reversible_command ();
3056 }
3057
3058 void
3059 Editor::region_fill_selection ()
3060 {
3061         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3062                 return;
3063         }
3064
3065         if (selection->time.empty()) {
3066                 return;
3067         }
3068
3069         boost::shared_ptr<Region> region = _regions->get_single_selection ();
3070         if (region == 0) {
3071                 return;
3072         }
3073
3074         framepos_t start = selection->time[clicked_selection].start;
3075         framepos_t end = selection->time[clicked_selection].end;
3076
3077         boost::shared_ptr<Playlist> playlist;
3078
3079         if (selection->tracks.empty()) {
3080                 return;
3081         }
3082
3083         framepos_t selection_length = end - start;
3084         float times = (float)selection_length / region->length();
3085
3086         begin_reversible_command (_("fill selection"));
3087
3088         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3089
3090                 if ((playlist = (*i)->playlist()) == 0) {
3091                         continue;
3092                 }
3093
3094                 playlist->clear_changes ();
3095                 playlist->add_region (RegionFactory::create (region, true), start, times);
3096                 _session->add_command (new StatefulDiffCommand (playlist));
3097         }
3098
3099         commit_reversible_command ();
3100 }
3101
3102 void
3103 Editor::set_region_sync_position ()
3104 {
3105         set_sync_point (get_preferred_edit_position (), get_regions_from_selection_and_edit_point ());
3106 }
3107
3108 void
3109 Editor::set_sync_point (framepos_t where, const RegionSelection& rs)
3110 {
3111         bool in_command = false;
3112
3113         for (RegionSelection::const_iterator r = rs.begin(); r != rs.end(); ++r) {
3114
3115                 if (!(*r)->region()->covers (where)) {
3116                         continue;
3117                 }
3118
3119                 boost::shared_ptr<Region> region ((*r)->region());
3120
3121                 if (!in_command) {
3122                         begin_reversible_command (_("set sync point"));
3123                         in_command = true;
3124                 }
3125
3126                 region->clear_changes ();
3127                 region->set_sync_position (where);
3128                 _session->add_command(new StatefulDiffCommand (region));
3129         }
3130
3131         if (in_command) {
3132                 commit_reversible_command ();
3133         }
3134 }
3135
3136 /** Remove the sync positions of the selection */
3137 void
3138 Editor::remove_region_sync ()
3139 {
3140         RegionSelection rs = get_regions_from_selection_and_entered ();
3141         
3142         if (rs.empty()) {
3143                 return;
3144         }
3145
3146         begin_reversible_command (_("remove region sync"));
3147         
3148         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3149
3150                 (*i)->region()->clear_changes ();
3151                 (*i)->region()->clear_sync_position ();
3152                 _session->add_command(new StatefulDiffCommand ((*i)->region()));
3153         }
3154         
3155         commit_reversible_command ();
3156 }
3157
3158 void
3159 Editor::naturalize_region ()
3160 {
3161         RegionSelection rs = get_regions_from_selection_and_entered ();
3162
3163         if (rs.empty()) {
3164                 return;
3165         }
3166
3167         if (rs.size() > 1) {
3168                 begin_reversible_command (_("move regions to original position"));
3169         } else {
3170                 begin_reversible_command (_("move region to original position"));
3171         }
3172                 
3173         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3174                 (*i)->region()->clear_changes ();
3175                 (*i)->region()->move_to_natural_position (this);
3176                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
3177         }
3178         
3179         commit_reversible_command ();
3180 }
3181
3182 void
3183 Editor::align_regions (RegionPoint what)
3184 {
3185         RegionSelection const rs = get_regions_from_selection_and_edit_point ();
3186         
3187         if (rs.empty()) {
3188                 return;
3189         }
3190
3191         begin_reversible_command (_("align selection"));
3192
3193         framepos_t const position = get_preferred_edit_position ();
3194
3195         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
3196                 align_region_internal ((*i)->region(), what, position);
3197         }
3198
3199         commit_reversible_command ();
3200 }
3201
3202 struct RegionSortByTime {
3203     bool operator() (const RegionView* a, const RegionView* b) {
3204             return a->region()->position() < b->region()->position();
3205     }
3206 };
3207
3208 void
3209 Editor::align_regions_relative (RegionPoint point)
3210 {
3211         RegionSelection const rs = get_regions_from_selection_and_edit_point ();
3212         
3213         if (rs.empty()) {
3214                 return;
3215         }
3216
3217         framepos_t const position = get_preferred_edit_position ();
3218
3219         framepos_t distance = 0;
3220         framepos_t pos = 0;
3221         int dir = 1;
3222
3223         list<RegionView*> sorted;
3224         rs.by_position (sorted);
3225
3226         boost::shared_ptr<Region> r ((*sorted.begin())->region());
3227
3228         switch (point) {
3229         case Start:
3230                 pos = position;
3231                 if (position > r->position()) {
3232                         distance = position - r->position();
3233                 } else {
3234                         distance = r->position() - position;
3235                         dir = -1;
3236                 }
3237                 break;
3238
3239         case End:
3240                 if (position > r->last_frame()) {
3241                         distance = position - r->last_frame();
3242                         pos = r->position() + distance;
3243                 } else {
3244                         distance = r->last_frame() - position;
3245                         pos = r->position() - distance;
3246                         dir = -1;
3247                 }
3248                 break;
3249
3250         case SyncPoint:
3251                 pos = r->adjust_to_sync (position);
3252                 if (pos > r->position()) {
3253                         distance = pos - r->position();
3254                 } else {
3255                         distance = r->position() - pos;
3256                         dir = -1;
3257                 }
3258                 break;
3259         }
3260
3261         if (pos == r->position()) {
3262                 return;
3263         }
3264
3265         begin_reversible_command (_("align selection (relative)"));
3266
3267         /* move first one specially */
3268
3269         r->clear_changes ();
3270         r->set_position (pos, this);
3271         _session->add_command(new StatefulDiffCommand (r));
3272
3273         /* move rest by the same amount */
3274
3275         sorted.pop_front();
3276
3277         for (list<RegionView*>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
3278
3279                 boost::shared_ptr<Region> region ((*i)->region());
3280
3281                 region->clear_changes ();
3282
3283                 if (dir > 0) {
3284                         region->set_position (region->position() + distance, this);
3285                 } else {
3286                         region->set_position (region->position() - distance, this);
3287                 }
3288                 
3289                 _session->add_command(new StatefulDiffCommand (region));
3290
3291         }
3292
3293         commit_reversible_command ();
3294 }
3295
3296 void
3297 Editor::align_region (boost::shared_ptr<Region> region, RegionPoint point, framepos_t position)
3298 {
3299         begin_reversible_command (_("align region"));
3300         align_region_internal (region, point, position);
3301         commit_reversible_command ();
3302 }
3303
3304 void
3305 Editor::align_region_internal (boost::shared_ptr<Region> region, RegionPoint point, framepos_t position)
3306 {
3307         region->clear_changes ();
3308
3309         switch (point) {
3310         case SyncPoint:
3311                 region->set_position (region->adjust_to_sync (position), this);
3312                 break;
3313
3314         case End:
3315                 if (position > region->length()) {
3316                         region->set_position (position - region->length(), this);
3317                 }
3318                 break;
3319
3320         case Start:
3321                 region->set_position (position, this);
3322                 break;
3323         }
3324
3325         _session->add_command(new StatefulDiffCommand (region));
3326 }
3327
3328 void
3329 Editor::trim_region_front ()
3330 {
3331         trim_region (true);
3332 }
3333
3334 void
3335 Editor::trim_region_back ()
3336 {
3337         trim_region (false);
3338 }
3339
3340 void
3341 Editor::trim_region (bool front)
3342 {
3343         framepos_t where = get_preferred_edit_position();
3344         RegionSelection rs = get_regions_from_selection_and_edit_point ();
3345
3346         if (rs.empty()) {
3347                 return;
3348         }
3349
3350         begin_reversible_command (front ? _("trim front") : _("trim back"));
3351
3352         for (list<RegionView*>::const_iterator i = rs.by_layer().begin(); i != rs.by_layer().end(); ++i) {
3353                 if (!(*i)->region()->locked()) {
3354                         
3355                         (*i)->region()->clear_changes ();
3356                         
3357                         if (front) {
3358                                 (*i)->region()->trim_front (where, this);
3359                         } else {
3360                                 (*i)->region()->trim_end (where, this);
3361                         }
3362                         
3363                         _session->add_command (new StatefulDiffCommand ((*i)->region()));
3364                 }
3365         }
3366
3367         commit_reversible_command ();
3368 }
3369
3370 /** Trim the end of the selected regions to the position of the edit cursor */
3371 void
3372 Editor::trim_region_to_loop ()
3373 {
3374         Location* loc = _session->locations()->auto_loop_location();
3375         if (!loc) {
3376                 return;
3377         }
3378         trim_region_to_location (*loc, _("trim to loop"));
3379 }
3380
3381 void
3382 Editor::trim_region_to_punch ()
3383 {
3384         Location* loc = _session->locations()->auto_punch_location();
3385         if (!loc) {
3386                 return;
3387         }
3388         trim_region_to_location (*loc, _("trim to punch"));
3389 }
3390
3391 void
3392 Editor::trim_region_to_location (const Location& loc, const char* str)
3393 {
3394         RegionSelection rs = get_regions_from_selection_and_entered ();
3395
3396         begin_reversible_command (str);
3397
3398         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3399                 RegionView* rv = (*x);
3400
3401                 /* require region to span proposed trim */
3402                 switch (rv->region()->coverage (loc.start(), loc.end())) {
3403                 case OverlapInternal:
3404                         break;
3405                 default:
3406                         continue;
3407                 }
3408
3409                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3410                 if (!tav) {
3411                         return;
3412                 }
3413
3414                 float speed = 1.0;
3415                 framepos_t start;
3416                 framepos_t end;
3417
3418                 if (tav->track() != 0) {
3419                         speed = tav->track()->speed();
3420                 }
3421
3422                 start = session_frame_to_track_frame (loc.start(), speed);
3423                 end = session_frame_to_track_frame (loc.end(), speed);
3424                 
3425                 rv->region()->clear_changes ();
3426                 rv->region()->trim_to (start, (end - start), this);
3427                 _session->add_command(new StatefulDiffCommand (rv->region()));
3428         }
3429
3430         commit_reversible_command ();
3431 }
3432
3433 void
3434 Editor::trim_region_to_previous_region_end ()
3435 {
3436         return trim_to_region(false);
3437 }
3438
3439 void
3440 Editor::trim_region_to_next_region_start ()
3441 {
3442         return trim_to_region(true);
3443 }
3444
3445 void
3446 Editor::trim_to_region(bool forward)
3447 {
3448         RegionSelection rs = get_regions_from_selection_and_entered ();
3449
3450         begin_reversible_command (_("trim to region"));
3451
3452         boost::shared_ptr<Region> next_region;
3453
3454         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3455
3456                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*x);
3457
3458                 if (!arv) {
3459                         continue;
3460                 }
3461
3462                 AudioTimeAxisView* atav = dynamic_cast<AudioTimeAxisView*> (&arv->get_time_axis_view());
3463
3464                 if (!atav) {
3465                         return;
3466                 }
3467
3468                 float speed = 1.0;
3469
3470                 if (atav->track() != 0) {
3471                         speed = atav->track()->speed();
3472                 }
3473
3474
3475                 boost::shared_ptr<Region> region = arv->region();
3476                 boost::shared_ptr<Playlist> playlist (region->playlist());
3477
3478                 region->clear_changes ();
3479
3480                 if(forward){
3481
3482                     next_region = playlist->find_next_region (region->first_frame(), Start, 1);
3483
3484                     if(!next_region){
3485                         continue;
3486                     }
3487
3488                     region->trim_end((framepos_t) ( (next_region->first_frame() - 1) * speed), this);
3489                     arv->region_changed (PropertyChange (ARDOUR::Properties::length));
3490                 }
3491                 else {
3492
3493                     next_region = playlist->find_next_region (region->first_frame(), Start, 0);
3494
3495                     if(!next_region){
3496                         continue;
3497                     }
3498
3499                     region->trim_front((framepos_t) ((next_region->last_frame() + 1) * speed), this);
3500
3501                     arv->region_changed (ARDOUR::bounds_change);
3502                 }
3503
3504                 _session->add_command(new StatefulDiffCommand (region));
3505         }
3506
3507         commit_reversible_command ();
3508 }
3509
3510 void
3511 Editor::unfreeze_route ()
3512 {
3513         if (clicked_routeview == 0 || !clicked_routeview->is_track()) {
3514                 return;
3515         }
3516
3517         clicked_routeview->track()->unfreeze ();
3518 }
3519
3520 void*
3521 Editor::_freeze_thread (void* arg)
3522 {
3523         SessionEvent::create_per_thread_pool ("freeze events", 64);
3524
3525         return static_cast<Editor*>(arg)->freeze_thread ();
3526 }
3527
3528 void*
3529 Editor::freeze_thread ()
3530 {
3531         clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
3532         current_interthread_info->done = true;
3533         return 0;
3534 }
3535
3536 void
3537 Editor::freeze_route ()
3538 {
3539         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3540                 return;
3541         }
3542
3543         InterThreadInfo itt;
3544         current_interthread_info = &itt;
3545
3546         InterthreadProgressWindow ipw (current_interthread_info, _("Freeze"), _("Cancel Freeze"));
3547
3548         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3549
3550         set_canvas_cursor (wait_cursor);
3551
3552         while (!itt.done && !itt.cancel) {
3553                 gtk_main_iteration ();
3554         }
3555
3556         current_interthread_info = 0;
3557         set_canvas_cursor (current_canvas_cursor);
3558 }
3559
3560 void
3561 Editor::bounce_range_selection (bool replace, bool enable_processing)
3562 {
3563         if (selection->time.empty()) {
3564                 return;
3565         }
3566
3567         TrackSelection views = selection->tracks;
3568
3569         framepos_t start = selection->time[clicked_selection].start;
3570         framepos_t end = selection->time[clicked_selection].end;
3571         framepos_t cnt = end - start + 1;
3572
3573         begin_reversible_command (_("bounce range"));
3574
3575         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3576
3577                 RouteTimeAxisView* rtv;
3578
3579                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3580                         continue;
3581                 }
3582
3583                 boost::shared_ptr<Playlist> playlist;
3584
3585                 if ((playlist = rtv->playlist()) == 0) {
3586                         return;
3587                 }
3588
3589                 InterThreadInfo itt;
3590
3591                 playlist->clear_changes ();
3592                 playlist->clear_owned_changes ();
3593                 
3594                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3595
3596                 if (replace) {
3597                         list<AudioRange> ranges;
3598                         ranges.push_back (AudioRange (start, start+cnt, 0));
3599                         playlist->cut (ranges); // discard result
3600                         playlist->add_region (r, start);
3601                 }
3602
3603                 vector<Command*> cmds;
3604                 playlist->rdiff (cmds);
3605                 _session->add_commands (cmds);
3606
3607                 _session->add_command (new StatefulDiffCommand (playlist));
3608         }
3609
3610         commit_reversible_command ();
3611 }
3612
3613 /** Cut selected regions, automation points or a time range */
3614 void
3615 Editor::cut ()
3616 {
3617         cut_copy (Cut);
3618 }
3619
3620 /** Copy selected regions, automation points or a time range */
3621 void
3622 Editor::copy ()
3623 {
3624         cut_copy (Copy);
3625 }
3626
3627
3628 /** @return true if a Cut, Copy or Clear is possible */
3629 bool
3630 Editor::can_cut_copy () const
3631 {
3632         switch (current_mouse_mode()) {
3633
3634         case MouseObject:
3635                 if (!selection->regions.empty() || !selection->points.empty()) {
3636                         return true;
3637                 }
3638                 break;
3639
3640         case MouseRange:
3641                 if (!selection->time.empty()) {
3642                         return true;
3643                 }
3644                 break;
3645
3646         default:
3647                 break;
3648         }
3649
3650         return false;
3651 }
3652
3653
3654 /** Cut, copy or clear selected regions, automation points or a time range.
3655  * @param op Operation (Cut, Copy or Clear)
3656  */
3657 void
3658 Editor::cut_copy (CutCopyOp op)
3659 {
3660         /* only cancel selection if cut/copy is successful.*/
3661
3662         string opname;
3663
3664         switch (op) {
3665         case Cut:
3666                 opname = _("cut");
3667                 break;
3668         case Copy:
3669                 opname = _("copy");
3670                 break;
3671         case Clear:
3672                 opname = _("clear");
3673                 break;
3674         }
3675
3676         /* if we're deleting something, and the mouse is still pressed,
3677            the thing we started a drag for will be gone when we release
3678            the mouse button(s). avoid this. see part 2 at the end of
3679            this function.
3680         */
3681
3682         if (op == Cut || op == Clear) {
3683                 if (_drags->active ()) {
3684                         _drags->abort ();
3685                 }
3686         }
3687
3688         cut_buffer->clear ();
3689
3690         if (entered_marker) {
3691
3692                 /* cut/delete op while pointing at a marker */
3693
3694                 bool ignored;
3695                 Location* loc = find_location_from_marker (entered_marker, ignored);
3696
3697                 if (_session && loc) {
3698                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3699                 }
3700
3701                 _drags->abort ();
3702                 return;
3703         }
3704
3705         if (internal_editing()) {
3706
3707                 switch (current_mouse_mode()) {
3708                 case MouseObject:
3709                 case MouseRange:
3710                         cut_copy_midi (op);
3711                         break;
3712                 default:
3713                         break;
3714                 }
3715
3716         } else {
3717
3718                 RegionSelection rs;
3719
3720                 /* we only want to cut regions if some are selected */
3721
3722                 if (!selection->regions.empty()) {
3723                         rs = selection->regions;
3724                 }
3725
3726                 switch (current_mouse_mode()) {
3727                 case MouseObject:
3728                         if (!rs.empty() || !selection->points.empty()) {
3729
3730                                 begin_reversible_command (opname + _(" objects"));
3731
3732                                 if (!rs.empty()) {
3733                                         cut_copy_regions (op, rs);
3734
3735                                         if (op == Cut) {
3736                                                 selection->clear_regions ();
3737                                         }
3738                                 }
3739
3740                                 if (!selection->points.empty()) {
3741                                         cut_copy_points (op);
3742
3743                                         if (op == Cut) {
3744                                                 selection->clear_points ();
3745                                         }
3746                                 }
3747
3748                                 commit_reversible_command ();
3749                                 break; // terminate case statement here
3750                         }
3751                         if (!selection->time.empty()) {
3752                                 /* don't cause suprises */
3753                                 break;
3754                         }
3755                         // fall thru if there was nothing selected
3756
3757                 case MouseRange:
3758                         if (selection->time.empty()) {
3759                                 framepos_t start, end;
3760                                 if (!get_edit_op_range (start, end)) {
3761                                         return;
3762                                 }
3763                                 selection->set (start, end);
3764                         }
3765
3766                         begin_reversible_command (opname + _(" range"));
3767                         cut_copy_ranges (op);
3768                         commit_reversible_command ();
3769
3770                         if (op == Cut) {
3771                                 selection->clear_time ();
3772                         }
3773
3774                         break;
3775
3776                 default:
3777                         break;
3778                 }
3779         }
3780
3781         if (op == Cut || op == Clear) {
3782                 _drags->abort ();
3783         }
3784 }
3785
3786 /** Cut, copy or clear selected automation points.
3787  * @param op Operation (Cut, Copy or Clear)
3788  */
3789 void
3790 Editor::cut_copy_points (CutCopyOp op)
3791 {
3792         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3793
3794                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3795
3796                 if (atv) {
3797                         atv->cut_copy_clear_objects (selection->points, op);
3798                 }
3799         }
3800 }
3801
3802 /** Cut, copy or clear selected automation points.
3803  * @param op Operation (Cut, Copy or Clear)
3804  */
3805 void
3806 Editor::cut_copy_midi (CutCopyOp op)
3807 {
3808         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3809                 MidiRegionView* mrv = *i;
3810                 mrv->cut_copy_clear (op);
3811         }
3812 }
3813
3814
3815
3816 struct lt_playlist {
3817     bool operator () (const PlaylistState& a, const PlaylistState& b) {
3818             return a.playlist < b.playlist;
3819     }
3820 };
3821
3822 struct PlaylistMapping {
3823     TimeAxisView* tv;
3824     boost::shared_ptr<Playlist> pl;
3825
3826     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3827 };
3828
3829 /** Remove `clicked_regionview' */
3830 void
3831 Editor::remove_clicked_region ()
3832 {
3833         if (clicked_routeview == 0 || clicked_regionview == 0) {
3834                 return;
3835         }
3836
3837         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3838
3839         begin_reversible_command (_("remove region"));
3840         playlist->clear_changes ();
3841         playlist->remove_region (clicked_regionview->region());
3842         _session->add_command(new StatefulDiffCommand (playlist));
3843         commit_reversible_command ();
3844 }
3845
3846
3847 /** Remove the selected regions */
3848 void
3849 Editor::remove_selected_regions ()
3850 {
3851         RegionSelection rs = get_regions_from_selection_and_entered ();
3852
3853         if (!_session || rs.empty()) {
3854                 return;
3855         }
3856
3857         begin_reversible_command (_("remove region"));
3858
3859         list<boost::shared_ptr<Region> > regions_to_remove;
3860
3861         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3862                 // we can't just remove the region(s) in this loop because
3863                 // this removes them from the RegionSelection, and they thus
3864                 // disappear from underneath the iterator, and the ++i above
3865                 // SEGVs in a puzzling fashion.
3866
3867                 // so, first iterate over the regions to be removed from rs and
3868                 // add them to the regions_to_remove list, and then
3869                 // iterate over the list to actually remove them.
3870
3871                 regions_to_remove.push_back ((*i)->region());
3872         }
3873
3874         vector<boost::shared_ptr<Playlist> > playlists;
3875
3876         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
3877
3878                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
3879
3880                 if (!playlist) {
3881                         // is this check necessary?
3882                         continue;
3883                 }
3884
3885                 vector<boost::shared_ptr<Playlist> >::iterator i;
3886
3887                 //only prep history if this is a new playlist.
3888                 for (i = playlists.begin(); i != playlists.end(); ++i) {
3889                         if ((*i) == playlist) {
3890                                 break;
3891                         }
3892                 }
3893
3894                 if (i == playlists.end()) {
3895
3896                         playlist->clear_changes ();
3897                         playlist->freeze ();
3898
3899                         playlists.push_back (playlist);
3900                 }
3901
3902                 playlist->remove_region (*rl);
3903         }
3904
3905         vector<boost::shared_ptr<Playlist> >::iterator pl;
3906
3907         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
3908                 (*pl)->thaw ();
3909                 _session->add_command(new StatefulDiffCommand (*pl));
3910         }
3911
3912         commit_reversible_command ();
3913 }
3914
3915 /** Cut, copy or clear selected regions.
3916  * @param op Operation (Cut, Copy or Clear)
3917  */
3918 void
3919 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
3920 {
3921         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
3922            a map when we want ordered access to both elements. i think.
3923         */
3924
3925         vector<PlaylistMapping> pmap;
3926
3927         framepos_t first_position = max_framepos;
3928
3929         typedef set<boost::shared_ptr<Playlist> > FreezeList;
3930         FreezeList freezelist;
3931
3932         /* get ordering correct before we cut/copy */
3933
3934         rs.sort_by_position_and_track ();
3935
3936         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3937
3938                 first_position = min ((framepos_t) (*x)->region()->position(), first_position);
3939
3940                 if (op == Cut || op == Clear) {
3941                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3942
3943                         if (pl) {
3944                                 FreezeList::iterator fl;
3945
3946                                 //only take state if this is a new playlist.
3947                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
3948                                         if ((*fl) == pl) {
3949                                                 break;
3950                                         }
3951                                 }
3952
3953                                 if (fl == freezelist.end()) {
3954                                         pl->clear_changes();
3955                                         pl->freeze ();
3956                                         freezelist.insert (pl);
3957                                 }
3958                         }
3959                 }
3960
3961                 TimeAxisView* tv = &(*x)->get_time_axis_view();
3962                 vector<PlaylistMapping>::iterator z;
3963
3964                 for (z = pmap.begin(); z != pmap.end(); ++z) {
3965                         if ((*z).tv == tv) {
3966                                 break;
3967                         }
3968                 }
3969
3970                 if (z == pmap.end()) {
3971                         pmap.push_back (PlaylistMapping (tv));
3972                 }
3973         }
3974
3975         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
3976
3977                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3978
3979                 if (!pl) {
3980                         /* region not yet associated with a playlist (e.g. unfinished
3981                            capture pass.
3982                         */
3983                         ++x;
3984                         continue;
3985                 }
3986
3987                 TimeAxisView& tv = (*x)->get_time_axis_view();
3988                 boost::shared_ptr<Playlist> npl;
3989                 RegionSelection::iterator tmp;
3990
3991                 tmp = x;
3992                 ++tmp;
3993
3994                 vector<PlaylistMapping>::iterator z;
3995
3996                 for (z = pmap.begin(); z != pmap.end(); ++z) {
3997                         if ((*z).tv == &tv) {
3998                                 break;
3999                         }
4000                 }
4001
4002                 assert (z != pmap.end());
4003
4004                 if (!(*z).pl) {
4005                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4006                         npl->freeze();
4007                         (*z).pl = npl;
4008                 } else {
4009                         npl = (*z).pl;
4010                 }
4011
4012                 boost::shared_ptr<Region> r = (*x)->region();
4013                 boost::shared_ptr<Region> _xx;
4014
4015                 assert (r != 0);
4016
4017                 switch (op) {
4018                 case Cut:
4019                         _xx = RegionFactory::create (r);
4020                         npl->add_region (_xx, r->position() - first_position);
4021                         pl->remove_region (r);
4022                         break;
4023
4024                 case Copy:
4025                         /* copy region before adding, so we're not putting same object into two different playlists */
4026                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4027                         break;
4028
4029                 case Clear:
4030                         pl->remove_region (r);
4031                         break;
4032                 }
4033
4034                 x = tmp;
4035         }
4036
4037         list<boost::shared_ptr<Playlist> > foo;
4038
4039         /* the pmap is in the same order as the tracks in which selected regions occured */
4040
4041         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4042                 if ((*i).pl) {
4043                         (*i).pl->thaw();
4044                         foo.push_back ((*i).pl);
4045                 }
4046         }
4047
4048         if (!foo.empty()) {
4049                 cut_buffer->set (foo);
4050         }
4051
4052         if (pmap.empty()) {
4053                 _last_cut_copy_source_track = 0;
4054         } else {
4055                 _last_cut_copy_source_track = pmap.front().tv;
4056         }
4057         
4058         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4059                 (*pl)->thaw ();
4060                 _session->add_command (new StatefulDiffCommand (*pl));
4061         }
4062 }
4063
4064 void
4065 Editor::cut_copy_ranges (CutCopyOp op)
4066 {
4067         TrackViewList* ts;
4068         TrackViewList entered;
4069
4070         if (selection->tracks.empty()) {
4071                 if (!entered_track) {
4072                         return;
4073                 }
4074                 entered.push_back (entered_track);
4075                 ts = &entered;
4076         } else {
4077                 ts = &selection->tracks;
4078         }
4079
4080         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4081                 (*i)->cut_copy_clear (*selection, op);
4082         }
4083 }
4084
4085 void
4086 Editor::paste (float times)
4087 {
4088         paste_internal (get_preferred_edit_position(), times);
4089 }
4090
4091 void
4092 Editor::mouse_paste ()
4093 {
4094         framepos_t where;
4095         bool ignored;
4096
4097         if (!mouse_frame (where, ignored)) {
4098                 return;
4099         }
4100
4101         snap_to (where);
4102         paste_internal (where, 1);
4103 }
4104
4105 void
4106 Editor::paste_internal (framepos_t position, float times)
4107 {
4108         bool commit = false;
4109
4110         if (internal_editing()) {
4111                 if (cut_buffer->midi_notes.empty()) {
4112                         return;
4113                 }
4114         } else {
4115                 if (cut_buffer->empty()) {
4116                         return;
4117                 }
4118         }
4119
4120         if (position == max_framepos) {
4121                 position = get_preferred_edit_position();
4122         }
4123
4124         begin_reversible_command (_("paste"));
4125
4126         TrackViewList ts;
4127         TrackViewList::iterator i;
4128         size_t nth;
4129
4130         /* get everything in the correct order */
4131
4132         if (!selection->tracks.empty()) {
4133                 /* there are some selected tracks, so paste to them */
4134                 sort_track_selection ();
4135                 ts = selection->tracks;
4136         } else if (_last_cut_copy_source_track) {
4137                 /* otherwise paste to the track that the cut/copy came from;
4138                    see discussion in mants #3333.
4139                 */
4140                 ts.push_back (_last_cut_copy_source_track);
4141         }
4142
4143         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4144
4145                 /* undo/redo is handled by individual tracks/regions */
4146
4147                 if (internal_editing()) {
4148
4149                         RegionSelection rs;
4150                         RegionSelection::iterator r;
4151                         MidiNoteSelection::iterator cb;
4152
4153                         get_regions_at (rs, position, ts);
4154
4155                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4156                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4157                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4158                                 if (mrv) {
4159                                         mrv->paste (position, times, **cb);
4160                                         ++cb;
4161                                 }
4162                         }
4163
4164                 } else {
4165
4166                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4167                                 commit = true;
4168                         }
4169                 }
4170         }
4171
4172         if (commit) {
4173                 commit_reversible_command ();
4174         }
4175 }
4176
4177 void
4178 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4179 {
4180         boost::shared_ptr<Playlist> playlist;
4181         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4182         RegionSelection foo;
4183
4184         nframes_t const start_frame = regions.start ();
4185         nframes_t const end_frame = regions.end_frame ();
4186
4187         begin_reversible_command (_("duplicate region"));
4188
4189         selection->clear_regions ();
4190
4191         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4192
4193                 boost::shared_ptr<Region> r ((*i)->region());
4194
4195                 TimeAxisView& tv = (*i)->get_time_axis_view();
4196                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4197                 latest_regionviews.clear ();
4198                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4199
4200                 playlist = (*i)->region()->playlist();
4201                 playlist->clear_changes ();
4202                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame), times);
4203                 _session->add_command(new StatefulDiffCommand (playlist));
4204
4205                 c.disconnect ();
4206
4207                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4208         }
4209
4210         commit_reversible_command ();
4211
4212         if (!foo.empty()) {
4213                 selection->set (foo);
4214         }
4215 }
4216
4217 void
4218 Editor::duplicate_selection (float times)
4219 {
4220         if (selection->time.empty() || selection->tracks.empty()) {
4221                 return;
4222         }
4223
4224         boost::shared_ptr<Playlist> playlist;
4225         vector<boost::shared_ptr<Region> > new_regions;
4226         vector<boost::shared_ptr<Region> >::iterator ri;
4227
4228         create_region_from_selection (new_regions);
4229
4230         if (new_regions.empty()) {
4231                 return;
4232         }
4233
4234         begin_reversible_command (_("duplicate selection"));
4235
4236         ri = new_regions.begin();
4237
4238         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4239                 if ((playlist = (*i)->playlist()) == 0) {
4240                         continue;
4241                 }
4242                 playlist->clear_changes ();
4243                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4244                 _session->add_command (new StatefulDiffCommand (playlist));
4245
4246                 ++ri;
4247                 if (ri == new_regions.end()) {
4248                         --ri;
4249                 }
4250         }
4251
4252         commit_reversible_command ();
4253 }
4254
4255 void
4256 Editor::reset_point_selection ()
4257 {
4258         /* reset all selected points to the relevant default value */
4259
4260         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4261
4262                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4263
4264                 if (atv) {
4265                         atv->reset_objects (selection->points);
4266                 }
4267         }
4268 }
4269
4270 void
4271 Editor::center_playhead ()
4272 {
4273         float page = _canvas_width * frames_per_unit;
4274         center_screen_internal (playhead_cursor->current_frame, page);
4275 }
4276
4277 void
4278 Editor::center_edit_point ()
4279 {
4280         float page = _canvas_width * frames_per_unit;
4281         center_screen_internal (get_preferred_edit_position(), page);
4282 }
4283
4284 /** Caller must begin and commit a reversible command */
4285 void
4286 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4287 {
4288         playlist->clear_changes ();
4289         playlist->clear ();
4290         _session->add_command (new StatefulDiffCommand (playlist));
4291 }
4292
4293 void
4294 Editor::nudge_track (bool use_edit, bool forwards)
4295 {
4296         boost::shared_ptr<Playlist> playlist;
4297         framepos_t distance;
4298         framepos_t next_distance;
4299         framepos_t start;
4300
4301         if (use_edit) {
4302                 start = get_preferred_edit_position();
4303         } else {
4304                 start = 0;
4305         }
4306
4307         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4308                 return;
4309         }
4310
4311         if (selection->tracks.empty()) {
4312                 return;
4313         }
4314
4315         begin_reversible_command (_("nudge track"));
4316
4317         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4318
4319                 if ((playlist = (*i)->playlist()) == 0) {
4320                         continue;
4321                 }
4322
4323                 playlist->clear_changes ();
4324                 playlist->clear_owned_changes ();
4325
4326                 playlist->nudge_after (start, distance, forwards);
4327                 
4328                 vector<Command*> cmds;
4329
4330                 playlist->rdiff (cmds);
4331                 _session->add_commands (cmds);
4332
4333                 _session->add_command (new StatefulDiffCommand (playlist));
4334         }
4335
4336         commit_reversible_command ();
4337 }
4338
4339 void
4340 Editor::remove_last_capture ()
4341 {
4342         vector<string> choices;
4343         string prompt;
4344
4345         if (!_session) {
4346                 return;
4347         }
4348
4349         if (Config->get_verify_remove_last_capture()) {
4350                 prompt  = _("Do you really want to destroy the last capture?"
4351                             "\n(This is destructive and cannot be undone)");
4352
4353                 choices.push_back (_("No, do nothing."));
4354                 choices.push_back (_("Yes, destroy it."));
4355
4356                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4357
4358                 if (prompter.run () == 1) {
4359                         _session->remove_last_capture ();
4360                         _regions->redisplay ();
4361                 }
4362
4363         } else {
4364                 _session->remove_last_capture();
4365                 _regions->redisplay ();
4366         }
4367 }
4368
4369 void
4370 Editor::normalize_region ()
4371 {
4372         if (!_session) {
4373                 return;
4374         }
4375
4376         RegionSelection rs = get_regions_from_selection_and_entered ();
4377         
4378         if (rs.empty()) {
4379                 return;
4380         }
4381
4382         NormalizeDialog dialog (rs.size() > 1);
4383
4384         if (dialog.run () == RESPONSE_CANCEL) {
4385                 return;
4386         }
4387
4388         set_canvas_cursor (wait_cursor);
4389         gdk_flush ();
4390
4391         /* XXX: should really only count audio regions here */
4392         int const regions = rs.size ();
4393
4394         /* Make a list of the selected audio regions' maximum amplitudes, and also
4395            obtain the maximum amplitude of them all.
4396         */
4397         list<double> max_amps;
4398         double max_amp = 0;
4399         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
4400                 AudioRegionView const * arv = dynamic_cast<AudioRegionView const *> (*i);
4401                 if (arv) {
4402                         dialog.descend (1.0 / regions);
4403                         double const a = arv->audio_region()->maximum_amplitude (&dialog);
4404
4405                         if (a == -1) {
4406                                 /* the user cancelled the operation */
4407                                 set_canvas_cursor (current_canvas_cursor);
4408                                 return;
4409                         }
4410                         
4411                         max_amps.push_back (a);
4412                         max_amp = max (max_amp, a);
4413                         dialog.ascend ();
4414                 }
4415         }
4416
4417         begin_reversible_command (_("normalize"));
4418
4419         list<double>::const_iterator a = max_amps.begin ();
4420         
4421         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4422                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4423                 if (!arv) {
4424                         continue;
4425                 }
4426
4427                 arv->region()->clear_changes ();
4428
4429                 double const amp = dialog.normalize_individually() ? *a : max_amp;
4430                 
4431                 arv->audio_region()->normalize (amp, dialog.target ());
4432                 _session->add_command (new StatefulDiffCommand (arv->region()));
4433
4434                 ++a;
4435         }
4436
4437         commit_reversible_command ();
4438         set_canvas_cursor (current_canvas_cursor);
4439 }
4440
4441
4442 void
4443 Editor::reset_region_scale_amplitude ()
4444 {
4445         if (!_session) {
4446                 return;
4447         }
4448
4449         RegionSelection rs = get_regions_from_selection_and_entered ();
4450
4451         if (rs.empty()) {
4452                 return;
4453         }
4454
4455         begin_reversible_command ("reset gain");
4456
4457         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4458                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4459                 if (!arv)
4460                         continue;
4461                 arv->region()->clear_changes ();
4462                 arv->audio_region()->set_scale_amplitude (1.0f);
4463                 _session->add_command (new StatefulDiffCommand (arv->region()));
4464         }
4465
4466         commit_reversible_command ();
4467 }
4468
4469 void
4470 Editor::adjust_region_gain (bool up)
4471 {
4472         RegionSelection rs = get_regions_from_selection_and_entered ();
4473
4474         if (!_session || rs.empty()) {
4475                 return;
4476         }
4477
4478         begin_reversible_command ("adjust region gain");
4479
4480         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4481                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4482                 if (!arv) {
4483                         continue;
4484                 }
4485
4486                 arv->region()->clear_changes ();
4487                 
4488                 double fraction = gain_to_slider_position (arv->audio_region()->scale_amplitude ());
4489
4490                 if (up) {
4491                         fraction += 0.05;
4492                         fraction = min (fraction, 1.0);
4493                 } else {
4494                         fraction -= 0.05;
4495                         fraction = max (fraction, 0.0);
4496                 }
4497
4498                 if (!up && fraction <= 0) {
4499                         continue;
4500                 }
4501
4502                 fraction = slider_position_to_gain (fraction);
4503
4504                 if (up && fraction >= 2.0) {
4505                         continue;
4506                 }
4507
4508                 arv->audio_region()->set_scale_amplitude (fraction);
4509                 _session->add_command (new StatefulDiffCommand (arv->region()));
4510         }
4511
4512         commit_reversible_command ();
4513 }
4514
4515
4516 void
4517 Editor::reverse_region ()
4518 {
4519         if (!_session) {
4520                 return;
4521         }
4522
4523         Reverse rev (*_session);
4524         apply_filter (rev, _("reverse regions"));
4525 }
4526
4527 void
4528 Editor::strip_region_silence ()
4529 {
4530         if (!_session) {
4531                 return;
4532         }
4533
4534         RegionSelection rs = get_regions_from_selection_and_entered ();
4535
4536         if (rs.empty()) {
4537                 return;
4538         }
4539
4540         std::list<boost::shared_ptr<AudioRegion> > ar;
4541
4542         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4543                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4544                 if (arv) {
4545                         ar.push_back (arv->audio_region ());
4546                 }
4547         }
4548
4549         StripSilenceDialog d (_session, ar);
4550         int const r = d.run ();
4551
4552         if (r == Gtk::RESPONSE_OK) {
4553                 StripSilence s (*_session, d.threshold (), d.minimum_length (), d.fade_length ());
4554                 apply_filter (s, _("strip silence"), &d);
4555         }
4556 }
4557
4558 Command*
4559 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4560 {
4561         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4562         mrv.selection_as_notelist (selected, true);
4563
4564         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4565         v.push_back (selected);
4566
4567         return op (mrv.midi_region()->model(), v);
4568 }
4569
4570 void
4571 Editor::apply_midi_note_edit_op (MidiOperator& op)
4572 {
4573         Command* cmd;
4574
4575         RegionSelection rs = get_regions_from_selection_and_entered ();
4576
4577         if (rs.empty()) {
4578                 return;
4579         }
4580
4581         begin_reversible_command (op.name ());
4582
4583         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4584                 RegionSelection::iterator tmp = r;
4585                 ++tmp;
4586
4587                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4588
4589                 if (mrv) {
4590                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4591                         if (cmd) {
4592                                 (*cmd)();
4593                                 _session->add_command (cmd);
4594                         }
4595                 }
4596
4597                 r = tmp;
4598         }
4599
4600         commit_reversible_command ();
4601 }
4602
4603 void
4604 Editor::fork_region ()
4605 {
4606         RegionSelection rs = get_regions_from_selection_and_entered ();
4607
4608         if (rs.empty()) {
4609                 return;
4610         }
4611
4612         begin_reversible_command (_("Fork Region(s)"));
4613
4614         set_canvas_cursor (wait_cursor);
4615         gdk_flush ();
4616
4617         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4618                 RegionSelection::iterator tmp = r;
4619                 ++tmp;
4620
4621                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4622
4623                 if (mrv) {
4624                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4625                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4626                         
4627                         playlist->clear_changes ();
4628                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4629                         _session->add_command(new StatefulDiffCommand (playlist));
4630                 }
4631
4632                 r = tmp;
4633         }
4634
4635         commit_reversible_command ();
4636
4637         set_canvas_cursor (current_canvas_cursor);
4638 }
4639
4640 void
4641 Editor::quantize_region ()
4642 {
4643         if (!_session) {
4644                 return;
4645         }
4646
4647         QuantizeDialog* qd = new QuantizeDialog (*this);
4648
4649         qd->present ();
4650         const int r = qd->run ();
4651         qd->hide ();
4652
4653         if (r == Gtk::RESPONSE_OK) {
4654                 Quantize quant (*_session, Plain,
4655                                 qd->snap_start(), qd->snap_end(),
4656                                 qd->start_grid_size(), qd->end_grid_size(),
4657                                 qd->strength(), qd->swing(), qd->threshold());
4658
4659                 apply_midi_note_edit_op (quant);
4660         }
4661 }
4662
4663 void
4664 Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress)
4665 {
4666         RegionSelection rs = get_regions_from_selection_and_entered ();
4667
4668         if (rs.empty()) {
4669                 return;
4670         }
4671
4672         begin_reversible_command (command);
4673
4674         set_canvas_cursor (wait_cursor);
4675         gdk_flush ();
4676
4677         int n = 0;
4678         int const N = rs.size ();
4679         
4680         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4681                 RegionSelection::iterator tmp = r;
4682                 ++tmp;
4683
4684                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4685                 if (arv) {
4686                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4687
4688                         if (progress) {
4689                                 progress->descend (1.0 / N);
4690                         }
4691
4692                         if (arv->audio_region()->apply (filter, progress) == 0) {
4693
4694                                 playlist->clear_changes ();
4695
4696                                 if (filter.results.empty ()) {
4697
4698                                         /* no regions returned; remove the old one */
4699                                         playlist->remove_region (arv->region ());
4700
4701                                 } else {
4702
4703                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4704
4705                                         /* first region replaces the old one */
4706                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4707                                         ++res;
4708
4709                                         /* add the rest */
4710                                         while (res != filter.results.end()) {
4711                                                 playlist->add_region (*res, (*res)->position());
4712                                                 ++res;
4713                                         }
4714
4715                                 }
4716
4717                                 _session->add_command(new StatefulDiffCommand (playlist));
4718                         } else {
4719                                 goto out;
4720                         }
4721
4722                         if (progress) {
4723                                 progress->ascend ();
4724                         }
4725                 }
4726
4727                 r = tmp;
4728                 ++n;
4729         }
4730
4731         commit_reversible_command ();
4732
4733   out:
4734         set_canvas_cursor (current_canvas_cursor);
4735 }
4736
4737 void
4738 Editor::external_edit_region ()
4739 {
4740         /* more to come */
4741 }
4742
4743 void
4744 Editor::brush (framepos_t pos)
4745 {
4746         snap_to (pos);
4747
4748         RegionSelection rs = get_regions_from_selection_and_entered ();
4749
4750         if (rs.empty()) {
4751                 return;
4752         }
4753
4754         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4755                 mouse_brush_insert_region ((*i), pos);
4756         }
4757 }
4758
4759 void
4760 Editor::reset_region_gain_envelopes ()
4761 {
4762         RegionSelection rs = get_regions_from_selection_and_entered ();
4763
4764         if (!_session || rs.empty()) {
4765                 return;
4766         }
4767
4768         _session->begin_reversible_command (_("reset region gain"));
4769
4770         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4771                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4772                 if (arv) {
4773                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4774                         XMLNode& before (alist->get_state());
4775
4776                         arv->audio_region()->set_default_envelope ();
4777                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4778                 }
4779         }
4780
4781         _session->commit_reversible_command ();
4782 }
4783
4784 void
4785 Editor::toggle_gain_envelope_visibility ()
4786 {
4787         if (_ignore_region_action) {
4788                 return;
4789         }
4790         
4791         RegionSelection rs = get_regions_from_selection_and_entered ();
4792
4793         if (!_session || rs.empty()) {
4794                 return;
4795         }
4796
4797         _session->begin_reversible_command (_("region gain envelope visible"));
4798
4799         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4800                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4801                 if (arv) {
4802                         arv->region()->clear_changes ();
4803                         arv->set_envelope_visible (!arv->envelope_visible());
4804                         _session->add_command (new StatefulDiffCommand (arv->region()));
4805                 }
4806         }
4807
4808         _session->commit_reversible_command ();
4809 }
4810
4811 void
4812 Editor::toggle_gain_envelope_active ()
4813 {
4814         if (_ignore_region_action) {
4815                 return;
4816         }
4817         
4818         RegionSelection rs = get_regions_from_selection_and_entered ();
4819
4820         if (!_session || rs.empty()) {
4821                 return;
4822         }
4823
4824         _session->begin_reversible_command (_("region gain envelope active"));
4825
4826         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4827                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4828                 if (arv) {
4829                         arv->region()->clear_changes ();
4830                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4831                         _session->add_command (new StatefulDiffCommand (arv->region()));
4832                 }
4833         }
4834
4835         _session->commit_reversible_command ();
4836 }
4837
4838 void
4839 Editor::toggle_region_lock ()
4840 {
4841         if (_ignore_region_action) {
4842                 return;
4843         }
4844
4845         RegionSelection rs = get_regions_from_selection_and_entered ();
4846
4847         if (!_session || rs.empty()) {
4848                 return;
4849         }
4850
4851         _session->begin_reversible_command (_("toggle region lock"));
4852
4853         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4854                 (*i)->region()->clear_changes ();
4855                 (*i)->region()->set_locked (!(*i)->region()->locked());
4856                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4857         }
4858
4859         _session->commit_reversible_command ();
4860 }
4861
4862 void
4863 Editor::toggle_region_lock_style ()
4864 {
4865         if (_ignore_region_action) {
4866                 return;
4867         }
4868         
4869         RegionSelection rs = get_regions_from_selection_and_entered ();
4870
4871         if (!_session || rs.empty()) {
4872                 return;
4873         }
4874
4875         _session->begin_reversible_command (_("region lock style"));
4876
4877         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4878                 (*i)->region()->clear_changes ();
4879                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
4880                 (*i)->region()->set_position_lock_style (ns);
4881                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4882         }
4883
4884         _session->commit_reversible_command ();
4885 }
4886
4887 void
4888 Editor::toggle_opaque_region ()
4889 {
4890         if (_ignore_region_action) {
4891                 return;
4892         }
4893         
4894         RegionSelection rs = get_regions_from_selection_and_entered ();
4895
4896         if (!_session || rs.empty()) {
4897                 return;
4898         }
4899
4900         _session->begin_reversible_command (_("change region opacity"));
4901
4902         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4903                 (*i)->region()->clear_changes ();
4904                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4905                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4906         }
4907
4908         _session->commit_reversible_command ();
4909 }
4910
4911 void
4912 Editor::toggle_record_enable ()
4913 {
4914         bool new_state = false;
4915         bool first = true;
4916         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4917                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4918                 if (!rtav)
4919                         continue;
4920                 if (!rtav->is_track())
4921                         continue;
4922
4923                 if (first) {
4924                         new_state = !rtav->track()->record_enabled();
4925                         first = false;
4926                 }
4927
4928                 rtav->track()->set_record_enabled (new_state, this);
4929         }
4930 }
4931
4932
4933 void
4934 Editor::set_fade_length (bool in)
4935 {
4936         RegionSelection rs = get_regions_from_selection_and_entered ();
4937
4938         if (rs.empty()) {
4939                 return;
4940         }
4941
4942         /* we need a region to measure the offset from the start */
4943
4944         RegionView* rv = rs.front ();
4945
4946         framepos_t pos = get_preferred_edit_position();
4947         framepos_t len;
4948         char const * cmd;
4949
4950         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
4951                 /* edit point is outside the relevant region */
4952                 return;
4953         }
4954
4955         if (in) {
4956                 if (pos <= rv->region()->position()) {
4957                         /* can't do it */
4958                         return;
4959                 }
4960                 len = pos - rv->region()->position();
4961                 cmd = _("set fade in length");
4962         } else {
4963                 if (pos >= rv->region()->last_frame()) {
4964                         /* can't do it */
4965                         return;
4966                 }
4967                 len = rv->region()->last_frame() - pos;
4968                 cmd = _("set fade out length");
4969         }
4970
4971         begin_reversible_command (cmd);
4972
4973         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4974                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4975
4976                 if (!tmp) {
4977                         return;
4978                 }
4979
4980                 boost::shared_ptr<AutomationList> alist;
4981                 if (in) {
4982                         alist = tmp->audio_region()->fade_in();
4983                 } else {
4984                         alist = tmp->audio_region()->fade_out();
4985                 }
4986
4987                 XMLNode &before = alist->get_state();
4988
4989                 if (in) {
4990                         tmp->audio_region()->set_fade_in_length (len);
4991                         tmp->audio_region()->set_fade_in_active (true);
4992                 } else {
4993                         tmp->audio_region()->set_fade_out_length (len);
4994                         tmp->audio_region()->set_fade_out_active (true);
4995                 }
4996
4997                 XMLNode &after = alist->get_state();
4998                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
4999         }
5000
5001         commit_reversible_command ();
5002 }
5003
5004 void
5005 Editor::set_fade_in_shape (FadeShape shape)
5006 {
5007         RegionSelection rs = get_regions_from_selection_and_entered ();
5008
5009         if (rs.empty()) {
5010                 return;
5011         }
5012
5013         begin_reversible_command (_("set fade in shape"));
5014
5015         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5016                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5017
5018                 if (!tmp) {
5019                         return;
5020                 }
5021
5022                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5023                 XMLNode &before = alist->get_state();
5024
5025                 tmp->audio_region()->set_fade_in_shape (shape);
5026
5027                 XMLNode &after = alist->get_state();
5028                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5029         }
5030
5031         commit_reversible_command ();
5032
5033 }
5034
5035 void
5036 Editor::set_fade_out_shape (FadeShape shape)
5037 {
5038         RegionSelection rs = get_regions_from_selection_and_entered ();
5039
5040         if (rs.empty()) {
5041                 return;
5042         }
5043
5044         begin_reversible_command (_("set fade out shape"));
5045
5046         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5047                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5048
5049                 if (!tmp) {
5050                         return;
5051                 }
5052
5053                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5054                 XMLNode &before = alist->get_state();
5055
5056                 tmp->audio_region()->set_fade_out_shape (shape);
5057
5058                 XMLNode &after = alist->get_state();
5059                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5060         }
5061
5062         commit_reversible_command ();
5063 }
5064
5065 void
5066 Editor::set_fade_in_active (bool yn)
5067 {
5068         RegionSelection rs = get_regions_from_selection_and_entered ();
5069
5070         if (rs.empty()) {
5071                 return;
5072         }
5073
5074         begin_reversible_command (_("set fade in active"));
5075
5076         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5077                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5078
5079                 if (!tmp) {
5080                         return;
5081                 }
5082
5083
5084                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5085                 
5086                 ar->clear_changes ();
5087                 ar->set_fade_in_active (yn);
5088                 _session->add_command (new StatefulDiffCommand (ar));
5089         }
5090
5091         commit_reversible_command ();
5092 }
5093
5094 void
5095 Editor::set_fade_out_active (bool yn)
5096 {
5097         RegionSelection rs = get_regions_from_selection_and_entered ();
5098
5099         if (rs.empty()) {
5100                 return;
5101         }
5102
5103         begin_reversible_command (_("set fade out active"));
5104
5105         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5106                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5107
5108                 if (!tmp) {
5109                         return;
5110                 }
5111
5112                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5113
5114                 ar->clear_changes ();
5115                 ar->set_fade_out_active (yn);
5116                 _session->add_command(new StatefulDiffCommand (ar));
5117         }
5118
5119         commit_reversible_command ();
5120 }
5121
5122 void
5123 Editor::toggle_region_fades (int dir)
5124 {
5125         boost::shared_ptr<AudioRegion> ar;
5126         bool yn;
5127
5128         RegionSelection rs = get_regions_from_selection_and_entered ();
5129
5130         if (rs.empty()) {
5131                 return;
5132         }
5133
5134         RegionSelection::iterator i;    
5135         for (i = rs.begin(); i != rs.end(); ++i) {
5136                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5137                         if (dir == -1) {
5138                                 yn = ar->fade_out_active ();
5139                         } else {
5140                                 yn = ar->fade_in_active ();
5141                         }
5142                         break;
5143                 }
5144         }
5145
5146         if (i == rs.end()) {
5147                 return;
5148         }
5149
5150         /* XXX should this undo-able? */
5151
5152         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5153                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5154                         continue;
5155                 }
5156                 if (dir == 1 || dir == 0) {
5157                         ar->set_fade_in_active (!yn);
5158                 }
5159
5160                 if (dir == -1 || dir == 0) {
5161                         ar->set_fade_out_active (!yn);
5162                 }
5163         }
5164 }
5165
5166
5167 /** Update region fade visibility after its configuration has been changed */
5168 void
5169 Editor::update_region_fade_visibility ()
5170 {
5171         bool _fade_visibility = _session->config.get_show_region_fades ();
5172
5173         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5174                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5175                 if (v) {
5176                         if (_fade_visibility) {
5177                                 v->audio_view()->show_all_fades ();
5178                         } else {
5179                                 v->audio_view()->hide_all_fades ();
5180                         }
5181                 }
5182         }
5183 }
5184
5185 /** Update crossfade visibility after its configuration has been changed */
5186 void
5187 Editor::update_xfade_visibility ()
5188 {
5189         _xfade_visibility = _session->config.get_xfades_visible ();
5190
5191         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5192                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5193                 if (v) {
5194                         if (_xfade_visibility) {
5195                                 v->show_all_xfades ();
5196                         } else {
5197                                 v->hide_all_xfades ();
5198                         }
5199                 }
5200         }
5201 }
5202
5203 void
5204 Editor::set_edit_point ()
5205 {
5206         framepos_t where;
5207         bool ignored;
5208
5209         if (!mouse_frame (where, ignored)) {
5210                 return;
5211         }
5212
5213         snap_to (where);
5214
5215         if (selection->markers.empty()) {
5216
5217                 mouse_add_new_marker (where);
5218
5219         } else {
5220                 bool ignored;
5221
5222                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5223
5224                 if (loc) {
5225                         loc->move_to (where);
5226                 }
5227         }
5228 }
5229
5230 void
5231 Editor::set_playhead_cursor ()
5232 {
5233         if (entered_marker) {
5234                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5235         } else {
5236                 framepos_t where;
5237                 bool ignored;
5238
5239                 if (!mouse_frame (where, ignored)) {
5240                         return;
5241                 }
5242
5243                 snap_to (where);
5244
5245                 if (_session) {
5246                         _session->request_locate (where, _session->transport_rolling());
5247                 }
5248         }
5249 }
5250
5251 void
5252 Editor::split_region ()
5253 {
5254         if (((mouse_mode == MouseRange) || 
5255              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) && 
5256             !selection->time.empty()) {
5257                 separate_regions_between (selection->time);
5258                 return;
5259         } 
5260
5261         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5262
5263         framepos_t where = get_preferred_edit_position ();
5264
5265         if (rs.empty()) {
5266                 return;
5267         }
5268
5269         split_regions_at (where, rs);
5270 }
5271
5272 void
5273 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5274 {
5275         if (entered_track && mouse_mode == MouseObject) {
5276                 if (!selection->tracks.empty()) {
5277                         if (!selection->selected (entered_track)) {
5278                                 selection->add (entered_track);
5279                         }
5280                 } else {
5281                         /* there is no selection, but this operation requires/prefers selected objects */
5282
5283                         if (op_really_wants_one_track_if_none_are_selected) {
5284                                 selection->set (entered_track);
5285                         }
5286                 }
5287         }
5288 }
5289
5290 struct EditorOrderRouteSorter {
5291     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5292             /* use of ">" forces the correct sort order */
5293             return a->order_key ("editor") < b->order_key ("editor");
5294     }
5295 };
5296
5297 void
5298 Editor::select_next_route()
5299 {
5300         if (selection->tracks.empty()) {
5301                 selection->set (track_views.front());
5302                 return;
5303         }
5304
5305         TimeAxisView* current = selection->tracks.front();
5306
5307         RouteUI *rui;
5308         do {
5309                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5310                         if (*i == current) {
5311                                 ++i;
5312                                 if (i != track_views.end()) {
5313                                         current = (*i);
5314                                 } else {
5315                                         current = (*(track_views.begin()));
5316                                         //selection->set (*(track_views.begin()));
5317                                 }
5318                                 break;
5319                         }
5320                 }
5321                 rui = dynamic_cast<RouteUI *>(current);
5322         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5323
5324         selection->set(current);
5325
5326         ensure_track_visible(current);
5327 }
5328
5329 void
5330 Editor::select_prev_route()
5331 {
5332         if (selection->tracks.empty()) {
5333                 selection->set (track_views.front());
5334                 return;
5335         }
5336
5337         TimeAxisView* current = selection->tracks.front();
5338
5339         RouteUI *rui;
5340         do {
5341                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5342                         if (*i == current) {
5343                                 ++i;
5344                                 if (i != track_views.rend()) {
5345                                         current = (*i);
5346                                 } else {
5347                                         current = *(track_views.rbegin());
5348                                 }
5349                                 break;
5350                         }
5351                 }
5352                 rui = dynamic_cast<RouteUI *>(current);
5353         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5354
5355         selection->set (current);
5356
5357         ensure_track_visible(current);
5358 }
5359
5360 void
5361 Editor::ensure_track_visible(TimeAxisView *track)
5362 {
5363         if (track->hidden())
5364                 return;
5365
5366         double const current_view_min_y = vertical_adjustment.get_value();
5367         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5368
5369         double const track_min_y = track->y_position ();
5370         double const track_max_y = track->y_position () + track->effective_height ();
5371
5372         if (track_min_y >= current_view_min_y &&
5373             track_max_y <= current_view_max_y) {
5374                 return;
5375         }
5376
5377         double new_value;
5378
5379         if (track_min_y < current_view_min_y) {
5380                 // Track is above the current view
5381                 new_value = track_min_y;
5382         } else {
5383                 // Track is below the current view
5384                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5385         }
5386
5387         vertical_adjustment.set_value(new_value);
5388 }
5389
5390 void
5391 Editor::set_loop_from_selection (bool play)
5392 {
5393         if (_session == 0 || selection->time.empty()) {
5394                 return;
5395         }
5396
5397         framepos_t start = selection->time[clicked_selection].start;
5398         framepos_t end = selection->time[clicked_selection].end;
5399
5400         set_loop_range (start, end,  _("set loop range from selection"));
5401
5402         if (play) {
5403                 _session->request_play_loop (true);
5404                 _session->request_locate (start, true);
5405         }
5406 }
5407
5408 void
5409 Editor::set_loop_from_edit_range (bool play)
5410 {
5411         if (_session == 0) {
5412                 return;
5413         }
5414
5415         framepos_t start;
5416         framepos_t end;
5417
5418         if (!get_edit_op_range (start, end)) {
5419                 return;
5420         }
5421
5422         set_loop_range (start, end,  _("set loop range from edit range"));
5423
5424         if (play) {
5425                 _session->request_play_loop (true);
5426                 _session->request_locate (start, true);
5427         }
5428 }
5429
5430 void
5431 Editor::set_loop_from_region (bool play)
5432 {
5433         framepos_t start = max_framepos;
5434         framepos_t end = 0;
5435
5436         RegionSelection rs = get_regions_from_selection_and_entered ();
5437
5438         if (rs.empty()) {
5439                 return;
5440         }
5441
5442         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5443                 if ((*i)->region()->position() < start) {
5444                         start = (*i)->region()->position();
5445                 }
5446                 if ((*i)->region()->last_frame() + 1 > end) {
5447                         end = (*i)->region()->last_frame() + 1;
5448                 }
5449         }
5450
5451         set_loop_range (start, end, _("set loop range from region"));
5452
5453         if (play) {
5454                 _session->request_play_loop (true);
5455                 _session->request_locate (start, true);
5456         }
5457 }
5458
5459 void
5460 Editor::set_punch_from_selection ()
5461 {
5462         if (_session == 0 || selection->time.empty()) {
5463                 return;
5464         }
5465
5466         framepos_t start = selection->time[clicked_selection].start;
5467         framepos_t end = selection->time[clicked_selection].end;
5468
5469         set_punch_range (start, end,  _("set punch range from selection"));
5470 }
5471
5472 void
5473 Editor::set_punch_from_edit_range ()
5474 {
5475         if (_session == 0) {
5476                 return;
5477         }
5478
5479         framepos_t start;
5480         framepos_t end;
5481
5482         if (!get_edit_op_range (start, end)) {
5483                 return;
5484         }
5485
5486         set_punch_range (start, end,  _("set punch range from edit range"));
5487 }
5488
5489 void
5490 Editor::set_punch_from_region ()
5491 {
5492         framepos_t start = max_framepos;
5493         framepos_t end = 0;
5494
5495         RegionSelection rs = get_regions_from_selection_and_entered ();
5496
5497         if (rs.empty()) {
5498                 return;
5499         }
5500
5501         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5502                 if ((*i)->region()->position() < start) {
5503                         start = (*i)->region()->position();
5504                 }
5505                 if ((*i)->region()->last_frame() + 1 > end) {
5506                         end = (*i)->region()->last_frame() + 1;
5507                 }
5508         }
5509
5510         set_punch_range (start, end, _("set punch range from region"));
5511 }
5512
5513 void
5514 Editor::pitch_shift_region ()
5515 {
5516         RegionSelection rs = get_regions_from_selection_and_entered ();
5517
5518         if (rs.empty()) {
5519                 return;
5520         }
5521
5522         pitch_shift (rs, 1.2);
5523 }
5524
5525 void
5526 Editor::set_tempo_from_region ()
5527 {
5528         RegionSelection rs = get_regions_from_selection_and_entered ();
5529
5530         if (!_session || rs.empty()) {
5531                 return;
5532         }
5533
5534         RegionView* rv = rs.front();
5535
5536         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5537 }
5538
5539 void
5540 Editor::use_range_as_bar ()
5541 {
5542         framepos_t start, end;
5543         if (get_edit_op_range (start, end)) {
5544                 define_one_bar (start, end);
5545         }
5546 }
5547
5548 void
5549 Editor::define_one_bar (framepos_t start, framepos_t end)
5550 {
5551         framepos_t length = end - start;
5552
5553         const Meter& m (_session->tempo_map().meter_at (start));
5554
5555         /* length = 1 bar */
5556
5557         /* now we want frames per beat.
5558            we have frames per bar, and beats per bar, so ...
5559         */
5560
5561         double frames_per_beat = length / m.beats_per_bar();
5562
5563         /* beats per minute = */
5564
5565         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5566
5567         /* now decide whether to:
5568
5569             (a) set global tempo
5570             (b) add a new tempo marker
5571
5572         */
5573
5574         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5575
5576         bool do_global = false;
5577
5578         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5579
5580                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5581                    at the start, or create a new marker
5582                 */
5583
5584                 vector<string> options;
5585                 options.push_back (_("Cancel"));
5586                 options.push_back (_("Add new marker"));
5587                 options.push_back (_("Set global tempo"));
5588
5589                 Choice c (
5590                         _("Define one bar"),
5591                         _("Do you want to set the global tempo or add a new tempo marker?"),
5592                         options
5593                         );
5594                 
5595                 c.set_default_response (2);
5596
5597                 switch (c.run()) {
5598                 case 0:
5599                         return;
5600
5601                 case 2:
5602                         do_global = true;
5603                         break;
5604
5605                 default:
5606                         do_global = false;
5607                 }
5608
5609         } else {
5610
5611                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5612                    if the marker is at the region starter, change it, otherwise add
5613                    a new tempo marker
5614                 */
5615         }
5616
5617         begin_reversible_command (_("set tempo from region"));
5618         XMLNode& before (_session->tempo_map().get_state());
5619
5620         if (do_global) {
5621                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5622         } else if (t.frame() == start) {
5623                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5624         } else {
5625                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5626         }
5627
5628         XMLNode& after (_session->tempo_map().get_state());
5629
5630         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5631         commit_reversible_command ();
5632 }
5633
5634 void
5635 Editor::split_region_at_transients ()
5636 {
5637         AnalysisFeatureList positions;
5638
5639         RegionSelection rs = get_regions_from_selection_and_entered ();
5640
5641         if (!_session || rs.empty()) {
5642                 return;
5643         }
5644
5645         _session->begin_reversible_command (_("split regions"));
5646
5647         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5648
5649                 RegionSelection::iterator tmp;
5650
5651                 tmp = i;
5652                 ++tmp;
5653
5654                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5655
5656                 if (ar && (ar->get_transients (positions) == 0)) {
5657                         split_region_at_points ((*i)->region(), positions, true);
5658                         positions.clear ();
5659                 }
5660
5661                 i = tmp;
5662         }
5663
5664         _session->commit_reversible_command ();
5665
5666 }
5667
5668 void
5669 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5670 {
5671         bool use_rhythmic_rodent = false;
5672
5673         boost::shared_ptr<Playlist> pl = r->playlist();
5674
5675         if (!pl) {
5676                 return;
5677         }
5678
5679         if (positions.empty()) {
5680                 return;
5681         }
5682
5683
5684         if (positions.size() > 20) {
5685                 std::string msgstr = string_compose (_("You are about to split\n%1\ninto %2 pieces.\nThis could take a long time."), r->name(), positions.size() + 1);
5686                 MessageDialog msg (msgstr,
5687                                    false,
5688                                    Gtk::MESSAGE_INFO,
5689                                    Gtk::BUTTONS_OK_CANCEL);
5690
5691                 if (can_ferret) {
5692                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5693                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5694                 } else {
5695                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5696                 }
5697
5698                 msg.set_title (_("Excessive split?"));
5699                 msg.present ();
5700
5701                 int response = msg.run();
5702                 msg.hide ();
5703                 
5704                 switch (response) {
5705                 case RESPONSE_OK:
5706                         break;
5707                 case RESPONSE_APPLY:
5708                         use_rhythmic_rodent = true;
5709                         break;
5710                 default:
5711                         return;
5712                 }
5713         }
5714
5715         if (use_rhythmic_rodent) {
5716                 show_rhythm_ferret ();
5717                 return;
5718         }
5719
5720         AnalysisFeatureList::const_iterator x;
5721
5722         pl->clear_changes ();
5723
5724         x = positions.begin();
5725
5726         if (x == positions.end()) {
5727                 return;
5728         }
5729
5730         pl->freeze ();
5731         pl->remove_region (r);
5732
5733         framepos_t pos = 0;
5734
5735         while (x != positions.end()) {
5736           
5737                 /* deal with positons that are out of scope of present region bounds */
5738                 if (*x <= 0 || *x > r->length()){
5739                         ++x;
5740                         continue;
5741                 }
5742
5743                 /* file start = original start + how far we from the initial position ?
5744                  */
5745
5746                 framepos_t file_start = r->start() + pos;
5747
5748                 /* length = next position - current position
5749                  */
5750
5751                 framepos_t len = (*x) - pos;
5752                 
5753                 /* XXX we do we really want to allow even single-sample regions?
5754                    shouldn't we have some kind of lower limit on region size?
5755                 */
5756
5757                 if (len <= 0) {
5758                         break;
5759                 }
5760
5761                 string new_name;
5762
5763                 if (RegionFactory::region_name (new_name, r->name())) {
5764                         break;
5765                 }
5766
5767                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5768
5769                 PropertyList plist; 
5770                 
5771                 plist.add (ARDOUR::Properties::start, file_start);
5772                 plist.add (ARDOUR::Properties::length, len);
5773                 plist.add (ARDOUR::Properties::name, new_name);
5774                 plist.add (ARDOUR::Properties::layer, 0);
5775
5776                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5777                 pl->add_region (nr, r->position() + pos);
5778
5779                 pos += len;
5780                 ++x;
5781         }
5782
5783         string new_name;
5784
5785         RegionFactory::region_name (new_name, r->name());
5786         
5787         /* Add the final region */
5788         PropertyList plist; 
5789                 
5790         plist.add (ARDOUR::Properties::start, r->start() + pos);
5791         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
5792         plist.add (ARDOUR::Properties::name, new_name);
5793         plist.add (ARDOUR::Properties::layer, 0);
5794
5795         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5796         pl->add_region (nr, r->position() + pos);
5797
5798         
5799         pl->thaw ();
5800
5801         _session->add_command (new StatefulDiffCommand (pl));
5802 }
5803
5804 void
5805 Editor::place_transient()
5806 {
5807         if (!_session) {
5808                 return;
5809         }
5810
5811         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5812
5813         if (rs.empty()) {
5814                 return;
5815         }
5816         
5817         framepos_t where = get_preferred_edit_position();
5818
5819         _session->begin_reversible_command (_("place transient"));
5820         
5821         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5822                 framepos_t position = (*r)->region()->position();
5823                 (*r)->region()->add_transient(where - position);
5824         }
5825         
5826         _session->commit_reversible_command ();
5827 }
5828
5829 void
5830 Editor::remove_transient(ArdourCanvas::Item* item)
5831 {
5832         if (!_session) {
5833                 return;
5834         }
5835
5836         ArdourCanvas::SimpleLine* _line = reinterpret_cast<ArdourCanvas::SimpleLine*> (item);
5837         assert (_line);
5838
5839         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
5840         _arv->remove_transient(_line->property_x1());
5841 }
5842
5843 void
5844 Editor::snap_regions_to_grid ()
5845 {
5846         RegionSelection rs = get_regions_from_selection_and_entered ();
5847
5848         if (!_session || rs.empty()) {
5849                 return;
5850         }
5851         
5852         _session->begin_reversible_command (_("snap regions to grid"));
5853         
5854         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5855                 framepos_t start_frame = (*r)->region()->first_frame ();
5856                 snap_to (start_frame);
5857                 (*r)->region()->set_position (start_frame, this);
5858         }
5859         
5860         _session->commit_reversible_command ();
5861 }
5862
5863 void
5864 Editor::close_region_gaps ()
5865 {       
5866         RegionSelection rs = get_regions_from_selection_and_entered ();
5867
5868         if (!_session || rs.empty()) {
5869                 return;
5870         }
5871
5872         Dialog dialog (_("Close Region Gaps"));
5873
5874         Table table (2, 3);
5875         table.set_spacings (12);
5876         table.set_border_width (12);
5877         Label* l = manage (new Label (_("Crossfade length")));
5878         l->set_alignment (0, 0.5);
5879         table.attach (*l, 0, 1, 0, 1);
5880         
5881         SpinButton spin_crossfade (1, 0);
5882         spin_crossfade.set_range (0, 15);
5883         spin_crossfade.set_increments (1, 1);
5884         spin_crossfade.set_value (3);
5885         table.attach (spin_crossfade, 1, 2, 0, 1);
5886
5887         table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
5888
5889         l = manage (new Label (_("Pull-back length")));
5890         l->set_alignment (0, 0.5);
5891         table.attach (*l, 0, 1, 1, 2);
5892         
5893         SpinButton spin_pullback (1, 0);
5894         spin_pullback.set_range (0, 15);
5895         spin_pullback.set_increments (1, 1);
5896         spin_pullback.set_value (5);
5897         table.attach (spin_pullback, 1, 2, 1, 2);
5898
5899         table.attach (*manage (new Label (_("ms"))), 2, 3, 1, 2);
5900         
5901         dialog.get_vbox()->pack_start (table);
5902         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
5903         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
5904         dialog.show_all ();
5905
5906         if (dialog.run () == RESPONSE_CANCEL) {
5907                 return;
5908         }
5909
5910         framepos_t crossfade_len = spin_crossfade.get_value(); 
5911         framepos_t pull_back_frames = spin_pullback.get_value();
5912
5913         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
5914         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
5915
5916         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
5917         
5918         _session->begin_reversible_command (_("close region gaps"));
5919                 
5920         int idx = 0;
5921         boost::shared_ptr<Region> last_region;
5922         
5923         rs.sort_by_position_and_track();
5924         
5925         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5926
5927                 framepos_t position = (*r)->region()->position();
5928           
5929                 if (idx == 0 || position < last_region->position()){
5930                         last_region = (*r)->region();
5931                         idx++;
5932                         continue;
5933                 }
5934                 
5935                 (*r)->region()->trim_front( (position - pull_back_frames), this );
5936                 last_region->trim_end( (position - pull_back_frames + crossfade_len), this );
5937                 
5938                 last_region = (*r)->region();
5939                 
5940                 idx++;
5941         }
5942         
5943         _session->commit_reversible_command ();
5944 }
5945
5946 void
5947 Editor::tab_to_transient (bool forward)
5948 {
5949         AnalysisFeatureList positions;
5950
5951         RegionSelection rs = get_regions_from_selection_and_entered ();
5952
5953         if (!_session) {
5954                 return;
5955         }
5956
5957         framepos_t pos = _session->audible_frame ();
5958
5959         if (!selection->tracks.empty()) {
5960
5961                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
5962
5963                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
5964
5965                         if (rtv) {
5966                                 boost::shared_ptr<Track> tr = rtv->track();
5967                                 if (tr) {
5968                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
5969                                         if (pl) {
5970                                                 framepos_t result = pl->find_next_transient (pos, forward ? 1 : -1);
5971
5972                                                 if (result >= 0) {
5973                                                         positions.push_back (result);
5974                                                 }
5975                                         }
5976                                 }
5977                         }
5978                 }
5979
5980         } else {
5981
5982                 if (rs.empty()) {
5983                         return;
5984                 }
5985
5986                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5987                         (*r)->region()->get_transients (positions);
5988                 }
5989         }
5990
5991         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
5992
5993         if (forward) {
5994                 AnalysisFeatureList::iterator x;
5995
5996                 for (x = positions.begin(); x != positions.end(); ++x) {
5997                         if ((*x) > pos) {
5998                                 break;
5999                         }
6000                 }
6001
6002                 if (x != positions.end ()) {
6003                         _session->request_locate (*x);
6004                 }
6005
6006         } else {
6007                 AnalysisFeatureList::reverse_iterator x;
6008
6009                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6010                         if ((*x) < pos) {
6011                                 break;
6012                         }
6013                 }
6014
6015                 if (x != positions.rend ()) {
6016                         _session->request_locate (*x);
6017                 }
6018         }
6019 }
6020
6021 void
6022 Editor::playhead_forward_to_grid ()
6023 {
6024         if (!_session) return;
6025         framepos_t pos = playhead_cursor->current_frame;
6026         if (pos < max_framepos - 1) {
6027                 pos += 2;
6028                 snap_to_internal (pos, 1, false);
6029                 _session->request_locate (pos);
6030         }
6031 }
6032
6033
6034 void
6035 Editor::playhead_backward_to_grid ()
6036 {
6037         if (!_session) return;
6038         framepos_t pos = playhead_cursor->current_frame;
6039         if (pos > 2) {
6040                 pos -= 2;
6041                 snap_to_internal (pos, -1, false);
6042                 _session->request_locate (pos);
6043         }
6044 }
6045
6046 void
6047 Editor::set_track_height (Height h)
6048 {
6049         TrackSelection& ts (selection->tracks);
6050
6051         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6052                 (*x)->set_height (h);
6053         }
6054 }
6055
6056 void
6057 Editor::toggle_tracks_active ()
6058 {
6059         TrackSelection& ts (selection->tracks);
6060         bool first = true;
6061         bool target = false;
6062
6063         if (ts.empty()) {
6064                 return;
6065         }
6066
6067         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6068                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6069
6070                 if (rtv) {
6071                         if (first) {
6072                                 target = !rtv->_route->active();
6073                                 first = false;
6074                         }
6075                         rtv->_route->set_active (target);
6076                 }
6077         }
6078 }
6079
6080 void
6081 Editor::remove_tracks ()
6082 {
6083         TrackSelection& ts (selection->tracks);
6084
6085         if (ts.empty()) {
6086                 return;
6087         }
6088
6089         vector<string> choices;
6090         string prompt;
6091         int ntracks = 0;
6092         int nbusses = 0;
6093         const char* trackstr;
6094         const char* busstr;
6095         vector<boost::shared_ptr<Route> > routes;
6096         bool special_bus = false;
6097
6098         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6099                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6100                 if (rtv) {
6101                         if (rtv->is_track()) {
6102                                 ntracks++;
6103                         } else {
6104                                 nbusses++;
6105                         }
6106                 }
6107                 routes.push_back (rtv->_route);
6108
6109                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6110                         special_bus = true;
6111                 }
6112         }
6113
6114         if (special_bus && !Config->get_allow_special_bus_removal()) {
6115                 MessageDialog msg (_("That would be bad news ...."),
6116                                    false,
6117                                    Gtk::MESSAGE_INFO,
6118                                    Gtk::BUTTONS_OK);
6119                 msg.set_secondary_text (string_compose (_(
6120 "Removing the master or monitor bus is such a bad idea\n\
6121 that %1 is not going to allow it.\n\
6122 \n\
6123 If you really want to do this sort of thing\n\
6124 edit your ardour.rc file to set the\n\
6125 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6126
6127                 msg.present ();
6128                 msg.run ();
6129                 return;
6130         }
6131                 
6132         if (ntracks + nbusses == 0) {
6133                 return;
6134         }
6135
6136         if (ntracks > 1) {
6137                 trackstr = _("tracks");
6138         } else {
6139                 trackstr = _("track");
6140         }
6141
6142         if (nbusses > 1) {
6143                 busstr = _("busses");
6144         } else {
6145                 busstr = _("bus");
6146         }
6147
6148         if (ntracks) {
6149                 if (nbusses) {
6150                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6151                                                     "(You may also lose the playlists associated with the %2)\n\n"
6152                                                     "This action cannot be undone, and the session file will be overwritten!"),
6153                                                   ntracks, trackstr, nbusses, busstr);
6154                 } else {
6155                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6156                                                     "(You may also lose the playlists associated with the %2)\n\n"
6157                                                     "This action cannot be undone, and the session file will be overwritten!"),
6158                                                   ntracks, trackstr);
6159                 }
6160         } else if (nbusses) {
6161                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6162                                             "This action cannot be undon, and the session file will be overwritten"),
6163                                           nbusses, busstr);
6164         }
6165
6166         choices.push_back (_("No, do nothing."));
6167         if (ntracks + nbusses > 1) {
6168                 choices.push_back (_("Yes, remove them."));
6169         } else {
6170                 choices.push_back (_("Yes, remove it."));
6171         }
6172
6173         string title;
6174         if (ntracks) {
6175                 title = string_compose (_("Remove %1"), trackstr);
6176         } else {
6177                 title = string_compose (_("Remove %1"), busstr);
6178         }
6179
6180         Choice prompter (title, prompt, choices);
6181
6182         if (prompter.run () != 1) {
6183                 return;
6184         }
6185
6186         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6187                 _session->remove_route (*x);
6188         }
6189 }
6190
6191 void
6192 Editor::do_insert_time ()
6193 {
6194         if (selection->tracks.empty()) {
6195                 return;
6196         }
6197
6198         InsertTimeDialog d (*this);
6199         int response = d.run ();
6200
6201         if (response != RESPONSE_OK) {
6202                 return;
6203         }
6204
6205         if (d.distance() == 0) {
6206                 return;
6207         }
6208
6209         InsertTimeOption opt = d.intersected_region_action ();
6210
6211         insert_time (
6212                 get_preferred_edit_position(),
6213                 d.distance(),
6214                 opt,
6215                 d.move_glued(),
6216                 d.move_markers(),
6217                 d.move_glued_markers(),
6218                 d.move_locked_markers(),
6219                 d.move_tempos()
6220                 );
6221 }
6222
6223 void
6224 Editor::insert_time (framepos_t pos, framecnt_t frames, InsertTimeOption opt,
6225                      bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too)
6226 {
6227         bool commit = false;
6228
6229         if (Config->get_edit_mode() == Lock) {
6230                 return;
6231         }
6232
6233         begin_reversible_command (_("insert time"));
6234
6235         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6236                 /* regions */
6237                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6238
6239                 if (pl) {
6240
6241                         pl->clear_changes ();
6242                         pl->clear_owned_changes ();
6243
6244                         if (opt == SplitIntersected) {
6245                                 pl->split (pos);
6246                         }
6247
6248                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6249
6250                         vector<Command*> cmds;
6251                         pl->rdiff (cmds);
6252                         _session->add_commands (cmds);
6253                         
6254                         _session->add_command (new StatefulDiffCommand (pl));
6255                         commit = true;
6256                 }
6257
6258                 /* automation */
6259                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6260                 if (rtav) {
6261                         rtav->route ()->shift (pos, frames);
6262                         commit = true;
6263                 }
6264         }
6265
6266         /* markers */
6267         if (markers_too) {
6268                 bool moved = false;
6269                 XMLNode& before (_session->locations()->get_state());
6270                 Locations::LocationList copy (_session->locations()->list());
6271
6272                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6273
6274                         Locations::LocationList::const_iterator tmp;
6275
6276                         bool const was_locked = (*i)->locked ();
6277                         if (locked_markers_too) {
6278                                 (*i)->unlock ();
6279                         }
6280
6281                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6282
6283                                 if ((*i)->start() >= pos) {
6284                                         (*i)->set_start ((*i)->start() + frames);
6285                                         if (!(*i)->is_mark()) {
6286                                                 (*i)->set_end ((*i)->end() + frames);
6287                                         }
6288                                         moved = true;
6289                                 }
6290                                 
6291                         }
6292
6293                         if (was_locked) {
6294                                 (*i)->lock ();
6295                         }
6296                 }
6297
6298                 if (moved) {
6299                         XMLNode& after (_session->locations()->get_state());
6300                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6301                 }
6302         }
6303
6304         if (tempo_too) {
6305                 _session->tempo_map().insert_time (pos, frames);
6306         }
6307
6308         if (commit) {
6309                 commit_reversible_command ();
6310         }
6311 }
6312
6313 void
6314 Editor::fit_selected_tracks ()
6315 {
6316         fit_tracks (selection->tracks);
6317 }
6318
6319 void
6320 Editor::fit_tracks (TrackViewList & tracks)
6321 {
6322         if (tracks.empty()) {
6323                 return;
6324         }
6325
6326         uint32_t child_heights = 0;
6327
6328         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6329
6330                 if (!(*t)->marked_for_display()) {
6331                         continue;
6332                 }
6333
6334                 child_heights += (*t)->effective_height() - (*t)->current_height();
6335         }
6336
6337         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6338         double first_y_pos = DBL_MAX;
6339
6340         if (h < TimeAxisView::preset_height (HeightSmall)) {
6341                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6342                 /* too small to be displayed */
6343                 return;
6344         }
6345
6346         undo_visual_stack.push_back (current_visual_state());
6347
6348         /* build a list of all tracks, including children */
6349
6350         TrackViewList all;
6351         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6352                 all.push_back (*i);
6353                 TimeAxisView::Children c = (*i)->get_child_list ();
6354                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6355                         all.push_back (j->get());
6356                 }
6357         }
6358
6359         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6360
6361         bool prev_was_selected = false;
6362         bool is_selected = tracks.contains (all.front());
6363         bool next_is_selected;
6364
6365         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6366
6367                 TrackViewList::iterator next;
6368
6369                 next = t;
6370                 ++next;
6371
6372                 if (next != all.end()) {
6373                         next_is_selected = tracks.contains (*next);
6374                 } else {
6375                         next_is_selected = false;
6376                 }
6377
6378                 if (is_selected) {
6379                         (*t)->set_height (h);
6380                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6381                 } else {
6382                         if (prev_was_selected && next_is_selected) {
6383                                 hide_track_in_display (*t);
6384                         }
6385                 }
6386
6387                 prev_was_selected = is_selected;
6388                 is_selected = next_is_selected;
6389         }
6390
6391         /*
6392            set the controls_layout height now, because waiting for its size
6393            request signal handler will cause the vertical adjustment setting to fail
6394         */
6395
6396         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6397         vertical_adjustment.set_value (first_y_pos);
6398
6399         redo_visual_stack.push_back (current_visual_state());
6400 }
6401
6402 void
6403 Editor::save_visual_state (uint32_t n)
6404 {
6405         while (visual_states.size() <= n) {
6406                 visual_states.push_back (0);
6407         }
6408
6409         delete visual_states[n];
6410
6411         visual_states[n] = current_visual_state (true);
6412         gdk_beep ();
6413 }
6414
6415 void
6416 Editor::goto_visual_state (uint32_t n)
6417 {
6418         if (visual_states.size() <= n) {
6419                 return;
6420         }
6421
6422         if (visual_states[n] == 0) {
6423                 return;
6424         }
6425
6426         use_visual_state (*visual_states[n]);
6427 }
6428
6429 void
6430 Editor::start_visual_state_op (uint32_t n)
6431 {
6432         if (visual_state_op_connection.empty()) {
6433                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6434         }
6435 }
6436
6437 void
6438 Editor::cancel_visual_state_op (uint32_t n)
6439 {
6440         if (!visual_state_op_connection.empty()) {
6441                 visual_state_op_connection.disconnect();
6442                 goto_visual_state (n);
6443         }  else {
6444                 //we land here if called from the menu OR if end_visual_state_op has been called
6445                 //so check if we are already in visual state n
6446                 // XXX not yet checking it at all, but redoing does not hurt
6447                 goto_visual_state (n);
6448         }
6449 }
6450
6451 bool
6452 Editor::end_visual_state_op (uint32_t n)
6453 {
6454         visual_state_op_connection.disconnect();
6455         save_visual_state (n);
6456
6457         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6458         char buf[32];
6459         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6460         pup->set_text (buf);
6461         pup->touch();
6462
6463         return false; // do not call again
6464 }
6465
6466 void
6467 Editor::toggle_region_mute ()
6468 {
6469         if (_ignore_region_action) {
6470                 return;
6471         }
6472         
6473         RegionSelection rs = get_regions_from_selection_and_entered ();
6474
6475         if (rs.empty ()) {
6476                 return;
6477         }
6478
6479         if (rs.size() > 1) {
6480                 begin_reversible_command (_("mute regions"));
6481         } else {
6482                 begin_reversible_command (_("mute region"));
6483         }
6484         
6485         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
6486                 
6487                 (*i)->region()->playlist()->clear_changes ();
6488                 (*i)->region()->set_muted (!(*i)->region()->muted ());
6489                 _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
6490                 
6491         }
6492         
6493         commit_reversible_command ();
6494 }
6495