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