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