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