77b2f40bcc5aa33e818ebac642f112aad083c5a7
[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 fraction = gain_to_slider_position (arv->audio_region()->scale_amplitude ());
4522
4523                 if (up) {
4524                         fraction += 0.05;
4525                         fraction = min (fraction, 1.0);
4526                 } else {
4527                         fraction -= 0.05;
4528                         fraction = max (fraction, 0.0);
4529                 }
4530
4531                 if (!up && fraction <= 0) {
4532                         continue;
4533                 }
4534
4535                 fraction = slider_position_to_gain (fraction);
4536
4537                 if (up && fraction >= 2.0) {
4538                         continue;
4539                 }
4540
4541                 arv->audio_region()->set_scale_amplitude (fraction);
4542                 _session->add_command (new StatefulDiffCommand (arv->region()));
4543         }
4544
4545         commit_reversible_command ();
4546 }
4547
4548
4549 void
4550 Editor::reverse_region ()
4551 {
4552         if (!_session) {
4553                 return;
4554         }
4555
4556         Reverse rev (*_session);
4557         apply_filter (rev, _("reverse regions"));
4558 }
4559
4560 void
4561 Editor::strip_region_silence ()
4562 {
4563         if (!_session) {
4564                 return;
4565         }
4566
4567         RegionSelection rs = get_regions_from_selection_and_entered ();
4568
4569         if (rs.empty()) {
4570                 return;
4571         }
4572
4573         std::list<RegionView*> audio_only;
4574
4575         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4576                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4577                 if (arv) {
4578                         audio_only.push_back (arv);
4579                 }
4580         }
4581
4582         StripSilenceDialog d (_session, audio_only);
4583         int const r = d.run ();
4584
4585         d.drop_rects ();
4586         
4587         if (r == Gtk::RESPONSE_OK) {
4588                 ARDOUR::AudioIntervalMap silences;
4589                 d.silences (silences);
4590                 StripSilence s (*_session, silences, d.fade_length());
4591                 apply_filter (s, _("strip silence"), &d);
4592         } 
4593 }
4594
4595 Command*
4596 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4597 {
4598         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4599         mrv.selection_as_notelist (selected, true);
4600
4601         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4602         v.push_back (selected);
4603
4604         return op (mrv.midi_region()->model(), v);
4605 }
4606
4607 void
4608 Editor::apply_midi_note_edit_op (MidiOperator& op)
4609 {
4610         Command* cmd;
4611
4612         RegionSelection rs = get_regions_from_selection_and_entered ();
4613
4614         if (rs.empty()) {
4615                 return;
4616         }
4617
4618         begin_reversible_command (op.name ());
4619
4620         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4621                 RegionSelection::iterator tmp = r;
4622                 ++tmp;
4623
4624                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4625
4626                 if (mrv) {
4627                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4628                         if (cmd) {
4629                                 (*cmd)();
4630                                 _session->add_command (cmd);
4631                         }
4632                 }
4633
4634                 r = tmp;
4635         }
4636
4637         commit_reversible_command ();
4638 }
4639
4640 void
4641 Editor::fork_region ()
4642 {
4643         RegionSelection rs = get_regions_from_selection_and_entered ();
4644
4645         if (rs.empty()) {
4646                 return;
4647         }
4648
4649         begin_reversible_command (_("Fork Region(s)"));
4650
4651         set_canvas_cursor (_cursors->wait);
4652         gdk_flush ();
4653
4654         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4655                 RegionSelection::iterator tmp = r;
4656                 ++tmp;
4657
4658                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4659
4660                 if (mrv) {
4661                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4662                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4663                         
4664                         playlist->clear_changes ();
4665                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4666                         _session->add_command(new StatefulDiffCommand (playlist));
4667                 }
4668
4669                 r = tmp;
4670         }
4671
4672         commit_reversible_command ();
4673
4674         set_canvas_cursor (current_canvas_cursor);
4675 }
4676
4677 void
4678 Editor::quantize_region ()
4679 {
4680         int selected_midi_region_cnt = 0;
4681
4682         if (!_session) {
4683                 return;
4684         }
4685
4686         RegionSelection rs = get_regions_from_selection_and_entered ();
4687
4688         if (rs.empty()) {
4689                 return;
4690         }
4691
4692         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4693                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4694                 if (mrv) {
4695                         selected_midi_region_cnt++;
4696                 }
4697         }
4698
4699         if (selected_midi_region_cnt == 0) {
4700                 return;
4701         }
4702
4703         QuantizeDialog* qd = new QuantizeDialog (*this);
4704
4705         qd->present ();
4706         const int r = qd->run ();
4707         qd->hide ();
4708
4709         if (r == Gtk::RESPONSE_OK) {
4710                 Quantize quant (*_session, Plain,
4711                                 qd->snap_start(), qd->snap_end(),
4712                                 qd->start_grid_size(), qd->end_grid_size(),
4713                                 qd->strength(), qd->swing(), qd->threshold());
4714
4715                 apply_midi_note_edit_op (quant);
4716         }
4717 }
4718
4719 void
4720 Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress)
4721 {
4722         RegionSelection rs = get_regions_from_selection_and_entered ();
4723
4724         if (rs.empty()) {
4725                 return;
4726         }
4727
4728         begin_reversible_command (command);
4729
4730         set_canvas_cursor (_cursors->wait);
4731         gdk_flush ();
4732
4733         int n = 0;
4734         int const N = rs.size ();
4735         
4736         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4737                 RegionSelection::iterator tmp = r;
4738                 ++tmp;
4739
4740                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4741                 if (arv) {
4742                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4743
4744                         if (progress) {
4745                                 progress->descend (1.0 / N);
4746                         }
4747
4748                         if (arv->audio_region()->apply (filter, progress) == 0) {
4749
4750                                 playlist->clear_changes ();
4751
4752                                 if (filter.results.empty ()) {
4753
4754                                         /* no regions returned; remove the old one */
4755                                         playlist->remove_region (arv->region ());
4756
4757                                 } else {
4758
4759                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4760
4761                                         /* first region replaces the old one */
4762                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4763                                         ++res;
4764
4765                                         /* add the rest */
4766                                         while (res != filter.results.end()) {
4767                                                 playlist->add_region (*res, (*res)->position());
4768                                                 ++res;
4769                                         }
4770
4771                                 }
4772
4773                                 _session->add_command(new StatefulDiffCommand (playlist));
4774                         } else {
4775                                 goto out;
4776                         }
4777
4778                         if (progress) {
4779                                 progress->ascend ();
4780                         }
4781                 }
4782
4783                 r = tmp;
4784                 ++n;
4785         }
4786
4787         commit_reversible_command ();
4788
4789   out:
4790         set_canvas_cursor (current_canvas_cursor);
4791 }
4792
4793 void
4794 Editor::external_edit_region ()
4795 {
4796         /* more to come */
4797 }
4798
4799 void
4800 Editor::brush (framepos_t pos)
4801 {
4802         snap_to (pos);
4803
4804         RegionSelection rs = get_regions_from_selection_and_entered ();
4805
4806         if (rs.empty()) {
4807                 return;
4808         }
4809
4810         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4811                 mouse_brush_insert_region ((*i), pos);
4812         }
4813 }
4814
4815 void
4816 Editor::reset_region_gain_envelopes ()
4817 {
4818         RegionSelection rs = get_regions_from_selection_and_entered ();
4819
4820         if (!_session || rs.empty()) {
4821                 return;
4822         }
4823
4824         _session->begin_reversible_command (_("reset region gain"));
4825
4826         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4827                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4828                 if (arv) {
4829                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4830                         XMLNode& before (alist->get_state());
4831
4832                         arv->audio_region()->set_default_envelope ();
4833                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4834                 }
4835         }
4836
4837         _session->commit_reversible_command ();
4838 }
4839
4840 void
4841 Editor::toggle_gain_envelope_visibility ()
4842 {
4843         if (_ignore_region_action) {
4844                 return;
4845         }
4846         
4847         RegionSelection rs = get_regions_from_selection_and_entered ();
4848
4849         if (!_session || rs.empty()) {
4850                 return;
4851         }
4852
4853         _session->begin_reversible_command (_("region gain envelope visible"));
4854
4855         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4856                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4857                 if (arv) {
4858                         arv->region()->clear_changes ();
4859                         arv->set_envelope_visible (!arv->envelope_visible());
4860                         _session->add_command (new StatefulDiffCommand (arv->region()));
4861                 }
4862         }
4863
4864         _session->commit_reversible_command ();
4865 }
4866
4867 void
4868 Editor::toggle_gain_envelope_active ()
4869 {
4870         if (_ignore_region_action) {
4871                 return;
4872         }
4873         
4874         RegionSelection rs = get_regions_from_selection_and_entered ();
4875
4876         if (!_session || rs.empty()) {
4877                 return;
4878         }
4879
4880         _session->begin_reversible_command (_("region gain envelope active"));
4881
4882         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4883                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4884                 if (arv) {
4885                         arv->region()->clear_changes ();
4886                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4887                         _session->add_command (new StatefulDiffCommand (arv->region()));
4888                 }
4889         }
4890
4891         _session->commit_reversible_command ();
4892 }
4893
4894 void
4895 Editor::toggle_region_lock ()
4896 {
4897         if (_ignore_region_action) {
4898                 return;
4899         }
4900
4901         RegionSelection rs = get_regions_from_selection_and_entered ();
4902
4903         if (!_session || rs.empty()) {
4904                 return;
4905         }
4906
4907         _session->begin_reversible_command (_("toggle region lock"));
4908
4909         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4910                 (*i)->region()->clear_changes ();
4911                 (*i)->region()->set_locked (!(*i)->region()->locked());
4912                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4913         }
4914
4915         _session->commit_reversible_command ();
4916 }
4917
4918 void
4919 Editor::toggle_region_lock_style ()
4920 {
4921         if (_ignore_region_action) {
4922                 return;
4923         }
4924         
4925         RegionSelection rs = get_regions_from_selection_and_entered ();
4926
4927         if (!_session || rs.empty()) {
4928                 return;
4929         }
4930
4931         _session->begin_reversible_command (_("region lock style"));
4932
4933         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4934                 (*i)->region()->clear_changes ();
4935                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
4936                 (*i)->region()->set_position_lock_style (ns);
4937                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4938         }
4939
4940         _session->commit_reversible_command ();
4941 }
4942
4943 void
4944 Editor::toggle_opaque_region ()
4945 {
4946         if (_ignore_region_action) {
4947                 return;
4948         }
4949         
4950         RegionSelection rs = get_regions_from_selection_and_entered ();
4951
4952         if (!_session || rs.empty()) {
4953                 return;
4954         }
4955
4956         _session->begin_reversible_command (_("change region opacity"));
4957
4958         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4959                 (*i)->region()->clear_changes ();
4960                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4961                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4962         }
4963
4964         _session->commit_reversible_command ();
4965 }
4966
4967 void
4968 Editor::toggle_record_enable ()
4969 {
4970         bool new_state = false;
4971         bool first = true;
4972         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4973                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4974                 if (!rtav)
4975                         continue;
4976                 if (!rtav->is_track())
4977                         continue;
4978
4979                 if (first) {
4980                         new_state = !rtav->track()->record_enabled();
4981                         first = false;
4982                 }
4983
4984                 rtav->track()->set_record_enabled (new_state, this);
4985         }
4986 }
4987
4988
4989 void
4990 Editor::set_fade_length (bool in)
4991 {
4992         RegionSelection rs = get_regions_from_selection_and_entered ();
4993
4994         if (rs.empty()) {
4995                 return;
4996         }
4997
4998         /* we need a region to measure the offset from the start */
4999
5000         RegionView* rv = rs.front ();
5001
5002         framepos_t pos = get_preferred_edit_position();
5003         framepos_t len;
5004         char const * cmd;
5005
5006         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
5007                 /* edit point is outside the relevant region */
5008                 return;
5009         }
5010
5011         if (in) {
5012                 if (pos <= rv->region()->position()) {
5013                         /* can't do it */
5014                         return;
5015                 }
5016                 len = pos - rv->region()->position();
5017                 cmd = _("set fade in length");
5018         } else {
5019                 if (pos >= rv->region()->last_frame()) {
5020                         /* can't do it */
5021                         return;
5022                 }
5023                 len = rv->region()->last_frame() - pos;
5024                 cmd = _("set fade out length");
5025         }
5026
5027         begin_reversible_command (cmd);
5028
5029         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5030                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5031
5032                 if (!tmp) {
5033                         return;
5034                 }
5035
5036                 boost::shared_ptr<AutomationList> alist;
5037                 if (in) {
5038                         alist = tmp->audio_region()->fade_in();
5039                 } else {
5040                         alist = tmp->audio_region()->fade_out();
5041                 }
5042
5043                 XMLNode &before = alist->get_state();
5044
5045                 if (in) {
5046                         tmp->audio_region()->set_fade_in_length (len);
5047                         tmp->audio_region()->set_fade_in_active (true);
5048                 } else {
5049                         tmp->audio_region()->set_fade_out_length (len);
5050                         tmp->audio_region()->set_fade_out_active (true);
5051                 }
5052
5053                 XMLNode &after = alist->get_state();
5054                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
5055         }
5056
5057         commit_reversible_command ();
5058 }
5059
5060 void
5061 Editor::set_fade_in_shape (FadeShape shape)
5062 {
5063         RegionSelection rs = get_regions_from_selection_and_entered ();
5064
5065         if (rs.empty()) {
5066                 return;
5067         }
5068
5069         begin_reversible_command (_("set fade in shape"));
5070
5071         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5072                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5073
5074                 if (!tmp) {
5075                         return;
5076                 }
5077
5078                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5079                 XMLNode &before = alist->get_state();
5080
5081                 tmp->audio_region()->set_fade_in_shape (shape);
5082
5083                 XMLNode &after = alist->get_state();
5084                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5085         }
5086
5087         commit_reversible_command ();
5088
5089 }
5090
5091 void
5092 Editor::set_fade_out_shape (FadeShape shape)
5093 {
5094         RegionSelection rs = get_regions_from_selection_and_entered ();
5095
5096         if (rs.empty()) {
5097                 return;
5098         }
5099
5100         begin_reversible_command (_("set fade out shape"));
5101
5102         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5103                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5104
5105                 if (!tmp) {
5106                         return;
5107                 }
5108
5109                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5110                 XMLNode &before = alist->get_state();
5111
5112                 tmp->audio_region()->set_fade_out_shape (shape);
5113
5114                 XMLNode &after = alist->get_state();
5115                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5116         }
5117
5118         commit_reversible_command ();
5119 }
5120
5121 void
5122 Editor::set_fade_in_active (bool yn)
5123 {
5124         RegionSelection rs = get_regions_from_selection_and_entered ();
5125
5126         if (rs.empty()) {
5127                 return;
5128         }
5129
5130         begin_reversible_command (_("set fade in active"));
5131
5132         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5133                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5134
5135                 if (!tmp) {
5136                         return;
5137                 }
5138
5139
5140                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5141                 
5142                 ar->clear_changes ();
5143                 ar->set_fade_in_active (yn);
5144                 _session->add_command (new StatefulDiffCommand (ar));
5145         }
5146
5147         commit_reversible_command ();
5148 }
5149
5150 void
5151 Editor::set_fade_out_active (bool yn)
5152 {
5153         RegionSelection rs = get_regions_from_selection_and_entered ();
5154
5155         if (rs.empty()) {
5156                 return;
5157         }
5158
5159         begin_reversible_command (_("set fade out active"));
5160
5161         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5162                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5163
5164                 if (!tmp) {
5165                         return;
5166                 }
5167
5168                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5169
5170                 ar->clear_changes ();
5171                 ar->set_fade_out_active (yn);
5172                 _session->add_command(new StatefulDiffCommand (ar));
5173         }
5174
5175         commit_reversible_command ();
5176 }
5177
5178 void
5179 Editor::toggle_region_fades (int dir)
5180 {
5181         boost::shared_ptr<AudioRegion> ar;
5182         bool yn;
5183
5184         RegionSelection rs = get_regions_from_selection_and_entered ();
5185
5186         if (rs.empty()) {
5187                 return;
5188         }
5189
5190         RegionSelection::iterator i;    
5191         for (i = rs.begin(); i != rs.end(); ++i) {
5192                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5193                         if (dir == -1) {
5194                                 yn = ar->fade_out_active ();
5195                         } else {
5196                                 yn = ar->fade_in_active ();
5197                         }
5198                         break;
5199                 }
5200         }
5201
5202         if (i == rs.end()) {
5203                 return;
5204         }
5205
5206         /* XXX should this undo-able? */
5207
5208         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5209                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5210                         continue;
5211                 }
5212                 if (dir == 1 || dir == 0) {
5213                         ar->set_fade_in_active (!yn);
5214                 }
5215
5216                 if (dir == -1 || dir == 0) {
5217                         ar->set_fade_out_active (!yn);
5218                 }
5219         }
5220 }
5221
5222
5223 /** Update region fade visibility after its configuration has been changed */
5224 void
5225 Editor::update_region_fade_visibility ()
5226 {
5227         bool _fade_visibility = _session->config.get_show_region_fades ();
5228
5229         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5230                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5231                 if (v) {
5232                         if (_fade_visibility) {
5233                                 v->audio_view()->show_all_fades ();
5234                         } else {
5235                                 v->audio_view()->hide_all_fades ();
5236                         }
5237                 }
5238         }
5239 }
5240
5241 /** Update crossfade visibility after its configuration has been changed */
5242 void
5243 Editor::update_xfade_visibility ()
5244 {
5245         _xfade_visibility = _session->config.get_xfades_visible ();
5246
5247         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5248                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5249                 if (v) {
5250                         if (_xfade_visibility) {
5251                                 v->show_all_xfades ();
5252                         } else {
5253                                 v->hide_all_xfades ();
5254                         }
5255                 }
5256         }
5257 }
5258
5259 void
5260 Editor::set_edit_point ()
5261 {
5262         framepos_t where;
5263         bool ignored;
5264
5265         if (!mouse_frame (where, ignored)) {
5266                 return;
5267         }
5268
5269         snap_to (where);
5270
5271         if (selection->markers.empty()) {
5272
5273                 mouse_add_new_marker (where);
5274
5275         } else {
5276                 bool ignored;
5277
5278                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5279
5280                 if (loc) {
5281                         loc->move_to (where);
5282                 }
5283         }
5284 }
5285
5286 void
5287 Editor::set_playhead_cursor ()
5288 {
5289         if (entered_marker) {
5290                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5291         } else {
5292                 framepos_t where;
5293                 bool ignored;
5294
5295                 if (!mouse_frame (where, ignored)) {
5296                         return;
5297                 }
5298
5299                 snap_to (where);
5300
5301                 if (_session) {
5302                         _session->request_locate (where, _session->transport_rolling());
5303                 }
5304         }
5305 }
5306
5307 void
5308 Editor::split_region ()
5309 {
5310         if (((mouse_mode == MouseRange) || 
5311              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) && 
5312             !selection->time.empty()) {
5313                 separate_regions_between (selection->time);
5314                 return;
5315         } 
5316
5317         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5318
5319         framepos_t where = get_preferred_edit_position ();
5320
5321         if (rs.empty()) {
5322                 return;
5323         }
5324
5325         split_regions_at (where, rs);
5326 }
5327
5328 void
5329 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5330 {
5331         if (entered_track && mouse_mode == MouseObject) {
5332                 if (!selection->tracks.empty()) {
5333                         if (!selection->selected (entered_track)) {
5334                                 selection->add (entered_track);
5335                         }
5336                 } else {
5337                         /* there is no selection, but this operation requires/prefers selected objects */
5338
5339                         if (op_really_wants_one_track_if_none_are_selected) {
5340                                 selection->set (entered_track);
5341                         }
5342                 }
5343         }
5344 }
5345
5346 struct EditorOrderRouteSorter {
5347     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5348             /* use of ">" forces the correct sort order */
5349             return a->order_key ("editor") < b->order_key ("editor");
5350     }
5351 };
5352
5353 void
5354 Editor::select_next_route()
5355 {
5356         if (selection->tracks.empty()) {
5357                 selection->set (track_views.front());
5358                 return;
5359         }
5360
5361         TimeAxisView* current = selection->tracks.front();
5362
5363         RouteUI *rui;
5364         do {
5365                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5366                         if (*i == current) {
5367                                 ++i;
5368                                 if (i != track_views.end()) {
5369                                         current = (*i);
5370                                 } else {
5371                                         current = (*(track_views.begin()));
5372                                         //selection->set (*(track_views.begin()));
5373                                 }
5374                                 break;
5375                         }
5376                 }
5377                 rui = dynamic_cast<RouteUI *>(current);
5378         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5379
5380         selection->set(current);
5381
5382         ensure_track_visible(current);
5383 }
5384
5385 void
5386 Editor::select_prev_route()
5387 {
5388         if (selection->tracks.empty()) {
5389                 selection->set (track_views.front());
5390                 return;
5391         }
5392
5393         TimeAxisView* current = selection->tracks.front();
5394
5395         RouteUI *rui;
5396         do {
5397                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5398                         if (*i == current) {
5399                                 ++i;
5400                                 if (i != track_views.rend()) {
5401                                         current = (*i);
5402                                 } else {
5403                                         current = *(track_views.rbegin());
5404                                 }
5405                                 break;
5406                         }
5407                 }
5408                 rui = dynamic_cast<RouteUI *>(current);
5409         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5410
5411         selection->set (current);
5412
5413         ensure_track_visible(current);
5414 }
5415
5416 void
5417 Editor::ensure_track_visible(TimeAxisView *track)
5418 {
5419         if (track->hidden())
5420                 return;
5421
5422         double const current_view_min_y = vertical_adjustment.get_value();
5423         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5424
5425         double const track_min_y = track->y_position ();
5426         double const track_max_y = track->y_position () + track->effective_height ();
5427
5428         if (track_min_y >= current_view_min_y &&
5429             track_max_y <= current_view_max_y) {
5430                 return;
5431         }
5432
5433         double new_value;
5434
5435         if (track_min_y < current_view_min_y) {
5436                 // Track is above the current view
5437                 new_value = track_min_y;
5438         } else {
5439                 // Track is below the current view
5440                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5441         }
5442
5443         vertical_adjustment.set_value(new_value);
5444 }
5445
5446 void
5447 Editor::set_loop_from_selection (bool play)
5448 {
5449         if (_session == 0 || selection->time.empty()) {
5450                 return;
5451         }
5452
5453         framepos_t start = selection->time[clicked_selection].start;
5454         framepos_t end = selection->time[clicked_selection].end;
5455
5456         set_loop_range (start, end,  _("set loop range from selection"));
5457
5458         if (play) {
5459                 _session->request_play_loop (true);
5460                 _session->request_locate (start, true);
5461         }
5462 }
5463
5464 void
5465 Editor::set_loop_from_edit_range (bool play)
5466 {
5467         if (_session == 0) {
5468                 return;
5469         }
5470
5471         framepos_t start;
5472         framepos_t end;
5473
5474         if (!get_edit_op_range (start, end)) {
5475                 return;
5476         }
5477
5478         set_loop_range (start, end,  _("set loop range from edit range"));
5479
5480         if (play) {
5481                 _session->request_play_loop (true);
5482                 _session->request_locate (start, true);
5483         }
5484 }
5485
5486 void
5487 Editor::set_loop_from_region (bool play)
5488 {
5489         framepos_t start = max_framepos;
5490         framepos_t end = 0;
5491
5492         RegionSelection rs = get_regions_from_selection_and_entered ();
5493
5494         if (rs.empty()) {
5495                 return;
5496         }
5497
5498         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5499                 if ((*i)->region()->position() < start) {
5500                         start = (*i)->region()->position();
5501                 }
5502                 if ((*i)->region()->last_frame() + 1 > end) {
5503                         end = (*i)->region()->last_frame() + 1;
5504                 }
5505         }
5506
5507         set_loop_range (start, end, _("set loop range from region"));
5508
5509         if (play) {
5510                 _session->request_play_loop (true);
5511                 _session->request_locate (start, true);
5512         }
5513 }
5514
5515 void
5516 Editor::set_punch_from_selection ()
5517 {
5518         if (_session == 0 || selection->time.empty()) {
5519                 return;
5520         }
5521
5522         framepos_t start = selection->time[clicked_selection].start;
5523         framepos_t end = selection->time[clicked_selection].end;
5524
5525         set_punch_range (start, end,  _("set punch range from selection"));
5526 }
5527
5528 void
5529 Editor::set_punch_from_edit_range ()
5530 {
5531         if (_session == 0) {
5532                 return;
5533         }
5534
5535         framepos_t start;
5536         framepos_t end;
5537
5538         if (!get_edit_op_range (start, end)) {
5539                 return;
5540         }
5541
5542         set_punch_range (start, end,  _("set punch range from edit range"));
5543 }
5544
5545 void
5546 Editor::set_punch_from_region ()
5547 {
5548         framepos_t start = max_framepos;
5549         framepos_t end = 0;
5550
5551         RegionSelection rs = get_regions_from_selection_and_entered ();
5552
5553         if (rs.empty()) {
5554                 return;
5555         }
5556
5557         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5558                 if ((*i)->region()->position() < start) {
5559                         start = (*i)->region()->position();
5560                 }
5561                 if ((*i)->region()->last_frame() + 1 > end) {
5562                         end = (*i)->region()->last_frame() + 1;
5563                 }
5564         }
5565
5566         set_punch_range (start, end, _("set punch range from region"));
5567 }
5568
5569 void
5570 Editor::pitch_shift_region ()
5571 {
5572         RegionSelection rs = get_regions_from_selection_and_entered ();
5573
5574         if (rs.empty()) {
5575                 return;
5576         }
5577
5578         pitch_shift (rs, 1.2);
5579 }
5580
5581 void
5582 Editor::set_tempo_from_region ()
5583 {
5584         RegionSelection rs = get_regions_from_selection_and_entered ();
5585
5586         if (!_session || rs.empty()) {
5587                 return;
5588         }
5589
5590         RegionView* rv = rs.front();
5591
5592         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5593 }
5594
5595 void
5596 Editor::use_range_as_bar ()
5597 {
5598         framepos_t start, end;
5599         if (get_edit_op_range (start, end)) {
5600                 define_one_bar (start, end);
5601         }
5602 }
5603
5604 void
5605 Editor::define_one_bar (framepos_t start, framepos_t end)
5606 {
5607         framepos_t length = end - start;
5608
5609         const Meter& m (_session->tempo_map().meter_at (start));
5610
5611         /* length = 1 bar */
5612
5613         /* now we want frames per beat.
5614            we have frames per bar, and beats per bar, so ...
5615         */
5616
5617         double frames_per_beat = length / m.beats_per_bar();
5618
5619         /* beats per minute = */
5620
5621         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5622
5623         /* now decide whether to:
5624
5625             (a) set global tempo
5626             (b) add a new tempo marker
5627
5628         */
5629
5630         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5631
5632         bool do_global = false;
5633
5634         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5635
5636                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5637                    at the start, or create a new marker
5638                 */
5639
5640                 vector<string> options;
5641                 options.push_back (_("Cancel"));
5642                 options.push_back (_("Add new marker"));
5643                 options.push_back (_("Set global tempo"));
5644
5645                 Choice c (
5646                         _("Define one bar"),
5647                         _("Do you want to set the global tempo or add a new tempo marker?"),
5648                         options
5649                         );
5650                 
5651                 c.set_default_response (2);
5652
5653                 switch (c.run()) {
5654                 case 0:
5655                         return;
5656
5657                 case 2:
5658                         do_global = true;
5659                         break;
5660
5661                 default:
5662                         do_global = false;
5663                 }
5664
5665         } else {
5666
5667                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5668                    if the marker is at the region starter, change it, otherwise add
5669                    a new tempo marker
5670                 */
5671         }
5672
5673         begin_reversible_command (_("set tempo from region"));
5674         XMLNode& before (_session->tempo_map().get_state());
5675
5676         if (do_global) {
5677                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5678         } else if (t.frame() == start) {
5679                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5680         } else {
5681                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5682         }
5683
5684         XMLNode& after (_session->tempo_map().get_state());
5685
5686         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5687         commit_reversible_command ();
5688 }
5689
5690 void
5691 Editor::split_region_at_transients ()
5692 {
5693         AnalysisFeatureList positions;
5694
5695         RegionSelection rs = get_regions_from_selection_and_entered ();
5696
5697         if (!_session || rs.empty()) {
5698                 return;
5699         }
5700
5701         _session->begin_reversible_command (_("split regions"));
5702
5703         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5704
5705                 RegionSelection::iterator tmp;
5706
5707                 tmp = i;
5708                 ++tmp;
5709
5710                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5711
5712                 if (ar && (ar->get_transients (positions) == 0)) {
5713                         split_region_at_points ((*i)->region(), positions, true);
5714                         positions.clear ();
5715                 }
5716
5717                 i = tmp;
5718         }
5719
5720         _session->commit_reversible_command ();
5721
5722 }
5723
5724 void
5725 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5726 {
5727         bool use_rhythmic_rodent = false;
5728
5729         boost::shared_ptr<Playlist> pl = r->playlist();
5730
5731         if (!pl) {
5732                 return;
5733         }
5734
5735         if (positions.empty()) {
5736                 return;
5737         }
5738
5739
5740         if (positions.size() > 20) {
5741                 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);
5742                 MessageDialog msg (msgstr,
5743                                    false,
5744                                    Gtk::MESSAGE_INFO,
5745                                    Gtk::BUTTONS_OK_CANCEL);
5746
5747                 if (can_ferret) {
5748                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5749                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5750                 } else {
5751                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5752                 }
5753
5754                 msg.set_title (_("Excessive split?"));
5755                 msg.present ();
5756
5757                 int response = msg.run();
5758                 msg.hide ();
5759                 
5760                 switch (response) {
5761                 case RESPONSE_OK:
5762                         break;
5763                 case RESPONSE_APPLY:
5764                         use_rhythmic_rodent = true;
5765                         break;
5766                 default:
5767                         return;
5768                 }
5769         }
5770
5771         if (use_rhythmic_rodent) {
5772                 show_rhythm_ferret ();
5773                 return;
5774         }
5775
5776         AnalysisFeatureList::const_iterator x;
5777
5778         pl->clear_changes ();
5779
5780         x = positions.begin();
5781
5782         if (x == positions.end()) {
5783                 return;
5784         }
5785
5786         pl->freeze ();
5787         pl->remove_region (r);
5788
5789         framepos_t pos = 0;
5790
5791         while (x != positions.end()) {
5792           
5793                 /* deal with positons that are out of scope of present region bounds */
5794                 if (*x <= 0 || *x > r->length()){
5795                         ++x;
5796                         continue;
5797                 }
5798
5799                 /* file start = original start + how far we from the initial position ?
5800                  */
5801
5802                 framepos_t file_start = r->start() + pos;
5803
5804                 /* length = next position - current position
5805                  */
5806
5807                 framepos_t len = (*x) - pos;
5808                 
5809                 /* XXX we do we really want to allow even single-sample regions?
5810                    shouldn't we have some kind of lower limit on region size?
5811                 */
5812
5813                 if (len <= 0) {
5814                         break;
5815                 }
5816
5817                 string new_name;
5818
5819                 if (RegionFactory::region_name (new_name, r->name())) {
5820                         break;
5821                 }
5822
5823                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5824
5825                 PropertyList plist; 
5826                 
5827                 plist.add (ARDOUR::Properties::start, file_start);
5828                 plist.add (ARDOUR::Properties::length, len);
5829                 plist.add (ARDOUR::Properties::name, new_name);
5830                 plist.add (ARDOUR::Properties::layer, 0);
5831
5832                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5833                 pl->add_region (nr, r->position() + pos);
5834
5835                 pos += len;
5836                 ++x;
5837         }
5838
5839         string new_name;
5840
5841         RegionFactory::region_name (new_name, r->name());
5842         
5843         /* Add the final region */
5844         PropertyList plist; 
5845                 
5846         plist.add (ARDOUR::Properties::start, r->start() + pos);
5847         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
5848         plist.add (ARDOUR::Properties::name, new_name);
5849         plist.add (ARDOUR::Properties::layer, 0);
5850
5851         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5852         pl->add_region (nr, r->position() + pos);
5853
5854         
5855         pl->thaw ();
5856
5857         _session->add_command (new StatefulDiffCommand (pl));
5858 }
5859
5860 void
5861 Editor::place_transient()
5862 {
5863         if (!_session) {
5864                 return;
5865         }
5866
5867         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5868
5869         if (rs.empty()) {
5870                 return;
5871         }
5872         
5873         framepos_t where = get_preferred_edit_position();
5874
5875         _session->begin_reversible_command (_("place transient"));
5876         
5877         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5878                 framepos_t position = (*r)->region()->position();
5879                 (*r)->region()->add_transient(where - position);
5880         }
5881         
5882         _session->commit_reversible_command ();
5883 }
5884
5885 void
5886 Editor::remove_transient(ArdourCanvas::Item* item)
5887 {
5888         if (!_session) {
5889                 return;
5890         }
5891
5892         ArdourCanvas::SimpleLine* _line = reinterpret_cast<ArdourCanvas::SimpleLine*> (item);
5893         assert (_line);
5894
5895         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
5896         _arv->remove_transient(_line->property_x1());
5897 }
5898
5899 void
5900 Editor::snap_regions_to_grid ()
5901 {
5902         RegionSelection rs = get_regions_from_selection_and_entered ();
5903
5904         if (!_session || rs.empty()) {
5905                 return;
5906         }
5907         
5908         _session->begin_reversible_command (_("snap regions to grid"));
5909         
5910         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5911                 framepos_t start_frame = (*r)->region()->first_frame ();
5912                 snap_to (start_frame);
5913                 (*r)->region()->set_position (start_frame, this);
5914         }
5915         
5916         _session->commit_reversible_command ();
5917 }
5918
5919 void
5920 Editor::close_region_gaps ()
5921 {       
5922         RegionSelection rs = get_regions_from_selection_and_entered ();
5923
5924         if (!_session || rs.empty()) {
5925                 return;
5926         }
5927
5928         Dialog dialog (_("Close Region Gaps"));
5929
5930         Table table (2, 3);
5931         table.set_spacings (12);
5932         table.set_border_width (12);
5933         Label* l = manage (new Label (_("Crossfade length")));
5934         l->set_alignment (0, 0.5);
5935         table.attach (*l, 0, 1, 0, 1);
5936         
5937         SpinButton spin_crossfade (1, 0);
5938         spin_crossfade.set_range (0, 15);
5939         spin_crossfade.set_increments (1, 1);
5940         spin_crossfade.set_value (3);
5941         table.attach (spin_crossfade, 1, 2, 0, 1);
5942
5943         table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
5944
5945         l = manage (new Label (_("Pull-back length")));
5946         l->set_alignment (0, 0.5);
5947         table.attach (*l, 0, 1, 1, 2);
5948         
5949         SpinButton spin_pullback (1, 0);
5950         spin_pullback.set_range (0, 15);
5951         spin_pullback.set_increments (1, 1);
5952         spin_pullback.set_value (5);
5953         table.attach (spin_pullback, 1, 2, 1, 2);
5954
5955         table.attach (*manage (new Label (_("ms"))), 2, 3, 1, 2);
5956         
5957         dialog.get_vbox()->pack_start (table);
5958         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
5959         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
5960         dialog.show_all ();
5961
5962         if (dialog.run () == RESPONSE_CANCEL) {
5963                 return;
5964         }
5965
5966         framepos_t crossfade_len = spin_crossfade.get_value(); 
5967         framepos_t pull_back_frames = spin_pullback.get_value();
5968
5969         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
5970         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
5971
5972         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
5973         
5974         _session->begin_reversible_command (_("close region gaps"));
5975                 
5976         int idx = 0;
5977         boost::shared_ptr<Region> last_region;
5978         
5979         rs.sort_by_position_and_track();
5980         
5981         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5982
5983                 framepos_t position = (*r)->region()->position();
5984           
5985                 if (idx == 0 || position < last_region->position()){
5986                         last_region = (*r)->region();
5987                         idx++;
5988                         continue;
5989                 }
5990                 
5991                 (*r)->region()->trim_front( (position - pull_back_frames), this );
5992                 last_region->trim_end( (position - pull_back_frames + crossfade_len), this );
5993                 
5994                 last_region = (*r)->region();
5995                 
5996                 idx++;
5997         }
5998         
5999         _session->commit_reversible_command ();
6000 }
6001
6002 void
6003 Editor::tab_to_transient (bool forward)
6004 {
6005         AnalysisFeatureList positions;
6006
6007         RegionSelection rs = get_regions_from_selection_and_entered ();
6008
6009         if (!_session) {
6010                 return;
6011         }
6012
6013         framepos_t pos = _session->audible_frame ();
6014
6015         if (!selection->tracks.empty()) {
6016
6017                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
6018
6019                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
6020
6021                         if (rtv) {
6022                                 boost::shared_ptr<Track> tr = rtv->track();
6023                                 if (tr) {
6024                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
6025                                         if (pl) {
6026                                                 framepos_t result = pl->find_next_transient (pos, forward ? 1 : -1);
6027
6028                                                 if (result >= 0) {
6029                                                         positions.push_back (result);
6030                                                 }
6031                                         }
6032                                 }
6033                         }
6034                 }
6035
6036         } else {
6037
6038                 if (rs.empty()) {
6039                         return;
6040                 }
6041
6042                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6043                         (*r)->region()->get_transients (positions);
6044                 }
6045         }
6046
6047         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
6048
6049         if (forward) {
6050                 AnalysisFeatureList::iterator x;
6051
6052                 for (x = positions.begin(); x != positions.end(); ++x) {
6053                         if ((*x) > pos) {
6054                                 break;
6055                         }
6056                 }
6057
6058                 if (x != positions.end ()) {
6059                         _session->request_locate (*x);
6060                 }
6061
6062         } else {
6063                 AnalysisFeatureList::reverse_iterator x;
6064
6065                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6066                         if ((*x) < pos) {
6067                                 break;
6068                         }
6069                 }
6070
6071                 if (x != positions.rend ()) {
6072                         _session->request_locate (*x);
6073                 }
6074         }
6075 }
6076
6077 void
6078 Editor::playhead_forward_to_grid ()
6079 {
6080         if (!_session) return;
6081         framepos_t pos = playhead_cursor->current_frame;
6082         if (pos < max_framepos - 1) {
6083                 pos += 2;
6084                 snap_to_internal (pos, 1, false);
6085                 _session->request_locate (pos);
6086         }
6087 }
6088
6089
6090 void
6091 Editor::playhead_backward_to_grid ()
6092 {
6093         if (!_session) return;
6094         framepos_t pos = playhead_cursor->current_frame;
6095         if (pos > 2) {
6096                 pos -= 2;
6097                 snap_to_internal (pos, -1, false);
6098                 _session->request_locate (pos);
6099         }
6100 }
6101
6102 void
6103 Editor::set_track_height (Height h)
6104 {
6105         TrackSelection& ts (selection->tracks);
6106
6107         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6108                 (*x)->set_height (h);
6109         }
6110 }
6111
6112 void
6113 Editor::toggle_tracks_active ()
6114 {
6115         TrackSelection& ts (selection->tracks);
6116         bool first = true;
6117         bool target = false;
6118
6119         if (ts.empty()) {
6120                 return;
6121         }
6122
6123         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6124                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6125
6126                 if (rtv) {
6127                         if (first) {
6128                                 target = !rtv->_route->active();
6129                                 first = false;
6130                         }
6131                         rtv->_route->set_active (target);
6132                 }
6133         }
6134 }
6135
6136 void
6137 Editor::remove_tracks ()
6138 {
6139         TrackSelection& ts (selection->tracks);
6140
6141         if (ts.empty()) {
6142                 return;
6143         }
6144
6145         vector<string> choices;
6146         string prompt;
6147         int ntracks = 0;
6148         int nbusses = 0;
6149         const char* trackstr;
6150         const char* busstr;
6151         vector<boost::shared_ptr<Route> > routes;
6152         bool special_bus = false;
6153
6154         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6155                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6156                 if (rtv) {
6157                         if (rtv->is_track()) {
6158                                 ntracks++;
6159                         } else {
6160                                 nbusses++;
6161                         }
6162                 }
6163                 routes.push_back (rtv->_route);
6164
6165                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6166                         special_bus = true;
6167                 }
6168         }
6169
6170         if (special_bus && !Config->get_allow_special_bus_removal()) {
6171                 MessageDialog msg (_("That would be bad news ...."),
6172                                    false,
6173                                    Gtk::MESSAGE_INFO,
6174                                    Gtk::BUTTONS_OK);
6175                 msg.set_secondary_text (string_compose (_(
6176                                                                 "Removing the master or monitor bus is such a bad idea\n\
6177 that %1 is not going to allow it.\n\
6178 \n\
6179 If you really want to do this sort of thing\n\
6180 edit your ardour.rc file to set the\n\
6181 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6182
6183                 msg.present ();
6184                 msg.run ();
6185                 return;
6186         }
6187                 
6188         if (ntracks + nbusses == 0) {
6189                 return;
6190         }
6191
6192         if (ntracks > 1) {
6193                 trackstr = _("tracks");
6194         } else {
6195                 trackstr = _("track");
6196         }
6197
6198         if (nbusses > 1) {
6199                 busstr = _("busses");
6200         } else {
6201                 busstr = _("bus");
6202         }
6203
6204         if (ntracks) {
6205                 if (nbusses) {
6206                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6207                                                     "(You may also lose the playlists associated with the %2)\n\n"
6208                                                     "This action cannot be undone, and the session file will be overwritten!"),
6209                                                   ntracks, trackstr, nbusses, busstr);
6210                 } else {
6211                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6212                                                     "(You may also lose the playlists associated with the %2)\n\n"
6213                                                     "This action cannot be undone, and the session file will be overwritten!"),
6214                                                   ntracks, trackstr);
6215                 }
6216         } else if (nbusses) {
6217                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6218                                             "This action cannot be undon, and the session file will be overwritten"),
6219                                           nbusses, busstr);
6220         }
6221
6222         choices.push_back (_("No, do nothing."));
6223         if (ntracks + nbusses > 1) {
6224                 choices.push_back (_("Yes, remove them."));
6225         } else {
6226                 choices.push_back (_("Yes, remove it."));
6227         }
6228
6229         string title;
6230         if (ntracks) {
6231                 title = string_compose (_("Remove %1"), trackstr);
6232         } else {
6233                 title = string_compose (_("Remove %1"), busstr);
6234         }
6235
6236         Choice prompter (title, prompt, choices);
6237
6238         if (prompter.run () != 1) {
6239                 return;
6240         }
6241
6242         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6243                 _session->remove_route (*x);
6244         }
6245 }
6246
6247 void
6248 Editor::do_insert_time ()
6249 {
6250         if (selection->tracks.empty()) {
6251                 return;
6252         }
6253
6254         InsertTimeDialog d (*this);
6255         int response = d.run ();
6256
6257         if (response != RESPONSE_OK) {
6258                 return;
6259         }
6260
6261         if (d.distance() == 0) {
6262                 return;
6263         }
6264
6265         InsertTimeOption opt = d.intersected_region_action ();
6266
6267         insert_time (
6268                 get_preferred_edit_position(),
6269                 d.distance(),
6270                 opt,
6271                 d.move_glued(),
6272                 d.move_markers(),
6273                 d.move_glued_markers(),
6274                 d.move_locked_markers(),
6275                 d.move_tempos()
6276                 );
6277 }
6278
6279 void
6280 Editor::insert_time (framepos_t pos, framecnt_t frames, InsertTimeOption opt,
6281                      bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too)
6282 {
6283         bool commit = false;
6284
6285         if (Config->get_edit_mode() == Lock) {
6286                 return;
6287         }
6288
6289         begin_reversible_command (_("insert time"));
6290
6291         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6292                 /* regions */
6293                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6294
6295                 if (pl) {
6296
6297                         pl->clear_changes ();
6298                         pl->clear_owned_changes ();
6299
6300                         if (opt == SplitIntersected) {
6301                                 pl->split (pos);
6302                         }
6303
6304                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6305
6306                         vector<Command*> cmds;
6307                         pl->rdiff (cmds);
6308                         _session->add_commands (cmds);
6309                         
6310                         _session->add_command (new StatefulDiffCommand (pl));
6311                         commit = true;
6312                 }
6313
6314                 /* automation */
6315                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6316                 if (rtav) {
6317                         rtav->route ()->shift (pos, frames);
6318                         commit = true;
6319                 }
6320         }
6321
6322         /* markers */
6323         if (markers_too) {
6324                 bool moved = false;
6325                 XMLNode& before (_session->locations()->get_state());
6326                 Locations::LocationList copy (_session->locations()->list());
6327
6328                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6329
6330                         Locations::LocationList::const_iterator tmp;
6331
6332                         bool const was_locked = (*i)->locked ();
6333                         if (locked_markers_too) {
6334                                 (*i)->unlock ();
6335                         }
6336
6337                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6338
6339                                 if ((*i)->start() >= pos) {
6340                                         (*i)->set_start ((*i)->start() + frames);
6341                                         if (!(*i)->is_mark()) {
6342                                                 (*i)->set_end ((*i)->end() + frames);
6343                                         }
6344                                         moved = true;
6345                                 }
6346                                 
6347                         }
6348
6349                         if (was_locked) {
6350                                 (*i)->lock ();
6351                         }
6352                 }
6353
6354                 if (moved) {
6355                         XMLNode& after (_session->locations()->get_state());
6356                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6357                 }
6358         }
6359
6360         if (tempo_too) {
6361                 _session->tempo_map().insert_time (pos, frames);
6362         }
6363
6364         if (commit) {
6365                 commit_reversible_command ();
6366         }
6367 }
6368
6369 void
6370 Editor::fit_selected_tracks ()
6371 {
6372         fit_tracks (selection->tracks);
6373 }
6374
6375 void
6376 Editor::fit_tracks (TrackViewList & tracks)
6377 {
6378         if (tracks.empty()) {
6379                 return;
6380         }
6381
6382         uint32_t child_heights = 0;
6383
6384         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6385
6386                 if (!(*t)->marked_for_display()) {
6387                         continue;
6388                 }
6389
6390                 child_heights += (*t)->effective_height() - (*t)->current_height();
6391         }
6392
6393         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6394         double first_y_pos = DBL_MAX;
6395
6396         if (h < TimeAxisView::preset_height (HeightSmall)) {
6397                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6398                 /* too small to be displayed */
6399                 return;
6400         }
6401
6402         undo_visual_stack.push_back (current_visual_state());
6403
6404         /* build a list of all tracks, including children */
6405
6406         TrackViewList all;
6407         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6408                 all.push_back (*i);
6409                 TimeAxisView::Children c = (*i)->get_child_list ();
6410                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6411                         all.push_back (j->get());
6412                 }
6413         }
6414
6415         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6416
6417         bool prev_was_selected = false;
6418         bool is_selected = tracks.contains (all.front());
6419         bool next_is_selected;
6420
6421         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6422
6423                 TrackViewList::iterator next;
6424
6425                 next = t;
6426                 ++next;
6427
6428                 if (next != all.end()) {
6429                         next_is_selected = tracks.contains (*next);
6430                 } else {
6431                         next_is_selected = false;
6432                 }
6433
6434                 if (is_selected) {
6435                         (*t)->set_height (h);
6436                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6437                 } else {
6438                         if (prev_was_selected && next_is_selected) {
6439                                 hide_track_in_display (*t);
6440                         }
6441                 }
6442
6443                 prev_was_selected = is_selected;
6444                 is_selected = next_is_selected;
6445         }
6446
6447         /*
6448            set the controls_layout height now, because waiting for its size
6449            request signal handler will cause the vertical adjustment setting to fail
6450         */
6451
6452         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6453         vertical_adjustment.set_value (first_y_pos);
6454
6455         redo_visual_stack.push_back (current_visual_state());
6456 }
6457
6458 void
6459 Editor::save_visual_state (uint32_t n)
6460 {
6461         while (visual_states.size() <= n) {
6462                 visual_states.push_back (0);
6463         }
6464
6465         delete visual_states[n];
6466
6467         visual_states[n] = current_visual_state (true);
6468         gdk_beep ();
6469 }
6470
6471 void
6472 Editor::goto_visual_state (uint32_t n)
6473 {
6474         if (visual_states.size() <= n) {
6475                 return;
6476         }
6477
6478         if (visual_states[n] == 0) {
6479                 return;
6480         }
6481
6482         use_visual_state (*visual_states[n]);
6483 }
6484
6485 void
6486 Editor::start_visual_state_op (uint32_t n)
6487 {
6488         if (visual_state_op_connection.empty()) {
6489                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6490         }
6491 }
6492
6493 void
6494 Editor::cancel_visual_state_op (uint32_t n)
6495 {
6496         if (!visual_state_op_connection.empty()) {
6497                 visual_state_op_connection.disconnect();
6498                 goto_visual_state (n);
6499         }  else {
6500                 //we land here if called from the menu OR if end_visual_state_op has been called
6501                 //so check if we are already in visual state n
6502                 // XXX not yet checking it at all, but redoing does not hurt
6503                 goto_visual_state (n);
6504         }
6505 }
6506
6507 bool
6508 Editor::end_visual_state_op (uint32_t n)
6509 {
6510         visual_state_op_connection.disconnect();
6511         save_visual_state (n);
6512
6513         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6514         char buf[32];
6515         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6516         pup->set_text (buf);
6517         pup->touch();
6518
6519         return false; // do not call again
6520 }
6521
6522 void
6523 Editor::toggle_region_mute ()
6524 {
6525         if (_ignore_region_action) {
6526                 return;
6527         }
6528         
6529         RegionSelection rs = get_regions_from_selection_and_entered ();
6530
6531         if (rs.empty ()) {
6532                 return;
6533         }
6534
6535         if (rs.size() > 1) {
6536                 begin_reversible_command (_("mute regions"));
6537         } else {
6538                 begin_reversible_command (_("mute region"));
6539         }
6540         
6541         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
6542                 
6543                 (*i)->region()->playlist()->clear_changes ();
6544                 (*i)->region()->set_muted (!(*i)->region()->muted ());
6545                 _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
6546                 
6547         }
6548         
6549         commit_reversible_command ();
6550 }
6551