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