Hopefully fix visual glitches on dragging fade ins/outs.
[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         if (!clicked_routeview->track()->bounceable()) {
3551                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_routeview);
3552                 if (rtv && !rtv->track()->bounceable()) {
3553                         MessageDialog d (
3554                                 _("This route cannot be frozen because it has more outputs than inputs.  "
3555                                   "You can fix this by increasing the number of inputs.")
3556                                 );
3557                         d.set_title (_("Cannot freeze"));
3558                         d.run ();
3559                         return;
3560                 }
3561         }
3562
3563         InterThreadInfo itt;
3564         current_interthread_info = &itt;
3565
3566         InterthreadProgressWindow ipw (current_interthread_info, _("Freeze"), _("Cancel Freeze"));
3567
3568         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3569
3570         set_canvas_cursor (_cursors->wait);
3571
3572         while (!itt.done && !itt.cancel) {
3573                 gtk_main_iteration ();
3574         }
3575
3576         current_interthread_info = 0;
3577         set_canvas_cursor (current_canvas_cursor);
3578 }
3579
3580 void
3581 Editor::bounce_range_selection (bool replace, bool enable_processing)
3582 {
3583         if (selection->time.empty()) {
3584                 return;
3585         }
3586
3587         TrackSelection views = selection->tracks;
3588
3589         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3590                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
3591                 if (rtv && !rtv->track()->bounceable()) {
3592                         MessageDialog d (
3593                                 _("One or more selected tracks cannot be bounced because it has more outputs than inputs.  "
3594                                   "You can fix this by increasing the number of inputs on that track.")
3595                                 );
3596                         d.set_title (_("Cannot bounce"));
3597                         d.run ();
3598                         return;
3599                 }
3600         }
3601
3602         framepos_t start = selection->time[clicked_selection].start;
3603         framepos_t end = selection->time[clicked_selection].end;
3604         framepos_t cnt = end - start + 1;
3605
3606         begin_reversible_command (_("bounce range"));
3607
3608         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3609
3610                 RouteTimeAxisView* rtv;
3611
3612                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3613                         continue;
3614                 }
3615
3616                 boost::shared_ptr<Playlist> playlist;
3617
3618                 if ((playlist = rtv->playlist()) == 0) {
3619                         return;
3620                 }
3621
3622                 InterThreadInfo itt;
3623
3624                 playlist->clear_changes ();
3625                 playlist->clear_owned_changes ();
3626                 
3627                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3628
3629                 if (replace) {
3630                         list<AudioRange> ranges;
3631                         ranges.push_back (AudioRange (start, start+cnt, 0));
3632                         playlist->cut (ranges); // discard result
3633                         playlist->add_region (r, start);
3634                 }
3635
3636                 vector<Command*> cmds;
3637                 playlist->rdiff (cmds);
3638                 _session->add_commands (cmds);
3639
3640                 _session->add_command (new StatefulDiffCommand (playlist));
3641         }
3642
3643         commit_reversible_command ();
3644 }
3645
3646 /** Cut selected regions, automation points or a time range */
3647 void
3648 Editor::cut ()
3649 {
3650         cut_copy (Cut);
3651 }
3652
3653 /** Copy selected regions, automation points or a time range */
3654 void
3655 Editor::copy ()
3656 {
3657         cut_copy (Copy);
3658 }
3659
3660
3661 /** @return true if a Cut, Copy or Clear is possible */
3662 bool
3663 Editor::can_cut_copy () const
3664 {
3665         switch (current_mouse_mode()) {
3666
3667         case MouseObject:
3668                 if (!selection->regions.empty() || !selection->points.empty()) {
3669                         return true;
3670                 }
3671                 break;
3672
3673         case MouseRange:
3674                 if (!selection->time.empty()) {
3675                         return true;
3676                 }
3677                 break;
3678
3679         default:
3680                 break;
3681         }
3682
3683         return false;
3684 }
3685
3686
3687 /** Cut, copy or clear selected regions, automation points or a time range.
3688  * @param op Operation (Cut, Copy or Clear)
3689  */
3690 void
3691 Editor::cut_copy (CutCopyOp op)
3692 {
3693         /* only cancel selection if cut/copy is successful.*/
3694
3695         string opname;
3696
3697         switch (op) {
3698         case Cut:
3699                 opname = _("cut");
3700                 break;
3701         case Copy:
3702                 opname = _("copy");
3703                 break;
3704         case Clear:
3705                 opname = _("clear");
3706                 break;
3707         }
3708
3709         /* if we're deleting something, and the mouse is still pressed,
3710            the thing we started a drag for will be gone when we release
3711            the mouse button(s). avoid this. see part 2 at the end of
3712            this function.
3713         */
3714
3715         if (op == Cut || op == Clear) {
3716                 if (_drags->active ()) {
3717                         _drags->abort ();
3718                 }
3719         }
3720
3721         cut_buffer->clear ();
3722
3723         if (entered_marker) {
3724
3725                 /* cut/delete op while pointing at a marker */
3726
3727                 bool ignored;
3728                 Location* loc = find_location_from_marker (entered_marker, ignored);
3729
3730                 if (_session && loc) {
3731                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3732                 }
3733
3734                 _drags->abort ();
3735                 return;
3736         }
3737
3738         if (internal_editing()) {
3739
3740                 switch (current_mouse_mode()) {
3741                 case MouseObject:
3742                 case MouseRange:
3743                         cut_copy_midi (op);
3744                         break;
3745                 default:
3746                         break;
3747                 }
3748
3749         } else {
3750
3751                 RegionSelection rs;
3752
3753                 /* we only want to cut regions if some are selected */
3754
3755                 if (!selection->regions.empty()) {
3756                         rs = selection->regions;
3757                 }
3758
3759                 switch (current_mouse_mode()) {
3760                 case MouseObject:
3761                         if (!rs.empty() || !selection->points.empty()) {
3762
3763                                 begin_reversible_command (opname + _(" objects"));
3764
3765                                 if (!rs.empty()) {
3766                                         cut_copy_regions (op, rs);
3767
3768                                         if (op == Cut) {
3769                                                 selection->clear_regions ();
3770                                         }
3771                                 }
3772
3773                                 if (!selection->points.empty()) {
3774                                         cut_copy_points (op);
3775
3776                                         if (op == Cut) {
3777                                                 selection->clear_points ();
3778                                         }
3779                                 }
3780
3781                                 commit_reversible_command ();
3782                                 break; // terminate case statement here
3783                         }
3784                         if (!selection->time.empty()) {
3785                                 /* don't cause suprises */
3786                                 break;
3787                         }
3788                         // fall thru if there was nothing selected
3789
3790                 case MouseRange:
3791                         if (selection->time.empty()) {
3792                                 framepos_t start, end;
3793                                 if (!get_edit_op_range (start, end)) {
3794                                         return;
3795                                 }
3796                                 selection->set (start, end);
3797                         }
3798
3799                         begin_reversible_command (opname + _(" range"));
3800                         cut_copy_ranges (op);
3801                         commit_reversible_command ();
3802
3803                         if (op == Cut) {
3804                                 selection->clear_time ();
3805                         }
3806
3807                         break;
3808
3809                 default:
3810                         break;
3811                 }
3812         }
3813
3814         if (op == Cut || op == Clear) {
3815                 _drags->abort ();
3816         }
3817 }
3818
3819 /** Cut, copy or clear selected automation points.
3820  * @param op Operation (Cut, Copy or Clear)
3821  */
3822 void
3823 Editor::cut_copy_points (CutCopyOp op)
3824 {
3825         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3826
3827                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3828
3829                 if (atv) {
3830                         atv->cut_copy_clear_objects (selection->points, op);
3831                 }
3832         }
3833 }
3834
3835 /** Cut, copy or clear selected automation points.
3836  * @param op Operation (Cut, Copy or Clear)
3837  */
3838 void
3839 Editor::cut_copy_midi (CutCopyOp op)
3840 {
3841         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3842                 MidiRegionView* mrv = *i;
3843                 mrv->cut_copy_clear (op);
3844         }
3845 }
3846
3847
3848
3849 struct lt_playlist {
3850     bool operator () (const PlaylistState& a, const PlaylistState& b) {
3851             return a.playlist < b.playlist;
3852     }
3853 };
3854
3855 struct PlaylistMapping {
3856     TimeAxisView* tv;
3857     boost::shared_ptr<Playlist> pl;
3858
3859     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3860 };
3861
3862 /** Remove `clicked_regionview' */
3863 void
3864 Editor::remove_clicked_region ()
3865 {
3866         if (clicked_routeview == 0 || clicked_regionview == 0) {
3867                 return;
3868         }
3869
3870         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3871
3872         begin_reversible_command (_("remove region"));
3873         playlist->clear_changes ();
3874         playlist->remove_region (clicked_regionview->region());
3875         _session->add_command(new StatefulDiffCommand (playlist));
3876         commit_reversible_command ();
3877 }
3878
3879
3880 /** Remove the selected regions */
3881 void
3882 Editor::remove_selected_regions ()
3883 {
3884         RegionSelection rs = get_regions_from_selection_and_entered ();
3885
3886         if (!_session || rs.empty()) {
3887                 return;
3888         }
3889
3890         begin_reversible_command (_("remove region"));
3891
3892         list<boost::shared_ptr<Region> > regions_to_remove;
3893
3894         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3895                 // we can't just remove the region(s) in this loop because
3896                 // this removes them from the RegionSelection, and they thus
3897                 // disappear from underneath the iterator, and the ++i above
3898                 // SEGVs in a puzzling fashion.
3899
3900                 // so, first iterate over the regions to be removed from rs and
3901                 // add them to the regions_to_remove list, and then
3902                 // iterate over the list to actually remove them.
3903
3904                 regions_to_remove.push_back ((*i)->region());
3905         }
3906
3907         vector<boost::shared_ptr<Playlist> > playlists;
3908
3909         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
3910
3911                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
3912
3913                 if (!playlist) {
3914                         // is this check necessary?
3915                         continue;
3916                 }
3917
3918                 vector<boost::shared_ptr<Playlist> >::iterator i;
3919
3920                 //only prep history if this is a new playlist.
3921                 for (i = playlists.begin(); i != playlists.end(); ++i) {
3922                         if ((*i) == playlist) {
3923                                 break;
3924                         }
3925                 }
3926
3927                 if (i == playlists.end()) {
3928
3929                         playlist->clear_changes ();
3930                         playlist->freeze ();
3931
3932                         playlists.push_back (playlist);
3933                 }
3934
3935                 playlist->remove_region (*rl);
3936         }
3937
3938         vector<boost::shared_ptr<Playlist> >::iterator pl;
3939
3940         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
3941                 (*pl)->thaw ();
3942                 _session->add_command(new StatefulDiffCommand (*pl));
3943         }
3944
3945         commit_reversible_command ();
3946 }
3947
3948 /** Cut, copy or clear selected regions.
3949  * @param op Operation (Cut, Copy or Clear)
3950  */
3951 void
3952 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
3953 {
3954         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
3955            a map when we want ordered access to both elements. i think.
3956         */
3957
3958         vector<PlaylistMapping> pmap;
3959
3960         framepos_t first_position = max_framepos;
3961
3962         typedef set<boost::shared_ptr<Playlist> > FreezeList;
3963         FreezeList freezelist;
3964
3965         /* get ordering correct before we cut/copy */
3966
3967         rs.sort_by_position_and_track ();
3968
3969         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3970
3971                 first_position = min ((framepos_t) (*x)->region()->position(), first_position);
3972
3973                 if (op == Cut || op == Clear) {
3974                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3975
3976                         if (pl) {
3977                                 FreezeList::iterator fl;
3978
3979                                 //only take state if this is a new playlist.
3980                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
3981                                         if ((*fl) == pl) {
3982                                                 break;
3983                                         }
3984                                 }
3985
3986                                 if (fl == freezelist.end()) {
3987                                         pl->clear_changes();
3988                                         pl->freeze ();
3989                                         freezelist.insert (pl);
3990                                 }
3991                         }
3992                 }
3993
3994                 TimeAxisView* tv = &(*x)->get_time_axis_view();
3995                 vector<PlaylistMapping>::iterator z;
3996
3997                 for (z = pmap.begin(); z != pmap.end(); ++z) {
3998                         if ((*z).tv == tv) {
3999                                 break;
4000                         }
4001                 }
4002
4003                 if (z == pmap.end()) {
4004                         pmap.push_back (PlaylistMapping (tv));
4005                 }
4006         }
4007
4008         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
4009
4010                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4011
4012                 if (!pl) {
4013                         /* region not yet associated with a playlist (e.g. unfinished
4014                            capture pass.
4015                         */
4016                         ++x;
4017                         continue;
4018                 }
4019
4020                 TimeAxisView& tv = (*x)->get_time_axis_view();
4021                 boost::shared_ptr<Playlist> npl;
4022                 RegionSelection::iterator tmp;
4023
4024                 tmp = x;
4025                 ++tmp;
4026
4027                 vector<PlaylistMapping>::iterator z;
4028
4029                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4030                         if ((*z).tv == &tv) {
4031                                 break;
4032                         }
4033                 }
4034
4035                 assert (z != pmap.end());
4036
4037                 if (!(*z).pl) {
4038                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4039                         npl->freeze();
4040                         (*z).pl = npl;
4041                 } else {
4042                         npl = (*z).pl;
4043                 }
4044
4045                 boost::shared_ptr<Region> r = (*x)->region();
4046                 boost::shared_ptr<Region> _xx;
4047
4048                 assert (r != 0);
4049
4050                 switch (op) {
4051                 case Cut:
4052                         _xx = RegionFactory::create (r);
4053                         npl->add_region (_xx, r->position() - first_position);
4054                         pl->remove_region (r);
4055                         break;
4056
4057                 case Copy:
4058                         /* copy region before adding, so we're not putting same object into two different playlists */
4059                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4060                         break;
4061
4062                 case Clear:
4063                         pl->remove_region (r);
4064                         break;
4065                 }
4066
4067                 x = tmp;
4068         }
4069
4070         list<boost::shared_ptr<Playlist> > foo;
4071
4072         /* the pmap is in the same order as the tracks in which selected regions occured */
4073
4074         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4075                 if ((*i).pl) {
4076                         (*i).pl->thaw();
4077                         foo.push_back ((*i).pl);
4078                 }
4079         }
4080
4081         if (!foo.empty()) {
4082                 cut_buffer->set (foo);
4083         }
4084
4085         if (pmap.empty()) {
4086                 _last_cut_copy_source_track = 0;
4087         } else {
4088                 _last_cut_copy_source_track = pmap.front().tv;
4089         }
4090         
4091         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4092                 (*pl)->thaw ();
4093                 _session->add_command (new StatefulDiffCommand (*pl));
4094         }
4095 }
4096
4097 void
4098 Editor::cut_copy_ranges (CutCopyOp op)
4099 {
4100         TrackViewList* ts;
4101         TrackViewList entered;
4102
4103         if (selection->tracks.empty()) {
4104                 if (!entered_track) {
4105                         return;
4106                 }
4107                 entered.push_back (entered_track);
4108                 ts = &entered;
4109         } else {
4110                 ts = &selection->tracks;
4111         }
4112
4113         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4114                 (*i)->cut_copy_clear (*selection, op);
4115         }
4116 }
4117
4118 void
4119 Editor::paste (float times)
4120 {
4121         paste_internal (get_preferred_edit_position(), times);
4122 }
4123
4124 void
4125 Editor::mouse_paste ()
4126 {
4127         framepos_t where;
4128         bool ignored;
4129
4130         if (!mouse_frame (where, ignored)) {
4131                 return;
4132         }
4133
4134         snap_to (where);
4135         paste_internal (where, 1);
4136 }
4137
4138 void
4139 Editor::paste_internal (framepos_t position, float times)
4140 {
4141         bool commit = false;
4142
4143         if (internal_editing()) {
4144                 if (cut_buffer->midi_notes.empty()) {
4145                         return;
4146                 }
4147         } else {
4148                 if (cut_buffer->empty()) {
4149                         return;
4150                 }
4151         }
4152
4153         if (position == max_framepos) {
4154                 position = get_preferred_edit_position();
4155         }
4156
4157         begin_reversible_command (_("paste"));
4158
4159         TrackViewList ts;
4160         TrackViewList::iterator i;
4161         size_t nth;
4162
4163         /* get everything in the correct order */
4164
4165         if (!selection->tracks.empty()) {
4166                 /* there are some selected tracks, so paste to them */
4167                 sort_track_selection ();
4168                 ts = selection->tracks;
4169         } else if (_last_cut_copy_source_track) {
4170                 /* otherwise paste to the track that the cut/copy came from;
4171                    see discussion in mants #3333.
4172                 */
4173                 ts.push_back (_last_cut_copy_source_track);
4174         }
4175
4176         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4177
4178                 /* undo/redo is handled by individual tracks/regions */
4179
4180                 if (internal_editing()) {
4181
4182                         RegionSelection rs;
4183                         RegionSelection::iterator r;
4184                         MidiNoteSelection::iterator cb;
4185
4186                         get_regions_at (rs, position, ts);
4187
4188                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4189                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4190                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4191                                 if (mrv) {
4192                                         mrv->paste (position, times, **cb);
4193                                         ++cb;
4194                                 }
4195                         }
4196
4197                 } else {
4198
4199                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4200                                 commit = true;
4201                         }
4202                 }
4203         }
4204
4205         if (commit) {
4206                 commit_reversible_command ();
4207         }
4208 }
4209
4210 void
4211 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4212 {
4213         boost::shared_ptr<Playlist> playlist;
4214         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4215         RegionSelection foo;
4216
4217         framepos_t const start_frame = regions.start ();
4218         framepos_t const end_frame = regions.end_frame ();
4219
4220         begin_reversible_command (_("duplicate region"));
4221
4222         selection->clear_regions ();
4223
4224         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4225
4226                 boost::shared_ptr<Region> r ((*i)->region());
4227
4228                 TimeAxisView& tv = (*i)->get_time_axis_view();
4229                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4230                 latest_regionviews.clear ();
4231                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4232
4233                 playlist = (*i)->region()->playlist();
4234                 playlist->clear_changes ();
4235                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame), times);
4236                 _session->add_command(new StatefulDiffCommand (playlist));
4237
4238                 c.disconnect ();
4239
4240                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4241         }
4242
4243         commit_reversible_command ();
4244
4245         if (!foo.empty()) {
4246                 selection->set (foo);
4247         }
4248 }
4249
4250 void
4251 Editor::duplicate_selection (float times)
4252 {
4253         if (selection->time.empty() || selection->tracks.empty()) {
4254                 return;
4255         }
4256
4257         boost::shared_ptr<Playlist> playlist;
4258         vector<boost::shared_ptr<Region> > new_regions;
4259         vector<boost::shared_ptr<Region> >::iterator ri;
4260
4261         create_region_from_selection (new_regions);
4262
4263         if (new_regions.empty()) {
4264                 return;
4265         }
4266
4267         begin_reversible_command (_("duplicate selection"));
4268
4269         ri = new_regions.begin();
4270
4271         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4272                 if ((playlist = (*i)->playlist()) == 0) {
4273                         continue;
4274                 }
4275                 playlist->clear_changes ();
4276                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4277                 _session->add_command (new StatefulDiffCommand (playlist));
4278
4279                 ++ri;
4280                 if (ri == new_regions.end()) {
4281                         --ri;
4282                 }
4283         }
4284
4285         commit_reversible_command ();
4286 }
4287
4288 void
4289 Editor::reset_point_selection ()
4290 {
4291         /* reset all selected points to the relevant default value */
4292
4293         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4294
4295                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4296
4297                 if (atv) {
4298                         atv->reset_objects (selection->points);
4299                 }
4300         }
4301 }
4302
4303 void
4304 Editor::center_playhead ()
4305 {
4306         float page = _canvas_width * frames_per_unit;
4307         center_screen_internal (playhead_cursor->current_frame, page);
4308 }
4309
4310 void
4311 Editor::center_edit_point ()
4312 {
4313         float page = _canvas_width * frames_per_unit;
4314         center_screen_internal (get_preferred_edit_position(), page);
4315 }
4316
4317 /** Caller must begin and commit a reversible command */
4318 void
4319 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4320 {
4321         playlist->clear_changes ();
4322         playlist->clear ();
4323         _session->add_command (new StatefulDiffCommand (playlist));
4324 }
4325
4326 void
4327 Editor::nudge_track (bool use_edit, bool forwards)
4328 {
4329         boost::shared_ptr<Playlist> playlist;
4330         framepos_t distance;
4331         framepos_t next_distance;
4332         framepos_t start;
4333
4334         if (use_edit) {
4335                 start = get_preferred_edit_position();
4336         } else {
4337                 start = 0;
4338         }
4339
4340         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4341                 return;
4342         }
4343
4344         if (selection->tracks.empty()) {
4345                 return;
4346         }
4347
4348         begin_reversible_command (_("nudge track"));
4349
4350         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4351
4352                 if ((playlist = (*i)->playlist()) == 0) {
4353                         continue;
4354                 }
4355
4356                 playlist->clear_changes ();
4357                 playlist->clear_owned_changes ();
4358
4359                 playlist->nudge_after (start, distance, forwards);
4360                 
4361                 vector<Command*> cmds;
4362                 
4363                 playlist->rdiff (cmds);
4364                 _session->add_commands (cmds);
4365                 
4366                 _session->add_command (new StatefulDiffCommand (playlist));
4367         }
4368
4369         commit_reversible_command ();
4370 }
4371
4372 void
4373 Editor::remove_last_capture ()
4374 {
4375         vector<string> choices;
4376         string prompt;
4377
4378         if (!_session) {
4379                 return;
4380         }
4381
4382         if (Config->get_verify_remove_last_capture()) {
4383                 prompt  = _("Do you really want to destroy the last capture?"
4384                             "\n(This is destructive and cannot be undone)");
4385
4386                 choices.push_back (_("No, do nothing."));
4387                 choices.push_back (_("Yes, destroy it."));
4388
4389                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4390
4391                 if (prompter.run () == 1) {
4392                         _session->remove_last_capture ();
4393                         _regions->redisplay ();
4394                 }
4395
4396         } else {
4397                 _session->remove_last_capture();
4398                 _regions->redisplay ();
4399         }
4400 }
4401
4402 void
4403 Editor::normalize_region ()
4404 {
4405         if (!_session) {
4406                 return;
4407         }
4408
4409         RegionSelection rs = get_regions_from_selection_and_entered ();
4410         
4411         if (rs.empty()) {
4412                 return;
4413         }
4414
4415         NormalizeDialog dialog (rs.size() > 1);
4416
4417         if (dialog.run () == RESPONSE_CANCEL) {
4418                 return;
4419         }
4420
4421         set_canvas_cursor (_cursors->wait);
4422         gdk_flush ();
4423
4424         /* XXX: should really only count audio regions here */
4425         int const regions = rs.size ();
4426
4427         /* Make a list of the selected audio regions' maximum amplitudes, and also
4428            obtain the maximum amplitude of them all.
4429         */
4430         list<double> max_amps;
4431         double max_amp = 0;
4432         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
4433                 AudioRegionView const * arv = dynamic_cast<AudioRegionView const *> (*i);
4434                 if (arv) {
4435                         dialog.descend (1.0 / regions);
4436                         double const a = arv->audio_region()->maximum_amplitude (&dialog);
4437
4438                         if (a == -1) {
4439                                 /* the user cancelled the operation */
4440                                 set_canvas_cursor (current_canvas_cursor);
4441                                 return;
4442                         }
4443                         
4444                         max_amps.push_back (a);
4445                         max_amp = max (max_amp, a);
4446                         dialog.ascend ();
4447                 }
4448         }
4449
4450         begin_reversible_command (_("normalize"));
4451
4452         list<double>::const_iterator a = max_amps.begin ();
4453         
4454         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4455                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4456                 if (!arv) {
4457                         continue;
4458                 }
4459
4460                 arv->region()->clear_changes ();
4461
4462                 double const amp = dialog.normalize_individually() ? *a : max_amp;
4463                 
4464                 arv->audio_region()->normalize (amp, dialog.target ());
4465                 _session->add_command (new StatefulDiffCommand (arv->region()));
4466
4467                 ++a;
4468         }
4469
4470         commit_reversible_command ();
4471         set_canvas_cursor (current_canvas_cursor);
4472 }
4473
4474
4475 void
4476 Editor::reset_region_scale_amplitude ()
4477 {
4478         if (!_session) {
4479                 return;
4480         }
4481
4482         RegionSelection rs = get_regions_from_selection_and_entered ();
4483
4484         if (rs.empty()) {
4485                 return;
4486         }
4487
4488         begin_reversible_command ("reset gain");
4489
4490         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4491                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4492                 if (!arv)
4493                         continue;
4494                 arv->region()->clear_changes ();
4495                 arv->audio_region()->set_scale_amplitude (1.0f);
4496                 _session->add_command (new StatefulDiffCommand (arv->region()));
4497         }
4498
4499         commit_reversible_command ();
4500 }
4501
4502 void
4503 Editor::adjust_region_gain (bool up)
4504 {
4505         RegionSelection rs = get_regions_from_selection_and_entered ();
4506
4507         if (!_session || rs.empty()) {
4508                 return;
4509         }
4510
4511         begin_reversible_command ("adjust region gain");
4512
4513         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4514                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4515                 if (!arv) {
4516                         continue;
4517                 }
4518
4519                 arv->region()->clear_changes ();
4520
4521                 double dB = accurate_coefficient_to_dB (arv->audio_region()->scale_amplitude ());
4522
4523                 if (up) {
4524                         dB += 1;
4525                 } else {
4526                         dB -= 1;
4527                 }
4528
4529                 arv->audio_region()->set_scale_amplitude (dB_to_coefficient (dB));
4530                 _session->add_command (new StatefulDiffCommand (arv->region()));
4531         }
4532
4533         commit_reversible_command ();
4534 }
4535
4536
4537 void
4538 Editor::reverse_region ()
4539 {
4540         if (!_session) {
4541                 return;
4542         }
4543
4544         Reverse rev (*_session);
4545         apply_filter (rev, _("reverse regions"));
4546 }
4547
4548 void
4549 Editor::strip_region_silence ()
4550 {
4551         if (!_session) {
4552                 return;
4553         }
4554
4555         RegionSelection rs = get_regions_from_selection_and_entered ();
4556
4557         if (rs.empty()) {
4558                 return;
4559         }
4560
4561         std::list<RegionView*> audio_only;
4562
4563         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4564                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4565                 if (arv) {
4566                         audio_only.push_back (arv);
4567                 }
4568         }
4569
4570         StripSilenceDialog d (_session, audio_only);
4571         int const r = d.run ();
4572
4573         d.drop_rects ();
4574         
4575         if (r == Gtk::RESPONSE_OK) {
4576                 ARDOUR::AudioIntervalMap silences;
4577                 d.silences (silences);
4578                 StripSilence s (*_session, silences, d.fade_length());
4579                 apply_filter (s, _("strip silence"), &d);
4580         } 
4581 }
4582
4583 Command*
4584 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4585 {
4586         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4587         mrv.selection_as_notelist (selected, true);
4588
4589         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4590         v.push_back (selected);
4591
4592         return op (mrv.midi_region()->model(), v);
4593 }
4594
4595 void
4596 Editor::apply_midi_note_edit_op (MidiOperator& op)
4597 {
4598         Command* cmd;
4599
4600         RegionSelection rs = get_regions_from_selection_and_entered ();
4601
4602         if (rs.empty()) {
4603                 return;
4604         }
4605
4606         begin_reversible_command (op.name ());
4607
4608         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4609                 RegionSelection::iterator tmp = r;
4610                 ++tmp;
4611
4612                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4613
4614                 if (mrv) {
4615                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4616                         if (cmd) {
4617                                 (*cmd)();
4618                                 _session->add_command (cmd);
4619                         }
4620                 }
4621
4622                 r = tmp;
4623         }
4624
4625         commit_reversible_command ();
4626 }
4627
4628 void
4629 Editor::fork_region ()
4630 {
4631         RegionSelection rs = get_regions_from_selection_and_entered ();
4632
4633         if (rs.empty()) {
4634                 return;
4635         }
4636
4637         begin_reversible_command (_("Fork Region(s)"));
4638
4639         set_canvas_cursor (_cursors->wait);
4640         gdk_flush ();
4641
4642         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4643                 RegionSelection::iterator tmp = r;
4644                 ++tmp;
4645
4646                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4647
4648                 if (mrv) {
4649                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4650                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4651                         
4652                         playlist->clear_changes ();
4653                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4654                         _session->add_command(new StatefulDiffCommand (playlist));
4655                 }
4656
4657                 r = tmp;
4658         }
4659
4660         commit_reversible_command ();
4661
4662         set_canvas_cursor (current_canvas_cursor);
4663 }
4664
4665 void
4666 Editor::quantize_region ()
4667 {
4668         int selected_midi_region_cnt = 0;
4669
4670         if (!_session) {
4671                 return;
4672         }
4673
4674         RegionSelection rs = get_regions_from_selection_and_entered ();
4675
4676         if (rs.empty()) {
4677                 return;
4678         }
4679
4680         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4681                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4682                 if (mrv) {
4683                         selected_midi_region_cnt++;
4684                 }
4685         }
4686
4687         if (selected_midi_region_cnt == 0) {
4688                 return;
4689         }
4690
4691         QuantizeDialog* qd = new QuantizeDialog (*this);
4692
4693         qd->present ();
4694         const int r = qd->run ();
4695         qd->hide ();
4696
4697         if (r == Gtk::RESPONSE_OK) {
4698                 Quantize quant (*_session, Plain,
4699                                 qd->snap_start(), qd->snap_end(),
4700                                 qd->start_grid_size(), qd->end_grid_size(),
4701                                 qd->strength(), qd->swing(), qd->threshold());
4702
4703                 apply_midi_note_edit_op (quant);
4704         }
4705 }
4706
4707 void
4708 Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress)
4709 {
4710         RegionSelection rs = get_regions_from_selection_and_entered ();
4711
4712         if (rs.empty()) {
4713                 return;
4714         }
4715
4716         begin_reversible_command (command);
4717
4718         set_canvas_cursor (_cursors->wait);
4719         gdk_flush ();
4720
4721         int n = 0;
4722         int const N = rs.size ();
4723         
4724         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4725                 RegionSelection::iterator tmp = r;
4726                 ++tmp;
4727
4728                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4729                 if (arv) {
4730                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4731
4732                         if (progress) {
4733                                 progress->descend (1.0 / N);
4734                         }
4735
4736                         if (arv->audio_region()->apply (filter, progress) == 0) {
4737
4738                                 playlist->clear_changes ();
4739
4740                                 if (filter.results.empty ()) {
4741
4742                                         /* no regions returned; remove the old one */
4743                                         playlist->remove_region (arv->region ());
4744
4745                                 } else {
4746
4747                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4748
4749                                         /* first region replaces the old one */
4750                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4751                                         ++res;
4752
4753                                         /* add the rest */
4754                                         while (res != filter.results.end()) {
4755                                                 playlist->add_region (*res, (*res)->position());
4756                                                 ++res;
4757                                         }
4758
4759                                 }
4760
4761                                 _session->add_command(new StatefulDiffCommand (playlist));
4762                         } else {
4763                                 goto out;
4764                         }
4765
4766                         if (progress) {
4767                                 progress->ascend ();
4768                         }
4769                 }
4770
4771                 r = tmp;
4772                 ++n;
4773         }
4774
4775         commit_reversible_command ();
4776
4777   out:
4778         set_canvas_cursor (current_canvas_cursor);
4779 }
4780
4781 void
4782 Editor::external_edit_region ()
4783 {
4784         /* more to come */
4785 }
4786
4787 void
4788 Editor::brush (framepos_t pos)
4789 {
4790         snap_to (pos);
4791
4792         RegionSelection rs = get_regions_from_selection_and_entered ();
4793
4794         if (rs.empty()) {
4795                 return;
4796         }
4797
4798         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4799                 mouse_brush_insert_region ((*i), pos);
4800         }
4801 }
4802
4803 void
4804 Editor::reset_region_gain_envelopes ()
4805 {
4806         RegionSelection rs = get_regions_from_selection_and_entered ();
4807
4808         if (!_session || rs.empty()) {
4809                 return;
4810         }
4811
4812         _session->begin_reversible_command (_("reset region gain"));
4813
4814         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4815                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4816                 if (arv) {
4817                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4818                         XMLNode& before (alist->get_state());
4819
4820                         arv->audio_region()->set_default_envelope ();
4821                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4822                 }
4823         }
4824
4825         _session->commit_reversible_command ();
4826 }
4827
4828 void
4829 Editor::toggle_gain_envelope_visibility ()
4830 {
4831         if (_ignore_region_action) {
4832                 return;
4833         }
4834         
4835         RegionSelection rs = get_regions_from_selection_and_entered ();
4836
4837         if (!_session || rs.empty()) {
4838                 return;
4839         }
4840
4841         _session->begin_reversible_command (_("region gain envelope visible"));
4842
4843         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4844                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4845                 if (arv) {
4846                         arv->region()->clear_changes ();
4847                         arv->set_envelope_visible (!arv->envelope_visible());
4848                         _session->add_command (new StatefulDiffCommand (arv->region()));
4849                 }
4850         }
4851
4852         _session->commit_reversible_command ();
4853 }
4854
4855 void
4856 Editor::toggle_gain_envelope_active ()
4857 {
4858         if (_ignore_region_action) {
4859                 return;
4860         }
4861         
4862         RegionSelection rs = get_regions_from_selection_and_entered ();
4863
4864         if (!_session || rs.empty()) {
4865                 return;
4866         }
4867
4868         _session->begin_reversible_command (_("region gain envelope active"));
4869
4870         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4871                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4872                 if (arv) {
4873                         arv->region()->clear_changes ();
4874                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4875                         _session->add_command (new StatefulDiffCommand (arv->region()));
4876                 }
4877         }
4878
4879         _session->commit_reversible_command ();
4880 }
4881
4882 void
4883 Editor::toggle_region_lock ()
4884 {
4885         if (_ignore_region_action) {
4886                 return;
4887         }
4888
4889         RegionSelection rs = get_regions_from_selection_and_entered ();
4890
4891         if (!_session || rs.empty()) {
4892                 return;
4893         }
4894
4895         _session->begin_reversible_command (_("toggle region lock"));
4896
4897         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4898                 (*i)->region()->clear_changes ();
4899                 (*i)->region()->set_locked (!(*i)->region()->locked());
4900                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4901         }
4902
4903         _session->commit_reversible_command ();
4904 }
4905
4906 void
4907 Editor::toggle_region_lock_style ()
4908 {
4909         if (_ignore_region_action) {
4910                 return;
4911         }
4912         
4913         RegionSelection rs = get_regions_from_selection_and_entered ();
4914
4915         if (!_session || rs.empty()) {
4916                 return;
4917         }
4918
4919         _session->begin_reversible_command (_("region lock style"));
4920
4921         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4922                 (*i)->region()->clear_changes ();
4923                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
4924                 (*i)->region()->set_position_lock_style (ns);
4925                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4926         }
4927
4928         _session->commit_reversible_command ();
4929 }
4930
4931 void
4932 Editor::toggle_opaque_region ()
4933 {
4934         if (_ignore_region_action) {
4935                 return;
4936         }
4937         
4938         RegionSelection rs = get_regions_from_selection_and_entered ();
4939
4940         if (!_session || rs.empty()) {
4941                 return;
4942         }
4943
4944         _session->begin_reversible_command (_("change region opacity"));
4945
4946         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4947                 (*i)->region()->clear_changes ();
4948                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4949                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4950         }
4951
4952         _session->commit_reversible_command ();
4953 }
4954
4955 void
4956 Editor::toggle_record_enable ()
4957 {
4958         bool new_state = false;
4959         bool first = true;
4960         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4961                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4962                 if (!rtav)
4963                         continue;
4964                 if (!rtav->is_track())
4965                         continue;
4966
4967                 if (first) {
4968                         new_state = !rtav->track()->record_enabled();
4969                         first = false;
4970                 }
4971
4972                 rtav->track()->set_record_enabled (new_state, this);
4973         }
4974 }
4975
4976
4977 void
4978 Editor::set_fade_length (bool in)
4979 {
4980         RegionSelection rs = get_regions_from_selection_and_entered ();
4981
4982         if (rs.empty()) {
4983                 return;
4984         }
4985
4986         /* we need a region to measure the offset from the start */
4987
4988         RegionView* rv = rs.front ();
4989
4990         framepos_t pos = get_preferred_edit_position();
4991         framepos_t len;
4992         char const * cmd;
4993
4994         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
4995                 /* edit point is outside the relevant region */
4996                 return;
4997         }
4998
4999         if (in) {
5000                 if (pos <= rv->region()->position()) {
5001                         /* can't do it */
5002                         return;
5003                 }
5004                 len = pos - rv->region()->position();
5005                 cmd = _("set fade in length");
5006         } else {
5007                 if (pos >= rv->region()->last_frame()) {
5008                         /* can't do it */
5009                         return;
5010                 }
5011                 len = rv->region()->last_frame() - pos;
5012                 cmd = _("set fade out length");
5013         }
5014
5015         begin_reversible_command (cmd);
5016
5017         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5018                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5019
5020                 if (!tmp) {
5021                         return;
5022                 }
5023
5024                 boost::shared_ptr<AutomationList> alist;
5025                 if (in) {
5026                         alist = tmp->audio_region()->fade_in();
5027                 } else {
5028                         alist = tmp->audio_region()->fade_out();
5029                 }
5030
5031                 XMLNode &before = alist->get_state();
5032
5033                 if (in) {
5034                         tmp->audio_region()->set_fade_in_length (len);
5035                         tmp->audio_region()->set_fade_in_active (true);
5036                 } else {
5037                         tmp->audio_region()->set_fade_out_length (len);
5038                         tmp->audio_region()->set_fade_out_active (true);
5039                 }
5040
5041                 XMLNode &after = alist->get_state();
5042                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
5043         }
5044
5045         commit_reversible_command ();
5046 }
5047
5048 void
5049 Editor::set_fade_in_shape (FadeShape shape)
5050 {
5051         RegionSelection rs = get_regions_from_selection_and_entered ();
5052
5053         if (rs.empty()) {
5054                 return;
5055         }
5056
5057         begin_reversible_command (_("set fade in shape"));
5058
5059         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5060                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5061
5062                 if (!tmp) {
5063                         return;
5064                 }
5065
5066                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5067                 XMLNode &before = alist->get_state();
5068
5069                 tmp->audio_region()->set_fade_in_shape (shape);
5070
5071                 XMLNode &after = alist->get_state();
5072                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5073         }
5074
5075         commit_reversible_command ();
5076
5077 }
5078
5079 void
5080 Editor::set_fade_out_shape (FadeShape shape)
5081 {
5082         RegionSelection rs = get_regions_from_selection_and_entered ();
5083
5084         if (rs.empty()) {
5085                 return;
5086         }
5087
5088         begin_reversible_command (_("set fade out shape"));
5089
5090         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5091                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5092
5093                 if (!tmp) {
5094                         return;
5095                 }
5096
5097                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5098                 XMLNode &before = alist->get_state();
5099
5100                 tmp->audio_region()->set_fade_out_shape (shape);
5101
5102                 XMLNode &after = alist->get_state();
5103                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5104         }
5105
5106         commit_reversible_command ();
5107 }
5108
5109 void
5110 Editor::set_fade_in_active (bool yn)
5111 {
5112         RegionSelection rs = get_regions_from_selection_and_entered ();
5113
5114         if (rs.empty()) {
5115                 return;
5116         }
5117
5118         begin_reversible_command (_("set fade in active"));
5119
5120         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5121                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5122
5123                 if (!tmp) {
5124                         return;
5125                 }
5126
5127
5128                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5129                 
5130                 ar->clear_changes ();
5131                 ar->set_fade_in_active (yn);
5132                 _session->add_command (new StatefulDiffCommand (ar));
5133         }
5134
5135         commit_reversible_command ();
5136 }
5137
5138 void
5139 Editor::set_fade_out_active (bool yn)
5140 {
5141         RegionSelection rs = get_regions_from_selection_and_entered ();
5142
5143         if (rs.empty()) {
5144                 return;
5145         }
5146
5147         begin_reversible_command (_("set fade out active"));
5148
5149         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5150                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5151
5152                 if (!tmp) {
5153                         return;
5154                 }
5155
5156                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5157
5158                 ar->clear_changes ();
5159                 ar->set_fade_out_active (yn);
5160                 _session->add_command(new StatefulDiffCommand (ar));
5161         }
5162
5163         commit_reversible_command ();
5164 }
5165
5166 void
5167 Editor::toggle_region_fades (int dir)
5168 {
5169         boost::shared_ptr<AudioRegion> ar;
5170         bool yn;
5171
5172         RegionSelection rs = get_regions_from_selection_and_entered ();
5173
5174         if (rs.empty()) {
5175                 return;
5176         }
5177
5178         RegionSelection::iterator i;    
5179         for (i = rs.begin(); i != rs.end(); ++i) {
5180                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5181                         if (dir == -1) {
5182                                 yn = ar->fade_out_active ();
5183                         } else {
5184                                 yn = ar->fade_in_active ();
5185                         }
5186                         break;
5187                 }
5188         }
5189
5190         if (i == rs.end()) {
5191                 return;
5192         }
5193
5194         /* XXX should this undo-able? */
5195
5196         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5197                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5198                         continue;
5199                 }
5200                 if (dir == 1 || dir == 0) {
5201                         ar->set_fade_in_active (!yn);
5202                 }
5203
5204                 if (dir == -1 || dir == 0) {
5205                         ar->set_fade_out_active (!yn);
5206                 }
5207         }
5208 }
5209
5210
5211 /** Update region fade visibility after its configuration has been changed */
5212 void
5213 Editor::update_region_fade_visibility ()
5214 {
5215         bool _fade_visibility = _session->config.get_show_region_fades ();
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 (_fade_visibility) {
5221                                 v->audio_view()->show_all_fades ();
5222                         } else {
5223                                 v->audio_view()->hide_all_fades ();
5224                         }
5225                 }
5226         }
5227 }
5228
5229 /** Update crossfade visibility after its configuration has been changed */
5230 void
5231 Editor::update_xfade_visibility ()
5232 {
5233         _xfade_visibility = _session->config.get_xfades_visible ();
5234
5235         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5236                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5237                 if (v) {
5238                         if (_xfade_visibility) {
5239                                 v->show_all_xfades ();
5240                         } else {
5241                                 v->hide_all_xfades ();
5242                         }
5243                 }
5244         }
5245 }
5246
5247 void
5248 Editor::set_edit_point ()
5249 {
5250         framepos_t where;
5251         bool ignored;
5252
5253         if (!mouse_frame (where, ignored)) {
5254                 return;
5255         }
5256
5257         snap_to (where);
5258
5259         if (selection->markers.empty()) {
5260
5261                 mouse_add_new_marker (where);
5262
5263         } else {
5264                 bool ignored;
5265
5266                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5267
5268                 if (loc) {
5269                         loc->move_to (where);
5270                 }
5271         }
5272 }
5273
5274 void
5275 Editor::set_playhead_cursor ()
5276 {
5277         if (entered_marker) {
5278                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5279         } else {
5280                 framepos_t where;
5281                 bool ignored;
5282
5283                 if (!mouse_frame (where, ignored)) {
5284                         return;
5285                 }
5286
5287                 snap_to (where);
5288
5289                 if (_session) {
5290                         _session->request_locate (where, _session->transport_rolling());
5291                 }
5292         }
5293 }
5294
5295 void
5296 Editor::split_region ()
5297 {
5298         if (((mouse_mode == MouseRange) || 
5299              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) && 
5300             !selection->time.empty()) {
5301                 separate_regions_between (selection->time);
5302                 return;
5303         } 
5304
5305         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5306
5307         framepos_t where = get_preferred_edit_position ();
5308
5309         if (rs.empty()) {
5310                 return;
5311         }
5312
5313         split_regions_at (where, rs);
5314 }
5315
5316 void
5317 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5318 {
5319         if (entered_track && mouse_mode == MouseObject) {
5320                 if (!selection->tracks.empty()) {
5321                         if (!selection->selected (entered_track)) {
5322                                 selection->add (entered_track);
5323                         }
5324                 } else {
5325                         /* there is no selection, but this operation requires/prefers selected objects */
5326
5327                         if (op_really_wants_one_track_if_none_are_selected) {
5328                                 selection->set (entered_track);
5329                         }
5330                 }
5331         }
5332 }
5333
5334 struct EditorOrderRouteSorter {
5335     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5336             /* use of ">" forces the correct sort order */
5337             return a->order_key ("editor") < b->order_key ("editor");
5338     }
5339 };
5340
5341 void
5342 Editor::select_next_route()
5343 {
5344         if (selection->tracks.empty()) {
5345                 selection->set (track_views.front());
5346                 return;
5347         }
5348
5349         TimeAxisView* current = selection->tracks.front();
5350
5351         RouteUI *rui;
5352         do {
5353                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5354                         if (*i == current) {
5355                                 ++i;
5356                                 if (i != track_views.end()) {
5357                                         current = (*i);
5358                                 } else {
5359                                         current = (*(track_views.begin()));
5360                                         //selection->set (*(track_views.begin()));
5361                                 }
5362                                 break;
5363                         }
5364                 }
5365                 rui = dynamic_cast<RouteUI *>(current);
5366         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5367
5368         selection->set(current);
5369
5370         ensure_track_visible(current);
5371 }
5372
5373 void
5374 Editor::select_prev_route()
5375 {
5376         if (selection->tracks.empty()) {
5377                 selection->set (track_views.front());
5378                 return;
5379         }
5380
5381         TimeAxisView* current = selection->tracks.front();
5382
5383         RouteUI *rui;
5384         do {
5385                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5386                         if (*i == current) {
5387                                 ++i;
5388                                 if (i != track_views.rend()) {
5389                                         current = (*i);
5390                                 } else {
5391                                         current = *(track_views.rbegin());
5392                                 }
5393                                 break;
5394                         }
5395                 }
5396                 rui = dynamic_cast<RouteUI *>(current);
5397         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5398
5399         selection->set (current);
5400
5401         ensure_track_visible(current);
5402 }
5403
5404 void
5405 Editor::ensure_track_visible(TimeAxisView *track)
5406 {
5407         if (track->hidden())
5408                 return;
5409
5410         double const current_view_min_y = vertical_adjustment.get_value();
5411         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5412
5413         double const track_min_y = track->y_position ();
5414         double const track_max_y = track->y_position () + track->effective_height ();
5415
5416         if (track_min_y >= current_view_min_y &&
5417             track_max_y <= current_view_max_y) {
5418                 return;
5419         }
5420
5421         double new_value;
5422
5423         if (track_min_y < current_view_min_y) {
5424                 // Track is above the current view
5425                 new_value = track_min_y;
5426         } else {
5427                 // Track is below the current view
5428                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5429         }
5430
5431         vertical_adjustment.set_value(new_value);
5432 }
5433
5434 void
5435 Editor::set_loop_from_selection (bool play)
5436 {
5437         if (_session == 0 || selection->time.empty()) {
5438                 return;
5439         }
5440
5441         framepos_t start = selection->time[clicked_selection].start;
5442         framepos_t end = selection->time[clicked_selection].end;
5443
5444         set_loop_range (start, end,  _("set loop range from selection"));
5445
5446         if (play) {
5447                 _session->request_play_loop (true);
5448                 _session->request_locate (start, true);
5449         }
5450 }
5451
5452 void
5453 Editor::set_loop_from_edit_range (bool play)
5454 {
5455         if (_session == 0) {
5456                 return;
5457         }
5458
5459         framepos_t start;
5460         framepos_t end;
5461
5462         if (!get_edit_op_range (start, end)) {
5463                 return;
5464         }
5465
5466         set_loop_range (start, end,  _("set loop range from edit range"));
5467
5468         if (play) {
5469                 _session->request_play_loop (true);
5470                 _session->request_locate (start, true);
5471         }
5472 }
5473
5474 void
5475 Editor::set_loop_from_region (bool play)
5476 {
5477         framepos_t start = max_framepos;
5478         framepos_t end = 0;
5479
5480         RegionSelection rs = get_regions_from_selection_and_entered ();
5481
5482         if (rs.empty()) {
5483                 return;
5484         }
5485
5486         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5487                 if ((*i)->region()->position() < start) {
5488                         start = (*i)->region()->position();
5489                 }
5490                 if ((*i)->region()->last_frame() + 1 > end) {
5491                         end = (*i)->region()->last_frame() + 1;
5492                 }
5493         }
5494
5495         set_loop_range (start, end, _("set loop range from region"));
5496
5497         if (play) {
5498                 _session->request_play_loop (true);
5499                 _session->request_locate (start, true);
5500         }
5501 }
5502
5503 void
5504 Editor::set_punch_from_selection ()
5505 {
5506         if (_session == 0 || selection->time.empty()) {
5507                 return;
5508         }
5509
5510         framepos_t start = selection->time[clicked_selection].start;
5511         framepos_t end = selection->time[clicked_selection].end;
5512
5513         set_punch_range (start, end,  _("set punch range from selection"));
5514 }
5515
5516 void
5517 Editor::set_punch_from_edit_range ()
5518 {
5519         if (_session == 0) {
5520                 return;
5521         }
5522
5523         framepos_t start;
5524         framepos_t end;
5525
5526         if (!get_edit_op_range (start, end)) {
5527                 return;
5528         }
5529
5530         set_punch_range (start, end,  _("set punch range from edit range"));
5531 }
5532
5533 void
5534 Editor::set_punch_from_region ()
5535 {
5536         framepos_t start = max_framepos;
5537         framepos_t end = 0;
5538
5539         RegionSelection rs = get_regions_from_selection_and_entered ();
5540
5541         if (rs.empty()) {
5542                 return;
5543         }
5544
5545         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5546                 if ((*i)->region()->position() < start) {
5547                         start = (*i)->region()->position();
5548                 }
5549                 if ((*i)->region()->last_frame() + 1 > end) {
5550                         end = (*i)->region()->last_frame() + 1;
5551                 }
5552         }
5553
5554         set_punch_range (start, end, _("set punch range from region"));
5555 }
5556
5557 void
5558 Editor::pitch_shift_region ()
5559 {
5560         RegionSelection rs = get_regions_from_selection_and_entered ();
5561
5562         if (rs.empty()) {
5563                 return;
5564         }
5565
5566         pitch_shift (rs, 1.2);
5567 }
5568
5569 void
5570 Editor::set_tempo_from_region ()
5571 {
5572         RegionSelection rs = get_regions_from_selection_and_entered ();
5573
5574         if (!_session || rs.empty()) {
5575                 return;
5576         }
5577
5578         RegionView* rv = rs.front();
5579
5580         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5581 }
5582
5583 void
5584 Editor::use_range_as_bar ()
5585 {
5586         framepos_t start, end;
5587         if (get_edit_op_range (start, end)) {
5588                 define_one_bar (start, end);
5589         }
5590 }
5591
5592 void
5593 Editor::define_one_bar (framepos_t start, framepos_t end)
5594 {
5595         framepos_t length = end - start;
5596
5597         const Meter& m (_session->tempo_map().meter_at (start));
5598
5599         /* length = 1 bar */
5600
5601         /* now we want frames per beat.
5602            we have frames per bar, and beats per bar, so ...
5603         */
5604
5605         double frames_per_beat = length / m.beats_per_bar();
5606
5607         /* beats per minute = */
5608
5609         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5610
5611         /* now decide whether to:
5612
5613             (a) set global tempo
5614             (b) add a new tempo marker
5615
5616         */
5617
5618         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5619
5620         bool do_global = false;
5621
5622         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5623
5624                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5625                    at the start, or create a new marker
5626                 */
5627
5628                 vector<string> options;
5629                 options.push_back (_("Cancel"));
5630                 options.push_back (_("Add new marker"));
5631                 options.push_back (_("Set global tempo"));
5632
5633                 Choice c (
5634                         _("Define one bar"),
5635                         _("Do you want to set the global tempo or add a new tempo marker?"),
5636                         options
5637                         );
5638                 
5639                 c.set_default_response (2);
5640
5641                 switch (c.run()) {
5642                 case 0:
5643                         return;
5644
5645                 case 2:
5646                         do_global = true;
5647                         break;
5648
5649                 default:
5650                         do_global = false;
5651                 }
5652
5653         } else {
5654
5655                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5656                    if the marker is at the region starter, change it, otherwise add
5657                    a new tempo marker
5658                 */
5659         }
5660
5661         begin_reversible_command (_("set tempo from region"));
5662         XMLNode& before (_session->tempo_map().get_state());
5663
5664         if (do_global) {
5665                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5666         } else if (t.frame() == start) {
5667                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5668         } else {
5669                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5670         }
5671
5672         XMLNode& after (_session->tempo_map().get_state());
5673
5674         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5675         commit_reversible_command ();
5676 }
5677
5678 void
5679 Editor::split_region_at_transients ()
5680 {
5681         AnalysisFeatureList positions;
5682
5683         RegionSelection rs = get_regions_from_selection_and_entered ();
5684
5685         if (!_session || rs.empty()) {
5686                 return;
5687         }
5688
5689         _session->begin_reversible_command (_("split regions"));
5690
5691         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5692
5693                 RegionSelection::iterator tmp;
5694
5695                 tmp = i;
5696                 ++tmp;
5697
5698                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5699
5700                 if (ar && (ar->get_transients (positions) == 0)) {
5701                         split_region_at_points ((*i)->region(), positions, true);
5702                         positions.clear ();
5703                 }
5704
5705                 i = tmp;
5706         }
5707
5708         _session->commit_reversible_command ();
5709
5710 }
5711
5712 void
5713 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5714 {
5715         bool use_rhythmic_rodent = false;
5716
5717         boost::shared_ptr<Playlist> pl = r->playlist();
5718
5719         if (!pl) {
5720                 return;
5721         }
5722
5723         if (positions.empty()) {
5724                 return;
5725         }
5726
5727
5728         if (positions.size() > 20) {
5729                 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);
5730                 MessageDialog msg (msgstr,
5731                                    false,
5732                                    Gtk::MESSAGE_INFO,
5733                                    Gtk::BUTTONS_OK_CANCEL);
5734
5735                 if (can_ferret) {
5736                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5737                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5738                 } else {
5739                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5740                 }
5741
5742                 msg.set_title (_("Excessive split?"));
5743                 msg.present ();
5744
5745                 int response = msg.run();
5746                 msg.hide ();
5747                 
5748                 switch (response) {
5749                 case RESPONSE_OK:
5750                         break;
5751                 case RESPONSE_APPLY:
5752                         use_rhythmic_rodent = true;
5753                         break;
5754                 default:
5755                         return;
5756                 }
5757         }
5758
5759         if (use_rhythmic_rodent) {
5760                 show_rhythm_ferret ();
5761                 return;
5762         }
5763
5764         AnalysisFeatureList::const_iterator x;
5765
5766         pl->clear_changes ();
5767
5768         x = positions.begin();
5769
5770         if (x == positions.end()) {
5771                 return;
5772         }
5773
5774         pl->freeze ();
5775         pl->remove_region (r);
5776
5777         framepos_t pos = 0;
5778
5779         while (x != positions.end()) {
5780           
5781                 /* deal with positons that are out of scope of present region bounds */
5782                 if (*x <= 0 || *x > r->length()){
5783                         ++x;
5784                         continue;
5785                 }
5786
5787                 /* file start = original start + how far we from the initial position ?
5788                  */
5789
5790                 framepos_t file_start = r->start() + pos;
5791
5792                 /* length = next position - current position
5793                  */
5794
5795                 framepos_t len = (*x) - pos;
5796                 
5797                 /* XXX we do we really want to allow even single-sample regions?
5798                    shouldn't we have some kind of lower limit on region size?
5799                 */
5800
5801                 if (len <= 0) {
5802                         break;
5803                 }
5804
5805                 string new_name;
5806
5807                 if (RegionFactory::region_name (new_name, r->name())) {
5808                         break;
5809                 }
5810
5811                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5812
5813                 PropertyList plist; 
5814                 
5815                 plist.add (ARDOUR::Properties::start, file_start);
5816                 plist.add (ARDOUR::Properties::length, len);
5817                 plist.add (ARDOUR::Properties::name, new_name);
5818                 plist.add (ARDOUR::Properties::layer, 0);
5819
5820                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5821                 pl->add_region (nr, r->position() + pos);
5822
5823                 pos += len;
5824                 ++x;
5825         }
5826
5827         string new_name;
5828
5829         RegionFactory::region_name (new_name, r->name());
5830         
5831         /* Add the final region */
5832         PropertyList plist; 
5833                 
5834         plist.add (ARDOUR::Properties::start, r->start() + pos);
5835         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
5836         plist.add (ARDOUR::Properties::name, new_name);
5837         plist.add (ARDOUR::Properties::layer, 0);
5838
5839         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5840         pl->add_region (nr, r->position() + pos);
5841
5842         
5843         pl->thaw ();
5844
5845         _session->add_command (new StatefulDiffCommand (pl));
5846 }
5847
5848 void
5849 Editor::place_transient()
5850 {
5851         if (!_session) {
5852                 return;
5853         }
5854
5855         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5856
5857         if (rs.empty()) {
5858                 return;
5859         }
5860         
5861         framepos_t where = get_preferred_edit_position();
5862
5863         _session->begin_reversible_command (_("place transient"));
5864         
5865         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5866                 framepos_t position = (*r)->region()->position();
5867                 (*r)->region()->add_transient(where - position);
5868         }
5869         
5870         _session->commit_reversible_command ();
5871 }
5872
5873 void
5874 Editor::remove_transient(ArdourCanvas::Item* item)
5875 {
5876         if (!_session) {
5877                 return;
5878         }
5879
5880         ArdourCanvas::SimpleLine* _line = reinterpret_cast<ArdourCanvas::SimpleLine*> (item);
5881         assert (_line);
5882
5883         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
5884         _arv->remove_transient(_line->property_x1());
5885 }
5886
5887 void
5888 Editor::snap_regions_to_grid ()
5889 {
5890         RegionSelection rs = get_regions_from_selection_and_entered ();
5891
5892         if (!_session || rs.empty()) {
5893                 return;
5894         }
5895         
5896         _session->begin_reversible_command (_("snap regions to grid"));
5897         
5898         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5899                 framepos_t start_frame = (*r)->region()->first_frame ();
5900                 snap_to (start_frame);
5901                 (*r)->region()->set_position (start_frame, this);
5902         }
5903         
5904         _session->commit_reversible_command ();
5905 }
5906
5907 void
5908 Editor::close_region_gaps ()
5909 {       
5910         RegionSelection rs = get_regions_from_selection_and_entered ();
5911
5912         if (!_session || rs.empty()) {
5913                 return;
5914         }
5915
5916         Dialog dialog (_("Close Region Gaps"));
5917
5918         Table table (2, 3);
5919         table.set_spacings (12);
5920         table.set_border_width (12);
5921         Label* l = manage (new Label (_("Crossfade length")));
5922         l->set_alignment (0, 0.5);
5923         table.attach (*l, 0, 1, 0, 1);
5924         
5925         SpinButton spin_crossfade (1, 0);
5926         spin_crossfade.set_range (0, 15);
5927         spin_crossfade.set_increments (1, 1);
5928         spin_crossfade.set_value (3);
5929         table.attach (spin_crossfade, 1, 2, 0, 1);
5930
5931         table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
5932
5933         l = manage (new Label (_("Pull-back length")));
5934         l->set_alignment (0, 0.5);
5935         table.attach (*l, 0, 1, 1, 2);
5936         
5937         SpinButton spin_pullback (1, 0);
5938         spin_pullback.set_range (0, 15);
5939         spin_pullback.set_increments (1, 1);
5940         spin_pullback.set_value (5);
5941         table.attach (spin_pullback, 1, 2, 1, 2);
5942
5943         table.attach (*manage (new Label (_("ms"))), 2, 3, 1, 2);
5944         
5945         dialog.get_vbox()->pack_start (table);
5946         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
5947         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
5948         dialog.show_all ();
5949
5950         if (dialog.run () == RESPONSE_CANCEL) {
5951                 return;
5952         }
5953
5954         framepos_t crossfade_len = spin_crossfade.get_value(); 
5955         framepos_t pull_back_frames = spin_pullback.get_value();
5956
5957         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
5958         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
5959
5960         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
5961         
5962         _session->begin_reversible_command (_("close region gaps"));
5963                 
5964         int idx = 0;
5965         boost::shared_ptr<Region> last_region;
5966         
5967         rs.sort_by_position_and_track();
5968         
5969         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5970
5971                 framepos_t position = (*r)->region()->position();
5972           
5973                 if (idx == 0 || position < last_region->position()){
5974                         last_region = (*r)->region();
5975                         idx++;
5976                         continue;
5977                 }
5978                 
5979                 (*r)->region()->trim_front( (position - pull_back_frames), this );
5980                 last_region->trim_end( (position - pull_back_frames + crossfade_len), this );
5981                 
5982                 last_region = (*r)->region();
5983                 
5984                 idx++;
5985         }
5986         
5987         _session->commit_reversible_command ();
5988 }
5989
5990 void
5991 Editor::tab_to_transient (bool forward)
5992 {
5993         AnalysisFeatureList positions;
5994
5995         RegionSelection rs = get_regions_from_selection_and_entered ();
5996
5997         if (!_session) {
5998                 return;
5999         }
6000
6001         framepos_t pos = _session->audible_frame ();
6002
6003         if (!selection->tracks.empty()) {
6004
6005                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
6006
6007                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
6008
6009                         if (rtv) {
6010                                 boost::shared_ptr<Track> tr = rtv->track();
6011                                 if (tr) {
6012                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
6013                                         if (pl) {
6014                                                 framepos_t result = pl->find_next_transient (pos, forward ? 1 : -1);
6015
6016                                                 if (result >= 0) {
6017                                                         positions.push_back (result);
6018                                                 }
6019                                         }
6020                                 }
6021                         }
6022                 }
6023
6024         } else {
6025
6026                 if (rs.empty()) {
6027                         return;
6028                 }
6029
6030                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6031                         (*r)->region()->get_transients (positions);
6032                 }
6033         }
6034
6035         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
6036
6037         if (forward) {
6038                 AnalysisFeatureList::iterator x;
6039
6040                 for (x = positions.begin(); x != positions.end(); ++x) {
6041                         if ((*x) > pos) {
6042                                 break;
6043                         }
6044                 }
6045
6046                 if (x != positions.end ()) {
6047                         _session->request_locate (*x);
6048                 }
6049
6050         } else {
6051                 AnalysisFeatureList::reverse_iterator x;
6052
6053                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6054                         if ((*x) < pos) {
6055                                 break;
6056                         }
6057                 }
6058
6059                 if (x != positions.rend ()) {
6060                         _session->request_locate (*x);
6061                 }
6062         }
6063 }
6064
6065 void
6066 Editor::playhead_forward_to_grid ()
6067 {
6068         if (!_session) return;
6069         framepos_t pos = playhead_cursor->current_frame;
6070         if (pos < max_framepos - 1) {
6071                 pos += 2;
6072                 snap_to_internal (pos, 1, false);
6073                 _session->request_locate (pos);
6074         }
6075 }
6076
6077
6078 void
6079 Editor::playhead_backward_to_grid ()
6080 {
6081         if (!_session) return;
6082         framepos_t pos = playhead_cursor->current_frame;
6083         if (pos > 2) {
6084                 pos -= 2;
6085                 snap_to_internal (pos, -1, false);
6086                 _session->request_locate (pos);
6087         }
6088 }
6089
6090 void
6091 Editor::set_track_height (Height h)
6092 {
6093         TrackSelection& ts (selection->tracks);
6094
6095         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6096                 (*x)->set_height (h);
6097         }
6098 }
6099
6100 void
6101 Editor::toggle_tracks_active ()
6102 {
6103         TrackSelection& ts (selection->tracks);
6104         bool first = true;
6105         bool target = false;
6106
6107         if (ts.empty()) {
6108                 return;
6109         }
6110
6111         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6112                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6113
6114                 if (rtv) {
6115                         if (first) {
6116                                 target = !rtv->_route->active();
6117                                 first = false;
6118                         }
6119                         rtv->_route->set_active (target);
6120                 }
6121         }
6122 }
6123
6124 void
6125 Editor::remove_tracks ()
6126 {
6127         TrackSelection& ts (selection->tracks);
6128
6129         if (ts.empty()) {
6130                 return;
6131         }
6132
6133         vector<string> choices;
6134         string prompt;
6135         int ntracks = 0;
6136         int nbusses = 0;
6137         const char* trackstr;
6138         const char* busstr;
6139         vector<boost::shared_ptr<Route> > routes;
6140         bool special_bus = false;
6141
6142         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6143                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6144                 if (rtv) {
6145                         if (rtv->is_track()) {
6146                                 ntracks++;
6147                         } else {
6148                                 nbusses++;
6149                         }
6150                 }
6151                 routes.push_back (rtv->_route);
6152
6153                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6154                         special_bus = true;
6155                 }
6156         }
6157
6158         if (special_bus && !Config->get_allow_special_bus_removal()) {
6159                 MessageDialog msg (_("That would be bad news ...."),
6160                                    false,
6161                                    Gtk::MESSAGE_INFO,
6162                                    Gtk::BUTTONS_OK);
6163                 msg.set_secondary_text (string_compose (_(
6164                                                                 "Removing the master or monitor bus is such a bad idea\n\
6165 that %1 is not going to allow it.\n\
6166 \n\
6167 If you really want to do this sort of thing\n\
6168 edit your ardour.rc file to set the\n\
6169 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6170
6171                 msg.present ();
6172                 msg.run ();
6173                 return;
6174         }
6175                 
6176         if (ntracks + nbusses == 0) {
6177                 return;
6178         }
6179
6180         if (ntracks > 1) {
6181                 trackstr = _("tracks");
6182         } else {
6183                 trackstr = _("track");
6184         }
6185
6186         if (nbusses > 1) {
6187                 busstr = _("busses");
6188         } else {
6189                 busstr = _("bus");
6190         }
6191
6192         if (ntracks) {
6193                 if (nbusses) {
6194                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6195                                                     "(You may also lose the playlists associated with the %2)\n\n"
6196                                                     "This action cannot be undone, and the session file will be overwritten!"),
6197                                                   ntracks, trackstr, nbusses, busstr);
6198                 } else {
6199                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6200                                                     "(You may also lose the playlists associated with the %2)\n\n"
6201                                                     "This action cannot be undone, and the session file will be overwritten!"),
6202                                                   ntracks, trackstr);
6203                 }
6204         } else if (nbusses) {
6205                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6206                                             "This action cannot be undon, and the session file will be overwritten"),
6207                                           nbusses, busstr);
6208         }
6209
6210         choices.push_back (_("No, do nothing."));
6211         if (ntracks + nbusses > 1) {
6212                 choices.push_back (_("Yes, remove them."));
6213         } else {
6214                 choices.push_back (_("Yes, remove it."));
6215         }
6216
6217         string title;
6218         if (ntracks) {
6219                 title = string_compose (_("Remove %1"), trackstr);
6220         } else {
6221                 title = string_compose (_("Remove %1"), busstr);
6222         }
6223
6224         Choice prompter (title, prompt, choices);
6225
6226         if (prompter.run () != 1) {
6227                 return;
6228         }
6229
6230         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6231                 _session->remove_route (*x);
6232         }
6233 }
6234
6235 void
6236 Editor::do_insert_time ()
6237 {
6238         if (selection->tracks.empty()) {
6239                 return;
6240         }
6241
6242         InsertTimeDialog d (*this);
6243         int response = d.run ();
6244
6245         if (response != RESPONSE_OK) {
6246                 return;
6247         }
6248
6249         if (d.distance() == 0) {
6250                 return;
6251         }
6252
6253         InsertTimeOption opt = d.intersected_region_action ();
6254
6255         insert_time (
6256                 get_preferred_edit_position(),
6257                 d.distance(),
6258                 opt,
6259                 d.move_glued(),
6260                 d.move_markers(),
6261                 d.move_glued_markers(),
6262                 d.move_locked_markers(),
6263                 d.move_tempos()
6264                 );
6265 }
6266
6267 void
6268 Editor::insert_time (framepos_t pos, framecnt_t frames, InsertTimeOption opt,
6269                      bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too)
6270 {
6271         bool commit = false;
6272
6273         if (Config->get_edit_mode() == Lock) {
6274                 return;
6275         }
6276
6277         begin_reversible_command (_("insert time"));
6278
6279         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6280                 /* regions */
6281                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6282
6283                 if (pl) {
6284
6285                         pl->clear_changes ();
6286                         pl->clear_owned_changes ();
6287
6288                         if (opt == SplitIntersected) {
6289                                 pl->split (pos);
6290                         }
6291
6292                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6293
6294                         vector<Command*> cmds;
6295                         pl->rdiff (cmds);
6296                         _session->add_commands (cmds);
6297                         
6298                         _session->add_command (new StatefulDiffCommand (pl));
6299                         commit = true;
6300                 }
6301
6302                 /* automation */
6303                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6304                 if (rtav) {
6305                         rtav->route ()->shift (pos, frames);
6306                         commit = true;
6307                 }
6308         }
6309
6310         /* markers */
6311         if (markers_too) {
6312                 bool moved = false;
6313                 XMLNode& before (_session->locations()->get_state());
6314                 Locations::LocationList copy (_session->locations()->list());
6315
6316                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6317
6318                         Locations::LocationList::const_iterator tmp;
6319
6320                         bool const was_locked = (*i)->locked ();
6321                         if (locked_markers_too) {
6322                                 (*i)->unlock ();
6323                         }
6324
6325                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6326
6327                                 if ((*i)->start() >= pos) {
6328                                         (*i)->set_start ((*i)->start() + frames);
6329                                         if (!(*i)->is_mark()) {
6330                                                 (*i)->set_end ((*i)->end() + frames);
6331                                         }
6332                                         moved = true;
6333                                 }
6334                                 
6335                         }
6336
6337                         if (was_locked) {
6338                                 (*i)->lock ();
6339                         }
6340                 }
6341
6342                 if (moved) {
6343                         XMLNode& after (_session->locations()->get_state());
6344                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6345                 }
6346         }
6347
6348         if (tempo_too) {
6349                 _session->tempo_map().insert_time (pos, frames);
6350         }
6351
6352         if (commit) {
6353                 commit_reversible_command ();
6354         }
6355 }
6356
6357 void
6358 Editor::fit_selected_tracks ()
6359 {
6360         fit_tracks (selection->tracks);
6361 }
6362
6363 void
6364 Editor::fit_tracks (TrackViewList & tracks)
6365 {
6366         if (tracks.empty()) {
6367                 return;
6368         }
6369
6370         uint32_t child_heights = 0;
6371
6372         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6373
6374                 if (!(*t)->marked_for_display()) {
6375                         continue;
6376                 }
6377
6378                 child_heights += (*t)->effective_height() - (*t)->current_height();
6379         }
6380
6381         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6382         double first_y_pos = DBL_MAX;
6383
6384         if (h < TimeAxisView::preset_height (HeightSmall)) {
6385                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6386                 /* too small to be displayed */
6387                 return;
6388         }
6389
6390         undo_visual_stack.push_back (current_visual_state());
6391
6392         /* build a list of all tracks, including children */
6393
6394         TrackViewList all;
6395         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6396                 all.push_back (*i);
6397                 TimeAxisView::Children c = (*i)->get_child_list ();
6398                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6399                         all.push_back (j->get());
6400                 }
6401         }
6402
6403         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6404
6405         bool prev_was_selected = false;
6406         bool is_selected = tracks.contains (all.front());
6407         bool next_is_selected;
6408
6409         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6410
6411                 TrackViewList::iterator next;
6412
6413                 next = t;
6414                 ++next;
6415
6416                 if (next != all.end()) {
6417                         next_is_selected = tracks.contains (*next);
6418                 } else {
6419                         next_is_selected = false;
6420                 }
6421
6422                 if (is_selected) {
6423                         (*t)->set_height (h);
6424                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6425                 } else {
6426                         if (prev_was_selected && next_is_selected) {
6427                                 hide_track_in_display (*t);
6428                         }
6429                 }
6430
6431                 prev_was_selected = is_selected;
6432                 is_selected = next_is_selected;
6433         }
6434
6435         /*
6436            set the controls_layout height now, because waiting for its size
6437            request signal handler will cause the vertical adjustment setting to fail
6438         */
6439
6440         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6441         vertical_adjustment.set_value (first_y_pos);
6442
6443         redo_visual_stack.push_back (current_visual_state());
6444 }
6445
6446 void
6447 Editor::save_visual_state (uint32_t n)
6448 {
6449         while (visual_states.size() <= n) {
6450                 visual_states.push_back (0);
6451         }
6452
6453         delete visual_states[n];
6454
6455         visual_states[n] = current_visual_state (true);
6456         gdk_beep ();
6457 }
6458
6459 void
6460 Editor::goto_visual_state (uint32_t n)
6461 {
6462         if (visual_states.size() <= n) {
6463                 return;
6464         }
6465
6466         if (visual_states[n] == 0) {
6467                 return;
6468         }
6469
6470         use_visual_state (*visual_states[n]);
6471 }
6472
6473 void
6474 Editor::start_visual_state_op (uint32_t n)
6475 {
6476         if (visual_state_op_connection.empty()) {
6477                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6478         }
6479 }
6480
6481 void
6482 Editor::cancel_visual_state_op (uint32_t n)
6483 {
6484         if (!visual_state_op_connection.empty()) {
6485                 visual_state_op_connection.disconnect();
6486                 goto_visual_state (n);
6487         }  else {
6488                 //we land here if called from the menu OR if end_visual_state_op has been called
6489                 //so check if we are already in visual state n
6490                 // XXX not yet checking it at all, but redoing does not hurt
6491                 goto_visual_state (n);
6492         }
6493 }
6494
6495 bool
6496 Editor::end_visual_state_op (uint32_t n)
6497 {
6498         visual_state_op_connection.disconnect();
6499         save_visual_state (n);
6500
6501         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6502         char buf[32];
6503         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6504         pup->set_text (buf);
6505         pup->touch();
6506
6507         return false; // do not call again
6508 }
6509
6510 void
6511 Editor::toggle_region_mute ()
6512 {
6513         if (_ignore_region_action) {
6514                 return;
6515         }
6516         
6517         RegionSelection rs = get_regions_from_selection_and_entered ();
6518
6519         if (rs.empty ()) {
6520                 return;
6521         }
6522
6523         if (rs.size() > 1) {
6524                 begin_reversible_command (_("mute regions"));
6525         } else {
6526                 begin_reversible_command (_("mute region"));
6527         }
6528         
6529         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
6530                 
6531                 (*i)->region()->playlist()->clear_changes ();
6532                 (*i)->region()->set_muted (!(*i)->region()->muted ());
6533                 _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
6534                 
6535         }
6536         
6537         commit_reversible_command ();
6538 }
6539