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