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