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