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