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