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