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