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