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