changes to help strp silence
[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->frozen()) {
159                         /* we haven't seen this playlist before */
160
161                         /* remember used playlists so we can thaw them later */
162                         used_playlists.push_back(pl);
163                         pl->freeze();
164                 }
165
166                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*a);
167                 if (arv) {
168                         _new_regionviews_show_envelope = arv->envelope_visible();
169                 }
170
171                 if (pl) {
172                         pl->clear_history ();
173                         pl->split_region ((*a)->region(), where);
174                         _session->add_command (new StatefulDiffCommand (pl));
175                 }
176
177                 a = tmp;
178         }
179
180         while (used_playlists.size() > 0) {
181                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
182                 (*i)->thaw();
183                 used_playlists.pop_front();
184         }
185
186         commit_reversible_command ();
187         _new_regionviews_show_envelope = false;
188 }
189
190 boost::shared_ptr<Region>
191 Editor::select_region_for_operation (int /*dir*/, TimeAxisView **tv)
192 {
193         RegionView* rv;
194         boost::shared_ptr<Region> region;
195         nframes64_t start = 0;
196
197         if (selection->time.start () == selection->time.end_frame ()) {
198
199                 /* no current selection-> is there a selected regionview? */
200
201                 if (selection->regions.empty()) {
202                         return region;
203                 }
204
205         }
206
207         if (!selection->regions.empty()) {
208
209                 rv = *(selection->regions.begin());
210                 (*tv) = &rv->get_time_axis_view();
211                 region = rv->region();
212
213         } else if (!selection->tracks.empty()) {
214
215                 (*tv) = selection->tracks.front();
216
217                 RouteTimeAxisView* rtv;
218
219                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*tv)) != 0) {
220                         boost::shared_ptr<Playlist> pl;
221
222                         if ((pl = rtv->playlist()) == 0) {
223                                 return region;
224                         }
225
226                         region = pl->top_region_at (start);
227                 }
228         }
229
230         return region;
231 }
232
233 void
234 Editor::extend_selection_to_end_of_region (bool next)
235 {
236         TimeAxisView *tv;
237         boost::shared_ptr<Region> region;
238         nframes64_t start;
239
240         if ((region = select_region_for_operation (next ? 1 : 0, &tv)) == 0) {
241                 return;
242         }
243
244         if (region && selection->time.start () == selection->time.end_frame ()) {
245                 start = region->position();
246         } else {
247                 start = selection->time.start ();
248         }
249
250         begin_reversible_command (_("extend selection"));
251         selection->set (start, region->position() + region->length());
252         commit_reversible_command ();
253 }
254
255 void
256 Editor::extend_selection_to_start_of_region (bool previous)
257 {
258         TimeAxisView *tv;
259         boost::shared_ptr<Region> region;
260         nframes64_t end;
261
262         if ((region = select_region_for_operation (previous ? -1 : 0, &tv)) == 0) {
263                 return;
264         }
265
266         if (region && selection->time.start () == selection->time.end_frame ()) {
267                 end = region->position() + region->length();
268         } else {
269                 end = selection->time.end_frame ();
270         }
271
272         /* Try to leave the selection with the same route if possible */
273
274         begin_reversible_command (_("extend selection"));
275         selection->set (region->position(), end);
276         commit_reversible_command ();
277 }
278
279 bool
280 Editor::nudge_forward_release (GdkEventButton* ev)
281 {
282         if (ev->state & Keyboard::PrimaryModifier) {
283                 nudge_forward (false, true);
284         } else {
285                 nudge_forward (false, false);
286         }
287         return false;
288 }
289
290 bool
291 Editor::nudge_backward_release (GdkEventButton* ev)
292 {
293         if (ev->state & Keyboard::PrimaryModifier) {
294                 nudge_backward (false, true);
295         } else {
296                 nudge_backward (false, false);
297         }
298         return false;
299 }
300
301
302 void
303 Editor::nudge_forward (bool next, bool force_playhead)
304 {
305         nframes64_t distance;
306         nframes64_t next_distance;
307         RegionSelection rs;
308
309         get_regions_for_action (rs);
310
311         if (!_session) return;
312
313         if (!force_playhead && !rs.empty()) {
314
315                 begin_reversible_command (_("nudge regions forward"));
316
317                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
318                         boost::shared_ptr<Region> r ((*i)->region());
319
320                         distance = get_nudge_distance (r->position(), next_distance);
321
322                         if (next) {
323                                 distance = next_distance;
324                         }
325
326                         r->clear_history ();
327                         r->set_position (r->position() + distance, this);
328                         _session->add_command (new StatefulDiffCommand (r));
329                 }
330
331                 commit_reversible_command ();
332
333
334         } else if (!force_playhead && !selection->markers.empty()) {
335
336                 bool is_start;
337
338                 begin_reversible_command (_("nudge location forward"));
339
340                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
341
342                         Location* loc = find_location_from_marker ((*i), is_start);
343
344                         if (loc) {
345
346                                 XMLNode& before (loc->get_state());
347
348                                 if (is_start) {
349                                         distance = get_nudge_distance (loc->start(), next_distance);
350                                         if (next) {
351                                                 distance = next_distance;
352                                         }
353                                         if (max_frames - distance > loc->start() + loc->length()) {
354                                                 loc->set_start (loc->start() + distance);
355                                         } else {
356                                                 loc->set_start (max_frames - loc->length());
357                                         }
358                                 } else {
359                                         distance = get_nudge_distance (loc->end(), next_distance);
360                                         if (next) {
361                                                 distance = next_distance;
362                                         }
363                                         if (max_frames - distance > loc->end()) {
364                                                 loc->set_end (loc->end() + distance);
365                                         } else {
366                                                 loc->set_end (max_frames);
367                                         }
368                                 }
369                                 XMLNode& after (loc->get_state());
370                                 _session->add_command (new MementoCommand<Location>(*loc, &before, &after));
371                         }
372                 }
373
374                 commit_reversible_command ();
375
376         } else {
377                 distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
378                 _session->request_locate (playhead_cursor->current_frame + distance);
379         }
380 }
381
382 void
383 Editor::nudge_backward (bool next, bool force_playhead)
384 {
385         nframes64_t distance;
386         nframes64_t next_distance;
387         RegionSelection rs;
388
389         get_regions_for_action (rs);
390
391         if (!_session) return;
392
393         if (!force_playhead && !rs.empty()) {
394
395                 begin_reversible_command (_("nudge regions backward"));
396
397                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
398                         boost::shared_ptr<Region> r ((*i)->region());
399
400                         distance = get_nudge_distance (r->position(), next_distance);
401
402                         if (next) {
403                                 distance = next_distance;
404                         }
405                         
406                         r->clear_history ();
407
408                         if (r->position() > distance) {
409                                 r->set_position (r->position() - distance, this);
410                         } else {
411                                 r->set_position (0, this);
412                         }
413                         _session->add_command (new StatefulDiffCommand (r));
414                 }
415
416                 commit_reversible_command ();
417
418         } else if (!force_playhead && !selection->markers.empty()) {
419
420                 bool is_start;
421
422                 begin_reversible_command (_("nudge location forward"));
423
424                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
425
426                         Location* loc = find_location_from_marker ((*i), is_start);
427
428                         if (loc) {
429
430                                 XMLNode& before (loc->get_state());
431
432                                 if (is_start) {
433                                         distance = get_nudge_distance (loc->start(), next_distance);
434                                         if (next) {
435                                                 distance = next_distance;
436                                         }
437                                         if (distance < loc->start()) {
438                                                 loc->set_start (loc->start() - distance);
439                                         } else {
440                                                 loc->set_start (0);
441                                         }
442                                 } else {
443                                         distance = get_nudge_distance (loc->end(), next_distance);
444
445                                         if (next) {
446                                                 distance = next_distance;
447                                         }
448
449                                         if (distance < loc->end() - loc->length()) {
450                                                 loc->set_end (loc->end() - distance);
451                                         } else {
452                                                 loc->set_end (loc->length());
453                                         }
454                                 }
455
456                                 XMLNode& after (loc->get_state());
457                                 _session->add_command (new MementoCommand<Location>(*loc, &before, &after));
458                         }
459                 }
460
461                 commit_reversible_command ();
462
463         } else {
464
465                 distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
466
467                 if (playhead_cursor->current_frame > distance) {
468                         _session->request_locate (playhead_cursor->current_frame - distance);
469                 } else {
470                         _session->goto_start();
471                 }
472         }
473 }
474
475 void
476 Editor::nudge_forward_capture_offset ()
477 {
478         nframes64_t distance;
479         RegionSelection rs;
480
481         get_regions_for_action (rs);
482
483         if (!_session) return;
484
485         if (!rs.empty()) {
486
487                 begin_reversible_command (_("nudge forward"));
488
489                 distance = _session->worst_output_latency();
490
491                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
492                         boost::shared_ptr<Region> r ((*i)->region());
493
494                         r->clear_history ();
495                         r->set_position (r->position() + distance, this);
496                         _session->add_command(new StatefulDiffCommand (r));
497                 }
498
499                 commit_reversible_command ();
500
501         }
502 }
503
504 void
505 Editor::nudge_backward_capture_offset ()
506 {
507         nframes64_t distance;
508         RegionSelection rs;
509
510         get_regions_for_action (rs);
511
512         if (!_session) return;
513
514         if (!rs.empty()) {
515
516                 begin_reversible_command (_("nudge forward"));
517
518                 distance = _session->worst_output_latency();
519
520                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
521                         boost::shared_ptr<Region> r ((*i)->region());
522
523                         r->clear_history ();
524
525                         if (r->position() > distance) {
526                                 r->set_position (r->position() - distance, this);
527                         } else {
528                                 r->set_position (0, this);
529                         }
530                         _session->add_command(new StatefulDiffCommand (r));
531                 }
532
533                 commit_reversible_command ();
534         }
535 }
536
537 /* DISPLAY MOTION */
538
539 void
540 Editor::move_to_start ()
541 {
542         _session->goto_start ();
543 }
544
545 void
546 Editor::move_to_end ()
547 {
548
549         _session->request_locate (_session->current_end_frame());
550 }
551
552 void
553 Editor::build_region_boundary_cache ()
554 {
555         nframes64_t pos = 0;
556         vector<RegionPoint> interesting_points;
557         boost::shared_ptr<Region> r;
558         TrackViewList tracks;
559         bool at_end = false;
560
561         region_boundary_cache.clear ();
562
563         if (_session == 0) {
564                 return;
565         }
566
567         switch (_snap_type) {
568         case SnapToRegionStart:
569                 interesting_points.push_back (Start);
570                 break;
571         case SnapToRegionEnd:
572                 interesting_points.push_back (End);
573                 break;
574         case SnapToRegionSync:
575                 interesting_points.push_back (SyncPoint);
576                 break;
577         case SnapToRegionBoundary:
578                 interesting_points.push_back (Start);
579                 interesting_points.push_back (End);
580                 break;
581         default:
582                 fatal << string_compose (_("build_region_boundary_cache called with snap_type = %1"), _snap_type) << endmsg;
583                 /*NOTREACHED*/
584                 return;
585         }
586
587         TimeAxisView *ontrack = 0;
588         TrackViewList tlist;
589
590         if (!selection->tracks.empty()) {
591                 tlist = selection->tracks;
592         } else {
593                 tlist = track_views;
594         }
595
596         while (pos < _session->current_end_frame() && !at_end) {
597
598                 nframes64_t rpos;
599                 nframes64_t lpos = max_frames;
600
601                 for (vector<RegionPoint>::iterator p = interesting_points.begin(); p != interesting_points.end(); ++p) {
602
603                         if ((r = find_next_region (pos, *p, 1, tlist, &ontrack)) == 0) {
604                                 if (*p == interesting_points.back()) {
605                                         at_end = true;
606                                 }
607                                 /* move to next point type */
608                                 continue;
609                         }
610
611                         switch (*p) {
612                         case Start:
613                                 rpos = r->first_frame();
614                                 break;
615
616                         case End:
617                                 rpos = r->last_frame();
618                                 break;
619
620                         case SyncPoint:
621                                 rpos = r->sync_position ();
622                                 //r->adjust_to_sync (r->first_frame());
623                                 break;
624
625                         default:
626                                 break;
627                         }
628
629                         float speed = 1.0f;
630                         RouteTimeAxisView *rtav;
631
632                         if (ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0 ) {
633                                 if (rtav->get_diskstream() != 0) {
634                                         speed = rtav->get_diskstream()->speed();
635                                 }
636                         }
637
638                         rpos = track_frame_to_session_frame (rpos, speed);
639
640                         if (rpos < lpos) {
641                                 lpos = rpos;
642                         }
643
644                         /* prevent duplicates, but we don't use set<> because we want to be able
645                            to sort later.
646                         */
647
648                         vector<nframes64_t>::iterator ri;
649
650                         for (ri = region_boundary_cache.begin(); ri != region_boundary_cache.end(); ++ri) {
651                                 if (*ri == rpos) {
652                                         break;
653                                 }
654                         }
655
656                         if (ri == region_boundary_cache.end()) {
657                                 region_boundary_cache.push_back (rpos);
658                         }
659                 }
660
661                 pos = lpos + 1;
662         }
663
664         /* finally sort to be sure that the order is correct */
665
666         sort (region_boundary_cache.begin(), region_boundary_cache.end());
667 }
668
669 boost::shared_ptr<Region>
670 Editor::find_next_region (nframes64_t frame, RegionPoint point, int32_t dir, TrackViewList& tracks, TimeAxisView **ontrack)
671 {
672         TrackViewList::iterator i;
673         nframes64_t closest = max_frames;
674         boost::shared_ptr<Region> ret;
675         nframes64_t rpos = 0;
676
677         float track_speed;
678         nframes64_t track_frame;
679         RouteTimeAxisView *rtav;
680
681         for (i = tracks.begin(); i != tracks.end(); ++i) {
682
683                 nframes64_t distance;
684                 boost::shared_ptr<Region> r;
685
686                 track_speed = 1.0f;
687                 if ( (rtav = dynamic_cast<RouteTimeAxisView*>(*i)) != 0 ) {
688                         if (rtav->get_diskstream()!=0)
689                                 track_speed = rtav->get_diskstream()->speed();
690                 }
691
692                 track_frame = session_frame_to_track_frame(frame, track_speed);
693
694                 if ((r = (*i)->find_next_region (track_frame, point, dir)) == 0) {
695                         continue;
696                 }
697
698                 switch (point) {
699                 case Start:
700                         rpos = r->first_frame ();
701                         break;
702
703                 case End:
704                         rpos = r->last_frame ();
705                         break;
706
707                 case SyncPoint:
708                         rpos = r->sync_position ();
709                         // r->adjust_to_sync (r->first_frame());
710                         break;
711                 }
712
713                 // rpos is a "track frame", converting it to "_session frame"
714                 rpos = track_frame_to_session_frame(rpos, track_speed);
715
716                 if (rpos > frame) {
717                         distance = rpos - frame;
718                 } else {
719                         distance = frame - rpos;
720                 }
721
722                 if (distance < closest) {
723                         closest = distance;
724                         if (ontrack != 0)
725                                 *ontrack = (*i);
726                         ret = r;
727                 }
728         }
729
730         return ret;
731 }
732
733 nframes64_t
734 Editor::find_next_region_boundary (nframes64_t pos, int32_t dir, const TrackViewList& tracks)
735 {
736         nframes64_t distance = max_frames;
737         nframes64_t current_nearest = -1;
738
739
740         for (TrackViewList::const_iterator i = tracks.begin(); i != tracks.end(); ++i) {
741                 nframes64_t contender;
742                 nframes64_t d;
743
744                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
745
746                 if (!rtv) {
747                         continue;
748                 }
749
750                 if ((contender = rtv->find_next_region_boundary (pos, dir)) < 0) {
751                         continue;
752                 }
753
754                 d = ::llabs (pos - contender);
755
756                 if (d < distance) {
757                         current_nearest = contender;
758                         distance = d;
759                 }
760         }
761
762         return current_nearest;
763 }
764
765 nframes64_t
766 Editor::get_region_boundary (nframes64_t pos, int32_t dir, bool with_selection, bool only_onscreen)
767 {
768         nframes64_t target;
769         TrackViewList tvl;
770
771         if (with_selection && Config->get_region_boundaries_from_selected_tracks()) {
772
773                 if (!selection->tracks.empty()) {
774
775                         target = find_next_region_boundary (pos, dir, selection->tracks);
776
777                 } else {
778
779                         if (only_onscreen || Config->get_region_boundaries_from_onscreen_tracks()) {
780                                 get_onscreen_tracks (tvl);
781                                 target = find_next_region_boundary (pos, dir, tvl);
782                         } else {
783                                 target = find_next_region_boundary (pos, dir, track_views);
784                         }
785                 }
786
787         } else {
788
789                 if (only_onscreen || Config->get_region_boundaries_from_onscreen_tracks()) {
790                         get_onscreen_tracks (tvl);
791                         target = find_next_region_boundary (pos, dir, tvl);
792                 } else {
793                         target = find_next_region_boundary (pos, dir, track_views);
794                 }
795         }
796
797         return target;
798 }
799
800 void
801 Editor::cursor_to_region_boundary (bool with_selection, int32_t dir)
802 {
803         nframes64_t pos = playhead_cursor->current_frame;
804         nframes64_t target;
805
806         if (!_session) {
807                 return;
808         }
809
810         // so we don't find the current region again..
811         if (dir > 0 || pos > 0) {
812                 pos += dir;
813         }
814
815         if ((target = get_region_boundary (pos, dir, with_selection, false)) < 0) {
816                 return;
817         }
818
819         _session->request_locate (target);
820 }
821
822 void
823 Editor::cursor_to_next_region_boundary (bool with_selection)
824 {
825         cursor_to_region_boundary (with_selection, 1);
826 }
827
828 void
829 Editor::cursor_to_previous_region_boundary (bool with_selection)
830 {
831         cursor_to_region_boundary (with_selection, -1);
832 }
833
834 void
835 Editor::cursor_to_region_point (EditorCursor* cursor, RegionPoint point, int32_t dir)
836 {
837         boost::shared_ptr<Region> r;
838         nframes64_t pos = cursor->current_frame;
839
840         if (!_session) {
841                 return;
842         }
843
844         TimeAxisView *ontrack = 0;
845
846         // so we don't find the current region again..
847         if (dir>0 || pos>0)
848                 pos+=dir;
849
850         if (!selection->tracks.empty()) {
851
852                 r = find_next_region (pos, point, dir, selection->tracks, &ontrack);
853
854         } else if (clicked_axisview) {
855
856                 TrackViewList t;
857                 t.push_back (clicked_axisview);
858
859                 r = find_next_region (pos, point, dir, t, &ontrack);
860
861         } else {
862
863                 r = find_next_region (pos, point, dir, track_views, &ontrack);
864         }
865
866         if (r == 0) {
867                 return;
868         }
869
870         switch (point){
871         case Start:
872                 pos = r->first_frame ();
873                 break;
874
875         case End:
876                 pos = r->last_frame ();
877                 break;
878
879         case SyncPoint:
880                 pos = r->sync_position ();
881                 // r->adjust_to_sync (r->first_frame());
882                 break;
883         }
884
885         float speed = 1.0f;
886         RouteTimeAxisView *rtav;
887
888         if ( ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0 ) {
889                 if (rtav->get_diskstream() != 0) {
890                         speed = rtav->get_diskstream()->speed();
891                 }
892         }
893
894         pos = track_frame_to_session_frame(pos, speed);
895
896         if (cursor == playhead_cursor) {
897                 _session->request_locate (pos);
898         } else {
899                 cursor->set_position (pos);
900         }
901 }
902
903 void
904 Editor::cursor_to_next_region_point (EditorCursor* cursor, RegionPoint point)
905 {
906         cursor_to_region_point (cursor, point, 1);
907 }
908
909 void
910 Editor::cursor_to_previous_region_point (EditorCursor* cursor, RegionPoint point)
911 {
912         cursor_to_region_point (cursor, point, -1);
913 }
914
915 void
916 Editor::cursor_to_selection_start (EditorCursor *cursor)
917 {
918         nframes64_t pos = 0;
919         RegionSelection rs;
920
921         get_regions_for_action (rs);
922
923         switch (mouse_mode) {
924         case MouseObject:
925                 if (!rs.empty()) {
926                         pos = rs.start();
927                 }
928                 break;
929
930         case MouseRange:
931                 if (!selection->time.empty()) {
932                         pos = selection->time.start ();
933                 }
934                 break;
935
936         default:
937                 return;
938         }
939
940         if (cursor == playhead_cursor) {
941                 _session->request_locate (pos);
942         } else {
943                 cursor->set_position (pos);
944         }
945 }
946
947 void
948 Editor::cursor_to_selection_end (EditorCursor *cursor)
949 {
950         nframes64_t pos = 0;
951         RegionSelection rs;
952
953         get_regions_for_action (rs);
954
955         switch (mouse_mode) {
956         case MouseObject:
957                 if (!rs.empty()) {
958                         pos = rs.end_frame();
959                 }
960                 break;
961
962         case MouseRange:
963                 if (!selection->time.empty()) {
964                         pos = selection->time.end_frame ();
965                 }
966                 break;
967
968         default:
969                 return;
970         }
971
972         if (cursor == playhead_cursor) {
973                 _session->request_locate (pos);
974         } else {
975                 cursor->set_position (pos);
976         }
977 }
978
979 void
980 Editor::selected_marker_to_region_boundary (bool with_selection, int32_t dir)
981 {
982         nframes64_t target;
983         Location* loc;
984         bool ignored;
985
986         if (!_session) {
987                 return;
988         }
989
990         if (selection->markers.empty()) {
991                 nframes64_t mouse;
992                 bool ignored;
993
994                 if (!mouse_frame (mouse, ignored)) {
995                         return;
996                 }
997
998                 add_location_mark (mouse);
999         }
1000
1001         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1002                 return;
1003         }
1004
1005         nframes64_t pos = loc->start();
1006
1007         // so we don't find the current region again..
1008         if (dir > 0 || pos > 0) {
1009                 pos += dir;
1010         }
1011
1012         if ((target = get_region_boundary (pos, dir, with_selection, false)) < 0) {
1013                 return;
1014         }
1015
1016         loc->move_to (target);
1017 }
1018
1019 void
1020 Editor::selected_marker_to_next_region_boundary (bool with_selection)
1021 {
1022         selected_marker_to_region_boundary (with_selection, 1);
1023 }
1024
1025 void
1026 Editor::selected_marker_to_previous_region_boundary (bool with_selection)
1027 {
1028         selected_marker_to_region_boundary (with_selection, -1);
1029 }
1030
1031 void
1032 Editor::selected_marker_to_region_point (RegionPoint point, int32_t dir)
1033 {
1034         boost::shared_ptr<Region> r;
1035         nframes64_t pos;
1036         Location* loc;
1037         bool ignored;
1038
1039         if (!_session || selection->markers.empty()) {
1040                 return;
1041         }
1042
1043         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1044                 return;
1045         }
1046
1047         TimeAxisView *ontrack = 0;
1048
1049         pos = loc->start();
1050
1051         // so we don't find the current region again..
1052         if (dir>0 || pos>0)
1053                 pos+=dir;
1054
1055         if (!selection->tracks.empty()) {
1056
1057                 r = find_next_region (pos, point, dir, selection->tracks, &ontrack);
1058
1059         } else {
1060
1061                 r = find_next_region (pos, point, dir, track_views, &ontrack);
1062         }
1063
1064         if (r == 0) {
1065                 return;
1066         }
1067
1068         switch (point){
1069         case Start:
1070                 pos = r->first_frame ();
1071                 break;
1072
1073         case End:
1074                 pos = r->last_frame ();
1075                 break;
1076
1077         case SyncPoint:
1078                 pos = r->adjust_to_sync (r->first_frame());
1079                 break;
1080         }
1081
1082         float speed = 1.0f;
1083         RouteTimeAxisView *rtav;
1084
1085         if (ontrack != 0 && (rtav = dynamic_cast<RouteTimeAxisView*>(ontrack)) != 0) {
1086                 if (rtav->get_diskstream() != 0) {
1087                         speed = rtav->get_diskstream()->speed();
1088                 }
1089         }
1090
1091         pos = track_frame_to_session_frame(pos, speed);
1092
1093         loc->move_to (pos);
1094 }
1095
1096 void
1097 Editor::selected_marker_to_next_region_point (RegionPoint point)
1098 {
1099         selected_marker_to_region_point (point, 1);
1100 }
1101
1102 void
1103 Editor::selected_marker_to_previous_region_point (RegionPoint point)
1104 {
1105         selected_marker_to_region_point (point, -1);
1106 }
1107
1108 void
1109 Editor::selected_marker_to_selection_start ()
1110 {
1111         nframes64_t pos = 0;
1112         Location* loc;
1113         bool ignored;
1114
1115         if (!_session || selection->markers.empty()) {
1116                 return;
1117         }
1118
1119         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1120                 return;
1121         }
1122
1123         RegionSelection rs;
1124
1125         get_regions_for_action (rs);
1126
1127         switch (mouse_mode) {
1128         case MouseObject:
1129                 if (!rs.empty()) {
1130                         pos = rs.start();
1131                 }
1132                 break;
1133
1134         case MouseRange:
1135                 if (!selection->time.empty()) {
1136                         pos = selection->time.start ();
1137                 }
1138                 break;
1139
1140         default:
1141                 return;
1142         }
1143
1144         loc->move_to (pos);
1145 }
1146
1147 void
1148 Editor::selected_marker_to_selection_end ()
1149 {
1150         nframes64_t pos = 0;
1151         Location* loc;
1152         bool ignored;
1153
1154         if (!_session || selection->markers.empty()) {
1155                 return;
1156         }
1157
1158         if ((loc = find_location_from_marker (selection->markers.front(), ignored)) == 0) {
1159                 return;
1160         }
1161
1162         RegionSelection rs;
1163
1164         get_regions_for_action (rs);
1165
1166         switch (mouse_mode) {
1167         case MouseObject:
1168                 if (!rs.empty()) {
1169                         pos = rs.end_frame();
1170                 }
1171                 break;
1172
1173         case MouseRange:
1174                 if (!selection->time.empty()) {
1175                         pos = selection->time.end_frame ();
1176                 }
1177                 break;
1178
1179         default:
1180                 return;
1181         }
1182
1183         loc->move_to (pos);
1184 }
1185
1186 void
1187 Editor::scroll_playhead (bool forward)
1188 {
1189         nframes64_t pos = playhead_cursor->current_frame;
1190         nframes64_t delta = (nframes64_t) floor (current_page_frames() / 0.8);
1191
1192         if (forward) {
1193                 if (pos == max_frames) {
1194                         return;
1195                 }
1196
1197                 if (pos < max_frames - delta) {
1198                         pos += delta ;
1199                 } else {
1200                         pos = max_frames;
1201                 }
1202
1203         } else {
1204
1205                 if (pos == 0) {
1206                         return;
1207                 }
1208
1209                 if (pos > delta) {
1210                         pos -= delta;
1211                 } else {
1212                         pos = 0;
1213                 }
1214         }
1215
1216         _session->request_locate (pos);
1217 }
1218
1219 void
1220 Editor::playhead_backward ()
1221 {
1222         nframes64_t pos;
1223         nframes64_t cnt;
1224         float prefix;
1225         bool was_floating;
1226
1227         if (get_prefix (prefix, was_floating)) {
1228                 cnt = 1;
1229         } else {
1230                 if (was_floating) {
1231                         cnt = (nframes64_t) floor (prefix * _session->frame_rate ());
1232                 } else {
1233                         cnt = (nframes64_t) prefix;
1234                 }
1235         }
1236
1237         pos = playhead_cursor->current_frame;
1238
1239         if ((nframes64_t) pos < cnt) {
1240                 pos = 0;
1241         } else {
1242                 pos -= cnt;
1243         }
1244
1245         /* XXX this is completely insane. with the current buffering
1246            design, we'll force a complete track buffer flush and
1247            reload, just to move 1 sample !!!
1248         */
1249
1250         _session->request_locate (pos);
1251 }
1252
1253 void
1254 Editor::playhead_forward ()
1255 {
1256         nframes64_t pos;
1257         nframes64_t cnt;
1258         bool was_floating;
1259         float prefix;
1260
1261         if (get_prefix (prefix, was_floating)) {
1262                 cnt = 1;
1263         } else {
1264                 if (was_floating) {
1265                         cnt = (nframes64_t) floor (prefix * _session->frame_rate ());
1266                 } else {
1267                         cnt = (nframes64_t) floor (prefix);
1268                 }
1269         }
1270
1271         pos = playhead_cursor->current_frame;
1272
1273         /* XXX this is completely insane. with the current buffering
1274            design, we'll force a complete track buffer flush and
1275            reload, just to move 1 sample !!!
1276         */
1277
1278         _session->request_locate (pos+cnt);
1279 }
1280
1281 void
1282 Editor::cursor_align (bool playhead_to_edit)
1283 {
1284         if (!_session) {
1285                 return;
1286         }
1287
1288         if (playhead_to_edit) {
1289
1290                 if (selection->markers.empty()) {
1291                         return;
1292                 }
1293
1294                 _session->request_locate (selection->markers.front()->position(), _session->transport_rolling());
1295
1296         } else {
1297                 /* move selected markers to playhead */
1298
1299                 for (MarkerSelection::iterator i = selection->markers.begin(); i != selection->markers.end(); ++i) {
1300                         bool ignored;
1301
1302                         Location* loc = find_location_from_marker (*i, ignored);
1303
1304                         if (loc->is_mark()) {
1305                                 loc->set_start (playhead_cursor->current_frame);
1306                         } else {
1307                                 loc->set (playhead_cursor->current_frame,
1308                                           playhead_cursor->current_frame + loc->length());
1309                         }
1310                 }
1311         }
1312 }
1313
1314 void
1315 Editor::edit_cursor_backward ()
1316 {
1317         nframes64_t pos;
1318         nframes64_t cnt;
1319         float prefix;
1320         bool was_floating;
1321
1322         if (get_prefix (prefix, was_floating)) {
1323                 cnt = 1;
1324         } else {
1325                 if (was_floating) {
1326                         cnt = (nframes64_t) floor (prefix * _session->frame_rate ());
1327                 } else {
1328                         cnt = (nframes64_t) prefix;
1329                 }
1330         }
1331
1332         if ((pos = get_preferred_edit_position()) < 0) {
1333                 return;
1334         }
1335
1336         if (pos < cnt) {
1337                 pos = 0;
1338         } else {
1339                 pos -= cnt;
1340         }
1341
1342         // EDIT CURSOR edit_cursor->set_position (pos);
1343 }
1344
1345 void
1346 Editor::edit_cursor_forward ()
1347 {
1348         //nframes64_t pos;
1349         nframes64_t cnt;
1350         bool was_floating;
1351         float prefix;
1352
1353         if (get_prefix (prefix, was_floating)) {
1354                 cnt = 1;
1355         } else {
1356                 if (was_floating) {
1357                         cnt = (nframes64_t) floor (prefix * _session->frame_rate ());
1358                 } else {
1359                         cnt = (nframes64_t) floor (prefix);
1360                 }
1361         }
1362
1363         // pos = edit_cursor->current_frame;
1364         // EDIT CURSOR edit_cursor->set_position (pos+cnt);
1365 }
1366
1367 void
1368 Editor::goto_frame ()
1369 {
1370         float prefix;
1371         bool was_floating;
1372         nframes64_t frame;
1373
1374         if (get_prefix (prefix, was_floating)) {
1375                 return;
1376         }
1377
1378         if (was_floating) {
1379                 frame = (nframes64_t) floor (prefix * _session->frame_rate());
1380         } else {
1381                 frame = (nframes64_t) floor (prefix);
1382         }
1383
1384         _session->request_locate (frame);
1385 }
1386
1387 void
1388 Editor::scroll_backward (float pages)
1389 {
1390         nframes64_t frame;
1391         nframes64_t one_page = (nframes64_t) rint (_canvas_width * frames_per_unit);
1392         bool was_floating;
1393         float prefix;
1394         nframes64_t cnt;
1395
1396         if (get_prefix (prefix, was_floating)) {
1397                 cnt = (nframes64_t) floor (pages * one_page);
1398         } else {
1399                 if (was_floating) {
1400                         cnt = (nframes64_t) floor (prefix * _session->frame_rate());
1401                 } else {
1402                         cnt = (nframes64_t) floor (prefix * one_page);
1403                 }
1404         }
1405
1406         if (leftmost_frame < cnt) {
1407                 frame = 0;
1408         } else {
1409                 frame = leftmost_frame - cnt;
1410         }
1411
1412         reset_x_origin (frame);
1413 }
1414
1415 void
1416 Editor::scroll_forward (float pages)
1417 {
1418         nframes64_t frame;
1419         nframes64_t one_page = (nframes64_t) rint (_canvas_width * frames_per_unit);
1420         bool was_floating;
1421         float prefix;
1422         nframes64_t cnt;
1423
1424         if (get_prefix (prefix, was_floating)) {
1425                 cnt = (nframes64_t) floor (pages * one_page);
1426         } else {
1427                 if (was_floating) {
1428                         cnt = (nframes64_t) floor (prefix * _session->frame_rate());
1429                 } else {
1430                         cnt = (nframes64_t) floor (prefix * one_page);
1431                 }
1432         }
1433
1434         if (max_frames - cnt < leftmost_frame) {
1435                 frame = max_frames - cnt;
1436         } else {
1437                 frame = leftmost_frame + cnt;
1438         }
1439
1440         reset_x_origin (frame);
1441 }
1442
1443 void
1444 Editor::scroll_tracks_down ()
1445 {
1446         float prefix;
1447         bool was_floating;
1448         int cnt;
1449
1450         if (get_prefix (prefix, was_floating)) {
1451                 cnt = 1;
1452         } else {
1453                 cnt = (int) floor (prefix);
1454         }
1455
1456         double vert_value = vertical_adjustment.get_value() + (cnt *
1457                 vertical_adjustment.get_page_size());
1458         if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
1459                 vert_value = vertical_adjustment.get_upper() - _canvas_height;
1460         }
1461         vertical_adjustment.set_value (vert_value);
1462 }
1463
1464 void
1465 Editor::scroll_tracks_up ()
1466 {
1467         float prefix;
1468         bool was_floating;
1469         int cnt;
1470
1471         if (get_prefix (prefix, was_floating)) {
1472                 cnt = 1;
1473         } else {
1474                 cnt = (int) floor (prefix);
1475         }
1476
1477         vertical_adjustment.set_value (vertical_adjustment.get_value() - (cnt * vertical_adjustment.get_page_size()));
1478 }
1479
1480 void
1481 Editor::scroll_tracks_down_line ()
1482 {
1483         double vert_value = vertical_adjustment.get_value() + 60;
1484
1485         if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
1486                 vert_value = vertical_adjustment.get_upper() - _canvas_height;
1487         }
1488         
1489         vertical_adjustment.set_value (vert_value);
1490 }
1491
1492 void
1493 Editor::scroll_tracks_up_line ()
1494 {
1495         reset_y_origin (vertical_adjustment.get_value() - 60);
1496 }
1497
1498 /* ZOOM */
1499
1500 void
1501 Editor::tav_zoom_step (bool coarser)
1502 {
1503         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
1504
1505         _routes->suspend_redisplay ();
1506
1507         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1508                 TimeAxisView *tv = (static_cast<TimeAxisView*>(*i));
1509                         tv->step_height (coarser);
1510         }
1511
1512         _routes->resume_redisplay ();
1513 }
1514
1515 void
1516 Editor::temporal_zoom_step (bool coarser)
1517 {
1518         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
1519
1520         double nfpu;
1521
1522         nfpu = frames_per_unit;
1523
1524         if (coarser) {
1525                 nfpu *= 1.61803399;
1526         } else {
1527                 nfpu = max(1.0,(nfpu/1.61803399));
1528         }
1529
1530         temporal_zoom (nfpu);
1531 }
1532
1533 void
1534 Editor::temporal_zoom (gdouble fpu)
1535 {
1536         if (!_session) return;
1537
1538         nframes64_t current_page = current_page_frames();
1539         nframes64_t current_leftmost = leftmost_frame;
1540         nframes64_t current_rightmost;
1541         nframes64_t current_center;
1542         nframes64_t new_page_size;
1543         nframes64_t half_page_size;
1544         nframes64_t leftmost_after_zoom = 0;
1545         nframes64_t where;
1546         bool in_track_canvas;
1547         double nfpu;
1548         double l;
1549
1550         /* XXX this limit is also in ::set_frames_per_unit() */
1551
1552         if (frames_per_unit <= 2.0 && fpu <= frames_per_unit) {
1553                 return;
1554         }
1555
1556         nfpu = fpu;
1557
1558         new_page_size = (nframes64_t) floor (_canvas_width * nfpu);
1559         half_page_size = new_page_size / 2;
1560
1561         switch (zoom_focus) {
1562         case ZoomFocusLeft:
1563                 leftmost_after_zoom = current_leftmost;
1564                 break;
1565
1566         case ZoomFocusRight:
1567                 current_rightmost = leftmost_frame + current_page;
1568                 if (current_rightmost < new_page_size) {
1569                         leftmost_after_zoom = 0;
1570                 } else {
1571                         leftmost_after_zoom = current_rightmost - new_page_size;
1572                 }
1573                 break;
1574
1575         case ZoomFocusCenter:
1576                 current_center = current_leftmost + (current_page/2);
1577                 if (current_center < half_page_size) {
1578                         leftmost_after_zoom = 0;
1579                 } else {
1580                         leftmost_after_zoom = current_center - half_page_size;
1581                 }
1582                 break;
1583
1584         case ZoomFocusPlayhead:
1585                 /* centre playhead */
1586                 l = playhead_cursor->current_frame - (new_page_size * 0.5);
1587
1588                 if (l < 0) {
1589                         leftmost_after_zoom = 0;
1590                 } else if (l > max_frames) {
1591                         leftmost_after_zoom = max_frames - new_page_size;
1592                 } else {
1593                         leftmost_after_zoom = (nframes64_t) l;
1594                 }
1595                 break;
1596
1597         case ZoomFocusMouse:
1598                 /* try to keep the mouse over the same point in the display */
1599
1600                 if (!mouse_frame (where, in_track_canvas)) {
1601                         /* use playhead instead */
1602                         where = playhead_cursor->current_frame;
1603
1604                         if (where < half_page_size) {
1605                                 leftmost_after_zoom = 0;
1606                         } else {
1607                                 leftmost_after_zoom = where - half_page_size;
1608                         }
1609
1610                 } else {
1611
1612                         l = - ((new_page_size * ((where - current_leftmost)/(double)current_page)) - where);
1613
1614                         if (l < 0) {
1615                                 leftmost_after_zoom = 0;
1616                         } else if (l > max_frames) {
1617                                 leftmost_after_zoom = max_frames - new_page_size;
1618                         } else {
1619                                 leftmost_after_zoom = (nframes64_t) l;
1620                         }
1621                 }
1622
1623                 break;
1624
1625         case ZoomFocusEdit:
1626                 /* try to keep the edit point in the same place */
1627                 where = get_preferred_edit_position ();
1628
1629                 if (where > 0) {
1630
1631                         double l = - ((new_page_size * ((where - current_leftmost)/(double)current_page)) - where);
1632
1633                         if (l < 0) {
1634                                 leftmost_after_zoom = 0;
1635                         } else if (l > max_frames) {
1636                                 leftmost_after_zoom = max_frames - new_page_size;
1637                         } else {
1638                                 leftmost_after_zoom = (nframes64_t) l;
1639                         }
1640
1641                 } else {
1642                         /* edit point not defined */
1643                         return;
1644                 }
1645                 break;
1646
1647         }
1648
1649         // leftmost_after_zoom = min (leftmost_after_zoom, _session->current_end_frame());
1650
1651         reposition_and_zoom (leftmost_after_zoom, nfpu);
1652 }
1653
1654 void
1655 Editor::temporal_zoom_region (bool both_axes)
1656 {
1657
1658         nframes64_t start = max_frames;
1659         nframes64_t end = 0;
1660         RegionSelection rs;
1661         set<TimeAxisView*> tracks;
1662
1663         get_regions_for_action (rs);
1664
1665         if (rs.empty()) {
1666                 return;
1667         }
1668
1669         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
1670
1671                 if ((*i)->region()->position() < start) {
1672                         start = (*i)->region()->position();
1673                 }
1674
1675                 if ((*i)->region()->last_frame() + 1 > end) {
1676                         end = (*i)->region()->last_frame() + 1;
1677                 }
1678
1679                 tracks.insert (&((*i)->get_time_axis_view()));
1680         }
1681
1682         /* now comes an "interesting" hack ... make sure we leave a little space
1683            at each end of the editor so that the zoom doesn't fit the region
1684            precisely to the screen.
1685         */
1686
1687         GdkScreen* screen = gdk_screen_get_default ();
1688         gint pixwidth = gdk_screen_get_width (screen);
1689         gint mmwidth = gdk_screen_get_width_mm (screen);
1690         double pix_per_mm = (double) pixwidth/ (double) mmwidth;
1691         double one_centimeter_in_pixels = pix_per_mm * 10.0;
1692
1693         if ((start == 0 && end == 0) || end < start) {
1694                 return;
1695         }
1696
1697         nframes64_t range = end - start;
1698         double new_fpu = (double)range / (double)_canvas_width;
1699         nframes64_t extra_samples = (nframes64_t) floor (one_centimeter_in_pixels * new_fpu);
1700
1701         if (start > extra_samples) {
1702                 start -= extra_samples;
1703         } else {
1704                 start = 0;
1705         }
1706
1707         if (max_frames - extra_samples > end) {
1708                 end += extra_samples;
1709         } else {
1710                 end = max_frames;
1711         }
1712
1713         if (both_axes) {
1714                 /* save visual state with track states included, and prevent
1715                    set_frames_per_unit() from doing it again.
1716                 */
1717                 undo_visual_stack.push_back (current_visual_state(true));
1718                 no_save_visual = true;
1719         }
1720
1721         temporal_zoom_by_frame (start, end, "zoom to region");
1722
1723         if (both_axes) {
1724                 uint32_t per_track_height = (uint32_t) floor ((_canvas_height - canvas_timebars_vsize - 10.0) / tracks.size());
1725
1726                 /* set visible track heights appropriately */
1727
1728                 for (set<TimeAxisView*>::iterator t = tracks.begin(); t != tracks.end(); ++t) {
1729                         (*t)->set_height (per_track_height);
1730                 }
1731
1732                 /* hide irrelevant tracks */
1733
1734                 _routes->suspend_redisplay ();
1735
1736                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1737                         if (find (tracks.begin(), tracks.end(), (*i)) == tracks.end()) {
1738                                 hide_track_in_display (**i, true);
1739                         }
1740                 }
1741
1742                 _routes->resume_redisplay ();
1743
1744                 vertical_adjustment.set_value (0.0);
1745                 no_save_visual = false;
1746         }
1747
1748         redo_visual_stack.push_back (current_visual_state());
1749 }
1750
1751 void
1752 Editor::zoom_to_region (bool both_axes)
1753 {
1754         temporal_zoom_region (both_axes);
1755 }
1756
1757 void
1758 Editor::temporal_zoom_selection ()
1759 {
1760         if (!selection) return;
1761
1762         if (selection->time.empty()) {
1763                 return;
1764         }
1765
1766         nframes64_t start = selection->time[clicked_selection].start;
1767         nframes64_t end = selection->time[clicked_selection].end;
1768
1769         temporal_zoom_by_frame (start, end, "zoom to selection");
1770 }
1771
1772 void
1773 Editor::temporal_zoom_session ()
1774 {
1775         ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_session)
1776
1777         if (_session) {
1778                 temporal_zoom_by_frame (_session->current_start_frame(), _session->current_end_frame(), "zoom to _session");
1779         }
1780 }
1781
1782 void
1783 Editor::temporal_zoom_by_frame (nframes64_t start, nframes64_t end, const string & /*op*/)
1784 {
1785         if (!_session) return;
1786
1787         if ((start == 0 && end == 0) || end < start) {
1788                 return;
1789         }
1790
1791         nframes64_t range = end - start;
1792
1793         double new_fpu = (double)range / (double)_canvas_width;
1794
1795         nframes64_t new_page = (nframes64_t) floor (_canvas_width * new_fpu);
1796         nframes64_t middle = (nframes64_t) floor( (double)start + ((double)range / 2.0f ));
1797         nframes64_t new_leftmost = (nframes64_t) floor( (double)middle - ((double)new_page/2.0f));
1798
1799         if (new_leftmost > middle) {
1800                 new_leftmost = 0;
1801         }
1802
1803         reposition_and_zoom (new_leftmost, new_fpu);
1804 }
1805
1806 void
1807 Editor::temporal_zoom_to_frame (bool coarser, nframes64_t frame)
1808 {
1809         if (!_session) {
1810                 return;
1811         }
1812         double range_before = frame - leftmost_frame;
1813         double new_fpu;
1814
1815         new_fpu = frames_per_unit;
1816
1817         if (coarser) {
1818                 new_fpu *= 1.61803399;
1819                 range_before *= 1.61803399;
1820         } else {
1821                 new_fpu = max(1.0,(new_fpu/1.61803399));
1822                 range_before /= 1.61803399;
1823         }
1824
1825         if (new_fpu == frames_per_unit)  {
1826                 return;
1827         }
1828
1829         nframes64_t new_leftmost = frame - (nframes64_t)range_before;
1830
1831         if (new_leftmost > frame) {
1832                 new_leftmost = 0;
1833         }
1834 //      begin_reversible_command (_("zoom to frame"));
1835 //      _session->add_undo (sigc::bind (sigc::mem_fun(*this, &Editor::reposition_and_zoom), leftmost_frame, frames_per_unit));
1836 //      _session->add_redo (sigc::bind (sigc::mem_fun(*this, &Editor::reposition_and_zoom), new_leftmost, new_fpu));
1837 //      commit_reversible_command ();
1838
1839         reposition_and_zoom (new_leftmost, new_fpu);
1840 }
1841
1842
1843 bool
1844 Editor::choose_new_marker_name(string &name) {
1845
1846         if (!Config->get_name_new_markers()) {
1847                 /* don't prompt user for a new name */
1848                 return true;
1849         }
1850
1851         ArdourPrompter dialog (true);
1852
1853         dialog.set_prompt (_("New Name:"));
1854
1855         dialog.set_title (_("New Location Marker"));
1856
1857         dialog.set_name ("MarkNameWindow");
1858         dialog.set_size_request (250, -1);
1859         dialog.set_position (Gtk::WIN_POS_MOUSE);
1860
1861         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
1862         dialog.set_initial_text (name);
1863
1864         dialog.show ();
1865
1866         switch (dialog.run ()) {
1867         case RESPONSE_ACCEPT:
1868                 break;
1869         default:
1870                 return false;
1871         }
1872
1873         dialog.get_result(name);
1874         return true;
1875
1876 }
1877
1878
1879 void
1880 Editor::add_location_from_selection ()
1881 {
1882         string rangename;
1883
1884         if (selection->time.empty()) {
1885                 return;
1886         }
1887
1888         if (_session == 0 || clicked_axisview == 0) {
1889                 return;
1890         }
1891
1892         nframes64_t start = selection->time[clicked_selection].start;
1893         nframes64_t end = selection->time[clicked_selection].end;
1894
1895         _session->locations()->next_available_name(rangename,"selection");
1896         Location *location = new Location (start, end, rangename, Location::IsRangeMarker);
1897
1898         _session->begin_reversible_command (_("add marker"));
1899         XMLNode &before = _session->locations()->get_state();
1900         _session->locations()->add (location, true);
1901         XMLNode &after = _session->locations()->get_state();
1902         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1903         _session->commit_reversible_command ();
1904 }
1905
1906 void
1907 Editor::add_location_mark (nframes64_t where)
1908 {
1909         string markername;
1910
1911         select_new_marker = true;
1912
1913         _session->locations()->next_available_name(markername,"mark");
1914         if (!choose_new_marker_name(markername)) {
1915                 return;
1916         }
1917         Location *location = new Location (where, where, markername, Location::IsMark);
1918         _session->begin_reversible_command (_("add marker"));
1919         XMLNode &before = _session->locations()->get_state();
1920         _session->locations()->add (location, true);
1921         XMLNode &after = _session->locations()->get_state();
1922         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1923         _session->commit_reversible_command ();
1924 }
1925
1926 void
1927 Editor::add_location_from_playhead_cursor ()
1928 {
1929         add_location_mark (_session->audible_frame());
1930 }
1931
1932 void
1933 Editor::add_locations_from_audio_region ()
1934 {
1935         RegionSelection rs;
1936
1937         get_regions_for_action (rs);
1938
1939         if (rs.empty()) {
1940                 return;
1941         }
1942
1943         _session->begin_reversible_command (rs.size () > 1 ? _("add markers") : _("add marker"));
1944         XMLNode &before = _session->locations()->get_state();
1945
1946         cerr << "Add locations\n";
1947
1948         for (RegionSelection::iterator i = rs.begin (); i != rs.end (); ++i) {
1949
1950                 boost::shared_ptr<Region> region = (*i)->region ();
1951
1952                 Location *location = new Location (region->position(), region->last_frame(), region->name(), Location::IsRangeMarker);
1953
1954                 _session->locations()->add (location, true);
1955         }
1956
1957         XMLNode &after = _session->locations()->get_state();
1958         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1959         _session->commit_reversible_command ();
1960 }
1961
1962 void
1963 Editor::add_location_from_audio_region ()
1964 {
1965         RegionSelection rs;
1966
1967         get_regions_for_action (rs);
1968
1969         if (rs.empty()) {
1970                 return;
1971         }
1972
1973         _session->begin_reversible_command (_("add marker"));
1974         XMLNode &before = _session->locations()->get_state();
1975
1976         string markername;
1977
1978         if (rs.size() > 1) {            // more than one region selected
1979                 _session->locations()->next_available_name(markername, "regions");
1980         } else {
1981                 RegionView* rv = *(rs.begin());
1982                 boost::shared_ptr<Region> region = rv->region();
1983                 markername = region->name();
1984         }
1985
1986         if (!choose_new_marker_name(markername)) {
1987                 return;
1988         }
1989
1990         cerr << "Add location\n";
1991
1992         // single range spanning all selected
1993         Location *location = new Location (rs.start(), rs.end_frame(), markername, Location::IsRangeMarker);
1994         _session->locations()->add (location, true);
1995
1996         XMLNode &after = _session->locations()->get_state();
1997         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1998         _session->commit_reversible_command ();
1999 }
2000
2001 void
2002 Editor::amplitude_zoom_step (bool in)
2003 {
2004         gdouble zoom = 1.0;
2005
2006         if (in) {
2007                 zoom *= 2.0;
2008         } else {
2009                 if (zoom > 2.0) {
2010                         zoom /= 2.0;
2011                 } else {
2012                         zoom = 1.0;
2013                 }
2014         }
2015
2016 #ifdef FIX_FOR_CANVAS
2017         /* XXX DO SOMETHING */
2018 #endif
2019 }
2020
2021
2022 /* DELETION */
2023
2024
2025 void
2026 Editor::delete_sample_forward ()
2027 {
2028 }
2029
2030 void
2031 Editor::delete_sample_backward ()
2032 {
2033 }
2034
2035 void
2036 Editor::delete_screen ()
2037 {
2038 }
2039
2040 /* SEARCH */
2041
2042 void
2043 Editor::search_backwards ()
2044 {
2045         /* what ? */
2046 }
2047
2048 void
2049 Editor::search_forwards ()
2050 {
2051         /* what ? */
2052 }
2053
2054 /* MARKS */
2055
2056 void
2057 Editor::jump_forward_to_mark ()
2058 {
2059         if (!_session) {
2060                 return;
2061         }
2062
2063         Location *location = _session->locations()->first_location_after (playhead_cursor->current_frame);
2064
2065         if (location) {
2066                 _session->request_locate (location->start(), _session->transport_rolling());
2067         } else {
2068                 _session->request_locate (_session->current_end_frame());
2069         }
2070 }
2071
2072 void
2073 Editor::jump_backward_to_mark ()
2074 {
2075         if (!_session) {
2076                 return;
2077         }
2078
2079         Location *location = _session->locations()->first_location_before (playhead_cursor->current_frame);
2080
2081         if (location) {
2082                 _session->request_locate (location->start(), _session->transport_rolling());
2083         } else {
2084                 _session->goto_start ();
2085         }
2086 }
2087
2088 void
2089 Editor::set_mark ()
2090 {
2091         nframes64_t pos;
2092         float prefix;
2093         bool was_floating;
2094         string markername;
2095
2096         if (get_prefix (prefix, was_floating)) {
2097                 pos = _session->audible_frame ();
2098         } else {
2099                 if (was_floating) {
2100                         pos = (nframes64_t) floor (prefix * _session->frame_rate ());
2101                 } else {
2102                         pos = (nframes64_t) floor (prefix);
2103                 }
2104         }
2105
2106         _session->locations()->next_available_name(markername,"mark");
2107         if (!choose_new_marker_name(markername)) {
2108                 return;
2109         }
2110         _session->locations()->add (new Location (pos, 0, markername, Location::IsMark), true);
2111 }
2112
2113 void
2114 Editor::clear_markers ()
2115 {
2116         if (_session) {
2117                 _session->begin_reversible_command (_("clear markers"));
2118                 XMLNode &before = _session->locations()->get_state();
2119                 _session->locations()->clear_markers ();
2120                 XMLNode &after = _session->locations()->get_state();
2121                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2122                 _session->commit_reversible_command ();
2123         }
2124 }
2125
2126 void
2127 Editor::clear_ranges ()
2128 {
2129         if (_session) {
2130                 _session->begin_reversible_command (_("clear ranges"));
2131                 XMLNode &before = _session->locations()->get_state();
2132
2133                 Location * looploc = _session->locations()->auto_loop_location();
2134                 Location * punchloc = _session->locations()->auto_punch_location();
2135
2136                 _session->locations()->clear_ranges ();
2137                 // re-add these
2138                 if (looploc) _session->locations()->add (looploc);
2139                 if (punchloc) _session->locations()->add (punchloc);
2140
2141                 XMLNode &after = _session->locations()->get_state();
2142                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2143                 _session->commit_reversible_command ();
2144         }
2145 }
2146
2147 void
2148 Editor::clear_locations ()
2149 {
2150         _session->begin_reversible_command (_("clear locations"));
2151         XMLNode &before = _session->locations()->get_state();
2152         _session->locations()->clear ();
2153         XMLNode &after = _session->locations()->get_state();
2154         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
2155         _session->commit_reversible_command ();
2156         _session->locations()->clear ();
2157 }
2158
2159 void
2160 Editor::unhide_markers ()
2161 {
2162         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
2163                 Location *l = (*i).first;
2164                 if (l->is_hidden() && l->is_mark()) {
2165                         l->set_hidden(false, this);
2166                 }
2167         }
2168 }
2169
2170 void
2171 Editor::unhide_ranges ()
2172 {
2173         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
2174                 Location *l = (*i).first;
2175                 if (l->is_hidden() && l->is_range_marker()) {
2176                         l->set_hidden(false, this);
2177                 }
2178         }
2179 }
2180
2181 /* INSERT/REPLACE */
2182
2183 void
2184 Editor::insert_region_list_drag (boost::shared_ptr<Region> region, int x, int y)
2185 {
2186         double wx, wy;
2187         double cx, cy;
2188         nframes64_t where;
2189         RouteTimeAxisView *rtv = 0;
2190         boost::shared_ptr<Playlist> playlist;
2191
2192         track_canvas->window_to_world (x, y, wx, wy);
2193         //wx += horizontal_adjustment.get_value();
2194         //wy += vertical_adjustment.get_value();
2195
2196         GdkEvent event;
2197         event.type = GDK_BUTTON_RELEASE;
2198         event.button.x = wx;
2199         event.button.y = wy;
2200
2201         where = event_frame (&event, &cx, &cy);
2202
2203         if (where < leftmost_frame || where > leftmost_frame + current_page_frames()) {
2204                 /* clearly outside canvas area */
2205                 return;
2206         }
2207
2208         std::pair<TimeAxisView*, int> tv = trackview_by_y_position (cy);
2209         if (tv.first == 0) {
2210                 return;
2211         }
2212
2213         if ((rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
2214                 return;
2215         }
2216
2217         if ((playlist = rtv->playlist()) == 0) {
2218                 return;
2219         }
2220
2221         snap_to (where);
2222
2223         begin_reversible_command (_("insert dragged region"));
2224         playlist->clear_history ();
2225         playlist->add_region (RegionFactory::create (region), where, 1.0);
2226         _session->add_command(new StatefulDiffCommand (playlist));
2227         commit_reversible_command ();
2228 }
2229
2230 void
2231 Editor::insert_route_list_drag (boost::shared_ptr<Route> route, int x, int y) {
2232         double wx, wy;
2233         double cx, cy;
2234         nframes_t where;
2235         RouteTimeAxisView *dest_rtv = 0;
2236         RouteTimeAxisView *source_rtv = 0;
2237
2238         track_canvas->window_to_world (x, y, wx, wy);
2239         wx += horizontal_adjustment.get_value();
2240         wy += vertical_adjustment.get_value();
2241
2242         GdkEvent event;
2243         event.type = GDK_BUTTON_RELEASE;
2244         event.button.x = wx;
2245         event.button.y = wy;
2246
2247         where = event_frame (&event, &cx, &cy);
2248
2249         std::pair<TimeAxisView*, int> const tv = trackview_by_y_position (cy);
2250         if (tv.first == 0) {
2251                 return;
2252         }
2253
2254         if ((dest_rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
2255                 return;
2256         }
2257
2258         /* use this drag source to add underlay to a track. But we really don't care
2259            about the Route, only the view of the route, so find it first */
2260         for(TrackViewList::iterator it = track_views.begin(); it != track_views.end(); ++it) {
2261                 if((source_rtv = dynamic_cast<RouteTimeAxisView*>(*it)) == 0) {
2262                         continue;
2263                 }
2264
2265                 if(source_rtv->route() == route && source_rtv != dest_rtv) {
2266                         dest_rtv->add_underlay(source_rtv->view());
2267                         break;
2268                 }
2269         }
2270 }
2271
2272 void
2273 Editor::insert_region_list_selection (float times)
2274 {
2275         RouteTimeAxisView *tv = 0;
2276         boost::shared_ptr<Playlist> playlist;
2277
2278         if (clicked_routeview != 0) {
2279                 tv = clicked_routeview;
2280         } else if (!selection->tracks.empty()) {
2281                 if ((tv = dynamic_cast<RouteTimeAxisView*>(selection->tracks.front())) == 0) {
2282                         return;
2283                 }
2284         } else if (entered_track != 0) {
2285                 if ((tv = dynamic_cast<RouteTimeAxisView*>(entered_track)) == 0) {
2286                         return;
2287                 }
2288         } else {
2289                 return;
2290         }
2291
2292         if ((playlist = tv->playlist()) == 0) {
2293                 return;
2294         }
2295
2296         boost::shared_ptr<Region> region = _regions->get_single_selection ();
2297         if (region == 0) {
2298                 return;
2299         }
2300
2301         begin_reversible_command (_("insert region"));
2302         playlist->clear_history ();
2303         playlist->add_region ((RegionFactory::create (region)), get_preferred_edit_position(), times);
2304         _session->add_command(new StatefulDiffCommand (playlist));
2305         commit_reversible_command ();
2306 }
2307
2308 /* BUILT-IN EFFECTS */
2309
2310 void
2311 Editor::reverse_selection ()
2312 {
2313
2314 }
2315
2316 /* GAIN ENVELOPE EDITING */
2317
2318 void
2319 Editor::edit_envelope ()
2320 {
2321 }
2322
2323 /* PLAYBACK */
2324
2325 void
2326 Editor::transition_to_rolling (bool fwd)
2327 {
2328         if (!_session) {
2329                 return;
2330         }
2331
2332         if (_session->config.get_external_sync()) {
2333                 switch (_session->config.get_sync_source()) {
2334                 case JACK:
2335                         break;
2336                 default:
2337                         /* transport controlled by the master */
2338                         return;
2339                 }
2340         }
2341
2342         if (_session->is_auditioning()) {
2343                 _session->cancel_audition ();
2344                 return;
2345         }
2346
2347         _session->request_transport_speed (fwd ? 1.0f : -1.0f);
2348 }
2349
2350 void
2351 Editor::play_from_start ()
2352 {
2353         _session->request_locate (_session->current_start_frame(), true);
2354 }
2355
2356 void
2357 Editor::play_from_edit_point ()
2358 {
2359         _session->request_locate (get_preferred_edit_position(), true);
2360 }
2361
2362 void
2363 Editor::play_from_edit_point_and_return ()
2364 {
2365         nframes64_t start_frame;
2366         nframes64_t return_frame;
2367
2368         start_frame = get_preferred_edit_position (true);
2369
2370         if (_session->transport_rolling()) {
2371                 _session->request_locate (start_frame, false);
2372                 return;
2373         }
2374
2375         /* don't reset the return frame if its already set */
2376
2377         if ((return_frame = _session->requested_return_frame()) < 0) {
2378                 return_frame = _session->audible_frame();
2379         }
2380
2381         if (start_frame >= 0) {
2382                 _session->request_roll_at_and_return (start_frame, return_frame);
2383         }
2384 }
2385
2386 void
2387 Editor::play_selection ()
2388 {
2389         if (selection->time.empty()) {
2390                 return;
2391         }
2392
2393         _session->request_play_range (&selection->time, true);
2394 }
2395
2396 void
2397 Editor::loop_selected_region ()
2398 {
2399         RegionSelection rs;
2400
2401         get_regions_for_action (rs);
2402
2403         if (!rs.empty()) {
2404                 RegionView *rv = *(rs.begin());
2405                 Location* tll;
2406
2407                 if ((tll = transport_loop_location()) != 0)  {
2408
2409                         tll->set (rv->region()->position(), rv->region()->last_frame());
2410
2411                         // enable looping, reposition and start rolling
2412
2413                         _session->request_play_loop (true);
2414                         _session->request_locate (tll->start(), false);
2415                         _session->request_transport_speed (1.0f);
2416                 }
2417         }
2418 }
2419
2420 void
2421 Editor::play_location (Location& location)
2422 {
2423         if (location.start() <= location.end()) {
2424                 return;
2425         }
2426
2427         _session->request_bounded_roll (location.start(), location.end());
2428 }
2429
2430 void
2431 Editor::loop_location (Location& location)
2432 {
2433         if (location.start() <= location.end()) {
2434                 return;
2435         }
2436
2437         Location* tll;
2438
2439         if ((tll = transport_loop_location()) != 0) {
2440                 tll->set (location.start(), location.end());
2441
2442                 // enable looping, reposition and start rolling
2443                 _session->request_play_loop (true);
2444                 _session->request_locate (tll->start(), true);
2445         }
2446 }
2447
2448 void
2449 Editor::raise_region ()
2450 {
2451         selection->foreach_region (&Region::raise);
2452 }
2453
2454 void
2455 Editor::raise_region_to_top ()
2456 {
2457         selection->foreach_region (&Region::raise_to_top);
2458 }
2459
2460 void
2461 Editor::lower_region ()
2462 {
2463         selection->foreach_region (&Region::lower);
2464 }
2465
2466 void
2467 Editor::lower_region_to_bottom ()
2468 {
2469         selection->foreach_region (&Region::lower_to_bottom);
2470 }
2471
2472 /** Show the region editor for the selected regions */
2473 void
2474 Editor::edit_region ()
2475 {
2476         selection->foreach_regionview (&RegionView::show_region_editor);
2477 }
2478
2479 /** Show the midi list editor for the selected MIDI regions */
2480 void
2481 Editor::show_midi_list_editor ()
2482 {
2483         selection->foreach_midi_regionview (&MidiRegionView::show_list_editor);
2484 }
2485
2486 void
2487 Editor::rename_region()
2488 {
2489         RegionSelection rs;
2490
2491         get_regions_for_action (rs);
2492
2493         if (rs.empty()) {
2494                 return;
2495         }
2496
2497         ArdourDialog d (*this, _("Rename Region"), true, false);
2498         Entry entry;
2499         Label label (_("New name:"));
2500         HBox hbox;
2501
2502         hbox.set_spacing (6);
2503         hbox.pack_start (label, false, false);
2504         hbox.pack_start (entry, true, true);
2505
2506         d.get_vbox()->set_border_width (12);
2507         d.get_vbox()->pack_start (hbox, false, false);
2508
2509         d.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
2510         d.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2511
2512         d.set_size_request (300, -1);
2513         d.set_position (Gtk::WIN_POS_MOUSE);
2514
2515         entry.set_text (rs.front()->region()->name());
2516         entry.select_region (0, -1);
2517
2518         entry.signal_activate().connect (sigc::bind (sigc::mem_fun (d, &Dialog::response), RESPONSE_OK));
2519
2520         d.show_all ();
2521
2522         entry.grab_focus();
2523
2524         int ret = d.run();
2525
2526         d.hide ();
2527
2528         if (ret == RESPONSE_OK) {
2529                 std::string str = entry.get_text();
2530                 strip_whitespace_edges (str);
2531                 if (!str.empty()) {
2532                         rs.front()->region()->set_name (str);
2533                         _regions->redisplay ();
2534                 }
2535         }
2536 }
2537
2538 void
2539 Editor::audition_playlist_region_via_route (boost::shared_ptr<Region> region, Route& route)
2540 {
2541         if (_session->is_auditioning()) {
2542                 _session->cancel_audition ();
2543         }
2544
2545         // note: some potential for creativity here, because region doesn't
2546         // have to belong to the playlist that Route is handling
2547
2548         // bool was_soloed = route.soloed();
2549
2550         route.set_solo (true, this);
2551
2552         _session->request_bounded_roll (region->position(), region->position() + region->length());
2553
2554         /* XXX how to unset the solo state ? */
2555 }
2556
2557 /** Start an audition of the first selected region */
2558 void
2559 Editor::play_edit_range ()
2560 {
2561         nframes64_t start, end;
2562
2563         if (get_edit_op_range (start, end)) {
2564                 _session->request_bounded_roll (start, end);
2565         }
2566 }
2567
2568 void
2569 Editor::play_selected_region ()
2570 {
2571         nframes64_t start = max_frames;
2572         nframes64_t end = 0;
2573         RegionSelection rs;
2574
2575         get_regions_for_action (rs);
2576
2577         if (rs.empty()) {
2578                 return;
2579         }
2580
2581         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2582                 if ((*i)->region()->position() < start) {
2583                         start = (*i)->region()->position();
2584                 }
2585                 if ((*i)->region()->last_frame() + 1 > end) {
2586                         end = (*i)->region()->last_frame() + 1;
2587                 }
2588         }
2589
2590         _session->request_bounded_roll (start, end);
2591 }
2592
2593 void
2594 Editor::audition_playlist_region_standalone (boost::shared_ptr<Region> region)
2595 {
2596         _session->audition_region (region);
2597 }
2598
2599 void
2600 Editor::build_interthread_progress_window ()
2601 {
2602         interthread_progress_window = new ArdourDialog (X_("interthread progress"), true);
2603
2604         interthread_progress_bar.set_orientation (Gtk::PROGRESS_LEFT_TO_RIGHT);
2605
2606         interthread_progress_window->set_border_width (12);
2607         interthread_progress_window->get_vbox()->set_spacing (6);
2608
2609         interthread_progress_label.set_alignment (0.5, 0.5);
2610
2611         interthread_progress_window->get_vbox()->pack_start (interthread_progress_label, false, false);
2612         interthread_progress_window->get_vbox()->pack_start (interthread_progress_bar,false, false);
2613
2614         // GTK2FIX: this button needs a modifiable label
2615
2616         Button* b = interthread_progress_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
2617         b->signal_clicked().connect (sigc::mem_fun(*this, &Editor::interthread_cancel_clicked));
2618
2619         interthread_cancel_button.add (interthread_cancel_label);
2620
2621         interthread_progress_window->set_default_size (200, 100);
2622 }
2623
2624 void
2625 Editor::interthread_cancel_clicked ()
2626 {
2627         if (current_interthread_info) {
2628                 current_interthread_info->cancel = true;
2629         }
2630 }
2631
2632 void
2633 Editor::region_from_selection ()
2634 {
2635         if (clicked_axisview == 0) {
2636                 return;
2637         }
2638
2639         if (selection->time.empty()) {
2640                 return;
2641         }
2642
2643         nframes64_t start = selection->time[clicked_selection].start;
2644         nframes64_t end = selection->time[clicked_selection].end;
2645
2646         TrackViewList tracks = get_tracks_for_range_action ();
2647
2648         nframes64_t selection_cnt = end - start + 1;
2649
2650         for (TrackSelection::iterator i = tracks.begin(); i != tracks.end(); ++i) {
2651                 boost::shared_ptr<Region> current;
2652                 boost::shared_ptr<Playlist> pl;
2653                 nframes64_t internal_start;
2654                 string new_name;
2655
2656                 if ((pl = (*i)->playlist()) == 0) {
2657                         continue;
2658                 }
2659
2660                 if ((current = pl->top_region_at (start)) == 0) {
2661                         continue;
2662                 }
2663
2664                 internal_start = start - current->position();
2665                 _session->region_name (new_name, current->name(), true);
2666
2667                 PropertyList plist; 
2668                 
2669                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2670                 plist.add (ARDOUR::Properties::length, selection_cnt);
2671                 plist.add (ARDOUR::Properties::name, new_name);
2672                 plist.add (ARDOUR::Properties::layer, 0);
2673
2674                 boost::shared_ptr<Region> region (RegionFactory::create (current, plist));
2675         }
2676 }
2677
2678 void
2679 Editor::create_region_from_selection (vector<boost::shared_ptr<Region> >& new_regions)
2680 {
2681         if (selection->time.empty() || selection->tracks.empty()) {
2682                 return;
2683         }
2684
2685         nframes64_t start = selection->time[clicked_selection].start;
2686         nframes64_t end = selection->time[clicked_selection].end;
2687
2688         sort_track_selection ();
2689
2690         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
2691                 boost::shared_ptr<Region> current;
2692                 boost::shared_ptr<Playlist> playlist;
2693                 nframes64_t internal_start;
2694                 string new_name;
2695
2696                 if ((playlist = (*i)->playlist()) == 0) {
2697                         continue;
2698                 }
2699
2700                 if ((current = playlist->top_region_at(start)) == 0) {
2701                         continue;
2702                 }
2703
2704                 internal_start = start - current->position();
2705                 _session->region_name (new_name, current->name(), true);
2706
2707                 PropertyList plist; 
2708                 
2709                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2710                 plist.add (ARDOUR::Properties::length, end - start + 1);
2711                 plist.add (ARDOUR::Properties::name, new_name);
2712
2713                 new_regions.push_back (RegionFactory::create (current, plist));
2714         }
2715 }
2716
2717 void
2718 Editor::split_multichannel_region ()
2719 {
2720         RegionSelection rs;
2721
2722         get_regions_for_action (rs);
2723
2724         if (rs.empty()) {
2725                 return;
2726         }
2727
2728         vector< boost::shared_ptr<Region> > v;
2729
2730         for (list<RegionView*>::iterator x = rs.begin(); x != rs.end(); ++x) {
2731                 (*x)->region()->separate_by_channel (*_session, v);
2732         }
2733 }
2734
2735 void
2736 Editor::new_region_from_selection ()
2737 {
2738         region_from_selection ();
2739         cancel_selection ();
2740 }
2741
2742 static void
2743 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
2744 {
2745         switch (rv->region()->coverage (ar->start, ar->end - 1)) {
2746         case OverlapNone:
2747                 break;
2748         default:
2749                 rs->push_back (rv);
2750         }
2751 }
2752
2753 /** Return either:
2754  *    - selected tracks, or if there are none...
2755  *    - tracks containing selected regions, or if there are none...
2756  *    - all tracks
2757  * @return tracks.
2758  */
2759 TrackViewList
2760 Editor::get_tracks_for_range_action () const
2761 {
2762         TrackViewList t;
2763
2764         if (selection->tracks.empty()) {
2765
2766                 /* use tracks with selected regions */
2767
2768                 RegionSelection rs = selection->regions;
2769
2770                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2771                         TimeAxisView* tv = &(*i)->get_time_axis_view();
2772
2773                         if (!t.contains (tv)) {
2774                                 t.push_back (tv);
2775                         }
2776                 }
2777
2778                 if (t.empty()) {
2779                         /* no regions and no tracks: use all tracks */
2780                         t = track_views;
2781                 }
2782
2783         } else {
2784
2785                 t = selection->tracks;
2786         }
2787
2788         return t;
2789 }
2790
2791 void
2792 Editor::separate_regions_between (const TimeSelection& ts)
2793 {
2794         bool in_command = false;
2795         boost::shared_ptr<Playlist> playlist;
2796         RegionSelection new_selection;
2797
2798         TrackViewList tmptracks = get_tracks_for_range_action ();
2799         sort_track_selection (&tmptracks);
2800
2801         for (TrackSelection::iterator i = tmptracks.begin(); i != tmptracks.end(); ++i) {
2802
2803                 RouteTimeAxisView* rtv;
2804
2805                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2806
2807                         if (rtv->is_track()) {
2808
2809                                 /* no edits to destructive tracks */
2810
2811                                 if (rtv->track()->diskstream()->destructive()) {
2812                                         continue;
2813                                 }
2814
2815                                 if ((playlist = rtv->playlist()) != 0) {
2816
2817                                         playlist->clear_history ();
2818
2819                                         /* XXX need to consider musical time selections here at some point */
2820
2821                                         double speed = rtv->get_diskstream()->speed();
2822
2823
2824                                         for (list<AudioRange>::const_iterator t = ts.begin(); t != ts.end(); ++t) {
2825
2826                                                 sigc::connection c = rtv->view()->RegionViewAdded.connect (
2827                                                                 sigc::mem_fun(*this, &Editor::collect_new_region_view));
2828                                                 latest_regionviews.clear ();
2829
2830                                                 playlist->partition ((nframes64_t)((*t).start * speed),
2831                                                                 (nframes64_t)((*t).end * speed), true);
2832
2833                                                 c.disconnect ();
2834
2835                                                 if (!latest_regionviews.empty()) {
2836
2837                                                         rtv->view()->foreach_regionview (sigc::bind (
2838                                                                                 sigc::ptr_fun (add_if_covered),
2839                                                                                 &(*t), &new_selection));
2840                                                         
2841                                                         if (!in_command) {
2842                                                                 begin_reversible_command (_("separate"));
2843                                                                 in_command = true;
2844                                                         }
2845
2846                                                         _session->add_command(new StatefulDiffCommand (playlist));
2847                                                 }
2848                                         }
2849                                 }
2850                         }
2851                 }
2852         }
2853
2854         if (in_command) {
2855                 selection->set (new_selection);
2856                 set_mouse_mode (MouseObject);
2857
2858                 commit_reversible_command ();
2859         }
2860 }
2861
2862 /** Take tracks from get_tracks_for_range_action and cut any regions
2863  *  on those tracks so that the tracks are empty over the time
2864  *  selection.
2865  */
2866 void
2867 Editor::separate_region_from_selection ()
2868 {
2869         /* preferentially use *all* ranges in the time selection if we're in range mode
2870            to allow discontiguous operation, since get_edit_op_range() currently
2871            returns a single range.
2872         */
2873
2874         if (mouse_mode == MouseRange && !selection->time.empty()) {
2875
2876                 separate_regions_between (selection->time);
2877
2878         } else {
2879
2880                 nframes64_t start;
2881                 nframes64_t end;
2882
2883                 if (get_edit_op_range (start, end)) {
2884
2885                         AudioRange ar (start, end, 1);
2886                         TimeSelection ts;
2887                         ts.push_back (ar);
2888
2889                         separate_regions_between (ts);
2890                 }
2891         }
2892 }
2893
2894 void
2895 Editor::separate_region_from_punch ()
2896 {
2897         Location* loc  = _session->locations()->auto_punch_location();
2898         if (loc) {
2899                 separate_regions_using_location (*loc);
2900         }
2901 }
2902
2903 void
2904 Editor::separate_region_from_loop ()
2905 {
2906         Location* loc  = _session->locations()->auto_loop_location();
2907         if (loc) {
2908                 separate_regions_using_location (*loc);
2909         }
2910 }
2911
2912 void
2913 Editor::separate_regions_using_location (Location& loc)
2914 {
2915         if (loc.is_mark()) {
2916                 return;
2917         }
2918
2919         AudioRange ar (loc.start(), loc.end(), 1);
2920         TimeSelection ts;
2921
2922         ts.push_back (ar);
2923
2924         separate_regions_between (ts);
2925 }
2926
2927 void
2928 Editor::crop_region_to_selection ()
2929 {
2930         if (!selection->time.empty()) {
2931
2932                 crop_region_to (selection->time.start(), selection->time.end_frame());
2933
2934         } else {
2935
2936                 nframes64_t start;
2937                 nframes64_t end;
2938
2939                 if (get_edit_op_range (start, end)) {
2940                         crop_region_to (start, end);
2941                 }
2942         }
2943
2944 }
2945
2946 void
2947 Editor::crop_region_to (nframes64_t start, nframes64_t end)
2948 {
2949         vector<boost::shared_ptr<Playlist> > playlists;
2950         boost::shared_ptr<Playlist> playlist;
2951         TrackViewList* ts;
2952
2953         if (selection->tracks.empty()) {
2954                 ts = &track_views;
2955         } else {
2956                 sort_track_selection ();
2957                 ts = &selection->tracks;
2958         }
2959
2960         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
2961
2962                 RouteTimeAxisView* rtv;
2963
2964                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2965
2966                         boost::shared_ptr<Track> t = rtv->track();
2967
2968                         if (t != 0 && ! t->diskstream()->destructive()) {
2969
2970                                 if ((playlist = rtv->playlist()) != 0) {
2971                                         playlists.push_back (playlist);
2972                                 }
2973                         }
2974                 }
2975         }
2976
2977         if (playlists.empty()) {
2978                 return;
2979         }
2980
2981         nframes64_t the_start;
2982         nframes64_t the_end;
2983         nframes64_t cnt;
2984
2985         begin_reversible_command (_("trim to selection"));
2986
2987         for (vector<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2988
2989                 boost::shared_ptr<Region> region;
2990
2991                 the_start = start;
2992
2993                 if ((region = (*i)->top_region_at(the_start)) == 0) {
2994                         continue;
2995                 }
2996
2997                 /* now adjust lengths to that we do the right thing
2998                    if the selection extends beyond the region
2999                 */
3000
3001                 the_start = max (the_start, (nframes64_t) region->position());
3002                 if (max_frames - the_start < region->length()) {
3003                         the_end = the_start + region->length() - 1;
3004                 } else {
3005                         the_end = max_frames;
3006                 }
3007                 the_end = min (end, the_end);
3008                 cnt = the_end - the_start + 1;
3009
3010                 region->clear_history ();
3011                 region->trim_to (the_start, cnt, this);
3012                 _session->add_command (new StatefulDiffCommand (region));
3013         }
3014
3015         commit_reversible_command ();
3016 }
3017
3018 void
3019 Editor::region_fill_track ()
3020 {
3021         nframes64_t end;
3022         RegionSelection rs;
3023
3024         get_regions_for_action (rs);
3025
3026         if (!_session || rs.empty()) {
3027                 return;
3028         }
3029
3030         end = _session->current_end_frame ();
3031
3032         begin_reversible_command (_("region fill"));
3033
3034         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3035
3036                 boost::shared_ptr<Region> region ((*i)->region());
3037
3038                 boost::shared_ptr<Playlist> pl = region->playlist();
3039
3040                 if (end <= region->last_frame()) {
3041                         return;
3042                 }
3043
3044                 double times = (double) (end - region->last_frame()) / (double) region->length();
3045
3046                 if (times == 0) {
3047                         return;
3048                 }
3049
3050                 pl->clear_history ();
3051                 pl->add_region (RegionFactory::create (region), region->last_frame(), times);
3052                 _session->add_command (new StatefulDiffCommand (pl));
3053         }
3054
3055         commit_reversible_command ();
3056 }
3057
3058 void
3059 Editor::region_fill_selection ()
3060 {
3061         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3062                 return;
3063         }
3064
3065         if (selection->time.empty()) {
3066                 return;
3067         }
3068
3069         boost::shared_ptr<Region> region = _regions->get_single_selection ();
3070         if (region == 0) {
3071                 return;
3072         }
3073
3074         nframes64_t start = selection->time[clicked_selection].start;
3075         nframes64_t end = selection->time[clicked_selection].end;
3076
3077         boost::shared_ptr<Playlist> playlist;
3078
3079         if (selection->tracks.empty()) {
3080                 return;
3081         }
3082
3083         nframes64_t selection_length = end - start;
3084         float times = (float)selection_length / region->length();
3085
3086         begin_reversible_command (_("fill selection"));
3087
3088         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3089
3090                 if ((playlist = (*i)->playlist()) == 0) {
3091                         continue;
3092                 }
3093
3094                 playlist->clear_history ();
3095                 playlist->add_region (RegionFactory::create (region), start, times);
3096                 _session->add_command (new StatefulDiffCommand (playlist));
3097         }
3098
3099         commit_reversible_command ();
3100 }
3101
3102 void
3103 Editor::set_region_sync_from_edit_point ()
3104 {
3105         nframes64_t where = get_preferred_edit_position ();
3106         RegionSelection rs;
3107         get_regions_for_action (rs);
3108         set_sync_point (where, rs);
3109 }
3110
3111 void
3112 Editor::set_sync_point (nframes64_t where, const RegionSelection& rs)
3113 {
3114         bool in_command = false;
3115
3116         for (RegionSelection::const_iterator r = rs.begin(); r != rs.end(); ++r) {
3117
3118                 if (!(*r)->region()->covers (where)) {
3119                         continue;
3120                 }
3121
3122                 boost::shared_ptr<Region> region ((*r)->region());
3123
3124                 if (!in_command) {
3125                         begin_reversible_command (_("set sync point"));
3126                         in_command = true;
3127                 }
3128
3129                 region->clear_history ();
3130                 region->set_sync_position (where);
3131                 _session->add_command(new StatefulDiffCommand (region));
3132         }
3133
3134         if (in_command) {
3135                 commit_reversible_command ();
3136         }
3137 }
3138
3139 /** Remove the sync positions of the selection */
3140 void
3141 Editor::remove_region_sync ()
3142 {
3143         RegionSelection rs;
3144
3145         get_regions_for_action (rs);
3146
3147         if (rs.empty()) {
3148                 return;
3149         }
3150
3151         begin_reversible_command (_("remove sync"));
3152         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3153
3154                 (*i)->region()->clear_history ();
3155                 (*i)->region()->clear_sync_position ();
3156                 _session->add_command(new StatefulDiffCommand ((*i)->region()));
3157         }
3158         commit_reversible_command ();
3159 }
3160
3161 void
3162 Editor::naturalize ()
3163 {
3164         RegionSelection rs;
3165
3166         get_regions_for_action (rs);
3167
3168         if (rs.empty()) {
3169                 return;
3170         }
3171
3172         begin_reversible_command (_("naturalize"));
3173         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3174                 (*i)->region()->clear_history ();
3175                 (*i)->region()->move_to_natural_position (this);
3176                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
3177         }
3178         commit_reversible_command ();
3179 }
3180
3181 void
3182 Editor::align (RegionPoint what)
3183 {
3184         RegionSelection rs;
3185
3186         get_regions_for_action (rs);
3187         nframes64_t where = get_preferred_edit_position();
3188
3189         if (!rs.empty()) {
3190                 align_selection (what, where, rs);
3191         } else {
3192
3193                 RegionSelection rs;
3194                 get_regions_at (rs, where, selection->tracks);
3195                 align_selection (what, where, rs);
3196         }
3197 }
3198
3199 void
3200 Editor::align_relative (RegionPoint what)
3201 {
3202         nframes64_t where = get_preferred_edit_position();
3203         RegionSelection rs;
3204
3205         get_regions_for_action (rs);
3206
3207         if (!rs.empty()) {
3208                 align_selection_relative (what, where, rs);
3209         }
3210 }
3211
3212 struct RegionSortByTime {
3213     bool operator() (const RegionView* a, const RegionView* b) {
3214             return a->region()->position() < b->region()->position();
3215     }
3216 };
3217
3218 void
3219 Editor::align_selection_relative (RegionPoint point, nframes64_t position, const RegionSelection& rs)
3220 {
3221         if (rs.empty()) {
3222                 return;
3223         }
3224
3225         nframes64_t distance = 0;
3226         nframes64_t pos = 0;
3227         int dir = 1;
3228
3229         list<RegionView*> sorted;
3230         rs.by_position (sorted);
3231
3232         boost::shared_ptr<Region> r ((*sorted.begin())->region());
3233
3234         switch (point) {
3235         case Start:
3236                 pos = position;
3237                 if (position > r->position()) {
3238                         distance = position - r->position();
3239                 } else {
3240                         distance = r->position() - position;
3241                         dir = -1;
3242                 }
3243                 break;
3244
3245         case End:
3246                 if (position > r->last_frame()) {
3247                         distance = position - r->last_frame();
3248                         pos = r->position() + distance;
3249                 } else {
3250                         distance = r->last_frame() - position;
3251                         pos = r->position() - distance;
3252                         dir = -1;
3253                 }
3254                 break;
3255
3256         case SyncPoint:
3257                 pos = r->adjust_to_sync (position);
3258                 if (pos > r->position()) {
3259                         distance = pos - r->position();
3260                 } else {
3261                         distance = r->position() - pos;
3262                         dir = -1;
3263                 }
3264                 break;
3265         }
3266
3267         if (pos == r->position()) {
3268                 return;
3269         }
3270
3271         begin_reversible_command (_("align selection (relative)"));
3272
3273         /* move first one specially */
3274
3275         r->clear_history ();
3276         r->set_position (pos, this);
3277         _session->add_command(new StatefulDiffCommand (r));
3278
3279         /* move rest by the same amount */
3280
3281         sorted.pop_front();
3282
3283         for (list<RegionView*>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
3284
3285                 boost::shared_ptr<Region> region ((*i)->region());
3286
3287                 region->clear_history ();
3288
3289                 if (dir > 0) {
3290                         region->set_position (region->position() + distance, this);
3291                 } else {
3292                         region->set_position (region->position() - distance, this);
3293                 }
3294                 
3295                 _session->add_command(new StatefulDiffCommand (region));
3296
3297         }
3298
3299         commit_reversible_command ();
3300 }
3301
3302 void
3303 Editor::align_selection (RegionPoint point, nframes64_t position, const RegionSelection& rs)
3304 {
3305         if (rs.empty()) {
3306                 return;
3307         }
3308
3309         begin_reversible_command (_("align selection"));
3310
3311         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
3312                 align_region_internal ((*i)->region(), point, position);
3313         }
3314
3315         commit_reversible_command ();
3316 }
3317
3318 void
3319 Editor::align_region (boost::shared_ptr<Region> region, RegionPoint point, nframes64_t position)
3320 {
3321         begin_reversible_command (_("align region"));
3322         align_region_internal (region, point, position);
3323         commit_reversible_command ();
3324 }
3325
3326 void
3327 Editor::align_region_internal (boost::shared_ptr<Region> region, RegionPoint point, nframes64_t position)
3328 {
3329         region->clear_history ();
3330
3331         switch (point) {
3332         case SyncPoint:
3333                 region->set_position (region->adjust_to_sync (position), this);
3334                 break;
3335
3336         case End:
3337                 if (position > region->length()) {
3338                         region->set_position (position - region->length(), this);
3339                 }
3340                 break;
3341
3342         case Start:
3343                 region->set_position (position, this);
3344                 break;
3345         }
3346
3347         _session->add_command(new StatefulDiffCommand (region));
3348 }
3349
3350 void
3351 Editor::trim_region_front ()
3352 {
3353         trim_region (true);
3354 }
3355
3356 void
3357 Editor::trim_region_back ()
3358 {
3359         trim_region (false);
3360 }
3361
3362 void
3363 Editor::trim_region (bool front)
3364 {
3365         nframes64_t where = get_preferred_edit_position();
3366         RegionSelection rs;
3367
3368         get_regions_for_action (rs);
3369
3370         if (rs.empty()) {
3371                 return;
3372         }
3373
3374         begin_reversible_command (front ? _("trim front") : _("trim back"));
3375
3376         for (list<RegionView*>::const_iterator i = rs.by_layer().begin(); i != rs.by_layer().end(); ++i) {
3377                 if (!(*i)->region()->locked()) {
3378                         (*i)->region()->clear_history ();
3379                         if (front) {
3380                                 (*i)->region()->trim_front (where, this);
3381                         } else {
3382                                 (*i)->region()->trim_end (where, this);
3383                         }
3384                         _session->add_command (new StatefulDiffCommand ((*i)->region()));
3385                 }
3386         }
3387
3388         commit_reversible_command ();
3389 }
3390
3391 /** Trim the end of the selected regions to the position of the edit cursor */
3392 void
3393 Editor::trim_region_to_loop ()
3394 {
3395         Location* loc = _session->locations()->auto_loop_location();
3396         if (!loc) {
3397                 return;
3398         }
3399         trim_region_to_location (*loc, _("trim to loop"));
3400 }
3401
3402 void
3403 Editor::trim_region_to_punch ()
3404 {
3405         Location* loc = _session->locations()->auto_punch_location();
3406         if (!loc) {
3407                 return;
3408         }
3409         trim_region_to_location (*loc, _("trim to punch"));
3410 }
3411 void
3412 Editor::trim_region_to_location (const Location& loc, const char* str)
3413 {
3414         RegionSelection rs;
3415
3416         get_regions_for_action (rs);
3417
3418         begin_reversible_command (str);
3419
3420         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3421                 RegionView* rv = (*x);
3422
3423                 /* require region to span proposed trim */
3424                 switch (rv->region()->coverage (loc.start(), loc.end())) {
3425                 case OverlapInternal:
3426                         break;
3427                 default:
3428                         continue;
3429                 }
3430
3431                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3432                 if (!tav) {
3433                         return;
3434                 }
3435
3436                 float speed = 1.0;
3437                 nframes64_t start;
3438                 nframes64_t end;
3439
3440                 if (tav->get_diskstream() != 0) {
3441                         speed = tav->get_diskstream()->speed();
3442                 }
3443
3444                 start = session_frame_to_track_frame (loc.start(), speed);
3445                 end = session_frame_to_track_frame (loc.end(), speed);
3446                 
3447                 rv->region()->clear_history ();
3448                 rv->region()->trim_to (start, (end - start), this);
3449                 _session->add_command(new StatefulDiffCommand (rv->region()));
3450         }
3451
3452         commit_reversible_command ();
3453 }
3454
3455 void
3456 Editor::trim_region_to_edit_point ()
3457 {
3458         RegionSelection rs;
3459
3460         get_regions_for_action (rs);
3461
3462         nframes64_t where = get_preferred_edit_position();
3463
3464         begin_reversible_command (_("trim region start to edit point"));
3465
3466         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3467                 RegionView* rv = (*x);
3468
3469                 /* require region to cover trim */
3470                 if (!rv->region()->covers (where)) {
3471                         continue;
3472                 }
3473
3474                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3475                 if (!tav) {
3476                         return;
3477                 }
3478
3479                 float speed = 1.0;
3480
3481                 if (tav->get_diskstream() != 0) {
3482                         speed = tav->get_diskstream()->speed();
3483                 }
3484
3485                 rv->region()->clear_history ();
3486                 rv->region()->trim_end (session_frame_to_track_frame(where, speed), this);
3487                 _session->add_command(new StatefulDiffCommand (rv->region()));
3488         }
3489
3490         commit_reversible_command ();
3491 }
3492
3493 void
3494 Editor::trim_region_from_edit_point ()
3495 {
3496         RegionSelection rs;
3497
3498         get_regions_for_action (rs);
3499
3500         nframes64_t where = get_preferred_edit_position();
3501
3502         begin_reversible_command (_("trim region end to edit point"));
3503
3504         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3505                 RegionView* rv = (*x);
3506
3507                 /* require region to cover trim */
3508                 if (!rv->region()->covers (where)) {
3509                         continue;
3510                 }
3511
3512                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3513                 if (!tav) {
3514                         return;
3515                 }
3516
3517                 float speed = 1.0;
3518
3519                 if (tav->get_diskstream() != 0) {
3520                         speed = tav->get_diskstream()->speed();
3521                 }
3522
3523                 rv->region()->clear_history ();
3524                 rv->region()->trim_front (session_frame_to_track_frame(where, speed), this);
3525                 _session->add_command(new StatefulDiffCommand (rv->region()));
3526         }
3527
3528         commit_reversible_command ();
3529 }
3530
3531 void
3532 Editor::trim_region_to_previous_region_end ()
3533 {
3534         return trim_to_region(false);
3535 }
3536
3537 void
3538 Editor::trim_region_to_next_region_start ()
3539 {
3540         return trim_to_region(true);
3541 }
3542
3543 void
3544 Editor::trim_to_region(bool forward)
3545 {
3546         RegionSelection rs;
3547
3548         get_regions_for_action (rs);
3549
3550         begin_reversible_command (_("trim to region"));
3551
3552         boost::shared_ptr<Region> next_region;
3553
3554         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3555
3556                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*x);
3557
3558                 if (!arv) {
3559                         continue;
3560                 }
3561
3562                 AudioTimeAxisView* atav = dynamic_cast<AudioTimeAxisView*> (&arv->get_time_axis_view());
3563
3564                 if (!atav) {
3565                         return;
3566                 }
3567
3568                 float speed = 1.0;
3569
3570                 if (atav->get_diskstream() != 0) {
3571                         speed = atav->get_diskstream()->speed();
3572                 }
3573
3574
3575                 boost::shared_ptr<Region> region = arv->region();
3576                 boost::shared_ptr<Playlist> playlist (region->playlist());
3577
3578                 region->clear_history ();
3579
3580                 if(forward){
3581
3582                     next_region = playlist->find_next_region (region->first_frame(), Start, 1);
3583
3584                     if(!next_region){
3585                         continue;
3586                     }
3587
3588                     region->trim_end((nframes64_t) (next_region->first_frame() * speed), this);
3589                     arv->region_changed (PropertyChange (ARDOUR::Properties::length));
3590                 }
3591                 else {
3592
3593                     next_region = playlist->find_next_region (region->first_frame(), Start, 0);
3594
3595                     if(!next_region){
3596                         continue;
3597                     }
3598
3599                     region->trim_front((nframes64_t) ((next_region->last_frame() + 1) * speed), this);
3600
3601                     arv->region_changed (ARDOUR::bounds_change);
3602                 }
3603
3604                 _session->add_command(new StatefulDiffCommand (region));
3605         }
3606
3607         commit_reversible_command ();
3608 }
3609
3610 void
3611 Editor::unfreeze_route ()
3612 {
3613         if (clicked_routeview == 0 || !clicked_routeview->is_track()) {
3614                 return;
3615         }
3616
3617         clicked_routeview->track()->unfreeze ();
3618 }
3619
3620 void*
3621 Editor::_freeze_thread (void* arg)
3622 {
3623         SessionEvent::create_per_thread_pool ("freeze events", 64);
3624
3625         return static_cast<Editor*>(arg)->freeze_thread ();
3626 }
3627
3628 void*
3629 Editor::freeze_thread ()
3630 {
3631         clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
3632         current_interthread_info->done = true;
3633         return 0;
3634 }
3635
3636 gint
3637 Editor::freeze_progress_timeout (void */*arg*/)
3638 {
3639         interthread_progress_bar.set_fraction (current_interthread_info->progress);
3640         return !(current_interthread_info->done || current_interthread_info->cancel);
3641 }
3642
3643 void
3644 Editor::freeze_route ()
3645 {
3646         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3647                 return;
3648         }
3649
3650         InterThreadInfo itt;
3651
3652         if (interthread_progress_window == 0) {
3653                 build_interthread_progress_window ();
3654         }
3655
3656         interthread_progress_window->set_title (_("Freeze"));
3657         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
3658         interthread_progress_window->show_all ();
3659         interthread_progress_bar.set_fraction (0.0f);
3660         interthread_progress_label.set_text ("");
3661         interthread_cancel_label.set_text (_("Cancel Freeze"));
3662         current_interthread_info = &itt;
3663
3664         interthread_progress_connection =
3665           Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun(*this, &Editor::freeze_progress_timeout), (gpointer) 0), 100);
3666
3667         itt.done = false;
3668         itt.cancel = false;
3669         itt.progress = 0.0f;
3670
3671         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3672
3673         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
3674
3675         while (!itt.done && !itt.cancel) {
3676                 gtk_main_iteration ();
3677         }
3678
3679         interthread_progress_connection.disconnect ();
3680         interthread_progress_window->hide_all ();
3681         current_interthread_info = 0;
3682         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
3683 }
3684
3685 void
3686 Editor::bounce_range_selection (bool replace, bool enable_processing)
3687 {
3688         if (selection->time.empty()) {
3689                 return;
3690         }
3691
3692         TrackSelection views = selection->tracks;
3693
3694         nframes64_t start = selection->time[clicked_selection].start;
3695         nframes64_t end = selection->time[clicked_selection].end;
3696         nframes64_t cnt = end - start + 1;
3697
3698         begin_reversible_command (_("bounce range"));
3699
3700         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3701
3702                 RouteTimeAxisView* rtv;
3703
3704                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3705                         continue;
3706                 }
3707
3708                 boost::shared_ptr<Playlist> playlist;
3709
3710                 if ((playlist = rtv->playlist()) == 0) {
3711                         return;
3712                 }
3713
3714                 InterThreadInfo itt;
3715
3716                 itt.done = false;
3717                 itt.cancel = false;
3718                 itt.progress = false;
3719
3720                 playlist->clear_history ();
3721                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3722
3723                 if (replace) {
3724                         list<AudioRange> ranges;
3725                         ranges.push_back (AudioRange (start, start+cnt, 0));
3726                         playlist->cut (ranges); // discard result
3727                         playlist->add_region (r, start);
3728                 }
3729
3730                 _session->add_command (new StatefulDiffCommand (playlist));
3731         }
3732
3733         commit_reversible_command ();
3734 }
3735
3736 /** Cut selected regions, automation points or a time range */
3737 void
3738 Editor::cut ()
3739 {
3740         cut_copy (Cut);
3741 }
3742
3743 /** Copy selected regions, automation points or a time range */
3744 void
3745 Editor::copy ()
3746 {
3747         cut_copy (Copy);
3748 }
3749
3750
3751 /** @return true if a Cut, Copy or Clear is possible */
3752 bool
3753 Editor::can_cut_copy () const
3754 {
3755         switch (current_mouse_mode()) {
3756
3757         case MouseObject:
3758                 if (!selection->regions.empty() || !selection->points.empty()) {
3759                         return true;
3760                 }
3761                 break;
3762
3763         case MouseRange:
3764                 if (!selection->time.empty()) {
3765                         return true;
3766                 }
3767                 break;
3768
3769         default:
3770                 break;
3771         }
3772
3773         return false;
3774 }
3775
3776
3777 /** Cut, copy or clear selected regions, automation points or a time range.
3778  * @param op Operation (Cut, Copy or Clear)
3779  */
3780 void
3781 Editor::cut_copy (CutCopyOp op)
3782 {
3783         /* only cancel selection if cut/copy is successful.*/
3784
3785         string opname;
3786
3787         switch (op) {
3788         case Cut:
3789                 opname = _("cut");
3790                 break;
3791         case Copy:
3792                 opname = _("copy");
3793                 break;
3794         case Clear:
3795                 opname = _("clear");
3796                 break;
3797         }
3798
3799         /* if we're deleting something, and the mouse is still pressed,
3800            the thing we started a drag for will be gone when we release
3801            the mouse button(s). avoid this. see part 2 at the end of
3802            this function.
3803         */
3804
3805         if (op == Cut || op == Clear) {
3806                 if (_drags->active ()) {
3807                         _drags->abort ();
3808                 }
3809         }
3810
3811         cut_buffer->clear ();
3812
3813         if (entered_marker) {
3814
3815                 /* cut/delete op while pointing at a marker */
3816
3817                 bool ignored;
3818                 Location* loc = find_location_from_marker (entered_marker, ignored);
3819
3820                 if (_session && loc) {
3821                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3822                 }
3823
3824                 _drags->break_drag ();
3825                 return;
3826         }
3827
3828         if (internal_editing()) {
3829
3830                 switch (current_mouse_mode()) {
3831                 case MouseObject:
3832                 case MouseRange:
3833                         cut_copy_midi (op);
3834                         break;
3835                 default:
3836                         break;
3837                 }
3838
3839         } else {
3840
3841                 RegionSelection rs;
3842
3843                 /* we only want to cut regions if some are selected */
3844
3845                 if (!selection->regions.empty()) {
3846                         get_regions_for_action (rs, false, false);
3847                 }
3848
3849                 switch (current_mouse_mode()) {
3850                 case MouseObject:
3851                         if (!rs.empty() || !selection->points.empty()) {
3852
3853                                 begin_reversible_command (opname + _(" objects"));
3854
3855                                 if (!rs.empty()) {
3856                                         cut_copy_regions (op, rs);
3857
3858                                         if (op == Cut) {
3859                                                 selection->clear_regions ();
3860                                         }
3861                                 }
3862
3863                                 if (!selection->points.empty()) {
3864                                         cut_copy_points (op);
3865
3866                                         if (op == Cut) {
3867                                                 selection->clear_points ();
3868                                         }
3869                                 }
3870
3871                                 commit_reversible_command ();
3872                                 break; // terminate case statement here
3873                         }
3874                         if (!selection->time.empty()) {
3875                                 /* don't cause suprises */
3876                                 break;
3877                         }
3878                         // fall thru if there was nothing selected
3879
3880                 case MouseRange:
3881                         if (selection->time.empty()) {
3882                                 nframes64_t start, end;
3883                                 if (!get_edit_op_range (start, end)) {
3884                                         return;
3885                                 }
3886                                 selection->set (start, end);
3887                         }
3888
3889                         begin_reversible_command (opname + _(" range"));
3890                         cut_copy_ranges (op);
3891                         commit_reversible_command ();
3892
3893                         if (op == Cut) {
3894                                 selection->clear_time ();
3895                         }
3896
3897                         break;
3898
3899                 default:
3900                         break;
3901                 }
3902         }
3903
3904         if (op == Cut || op == Clear) {
3905                 _drags->break_drag ();
3906         }
3907 }
3908
3909 /** Cut, copy or clear selected automation points.
3910  * @param op Operation (Cut, Copy or Clear)
3911  */
3912 void
3913 Editor::cut_copy_points (CutCopyOp op)
3914 {
3915         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3916
3917                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3918
3919                 if (atv) {
3920                         atv->cut_copy_clear_objects (selection->points, op);
3921                 }
3922         }
3923 }
3924
3925 /** Cut, copy or clear selected automation points.
3926  * @param op Operation (Cut, Copy or Clear)
3927  */
3928 void
3929 Editor::cut_copy_midi (CutCopyOp op)
3930 {
3931         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3932                 MidiRegionView* mrv = *i;
3933                 mrv->cut_copy_clear (op);
3934         }
3935 }
3936
3937 struct PlaylistState {
3938     boost::shared_ptr<Playlist> playlist;
3939     XMLNode*  before;
3940 };
3941
3942 struct lt_playlist {
3943     bool operator () (const PlaylistState& a, const PlaylistState& b) {
3944             return a.playlist < b.playlist;
3945     }
3946 };
3947
3948 struct PlaylistMapping {
3949     TimeAxisView* tv;
3950     boost::shared_ptr<Playlist> pl;
3951
3952     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3953 };
3954
3955 /** Remove `clicked_regionview' */
3956 void
3957 Editor::remove_clicked_region ()
3958 {
3959         if (clicked_routeview == 0 || clicked_regionview == 0) {
3960                 return;
3961         }
3962
3963         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3964
3965         begin_reversible_command (_("remove region"));
3966         playlist->clear_history ();
3967         playlist->remove_region (clicked_regionview->region());
3968         _session->add_command(new StatefulDiffCommand (playlist));
3969         commit_reversible_command ();
3970 }
3971
3972
3973 /** Remove the selected regions */
3974 void
3975 Editor::remove_selected_regions ()
3976 {
3977         RegionSelection rs;
3978         get_regions_for_action (rs);
3979
3980         if (!_session) {
3981                 return;
3982         }
3983
3984         if (rs.empty()) {
3985                 return;
3986         }
3987
3988         begin_reversible_command (_("remove region"));
3989
3990         list<boost::shared_ptr<Region> > regions_to_remove;
3991
3992         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3993                 // we can't just remove the region(s) in this loop because
3994                 // this removes them from the RegionSelection, and they thus
3995                 // disappear from underneath the iterator, and the ++i above
3996                 // SEGVs in a puzzling fashion.
3997
3998                 // so, first iterate over the regions to be removed from rs and
3999                 // add them to the regions_to_remove list, and then
4000                 // iterate over the list to actually remove them.
4001
4002                 regions_to_remove.push_back ((*i)->region());
4003         }
4004
4005         vector<boost::shared_ptr<Playlist> > playlists;
4006
4007         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
4008
4009                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
4010
4011                 if (!playlist) {
4012                         // is this check necessary?
4013                         continue;
4014                 }
4015
4016                 vector<boost::shared_ptr<Playlist> >::iterator i;
4017
4018                 //only prep history if this is a new playlist.
4019                 for (i = playlists.begin(); i != playlists.end(); ++i) {
4020                         if ((*i) == playlist) {
4021                                 break;
4022                         }
4023                 }
4024
4025                 if (i == playlists.end()) {
4026
4027                         playlist->clear_history ();
4028                         playlist->freeze ();
4029
4030                         playlists.push_back (playlist);
4031                 }
4032
4033                 playlist->remove_region (*rl);
4034         }
4035
4036         vector<boost::shared_ptr<Playlist> >::iterator pl;
4037
4038         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
4039                 (*pl)->thaw ();
4040                 _session->add_command(new StatefulDiffCommand (*pl));
4041         }
4042
4043         commit_reversible_command ();
4044 }
4045
4046 /** Cut, copy or clear selected regions.
4047  * @param op Operation (Cut, Copy or Clear)
4048  */
4049 void
4050 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
4051 {
4052         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
4053            a map when we want ordered access to both elements. i think.
4054         */
4055
4056         vector<PlaylistMapping> pmap;
4057
4058         nframes64_t first_position = max_frames;
4059
4060         set<PlaylistState, lt_playlist> freezelist;
4061         pair<set<PlaylistState, lt_playlist>::iterator,bool> insert_result;
4062
4063         /* get ordering correct before we cut/copy */
4064
4065         rs.sort_by_position_and_track ();
4066
4067         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4068
4069                 first_position = min ((nframes64_t) (*x)->region()->position(), first_position);
4070
4071                 if (op == Cut || op == Clear) {
4072                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4073
4074                         if (pl) {
4075                                 set<PlaylistState, lt_playlist>::iterator fl;
4076
4077                                 //only take state if this is a new playlist.
4078                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
4079                                         if ((*fl).playlist == pl) {
4080                                                 break;
4081                                         }
4082                                 }
4083
4084                                 if (fl == freezelist.end()) {
4085                                         PlaylistState before;
4086                                         before.playlist = pl;
4087                                         before.before = &pl->get_state();
4088                                         pl->freeze ();
4089                                         insert_result = freezelist.insert (before);
4090                                 }
4091                         }
4092                 }
4093
4094                 TimeAxisView* tv = &(*x)->get_trackview();
4095                 vector<PlaylistMapping>::iterator z;
4096
4097                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4098                         if ((*z).tv == tv) {
4099                                 break;
4100                         }
4101                 }
4102
4103                 if (z == pmap.end()) {
4104                         pmap.push_back (PlaylistMapping (tv));
4105                 }
4106         }
4107
4108         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
4109
4110                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4111
4112                 if (!pl) {
4113                         /* impossible, but this handles it for the future */
4114                         continue;
4115                 }
4116
4117                 TimeAxisView& tv = (*x)->get_trackview();
4118                 boost::shared_ptr<Playlist> npl;
4119                 RegionSelection::iterator tmp;
4120
4121                 tmp = x;
4122                 ++tmp;
4123
4124                 vector<PlaylistMapping>::iterator z;
4125
4126                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4127                         if ((*z).tv == &tv) {
4128                                 break;
4129                         }
4130                 }
4131
4132                 assert (z != pmap.end());
4133
4134                 if (!(*z).pl) {
4135                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4136                         npl->freeze();
4137                         (*z).pl = npl;
4138                 } else {
4139                         npl = (*z).pl;
4140                 }
4141
4142                 boost::shared_ptr<Region> r = (*x)->region();
4143                 boost::shared_ptr<Region> _xx;
4144
4145                 assert (r != 0);
4146
4147                 switch (op) {
4148                 case Cut:
4149                         _xx = RegionFactory::create (r);
4150                         npl->add_region (_xx, r->position() - first_position);
4151                         pl->remove_region (r);
4152                         break;
4153
4154                 case Copy:
4155                         /* copy region before adding, so we're not putting same object into two different playlists */
4156                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4157                         break;
4158
4159                 case Clear:
4160                         pl->remove_region (r);
4161                         break;
4162                 }
4163
4164                 x = tmp;
4165         }
4166
4167         list<boost::shared_ptr<Playlist> > foo;
4168
4169         /* the pmap is in the same order as the tracks in which selected regions occured */
4170
4171         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4172                 (*i).pl->thaw();
4173                 foo.push_back ((*i).pl);
4174         }
4175
4176
4177         if (!foo.empty()) {
4178                 cut_buffer->set (foo);
4179         }
4180
4181         for (set<PlaylistState, lt_playlist>::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4182                 (*pl).playlist->thaw ();
4183                 _session->add_command (new MementoCommand<Playlist>(*(*pl).playlist, (*pl).before, &(*pl).playlist->get_state()));
4184         }
4185 }
4186
4187 void
4188 Editor::cut_copy_ranges (CutCopyOp op)
4189 {
4190         TrackViewList* ts;
4191         TrackViewList entered;
4192
4193         if (selection->tracks.empty()) {
4194                 if (!entered_track) {
4195                         return;
4196                 }
4197                 entered.push_back (entered_track);
4198                 ts = &entered;
4199         } else {
4200                 ts = &selection->tracks;
4201         }
4202
4203         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4204                 (*i)->cut_copy_clear (*selection, op);
4205         }
4206 }
4207
4208 void
4209 Editor::paste (float times)
4210 {
4211         paste_internal (get_preferred_edit_position(), times);
4212 }
4213
4214 void
4215 Editor::mouse_paste ()
4216 {
4217         nframes64_t where;
4218         bool ignored;
4219
4220         if (!mouse_frame (where, ignored)) {
4221                 return;
4222         }
4223
4224         snap_to (where);
4225         paste_internal (where, 1);
4226 }
4227
4228 void
4229 Editor::paste_internal (nframes64_t position, float times)
4230 {
4231         bool commit = false;
4232
4233         if (internal_editing()) {
4234                 if (cut_buffer->midi_notes.empty()) {
4235                         return;
4236                 }
4237         } else {
4238                 if (cut_buffer->empty()) {
4239                         return;
4240                 }
4241         }
4242
4243         if (position == max_frames) {
4244                 position = get_preferred_edit_position();
4245         }
4246
4247         begin_reversible_command (_("paste"));
4248
4249         TrackViewList ts;
4250         TrackViewList::iterator i;
4251         size_t nth;
4252
4253         /* get everything in the correct order */
4254
4255         if (!selection->tracks.empty()) {
4256                 sort_track_selection ();
4257                 ts = selection->tracks;
4258         } else if (entered_track) {
4259                 ts.push_back (entered_track);
4260         }
4261
4262         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4263
4264                 /* undo/redo is handled by individual tracks/regions */
4265
4266                 if (internal_editing()) {
4267
4268                         RegionSelection rs;
4269                         RegionSelection::iterator r;
4270                         MidiNoteSelection::iterator cb;
4271
4272                         get_regions_at (rs, position, ts);
4273
4274                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4275                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4276                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4277                                 if (mrv) {
4278                                         mrv->paste (position, times, **cb);
4279                                         ++cb;
4280                                 }
4281                         }
4282
4283                 } else {
4284
4285                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4286                                 commit = true;
4287                         }
4288                 }
4289         }
4290
4291         if (commit) {
4292                 commit_reversible_command ();
4293         }
4294 }
4295
4296 void
4297 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4298 {
4299         boost::shared_ptr<Playlist> playlist;
4300         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4301         RegionSelection foo;
4302
4303         nframes_t const start_frame = regions.start ();
4304         nframes_t const end_frame = regions.end_frame ();
4305
4306         begin_reversible_command (_("duplicate region"));
4307
4308         selection->clear_regions ();
4309
4310         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4311
4312                 boost::shared_ptr<Region> r ((*i)->region());
4313
4314                 TimeAxisView& tv = (*i)->get_time_axis_view();
4315                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4316                 latest_regionviews.clear ();
4317                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4318
4319                 playlist = (*i)->region()->playlist();
4320                 playlist->clear_history ();
4321                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame) + 1, times);
4322                 _session->add_command(new StatefulDiffCommand (playlist));
4323
4324                 c.disconnect ();
4325
4326                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4327         }
4328
4329         commit_reversible_command ();
4330
4331         if (!foo.empty()) {
4332                 selection->set (foo);
4333         }
4334 }
4335
4336 void
4337 Editor::duplicate_selection (float times)
4338 {
4339         if (selection->time.empty() || selection->tracks.empty()) {
4340                 return;
4341         }
4342
4343         boost::shared_ptr<Playlist> playlist;
4344         vector<boost::shared_ptr<Region> > new_regions;
4345         vector<boost::shared_ptr<Region> >::iterator ri;
4346
4347         create_region_from_selection (new_regions);
4348
4349         if (new_regions.empty()) {
4350                 return;
4351         }
4352
4353         begin_reversible_command (_("duplicate selection"));
4354
4355         ri = new_regions.begin();
4356
4357         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4358                 if ((playlist = (*i)->playlist()) == 0) {
4359                         continue;
4360                 }
4361                 playlist->clear_history ();
4362                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4363                 _session->add_command (new StatefulDiffCommand (playlist));
4364
4365                 ++ri;
4366                 if (ri == new_regions.end()) {
4367                         --ri;
4368                 }
4369         }
4370
4371         commit_reversible_command ();
4372 }
4373
4374 void
4375 Editor::reset_point_selection ()
4376 {
4377         /* reset all selected points to the relevant default value */
4378
4379         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4380
4381                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4382
4383                 if (atv) {
4384                         atv->reset_objects (selection->points);
4385                 }
4386         }
4387 }
4388
4389 void
4390 Editor::center_playhead ()
4391 {
4392         float page = _canvas_width * frames_per_unit;
4393         center_screen_internal (playhead_cursor->current_frame, page);
4394 }
4395
4396 void
4397 Editor::center_edit_point ()
4398 {
4399         float page = _canvas_width * frames_per_unit;
4400         center_screen_internal (get_preferred_edit_position(), page);
4401 }
4402
4403 void
4404 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4405 {
4406         begin_reversible_command (_("clear playlist"));
4407         playlist->clear_history ();
4408         playlist->clear ();
4409         _session->add_command (new StatefulDiffCommand (playlist));
4410         commit_reversible_command ();
4411 }
4412
4413 void
4414 Editor::nudge_track (bool use_edit, bool forwards)
4415 {
4416         boost::shared_ptr<Playlist> playlist;
4417         nframes64_t distance;
4418         nframes64_t next_distance;
4419         nframes64_t start;
4420
4421         if (use_edit) {
4422                 start = get_preferred_edit_position();
4423         } else {
4424                 start = 0;
4425         }
4426
4427         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4428                 return;
4429         }
4430
4431         if (selection->tracks.empty()) {
4432                 return;
4433         }
4434
4435         begin_reversible_command (_("nudge track"));
4436
4437         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4438
4439                 if ((playlist = (*i)->playlist()) == 0) {
4440                         continue;
4441                 }
4442
4443                 /* XXX STATEFUL this won't capture region moves if don't as a stateful diff
4444                  */
4445
4446                 XMLNode &before = playlist->get_state();
4447                 playlist->nudge_after (start, distance, forwards);
4448                 XMLNode &after = playlist->get_state();
4449                 _session->add_command (new MementoCommand<Playlist>(*playlist, &before, &after));
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 (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 (_session->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                         /* XXX STATEFUL this won't capture region motion if done as stateful diff 
6294                          */
6295
6296                         XMLNode &before = pl->get_state();
6297
6298                         if (opt == SplitIntersected) {
6299                                 pl->split (pos);
6300                         }
6301
6302                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6303
6304                         XMLNode &after = pl->get_state();
6305
6306                         _session->add_command (new MementoCommand<Playlist> (*pl, &before, &after));
6307                         commit = true;
6308                 }
6309
6310                 /* automation */
6311                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6312                 if (rtav) {
6313                         rtav->route ()->shift (pos, frames);
6314                         commit = true;
6315                 }
6316         }
6317
6318         /* markers */
6319         if (markers_too) {
6320                 bool moved = false;
6321                 XMLNode& before (_session->locations()->get_state());
6322                 Locations::LocationList copy (_session->locations()->list());
6323
6324                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6325
6326                         Locations::LocationList::const_iterator tmp;
6327
6328                         if ((*i)->start() >= pos) {
6329                                 (*i)->set_start ((*i)->start() + frames);
6330                                 if (!(*i)->is_mark()) {
6331                                         (*i)->set_end ((*i)->end() + frames);
6332                                 }
6333                                 moved = true;
6334                         }
6335                 }
6336
6337                 if (moved) {
6338                         XMLNode& after (_session->locations()->get_state());
6339                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6340                 }
6341         }
6342
6343         if (tempo_too) {
6344                 _session->tempo_map().insert_time (pos, frames);
6345         }
6346
6347         if (commit) {
6348                 commit_reversible_command ();
6349         }
6350 }
6351
6352 void
6353 Editor::fit_selected_tracks ()
6354 {
6355         fit_tracks (selection->tracks);
6356 }
6357
6358 void
6359 Editor::fit_tracks (TrackViewList & tracks)
6360 {
6361         if (tracks.empty()) {
6362                 return;
6363         }
6364
6365         uint32_t child_heights = 0;
6366
6367         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6368
6369                 if (!(*t)->marked_for_display()) {
6370                         continue;
6371                 }
6372
6373                 child_heights += (*t)->effective_height() - (*t)->current_height();
6374         }
6375
6376         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6377         double first_y_pos = DBL_MAX;
6378
6379         if (h < TimeAxisView::hSmall) {
6380                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6381                 /* too small to be displayed */
6382                 return;
6383         }
6384
6385         undo_visual_stack.push_back (current_visual_state());
6386
6387         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6388
6389         bool prev_was_selected = false;
6390         bool is_selected = tracks.contains (track_views.front());
6391         bool next_is_selected;
6392
6393         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
6394
6395                 TrackViewList::iterator next;
6396
6397                 next = t;
6398                 ++next;
6399
6400                 if (next != track_views.end()) {
6401                         next_is_selected = tracks.contains (*next);
6402                 } else {
6403                         next_is_selected = false;
6404                 }
6405
6406                 if (is_selected) {
6407                         (*t)->set_height (h);
6408                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6409                 } else {
6410                         if (prev_was_selected && next_is_selected) {
6411                                 hide_track_in_display (**t);
6412                         }
6413                 }
6414
6415                 prev_was_selected = is_selected;
6416                 is_selected = next_is_selected;
6417         }
6418
6419         /*
6420            set the controls_layout height now, because waiting for its size
6421            request signal handler will cause the vertical adjustment setting to fail
6422         */
6423
6424         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6425         vertical_adjustment.set_value (first_y_pos);
6426
6427         redo_visual_stack.push_back (current_visual_state());
6428 }
6429
6430 void
6431 Editor::save_visual_state (uint32_t n)
6432 {
6433         while (visual_states.size() <= n) {
6434                 visual_states.push_back (0);
6435         }
6436
6437         delete visual_states[n];
6438
6439         visual_states[n] = current_visual_state (true);
6440         gdk_beep ();
6441 }
6442
6443 void
6444 Editor::goto_visual_state (uint32_t n)
6445 {
6446         if (visual_states.size() <= n) {
6447                 return;
6448         }
6449
6450         if (visual_states[n] == 0) {
6451                 return;
6452         }
6453
6454         use_visual_state (*visual_states[n]);
6455 }
6456
6457 void
6458 Editor::start_visual_state_op (uint32_t n)
6459 {
6460         if (visual_state_op_connection.empty()) {
6461                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6462         }
6463 }
6464
6465 void
6466 Editor::cancel_visual_state_op (uint32_t n)
6467 {
6468         if (!visual_state_op_connection.empty()) {
6469                 visual_state_op_connection.disconnect();
6470                 goto_visual_state (n);
6471         }  else {
6472                 //we land here if called from the menu OR if end_visual_state_op has been called
6473                 //so check if we are already in visual state n
6474                 // XXX not yet checking it at all, but redoing does not hurt
6475                 goto_visual_state (n);
6476         }
6477 }
6478
6479 bool
6480 Editor::end_visual_state_op (uint32_t n)
6481 {
6482         visual_state_op_connection.disconnect();
6483         save_visual_state (n);
6484
6485         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6486         char buf[32];
6487         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6488         pup->set_text (buf);
6489         pup->touch();
6490
6491         return false; // do not call again
6492 }
6493