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