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