remove Glib::ustring from gtk2_ardour
[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                         /* impossible, but this handles it for the future */
4148                         continue;
4149                 }
4150
4151                 TimeAxisView& tv = (*x)->get_time_axis_view();
4152                 boost::shared_ptr<Playlist> npl;
4153                 RegionSelection::iterator tmp;
4154
4155                 tmp = x;
4156                 ++tmp;
4157
4158                 vector<PlaylistMapping>::iterator z;
4159
4160                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4161                         if ((*z).tv == &tv) {
4162                                 break;
4163                         }
4164                 }
4165
4166                 assert (z != pmap.end());
4167
4168                 if (!(*z).pl) {
4169                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4170                         npl->freeze();
4171                         (*z).pl = npl;
4172                 } else {
4173                         npl = (*z).pl;
4174                 }
4175
4176                 boost::shared_ptr<Region> r = (*x)->region();
4177                 boost::shared_ptr<Region> _xx;
4178
4179                 assert (r != 0);
4180
4181                 switch (op) {
4182                 case Cut:
4183                         _xx = RegionFactory::create (r);
4184                         npl->add_region (_xx, r->position() - first_position);
4185                         pl->remove_region (r);
4186                         break;
4187
4188                 case Copy:
4189                         /* copy region before adding, so we're not putting same object into two different playlists */
4190                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4191                         break;
4192
4193                 case Clear:
4194                         pl->remove_region (r);
4195                         break;
4196                 }
4197
4198                 x = tmp;
4199         }
4200
4201         list<boost::shared_ptr<Playlist> > foo;
4202
4203         /* the pmap is in the same order as the tracks in which selected regions occured */
4204
4205         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4206                 (*i).pl->thaw();
4207                 foo.push_back ((*i).pl);
4208         }
4209
4210         if (!foo.empty()) {
4211                 cut_buffer->set (foo);
4212         }
4213
4214         if (pmap.empty()) {
4215                 _last_cut_copy_source_track = 0;
4216         } else {
4217                 _last_cut_copy_source_track = pmap.front().tv;
4218         }
4219         
4220         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4221                 (*pl)->thaw ();
4222                 _session->add_command (new StatefulDiffCommand (*pl));
4223         }
4224 }
4225
4226 void
4227 Editor::cut_copy_ranges (CutCopyOp op)
4228 {
4229         TrackViewList* ts;
4230         TrackViewList entered;
4231
4232         if (selection->tracks.empty()) {
4233                 if (!entered_track) {
4234                         return;
4235                 }
4236                 entered.push_back (entered_track);
4237                 ts = &entered;
4238         } else {
4239                 ts = &selection->tracks;
4240         }
4241
4242         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4243                 (*i)->cut_copy_clear (*selection, op);
4244         }
4245 }
4246
4247 void
4248 Editor::paste (float times)
4249 {
4250         paste_internal (get_preferred_edit_position(), times);
4251 }
4252
4253 void
4254 Editor::mouse_paste ()
4255 {
4256         nframes64_t where;
4257         bool ignored;
4258
4259         if (!mouse_frame (where, ignored)) {
4260                 return;
4261         }
4262
4263         snap_to (where);
4264         paste_internal (where, 1);
4265 }
4266
4267 void
4268 Editor::paste_internal (nframes64_t position, float times)
4269 {
4270         bool commit = false;
4271
4272         if (internal_editing()) {
4273                 if (cut_buffer->midi_notes.empty()) {
4274                         return;
4275                 }
4276         } else {
4277                 if (cut_buffer->empty()) {
4278                         return;
4279                 }
4280         }
4281
4282         if (position == max_frames) {
4283                 position = get_preferred_edit_position();
4284         }
4285
4286         begin_reversible_command (_("paste"));
4287
4288         TrackViewList ts;
4289         TrackViewList::iterator i;
4290         size_t nth;
4291
4292         /* get everything in the correct order */
4293
4294         if (!selection->tracks.empty()) {
4295                 /* there are some selected tracks, so paste to them */
4296                 sort_track_selection ();
4297                 ts = selection->tracks;
4298         } else if (_last_cut_copy_source_track) {
4299                 /* otherwise paste to the track that the cut/copy came from;
4300                    see discussion in mants #3333.
4301                 */
4302                 ts.push_back (_last_cut_copy_source_track);
4303         }
4304
4305         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4306
4307                 /* undo/redo is handled by individual tracks/regions */
4308
4309                 if (internal_editing()) {
4310
4311                         RegionSelection rs;
4312                         RegionSelection::iterator r;
4313                         MidiNoteSelection::iterator cb;
4314
4315                         get_regions_at (rs, position, ts);
4316
4317                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4318                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4319                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4320                                 if (mrv) {
4321                                         mrv->paste (position, times, **cb);
4322                                         ++cb;
4323                                 }
4324                         }
4325
4326                 } else {
4327
4328                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4329                                 commit = true;
4330                         }
4331                 }
4332         }
4333
4334         if (commit) {
4335                 commit_reversible_command ();
4336         }
4337 }
4338
4339 void
4340 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4341 {
4342         boost::shared_ptr<Playlist> playlist;
4343         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4344         RegionSelection foo;
4345
4346         nframes_t const start_frame = regions.start ();
4347         nframes_t const end_frame = regions.end_frame ();
4348
4349         begin_reversible_command (_("duplicate region"));
4350
4351         selection->clear_regions ();
4352
4353         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4354
4355                 boost::shared_ptr<Region> r ((*i)->region());
4356
4357                 TimeAxisView& tv = (*i)->get_time_axis_view();
4358                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4359                 latest_regionviews.clear ();
4360                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4361
4362                 playlist = (*i)->region()->playlist();
4363                 playlist->clear_changes ();
4364                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame), times);
4365                 _session->add_command(new StatefulDiffCommand (playlist));
4366
4367                 c.disconnect ();
4368
4369                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4370         }
4371
4372         commit_reversible_command ();
4373
4374         if (!foo.empty()) {
4375                 selection->set (foo);
4376         }
4377 }
4378
4379 void
4380 Editor::duplicate_selection (float times)
4381 {
4382         if (selection->time.empty() || selection->tracks.empty()) {
4383                 return;
4384         }
4385
4386         boost::shared_ptr<Playlist> playlist;
4387         vector<boost::shared_ptr<Region> > new_regions;
4388         vector<boost::shared_ptr<Region> >::iterator ri;
4389
4390         create_region_from_selection (new_regions);
4391
4392         if (new_regions.empty()) {
4393                 return;
4394         }
4395
4396         begin_reversible_command (_("duplicate selection"));
4397
4398         ri = new_regions.begin();
4399
4400         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4401                 if ((playlist = (*i)->playlist()) == 0) {
4402                         continue;
4403                 }
4404                 playlist->clear_changes ();
4405                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4406                 _session->add_command (new StatefulDiffCommand (playlist));
4407
4408                 ++ri;
4409                 if (ri == new_regions.end()) {
4410                         --ri;
4411                 }
4412         }
4413
4414         commit_reversible_command ();
4415 }
4416
4417 void
4418 Editor::reset_point_selection ()
4419 {
4420         /* reset all selected points to the relevant default value */
4421
4422         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4423
4424                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4425
4426                 if (atv) {
4427                         atv->reset_objects (selection->points);
4428                 }
4429         }
4430 }
4431
4432 void
4433 Editor::center_playhead ()
4434 {
4435         float page = _canvas_width * frames_per_unit;
4436         center_screen_internal (playhead_cursor->current_frame, page);
4437 }
4438
4439 void
4440 Editor::center_edit_point ()
4441 {
4442         float page = _canvas_width * frames_per_unit;
4443         center_screen_internal (get_preferred_edit_position(), page);
4444 }
4445
4446 void
4447 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4448 {
4449         begin_reversible_command (_("clear playlist"));
4450         playlist->clear_changes ();
4451         playlist->clear ();
4452         _session->add_command (new StatefulDiffCommand (playlist));
4453         commit_reversible_command ();
4454 }
4455
4456 void
4457 Editor::nudge_track (bool use_edit, bool forwards)
4458 {
4459         boost::shared_ptr<Playlist> playlist;
4460         nframes64_t distance;
4461         nframes64_t next_distance;
4462         nframes64_t start;
4463
4464         if (use_edit) {
4465                 start = get_preferred_edit_position();
4466         } else {
4467                 start = 0;
4468         }
4469
4470         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4471                 return;
4472         }
4473
4474         if (selection->tracks.empty()) {
4475                 return;
4476         }
4477
4478         begin_reversible_command (_("nudge track"));
4479
4480         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4481
4482                 if ((playlist = (*i)->playlist()) == 0) {
4483                         continue;
4484                 }
4485
4486                 playlist->clear_changes ();
4487                 playlist->clear_owned_changes ();
4488
4489                 playlist->nudge_after (start, distance, forwards);
4490                 
4491                 vector<Command*> cmds;
4492
4493                 playlist->rdiff (cmds);
4494                 _session->add_commands (cmds);
4495
4496                 _session->add_command (new StatefulDiffCommand (playlist));
4497         }
4498
4499         commit_reversible_command ();
4500 }
4501
4502 void
4503 Editor::remove_last_capture ()
4504 {
4505         vector<string> choices;
4506         string prompt;
4507
4508         if (!_session) {
4509                 return;
4510         }
4511
4512         if (Config->get_verify_remove_last_capture()) {
4513                 prompt  = _("Do you really want to destroy the last capture?"
4514                             "\n(This is destructive and cannot be undone)");
4515
4516                 choices.push_back (_("No, do nothing."));
4517                 choices.push_back (_("Yes, destroy it."));
4518
4519                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4520
4521                 if (prompter.run () == 1) {
4522                         _session->remove_last_capture ();
4523                         _regions->redisplay ();
4524                 }
4525
4526         } else {
4527                 _session->remove_last_capture();
4528                 _regions->redisplay ();
4529         }
4530 }
4531
4532 void
4533 Editor::normalize_region ()
4534 {
4535         if (!_session) {
4536                 return;
4537         }
4538
4539         RegionSelection rs;
4540         get_regions_for_action (rs);
4541
4542         if (rs.empty()) {
4543                 return;
4544         }
4545
4546         Dialog dialog (rs.size() > 1 ? _("Normalize regions") : _("Normalize region"));
4547
4548         VBox vbox;
4549         vbox.set_spacing (6);
4550         vbox.set_border_width (6);
4551         
4552         HBox hbox;
4553         hbox.set_spacing (6);
4554         hbox.set_border_width (6);
4555         hbox.pack_start (*manage (new Label (_("Normalize to:"))));
4556         SpinButton spin (0.2, 2);
4557         spin.set_range (-112, 0);
4558         spin.set_increments (0.1, 1);
4559         spin.set_value (0);
4560         hbox.pack_start (spin);
4561         spin.set_value (_last_normalization_value);
4562         hbox.pack_start (*manage (new Label (_("dbFS"))));
4563         vbox.pack_start (hbox);
4564
4565         CheckButton* normalize_across_all = manage (new CheckButton (_("Normalize across all selected regions")));
4566         vbox.pack_start (*normalize_across_all);
4567         if (rs.size() <= 1) {
4568                 normalize_across_all->set_sensitive (false);
4569         }
4570
4571         vbox.show_all ();
4572         
4573         dialog.get_vbox()->set_spacing (12);
4574         dialog.get_vbox()->pack_start (vbox);
4575         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
4576         dialog.add_button (_("Normalize"), RESPONSE_ACCEPT);
4577
4578         if (dialog.run () == RESPONSE_CANCEL) {
4579                 return;
4580         }
4581
4582         begin_reversible_command (_("normalize"));
4583
4584         track_canvas->get_window()->set_cursor (*wait_cursor);
4585         gdk_flush ();
4586
4587         double maxamp = 0;
4588         if (normalize_across_all->get_active ()) {
4589                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4590                         AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4591                         if (!arv) {
4592                                 continue;
4593                         }
4594                         maxamp = max (maxamp, arv->audio_region()->maximum_amplitude ());
4595                 }
4596         }
4597         
4598         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4599                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4600                 if (!arv) {
4601                         continue;
4602                 }
4603                 arv->region()->clear_changes ();
4604
4605                 double const amp = normalize_across_all->get_active() ? maxamp : arv->audio_region()->maximum_amplitude ();
4606                 
4607                 arv->audio_region()->normalize (amp, spin.get_value ());
4608                 _session->add_command (new StatefulDiffCommand (arv->region()));
4609         }
4610
4611         commit_reversible_command ();
4612         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4613
4614         _last_normalization_value = spin.get_value ();
4615 }
4616
4617
4618 void
4619 Editor::reset_region_scale_amplitude ()
4620 {
4621         if (!_session) {
4622                 return;
4623         }
4624
4625         RegionSelection rs;
4626
4627         get_regions_for_action (rs);
4628
4629         if (rs.empty()) {
4630                 return;
4631         }
4632
4633         begin_reversible_command ("reset gain");
4634
4635         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4636                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4637                 if (!arv)
4638                         continue;
4639                 arv->region()->clear_changes ();
4640                 arv->audio_region()->set_scale_amplitude (1.0f);
4641                 _session->add_command (new StatefulDiffCommand (arv->region()));
4642         }
4643
4644         commit_reversible_command ();
4645 }
4646
4647 void
4648 Editor::adjust_region_scale_amplitude (bool up)
4649 {
4650         if (!_session) {
4651                 return;
4652         }
4653
4654         RegionSelection rs;
4655
4656         get_regions_for_action (rs);
4657
4658         if (rs.empty()) {
4659                 return;
4660         }
4661
4662         begin_reversible_command ("denormalize");
4663
4664         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4665                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4666                 if (!arv) {
4667                         continue;
4668                 }
4669
4670                 arv->region()->clear_changes ();
4671                 
4672                 double fraction = gain_to_slider_position (arv->audio_region()->scale_amplitude ());
4673
4674                 if (up) {
4675                         fraction += 0.05;
4676                         fraction = min (fraction, 1.0);
4677                 } else {
4678                         fraction -= 0.05;
4679                         fraction = max (fraction, 0.0);
4680                 }
4681
4682                 if (!up && fraction <= 0) {
4683                         continue;
4684                 }
4685
4686                 fraction = slider_position_to_gain (fraction);
4687
4688                 if (up && fraction >= 2.0) {
4689                         continue;
4690                 }
4691
4692                 arv->audio_region()->set_scale_amplitude (fraction);
4693                 _session->add_command (new StatefulDiffCommand (arv->region()));
4694         }
4695
4696         commit_reversible_command ();
4697 }
4698
4699
4700 void
4701 Editor::reverse_region ()
4702 {
4703         if (!_session) {
4704                 return;
4705         }
4706
4707         Reverse rev (*_session);
4708         apply_filter (rev, _("reverse regions"));
4709 }
4710
4711 void
4712 Editor::strip_region_silence ()
4713 {
4714         if (!_session) {
4715                 return;
4716         }
4717
4718         RegionSelection rs;
4719         get_regions_for_action (rs);
4720
4721         if (rs.empty()) {
4722                 return;
4723         }
4724
4725         std::list<boost::shared_ptr<AudioRegion> > ar;
4726
4727         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4728                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4729                 if (arv) {
4730                         ar.push_back (arv->audio_region ());
4731                 }
4732         }
4733
4734         StripSilenceDialog d (_session, ar);
4735         int const r = d.run ();
4736
4737         if (r == Gtk::RESPONSE_OK) {
4738                 StripSilence s (*_session, d.threshold (), d.minimum_length (), d.fade_length ());
4739                 apply_filter (s, _("strip silence"));
4740         }
4741 }
4742
4743 Command*
4744 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4745 {
4746         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4747         mrv.selection_as_notelist (selected, true);
4748
4749         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4750         v.push_back (selected);
4751
4752         return op (mrv.midi_region()->model(), v);
4753 }
4754
4755 void
4756 Editor::apply_midi_note_edit_op (MidiOperator& op)
4757 {
4758         RegionSelection rs;
4759         Command* cmd;
4760
4761         get_regions_for_action (rs);
4762
4763         if (rs.empty()) {
4764                 return;
4765         }
4766
4767         begin_reversible_command (op.name ());
4768
4769         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4770                 RegionSelection::iterator tmp = r;
4771                 ++tmp;
4772
4773                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4774
4775                 if (mrv) {
4776                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4777                         if (cmd) {
4778                                 (*cmd)();
4779                                 _session->add_command (cmd);
4780                         }
4781                 }
4782
4783                 r = tmp;
4784         }
4785
4786         commit_reversible_command ();
4787         rs.clear ();
4788 }
4789
4790 void
4791 Editor::fork_region ()
4792 {
4793         RegionSelection rs;
4794
4795         get_regions_for_action (rs);
4796
4797         if (rs.empty()) {
4798                 return;
4799         }
4800
4801         begin_reversible_command (_("Fork Region(s)"));
4802
4803         track_canvas->get_window()->set_cursor (*wait_cursor);
4804         gdk_flush ();
4805
4806         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4807                 RegionSelection::iterator tmp = r;
4808                 ++tmp;
4809
4810                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4811
4812                 if (mrv) {
4813                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4814                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4815                         
4816                         playlist->clear_changes ();
4817                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4818                         _session->add_command(new StatefulDiffCommand (playlist));
4819                 }
4820
4821                 r = tmp;
4822         }
4823
4824         commit_reversible_command ();
4825         rs.clear ();
4826
4827         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4828 }
4829
4830 void
4831 Editor::quantize_region ()
4832 {
4833         if (!_session) {
4834                 return;
4835         }
4836
4837         QuantizeDialog* qd = new QuantizeDialog (*this);
4838
4839         qd->present ();
4840         const int r = qd->run ();
4841         qd->hide ();
4842
4843         if (r == Gtk::RESPONSE_OK) {
4844                 Quantize quant (*_session, Plain,
4845                                 qd->snap_start(), qd->snap_end(),
4846                                 qd->start_grid_size(), qd->end_grid_size(),
4847                                 qd->strength(), qd->swing(), qd->threshold());
4848
4849                 apply_midi_note_edit_op (quant);
4850         }
4851 }
4852
4853 void
4854 Editor::apply_filter (Filter& filter, string command)
4855 {
4856         RegionSelection rs;
4857
4858         get_regions_for_action (rs);
4859
4860         if (rs.empty()) {
4861                 return;
4862         }
4863
4864         begin_reversible_command (command);
4865
4866         track_canvas->get_window()->set_cursor (*wait_cursor);
4867         gdk_flush ();
4868
4869         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4870                 RegionSelection::iterator tmp = r;
4871                 ++tmp;
4872
4873                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4874                 if (arv) {
4875                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4876
4877                         if (arv->audio_region()->apply (filter) == 0) {
4878
4879                                 playlist->clear_changes ();
4880                                 
4881                                 if (filter.results.empty ()) {
4882
4883                                         /* no regions returned; remove the old one */
4884                                         playlist->remove_region (arv->region ());
4885
4886                                 } else {
4887
4888                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4889
4890                                         /* first region replaces the old one */
4891                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4892                                         ++res;
4893
4894                                         /* add the rest */
4895                                         while (res != filter.results.end()) {
4896                                                 playlist->add_region (*res, (*res)->position());
4897                                                 ++res;
4898                                         }
4899
4900                                 }
4901
4902                                 _session->add_command(new StatefulDiffCommand (playlist));
4903                         } else {
4904                                 goto out;
4905                         }
4906                 }
4907
4908                 r = tmp;
4909         }
4910
4911         commit_reversible_command ();
4912         rs.clear ();
4913
4914   out:
4915         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4916 }
4917
4918 void
4919 Editor::region_selection_op (void (Region::*pmf)(void))
4920 {
4921         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4922                 Region* region = (*i)->region().get();
4923                 (region->*pmf)();
4924         }
4925 }
4926
4927
4928 void
4929 Editor::region_selection_op (void (Region::*pmf)(void*), void *arg)
4930 {
4931         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4932                 Region* region = (*i)->region().get();
4933                 (region->*pmf)(arg);
4934         }
4935 }
4936
4937 void
4938 Editor::region_selection_op (void (Region::*pmf)(bool), bool yn)
4939 {
4940         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4941                 Region* region = (*i)->region().get();
4942                 (region->*pmf)(yn);
4943         }
4944 }
4945
4946 void
4947 Editor::external_edit_region ()
4948 {
4949         /* more to come */
4950 }
4951
4952 void
4953 Editor::brush (nframes64_t pos)
4954 {
4955         RegionSelection sel;
4956         RegionSelection rs;
4957
4958         get_regions_for_action (rs);
4959
4960         snap_to (pos);
4961
4962         if (rs.empty()) {
4963                 return;
4964         }
4965
4966         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4967                 mouse_brush_insert_region ((*i), pos);
4968         }
4969 }
4970
4971 void
4972 Editor::reset_region_gain_envelopes ()
4973 {
4974         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4975
4976         if (!_session || rs.empty()) {
4977                 return;
4978         }
4979
4980         _session->begin_reversible_command (_("reset region gain"));
4981
4982         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4983                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4984                 if (arv) {
4985                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4986                         XMLNode& before (alist->get_state());
4987
4988                         arv->audio_region()->set_default_envelope ();
4989                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4990                 }
4991         }
4992
4993         _session->commit_reversible_command ();
4994 }
4995
4996 void
4997 Editor::toggle_gain_envelope_visibility ()
4998 {
4999         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5000
5001         if (!_session || rs.empty()) {
5002                 return;
5003         }
5004
5005         _session->begin_reversible_command (_("region gain envelope visible"));
5006
5007         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5008                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
5009                 if (arv) {
5010                         arv->region()->clear_changes ();
5011                         arv->set_envelope_visible (!arv->envelope_visible());
5012                         _session->add_command (new StatefulDiffCommand (arv->region()));
5013                 }
5014         }
5015
5016         _session->commit_reversible_command ();
5017 }
5018
5019 void
5020 Editor::toggle_gain_envelope_active ()
5021 {
5022         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5023
5024         if (!_session || rs.empty()) {
5025                 return;
5026         }
5027
5028         _session->begin_reversible_command (_("region gain envelope active"));
5029
5030         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5031                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
5032                 if (arv) {
5033                         arv->region()->clear_changes ();
5034                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
5035                         _session->add_command (new StatefulDiffCommand (arv->region()));
5036                 }
5037         }
5038
5039         _session->commit_reversible_command ();
5040 }
5041
5042 void
5043 Editor::toggle_region_lock ()
5044 {
5045         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5046
5047         if (!_session || rs.empty()) {
5048                 return;
5049         }
5050
5051         _session->begin_reversible_command (_("region lock"));
5052
5053         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5054                 (*i)->region()->clear_changes ();
5055                 (*i)->region()->set_locked (!(*i)->region()->locked());
5056                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
5057         }
5058
5059         _session->commit_reversible_command ();
5060 }
5061
5062 void
5063 Editor::toggle_region_lock_style ()
5064 {
5065         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5066
5067         if (!_session || rs.empty()) {
5068                 return;
5069         }
5070
5071         _session->begin_reversible_command (_("region lock style"));
5072
5073         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5074                 (*i)->region()->clear_changes ();
5075                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
5076                 (*i)->region()->set_position_lock_style (ns);
5077                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
5078         }
5079
5080         _session->commit_reversible_command ();
5081 }
5082
5083
5084 void
5085 Editor::toggle_region_mute ()
5086 {
5087         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5088
5089         if (!_session || rs.empty()) {
5090                 return;
5091         }
5092
5093         _session->begin_reversible_command (_("region mute"));
5094
5095         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5096                 (*i)->region()->clear_changes ();
5097                 (*i)->region()->set_muted (!(*i)->region()->muted());
5098                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
5099         }
5100
5101         _session->commit_reversible_command ();
5102 }
5103
5104 void
5105 Editor::toggle_region_opaque ()
5106 {
5107         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
5108
5109         if (!_session || rs.empty()) {
5110                 return;
5111         }
5112
5113         _session->begin_reversible_command (_("region opacity"));
5114
5115         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5116                 (*i)->region()->clear_changes ();
5117                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
5118                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
5119         }
5120
5121         _session->commit_reversible_command ();
5122 }
5123
5124 void
5125 Editor::toggle_record_enable ()
5126 {
5127         bool new_state = false;
5128         bool first = true;
5129         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
5130                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
5131                 if (!rtav)
5132                         continue;
5133                 if (!rtav->is_track())
5134                         continue;
5135
5136                 if (first) {
5137                         new_state = !rtav->track()->record_enabled();
5138                         first = false;
5139                 }
5140
5141                 rtav->track()->set_record_enabled (new_state, this);
5142         }
5143 }
5144
5145
5146 void
5147 Editor::set_fade_length (bool in)
5148 {
5149         RegionSelection rs;
5150
5151         get_regions_for_action (rs, true);
5152
5153         if (rs.empty()) {
5154                 return;
5155         }
5156
5157         /* we need a region to measure the offset from the start */
5158
5159         RegionView* rv = rs.front ();
5160
5161         nframes64_t pos = get_preferred_edit_position();
5162         nframes64_t len;
5163         char const * cmd;
5164
5165         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
5166                 /* edit point is outside the relevant region */
5167                 return;
5168         }
5169
5170         if (in) {
5171                 if (pos <= rv->region()->position()) {
5172                         /* can't do it */
5173                         return;
5174                 }
5175                 len = pos - rv->region()->position();
5176                 cmd = _("set fade in length");
5177         } else {
5178                 if (pos >= rv->region()->last_frame()) {
5179                         /* can't do it */
5180                         return;
5181                 }
5182                 len = rv->region()->last_frame() - pos;
5183                 cmd = _("set fade out length");
5184         }
5185
5186         begin_reversible_command (cmd);
5187
5188         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5189                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5190
5191                 if (!tmp) {
5192                         return;
5193                 }
5194
5195                 boost::shared_ptr<AutomationList> alist;
5196                 if (in) {
5197                         alist = tmp->audio_region()->fade_in();
5198                 } else {
5199                         alist = tmp->audio_region()->fade_out();
5200                 }
5201
5202                 XMLNode &before = alist->get_state();
5203
5204                 if (in) {
5205                         tmp->audio_region()->set_fade_in_length (len);
5206                         tmp->audio_region()->set_fade_in_active (true);
5207                 } else {
5208                         tmp->audio_region()->set_fade_out_length (len);
5209                         tmp->audio_region()->set_fade_out_active (true);
5210                 }
5211
5212                 XMLNode &after = alist->get_state();
5213                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
5214         }
5215
5216         commit_reversible_command ();
5217 }
5218
5219 void
5220 Editor::toggle_fade_active (bool in)
5221 {
5222         RegionSelection rs;
5223
5224         get_regions_for_action (rs);
5225
5226         if (rs.empty()) {
5227                 return;
5228         }
5229
5230         const char* cmd = (in ? _("toggle fade in active") : _("toggle fade out active"));
5231         bool have_switch = false;
5232         bool yn = false;
5233
5234         begin_reversible_command (cmd);
5235
5236         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5237                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5238
5239                 if (!tmp) {
5240                         return;
5241                 }
5242
5243                 boost::shared_ptr<AudioRegion> region (tmp->audio_region());
5244
5245                 /* make the behaviour consistent across all regions */
5246
5247                 if (!have_switch) {
5248                         if (in) {
5249                                 yn = region->fade_in_active();
5250                         } else {
5251                                 yn = region->fade_out_active();
5252                         }
5253                         have_switch = true;
5254                 }
5255
5256                 region->clear_changes ();
5257
5258                 if (in) {
5259                         region->set_fade_in_active (!yn);
5260                 } else {
5261                         region->set_fade_out_active (!yn);
5262                 }
5263                 
5264                 _session->add_command(new StatefulDiffCommand (region));
5265         }
5266
5267         commit_reversible_command ();
5268 }
5269
5270 void
5271 Editor::set_fade_in_shape (AudioRegion::FadeShape shape)
5272 {
5273         RegionSelection rs;
5274
5275         get_regions_for_action (rs);
5276
5277         if (rs.empty()) {
5278                 return;
5279         }
5280
5281         begin_reversible_command (_("set fade in shape"));
5282
5283         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5284                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5285
5286                 if (!tmp) {
5287                         return;
5288                 }
5289
5290                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5291                 XMLNode &before = alist->get_state();
5292
5293                 tmp->audio_region()->set_fade_in_shape (shape);
5294
5295                 XMLNode &after = alist->get_state();
5296                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5297         }
5298
5299         commit_reversible_command ();
5300
5301 }
5302
5303 void
5304 Editor::set_fade_out_shape (AudioRegion::FadeShape shape)
5305 {
5306         RegionSelection rs;
5307
5308         get_regions_for_action (rs);
5309
5310         if (rs.empty()) {
5311                 return;
5312         }
5313
5314         begin_reversible_command (_("set fade out shape"));
5315
5316         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5317                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5318
5319                 if (!tmp) {
5320                         return;
5321                 }
5322
5323                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5324                 XMLNode &before = alist->get_state();
5325
5326                 tmp->audio_region()->set_fade_out_shape (shape);
5327
5328                 XMLNode &after = alist->get_state();
5329                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5330         }
5331
5332         commit_reversible_command ();
5333 }
5334
5335 void
5336 Editor::set_fade_in_active (bool yn)
5337 {
5338         RegionSelection rs;
5339
5340         get_regions_for_action (rs);
5341
5342         if (rs.empty()) {
5343                 return;
5344         }
5345
5346         begin_reversible_command (_("set fade in active"));
5347
5348         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5349                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5350
5351                 if (!tmp) {
5352                         return;
5353                 }
5354
5355
5356                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5357                 
5358                 ar->clear_changes ();
5359                 ar->set_fade_in_active (yn);
5360                 _session->add_command (new StatefulDiffCommand (ar));
5361         }
5362
5363         commit_reversible_command ();
5364 }
5365
5366 void
5367 Editor::set_fade_out_active (bool yn)
5368 {
5369         RegionSelection rs;
5370
5371         get_regions_for_action (rs);
5372
5373         if (rs.empty()) {
5374                 return;
5375         }
5376
5377         begin_reversible_command (_("set fade out active"));
5378
5379         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5380                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5381
5382                 if (!tmp) {
5383                         return;
5384                 }
5385
5386                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5387
5388                 ar->clear_changes ();
5389                 ar->set_fade_out_active (yn);
5390                 _session->add_command(new StatefulDiffCommand (ar));
5391         }
5392
5393         commit_reversible_command ();
5394 }
5395
5396 void
5397 Editor::toggle_selected_region_fades (int dir)
5398 {
5399         RegionSelection rs;
5400         RegionSelection::iterator i;
5401         boost::shared_ptr<AudioRegion> ar;
5402         bool yn;
5403
5404         get_regions_for_action (rs);
5405
5406         if (rs.empty()) {
5407                 return;
5408         }
5409
5410         for (i = rs.begin(); i != rs.end(); ++i) {
5411                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5412                         if (dir == -1) {
5413                                 yn = ar->fade_out_active ();
5414                         } else {
5415                                 yn = ar->fade_in_active ();
5416                         }
5417                         break;
5418                 }
5419         }
5420
5421         if (i == rs.end()) {
5422                 return;
5423         }
5424
5425         /* XXX should this undo-able? */
5426
5427         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5428                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5429                         continue;
5430                 }
5431                 if (dir == 1 || dir == 0) {
5432                         ar->set_fade_in_active (!yn);
5433                 }
5434
5435                 if (dir == -1 || dir == 0) {
5436                         ar->set_fade_out_active (!yn);
5437                 }
5438         }
5439 }
5440
5441
5442 /** Update region fade visibility after its configuration has been changed */
5443 void
5444 Editor::update_region_fade_visibility ()
5445 {
5446         bool _fade_visibility = _session->config.get_show_region_fades ();
5447
5448         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5449                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5450                 if (v) {
5451                         if (_fade_visibility) {
5452                                 v->audio_view()->show_all_fades ();
5453                         } else {
5454                                 v->audio_view()->hide_all_fades ();
5455                         }
5456                 }
5457         }
5458 }
5459
5460 /** Update crossfade visibility after its configuration has been changed */
5461 void
5462 Editor::update_xfade_visibility ()
5463 {
5464         _xfade_visibility = _session->config.get_xfades_visible ();
5465
5466         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5467                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5468                 if (v) {
5469                         if (_xfade_visibility) {
5470                                 v->show_all_xfades ();
5471                         } else {
5472                                 v->hide_all_xfades ();
5473                         }
5474                 }
5475         }
5476 }
5477
5478 void
5479 Editor::set_edit_point ()
5480 {
5481         nframes64_t where;
5482         bool ignored;
5483
5484         if (!mouse_frame (where, ignored)) {
5485                 return;
5486         }
5487
5488         snap_to (where);
5489
5490         if (selection->markers.empty()) {
5491
5492                 mouse_add_new_marker (where);
5493
5494         } else {
5495                 bool ignored;
5496
5497                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5498
5499                 if (loc) {
5500                         loc->move_to (where);
5501                 }
5502         }
5503 }
5504
5505 void
5506 Editor::set_playhead_cursor ()
5507 {
5508         if (entered_marker) {
5509                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5510         } else {
5511                 nframes64_t where;
5512                 bool ignored;
5513
5514                 if (!mouse_frame (where, ignored)) {
5515                         return;
5516                 }
5517
5518                 snap_to (where);
5519
5520                 if (_session) {
5521                         _session->request_locate (where, _session->transport_rolling());
5522                 }
5523         }
5524 }
5525
5526 void
5527 Editor::split ()
5528 {
5529         if (((mouse_mode == MouseRange) || 
5530              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) && 
5531             !selection->time.empty()) {
5532                 separate_regions_between (selection->time);
5533                 return;
5534         } 
5535
5536         RegionSelection rs;
5537
5538         get_regions_for_action (rs, true);
5539
5540         nframes64_t where = get_preferred_edit_position();
5541
5542         if (rs.empty()) {
5543                 return;
5544         }
5545
5546         split_regions_at (where, rs);
5547 }
5548
5549 void
5550 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5551 {
5552         if (entered_track && mouse_mode == MouseObject) {
5553                 if (!selection->tracks.empty()) {
5554                         if (!selection->selected (entered_track)) {
5555                                 selection->add (entered_track);
5556                         }
5557                 } else {
5558                         /* there is no selection, but this operation requires/prefers selected objects */
5559
5560                         if (op_really_wants_one_track_if_none_are_selected) {
5561                                 selection->set (entered_track);
5562                         }
5563                 }
5564         }
5565 }
5566
5567 struct EditorOrderRouteSorter {
5568     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5569             /* use of ">" forces the correct sort order */
5570             return a->order_key ("editor") < b->order_key ("editor");
5571     }
5572 };
5573
5574 void
5575 Editor::select_next_route()
5576 {
5577         if (selection->tracks.empty()) {
5578                 selection->set (track_views.front());
5579                 return;
5580         }
5581
5582         TimeAxisView* current = selection->tracks.front();
5583
5584         RouteUI *rui;
5585         do {
5586                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5587                         if (*i == current) {
5588                                 ++i;
5589                                 if (i != track_views.end()) {
5590                                         current = (*i);
5591                                 } else {
5592                                         current = (*(track_views.begin()));
5593                                         //selection->set (*(track_views.begin()));
5594                                 }
5595                                 break;
5596                         }
5597                 }
5598                 rui = dynamic_cast<RouteUI *>(current);
5599         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5600
5601         selection->set(current);
5602
5603         ensure_track_visible(current);
5604 }
5605
5606 void
5607 Editor::select_prev_route()
5608 {
5609         if (selection->tracks.empty()) {
5610                 selection->set (track_views.front());
5611                 return;
5612         }
5613
5614         TimeAxisView* current = selection->tracks.front();
5615
5616         RouteUI *rui;
5617         do {
5618                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5619                         if (*i == current) {
5620                                 ++i;
5621                                 if (i != track_views.rend()) {
5622                                         current = (*i);
5623                                 } else {
5624                                         current = *(track_views.rbegin());
5625                                 }
5626                                 break;
5627                         }
5628                 }
5629                 rui = dynamic_cast<RouteUI *>(current);
5630         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5631
5632         selection->set (current);
5633
5634         ensure_track_visible(current);
5635 }
5636
5637 void
5638 Editor::ensure_track_visible(TimeAxisView *track)
5639 {
5640         if (track->hidden())
5641                 return;
5642
5643         double const current_view_min_y = vertical_adjustment.get_value();
5644         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5645
5646         double const track_min_y = track->y_position ();
5647         double const track_max_y = track->y_position () + track->effective_height ();
5648
5649         if (track_min_y >= current_view_min_y &&
5650             track_max_y <= current_view_max_y) {
5651                 return;
5652         }
5653
5654         double new_value;
5655
5656         if (track_min_y < current_view_min_y) {
5657                 // Track is above the current view
5658                 new_value = track_min_y;
5659         } else {
5660                 // Track is below the current view
5661                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5662         }
5663
5664         vertical_adjustment.set_value(new_value);
5665 }
5666
5667 void
5668 Editor::set_loop_from_selection (bool play)
5669 {
5670         if (_session == 0 || selection->time.empty()) {
5671                 return;
5672         }
5673
5674         nframes64_t start = selection->time[clicked_selection].start;
5675         nframes64_t end = selection->time[clicked_selection].end;
5676
5677         set_loop_range (start, end,  _("set loop range from selection"));
5678
5679         if (play) {
5680                 _session->request_play_loop (true);
5681                 _session->request_locate (start, true);
5682         }
5683 }
5684
5685 void
5686 Editor::set_loop_from_edit_range (bool play)
5687 {
5688         if (_session == 0) {
5689                 return;
5690         }
5691
5692         nframes64_t start;
5693         nframes64_t end;
5694
5695         if (!get_edit_op_range (start, end)) {
5696                 return;
5697         }
5698
5699         set_loop_range (start, end,  _("set loop range from edit range"));
5700
5701         if (play) {
5702                 _session->request_play_loop (true);
5703                 _session->request_locate (start, true);
5704         }
5705 }
5706
5707 void
5708 Editor::set_loop_from_region (bool play)
5709 {
5710         nframes64_t start = max_frames;
5711         nframes64_t end = 0;
5712
5713         RegionSelection rs;
5714
5715         get_regions_for_action (rs);
5716
5717         if (rs.empty()) {
5718                 return;
5719         }
5720
5721         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5722                 if ((*i)->region()->position() < start) {
5723                         start = (*i)->region()->position();
5724                 }
5725                 if ((*i)->region()->last_frame() + 1 > end) {
5726                         end = (*i)->region()->last_frame() + 1;
5727                 }
5728         }
5729
5730         set_loop_range (start, end, _("set loop range from region"));
5731
5732         if (play) {
5733                 _session->request_play_loop (true);
5734                 _session->request_locate (start, true);
5735         }
5736 }
5737
5738 void
5739 Editor::set_punch_from_selection ()
5740 {
5741         if (_session == 0 || selection->time.empty()) {
5742                 return;
5743         }
5744
5745         nframes64_t start = selection->time[clicked_selection].start;
5746         nframes64_t end = selection->time[clicked_selection].end;
5747
5748         set_punch_range (start, end,  _("set punch range from selection"));
5749 }
5750
5751 void
5752 Editor::set_punch_from_edit_range ()
5753 {
5754         if (_session == 0) {
5755                 return;
5756         }
5757
5758         nframes64_t start;
5759         nframes64_t end;
5760
5761         if (!get_edit_op_range (start, end)) {
5762                 return;
5763         }
5764
5765         set_punch_range (start, end,  _("set punch range from edit range"));
5766 }
5767
5768 void
5769 Editor::set_punch_from_region ()
5770 {
5771         nframes64_t start = max_frames;
5772         nframes64_t end = 0;
5773
5774         RegionSelection rs;
5775
5776         get_regions_for_action (rs);
5777
5778         if (rs.empty()) {
5779                 return;
5780         }
5781
5782         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5783                 if ((*i)->region()->position() < start) {
5784                         start = (*i)->region()->position();
5785                 }
5786                 if ((*i)->region()->last_frame() + 1 > end) {
5787                         end = (*i)->region()->last_frame() + 1;
5788                 }
5789         }
5790
5791         set_punch_range (start, end, _("set punch range from region"));
5792 }
5793
5794 void
5795 Editor::pitch_shift_regions ()
5796 {
5797         RegionSelection rs;
5798
5799         get_regions_for_action (rs);
5800
5801         if (rs.empty()) {
5802                 return;
5803         }
5804
5805         pitch_shift (rs, 1.2);
5806 }
5807
5808 void
5809 Editor::use_region_as_bar ()
5810 {
5811         if (!_session) {
5812                 return;
5813         }
5814
5815         RegionSelection rs;
5816
5817         get_regions_for_action (rs);
5818
5819         if (rs.empty()) {
5820                 return;
5821         }
5822
5823         RegionView* rv = rs.front();
5824
5825         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5826 }
5827
5828 void
5829 Editor::use_range_as_bar ()
5830 {
5831         nframes64_t start, end;
5832         if (get_edit_op_range (start, end)) {
5833                 define_one_bar (start, end);
5834         }
5835 }
5836
5837 void
5838 Editor::define_one_bar (nframes64_t start, nframes64_t end)
5839 {
5840         nframes64_t length = end - start;
5841
5842         const Meter& m (_session->tempo_map().meter_at (start));
5843
5844         /* length = 1 bar */
5845
5846         /* now we want frames per beat.
5847            we have frames per bar, and beats per bar, so ...
5848         */
5849
5850         double frames_per_beat = length / m.beats_per_bar();
5851
5852         /* beats per minute = */
5853
5854         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5855
5856         /* now decide whether to:
5857
5858             (a) set global tempo
5859             (b) add a new tempo marker
5860
5861         */
5862
5863         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5864
5865         bool do_global = false;
5866
5867         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5868
5869                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5870                    at the start, or create a new marker
5871                 */
5872
5873                 vector<string> options;
5874                 options.push_back (_("Cancel"));
5875                 options.push_back (_("Add new marker"));
5876                 options.push_back (_("Set global tempo"));
5877
5878                 Choice c (
5879                         _("Define one bar"),
5880                         _("Do you want to set the global tempo or add a new tempo marker?"),
5881                         options
5882                         );
5883                 
5884                 c.set_default_response (2);
5885
5886                 switch (c.run()) {
5887                 case 0:
5888                         return;
5889
5890                 case 2:
5891                         do_global = true;
5892                         break;
5893
5894                 default:
5895                         do_global = false;
5896                 }
5897
5898         } else {
5899
5900                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5901                    if the marker is at the region starter, change it, otherwise add
5902                    a new tempo marker
5903                 */
5904         }
5905
5906         begin_reversible_command (_("set tempo from region"));
5907         XMLNode& before (_session->tempo_map().get_state());
5908
5909         if (do_global) {
5910                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5911         } else if (t.frame() == start) {
5912                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5913         } else {
5914                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5915         }
5916
5917         XMLNode& after (_session->tempo_map().get_state());
5918
5919         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5920         commit_reversible_command ();
5921 }
5922
5923 void
5924 Editor::split_region_at_transients ()
5925 {
5926         AnalysisFeatureList positions;
5927
5928         if (!_session) {
5929                 return;
5930         }
5931
5932         RegionSelection rs;
5933
5934         get_regions_for_action (rs);
5935
5936         if (rs.empty()) {
5937                 return;
5938         }
5939
5940         _session->begin_reversible_command (_("split regions"));
5941
5942         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5943
5944                 RegionSelection::iterator tmp;
5945
5946                 tmp = i;
5947                 ++tmp;
5948
5949                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5950
5951                 if (ar && (ar->get_transients (positions) == 0)) {
5952                         split_region_at_points ((*i)->region(), positions, true);
5953                         positions.clear ();
5954                 }
5955
5956                 i = tmp;
5957         }
5958
5959         _session->commit_reversible_command ();
5960
5961 }
5962
5963 void
5964 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5965 {
5966         bool use_rhythmic_rodent = false;
5967
5968         boost::shared_ptr<Playlist> pl = r->playlist();
5969
5970         if (!pl) {
5971                 return;
5972         }
5973
5974         if (positions.empty()) {
5975                 return;
5976         }
5977
5978
5979         if (positions.size() > 20) {
5980                 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);
5981                 MessageDialog msg (msgstr,
5982                                    false,
5983                                    Gtk::MESSAGE_INFO,
5984                                    Gtk::BUTTONS_OK_CANCEL);
5985
5986                 if (can_ferret) {
5987                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5988                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5989                 } else {
5990                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5991                 }
5992
5993                 msg.set_title (_("Excessive split?"));
5994                 msg.present ();
5995
5996                 int response = msg.run();
5997                 msg.hide ();
5998                 
5999                 switch (response) {
6000                 case RESPONSE_OK:
6001                         break;
6002                 case RESPONSE_APPLY:
6003                         use_rhythmic_rodent = true;
6004                         break;
6005                 default:
6006                         return;
6007                 }
6008         }
6009
6010         if (use_rhythmic_rodent) {
6011                 show_rhythm_ferret ();
6012                 return;
6013         }
6014
6015         AnalysisFeatureList::const_iterator x;
6016
6017         pl->clear_changes ();
6018
6019         x = positions.begin();
6020
6021         if (x == positions.end()) {
6022                 return;
6023         }
6024
6025         pl->freeze ();
6026         pl->remove_region (r);
6027
6028         nframes64_t pos = 0;
6029
6030         while (x != positions.end()) {
6031           
6032                 /* deal with positons that are out of scope of present region bounds */
6033                 if (*x <= 0 || *x > r->length()){
6034                         ++x;
6035                         continue;
6036                 }
6037
6038                 /* file start = original start + how far we from the initial position ?
6039                  */
6040
6041                 nframes64_t file_start = r->start() + pos;
6042
6043                 /* length = next position - current position
6044                  */
6045
6046                 nframes64_t len = (*x) - pos;
6047                 
6048                 /* XXX we do we really want to allow even single-sample regions?
6049                    shouldn't we have some kind of lower limit on region size?
6050                 */
6051
6052                 if (len <= 0) {
6053                         break;
6054                 }
6055
6056                 string new_name;
6057
6058                 if (RegionFactory::region_name (new_name, r->name())) {
6059                         break;
6060                 }
6061
6062                 /* do NOT announce new regions 1 by one, just wait till they are all done */
6063
6064                 PropertyList plist; 
6065                 
6066                 plist.add (ARDOUR::Properties::start, file_start);
6067                 plist.add (ARDOUR::Properties::length, len);
6068                 plist.add (ARDOUR::Properties::name, new_name);
6069                 plist.add (ARDOUR::Properties::layer, 0);
6070
6071                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
6072                 pl->add_region (nr, r->position() + pos);
6073
6074                 pos += len;
6075                 ++x;
6076         }
6077
6078         string new_name;
6079
6080         RegionFactory::region_name (new_name, r->name());
6081         
6082         /* Add the final region */
6083         PropertyList plist; 
6084                 
6085         plist.add (ARDOUR::Properties::start, r->start() + pos);
6086         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
6087         plist.add (ARDOUR::Properties::name, new_name);
6088         plist.add (ARDOUR::Properties::layer, 0);
6089
6090         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
6091         pl->add_region (nr, r->position() + pos);
6092
6093         
6094         pl->thaw ();
6095
6096         _session->add_command (new StatefulDiffCommand (pl));
6097 }
6098
6099 void
6100 Editor::place_transient()
6101 {
6102         if (!_session) {
6103                 return;
6104         }
6105
6106         RegionSelection rs;
6107
6108         get_regions_for_action (rs);
6109
6110         if (rs.empty()) {
6111                 return;
6112         }
6113         
6114         nframes64_t where = get_preferred_edit_position();
6115
6116         _session->begin_reversible_command (_("place transient"));
6117         
6118         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6119                 framepos_t position = (*r)->region()->position();
6120                 (*r)->region()->add_transient(where - position);
6121         }
6122         
6123         _session->commit_reversible_command ();
6124 }
6125
6126 void
6127 Editor::remove_transient(ArdourCanvas::Item* item)
6128 {
6129         if (!_session) {
6130                 return;
6131         }
6132
6133         ArdourCanvas::SimpleLine* _line = reinterpret_cast<ArdourCanvas::SimpleLine*> (item);
6134         assert (_line);
6135
6136         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
6137         _arv->remove_transient(_line->property_x1());
6138 }
6139
6140 void
6141 Editor::snap_regions_to_grid()
6142 {
6143         if (!_session) {
6144                 return;
6145         }
6146
6147         RegionSelection rs;
6148
6149         get_regions_for_action (rs);
6150
6151         if (rs.empty()) {
6152                 return;
6153         }
6154         
6155         _session->begin_reversible_command (_("snap regions to grid"));
6156         
6157         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6158                 framepos_t start_frame = (*r)->region()->first_frame ();
6159                 snap_to (start_frame);
6160                 (*r)->region()->set_position (start_frame, this);
6161         }
6162         
6163         _session->commit_reversible_command ();
6164 }
6165
6166 void
6167 Editor::close_region_gaps()
6168 {       
6169         if (!_session) {
6170                 return;
6171         }
6172
6173         RegionSelection rs;
6174
6175         get_regions_for_action (rs);
6176         
6177         if (rs.empty()) {
6178                 return;
6179         }
6180         
6181         Dialog dialog (rs.size() > 1 ? _("Conform regions") : _("Conform region"));
6182         
6183         HBox hbox_crossfade;
6184         hbox_crossfade.set_spacing (10);
6185         //hbox_crossfade.set_border_width (3);
6186         hbox_crossfade.pack_start (*manage (new Label (_("Crossfade length:"))));
6187         
6188         SpinButton spin_crossfade (1, 0);
6189         spin_crossfade.set_range (0, 15);
6190         spin_crossfade.set_increments (1, 1);
6191         spin_crossfade.set_value (3);
6192         
6193         hbox_crossfade.pack_start (spin_crossfade);
6194         hbox_crossfade.pack_start (*manage (new Label (_("ms"))));
6195         hbox_crossfade.show_all ();
6196
6197         HBox hbox_pullback;
6198         
6199         hbox_pullback.set_spacing (10);
6200         //hbox_pullback.set_border_width (3);
6201         hbox_pullback.pack_start (*manage (new Label (_("Pull-back length:"))));
6202         
6203         SpinButton spin_pullback (1, 0);
6204         spin_pullback.set_range (0, 15);
6205         spin_pullback.set_increments (1, 1);
6206         spin_pullback.set_value (5);
6207         
6208         hbox_pullback.pack_start (spin_pullback);
6209         hbox_pullback.pack_start (*manage (new Label (_("ms"))));
6210         hbox_pullback.show_all ();
6211         
6212         dialog.get_vbox()->set_spacing (6);
6213         dialog.get_vbox()->pack_start (hbox_crossfade);
6214         dialog.get_vbox()->pack_start (hbox_pullback);
6215         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
6216         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
6217
6218         if (dialog.run () == RESPONSE_CANCEL) {
6219                 return;
6220         }
6221
6222         nframes64_t crossfade_len  = spin_crossfade.get_value(); 
6223         nframes64_t pull_back_frames = spin_pullback.get_value();
6224
6225         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
6226         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
6227
6228         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
6229         
6230         _session->begin_reversible_command (_("close region gaps"));
6231                 
6232         int idx = 0;
6233         boost::shared_ptr<Region> last_region;
6234         
6235         rs.sort_by_position_and_track();
6236         
6237         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6238
6239                 nframes64_t position = (*r)->region()->position();
6240           
6241                 if (idx == 0 || position < last_region->position()){
6242                         last_region = (*r)->region();
6243                         idx++;
6244                         continue;
6245                 }
6246                 
6247                 (*r)->region()->trim_front( (position - pull_back_frames), this );
6248                 last_region->trim_end( (position - pull_back_frames + crossfade_len), this );
6249                 
6250                 last_region = (*r)->region();
6251                 
6252                 idx++;
6253         }
6254         
6255         _session->commit_reversible_command ();
6256 }
6257
6258 void
6259 Editor::tab_to_transient (bool forward)
6260 {
6261         AnalysisFeatureList positions;
6262
6263         if (!_session) {
6264                 return;
6265         }
6266
6267         nframes64_t pos = _session->audible_frame ();
6268
6269         if (!selection->tracks.empty()) {
6270
6271                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
6272
6273                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
6274
6275                         if (rtv) {
6276                                 boost::shared_ptr<Track> tr = rtv->track();
6277                                 if (tr) {
6278                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
6279                                         if (pl) {
6280                                                 nframes64_t result = pl->find_next_transient (pos, forward ? 1 : -1);
6281
6282                                                 if (result >= 0) {
6283                                                         positions.push_back (result);
6284                                                 }
6285                                         }
6286                                 }
6287                         }
6288                 }
6289
6290         } else {
6291
6292                 RegionSelection rs;
6293
6294                 get_regions_for_action (rs);
6295
6296                 if (rs.empty()) {
6297                         return;
6298                 }
6299
6300                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6301                         (*r)->region()->get_transients (positions);
6302                 }
6303         }
6304
6305         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
6306
6307         if (forward) {
6308                 AnalysisFeatureList::iterator x;
6309
6310                 for (x = positions.begin(); x != positions.end(); ++x) {
6311                         if ((*x) > pos) {
6312                                 break;
6313                         }
6314                 }
6315
6316                 if (x != positions.end ()) {
6317                         _session->request_locate (*x);
6318                 }
6319
6320         } else {
6321                 AnalysisFeatureList::reverse_iterator x;
6322
6323                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6324                         if ((*x) < pos) {
6325                                 break;
6326                         }
6327                 }
6328
6329                 if (x != positions.rend ()) {
6330                         _session->request_locate (*x);
6331                 }
6332         }
6333 }
6334
6335 void
6336 Editor::playhead_forward_to_grid ()
6337 {
6338         if (!_session) return;
6339         nframes64_t pos = playhead_cursor->current_frame;
6340         if (pos < max_frames - 1) {
6341                 pos += 2;
6342                 snap_to_internal (pos, 1, false);
6343                 _session->request_locate (pos);
6344         }
6345 }
6346
6347
6348 void
6349 Editor::playhead_backward_to_grid ()
6350 {
6351         if (!_session) return;
6352         nframes64_t pos = playhead_cursor->current_frame;
6353         if (pos > 2) {
6354                 pos -= 2;
6355                 snap_to_internal (pos, -1, false);
6356                 _session->request_locate (pos);
6357         }
6358 }
6359
6360 void
6361 Editor::set_track_height (Height h)
6362 {
6363         TrackSelection& ts (selection->tracks);
6364
6365         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6366                 (*x)->set_height (h);
6367         }
6368 }
6369
6370 void
6371 Editor::toggle_tracks_active ()
6372 {
6373         TrackSelection& ts (selection->tracks);
6374         bool first = true;
6375         bool target = false;
6376
6377         if (ts.empty()) {
6378                 return;
6379         }
6380
6381         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6382                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6383
6384                 if (rtv) {
6385                         if (first) {
6386                                 target = !rtv->_route->active();
6387                                 first = false;
6388                         }
6389                         rtv->_route->set_active (target);
6390                 }
6391         }
6392 }
6393
6394 void
6395 Editor::remove_tracks ()
6396 {
6397         TrackSelection& ts (selection->tracks);
6398
6399         if (ts.empty()) {
6400                 return;
6401         }
6402
6403         vector<string> choices;
6404         string prompt;
6405         int ntracks = 0;
6406         int nbusses = 0;
6407         const char* trackstr;
6408         const char* busstr;
6409         vector<boost::shared_ptr<Route> > routes;
6410         bool special_bus = false;
6411
6412         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6413                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6414                 if (rtv) {
6415                         if (rtv->is_track()) {
6416                                 ntracks++;
6417                         } else {
6418                                 nbusses++;
6419                         }
6420                 }
6421                 routes.push_back (rtv->_route);
6422
6423                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6424                         special_bus = true;
6425                 }
6426         }
6427
6428         if (special_bus && !Config->get_allow_special_bus_removal()) {
6429                 MessageDialog msg (_("That would be bad news ...."),
6430                                    false,
6431                                    Gtk::MESSAGE_INFO,
6432                                    Gtk::BUTTONS_OK);
6433                 msg.set_secondary_text (string_compose (_(
6434 "Removing the master or monitor bus is such a bad idea\n\
6435 that %1 is not going to allow it.\n\
6436 \n\
6437 If you really want to do this sort of thing\n\
6438 edit your ardour.rc file to set the\n\
6439 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6440
6441                 msg.present ();
6442                 msg.run ();
6443                 return;
6444         }
6445                 
6446         if (ntracks + nbusses == 0) {
6447                 return;
6448         }
6449
6450         if (ntracks > 1) {
6451                 trackstr = _("tracks");
6452         } else {
6453                 trackstr = _("track");
6454         }
6455
6456         if (nbusses > 1) {
6457                 busstr = _("busses");
6458         } else {
6459                 busstr = _("bus");
6460         }
6461
6462         if (ntracks) {
6463                 if (nbusses) {
6464                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6465                                                     "(You may also lose the playlists associated with the %2)\n\n"
6466                                                     "This action cannot be undone, and the session file will be overwritten!"),
6467                                                   ntracks, trackstr, nbusses, busstr);
6468                 } else {
6469                         prompt  = string_compose (_("Do you really want to remove %1 %2?\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);
6473                 }
6474         } else if (nbusses) {
6475                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6476                                             "This action cannot be undon, and the session file will be overwritten"),
6477                                           nbusses, busstr);
6478         }
6479
6480         choices.push_back (_("No, do nothing."));
6481         if (ntracks + nbusses > 1) {
6482                 choices.push_back (_("Yes, remove them."));
6483         } else {
6484                 choices.push_back (_("Yes, remove it."));
6485         }
6486
6487         string title;
6488         if (ntracks) {
6489                 title = string_compose (_("Remove %1"), trackstr);
6490         } else {
6491                 title = string_compose (_("Remove %1"), busstr);
6492         }
6493
6494         Choice prompter (title, prompt, choices);
6495
6496         if (prompter.run () != 1) {
6497                 return;
6498         }
6499
6500         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6501                 _session->remove_route (*x);
6502         }
6503 }
6504
6505 void
6506 Editor::do_insert_time ()
6507 {
6508         if (selection->tracks.empty()) {
6509                 return;
6510         }
6511
6512         InsertTimeDialog d (*this);
6513         int response = d.run ();
6514
6515         if (response != RESPONSE_OK) {
6516                 return;
6517         }
6518
6519         if (d.distance() == 0) {
6520                 return;
6521         }
6522
6523         InsertTimeOption opt = d.intersected_region_action ();
6524
6525         insert_time (
6526                 get_preferred_edit_position(),
6527                 d.distance(),
6528                 opt,
6529                 d.move_glued(),
6530                 d.move_markers(),
6531                 d.move_glued_markers(),
6532                 d.move_locked_markers(),
6533                 d.move_tempos()
6534                 );
6535 }
6536
6537 void
6538 Editor::insert_time (nframes64_t pos, nframes64_t frames, InsertTimeOption opt,
6539                      bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too)
6540 {
6541         bool commit = false;
6542
6543         if (Config->get_edit_mode() == Lock) {
6544                 return;
6545         }
6546
6547         begin_reversible_command (_("insert time"));
6548
6549         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6550                 /* regions */
6551                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6552
6553                 if (pl) {
6554
6555                         pl->clear_changes ();
6556                         pl->clear_owned_changes ();
6557
6558                         if (opt == SplitIntersected) {
6559                                 pl->split (pos);
6560                         }
6561
6562                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6563
6564                         vector<Command*> cmds;
6565                         pl->rdiff (cmds);
6566                         _session->add_commands (cmds);
6567                         
6568                         _session->add_command (new StatefulDiffCommand (pl));
6569                         commit = true;
6570                 }
6571
6572                 /* automation */
6573                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6574                 if (rtav) {
6575                         rtav->route ()->shift (pos, frames);
6576                         commit = true;
6577                 }
6578         }
6579
6580         /* markers */
6581         if (markers_too) {
6582                 bool moved = false;
6583                 XMLNode& before (_session->locations()->get_state());
6584                 Locations::LocationList copy (_session->locations()->list());
6585
6586                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6587
6588                         Locations::LocationList::const_iterator tmp;
6589
6590                         bool const was_locked = (*i)->locked ();
6591                         if (locked_markers_too) {
6592                                 (*i)->unlock ();
6593                         }
6594
6595                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6596
6597                                 if ((*i)->start() >= pos) {
6598                                         (*i)->set_start ((*i)->start() + frames);
6599                                         if (!(*i)->is_mark()) {
6600                                                 (*i)->set_end ((*i)->end() + frames);
6601                                         }
6602                                         moved = true;
6603                                 }
6604                                 
6605                         }
6606
6607                         if (was_locked) {
6608                                 (*i)->lock ();
6609                         }
6610                 }
6611
6612                 if (moved) {
6613                         XMLNode& after (_session->locations()->get_state());
6614                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6615                 }
6616         }
6617
6618         if (tempo_too) {
6619                 _session->tempo_map().insert_time (pos, frames);
6620         }
6621
6622         if (commit) {
6623                 commit_reversible_command ();
6624         }
6625 }
6626
6627 void
6628 Editor::fit_selected_tracks ()
6629 {
6630         fit_tracks (selection->tracks);
6631 }
6632
6633 void
6634 Editor::fit_tracks (TrackViewList & tracks)
6635 {
6636         if (tracks.empty()) {
6637                 return;
6638         }
6639
6640         uint32_t child_heights = 0;
6641
6642         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6643
6644                 if (!(*t)->marked_for_display()) {
6645                         continue;
6646                 }
6647
6648                 child_heights += (*t)->effective_height() - (*t)->current_height();
6649         }
6650
6651         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6652         double first_y_pos = DBL_MAX;
6653
6654         if (h < TimeAxisView::preset_height (HeightSmall)) {
6655                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6656                 /* too small to be displayed */
6657                 return;
6658         }
6659
6660         undo_visual_stack.push_back (current_visual_state());
6661
6662         /* build a list of all tracks, including children */
6663
6664         TrackViewList all;
6665         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6666                 all.push_back (*i);
6667                 TimeAxisView::Children c = (*i)->get_child_list ();
6668                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6669                         all.push_back (j->get());
6670                 }
6671         }
6672
6673         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6674
6675         bool prev_was_selected = false;
6676         bool is_selected = tracks.contains (all.front());
6677         bool next_is_selected;
6678
6679         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6680
6681                 TrackViewList::iterator next;
6682
6683                 next = t;
6684                 ++next;
6685
6686                 if (next != all.end()) {
6687                         next_is_selected = tracks.contains (*next);
6688                 } else {
6689                         next_is_selected = false;
6690                 }
6691
6692                 if (is_selected) {
6693                         (*t)->set_height (h);
6694                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6695                 } else {
6696                         if (prev_was_selected && next_is_selected) {
6697                                 hide_track_in_display (*t);
6698                         }
6699                 }
6700
6701                 prev_was_selected = is_selected;
6702                 is_selected = next_is_selected;
6703         }
6704
6705         /*
6706            set the controls_layout height now, because waiting for its size
6707            request signal handler will cause the vertical adjustment setting to fail
6708         */
6709
6710         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6711         vertical_adjustment.set_value (first_y_pos);
6712
6713         redo_visual_stack.push_back (current_visual_state());
6714 }
6715
6716 void
6717 Editor::save_visual_state (uint32_t n)
6718 {
6719         while (visual_states.size() <= n) {
6720                 visual_states.push_back (0);
6721         }
6722
6723         delete visual_states[n];
6724
6725         visual_states[n] = current_visual_state (true);
6726         gdk_beep ();
6727 }
6728
6729 void
6730 Editor::goto_visual_state (uint32_t n)
6731 {
6732         if (visual_states.size() <= n) {
6733                 return;
6734         }
6735
6736         if (visual_states[n] == 0) {
6737                 return;
6738         }
6739
6740         use_visual_state (*visual_states[n]);
6741 }
6742
6743 void
6744 Editor::start_visual_state_op (uint32_t n)
6745 {
6746         if (visual_state_op_connection.empty()) {
6747                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6748         }
6749 }
6750
6751 void
6752 Editor::cancel_visual_state_op (uint32_t n)
6753 {
6754         if (!visual_state_op_connection.empty()) {
6755                 visual_state_op_connection.disconnect();
6756                 goto_visual_state (n);
6757         }  else {
6758                 //we land here if called from the menu OR if end_visual_state_op has been called
6759                 //so check if we are already in visual state n
6760                 // XXX not yet checking it at all, but redoing does not hurt
6761                 goto_visual_state (n);
6762         }
6763 }
6764
6765 bool
6766 Editor::end_visual_state_op (uint32_t n)
6767 {
6768         visual_state_op_connection.disconnect();
6769         save_visual_state (n);
6770
6771         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6772         char buf[32];
6773         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6774         pup->set_text (buf);
6775         pup->touch();
6776
6777         return false; // do not call again
6778 }
6779