Move region naming stuff from Session into RegionFactory, cleaning up some vestiges...
[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.5, 0.5);
2616
2617         interthread_progress_window->get_vbox()->pack_start (interthread_progress_label, false, false);
2618         interthread_progress_window->get_vbox()->pack_start (interthread_progress_bar,false, false);
2619
2620         // GTK2FIX: this button needs a modifiable label
2621
2622         Button* b = interthread_progress_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
2623         b->signal_clicked().connect (sigc::mem_fun(*this, &Editor::interthread_cancel_clicked));
2624
2625         interthread_cancel_button.add (interthread_cancel_label);
2626
2627         interthread_progress_window->set_default_size (200, 100);
2628 }
2629
2630 void
2631 Editor::interthread_cancel_clicked ()
2632 {
2633         if (current_interthread_info) {
2634                 current_interthread_info->cancel = true;
2635         }
2636 }
2637
2638 void
2639 Editor::region_from_selection ()
2640 {
2641         if (clicked_axisview == 0) {
2642                 return;
2643         }
2644
2645         if (selection->time.empty()) {
2646                 return;
2647         }
2648
2649         nframes64_t start = selection->time[clicked_selection].start;
2650         nframes64_t end = selection->time[clicked_selection].end;
2651
2652         TrackViewList tracks = get_tracks_for_range_action ();
2653
2654         nframes64_t selection_cnt = end - start + 1;
2655
2656         for (TrackSelection::iterator i = tracks.begin(); i != tracks.end(); ++i) {
2657                 boost::shared_ptr<Region> current;
2658                 boost::shared_ptr<Playlist> pl;
2659                 nframes64_t internal_start;
2660                 string new_name;
2661
2662                 if ((pl = (*i)->playlist()) == 0) {
2663                         continue;
2664                 }
2665
2666                 if ((current = pl->top_region_at (start)) == 0) {
2667                         continue;
2668                 }
2669
2670                 internal_start = start - current->position();
2671                 RegionFactory::region_name (new_name, current->name(), true);
2672
2673                 PropertyList plist; 
2674                 
2675                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2676                 plist.add (ARDOUR::Properties::length, selection_cnt);
2677                 plist.add (ARDOUR::Properties::name, new_name);
2678                 plist.add (ARDOUR::Properties::layer, 0);
2679
2680                 boost::shared_ptr<Region> region (RegionFactory::create (current, plist));
2681         }
2682 }
2683
2684 void
2685 Editor::create_region_from_selection (vector<boost::shared_ptr<Region> >& new_regions)
2686 {
2687         if (selection->time.empty() || selection->tracks.empty()) {
2688                 return;
2689         }
2690
2691         nframes64_t start = selection->time[clicked_selection].start;
2692         nframes64_t end = selection->time[clicked_selection].end;
2693
2694         sort_track_selection ();
2695
2696         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
2697                 boost::shared_ptr<Region> current;
2698                 boost::shared_ptr<Playlist> playlist;
2699                 nframes64_t internal_start;
2700                 string new_name;
2701
2702                 if ((playlist = (*i)->playlist()) == 0) {
2703                         continue;
2704                 }
2705
2706                 if ((current = playlist->top_region_at(start)) == 0) {
2707                         continue;
2708                 }
2709
2710                 internal_start = start - current->position();
2711                 RegionFactory::region_name (new_name, current->name(), true);
2712
2713                 PropertyList plist; 
2714                 
2715                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2716                 plist.add (ARDOUR::Properties::length, end - start + 1);
2717                 plist.add (ARDOUR::Properties::name, new_name);
2718
2719                 new_regions.push_back (RegionFactory::create (current, plist));
2720         }
2721 }
2722
2723 void
2724 Editor::split_multichannel_region ()
2725 {
2726         RegionSelection rs;
2727
2728         get_regions_for_action (rs);
2729
2730         if (rs.empty()) {
2731                 return;
2732         }
2733
2734         vector< boost::shared_ptr<Region> > v;
2735
2736         for (list<RegionView*>::iterator x = rs.begin(); x != rs.end(); ++x) {
2737                 (*x)->region()->separate_by_channel (*_session, v);
2738         }
2739 }
2740
2741 void
2742 Editor::new_region_from_selection ()
2743 {
2744         region_from_selection ();
2745         cancel_selection ();
2746 }
2747
2748 static void
2749 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
2750 {
2751         switch (rv->region()->coverage (ar->start, ar->end - 1)) {
2752         case OverlapNone:
2753                 break;
2754         default:
2755                 rs->push_back (rv);
2756         }
2757 }
2758
2759 /** Return either:
2760  *    - selected tracks, or if there are none...
2761  *    - tracks containing selected regions, or if there are none...
2762  *    - all tracks
2763  * @return tracks.
2764  */
2765 TrackViewList
2766 Editor::get_tracks_for_range_action () const
2767 {
2768         TrackViewList t;
2769
2770         if (selection->tracks.empty()) {
2771
2772                 /* use tracks with selected regions */
2773
2774                 RegionSelection rs = selection->regions;
2775
2776                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2777                         TimeAxisView* tv = &(*i)->get_time_axis_view();
2778
2779                         if (!t.contains (tv)) {
2780                                 t.push_back (tv);
2781                         }
2782                 }
2783
2784                 if (t.empty()) {
2785                         /* no regions and no tracks: use all tracks */
2786                         t = track_views;
2787                 }
2788
2789         } else {
2790
2791                 t = selection->tracks;
2792         }
2793
2794         return t;
2795 }
2796
2797 void
2798 Editor::separate_regions_between (const TimeSelection& ts)
2799 {
2800         bool in_command = false;
2801         boost::shared_ptr<Playlist> playlist;
2802         RegionSelection new_selection;
2803
2804         TrackViewList tmptracks = get_tracks_for_range_action ();
2805         sort_track_selection (&tmptracks);
2806
2807         for (TrackSelection::iterator i = tmptracks.begin(); i != tmptracks.end(); ++i) {
2808
2809                 RouteTimeAxisView* rtv;
2810
2811                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2812
2813                         if (rtv->is_track()) {
2814
2815                                 /* no edits to destructive tracks */
2816
2817                                 if (rtv->track()->diskstream()->destructive()) {
2818                                         continue;
2819                                 }
2820
2821                                 if ((playlist = rtv->playlist()) != 0) {
2822
2823                                         playlist->clear_history ();
2824
2825                                         /* XXX need to consider musical time selections here at some point */
2826
2827                                         double speed = rtv->get_diskstream()->speed();
2828
2829
2830                                         for (list<AudioRange>::const_iterator t = ts.begin(); t != ts.end(); ++t) {
2831
2832                                                 sigc::connection c = rtv->view()->RegionViewAdded.connect (
2833                                                                 sigc::mem_fun(*this, &Editor::collect_new_region_view));
2834                                                 latest_regionviews.clear ();
2835
2836                                                 playlist->partition ((nframes64_t)((*t).start * speed),
2837                                                                 (nframes64_t)((*t).end * speed), true);
2838
2839                                                 c.disconnect ();
2840
2841                                                 if (!latest_regionviews.empty()) {
2842
2843                                                         rtv->view()->foreach_regionview (sigc::bind (
2844                                                                                 sigc::ptr_fun (add_if_covered),
2845                                                                                 &(*t), &new_selection));
2846                                                         
2847                                                         if (!in_command) {
2848                                                                 begin_reversible_command (_("separate"));
2849                                                                 in_command = true;
2850                                                         }
2851
2852                                                         _session->add_command(new StatefulDiffCommand (playlist));
2853                                                 }
2854                                         }
2855                                 }
2856                         }
2857                 }
2858         }
2859
2860         if (in_command) {
2861                 selection->set (new_selection);
2862                 set_mouse_mode (MouseObject);
2863
2864                 commit_reversible_command ();
2865         }
2866 }
2867
2868 /** Take tracks from get_tracks_for_range_action and cut any regions
2869  *  on those tracks so that the tracks are empty over the time
2870  *  selection.
2871  */
2872 void
2873 Editor::separate_region_from_selection ()
2874 {
2875         /* preferentially use *all* ranges in the time selection if we're in range mode
2876            to allow discontiguous operation, since get_edit_op_range() currently
2877            returns a single range.
2878         */
2879
2880         if (mouse_mode == MouseRange && !selection->time.empty()) {
2881
2882                 separate_regions_between (selection->time);
2883
2884         } else {
2885
2886                 nframes64_t start;
2887                 nframes64_t end;
2888
2889                 if (get_edit_op_range (start, end)) {
2890
2891                         AudioRange ar (start, end, 1);
2892                         TimeSelection ts;
2893                         ts.push_back (ar);
2894
2895                         separate_regions_between (ts);
2896                 }
2897         }
2898 }
2899
2900 void
2901 Editor::separate_region_from_punch ()
2902 {
2903         Location* loc  = _session->locations()->auto_punch_location();
2904         if (loc) {
2905                 separate_regions_using_location (*loc);
2906         }
2907 }
2908
2909 void
2910 Editor::separate_region_from_loop ()
2911 {
2912         Location* loc  = _session->locations()->auto_loop_location();
2913         if (loc) {
2914                 separate_regions_using_location (*loc);
2915         }
2916 }
2917
2918 void
2919 Editor::separate_regions_using_location (Location& loc)
2920 {
2921         if (loc.is_mark()) {
2922                 return;
2923         }
2924
2925         AudioRange ar (loc.start(), loc.end(), 1);
2926         TimeSelection ts;
2927
2928         ts.push_back (ar);
2929
2930         separate_regions_between (ts);
2931 }
2932
2933 void
2934 Editor::crop_region_to_selection ()
2935 {
2936         if (!selection->time.empty()) {
2937
2938                 crop_region_to (selection->time.start(), selection->time.end_frame());
2939
2940         } else {
2941
2942                 nframes64_t start;
2943                 nframes64_t end;
2944
2945                 if (get_edit_op_range (start, end)) {
2946                         crop_region_to (start, end);
2947                 }
2948         }
2949
2950 }
2951
2952 void
2953 Editor::crop_region_to (nframes64_t start, nframes64_t end)
2954 {
2955         vector<boost::shared_ptr<Playlist> > playlists;
2956         boost::shared_ptr<Playlist> playlist;
2957         TrackViewList* ts;
2958
2959         if (selection->tracks.empty()) {
2960                 ts = &track_views;
2961         } else {
2962                 sort_track_selection ();
2963                 ts = &selection->tracks;
2964         }
2965
2966         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
2967
2968                 RouteTimeAxisView* rtv;
2969
2970                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2971
2972                         boost::shared_ptr<Track> t = rtv->track();
2973
2974                         if (t != 0 && ! t->diskstream()->destructive()) {
2975
2976                                 if ((playlist = rtv->playlist()) != 0) {
2977                                         playlists.push_back (playlist);
2978                                 }
2979                         }
2980                 }
2981         }
2982
2983         if (playlists.empty()) {
2984                 return;
2985         }
2986
2987         nframes64_t the_start;
2988         nframes64_t the_end;
2989         nframes64_t cnt;
2990
2991         begin_reversible_command (_("trim to selection"));
2992
2993         for (vector<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2994
2995                 boost::shared_ptr<Region> region;
2996
2997                 the_start = start;
2998
2999                 if ((region = (*i)->top_region_at(the_start)) == 0) {
3000                         continue;
3001                 }
3002
3003                 /* now adjust lengths to that we do the right thing
3004                    if the selection extends beyond the region
3005                 */
3006
3007                 the_start = max (the_start, (nframes64_t) region->position());
3008                 if (max_frames - the_start < region->length()) {
3009                         the_end = the_start + region->length() - 1;
3010                 } else {
3011                         the_end = max_frames;
3012                 }
3013                 the_end = min (end, the_end);
3014                 cnt = the_end - the_start + 1;
3015
3016                 region->clear_history ();
3017                 region->trim_to (the_start, cnt, this);
3018                 _session->add_command (new StatefulDiffCommand (region));
3019         }
3020
3021         commit_reversible_command ();
3022 }
3023
3024 void
3025 Editor::region_fill_track ()
3026 {
3027         nframes64_t end;
3028         RegionSelection rs;
3029
3030         get_regions_for_action (rs);
3031
3032         if (!_session || rs.empty()) {
3033                 return;
3034         }
3035
3036         end = _session->current_end_frame ();
3037
3038         begin_reversible_command (_("region fill"));
3039
3040         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3041
3042                 boost::shared_ptr<Region> region ((*i)->region());
3043
3044                 boost::shared_ptr<Playlist> pl = region->playlist();
3045
3046                 if (end <= region->last_frame()) {
3047                         return;
3048                 }
3049
3050                 double times = (double) (end - region->last_frame()) / (double) region->length();
3051
3052                 if (times == 0) {
3053                         return;
3054                 }
3055
3056                 pl->clear_history ();
3057                 pl->add_region (RegionFactory::create (region), region->last_frame(), times);
3058                 _session->add_command (new StatefulDiffCommand (pl));
3059         }
3060
3061         commit_reversible_command ();
3062 }
3063
3064 void
3065 Editor::region_fill_selection ()
3066 {
3067         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3068                 return;
3069         }
3070
3071         if (selection->time.empty()) {
3072                 return;
3073         }
3074
3075         boost::shared_ptr<Region> region = _regions->get_single_selection ();
3076         if (region == 0) {
3077                 return;
3078         }
3079
3080         nframes64_t start = selection->time[clicked_selection].start;
3081         nframes64_t end = selection->time[clicked_selection].end;
3082
3083         boost::shared_ptr<Playlist> playlist;
3084
3085         if (selection->tracks.empty()) {
3086                 return;
3087         }
3088
3089         nframes64_t selection_length = end - start;
3090         float times = (float)selection_length / region->length();
3091
3092         begin_reversible_command (_("fill selection"));
3093
3094         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3095
3096                 if ((playlist = (*i)->playlist()) == 0) {
3097                         continue;
3098                 }
3099
3100                 playlist->clear_history ();
3101                 playlist->add_region (RegionFactory::create (region), start, times);
3102                 _session->add_command (new StatefulDiffCommand (playlist));
3103         }
3104
3105         commit_reversible_command ();
3106 }
3107
3108 void
3109 Editor::set_region_sync_from_edit_point ()
3110 {
3111         nframes64_t where = get_preferred_edit_position ();
3112         RegionSelection rs;
3113         get_regions_for_action (rs);
3114         set_sync_point (where, rs);
3115 }
3116
3117 void
3118 Editor::set_sync_point (nframes64_t where, const RegionSelection& rs)
3119 {
3120         bool in_command = false;
3121
3122         for (RegionSelection::const_iterator r = rs.begin(); r != rs.end(); ++r) {
3123
3124                 if (!(*r)->region()->covers (where)) {
3125                         continue;
3126                 }
3127
3128                 boost::shared_ptr<Region> region ((*r)->region());
3129
3130                 if (!in_command) {
3131                         begin_reversible_command (_("set sync point"));
3132                         in_command = true;
3133                 }
3134
3135                 region->clear_history ();
3136                 region->set_sync_position (where);
3137                 _session->add_command(new StatefulDiffCommand (region));
3138         }
3139
3140         if (in_command) {
3141                 commit_reversible_command ();
3142         }
3143 }
3144
3145 /** Remove the sync positions of the selection */
3146 void
3147 Editor::remove_region_sync ()
3148 {
3149         RegionSelection rs;
3150
3151         get_regions_for_action (rs);
3152
3153         if (rs.empty()) {
3154                 return;
3155         }
3156
3157         begin_reversible_command (_("remove sync"));
3158         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3159
3160                 (*i)->region()->clear_history ();
3161                 (*i)->region()->clear_sync_position ();
3162                 _session->add_command(new StatefulDiffCommand ((*i)->region()));
3163         }
3164         commit_reversible_command ();
3165 }
3166
3167 void
3168 Editor::naturalize ()
3169 {
3170         RegionSelection rs;
3171
3172         get_regions_for_action (rs);
3173
3174         if (rs.empty()) {
3175                 return;
3176         }
3177
3178         begin_reversible_command (_("naturalize"));
3179         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3180                 (*i)->region()->clear_history ();
3181                 (*i)->region()->move_to_natural_position (this);
3182                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
3183         }
3184         commit_reversible_command ();
3185 }
3186
3187 void
3188 Editor::align (RegionPoint what)
3189 {
3190         RegionSelection rs;
3191
3192         get_regions_for_action (rs);
3193         nframes64_t where = get_preferred_edit_position();
3194
3195         if (!rs.empty()) {
3196                 align_selection (what, where, rs);
3197         } else {
3198
3199                 RegionSelection rs;
3200                 get_regions_at (rs, where, selection->tracks);
3201                 align_selection (what, where, rs);
3202         }
3203 }
3204
3205 void
3206 Editor::align_relative (RegionPoint what)
3207 {
3208         nframes64_t where = get_preferred_edit_position();
3209         RegionSelection rs;
3210
3211         get_regions_for_action (rs);
3212
3213         if (!rs.empty()) {
3214                 align_selection_relative (what, where, rs);
3215         }
3216 }
3217
3218 struct RegionSortByTime {
3219     bool operator() (const RegionView* a, const RegionView* b) {
3220             return a->region()->position() < b->region()->position();
3221     }
3222 };
3223
3224 void
3225 Editor::align_selection_relative (RegionPoint point, nframes64_t position, const RegionSelection& rs)
3226 {
3227         if (rs.empty()) {
3228                 return;
3229         }
3230
3231         nframes64_t distance = 0;
3232         nframes64_t pos = 0;
3233         int dir = 1;
3234
3235         list<RegionView*> sorted;
3236         rs.by_position (sorted);
3237
3238         boost::shared_ptr<Region> r ((*sorted.begin())->region());
3239
3240         switch (point) {
3241         case Start:
3242                 pos = position;
3243                 if (position > r->position()) {
3244                         distance = position - r->position();
3245                 } else {
3246                         distance = r->position() - position;
3247                         dir = -1;
3248                 }
3249                 break;
3250
3251         case End:
3252                 if (position > r->last_frame()) {
3253                         distance = position - r->last_frame();
3254                         pos = r->position() + distance;
3255                 } else {
3256                         distance = r->last_frame() - position;
3257                         pos = r->position() - distance;
3258                         dir = -1;
3259                 }
3260                 break;
3261
3262         case SyncPoint:
3263                 pos = r->adjust_to_sync (position);
3264                 if (pos > r->position()) {
3265                         distance = pos - r->position();
3266                 } else {
3267                         distance = r->position() - pos;
3268                         dir = -1;
3269                 }
3270                 break;
3271         }
3272
3273         if (pos == r->position()) {
3274                 return;
3275         }
3276
3277         begin_reversible_command (_("align selection (relative)"));
3278
3279         /* move first one specially */
3280
3281         r->clear_history ();
3282         r->set_position (pos, this);
3283         _session->add_command(new StatefulDiffCommand (r));
3284
3285         /* move rest by the same amount */
3286
3287         sorted.pop_front();
3288
3289         for (list<RegionView*>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
3290
3291                 boost::shared_ptr<Region> region ((*i)->region());
3292
3293                 region->clear_history ();
3294
3295                 if (dir > 0) {
3296                         region->set_position (region->position() + distance, this);
3297                 } else {
3298                         region->set_position (region->position() - distance, this);
3299                 }
3300                 
3301                 _session->add_command(new StatefulDiffCommand (region));
3302
3303         }
3304
3305         commit_reversible_command ();
3306 }
3307
3308 void
3309 Editor::align_selection (RegionPoint point, nframes64_t position, const RegionSelection& rs)
3310 {
3311         if (rs.empty()) {
3312                 return;
3313         }
3314
3315         begin_reversible_command (_("align selection"));
3316
3317         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
3318                 align_region_internal ((*i)->region(), point, position);
3319         }
3320
3321         commit_reversible_command ();
3322 }
3323
3324 void
3325 Editor::align_region (boost::shared_ptr<Region> region, RegionPoint point, nframes64_t position)
3326 {
3327         begin_reversible_command (_("align region"));
3328         align_region_internal (region, point, position);
3329         commit_reversible_command ();
3330 }
3331
3332 void
3333 Editor::align_region_internal (boost::shared_ptr<Region> region, RegionPoint point, nframes64_t position)
3334 {
3335         region->clear_history ();
3336
3337         switch (point) {
3338         case SyncPoint:
3339                 region->set_position (region->adjust_to_sync (position), this);
3340                 break;
3341
3342         case End:
3343                 if (position > region->length()) {
3344                         region->set_position (position - region->length(), this);
3345                 }
3346                 break;
3347
3348         case Start:
3349                 region->set_position (position, this);
3350                 break;
3351         }
3352
3353         _session->add_command(new StatefulDiffCommand (region));
3354 }
3355
3356 void
3357 Editor::trim_region_front ()
3358 {
3359         trim_region (true);
3360 }
3361
3362 void
3363 Editor::trim_region_back ()
3364 {
3365         trim_region (false);
3366 }
3367
3368 void
3369 Editor::trim_region (bool front)
3370 {
3371         nframes64_t where = get_preferred_edit_position();
3372         RegionSelection rs;
3373
3374         get_regions_for_action (rs);
3375
3376         if (rs.empty()) {
3377                 return;
3378         }
3379
3380         begin_reversible_command (front ? _("trim front") : _("trim back"));
3381
3382         for (list<RegionView*>::const_iterator i = rs.by_layer().begin(); i != rs.by_layer().end(); ++i) {
3383                 if (!(*i)->region()->locked()) {
3384                         (*i)->region()->clear_history ();
3385                         if (front) {
3386                                 (*i)->region()->trim_front (where, this);
3387                         } else {
3388                                 (*i)->region()->trim_end (where, this);
3389                         }
3390                         _session->add_command (new StatefulDiffCommand ((*i)->region()));
3391                 }
3392         }
3393
3394         commit_reversible_command ();
3395 }
3396
3397 /** Trim the end of the selected regions to the position of the edit cursor */
3398 void
3399 Editor::trim_region_to_loop ()
3400 {
3401         Location* loc = _session->locations()->auto_loop_location();
3402         if (!loc) {
3403                 return;
3404         }
3405         trim_region_to_location (*loc, _("trim to loop"));
3406 }
3407
3408 void
3409 Editor::trim_region_to_punch ()
3410 {
3411         Location* loc = _session->locations()->auto_punch_location();
3412         if (!loc) {
3413                 return;
3414         }
3415         trim_region_to_location (*loc, _("trim to punch"));
3416 }
3417 void
3418 Editor::trim_region_to_location (const Location& loc, const char* str)
3419 {
3420         RegionSelection rs;
3421
3422         get_regions_for_action (rs);
3423
3424         begin_reversible_command (str);
3425
3426         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3427                 RegionView* rv = (*x);
3428
3429                 /* require region to span proposed trim */
3430                 switch (rv->region()->coverage (loc.start(), loc.end())) {
3431                 case OverlapInternal:
3432                         break;
3433                 default:
3434                         continue;
3435                 }
3436
3437                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3438                 if (!tav) {
3439                         return;
3440                 }
3441
3442                 float speed = 1.0;
3443                 nframes64_t start;
3444                 nframes64_t end;
3445
3446                 if (tav->get_diskstream() != 0) {
3447                         speed = tav->get_diskstream()->speed();
3448                 }
3449
3450                 start = session_frame_to_track_frame (loc.start(), speed);
3451                 end = session_frame_to_track_frame (loc.end(), speed);
3452                 
3453                 rv->region()->clear_history ();
3454                 rv->region()->trim_to (start, (end - start), this);
3455                 _session->add_command(new StatefulDiffCommand (rv->region()));
3456         }
3457
3458         commit_reversible_command ();
3459 }
3460
3461 void
3462 Editor::trim_region_to_edit_point ()
3463 {
3464         RegionSelection rs;
3465
3466         get_regions_for_action (rs);
3467
3468         nframes64_t where = get_preferred_edit_position();
3469
3470         begin_reversible_command (_("trim region start to edit point"));
3471
3472         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3473                 RegionView* rv = (*x);
3474
3475                 /* require region to cover trim */
3476                 if (!rv->region()->covers (where)) {
3477                         continue;
3478                 }
3479
3480                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3481                 if (!tav) {
3482                         return;
3483                 }
3484
3485                 float speed = 1.0;
3486
3487                 if (tav->get_diskstream() != 0) {
3488                         speed = tav->get_diskstream()->speed();
3489                 }
3490
3491                 rv->region()->clear_history ();
3492                 rv->region()->trim_end (session_frame_to_track_frame(where, speed), this);
3493                 _session->add_command(new StatefulDiffCommand (rv->region()));
3494         }
3495
3496         commit_reversible_command ();
3497 }
3498
3499 void
3500 Editor::trim_region_from_edit_point ()
3501 {
3502         RegionSelection rs;
3503
3504         get_regions_for_action (rs);
3505
3506         nframes64_t where = get_preferred_edit_position();
3507
3508         begin_reversible_command (_("trim region end to edit point"));
3509
3510         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3511                 RegionView* rv = (*x);
3512
3513                 /* require region to cover trim */
3514                 if (!rv->region()->covers (where)) {
3515                         continue;
3516                 }
3517
3518                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3519                 if (!tav) {
3520                         return;
3521                 }
3522
3523                 float speed = 1.0;
3524
3525                 if (tav->get_diskstream() != 0) {
3526                         speed = tav->get_diskstream()->speed();
3527                 }
3528
3529                 rv->region()->clear_history ();
3530                 rv->region()->trim_front (session_frame_to_track_frame(where, speed), this);
3531                 _session->add_command(new StatefulDiffCommand (rv->region()));
3532         }
3533
3534         commit_reversible_command ();
3535 }
3536
3537 void
3538 Editor::trim_region_to_previous_region_end ()
3539 {
3540         return trim_to_region(false);
3541 }
3542
3543 void
3544 Editor::trim_region_to_next_region_start ()
3545 {
3546         return trim_to_region(true);
3547 }
3548
3549 void
3550 Editor::trim_to_region(bool forward)
3551 {
3552         RegionSelection rs;
3553
3554         get_regions_for_action (rs);
3555
3556         begin_reversible_command (_("trim to region"));
3557
3558         boost::shared_ptr<Region> next_region;
3559
3560         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3561
3562                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*x);
3563
3564                 if (!arv) {
3565                         continue;
3566                 }
3567
3568                 AudioTimeAxisView* atav = dynamic_cast<AudioTimeAxisView*> (&arv->get_time_axis_view());
3569
3570                 if (!atav) {
3571                         return;
3572                 }
3573
3574                 float speed = 1.0;
3575
3576                 if (atav->get_diskstream() != 0) {
3577                         speed = atav->get_diskstream()->speed();
3578                 }
3579
3580
3581                 boost::shared_ptr<Region> region = arv->region();
3582                 boost::shared_ptr<Playlist> playlist (region->playlist());
3583
3584                 region->clear_history ();
3585
3586                 if(forward){
3587
3588                     next_region = playlist->find_next_region (region->first_frame(), Start, 1);
3589
3590                     if(!next_region){
3591                         continue;
3592                     }
3593
3594                     region->trim_end((nframes64_t) (next_region->first_frame() * speed), this);
3595                     arv->region_changed (PropertyChange (ARDOUR::Properties::length));
3596                 }
3597                 else {
3598
3599                     next_region = playlist->find_next_region (region->first_frame(), Start, 0);
3600
3601                     if(!next_region){
3602                         continue;
3603                     }
3604
3605                     region->trim_front((nframes64_t) ((next_region->last_frame() + 1) * speed), this);
3606
3607                     arv->region_changed (ARDOUR::bounds_change);
3608                 }
3609
3610                 _session->add_command(new StatefulDiffCommand (region));
3611         }
3612
3613         commit_reversible_command ();
3614 }
3615
3616 void
3617 Editor::unfreeze_route ()
3618 {
3619         if (clicked_routeview == 0 || !clicked_routeview->is_track()) {
3620                 return;
3621         }
3622
3623         clicked_routeview->track()->unfreeze ();
3624 }
3625
3626 void*
3627 Editor::_freeze_thread (void* arg)
3628 {
3629         SessionEvent::create_per_thread_pool ("freeze events", 64);
3630
3631         return static_cast<Editor*>(arg)->freeze_thread ();
3632 }
3633
3634 void*
3635 Editor::freeze_thread ()
3636 {
3637         clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
3638         current_interthread_info->done = true;
3639         return 0;
3640 }
3641
3642 gint
3643 Editor::freeze_progress_timeout (void */*arg*/)
3644 {
3645         interthread_progress_bar.set_fraction (current_interthread_info->progress);
3646         return !(current_interthread_info->done || current_interthread_info->cancel);
3647 }
3648
3649 void
3650 Editor::freeze_route ()
3651 {
3652         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3653                 return;
3654         }
3655
3656         InterThreadInfo itt;
3657
3658         if (interthread_progress_window == 0) {
3659                 build_interthread_progress_window ();
3660         }
3661
3662         interthread_progress_window->set_title (_("Freeze"));
3663         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
3664         interthread_progress_window->show_all ();
3665         interthread_progress_bar.set_fraction (0.0f);
3666         interthread_progress_label.set_text ("");
3667         interthread_cancel_label.set_text (_("Cancel Freeze"));
3668         current_interthread_info = &itt;
3669
3670         interthread_progress_connection =
3671           Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun(*this, &Editor::freeze_progress_timeout), (gpointer) 0), 100);
3672
3673         itt.done = false;
3674         itt.cancel = false;
3675         itt.progress = 0.0f;
3676
3677         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3678
3679         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
3680
3681         while (!itt.done && !itt.cancel) {
3682                 gtk_main_iteration ();
3683         }
3684
3685         interthread_progress_connection.disconnect ();
3686         interthread_progress_window->hide_all ();
3687         current_interthread_info = 0;
3688         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
3689 }
3690
3691 void
3692 Editor::bounce_range_selection (bool replace, bool enable_processing)
3693 {
3694         if (selection->time.empty()) {
3695                 return;
3696         }
3697
3698         TrackSelection views = selection->tracks;
3699
3700         nframes64_t start = selection->time[clicked_selection].start;
3701         nframes64_t end = selection->time[clicked_selection].end;
3702         nframes64_t cnt = end - start + 1;
3703
3704         begin_reversible_command (_("bounce range"));
3705
3706         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3707
3708                 RouteTimeAxisView* rtv;
3709
3710                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3711                         continue;
3712                 }
3713
3714                 boost::shared_ptr<Playlist> playlist;
3715
3716                 if ((playlist = rtv->playlist()) == 0) {
3717                         return;
3718                 }
3719
3720                 InterThreadInfo itt;
3721
3722                 itt.done = false;
3723                 itt.cancel = false;
3724                 itt.progress = false;
3725
3726                 playlist->clear_history ();
3727                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3728
3729                 if (replace) {
3730                         list<AudioRange> ranges;
3731                         ranges.push_back (AudioRange (start, start+cnt, 0));
3732                         playlist->cut (ranges); // discard result
3733                         playlist->add_region (r, start);
3734                 }
3735
3736                 _session->add_command (new StatefulDiffCommand (playlist));
3737         }
3738
3739         commit_reversible_command ();
3740 }
3741
3742 /** Cut selected regions, automation points or a time range */
3743 void
3744 Editor::cut ()
3745 {
3746         cut_copy (Cut);
3747 }
3748
3749 /** Copy selected regions, automation points or a time range */
3750 void
3751 Editor::copy ()
3752 {
3753         cut_copy (Copy);
3754 }
3755
3756
3757 /** @return true if a Cut, Copy or Clear is possible */
3758 bool
3759 Editor::can_cut_copy () const
3760 {
3761         switch (current_mouse_mode()) {
3762
3763         case MouseObject:
3764                 if (!selection->regions.empty() || !selection->points.empty()) {
3765                         return true;
3766                 }
3767                 break;
3768
3769         case MouseRange:
3770                 if (!selection->time.empty()) {
3771                         return true;
3772                 }
3773                 break;
3774
3775         default:
3776                 break;
3777         }
3778
3779         return false;
3780 }
3781
3782
3783 /** Cut, copy or clear selected regions, automation points or a time range.
3784  * @param op Operation (Cut, Copy or Clear)
3785  */
3786 void
3787 Editor::cut_copy (CutCopyOp op)
3788 {
3789         /* only cancel selection if cut/copy is successful.*/
3790
3791         string opname;
3792
3793         switch (op) {
3794         case Cut:
3795                 opname = _("cut");
3796                 break;
3797         case Copy:
3798                 opname = _("copy");
3799                 break;
3800         case Clear:
3801                 opname = _("clear");
3802                 break;
3803         }
3804
3805         /* if we're deleting something, and the mouse is still pressed,
3806            the thing we started a drag for will be gone when we release
3807            the mouse button(s). avoid this. see part 2 at the end of
3808            this function.
3809         */
3810
3811         if (op == Cut || op == Clear) {
3812                 if (_drags->active ()) {
3813                         _drags->abort ();
3814                 }
3815         }
3816
3817         cut_buffer->clear ();
3818
3819         if (entered_marker) {
3820
3821                 /* cut/delete op while pointing at a marker */
3822
3823                 bool ignored;
3824                 Location* loc = find_location_from_marker (entered_marker, ignored);
3825
3826                 if (_session && loc) {
3827                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3828                 }
3829
3830                 _drags->break_drag ();
3831                 return;
3832         }
3833
3834         if (internal_editing()) {
3835
3836                 switch (current_mouse_mode()) {
3837                 case MouseObject:
3838                 case MouseRange:
3839                         cut_copy_midi (op);
3840                         break;
3841                 default:
3842                         break;
3843                 }
3844
3845         } else {
3846
3847                 RegionSelection rs;
3848
3849                 /* we only want to cut regions if some are selected */
3850
3851                 if (!selection->regions.empty()) {
3852                         get_regions_for_action (rs, false, false);
3853                 }
3854
3855                 switch (current_mouse_mode()) {
3856                 case MouseObject:
3857                         if (!rs.empty() || !selection->points.empty()) {
3858
3859                                 begin_reversible_command (opname + _(" objects"));
3860
3861                                 if (!rs.empty()) {
3862                                         cut_copy_regions (op, rs);
3863
3864                                         if (op == Cut) {
3865                                                 selection->clear_regions ();
3866                                         }
3867                                 }
3868
3869                                 if (!selection->points.empty()) {
3870                                         cut_copy_points (op);
3871
3872                                         if (op == Cut) {
3873                                                 selection->clear_points ();
3874                                         }
3875                                 }
3876
3877                                 commit_reversible_command ();
3878                                 break; // terminate case statement here
3879                         }
3880                         if (!selection->time.empty()) {
3881                                 /* don't cause suprises */
3882                                 break;
3883                         }
3884                         // fall thru if there was nothing selected
3885
3886                 case MouseRange:
3887                         if (selection->time.empty()) {
3888                                 nframes64_t start, end;
3889                                 if (!get_edit_op_range (start, end)) {
3890                                         return;
3891                                 }
3892                                 selection->set (start, end);
3893                         }
3894
3895                         begin_reversible_command (opname + _(" range"));
3896                         cut_copy_ranges (op);
3897                         commit_reversible_command ();
3898
3899                         if (op == Cut) {
3900                                 selection->clear_time ();
3901                         }
3902
3903                         break;
3904
3905                 default:
3906                         break;
3907                 }
3908         }
3909
3910         if (op == Cut || op == Clear) {
3911                 _drags->break_drag ();
3912         }
3913 }
3914
3915 /** Cut, copy or clear selected automation points.
3916  * @param op Operation (Cut, Copy or Clear)
3917  */
3918 void
3919 Editor::cut_copy_points (CutCopyOp op)
3920 {
3921         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3922
3923                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3924
3925                 if (atv) {
3926                         atv->cut_copy_clear_objects (selection->points, op);
3927                 }
3928         }
3929 }
3930
3931 /** Cut, copy or clear selected automation points.
3932  * @param op Operation (Cut, Copy or Clear)
3933  */
3934 void
3935 Editor::cut_copy_midi (CutCopyOp op)
3936 {
3937         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3938                 MidiRegionView* mrv = *i;
3939                 mrv->cut_copy_clear (op);
3940         }
3941 }
3942
3943 struct PlaylistMapping {
3944     TimeAxisView* tv;
3945     boost::shared_ptr<Playlist> pl;
3946
3947     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3948 };
3949
3950 /** Remove `clicked_regionview' */
3951 void
3952 Editor::remove_clicked_region ()
3953 {
3954         if (clicked_routeview == 0 || clicked_regionview == 0) {
3955                 return;
3956         }
3957
3958         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3959
3960         begin_reversible_command (_("remove region"));
3961         playlist->clear_history ();
3962         playlist->remove_region (clicked_regionview->region());
3963         _session->add_command(new StatefulDiffCommand (playlist));
3964         commit_reversible_command ();
3965 }
3966
3967
3968 /** Remove the selected regions */
3969 void
3970 Editor::remove_selected_regions ()
3971 {
3972         RegionSelection rs;
3973         get_regions_for_action (rs);
3974
3975         if (!_session) {
3976                 return;
3977         }
3978
3979         if (rs.empty()) {
3980                 return;
3981         }
3982
3983         begin_reversible_command (_("remove region"));
3984
3985         list<boost::shared_ptr<Region> > regions_to_remove;
3986
3987         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3988                 // we can't just remove the region(s) in this loop because
3989                 // this removes them from the RegionSelection, and they thus
3990                 // disappear from underneath the iterator, and the ++i above
3991                 // SEGVs in a puzzling fashion.
3992
3993                 // so, first iterate over the regions to be removed from rs and
3994                 // add them to the regions_to_remove list, and then
3995                 // iterate over the list to actually remove them.
3996
3997                 regions_to_remove.push_back ((*i)->region());
3998         }
3999
4000         vector<boost::shared_ptr<Playlist> > playlists;
4001
4002         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
4003
4004                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
4005
4006                 if (!playlist) {
4007                         // is this check necessary?
4008                         continue;
4009                 }
4010
4011                 vector<boost::shared_ptr<Playlist> >::iterator i;
4012
4013                 //only prep history if this is a new playlist.
4014                 for (i = playlists.begin(); i != playlists.end(); ++i) {
4015                         if ((*i) == playlist) {
4016                                 break;
4017                         }
4018                 }
4019
4020                 if (i == playlists.end()) {
4021
4022                         playlist->clear_history ();
4023                         playlist->freeze ();
4024
4025                         playlists.push_back (playlist);
4026                 }
4027
4028                 playlist->remove_region (*rl);
4029         }
4030
4031         vector<boost::shared_ptr<Playlist> >::iterator pl;
4032
4033         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
4034                 (*pl)->thaw ();
4035                 _session->add_command(new StatefulDiffCommand (*pl));
4036         }
4037
4038         commit_reversible_command ();
4039 }
4040
4041 /** Cut, copy or clear selected regions.
4042  * @param op Operation (Cut, Copy or Clear)
4043  */
4044 void
4045 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
4046 {
4047         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
4048            a map when we want ordered access to both elements. i think.
4049         */
4050
4051         vector<PlaylistMapping> pmap;
4052
4053         nframes64_t first_position = max_frames;
4054
4055         typedef set<boost::shared_ptr<Playlist> > FreezeList;
4056         FreezeList freezelist;
4057
4058         /* get ordering correct before we cut/copy */
4059
4060         rs.sort_by_position_and_track ();
4061
4062         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4063
4064                 first_position = min ((nframes64_t) (*x)->region()->position(), first_position);
4065
4066                 if (op == Cut || op == Clear) {
4067                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4068
4069                         if (pl) {
4070                                 FreezeList::iterator fl;
4071
4072                                 //only take state if this is a new playlist.
4073                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
4074                                         if ((*fl) == pl) {
4075                                                 break;
4076                                         }
4077                                 }
4078
4079                                 if (fl == freezelist.end()) {
4080                                         pl->clear_history();
4081                                         pl->freeze ();
4082                                         freezelist.insert (pl);
4083                                 }
4084                         }
4085                 }
4086
4087                 TimeAxisView* tv = &(*x)->get_trackview();
4088                 vector<PlaylistMapping>::iterator z;
4089
4090                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4091                         if ((*z).tv == tv) {
4092                                 break;
4093                         }
4094                 }
4095
4096                 if (z == pmap.end()) {
4097                         pmap.push_back (PlaylistMapping (tv));
4098                 }
4099         }
4100
4101         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
4102
4103                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4104
4105                 if (!pl) {
4106                         /* impossible, but this handles it for the future */
4107                         continue;
4108                 }
4109
4110                 TimeAxisView& tv = (*x)->get_trackview();
4111                 boost::shared_ptr<Playlist> npl;
4112                 RegionSelection::iterator tmp;
4113
4114                 tmp = x;
4115                 ++tmp;
4116
4117                 vector<PlaylistMapping>::iterator z;
4118
4119                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4120                         if ((*z).tv == &tv) {
4121                                 break;
4122                         }
4123                 }
4124
4125                 assert (z != pmap.end());
4126
4127                 if (!(*z).pl) {
4128                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4129                         npl->freeze();
4130                         (*z).pl = npl;
4131                 } else {
4132                         npl = (*z).pl;
4133                 }
4134
4135                 boost::shared_ptr<Region> r = (*x)->region();
4136                 boost::shared_ptr<Region> _xx;
4137
4138                 assert (r != 0);
4139
4140                 switch (op) {
4141                 case Cut:
4142                         _xx = RegionFactory::create (r);
4143                         npl->add_region (_xx, r->position() - first_position);
4144                         pl->remove_region (r);
4145                         break;
4146
4147                 case Copy:
4148                         /* copy region before adding, so we're not putting same object into two different playlists */
4149                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4150                         break;
4151
4152                 case Clear:
4153                         pl->remove_region (r);
4154                         break;
4155                 }
4156
4157                 x = tmp;
4158         }
4159
4160         list<boost::shared_ptr<Playlist> > foo;
4161
4162         /* the pmap is in the same order as the tracks in which selected regions occured */
4163
4164         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4165                 (*i).pl->thaw();
4166                 foo.push_back ((*i).pl);
4167         }
4168
4169
4170         if (!foo.empty()) {
4171                 cut_buffer->set (foo);
4172         }
4173         
4174         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4175                 (*pl)->thaw ();
4176                 _session->add_command (new StatefulDiffCommand (*pl));
4177         }
4178 }
4179
4180 void
4181 Editor::cut_copy_ranges (CutCopyOp op)
4182 {
4183         TrackViewList* ts;
4184         TrackViewList entered;
4185
4186         if (selection->tracks.empty()) {
4187                 if (!entered_track) {
4188                         return;
4189                 }
4190                 entered.push_back (entered_track);
4191                 ts = &entered;
4192         } else {
4193                 ts = &selection->tracks;
4194         }
4195
4196         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4197                 (*i)->cut_copy_clear (*selection, op);
4198         }
4199 }
4200
4201 void
4202 Editor::paste (float times)
4203 {
4204         paste_internal (get_preferred_edit_position(), times);
4205 }
4206
4207 void
4208 Editor::mouse_paste ()
4209 {
4210         nframes64_t where;
4211         bool ignored;
4212
4213         if (!mouse_frame (where, ignored)) {
4214                 return;
4215         }
4216
4217         snap_to (where);
4218         paste_internal (where, 1);
4219 }
4220
4221 void
4222 Editor::paste_internal (nframes64_t position, float times)
4223 {
4224         bool commit = false;
4225
4226         if (internal_editing()) {
4227                 if (cut_buffer->midi_notes.empty()) {
4228                         return;
4229                 }
4230         } else {
4231                 if (cut_buffer->empty()) {
4232                         return;
4233                 }
4234         }
4235
4236         if (position == max_frames) {
4237                 position = get_preferred_edit_position();
4238         }
4239
4240         begin_reversible_command (_("paste"));
4241
4242         TrackViewList ts;
4243         TrackViewList::iterator i;
4244         size_t nth;
4245
4246         /* get everything in the correct order */
4247
4248         if (!selection->tracks.empty()) {
4249                 sort_track_selection ();
4250                 ts = selection->tracks;
4251         } else if (entered_track) {
4252                 ts.push_back (entered_track);
4253         }
4254
4255         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4256
4257                 /* undo/redo is handled by individual tracks/regions */
4258
4259                 if (internal_editing()) {
4260
4261                         RegionSelection rs;
4262                         RegionSelection::iterator r;
4263                         MidiNoteSelection::iterator cb;
4264
4265                         get_regions_at (rs, position, ts);
4266
4267                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4268                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4269                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4270                                 if (mrv) {
4271                                         mrv->paste (position, times, **cb);
4272                                         ++cb;
4273                                 }
4274                         }
4275
4276                 } else {
4277
4278                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4279                                 commit = true;
4280                         }
4281                 }
4282         }
4283
4284         if (commit) {
4285                 commit_reversible_command ();
4286         }
4287 }
4288
4289 void
4290 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4291 {
4292         boost::shared_ptr<Playlist> playlist;
4293         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4294         RegionSelection foo;
4295
4296         nframes_t const start_frame = regions.start ();
4297         nframes_t const end_frame = regions.end_frame ();
4298
4299         begin_reversible_command (_("duplicate region"));
4300
4301         selection->clear_regions ();
4302
4303         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4304
4305                 boost::shared_ptr<Region> r ((*i)->region());
4306
4307                 TimeAxisView& tv = (*i)->get_time_axis_view();
4308                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4309                 latest_regionviews.clear ();
4310                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4311
4312                 playlist = (*i)->region()->playlist();
4313                 playlist->clear_history ();
4314                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame) + 1, times);
4315                 _session->add_command(new StatefulDiffCommand (playlist));
4316
4317                 c.disconnect ();
4318
4319                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4320         }
4321
4322         commit_reversible_command ();
4323
4324         if (!foo.empty()) {
4325                 selection->set (foo);
4326         }
4327 }
4328
4329 void
4330 Editor::duplicate_selection (float times)
4331 {
4332         if (selection->time.empty() || selection->tracks.empty()) {
4333                 return;
4334         }
4335
4336         boost::shared_ptr<Playlist> playlist;
4337         vector<boost::shared_ptr<Region> > new_regions;
4338         vector<boost::shared_ptr<Region> >::iterator ri;
4339
4340         create_region_from_selection (new_regions);
4341
4342         if (new_regions.empty()) {
4343                 return;
4344         }
4345
4346         begin_reversible_command (_("duplicate selection"));
4347
4348         ri = new_regions.begin();
4349
4350         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4351                 if ((playlist = (*i)->playlist()) == 0) {
4352                         continue;
4353                 }
4354                 playlist->clear_history ();
4355                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4356                 _session->add_command (new StatefulDiffCommand (playlist));
4357
4358                 ++ri;
4359                 if (ri == new_regions.end()) {
4360                         --ri;
4361                 }
4362         }
4363
4364         commit_reversible_command ();
4365 }
4366
4367 void
4368 Editor::reset_point_selection ()
4369 {
4370         /* reset all selected points to the relevant default value */
4371
4372         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4373
4374                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4375
4376                 if (atv) {
4377                         atv->reset_objects (selection->points);
4378                 }
4379         }
4380 }
4381
4382 void
4383 Editor::center_playhead ()
4384 {
4385         float page = _canvas_width * frames_per_unit;
4386         center_screen_internal (playhead_cursor->current_frame, page);
4387 }
4388
4389 void
4390 Editor::center_edit_point ()
4391 {
4392         float page = _canvas_width * frames_per_unit;
4393         center_screen_internal (get_preferred_edit_position(), page);
4394 }
4395
4396 void
4397 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4398 {
4399         begin_reversible_command (_("clear playlist"));
4400         playlist->clear_history ();
4401         playlist->clear ();
4402         _session->add_command (new StatefulDiffCommand (playlist));
4403         commit_reversible_command ();
4404 }
4405
4406 void
4407 Editor::nudge_track (bool use_edit, bool forwards)
4408 {
4409         boost::shared_ptr<Playlist> playlist;
4410         nframes64_t distance;
4411         nframes64_t next_distance;
4412         nframes64_t start;
4413
4414         if (use_edit) {
4415                 start = get_preferred_edit_position();
4416         } else {
4417                 start = 0;
4418         }
4419
4420         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4421                 return;
4422         }
4423
4424         if (selection->tracks.empty()) {
4425                 return;
4426         }
4427
4428         begin_reversible_command (_("nudge track"));
4429
4430         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4431
4432                 if ((playlist = (*i)->playlist()) == 0) {
4433                         continue;
4434                 }
4435
4436                 playlist->clear_history ();
4437                 playlist->clear_owned_history ();
4438
4439                 playlist->nudge_after (start, distance, forwards);
4440                 
4441                 vector<StatefulDiffCommand*> cmds;
4442
4443                 playlist->rdiff (cmds);
4444
4445                 for (vector<StatefulDiffCommand*>::iterator c = cmds.begin(); c != cmds.end(); ++c) {
4446                         _session->add_command (*c);
4447                 }
4448
4449                 _session->add_command (new StatefulDiffCommand (playlist));
4450         }
4451
4452         commit_reversible_command ();
4453 }
4454
4455 void
4456 Editor::remove_last_capture ()
4457 {
4458         vector<string> choices;
4459         string prompt;
4460
4461         if (!_session) {
4462                 return;
4463         }
4464
4465         if (Config->get_verify_remove_last_capture()) {
4466                 prompt  = _("Do you really want to destroy the last capture?"
4467                             "\n(This is destructive and cannot be undone)");
4468
4469                 choices.push_back (_("No, do nothing."));
4470                 choices.push_back (_("Yes, destroy it."));
4471
4472                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4473
4474                 if (prompter.run () == 1) {
4475                         _session->remove_last_capture ();
4476                 }
4477
4478         } else {
4479                 _session->remove_last_capture();
4480         }
4481 }
4482
4483 void
4484 Editor::normalize_region ()
4485 {
4486         if (!_session) {
4487                 return;
4488         }
4489
4490         RegionSelection rs;
4491         get_regions_for_action (rs);
4492
4493         if (rs.empty()) {
4494                 return;
4495         }
4496
4497         Dialog dialog (rs.size() > 1 ? _("Normalize regions") : _("Normalize region"));
4498         HBox hbox;
4499         hbox.pack_start (*manage (new Label (_("Normalize to:"))));
4500         SpinButton spin (0.2, 2);
4501         spin.set_range (-112, 0);
4502         spin.set_increments (0.1, 1);
4503         spin.set_value (0);
4504         hbox.pack_start (spin);
4505         spin.set_value (_last_normalization_value);
4506         hbox.pack_start (*manage (new Label (_("dbFS"))));
4507         hbox.show_all ();
4508         dialog.get_vbox()->pack_start (hbox);
4509         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
4510         dialog.add_button (_("Normalize"), RESPONSE_ACCEPT);
4511
4512         if (dialog.run () == RESPONSE_CANCEL) {
4513                 return;
4514         }
4515
4516         begin_reversible_command (_("normalize"));
4517
4518         track_canvas->get_window()->set_cursor (*wait_cursor);
4519         gdk_flush ();
4520
4521         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4522                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4523                 if (!arv)
4524                         continue;
4525                 arv->region()->clear_history ();
4526                 arv->audio_region()->normalize_to (spin.get_value());
4527                 _session->add_command (new StatefulDiffCommand (arv->region()));
4528                                        
4529         }
4530
4531         commit_reversible_command ();
4532         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4533
4534         _last_normalization_value = spin.get_value ();
4535 }
4536
4537
4538 void
4539 Editor::reset_region_scale_amplitude ()
4540 {
4541         if (!_session) {
4542                 return;
4543         }
4544
4545         RegionSelection rs;
4546
4547         get_regions_for_action (rs);
4548
4549         if (rs.empty()) {
4550                 return;
4551         }
4552
4553         begin_reversible_command ("reset gain");
4554
4555         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4556                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4557                 if (!arv)
4558                         continue;
4559                 arv->region()->clear_history ();
4560                 arv->audio_region()->set_scale_amplitude (1.0f);
4561                 _session->add_command (new StatefulDiffCommand (arv->region()));
4562         }
4563
4564         commit_reversible_command ();
4565 }
4566
4567 void
4568 Editor::adjust_region_scale_amplitude (bool up)
4569 {
4570         if (!_session) {
4571                 return;
4572         }
4573
4574         RegionSelection rs;
4575
4576         get_regions_for_action (rs);
4577
4578         if (rs.empty()) {
4579                 return;
4580         }
4581
4582         begin_reversible_command ("denormalize");
4583
4584         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4585                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4586                 if (!arv) {
4587                         continue;
4588                 }
4589
4590                 arv->region()->clear_history ();
4591                 
4592                 double fraction = gain_to_slider_position (arv->audio_region()->scale_amplitude ());
4593
4594                 if (up) {
4595                         fraction += 0.05;
4596                         fraction = min (fraction, 1.0);
4597                 } else {
4598                         fraction -= 0.05;
4599                         fraction = max (fraction, 0.0);
4600                 }
4601
4602                 if (!up && fraction <= 0) {
4603                         continue;
4604                 }
4605
4606                 fraction = slider_position_to_gain (fraction);
4607
4608                 if (up && fraction >= 2.0) {
4609                         continue;
4610                 }
4611
4612                 arv->audio_region()->set_scale_amplitude (fraction);
4613                 _session->add_command (new StatefulDiffCommand (arv->region()));
4614         }
4615
4616         commit_reversible_command ();
4617 }
4618
4619
4620 void
4621 Editor::reverse_region ()
4622 {
4623         if (!_session) {
4624                 return;
4625         }
4626
4627         Reverse rev (*_session);
4628         apply_filter (rev, _("reverse regions"));
4629 }
4630
4631 void
4632 Editor::strip_region_silence ()
4633 {
4634         if (!_session) {
4635                 return;
4636         }
4637
4638         RegionSelection rs;
4639         get_regions_for_action (rs);
4640
4641         if (rs.empty()) {
4642                 return;
4643         }
4644
4645         std::list<boost::shared_ptr<AudioRegion> > ar;
4646
4647         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4648                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4649                 if (arv) {
4650                         ar.push_back (arv->audio_region ());
4651                 }
4652         }
4653
4654         StripSilenceDialog d (_session, ar);
4655         int const r = d.run ();
4656
4657         if (r == Gtk::RESPONSE_OK) {
4658                 StripSilence s (*_session, d.threshold (), d.minimum_length (), d.fade_length ());
4659                 apply_filter (s, _("strip silence"));
4660         }
4661 }
4662
4663 Command*
4664 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4665 {
4666         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4667         mrv.selection_as_notelist (selected);
4668
4669         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4670         v.push_back (selected);
4671
4672         return op (mrv.midi_region()->model(), v);
4673 }
4674
4675 void
4676 Editor::apply_midi_note_edit_op (MidiOperator& op)
4677 {
4678         RegionSelection rs;
4679         Command* cmd;
4680
4681         get_regions_for_action (rs);
4682
4683         if (rs.empty()) {
4684                 return;
4685         }
4686
4687         begin_reversible_command (op.name ());
4688
4689         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4690                 RegionSelection::iterator tmp = r;
4691                 ++tmp;
4692
4693                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4694
4695                 if (mrv) {
4696                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4697                         if (cmd) {
4698                                 (*cmd)();
4699                                 _session->add_command (cmd);
4700                         }
4701                 }
4702
4703                 r = tmp;
4704         }
4705
4706         commit_reversible_command ();
4707         rs.clear ();
4708 }
4709
4710 void
4711 Editor::quantize_region ()
4712 {
4713         if (!_session) {
4714                 return;
4715         }
4716
4717         QuantizeDialog* qd = new QuantizeDialog (*this);
4718
4719         qd->present ();
4720         const int r = qd->run ();
4721         qd->hide ();
4722
4723         if (r == Gtk::RESPONSE_OK) {
4724                 Quantize quant (*_session, Plain,
4725                                 qd->snap_start(), qd->snap_end(),
4726                                 qd->start_grid_size(), qd->end_grid_size(),
4727                                 qd->strength(), qd->swing(), qd->threshold());
4728
4729                 apply_midi_note_edit_op (quant);
4730         }
4731 }
4732
4733 void
4734 Editor::apply_filter (Filter& filter, string command)
4735 {
4736         RegionSelection rs;
4737
4738         get_regions_for_action (rs);
4739
4740         if (rs.empty()) {
4741                 return;
4742         }
4743
4744         begin_reversible_command (command);
4745
4746         track_canvas->get_window()->set_cursor (*wait_cursor);
4747         gdk_flush ();
4748
4749         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4750                 RegionSelection::iterator tmp = r;
4751                 ++tmp;
4752
4753                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4754                 if (arv) {
4755                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4756
4757                         if (arv->audio_region()->apply (filter) == 0) {
4758
4759                                 playlist->clear_history ();
4760                                 
4761                                 if (filter.results.empty ()) {
4762
4763                                         /* no regions returned; remove the old one */
4764                                         playlist->remove_region (arv->region ());
4765
4766                                 } else {
4767
4768                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4769
4770                                         /* first region replaces the old one */
4771                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4772                                         ++res;
4773
4774                                         /* add the rest */
4775                                         while (res != filter.results.end()) {
4776                                                 playlist->add_region (*res, (*res)->position());
4777                                                 ++res;
4778                                         }
4779
4780                                 }
4781
4782                                 _session->add_command(new StatefulDiffCommand (playlist));
4783                         } else {
4784                                 goto out;
4785                         }
4786                 }
4787
4788                 r = tmp;
4789         }
4790
4791         commit_reversible_command ();
4792         rs.clear ();
4793
4794   out:
4795         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4796 }
4797
4798 void
4799 Editor::region_selection_op (void (Region::*pmf)(void))
4800 {
4801         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4802                 Region* region = (*i)->region().get();
4803                 (region->*pmf)();
4804         }
4805 }
4806
4807
4808 void
4809 Editor::region_selection_op (void (Region::*pmf)(void*), void *arg)
4810 {
4811         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4812                 Region* region = (*i)->region().get();
4813                 (region->*pmf)(arg);
4814         }
4815 }
4816
4817 void
4818 Editor::region_selection_op (void (Region::*pmf)(bool), bool yn)
4819 {
4820         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4821                 Region* region = (*i)->region().get();
4822                 (region->*pmf)(yn);
4823         }
4824 }
4825
4826 void
4827 Editor::external_edit_region ()
4828 {
4829         /* more to come */
4830 }
4831
4832 void
4833 Editor::brush (nframes64_t pos)
4834 {
4835         RegionSelection sel;
4836         RegionSelection rs;
4837
4838         get_regions_for_action (rs);
4839
4840         snap_to (pos);
4841
4842         if (rs.empty()) {
4843                 return;
4844         }
4845
4846         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4847                 mouse_brush_insert_region ((*i), pos);
4848         }
4849 }
4850
4851 void
4852 Editor::reset_region_gain_envelopes ()
4853 {
4854         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4855
4856         if (!_session || rs.empty()) {
4857                 return;
4858         }
4859
4860         _session->begin_reversible_command (_("reset region gain"));
4861
4862         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4863                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4864                 if (arv) {
4865                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4866                         XMLNode& before (alist->get_state());
4867
4868                         arv->audio_region()->set_default_envelope ();
4869                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4870                 }
4871         }
4872
4873         _session->commit_reversible_command ();
4874 }
4875
4876 void
4877 Editor::toggle_gain_envelope_visibility ()
4878 {
4879         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4880
4881         if (!_session || rs.empty()) {
4882                 return;
4883         }
4884
4885         _session->begin_reversible_command (_("region gain envelope visible"));
4886
4887         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4888                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4889                 if (arv) {
4890                         arv->region()->clear_history ();
4891                         arv->set_envelope_visible (!arv->envelope_visible());
4892                         _session->add_command (new StatefulDiffCommand (arv->region()));
4893                 }
4894         }
4895
4896         _session->commit_reversible_command ();
4897 }
4898
4899 void
4900 Editor::toggle_gain_envelope_active ()
4901 {
4902         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4903
4904         if (!_session || rs.empty()) {
4905                 return;
4906         }
4907
4908         _session->begin_reversible_command (_("region gain envelope active"));
4909
4910         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4911                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4912                 if (arv) {
4913                         arv->region()->clear_history ();
4914                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4915                         _session->add_command (new StatefulDiffCommand (arv->region()));
4916                 }
4917         }
4918
4919         _session->commit_reversible_command ();
4920 }
4921
4922 void
4923 Editor::toggle_region_lock ()
4924 {
4925         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4926
4927         if (!_session || rs.empty()) {
4928                 return;
4929         }
4930
4931         _session->begin_reversible_command (_("region lock"));
4932
4933         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4934                 (*i)->region()->clear_history ();
4935                 (*i)->region()->set_locked (!(*i)->region()->locked());
4936                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4937         }
4938
4939         _session->commit_reversible_command ();
4940 }
4941
4942 void
4943 Editor::set_region_lock_style (Region::PositionLockStyle ps)
4944 {
4945         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4946
4947         if (!_session || rs.empty()) {
4948                 return;
4949         }
4950
4951         _session->begin_reversible_command (_("region lock style"));
4952
4953         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4954                 (*i)->region()->clear_history ();
4955                 (*i)->region()->set_position_lock_style (ps);
4956                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4957         }
4958
4959         _session->commit_reversible_command ();
4960 }
4961
4962
4963 void
4964 Editor::toggle_region_mute ()
4965 {
4966         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4967
4968         if (!_session || rs.empty()) {
4969                 return;
4970         }
4971
4972         _session->begin_reversible_command (_("region mute"));
4973
4974         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4975                 (*i)->region()->clear_history ();
4976                 (*i)->region()->set_muted (!(*i)->region()->muted());
4977                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4978         }
4979
4980         _session->commit_reversible_command ();
4981 }
4982
4983 void
4984 Editor::toggle_region_opaque ()
4985 {
4986         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4987
4988         if (!_session || rs.empty()) {
4989                 return;
4990         }
4991
4992         _session->begin_reversible_command (_("region opacity"));
4993
4994         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4995                 (*i)->region()->clear_history ();
4996                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4997                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4998         }
4999
5000         _session->commit_reversible_command ();
5001 }
5002
5003 void
5004 Editor::toggle_record_enable ()
5005 {
5006         bool new_state = false;
5007         bool first = true;
5008         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
5009                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
5010                 if (!rtav)
5011                         continue;
5012                 if (!rtav->is_track())
5013                         continue;
5014
5015                 if (first) {
5016                         new_state = !rtav->track()->record_enabled();
5017                         first = false;
5018                 }
5019
5020                 rtav->track()->set_record_enable(new_state, this);
5021         }
5022 }
5023
5024
5025 void
5026 Editor::set_fade_length (bool in)
5027 {
5028         RegionSelection rs;
5029
5030         get_regions_for_action (rs, true);
5031
5032         if (rs.empty()) {
5033                 return;
5034         }
5035
5036         /* we need a region to measure the offset from the start */
5037
5038         RegionView* rv = rs.front ();
5039
5040         nframes64_t pos = get_preferred_edit_position();
5041         nframes64_t len;
5042         char* cmd;
5043
5044         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
5045                 /* edit point is outside the relevant region */
5046                 return;
5047         }
5048
5049         if (in) {
5050                 if (pos <= rv->region()->position()) {
5051                         /* can't do it */
5052                         return;
5053                 }
5054                 len = pos - rv->region()->position();
5055                 cmd = _("set fade in length");
5056         } else {
5057                 if (pos >= rv->region()->last_frame()) {
5058                         /* can't do it */
5059                         return;
5060                 }
5061                 len = rv->region()->last_frame() - pos;
5062                 cmd = _("set fade out length");
5063         }
5064
5065         begin_reversible_command (cmd);
5066
5067         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5068                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5069
5070                 if (!tmp) {
5071                         return;
5072                 }
5073
5074                 boost::shared_ptr<AutomationList> alist;
5075                 if (in) {
5076                         alist = tmp->audio_region()->fade_in();
5077                 } else {
5078                         alist = tmp->audio_region()->fade_out();
5079                 }
5080
5081                 XMLNode &before = alist->get_state();
5082
5083                 if (in) {
5084                         tmp->audio_region()->set_fade_in_length (len);
5085                         tmp->audio_region()->set_fade_in_active (true);
5086                 } else {
5087                         tmp->audio_region()->set_fade_out_length (len);
5088                         tmp->audio_region()->set_fade_out_active (true);
5089                 }
5090
5091                 XMLNode &after = alist->get_state();
5092                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
5093         }
5094
5095         commit_reversible_command ();
5096 }
5097
5098 void
5099 Editor::toggle_fade_active (bool in)
5100 {
5101         RegionSelection rs;
5102
5103         get_regions_for_action (rs);
5104
5105         if (rs.empty()) {
5106                 return;
5107         }
5108
5109         const char* cmd = (in ? _("toggle fade in active") : _("toggle fade out active"));
5110         bool have_switch = false;
5111         bool yn = false;
5112
5113         begin_reversible_command (cmd);
5114
5115         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5116                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5117
5118                 if (!tmp) {
5119                         return;
5120                 }
5121
5122                 boost::shared_ptr<AudioRegion> region (tmp->audio_region());
5123
5124                 /* make the behaviour consistent across all regions */
5125
5126                 if (!have_switch) {
5127                         if (in) {
5128                                 yn = region->fade_in_active();
5129                         } else {
5130                                 yn = region->fade_out_active();
5131                         }
5132                         have_switch = true;
5133                 }
5134
5135                 region->clear_history ();
5136
5137                 if (in) {
5138                         region->set_fade_in_active (!yn);
5139                 } else {
5140                         region->set_fade_out_active (!yn);
5141                 }
5142                 
5143                 _session->add_command(new StatefulDiffCommand (region));
5144         }
5145
5146         commit_reversible_command ();
5147 }
5148
5149 void
5150 Editor::set_fade_in_shape (AudioRegion::FadeShape shape)
5151 {
5152         RegionSelection rs;
5153
5154         get_regions_for_action (rs);
5155
5156         if (rs.empty()) {
5157                 return;
5158         }
5159
5160         begin_reversible_command (_("set fade in shape"));
5161
5162         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5163                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5164
5165                 if (!tmp) {
5166                         return;
5167                 }
5168
5169                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5170                 XMLNode &before = alist->get_state();
5171
5172                 tmp->audio_region()->set_fade_in_shape (shape);
5173
5174                 XMLNode &after = alist->get_state();
5175                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5176         }
5177
5178         commit_reversible_command ();
5179
5180 }
5181
5182 void
5183 Editor::set_fade_out_shape (AudioRegion::FadeShape shape)
5184 {
5185         RegionSelection rs;
5186
5187         get_regions_for_action (rs);
5188
5189         if (rs.empty()) {
5190                 return;
5191         }
5192
5193         begin_reversible_command (_("set fade out shape"));
5194
5195         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5196                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5197
5198                 if (!tmp) {
5199                         return;
5200                 }
5201
5202                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5203                 XMLNode &before = alist->get_state();
5204
5205                 tmp->audio_region()->set_fade_out_shape (shape);
5206
5207                 XMLNode &after = alist->get_state();
5208                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5209         }
5210
5211         commit_reversible_command ();
5212 }
5213
5214 void
5215 Editor::set_fade_in_active (bool yn)
5216 {
5217         RegionSelection rs;
5218
5219         get_regions_for_action (rs);
5220
5221         if (rs.empty()) {
5222                 return;
5223         }
5224
5225         begin_reversible_command (_("set fade in active"));
5226
5227         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5228                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5229
5230                 if (!tmp) {
5231                         return;
5232                 }
5233
5234
5235                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5236                 
5237                 ar->clear_history ();
5238                 ar->set_fade_in_active (yn);
5239                 _session->add_command (new StatefulDiffCommand (ar));
5240         }
5241
5242         commit_reversible_command ();
5243 }
5244
5245 void
5246 Editor::set_fade_out_active (bool yn)
5247 {
5248         RegionSelection rs;
5249
5250         get_regions_for_action (rs);
5251
5252         if (rs.empty()) {
5253                 return;
5254         }
5255
5256         begin_reversible_command (_("set fade out active"));
5257
5258         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5259                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5260
5261                 if (!tmp) {
5262                         return;
5263                 }
5264
5265                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5266
5267                 ar->clear_history ();
5268                 ar->set_fade_out_active (yn);
5269                 _session->add_command(new StatefulDiffCommand (ar));
5270         }
5271
5272         commit_reversible_command ();
5273 }
5274
5275 void
5276 Editor::toggle_selected_region_fades (int dir)
5277 {
5278         RegionSelection rs;
5279         RegionSelection::iterator i;
5280         boost::shared_ptr<AudioRegion> ar;
5281         bool yn;
5282
5283         get_regions_for_action (rs);
5284
5285         if (rs.empty()) {
5286                 return;
5287         }
5288
5289         for (i = rs.begin(); i != rs.end(); ++i) {
5290                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5291                         if (dir == -1) {
5292                                 yn = ar->fade_out_active ();
5293                         } else {
5294                                 yn = ar->fade_in_active ();
5295                         }
5296                         break;
5297                 }
5298         }
5299
5300         if (i == rs.end()) {
5301                 return;
5302         }
5303
5304         /* XXX should this undo-able? */
5305
5306         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5307                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5308                         continue;
5309                 }
5310                 if (dir == 1 || dir == 0) {
5311                         ar->set_fade_in_active (!yn);
5312                 }
5313
5314                 if (dir == -1 || dir == 0) {
5315                         ar->set_fade_out_active (!yn);
5316                 }
5317         }
5318 }
5319
5320
5321 /** Update region fade visibility after its configuration has been changed */
5322 void
5323 Editor::update_region_fade_visibility ()
5324 {
5325         bool _fade_visibility = _session->config.get_show_region_fades ();
5326
5327         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5328                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5329                 if (v) {
5330                         if (_fade_visibility) {
5331                                 v->audio_view()->show_all_fades ();
5332                         } else {
5333                                 v->audio_view()->hide_all_fades ();
5334                         }
5335                 }
5336         }
5337 }
5338
5339 /** Update crossfade visibility after its configuration has been changed */
5340 void
5341 Editor::update_xfade_visibility ()
5342 {
5343         _xfade_visibility = _session->config.get_xfades_visible ();
5344
5345         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5346                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5347                 if (v) {
5348                         if (_xfade_visibility) {
5349                                 v->show_all_xfades ();
5350                         } else {
5351                                 v->hide_all_xfades ();
5352                         }
5353                 }
5354         }
5355 }
5356
5357 void
5358 Editor::set_edit_point ()
5359 {
5360         nframes64_t where;
5361         bool ignored;
5362
5363         if (!mouse_frame (where, ignored)) {
5364                 return;
5365         }
5366
5367         snap_to (where);
5368
5369         if (selection->markers.empty()) {
5370
5371                 mouse_add_new_marker (where);
5372
5373         } else {
5374                 bool ignored;
5375
5376                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5377
5378                 if (loc) {
5379                         loc->move_to (where);
5380                 }
5381         }
5382 }
5383
5384 void
5385 Editor::set_playhead_cursor ()
5386 {
5387         if (entered_marker) {
5388                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5389         } else {
5390                 nframes64_t where;
5391                 bool ignored;
5392
5393                 if (!mouse_frame (where, ignored)) {
5394                         return;
5395                 }
5396
5397                 snap_to (where);
5398
5399                 if (_session) {
5400                         _session->request_locate (where, _session->transport_rolling());
5401                 }
5402         }
5403 }
5404
5405 void
5406 Editor::split ()
5407 {
5408         RegionSelection rs;
5409
5410         get_regions_for_action (rs, true);
5411
5412         nframes64_t where = get_preferred_edit_position();
5413
5414         if (rs.empty()) {
5415                 return;
5416         }
5417
5418         split_regions_at (where, rs);
5419 }
5420
5421 void
5422 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5423 {
5424         if (entered_track && mouse_mode == MouseObject) {
5425                 if (!selection->tracks.empty()) {
5426                         if (!selection->selected (entered_track)) {
5427                                 selection->add (entered_track);
5428                         }
5429                 } else {
5430                         /* there is no selection, but this operation requires/prefers selected objects */
5431
5432                         if (op_really_wants_one_track_if_none_are_selected) {
5433                                 selection->set (entered_track);
5434                         }
5435                 }
5436         }
5437 }
5438
5439 struct EditorOrderRouteSorter {
5440     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5441             /* use of ">" forces the correct sort order */
5442             return a->order_key ("editor") < b->order_key ("editor");
5443     }
5444 };
5445
5446 void
5447 Editor::select_next_route()
5448 {
5449         if (selection->tracks.empty()) {
5450                 selection->set (track_views.front());
5451                 return;
5452         }
5453
5454         TimeAxisView* current = selection->tracks.front();
5455
5456         RouteUI *rui;
5457         do {
5458                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5459                         if (*i == current) {
5460                                 ++i;
5461                                 if (i != track_views.end()) {
5462                                         current = (*i);
5463                                 } else {
5464                                         current = (*(track_views.begin()));
5465                                         //selection->set (*(track_views.begin()));
5466                                 }
5467                                 break;
5468                         }
5469                 }
5470                 rui = dynamic_cast<RouteUI *>(current);
5471         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5472
5473         selection->set(current);
5474
5475         ensure_track_visible(current);
5476 }
5477
5478 void
5479 Editor::select_prev_route()
5480 {
5481         if (selection->tracks.empty()) {
5482                 selection->set (track_views.front());
5483                 return;
5484         }
5485
5486         TimeAxisView* current = selection->tracks.front();
5487
5488         RouteUI *rui;
5489         do {
5490                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5491                         if (*i == current) {
5492                                 ++i;
5493                                 if (i != track_views.rend()) {
5494                                         current = (*i);
5495                                 } else {
5496                                         current = *(track_views.rbegin());
5497                                 }
5498                                 break;
5499                         }
5500                 }
5501                 rui = dynamic_cast<RouteUI *>(current);
5502         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5503
5504         selection->set (current);
5505
5506         ensure_track_visible(current);
5507 }
5508
5509 void
5510 Editor::ensure_track_visible(TimeAxisView *track)
5511 {
5512         if (track->hidden())
5513                 return;
5514
5515         double const current_view_min_y = vertical_adjustment.get_value();
5516         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5517
5518         double const track_min_y = track->y_position ();
5519         double const track_max_y = track->y_position () + track->effective_height ();
5520
5521         if (track_min_y >= current_view_min_y &&
5522             track_max_y <= current_view_max_y) {
5523                 return;
5524         }
5525
5526         double new_value;
5527
5528         if (track_min_y < current_view_min_y) {
5529                 // Track is above the current view
5530                 new_value = track_min_y;
5531         } else {
5532                 // Track is below the current view
5533                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5534         }
5535
5536         vertical_adjustment.set_value(new_value);
5537 }
5538
5539 void
5540 Editor::set_loop_from_selection (bool play)
5541 {
5542         if (_session == 0 || selection->time.empty()) {
5543                 return;
5544         }
5545
5546         nframes64_t start = selection->time[clicked_selection].start;
5547         nframes64_t end = selection->time[clicked_selection].end;
5548
5549         set_loop_range (start, end,  _("set loop range from selection"));
5550
5551         if (play) {
5552                 _session->request_play_loop (true);
5553                 _session->request_locate (start, true);
5554         }
5555 }
5556
5557 void
5558 Editor::set_loop_from_edit_range (bool play)
5559 {
5560         if (_session == 0) {
5561                 return;
5562         }
5563
5564         nframes64_t start;
5565         nframes64_t end;
5566
5567         if (!get_edit_op_range (start, end)) {
5568                 return;
5569         }
5570
5571         set_loop_range (start, end,  _("set loop range from edit range"));
5572
5573         if (play) {
5574                 _session->request_play_loop (true);
5575                 _session->request_locate (start, true);
5576         }
5577 }
5578
5579 void
5580 Editor::set_loop_from_region (bool play)
5581 {
5582         nframes64_t start = max_frames;
5583         nframes64_t end = 0;
5584
5585         RegionSelection rs;
5586
5587         get_regions_for_action (rs);
5588
5589         if (rs.empty()) {
5590                 return;
5591         }
5592
5593         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5594                 if ((*i)->region()->position() < start) {
5595                         start = (*i)->region()->position();
5596                 }
5597                 if ((*i)->region()->last_frame() + 1 > end) {
5598                         end = (*i)->region()->last_frame() + 1;
5599                 }
5600         }
5601
5602         set_loop_range (start, end, _("set loop range from region"));
5603
5604         if (play) {
5605                 _session->request_play_loop (true);
5606                 _session->request_locate (start, true);
5607         }
5608 }
5609
5610 void
5611 Editor::set_punch_from_selection ()
5612 {
5613         if (_session == 0 || selection->time.empty()) {
5614                 return;
5615         }
5616
5617         nframes64_t start = selection->time[clicked_selection].start;
5618         nframes64_t end = selection->time[clicked_selection].end;
5619
5620         set_punch_range (start, end,  _("set punch range from selection"));
5621 }
5622
5623 void
5624 Editor::set_punch_from_edit_range ()
5625 {
5626         if (_session == 0) {
5627                 return;
5628         }
5629
5630         nframes64_t start;
5631         nframes64_t end;
5632
5633         if (!get_edit_op_range (start, end)) {
5634                 return;
5635         }
5636
5637         set_punch_range (start, end,  _("set punch range from edit range"));
5638 }
5639
5640 void
5641 Editor::set_punch_from_region ()
5642 {
5643         nframes64_t start = max_frames;
5644         nframes64_t end = 0;
5645
5646         RegionSelection rs;
5647
5648         get_regions_for_action (rs);
5649
5650         if (rs.empty()) {
5651                 return;
5652         }
5653
5654         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5655                 if ((*i)->region()->position() < start) {
5656                         start = (*i)->region()->position();
5657                 }
5658                 if ((*i)->region()->last_frame() + 1 > end) {
5659                         end = (*i)->region()->last_frame() + 1;
5660                 }
5661         }
5662
5663         set_punch_range (start, end, _("set punch range from region"));
5664 }
5665
5666 void
5667 Editor::pitch_shift_regions ()
5668 {
5669         RegionSelection rs;
5670
5671         get_regions_for_action (rs);
5672
5673         if (rs.empty()) {
5674                 return;
5675         }
5676
5677         pitch_shift (rs, 1.2);
5678 }
5679
5680 void
5681 Editor::use_region_as_bar ()
5682 {
5683         if (!_session) {
5684                 return;
5685         }
5686
5687         RegionSelection rs;
5688
5689         get_regions_for_action (rs);
5690
5691         if (rs.empty()) {
5692                 return;
5693         }
5694
5695         RegionView* rv = rs.front();
5696
5697         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5698 }
5699
5700 void
5701 Editor::use_range_as_bar ()
5702 {
5703         nframes64_t start, end;
5704         if (get_edit_op_range (start, end)) {
5705                 define_one_bar (start, end);
5706         }
5707 }
5708
5709 void
5710 Editor::define_one_bar (nframes64_t start, nframes64_t end)
5711 {
5712         nframes64_t length = end - start;
5713
5714         const Meter& m (_session->tempo_map().meter_at (start));
5715
5716         /* length = 1 bar */
5717
5718         /* now we want frames per beat.
5719            we have frames per bar, and beats per bar, so ...
5720         */
5721
5722         double frames_per_beat = length / m.beats_per_bar();
5723
5724         /* beats per minute = */
5725
5726         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5727
5728         /* now decide whether to:
5729
5730             (a) set global tempo
5731             (b) add a new tempo marker
5732
5733         */
5734
5735         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5736
5737         bool do_global = false;
5738
5739         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5740
5741                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5742                    at the start, or create a new marker
5743                 */
5744
5745                 vector<string> options;
5746                 options.push_back (_("Cancel"));
5747                 options.push_back (_("Add new marker"));
5748                 options.push_back (_("Set global tempo"));
5749
5750                 Choice c (
5751                         _("Define one bar"),
5752                         _("Do you want to set the global tempo or add a new tempo marker?"),
5753                         options
5754                         );
5755                 
5756                 c.set_default_response (2);
5757
5758                 switch (c.run()) {
5759                 case 0:
5760                         return;
5761
5762                 case 2:
5763                         do_global = true;
5764                         break;
5765
5766                 default:
5767                         do_global = false;
5768                 }
5769
5770         } else {
5771
5772                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5773                    if the marker is at the region starter, change it, otherwise add
5774                    a new tempo marker
5775                 */
5776         }
5777
5778         begin_reversible_command (_("set tempo from region"));
5779         XMLNode& before (_session->tempo_map().get_state());
5780
5781         if (do_global) {
5782                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5783         } else if (t.frame() == start) {
5784                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5785         } else {
5786                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5787         }
5788
5789         XMLNode& after (_session->tempo_map().get_state());
5790
5791         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5792         commit_reversible_command ();
5793 }
5794
5795 void
5796 Editor::split_region_at_transients ()
5797 {
5798         AnalysisFeatureList positions;
5799
5800         if (!_session) {
5801                 return;
5802         }
5803
5804         RegionSelection rs;
5805
5806         get_regions_for_action (rs);
5807
5808         if (rs.empty()) {
5809                 return;
5810         }
5811
5812         _session->begin_reversible_command (_("split regions"));
5813
5814         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5815
5816                 RegionSelection::iterator tmp;
5817
5818                 tmp = i;
5819                 ++tmp;
5820
5821                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5822
5823                 if (ar && (ar->get_transients (positions) == 0)) {
5824                         split_region_at_points ((*i)->region(), positions, true);
5825                         positions.clear ();
5826                 }
5827
5828                 i = tmp;
5829         }
5830
5831         _session->commit_reversible_command ();
5832
5833 }
5834
5835 void
5836 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5837 {
5838         bool use_rhythmic_rodent = false;
5839
5840         boost::shared_ptr<Playlist> pl = r->playlist();
5841
5842         if (!pl) {
5843                 return;
5844         }
5845
5846         if (positions.empty()) {
5847                 return;
5848         }
5849
5850
5851         if (positions.size() > 20) {
5852                 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);
5853                 MessageDialog msg (msgstr,
5854                                    false,
5855                                    Gtk::MESSAGE_INFO,
5856                                    Gtk::BUTTONS_OK_CANCEL);
5857
5858                 if (can_ferret) {
5859                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5860                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5861                 } else {
5862                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5863                 }
5864
5865                 msg.set_title (_("Excessive split?"));
5866                 msg.present ();
5867
5868                 int response = msg.run();
5869                 msg.hide ();
5870                 switch (response) {
5871                 case RESPONSE_OK:
5872                         break;
5873                 case RESPONSE_APPLY:
5874                         use_rhythmic_rodent = true;
5875                         break;
5876                 default:
5877                         return;
5878                 }
5879         }
5880
5881         if (use_rhythmic_rodent) {
5882                 show_rhythm_ferret ();
5883                 return;
5884         }
5885
5886         AnalysisFeatureList::const_iterator x;
5887
5888         nframes64_t pos = r->position();
5889
5890         pl->clear_history ();
5891
5892         x = positions.begin();
5893
5894         while (x != positions.end()) {
5895                 if ((*x) > pos) {
5896                         break;
5897                 }
5898                 ++x;
5899         }
5900
5901         if (x == positions.end()) {
5902                 return;
5903         }
5904
5905         pl->freeze ();
5906         pl->remove_region (r);
5907
5908         while (x != positions.end()) {
5909
5910                 /* file start = original start + how far we from the initial position ?
5911                  */
5912
5913                 nframes64_t file_start = r->start() + (pos - r->position());
5914
5915                 /* length = next position - current position
5916                  */
5917
5918                 nframes64_t len = (*x) - pos;
5919
5920                 /* XXX we do we really want to allow even single-sample regions?
5921                    shouldn't we have some kind of lower limit on region size?
5922                 */
5923
5924                 if (len <= 0) {
5925                         break;
5926                 }
5927
5928                 string new_name;
5929
5930                 if (RegionFactory::region_name (new_name, r->name())) {
5931                         break;
5932                 }
5933
5934                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5935
5936                 PropertyList plist; 
5937                 
5938                 plist.add (ARDOUR::Properties::start, file_start);
5939                 plist.add (ARDOUR::Properties::length, len);
5940                 plist.add (ARDOUR::Properties::name, new_name);
5941                 plist.add (ARDOUR::Properties::layer, 0);
5942
5943                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5944                 pl->add_region (nr, pos);
5945
5946                 pos += len;
5947                 ++x;
5948
5949                 if (*x > r->last_frame()) {
5950
5951                         /* add final fragment */
5952
5953                         file_start = r->start() + (pos - r->position());
5954                         len = r->last_frame() - pos;
5955
5956                         PropertyList plist2; 
5957                         
5958                         plist2.add (ARDOUR::Properties::start, file_start);
5959                         plist2.add (ARDOUR::Properties::length, len);
5960                         plist2.add (ARDOUR::Properties::name, new_name);
5961                         plist2.add (ARDOUR::Properties::layer, 0);
5962
5963                         nr = RegionFactory::create (r->sources(), plist2); 
5964                         pl->add_region (nr, pos);
5965
5966                         break;
5967                 }
5968         }
5969
5970         pl->thaw ();
5971
5972         _session->add_command (new StatefulDiffCommand (pl));
5973 }
5974
5975 void
5976 Editor::tab_to_transient (bool forward)
5977 {
5978         AnalysisFeatureList positions;
5979
5980         if (!_session) {
5981                 return;
5982         }
5983
5984         nframes64_t pos = _session->audible_frame ();
5985
5986         if (!selection->tracks.empty()) {
5987
5988                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
5989
5990                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
5991
5992                         if (rtv) {
5993                                 boost::shared_ptr<Diskstream> ds = rtv->get_diskstream();
5994                                 if (ds) {
5995                                         boost::shared_ptr<Playlist> pl = rtv->get_diskstream()->playlist ();
5996                                         if (pl) {
5997                                                 nframes64_t result = pl->find_next_transient (pos, forward ? 1 : -1);
5998
5999                                                 if (result >= 0) {
6000                                                         positions.push_back (result);
6001                                                 }
6002                                         }
6003                                 }
6004                         }
6005                 }
6006
6007         } else {
6008
6009                 RegionSelection rs;
6010
6011                 get_regions_for_action (rs);
6012
6013                 if (rs.empty()) {
6014                         return;
6015                 }
6016
6017                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6018                         (*r)->region()->get_transients (positions);
6019                 }
6020         }
6021
6022         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
6023
6024         if (forward) {
6025                 AnalysisFeatureList::iterator x;
6026
6027                 for (x = positions.begin(); x != positions.end(); ++x) {
6028                         if ((*x) > pos) {
6029                                 break;
6030                         }
6031                 }
6032
6033                 if (x != positions.end ()) {
6034                         _session->request_locate (*x);
6035                 }
6036
6037         } else {
6038                 AnalysisFeatureList::reverse_iterator x;
6039
6040                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6041                         if ((*x) < pos) {
6042                                 break;
6043                         }
6044                 }
6045
6046                 if (x != positions.rend ()) {
6047                         _session->request_locate (*x);
6048                 }
6049         }
6050 }
6051 void
6052 Editor::playhead_forward_to_grid ()
6053 {
6054         if (!_session) return;
6055         nframes64_t pos = playhead_cursor->current_frame;
6056         if (pos < max_frames - 1) {
6057                 pos += 2;
6058                 snap_to_internal (pos, 1, false);
6059                 _session->request_locate (pos);
6060         }
6061 }
6062
6063
6064 void
6065 Editor::playhead_backward_to_grid ()
6066 {
6067         if (!_session) return;
6068         nframes64_t pos = playhead_cursor->current_frame;
6069         if (pos > 2) {
6070                 pos -= 2;
6071                 snap_to_internal (pos, -1, false);
6072                 _session->request_locate (pos);
6073         }
6074 }
6075
6076 void
6077 Editor::set_track_height (uint32_t h)
6078 {
6079         TrackSelection& ts (selection->tracks);
6080
6081         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6082                 (*x)->set_height (h);
6083         }
6084 }
6085
6086 void
6087 Editor::toggle_tracks_active ()
6088 {
6089         TrackSelection& ts (selection->tracks);
6090         bool first = true;
6091         bool target = false;
6092
6093         if (ts.empty()) {
6094                 return;
6095         }
6096
6097         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6098                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6099
6100                 if (rtv) {
6101                         if (first) {
6102                                 target = !rtv->_route->active();
6103                                 first = false;
6104                         }
6105                         rtv->_route->set_active (target);
6106                 }
6107         }
6108 }
6109
6110 void
6111 Editor::remove_tracks ()
6112 {
6113         TrackSelection& ts (selection->tracks);
6114
6115         if (ts.empty()) {
6116                 return;
6117         }
6118
6119         vector<string> choices;
6120         string prompt;
6121         int ntracks = 0;
6122         int nbusses = 0;
6123         const char* trackstr;
6124         const char* busstr;
6125         vector<boost::shared_ptr<Route> > routes;
6126
6127         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6128                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6129                 if (rtv) {
6130                         if (rtv->is_track()) {
6131                                 ntracks++;
6132                         } else {
6133                                 nbusses++;
6134                         }
6135                 }
6136                 routes.push_back (rtv->_route);
6137         }
6138
6139         if (ntracks + nbusses == 0) {
6140                 return;
6141         }
6142
6143         if (ntracks > 1) {
6144                 trackstr = _("tracks");
6145         } else {
6146                 trackstr = _("track");
6147         }
6148
6149         if (nbusses > 1) {
6150                 busstr = _("busses");
6151         } else {
6152                 busstr = _("bus");
6153         }
6154
6155         if (ntracks) {
6156                 if (nbusses) {
6157                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6158                                                     "(You may also lose the playlists associated with the %2)\n\n"
6159                                                     "This action cannot be undone!"),
6160                                                   ntracks, trackstr, nbusses, busstr);
6161                 } else {
6162                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6163                                                     "(You may also lose the playlists associated with the %2)\n\n"
6164                                                     "This action cannot be undone!"),
6165                                                   ntracks, trackstr);
6166                 }
6167         } else if (nbusses) {
6168                 prompt  = string_compose (_("Do you really want to remove %1 %2?"),
6169                                           nbusses, busstr);
6170         }
6171
6172         choices.push_back (_("No, do nothing."));
6173         if (ntracks + nbusses > 1) {
6174                 choices.push_back (_("Yes, remove them."));
6175         } else {
6176                 choices.push_back (_("Yes, remove it."));
6177         }
6178
6179         string title;
6180         if (ntracks) {
6181                 title = string_compose (_("Remove %1"), trackstr);
6182         } else {
6183                 title = string_compose (_("Remove %1"), busstr);
6184         }
6185
6186         Choice prompter (title, prompt, choices);
6187
6188         if (prompter.run () != 1) {
6189                 return;
6190         }
6191
6192         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6193                 _session->remove_route (*x);
6194         }
6195 }
6196
6197 void
6198 Editor::do_insert_time ()
6199 {
6200         if (selection->tracks.empty()) {
6201                 return;
6202         }
6203
6204         ArdourDialog d (*this, _("Insert Time"));
6205
6206         nframes64_t const pos = get_preferred_edit_position ();
6207
6208         d.get_vbox()->set_border_width (12);
6209         d.get_vbox()->set_spacing (4);
6210
6211         Table table (2, 2);
6212         table.set_spacings (4);
6213
6214         Label time_label (_("Time to insert:"));
6215         time_label.set_alignment (1, 0.5);
6216         table.attach (time_label, 0, 1, 0, 1, FILL | EXPAND);
6217         AudioClock clock ("insertTimeClock", true, X_("InsertTimeClock"), true, false, true, true);
6218         clock.set (0);
6219         clock.set_session (_session);
6220         clock.set_bbt_reference (pos);
6221         table.attach (clock, 1, 2, 0, 1);
6222
6223         Label intersected_label (_("Intersected regions should:"));
6224         intersected_label.set_alignment (1, 0.5);
6225         table.attach (intersected_label, 0, 1, 1, 2, FILL | EXPAND);
6226         ComboBoxText intersected_combo;
6227         intersected_combo.append_text (_("stay in position"));
6228         intersected_combo.append_text (_("move"));
6229         intersected_combo.append_text (_("be split"));
6230         intersected_combo.set_active (0);
6231         table.attach (intersected_combo, 1, 2, 1, 2);
6232
6233         d.get_vbox()->pack_start (table);
6234
6235         CheckButton move_glued (_("Move glued regions"));
6236         d.get_vbox()->pack_start (move_glued);
6237         CheckButton move_markers (_("Move markers"));
6238         d.get_vbox()->pack_start (move_markers);
6239         CheckButton move_tempos (_("Move tempo and meter changes"));
6240         d.get_vbox()->pack_start (move_tempos);
6241
6242         d.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
6243         d.add_button (_("Insert time"), Gtk::RESPONSE_OK);
6244         d.show_all ();
6245
6246         int response = d.run ();
6247
6248         if (response != RESPONSE_OK) {
6249                 return;
6250         }
6251
6252         nframes64_t distance = clock.current_duration (pos);
6253
6254         if (distance == 0) {
6255                 return;
6256         }
6257
6258         InsertTimeOption opt;
6259
6260         switch (intersected_combo.get_active_row_number ()) {
6261         case 0:
6262                 opt = LeaveIntersected;
6263                 break;
6264         case 1:
6265                 opt = MoveIntersected;
6266                 break;
6267         case 2:
6268                 opt = SplitIntersected;
6269                 break;
6270         }
6271
6272         insert_time (pos, distance, opt, move_glued.get_active(), move_markers.get_active(), move_tempos.get_active());
6273 }
6274
6275 void
6276 Editor::insert_time (nframes64_t pos, nframes64_t frames, InsertTimeOption opt,
6277                      bool ignore_music_glue, bool markers_too, bool tempo_too)
6278 {
6279         bool commit = false;
6280
6281         if (Config->get_edit_mode() == Lock) {
6282                 return;
6283         }
6284
6285         begin_reversible_command (_("insert time"));
6286
6287         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6288                 /* regions */
6289                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6290
6291                 if (pl) {
6292
6293                         pl->clear_history ();
6294                         pl->clear_owned_history ();
6295
6296                         if (opt == SplitIntersected) {
6297                                 pl->split (pos);
6298                         }
6299
6300                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6301
6302                         vector<StatefulDiffCommand*> cmds;
6303                         
6304                         pl->rdiff (cmds);
6305                         
6306                         cerr << "Shift generated " << cmds.size() << " sdc's\n";
6307
6308                         for (vector<StatefulDiffCommand*>::iterator c = cmds.begin(); c != cmds.end(); ++c) {
6309                                 _session->add_command (*c);
6310                         }
6311                         
6312                         _session->add_command (new StatefulDiffCommand (pl));
6313                         commit = true;
6314                 }
6315
6316                 /* automation */
6317                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6318                 if (rtav) {
6319                         rtav->route ()->shift (pos, frames);
6320                         commit = true;
6321                 }
6322         }
6323
6324         /* markers */
6325         if (markers_too) {
6326                 bool moved = false;
6327                 XMLNode& before (_session->locations()->get_state());
6328                 Locations::LocationList copy (_session->locations()->list());
6329
6330                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6331
6332                         Locations::LocationList::const_iterator tmp;
6333
6334                         if ((*i)->start() >= pos) {
6335                                 (*i)->set_start ((*i)->start() + frames);
6336                                 if (!(*i)->is_mark()) {
6337                                         (*i)->set_end ((*i)->end() + frames);
6338                                 }
6339                                 moved = true;
6340                         }
6341                 }
6342
6343                 if (moved) {
6344                         XMLNode& after (_session->locations()->get_state());
6345                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6346                 }
6347         }
6348
6349         if (tempo_too) {
6350                 _session->tempo_map().insert_time (pos, frames);
6351         }
6352
6353         if (commit) {
6354                 commit_reversible_command ();
6355         }
6356 }
6357
6358 void
6359 Editor::fit_selected_tracks ()
6360 {
6361         fit_tracks (selection->tracks);
6362 }
6363
6364 void
6365 Editor::fit_tracks (TrackViewList & tracks)
6366 {
6367         if (tracks.empty()) {
6368                 return;
6369         }
6370
6371         uint32_t child_heights = 0;
6372
6373         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6374
6375                 if (!(*t)->marked_for_display()) {
6376                         continue;
6377                 }
6378
6379                 child_heights += (*t)->effective_height() - (*t)->current_height();
6380         }
6381
6382         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6383         double first_y_pos = DBL_MAX;
6384
6385         if (h < TimeAxisView::hSmall) {
6386                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6387                 /* too small to be displayed */
6388                 return;
6389         }
6390
6391         undo_visual_stack.push_back (current_visual_state());
6392
6393         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6394
6395         bool prev_was_selected = false;
6396         bool is_selected = tracks.contains (track_views.front());
6397         bool next_is_selected;
6398
6399         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
6400
6401                 TrackViewList::iterator next;
6402
6403                 next = t;
6404                 ++next;
6405
6406                 if (next != track_views.end()) {
6407                         next_is_selected = tracks.contains (*next);
6408                 } else {
6409                         next_is_selected = false;
6410                 }
6411
6412                 if (is_selected) {
6413                         (*t)->set_height (h);
6414                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6415                 } else {
6416                         if (prev_was_selected && next_is_selected) {
6417                                 hide_track_in_display (**t);
6418                         }
6419                 }
6420
6421                 prev_was_selected = is_selected;
6422                 is_selected = next_is_selected;
6423         }
6424
6425         /*
6426            set the controls_layout height now, because waiting for its size
6427            request signal handler will cause the vertical adjustment setting to fail
6428         */
6429
6430         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6431         vertical_adjustment.set_value (first_y_pos);
6432
6433         redo_visual_stack.push_back (current_visual_state());
6434 }
6435
6436 void
6437 Editor::save_visual_state (uint32_t n)
6438 {
6439         while (visual_states.size() <= n) {
6440                 visual_states.push_back (0);
6441         }
6442
6443         delete visual_states[n];
6444
6445         visual_states[n] = current_visual_state (true);
6446         gdk_beep ();
6447 }
6448
6449 void
6450 Editor::goto_visual_state (uint32_t n)
6451 {
6452         if (visual_states.size() <= n) {
6453                 return;
6454         }
6455
6456         if (visual_states[n] == 0) {
6457                 return;
6458         }
6459
6460         use_visual_state (*visual_states[n]);
6461 }
6462
6463 void
6464 Editor::start_visual_state_op (uint32_t n)
6465 {
6466         if (visual_state_op_connection.empty()) {
6467                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6468         }
6469 }
6470
6471 void
6472 Editor::cancel_visual_state_op (uint32_t n)
6473 {
6474         if (!visual_state_op_connection.empty()) {
6475                 visual_state_op_connection.disconnect();
6476                 goto_visual_state (n);
6477         }  else {
6478                 //we land here if called from the menu OR if end_visual_state_op has been called
6479                 //so check if we are already in visual state n
6480                 // XXX not yet checking it at all, but redoing does not hurt
6481                 goto_visual_state (n);
6482         }
6483 }
6484
6485 bool
6486 Editor::end_visual_state_op (uint32_t n)
6487 {
6488         visual_state_op_connection.disconnect();
6489         save_visual_state (n);
6490
6491         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6492         char buf[32];
6493         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6494         pup->set_text (buf);
6495         pup->touch();
6496
6497         return false; // do not call again
6498 }
6499