Small cleanup: add constructor to InterThreadInfo.
[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         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3617
3618         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
3619
3620         while (!itt.done && !itt.cancel) {
3621                 gtk_main_iteration ();
3622         }
3623
3624         current_interthread_info = 0;
3625         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
3626 }
3627
3628 void
3629 Editor::bounce_range_selection (bool replace, bool enable_processing)
3630 {
3631         if (selection->time.empty()) {
3632                 return;
3633         }
3634
3635         TrackSelection views = selection->tracks;
3636
3637         nframes64_t start = selection->time[clicked_selection].start;
3638         nframes64_t end = selection->time[clicked_selection].end;
3639         nframes64_t cnt = end - start + 1;
3640
3641         begin_reversible_command (_("bounce range"));
3642
3643         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3644
3645                 RouteTimeAxisView* rtv;
3646
3647                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3648                         continue;
3649                 }
3650
3651                 boost::shared_ptr<Playlist> playlist;
3652
3653                 if ((playlist = rtv->playlist()) == 0) {
3654                         return;
3655                 }
3656
3657                 InterThreadInfo itt;
3658
3659                 playlist->clear_history ();
3660                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3661
3662                 if (replace) {
3663                         list<AudioRange> ranges;
3664                         ranges.push_back (AudioRange (start, start+cnt, 0));
3665                         playlist->cut (ranges); // discard result
3666                         playlist->add_region (r, start);
3667                 }
3668
3669                 _session->add_command (new StatefulDiffCommand (playlist));
3670         }
3671
3672         commit_reversible_command ();
3673 }
3674
3675 /** Cut selected regions, automation points or a time range */
3676 void
3677 Editor::cut ()
3678 {
3679         cut_copy (Cut);
3680 }
3681
3682 /** Copy selected regions, automation points or a time range */
3683 void
3684 Editor::copy ()
3685 {
3686         cut_copy (Copy);
3687 }
3688
3689
3690 /** @return true if a Cut, Copy or Clear is possible */
3691 bool
3692 Editor::can_cut_copy () const
3693 {
3694         switch (current_mouse_mode()) {
3695
3696         case MouseObject:
3697                 if (!selection->regions.empty() || !selection->points.empty()) {
3698                         return true;
3699                 }
3700                 break;
3701
3702         case MouseRange:
3703                 if (!selection->time.empty()) {
3704                         return true;
3705                 }
3706                 break;
3707
3708         default:
3709                 break;
3710         }
3711
3712         return false;
3713 }
3714
3715
3716 /** Cut, copy or clear selected regions, automation points or a time range.
3717  * @param op Operation (Cut, Copy or Clear)
3718  */
3719 void
3720 Editor::cut_copy (CutCopyOp op)
3721 {
3722         /* only cancel selection if cut/copy is successful.*/
3723
3724         string opname;
3725
3726         switch (op) {
3727         case Cut:
3728                 opname = _("cut");
3729                 break;
3730         case Copy:
3731                 opname = _("copy");
3732                 break;
3733         case Clear:
3734                 opname = _("clear");
3735                 break;
3736         }
3737
3738         /* if we're deleting something, and the mouse is still pressed,
3739            the thing we started a drag for will be gone when we release
3740            the mouse button(s). avoid this. see part 2 at the end of
3741            this function.
3742         */
3743
3744         if (op == Cut || op == Clear) {
3745                 if (_drags->active ()) {
3746                         _drags->abort ();
3747                 }
3748         }
3749
3750         cut_buffer->clear ();
3751
3752         if (entered_marker) {
3753
3754                 /* cut/delete op while pointing at a marker */
3755
3756                 bool ignored;
3757                 Location* loc = find_location_from_marker (entered_marker, ignored);
3758
3759                 if (_session && loc) {
3760                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3761                 }
3762
3763                 _drags->break_drag ();
3764                 return;
3765         }
3766
3767         if (internal_editing()) {
3768
3769                 switch (current_mouse_mode()) {
3770                 case MouseObject:
3771                 case MouseRange:
3772                         cut_copy_midi (op);
3773                         break;
3774                 default:
3775                         break;
3776                 }
3777
3778         } else {
3779
3780                 RegionSelection rs;
3781
3782                 /* we only want to cut regions if some are selected */
3783
3784                 if (!selection->regions.empty()) {
3785                         get_regions_for_action (rs, false, false);
3786                 }
3787
3788                 switch (current_mouse_mode()) {
3789                 case MouseObject:
3790                         if (!rs.empty() || !selection->points.empty()) {
3791
3792                                 begin_reversible_command (opname + _(" objects"));
3793
3794                                 if (!rs.empty()) {
3795                                         cut_copy_regions (op, rs);
3796
3797                                         if (op == Cut) {
3798                                                 selection->clear_regions ();
3799                                         }
3800                                 }
3801
3802                                 if (!selection->points.empty()) {
3803                                         cut_copy_points (op);
3804
3805                                         if (op == Cut) {
3806                                                 selection->clear_points ();
3807                                         }
3808                                 }
3809
3810                                 commit_reversible_command ();
3811                                 break; // terminate case statement here
3812                         }
3813                         if (!selection->time.empty()) {
3814                                 /* don't cause suprises */
3815                                 break;
3816                         }
3817                         // fall thru if there was nothing selected
3818
3819                 case MouseRange:
3820                         if (selection->time.empty()) {
3821                                 nframes64_t start, end;
3822                                 if (!get_edit_op_range (start, end)) {
3823                                         return;
3824                                 }
3825                                 selection->set (start, end);
3826                         }
3827
3828                         begin_reversible_command (opname + _(" range"));
3829                         cut_copy_ranges (op);
3830                         commit_reversible_command ();
3831
3832                         if (op == Cut) {
3833                                 selection->clear_time ();
3834                         }
3835
3836                         break;
3837
3838                 default:
3839                         break;
3840                 }
3841         }
3842
3843         if (op == Cut || op == Clear) {
3844                 _drags->break_drag ();
3845         }
3846 }
3847
3848 /** Cut, copy or clear selected automation points.
3849  * @param op Operation (Cut, Copy or Clear)
3850  */
3851 void
3852 Editor::cut_copy_points (CutCopyOp op)
3853 {
3854         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3855
3856                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3857
3858                 if (atv) {
3859                         atv->cut_copy_clear_objects (selection->points, op);
3860                 }
3861         }
3862 }
3863
3864 /** Cut, copy or clear selected automation points.
3865  * @param op Operation (Cut, Copy or Clear)
3866  */
3867 void
3868 Editor::cut_copy_midi (CutCopyOp op)
3869 {
3870         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3871                 MidiRegionView* mrv = *i;
3872                 mrv->cut_copy_clear (op);
3873         }
3874 }
3875
3876 struct PlaylistMapping {
3877     TimeAxisView* tv;
3878     boost::shared_ptr<Playlist> pl;
3879
3880     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3881 };
3882
3883 /** Remove `clicked_regionview' */
3884 void
3885 Editor::remove_clicked_region ()
3886 {
3887         if (clicked_routeview == 0 || clicked_regionview == 0) {
3888                 return;
3889         }
3890
3891         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3892
3893         begin_reversible_command (_("remove region"));
3894         playlist->clear_history ();
3895         playlist->remove_region (clicked_regionview->region());
3896         _session->add_command(new StatefulDiffCommand (playlist));
3897         commit_reversible_command ();
3898 }
3899
3900
3901 /** Remove the selected regions */
3902 void
3903 Editor::remove_selected_regions ()
3904 {
3905         RegionSelection rs;
3906         get_regions_for_action (rs);
3907
3908         if (!_session) {
3909                 return;
3910         }
3911
3912         if (rs.empty()) {
3913                 return;
3914         }
3915
3916         begin_reversible_command (_("remove region"));
3917
3918         list<boost::shared_ptr<Region> > regions_to_remove;
3919
3920         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3921                 // we can't just remove the region(s) in this loop because
3922                 // this removes them from the RegionSelection, and they thus
3923                 // disappear from underneath the iterator, and the ++i above
3924                 // SEGVs in a puzzling fashion.
3925
3926                 // so, first iterate over the regions to be removed from rs and
3927                 // add them to the regions_to_remove list, and then
3928                 // iterate over the list to actually remove them.
3929
3930                 regions_to_remove.push_back ((*i)->region());
3931         }
3932
3933         vector<boost::shared_ptr<Playlist> > playlists;
3934
3935         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
3936
3937                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
3938
3939                 if (!playlist) {
3940                         // is this check necessary?
3941                         continue;
3942                 }
3943
3944                 vector<boost::shared_ptr<Playlist> >::iterator i;
3945
3946                 //only prep history if this is a new playlist.
3947                 for (i = playlists.begin(); i != playlists.end(); ++i) {
3948                         if ((*i) == playlist) {
3949                                 break;
3950                         }
3951                 }
3952
3953                 if (i == playlists.end()) {
3954
3955                         playlist->clear_history ();
3956                         playlist->freeze ();
3957
3958                         playlists.push_back (playlist);
3959                 }
3960
3961                 playlist->remove_region (*rl);
3962         }
3963
3964         vector<boost::shared_ptr<Playlist> >::iterator pl;
3965
3966         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
3967                 (*pl)->thaw ();
3968                 _session->add_command(new StatefulDiffCommand (*pl));
3969         }
3970
3971         commit_reversible_command ();
3972 }
3973
3974 /** Cut, copy or clear selected regions.
3975  * @param op Operation (Cut, Copy or Clear)
3976  */
3977 void
3978 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
3979 {
3980         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
3981            a map when we want ordered access to both elements. i think.
3982         */
3983
3984         vector<PlaylistMapping> pmap;
3985
3986         nframes64_t first_position = max_frames;
3987
3988         typedef set<boost::shared_ptr<Playlist> > FreezeList;
3989         FreezeList freezelist;
3990
3991         /* get ordering correct before we cut/copy */
3992
3993         rs.sort_by_position_and_track ();
3994
3995         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3996
3997                 first_position = min ((nframes64_t) (*x)->region()->position(), first_position);
3998
3999                 if (op == Cut || op == Clear) {
4000                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4001
4002                         if (pl) {
4003                                 FreezeList::iterator fl;
4004
4005                                 //only take state if this is a new playlist.
4006                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
4007                                         if ((*fl) == pl) {
4008                                                 break;
4009                                         }
4010                                 }
4011
4012                                 if (fl == freezelist.end()) {
4013                                         pl->clear_history();
4014                                         pl->freeze ();
4015                                         freezelist.insert (pl);
4016                                 }
4017                         }
4018                 }
4019
4020                 TimeAxisView* tv = &(*x)->get_trackview();
4021                 vector<PlaylistMapping>::iterator z;
4022
4023                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4024                         if ((*z).tv == tv) {
4025                                 break;
4026                         }
4027                 }
4028
4029                 if (z == pmap.end()) {
4030                         pmap.push_back (PlaylistMapping (tv));
4031                 }
4032         }
4033
4034         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
4035
4036                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
4037
4038                 if (!pl) {
4039                         /* impossible, but this handles it for the future */
4040                         continue;
4041                 }
4042
4043                 TimeAxisView& tv = (*x)->get_trackview();
4044                 boost::shared_ptr<Playlist> npl;
4045                 RegionSelection::iterator tmp;
4046
4047                 tmp = x;
4048                 ++tmp;
4049
4050                 vector<PlaylistMapping>::iterator z;
4051
4052                 for (z = pmap.begin(); z != pmap.end(); ++z) {
4053                         if ((*z).tv == &tv) {
4054                                 break;
4055                         }
4056                 }
4057
4058                 assert (z != pmap.end());
4059
4060                 if (!(*z).pl) {
4061                         npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
4062                         npl->freeze();
4063                         (*z).pl = npl;
4064                 } else {
4065                         npl = (*z).pl;
4066                 }
4067
4068                 boost::shared_ptr<Region> r = (*x)->region();
4069                 boost::shared_ptr<Region> _xx;
4070
4071                 assert (r != 0);
4072
4073                 switch (op) {
4074                 case Cut:
4075                         _xx = RegionFactory::create (r);
4076                         npl->add_region (_xx, r->position() - first_position);
4077                         pl->remove_region (r);
4078                         break;
4079
4080                 case Copy:
4081                         /* copy region before adding, so we're not putting same object into two different playlists */
4082                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
4083                         break;
4084
4085                 case Clear:
4086                         pl->remove_region (r);
4087                         break;
4088                 }
4089
4090                 x = tmp;
4091         }
4092
4093         list<boost::shared_ptr<Playlist> > foo;
4094
4095         /* the pmap is in the same order as the tracks in which selected regions occured */
4096
4097         for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
4098                 (*i).pl->thaw();
4099                 foo.push_back ((*i).pl);
4100         }
4101
4102
4103         if (!foo.empty()) {
4104                 cut_buffer->set (foo);
4105         }
4106         
4107         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
4108                 (*pl)->thaw ();
4109                 _session->add_command (new StatefulDiffCommand (*pl));
4110         }
4111 }
4112
4113 void
4114 Editor::cut_copy_ranges (CutCopyOp op)
4115 {
4116         TrackViewList* ts;
4117         TrackViewList entered;
4118
4119         if (selection->tracks.empty()) {
4120                 if (!entered_track) {
4121                         return;
4122                 }
4123                 entered.push_back (entered_track);
4124                 ts = &entered;
4125         } else {
4126                 ts = &selection->tracks;
4127         }
4128
4129         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
4130                 (*i)->cut_copy_clear (*selection, op);
4131         }
4132 }
4133
4134 void
4135 Editor::paste (float times)
4136 {
4137         paste_internal (get_preferred_edit_position(), times);
4138 }
4139
4140 void
4141 Editor::mouse_paste ()
4142 {
4143         nframes64_t where;
4144         bool ignored;
4145
4146         if (!mouse_frame (where, ignored)) {
4147                 return;
4148         }
4149
4150         snap_to (where);
4151         paste_internal (where, 1);
4152 }
4153
4154 void
4155 Editor::paste_internal (nframes64_t position, float times)
4156 {
4157         bool commit = false;
4158
4159         if (internal_editing()) {
4160                 if (cut_buffer->midi_notes.empty()) {
4161                         return;
4162                 }
4163         } else {
4164                 if (cut_buffer->empty()) {
4165                         return;
4166                 }
4167         }
4168
4169         if (position == max_frames) {
4170                 position = get_preferred_edit_position();
4171         }
4172
4173         begin_reversible_command (_("paste"));
4174
4175         TrackViewList ts;
4176         TrackViewList::iterator i;
4177         size_t nth;
4178
4179         /* get everything in the correct order */
4180
4181         if (!selection->tracks.empty()) {
4182                 sort_track_selection ();
4183                 ts = selection->tracks;
4184         } else if (entered_track) {
4185                 ts.push_back (entered_track);
4186         }
4187
4188         for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4189
4190                 /* undo/redo is handled by individual tracks/regions */
4191
4192                 if (internal_editing()) {
4193
4194                         RegionSelection rs;
4195                         RegionSelection::iterator r;
4196                         MidiNoteSelection::iterator cb;
4197
4198                         get_regions_at (rs, position, ts);
4199
4200                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4201                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4202                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4203                                 if (mrv) {
4204                                         mrv->paste (position, times, **cb);
4205                                         ++cb;
4206                                 }
4207                         }
4208
4209                 } else {
4210
4211                         if ((*i)->paste (position, times, *cut_buffer, nth)) {
4212                                 commit = true;
4213                         }
4214                 }
4215         }
4216
4217         if (commit) {
4218                 commit_reversible_command ();
4219         }
4220 }
4221
4222 void
4223 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4224 {
4225         boost::shared_ptr<Playlist> playlist;
4226         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4227         RegionSelection foo;
4228
4229         nframes_t const start_frame = regions.start ();
4230         nframes_t const end_frame = regions.end_frame ();
4231
4232         begin_reversible_command (_("duplicate region"));
4233
4234         selection->clear_regions ();
4235
4236         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4237
4238                 boost::shared_ptr<Region> r ((*i)->region());
4239
4240                 TimeAxisView& tv = (*i)->get_time_axis_view();
4241                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4242                 latest_regionviews.clear ();
4243                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4244
4245                 playlist = (*i)->region()->playlist();
4246                 playlist->clear_history ();
4247                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame) + 1, times);
4248                 _session->add_command(new StatefulDiffCommand (playlist));
4249
4250                 c.disconnect ();
4251
4252                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4253         }
4254
4255         commit_reversible_command ();
4256
4257         if (!foo.empty()) {
4258                 selection->set (foo);
4259         }
4260 }
4261
4262 void
4263 Editor::duplicate_selection (float times)
4264 {
4265         if (selection->time.empty() || selection->tracks.empty()) {
4266                 return;
4267         }
4268
4269         boost::shared_ptr<Playlist> playlist;
4270         vector<boost::shared_ptr<Region> > new_regions;
4271         vector<boost::shared_ptr<Region> >::iterator ri;
4272
4273         create_region_from_selection (new_regions);
4274
4275         if (new_regions.empty()) {
4276                 return;
4277         }
4278
4279         begin_reversible_command (_("duplicate selection"));
4280
4281         ri = new_regions.begin();
4282
4283         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4284                 if ((playlist = (*i)->playlist()) == 0) {
4285                         continue;
4286                 }
4287                 playlist->clear_history ();
4288                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4289                 _session->add_command (new StatefulDiffCommand (playlist));
4290
4291                 ++ri;
4292                 if (ri == new_regions.end()) {
4293                         --ri;
4294                 }
4295         }
4296
4297         commit_reversible_command ();
4298 }
4299
4300 void
4301 Editor::reset_point_selection ()
4302 {
4303         /* reset all selected points to the relevant default value */
4304
4305         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4306
4307                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4308
4309                 if (atv) {
4310                         atv->reset_objects (selection->points);
4311                 }
4312         }
4313 }
4314
4315 void
4316 Editor::center_playhead ()
4317 {
4318         float page = _canvas_width * frames_per_unit;
4319         center_screen_internal (playhead_cursor->current_frame, page);
4320 }
4321
4322 void
4323 Editor::center_edit_point ()
4324 {
4325         float page = _canvas_width * frames_per_unit;
4326         center_screen_internal (get_preferred_edit_position(), page);
4327 }
4328
4329 void
4330 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4331 {
4332         begin_reversible_command (_("clear playlist"));
4333         playlist->clear_history ();
4334         playlist->clear ();
4335         _session->add_command (new StatefulDiffCommand (playlist));
4336         commit_reversible_command ();
4337 }
4338
4339 void
4340 Editor::nudge_track (bool use_edit, bool forwards)
4341 {
4342         boost::shared_ptr<Playlist> playlist;
4343         nframes64_t distance;
4344         nframes64_t next_distance;
4345         nframes64_t start;
4346
4347         if (use_edit) {
4348                 start = get_preferred_edit_position();
4349         } else {
4350                 start = 0;
4351         }
4352
4353         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4354                 return;
4355         }
4356
4357         if (selection->tracks.empty()) {
4358                 return;
4359         }
4360
4361         begin_reversible_command (_("nudge track"));
4362
4363         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4364
4365                 if ((playlist = (*i)->playlist()) == 0) {
4366                         continue;
4367                 }
4368
4369                 playlist->clear_history ();
4370                 playlist->clear_owned_history ();
4371
4372                 playlist->nudge_after (start, distance, forwards);
4373                 
4374                 vector<StatefulDiffCommand*> cmds;
4375
4376                 playlist->rdiff (cmds);
4377
4378                 for (vector<StatefulDiffCommand*>::iterator c = cmds.begin(); c != cmds.end(); ++c) {
4379                         _session->add_command (*c);
4380                 }
4381
4382                 _session->add_command (new StatefulDiffCommand (playlist));
4383         }
4384
4385         commit_reversible_command ();
4386 }
4387
4388 void
4389 Editor::remove_last_capture ()
4390 {
4391         vector<string> choices;
4392         string prompt;
4393
4394         if (!_session) {
4395                 return;
4396         }
4397
4398         if (Config->get_verify_remove_last_capture()) {
4399                 prompt  = _("Do you really want to destroy the last capture?"
4400                             "\n(This is destructive and cannot be undone)");
4401
4402                 choices.push_back (_("No, do nothing."));
4403                 choices.push_back (_("Yes, destroy it."));
4404
4405                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4406
4407                 if (prompter.run () == 1) {
4408                         _session->remove_last_capture ();
4409                 }
4410
4411         } else {
4412                 _session->remove_last_capture();
4413         }
4414 }
4415
4416 void
4417 Editor::normalize_region ()
4418 {
4419         if (!_session) {
4420                 return;
4421         }
4422
4423         RegionSelection rs;
4424         get_regions_for_action (rs);
4425
4426         if (rs.empty()) {
4427                 return;
4428         }
4429
4430         Dialog dialog (rs.size() > 1 ? _("Normalize regions") : _("Normalize region"));
4431         HBox hbox;
4432         hbox.set_spacing (6);
4433         hbox.set_border_width (6);
4434         hbox.pack_start (*manage (new Label (_("Normalize to:"))));
4435         SpinButton spin (0.2, 2);
4436         spin.set_range (-112, 0);
4437         spin.set_increments (0.1, 1);
4438         spin.set_value (0);
4439         hbox.pack_start (spin);
4440         spin.set_value (_last_normalization_value);
4441         hbox.pack_start (*manage (new Label (_("dbFS"))));
4442         hbox.show_all ();
4443         dialog.get_vbox()->set_spacing (12);
4444         dialog.get_vbox()->pack_start (hbox);
4445         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
4446         dialog.add_button (_("Normalize"), RESPONSE_ACCEPT);
4447
4448         if (dialog.run () == RESPONSE_CANCEL) {
4449                 return;
4450         }
4451
4452         begin_reversible_command (_("normalize"));
4453
4454         track_canvas->get_window()->set_cursor (*wait_cursor);
4455         gdk_flush ();
4456
4457         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4458                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4459                 if (!arv)
4460                         continue;
4461                 arv->region()->clear_history ();
4462                 arv->audio_region()->normalize_to (spin.get_value());
4463                 _session->add_command (new StatefulDiffCommand (arv->region()));
4464                                        
4465         }
4466
4467         commit_reversible_command ();
4468         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4469
4470         _last_normalization_value = spin.get_value ();
4471 }
4472
4473
4474 void
4475 Editor::reset_region_scale_amplitude ()
4476 {
4477         if (!_session) {
4478                 return;
4479         }
4480
4481         RegionSelection rs;
4482
4483         get_regions_for_action (rs);
4484
4485         if (rs.empty()) {
4486                 return;
4487         }
4488
4489         begin_reversible_command ("reset gain");
4490
4491         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4492                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4493                 if (!arv)
4494                         continue;
4495                 arv->region()->clear_history ();
4496                 arv->audio_region()->set_scale_amplitude (1.0f);
4497                 _session->add_command (new StatefulDiffCommand (arv->region()));
4498         }
4499
4500         commit_reversible_command ();
4501 }
4502
4503 void
4504 Editor::adjust_region_scale_amplitude (bool up)
4505 {
4506         if (!_session) {
4507                 return;
4508         }
4509
4510         RegionSelection rs;
4511
4512         get_regions_for_action (rs);
4513
4514         if (rs.empty()) {
4515                 return;
4516         }
4517
4518         begin_reversible_command ("denormalize");
4519
4520         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4521                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4522                 if (!arv) {
4523                         continue;
4524                 }
4525
4526                 arv->region()->clear_history ();
4527                 
4528                 double fraction = gain_to_slider_position (arv->audio_region()->scale_amplitude ());
4529
4530                 if (up) {
4531                         fraction += 0.05;
4532                         fraction = min (fraction, 1.0);
4533                 } else {
4534                         fraction -= 0.05;
4535                         fraction = max (fraction, 0.0);
4536                 }
4537
4538                 if (!up && fraction <= 0) {
4539                         continue;
4540                 }
4541
4542                 fraction = slider_position_to_gain (fraction);
4543
4544                 if (up && fraction >= 2.0) {
4545                         continue;
4546                 }
4547
4548                 arv->audio_region()->set_scale_amplitude (fraction);
4549                 _session->add_command (new StatefulDiffCommand (arv->region()));
4550         }
4551
4552         commit_reversible_command ();
4553 }
4554
4555
4556 void
4557 Editor::reverse_region ()
4558 {
4559         if (!_session) {
4560                 return;
4561         }
4562
4563         Reverse rev (*_session);
4564         apply_filter (rev, _("reverse regions"));
4565 }
4566
4567 void
4568 Editor::strip_region_silence ()
4569 {
4570         if (!_session) {
4571                 return;
4572         }
4573
4574         RegionSelection rs;
4575         get_regions_for_action (rs);
4576
4577         if (rs.empty()) {
4578                 return;
4579         }
4580
4581         std::list<boost::shared_ptr<AudioRegion> > ar;
4582
4583         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4584                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4585                 if (arv) {
4586                         ar.push_back (arv->audio_region ());
4587                 }
4588         }
4589
4590         StripSilenceDialog d (_session, ar);
4591         int const r = d.run ();
4592
4593         if (r == Gtk::RESPONSE_OK) {
4594                 StripSilence s (*_session, d.threshold (), d.minimum_length (), d.fade_length ());
4595                 apply_filter (s, _("strip silence"));
4596         }
4597 }
4598
4599 Command*
4600 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4601 {
4602         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4603         mrv.selection_as_notelist (selected);
4604
4605         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4606         v.push_back (selected);
4607
4608         return op (mrv.midi_region()->model(), v);
4609 }
4610
4611 void
4612 Editor::apply_midi_note_edit_op (MidiOperator& op)
4613 {
4614         RegionSelection rs;
4615         Command* cmd;
4616
4617         get_regions_for_action (rs);
4618
4619         if (rs.empty()) {
4620                 return;
4621         }
4622
4623         begin_reversible_command (op.name ());
4624
4625         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4626                 RegionSelection::iterator tmp = r;
4627                 ++tmp;
4628
4629                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4630
4631                 if (mrv) {
4632                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4633                         if (cmd) {
4634                                 (*cmd)();
4635                                 _session->add_command (cmd);
4636                         }
4637                 }
4638
4639                 r = tmp;
4640         }
4641
4642         commit_reversible_command ();
4643         rs.clear ();
4644 }
4645
4646 void
4647 Editor::quantize_region ()
4648 {
4649         if (!_session) {
4650                 return;
4651         }
4652
4653         QuantizeDialog* qd = new QuantizeDialog (*this);
4654
4655         qd->present ();
4656         const int r = qd->run ();
4657         qd->hide ();
4658
4659         if (r == Gtk::RESPONSE_OK) {
4660                 Quantize quant (*_session, Plain,
4661                                 qd->snap_start(), qd->snap_end(),
4662                                 qd->start_grid_size(), qd->end_grid_size(),
4663                                 qd->strength(), qd->swing(), qd->threshold());
4664
4665                 apply_midi_note_edit_op (quant);
4666         }
4667 }
4668
4669 void
4670 Editor::apply_filter (Filter& filter, string command)
4671 {
4672         RegionSelection rs;
4673
4674         get_regions_for_action (rs);
4675
4676         if (rs.empty()) {
4677                 return;
4678         }
4679
4680         begin_reversible_command (command);
4681
4682         track_canvas->get_window()->set_cursor (*wait_cursor);
4683         gdk_flush ();
4684
4685         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4686                 RegionSelection::iterator tmp = r;
4687                 ++tmp;
4688
4689                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4690                 if (arv) {
4691                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4692
4693                         if (arv->audio_region()->apply (filter) == 0) {
4694
4695                                 playlist->clear_history ();
4696                                 
4697                                 if (filter.results.empty ()) {
4698
4699                                         /* no regions returned; remove the old one */
4700                                         playlist->remove_region (arv->region ());
4701
4702                                 } else {
4703
4704                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4705
4706                                         /* first region replaces the old one */
4707                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4708                                         ++res;
4709
4710                                         /* add the rest */
4711                                         while (res != filter.results.end()) {
4712                                                 playlist->add_region (*res, (*res)->position());
4713                                                 ++res;
4714                                         }
4715
4716                                 }
4717
4718                                 _session->add_command(new StatefulDiffCommand (playlist));
4719                         } else {
4720                                 goto out;
4721                         }
4722                 }
4723
4724                 r = tmp;
4725         }
4726
4727         commit_reversible_command ();
4728         rs.clear ();
4729
4730   out:
4731         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
4732 }
4733
4734 void
4735 Editor::region_selection_op (void (Region::*pmf)(void))
4736 {
4737         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4738                 Region* region = (*i)->region().get();
4739                 (region->*pmf)();
4740         }
4741 }
4742
4743
4744 void
4745 Editor::region_selection_op (void (Region::*pmf)(void*), void *arg)
4746 {
4747         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4748                 Region* region = (*i)->region().get();
4749                 (region->*pmf)(arg);
4750         }
4751 }
4752
4753 void
4754 Editor::region_selection_op (void (Region::*pmf)(bool), bool yn)
4755 {
4756         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
4757                 Region* region = (*i)->region().get();
4758                 (region->*pmf)(yn);
4759         }
4760 }
4761
4762 void
4763 Editor::external_edit_region ()
4764 {
4765         /* more to come */
4766 }
4767
4768 void
4769 Editor::brush (nframes64_t pos)
4770 {
4771         RegionSelection sel;
4772         RegionSelection rs;
4773
4774         get_regions_for_action (rs);
4775
4776         snap_to (pos);
4777
4778         if (rs.empty()) {
4779                 return;
4780         }
4781
4782         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4783                 mouse_brush_insert_region ((*i), pos);
4784         }
4785 }
4786
4787 void
4788 Editor::reset_region_gain_envelopes ()
4789 {
4790         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4791
4792         if (!_session || rs.empty()) {
4793                 return;
4794         }
4795
4796         _session->begin_reversible_command (_("reset region gain"));
4797
4798         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4799                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4800                 if (arv) {
4801                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4802                         XMLNode& before (alist->get_state());
4803
4804                         arv->audio_region()->set_default_envelope ();
4805                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4806                 }
4807         }
4808
4809         _session->commit_reversible_command ();
4810 }
4811
4812 void
4813 Editor::toggle_gain_envelope_visibility ()
4814 {
4815         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4816
4817         if (!_session || rs.empty()) {
4818                 return;
4819         }
4820
4821         _session->begin_reversible_command (_("region gain envelope visible"));
4822
4823         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4824                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4825                 if (arv) {
4826                         arv->region()->clear_history ();
4827                         arv->set_envelope_visible (!arv->envelope_visible());
4828                         _session->add_command (new StatefulDiffCommand (arv->region()));
4829                 }
4830         }
4831
4832         _session->commit_reversible_command ();
4833 }
4834
4835 void
4836 Editor::toggle_gain_envelope_active ()
4837 {
4838         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4839
4840         if (!_session || rs.empty()) {
4841                 return;
4842         }
4843
4844         _session->begin_reversible_command (_("region gain envelope active"));
4845
4846         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4847                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4848                 if (arv) {
4849                         arv->region()->clear_history ();
4850                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4851                         _session->add_command (new StatefulDiffCommand (arv->region()));
4852                 }
4853         }
4854
4855         _session->commit_reversible_command ();
4856 }
4857
4858 void
4859 Editor::toggle_region_lock ()
4860 {
4861         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4862
4863         if (!_session || rs.empty()) {
4864                 return;
4865         }
4866
4867         _session->begin_reversible_command (_("region lock"));
4868
4869         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4870                 (*i)->region()->clear_history ();
4871                 (*i)->region()->set_locked (!(*i)->region()->locked());
4872                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4873         }
4874
4875         _session->commit_reversible_command ();
4876 }
4877
4878 void
4879 Editor::toggle_region_lock_style ()
4880 {
4881         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4882
4883         if (!_session || rs.empty()) {
4884                 return;
4885         }
4886
4887         _session->begin_reversible_command (_("region lock style"));
4888
4889         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4890                 (*i)->region()->clear_history ();
4891                 Region::PositionLockStyle const ns = (*i)->region()->positional_lock_style() == Region::AudioTime ? Region::MusicTime : Region::AudioTime;
4892                 (*i)->region()->set_position_lock_style (ns);
4893                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4894         }
4895
4896         _session->commit_reversible_command ();
4897 }
4898
4899
4900 void
4901 Editor::toggle_region_mute ()
4902 {
4903         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4904
4905         if (!_session || rs.empty()) {
4906                 return;
4907         }
4908
4909         _session->begin_reversible_command (_("region mute"));
4910
4911         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4912                 (*i)->region()->clear_history ();
4913                 (*i)->region()->set_muted (!(*i)->region()->muted());
4914                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4915         }
4916
4917         _session->commit_reversible_command ();
4918 }
4919
4920 void
4921 Editor::toggle_region_opaque ()
4922 {
4923         RegionSelection rs = get_equivalent_regions (selection->regions, ARDOUR::Properties::edit.property_id);
4924
4925         if (!_session || rs.empty()) {
4926                 return;
4927         }
4928
4929         _session->begin_reversible_command (_("region opacity"));
4930
4931         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4932                 (*i)->region()->clear_history ();
4933                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4934                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4935         }
4936
4937         _session->commit_reversible_command ();
4938 }
4939
4940 void
4941 Editor::toggle_record_enable ()
4942 {
4943         bool new_state = false;
4944         bool first = true;
4945         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4946                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4947                 if (!rtav)
4948                         continue;
4949                 if (!rtav->is_track())
4950                         continue;
4951
4952                 if (first) {
4953                         new_state = !rtav->track()->record_enabled();
4954                         first = false;
4955                 }
4956
4957                 rtav->track()->set_record_enable(new_state, this);
4958         }
4959 }
4960
4961
4962 void
4963 Editor::set_fade_length (bool in)
4964 {
4965         RegionSelection rs;
4966
4967         get_regions_for_action (rs, true);
4968
4969         if (rs.empty()) {
4970                 return;
4971         }
4972
4973         /* we need a region to measure the offset from the start */
4974
4975         RegionView* rv = rs.front ();
4976
4977         nframes64_t pos = get_preferred_edit_position();
4978         nframes64_t len;
4979         char* cmd;
4980
4981         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
4982                 /* edit point is outside the relevant region */
4983                 return;
4984         }
4985
4986         if (in) {
4987                 if (pos <= rv->region()->position()) {
4988                         /* can't do it */
4989                         return;
4990                 }
4991                 len = pos - rv->region()->position();
4992                 cmd = _("set fade in length");
4993         } else {
4994                 if (pos >= rv->region()->last_frame()) {
4995                         /* can't do it */
4996                         return;
4997                 }
4998                 len = rv->region()->last_frame() - pos;
4999                 cmd = _("set fade out length");
5000         }
5001
5002         begin_reversible_command (cmd);
5003
5004         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5005                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5006
5007                 if (!tmp) {
5008                         return;
5009                 }
5010
5011                 boost::shared_ptr<AutomationList> alist;
5012                 if (in) {
5013                         alist = tmp->audio_region()->fade_in();
5014                 } else {
5015                         alist = tmp->audio_region()->fade_out();
5016                 }
5017
5018                 XMLNode &before = alist->get_state();
5019
5020                 if (in) {
5021                         tmp->audio_region()->set_fade_in_length (len);
5022                         tmp->audio_region()->set_fade_in_active (true);
5023                 } else {
5024                         tmp->audio_region()->set_fade_out_length (len);
5025                         tmp->audio_region()->set_fade_out_active (true);
5026                 }
5027
5028                 XMLNode &after = alist->get_state();
5029                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
5030         }
5031
5032         commit_reversible_command ();
5033 }
5034
5035 void
5036 Editor::toggle_fade_active (bool in)
5037 {
5038         RegionSelection rs;
5039
5040         get_regions_for_action (rs);
5041
5042         if (rs.empty()) {
5043                 return;
5044         }
5045
5046         const char* cmd = (in ? _("toggle fade in active") : _("toggle fade out active"));
5047         bool have_switch = false;
5048         bool yn = false;
5049
5050         begin_reversible_command (cmd);
5051
5052         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5053                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5054
5055                 if (!tmp) {
5056                         return;
5057                 }
5058
5059                 boost::shared_ptr<AudioRegion> region (tmp->audio_region());
5060
5061                 /* make the behaviour consistent across all regions */
5062
5063                 if (!have_switch) {
5064                         if (in) {
5065                                 yn = region->fade_in_active();
5066                         } else {
5067                                 yn = region->fade_out_active();
5068                         }
5069                         have_switch = true;
5070                 }
5071
5072                 region->clear_history ();
5073
5074                 if (in) {
5075                         region->set_fade_in_active (!yn);
5076                 } else {
5077                         region->set_fade_out_active (!yn);
5078                 }
5079                 
5080                 _session->add_command(new StatefulDiffCommand (region));
5081         }
5082
5083         commit_reversible_command ();
5084 }
5085
5086 void
5087 Editor::set_fade_in_shape (AudioRegion::FadeShape shape)
5088 {
5089         RegionSelection rs;
5090
5091         get_regions_for_action (rs);
5092
5093         if (rs.empty()) {
5094                 return;
5095         }
5096
5097         begin_reversible_command (_("set fade in shape"));
5098
5099         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5100                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5101
5102                 if (!tmp) {
5103                         return;
5104                 }
5105
5106                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
5107                 XMLNode &before = alist->get_state();
5108
5109                 tmp->audio_region()->set_fade_in_shape (shape);
5110
5111                 XMLNode &after = alist->get_state();
5112                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5113         }
5114
5115         commit_reversible_command ();
5116
5117 }
5118
5119 void
5120 Editor::set_fade_out_shape (AudioRegion::FadeShape shape)
5121 {
5122         RegionSelection rs;
5123
5124         get_regions_for_action (rs);
5125
5126         if (rs.empty()) {
5127                 return;
5128         }
5129
5130         begin_reversible_command (_("set fade out shape"));
5131
5132         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5133                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5134
5135                 if (!tmp) {
5136                         return;
5137                 }
5138
5139                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5140                 XMLNode &before = alist->get_state();
5141
5142                 tmp->audio_region()->set_fade_out_shape (shape);
5143
5144                 XMLNode &after = alist->get_state();
5145                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5146         }
5147
5148         commit_reversible_command ();
5149 }
5150
5151 void
5152 Editor::set_fade_in_active (bool yn)
5153 {
5154         RegionSelection rs;
5155
5156         get_regions_for_action (rs);
5157
5158         if (rs.empty()) {
5159                 return;
5160         }
5161
5162         begin_reversible_command (_("set fade in active"));
5163
5164         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5165                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5166
5167                 if (!tmp) {
5168                         return;
5169                 }
5170
5171
5172                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5173                 
5174                 ar->clear_history ();
5175                 ar->set_fade_in_active (yn);
5176                 _session->add_command (new StatefulDiffCommand (ar));
5177         }
5178
5179         commit_reversible_command ();
5180 }
5181
5182 void
5183 Editor::set_fade_out_active (bool yn)
5184 {
5185         RegionSelection rs;
5186
5187         get_regions_for_action (rs);
5188
5189         if (rs.empty()) {
5190                 return;
5191         }
5192
5193         begin_reversible_command (_("set fade out active"));
5194
5195         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5196                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5197
5198                 if (!tmp) {
5199                         return;
5200                 }
5201
5202                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5203
5204                 ar->clear_history ();
5205                 ar->set_fade_out_active (yn);
5206                 _session->add_command(new StatefulDiffCommand (ar));
5207         }
5208
5209         commit_reversible_command ();
5210 }
5211
5212 void
5213 Editor::toggle_selected_region_fades (int dir)
5214 {
5215         RegionSelection rs;
5216         RegionSelection::iterator i;
5217         boost::shared_ptr<AudioRegion> ar;
5218         bool yn;
5219
5220         get_regions_for_action (rs);
5221
5222         if (rs.empty()) {
5223                 return;
5224         }
5225
5226         for (i = rs.begin(); i != rs.end(); ++i) {
5227                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5228                         if (dir == -1) {
5229                                 yn = ar->fade_out_active ();
5230                         } else {
5231                                 yn = ar->fade_in_active ();
5232                         }
5233                         break;
5234                 }
5235         }
5236
5237         if (i == rs.end()) {
5238                 return;
5239         }
5240
5241         /* XXX should this undo-able? */
5242
5243         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5244                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5245                         continue;
5246                 }
5247                 if (dir == 1 || dir == 0) {
5248                         ar->set_fade_in_active (!yn);
5249                 }
5250
5251                 if (dir == -1 || dir == 0) {
5252                         ar->set_fade_out_active (!yn);
5253                 }
5254         }
5255 }
5256
5257
5258 /** Update region fade visibility after its configuration has been changed */
5259 void
5260 Editor::update_region_fade_visibility ()
5261 {
5262         bool _fade_visibility = _session->config.get_show_region_fades ();
5263
5264         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5265                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5266                 if (v) {
5267                         if (_fade_visibility) {
5268                                 v->audio_view()->show_all_fades ();
5269                         } else {
5270                                 v->audio_view()->hide_all_fades ();
5271                         }
5272                 }
5273         }
5274 }
5275
5276 /** Update crossfade visibility after its configuration has been changed */
5277 void
5278 Editor::update_xfade_visibility ()
5279 {
5280         _xfade_visibility = _session->config.get_xfades_visible ();
5281
5282         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5283                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5284                 if (v) {
5285                         if (_xfade_visibility) {
5286                                 v->show_all_xfades ();
5287                         } else {
5288                                 v->hide_all_xfades ();
5289                         }
5290                 }
5291         }
5292 }
5293
5294 void
5295 Editor::set_edit_point ()
5296 {
5297         nframes64_t where;
5298         bool ignored;
5299
5300         if (!mouse_frame (where, ignored)) {
5301                 return;
5302         }
5303
5304         snap_to (where);
5305
5306         if (selection->markers.empty()) {
5307
5308                 mouse_add_new_marker (where);
5309
5310         } else {
5311                 bool ignored;
5312
5313                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5314
5315                 if (loc) {
5316                         loc->move_to (where);
5317                 }
5318         }
5319 }
5320
5321 void
5322 Editor::set_playhead_cursor ()
5323 {
5324         if (entered_marker) {
5325                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5326         } else {
5327                 nframes64_t where;
5328                 bool ignored;
5329
5330                 if (!mouse_frame (where, ignored)) {
5331                         return;
5332                 }
5333
5334                 snap_to (where);
5335
5336                 if (_session) {
5337                         _session->request_locate (where, _session->transport_rolling());
5338                 }
5339         }
5340 }
5341
5342 void
5343 Editor::split ()
5344 {
5345         RegionSelection rs;
5346
5347         get_regions_for_action (rs, true);
5348
5349         nframes64_t where = get_preferred_edit_position();
5350
5351         if (rs.empty()) {
5352                 return;
5353         }
5354
5355         split_regions_at (where, rs);
5356 }
5357
5358 void
5359 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5360 {
5361         if (entered_track && mouse_mode == MouseObject) {
5362                 if (!selection->tracks.empty()) {
5363                         if (!selection->selected (entered_track)) {
5364                                 selection->add (entered_track);
5365                         }
5366                 } else {
5367                         /* there is no selection, but this operation requires/prefers selected objects */
5368
5369                         if (op_really_wants_one_track_if_none_are_selected) {
5370                                 selection->set (entered_track);
5371                         }
5372                 }
5373         }
5374 }
5375
5376 struct EditorOrderRouteSorter {
5377     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5378             /* use of ">" forces the correct sort order */
5379             return a->order_key ("editor") < b->order_key ("editor");
5380     }
5381 };
5382
5383 void
5384 Editor::select_next_route()
5385 {
5386         if (selection->tracks.empty()) {
5387                 selection->set (track_views.front());
5388                 return;
5389         }
5390
5391         TimeAxisView* current = selection->tracks.front();
5392
5393         RouteUI *rui;
5394         do {
5395                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5396                         if (*i == current) {
5397                                 ++i;
5398                                 if (i != track_views.end()) {
5399                                         current = (*i);
5400                                 } else {
5401                                         current = (*(track_views.begin()));
5402                                         //selection->set (*(track_views.begin()));
5403                                 }
5404                                 break;
5405                         }
5406                 }
5407                 rui = dynamic_cast<RouteUI *>(current);
5408         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5409
5410         selection->set(current);
5411
5412         ensure_track_visible(current);
5413 }
5414
5415 void
5416 Editor::select_prev_route()
5417 {
5418         if (selection->tracks.empty()) {
5419                 selection->set (track_views.front());
5420                 return;
5421         }
5422
5423         TimeAxisView* current = selection->tracks.front();
5424
5425         RouteUI *rui;
5426         do {
5427                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5428                         if (*i == current) {
5429                                 ++i;
5430                                 if (i != track_views.rend()) {
5431                                         current = (*i);
5432                                 } else {
5433                                         current = *(track_views.rbegin());
5434                                 }
5435                                 break;
5436                         }
5437                 }
5438                 rui = dynamic_cast<RouteUI *>(current);
5439         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5440
5441         selection->set (current);
5442
5443         ensure_track_visible(current);
5444 }
5445
5446 void
5447 Editor::ensure_track_visible(TimeAxisView *track)
5448 {
5449         if (track->hidden())
5450                 return;
5451
5452         double const current_view_min_y = vertical_adjustment.get_value();
5453         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5454
5455         double const track_min_y = track->y_position ();
5456         double const track_max_y = track->y_position () + track->effective_height ();
5457
5458         if (track_min_y >= current_view_min_y &&
5459             track_max_y <= current_view_max_y) {
5460                 return;
5461         }
5462
5463         double new_value;
5464
5465         if (track_min_y < current_view_min_y) {
5466                 // Track is above the current view
5467                 new_value = track_min_y;
5468         } else {
5469                 // Track is below the current view
5470                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5471         }
5472
5473         vertical_adjustment.set_value(new_value);
5474 }
5475
5476 void
5477 Editor::set_loop_from_selection (bool play)
5478 {
5479         if (_session == 0 || selection->time.empty()) {
5480                 return;
5481         }
5482
5483         nframes64_t start = selection->time[clicked_selection].start;
5484         nframes64_t end = selection->time[clicked_selection].end;
5485
5486         set_loop_range (start, end,  _("set loop range from selection"));
5487
5488         if (play) {
5489                 _session->request_play_loop (true);
5490                 _session->request_locate (start, true);
5491         }
5492 }
5493
5494 void
5495 Editor::set_loop_from_edit_range (bool play)
5496 {
5497         if (_session == 0) {
5498                 return;
5499         }
5500
5501         nframes64_t start;
5502         nframes64_t end;
5503
5504         if (!get_edit_op_range (start, end)) {
5505                 return;
5506         }
5507
5508         set_loop_range (start, end,  _("set loop range from edit range"));
5509
5510         if (play) {
5511                 _session->request_play_loop (true);
5512                 _session->request_locate (start, true);
5513         }
5514 }
5515
5516 void
5517 Editor::set_loop_from_region (bool play)
5518 {
5519         nframes64_t start = max_frames;
5520         nframes64_t end = 0;
5521
5522         RegionSelection rs;
5523
5524         get_regions_for_action (rs);
5525
5526         if (rs.empty()) {
5527                 return;
5528         }
5529
5530         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5531                 if ((*i)->region()->position() < start) {
5532                         start = (*i)->region()->position();
5533                 }
5534                 if ((*i)->region()->last_frame() + 1 > end) {
5535                         end = (*i)->region()->last_frame() + 1;
5536                 }
5537         }
5538
5539         set_loop_range (start, end, _("set loop range from region"));
5540
5541         if (play) {
5542                 _session->request_play_loop (true);
5543                 _session->request_locate (start, true);
5544         }
5545 }
5546
5547 void
5548 Editor::set_punch_from_selection ()
5549 {
5550         if (_session == 0 || selection->time.empty()) {
5551                 return;
5552         }
5553
5554         nframes64_t start = selection->time[clicked_selection].start;
5555         nframes64_t end = selection->time[clicked_selection].end;
5556
5557         set_punch_range (start, end,  _("set punch range from selection"));
5558 }
5559
5560 void
5561 Editor::set_punch_from_edit_range ()
5562 {
5563         if (_session == 0) {
5564                 return;
5565         }
5566
5567         nframes64_t start;
5568         nframes64_t end;
5569
5570         if (!get_edit_op_range (start, end)) {
5571                 return;
5572         }
5573
5574         set_punch_range (start, end,  _("set punch range from edit range"));
5575 }
5576
5577 void
5578 Editor::set_punch_from_region ()
5579 {
5580         nframes64_t start = max_frames;
5581         nframes64_t end = 0;
5582
5583         RegionSelection rs;
5584
5585         get_regions_for_action (rs);
5586
5587         if (rs.empty()) {
5588                 return;
5589         }
5590
5591         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5592                 if ((*i)->region()->position() < start) {
5593                         start = (*i)->region()->position();
5594                 }
5595                 if ((*i)->region()->last_frame() + 1 > end) {
5596                         end = (*i)->region()->last_frame() + 1;
5597                 }
5598         }
5599
5600         set_punch_range (start, end, _("set punch range from region"));
5601 }
5602
5603 void
5604 Editor::pitch_shift_regions ()
5605 {
5606         RegionSelection rs;
5607
5608         get_regions_for_action (rs);
5609
5610         if (rs.empty()) {
5611                 return;
5612         }
5613
5614         pitch_shift (rs, 1.2);
5615 }
5616
5617 void
5618 Editor::use_region_as_bar ()
5619 {
5620         if (!_session) {
5621                 return;
5622         }
5623
5624         RegionSelection rs;
5625
5626         get_regions_for_action (rs);
5627
5628         if (rs.empty()) {
5629                 return;
5630         }
5631
5632         RegionView* rv = rs.front();
5633
5634         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5635 }
5636
5637 void
5638 Editor::use_range_as_bar ()
5639 {
5640         nframes64_t start, end;
5641         if (get_edit_op_range (start, end)) {
5642                 define_one_bar (start, end);
5643         }
5644 }
5645
5646 void
5647 Editor::define_one_bar (nframes64_t start, nframes64_t end)
5648 {
5649         nframes64_t length = end - start;
5650
5651         const Meter& m (_session->tempo_map().meter_at (start));
5652
5653         /* length = 1 bar */
5654
5655         /* now we want frames per beat.
5656            we have frames per bar, and beats per bar, so ...
5657         */
5658
5659         double frames_per_beat = length / m.beats_per_bar();
5660
5661         /* beats per minute = */
5662
5663         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5664
5665         /* now decide whether to:
5666
5667             (a) set global tempo
5668             (b) add a new tempo marker
5669
5670         */
5671
5672         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5673
5674         bool do_global = false;
5675
5676         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5677
5678                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5679                    at the start, or create a new marker
5680                 */
5681
5682                 vector<string> options;
5683                 options.push_back (_("Cancel"));
5684                 options.push_back (_("Add new marker"));
5685                 options.push_back (_("Set global tempo"));
5686
5687                 Choice c (
5688                         _("Define one bar"),
5689                         _("Do you want to set the global tempo or add a new tempo marker?"),
5690                         options
5691                         );
5692                 
5693                 c.set_default_response (2);
5694
5695                 switch (c.run()) {
5696                 case 0:
5697                         return;
5698
5699                 case 2:
5700                         do_global = true;
5701                         break;
5702
5703                 default:
5704                         do_global = false;
5705                 }
5706
5707         } else {
5708
5709                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5710                    if the marker is at the region starter, change it, otherwise add
5711                    a new tempo marker
5712                 */
5713         }
5714
5715         begin_reversible_command (_("set tempo from region"));
5716         XMLNode& before (_session->tempo_map().get_state());
5717
5718         if (do_global) {
5719                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5720         } else if (t.frame() == start) {
5721                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5722         } else {
5723                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5724         }
5725
5726         XMLNode& after (_session->tempo_map().get_state());
5727
5728         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5729         commit_reversible_command ();
5730 }
5731
5732 void
5733 Editor::split_region_at_transients ()
5734 {
5735         AnalysisFeatureList positions;
5736
5737         if (!_session) {
5738                 return;
5739         }
5740
5741         RegionSelection rs;
5742
5743         get_regions_for_action (rs);
5744
5745         if (rs.empty()) {
5746                 return;
5747         }
5748
5749         _session->begin_reversible_command (_("split regions"));
5750
5751         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5752
5753                 RegionSelection::iterator tmp;
5754
5755                 tmp = i;
5756                 ++tmp;
5757
5758                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5759
5760                 if (ar && (ar->get_transients (positions) == 0)) {
5761                         split_region_at_points ((*i)->region(), positions, true);
5762                         positions.clear ();
5763                 }
5764
5765                 i = tmp;
5766         }
5767
5768         _session->commit_reversible_command ();
5769
5770 }
5771
5772 void
5773 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret)
5774 {
5775         bool use_rhythmic_rodent = false;
5776
5777         boost::shared_ptr<Playlist> pl = r->playlist();
5778
5779         if (!pl) {
5780                 return;
5781         }
5782
5783         if (positions.empty()) {
5784                 return;
5785         }
5786
5787
5788         if (positions.size() > 20) {
5789                 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);
5790                 MessageDialog msg (msgstr,
5791                                    false,
5792                                    Gtk::MESSAGE_INFO,
5793                                    Gtk::BUTTONS_OK_CANCEL);
5794
5795                 if (can_ferret) {
5796                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5797                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5798                 } else {
5799                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5800                 }
5801
5802                 msg.set_title (_("Excessive split?"));
5803                 msg.present ();
5804
5805                 int response = msg.run();
5806                 msg.hide ();
5807                 switch (response) {
5808                 case RESPONSE_OK:
5809                         break;
5810                 case RESPONSE_APPLY:
5811                         use_rhythmic_rodent = true;
5812                         break;
5813                 default:
5814                         return;
5815                 }
5816         }
5817
5818         if (use_rhythmic_rodent) {
5819                 show_rhythm_ferret ();
5820                 return;
5821         }
5822
5823         AnalysisFeatureList::const_iterator x;
5824
5825         nframes64_t pos = r->position();
5826
5827         pl->clear_history ();
5828
5829         x = positions.begin();
5830
5831         while (x != positions.end()) {
5832                 if ((*x) > pos) {
5833                         break;
5834                 }
5835                 ++x;
5836         }
5837
5838         if (x == positions.end()) {
5839                 return;
5840         }
5841
5842         pl->freeze ();
5843         pl->remove_region (r);
5844
5845         while (x != positions.end()) {
5846
5847                 /* file start = original start + how far we from the initial position ?
5848                  */
5849
5850                 nframes64_t file_start = r->start() + (pos - r->position());
5851
5852                 /* length = next position - current position
5853                  */
5854
5855                 nframes64_t len = (*x) - pos;
5856
5857                 /* XXX we do we really want to allow even single-sample regions?
5858                    shouldn't we have some kind of lower limit on region size?
5859                 */
5860
5861                 if (len <= 0) {
5862                         break;
5863                 }
5864
5865                 string new_name;
5866
5867                 if (RegionFactory::region_name (new_name, r->name())) {
5868                         break;
5869                 }
5870
5871                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5872
5873                 PropertyList plist; 
5874                 
5875                 plist.add (ARDOUR::Properties::start, file_start);
5876                 plist.add (ARDOUR::Properties::length, len);
5877                 plist.add (ARDOUR::Properties::name, new_name);
5878                 plist.add (ARDOUR::Properties::layer, 0);
5879
5880                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5881                 pl->add_region (nr, pos);
5882
5883                 pos += len;
5884                 ++x;
5885
5886                 if (*x > r->last_frame()) {
5887
5888                         /* add final fragment */
5889
5890                         file_start = r->start() + (pos - r->position());
5891                         len = r->last_frame() - pos;
5892
5893                         PropertyList plist2; 
5894                         
5895                         plist2.add (ARDOUR::Properties::start, file_start);
5896                         plist2.add (ARDOUR::Properties::length, len);
5897                         plist2.add (ARDOUR::Properties::name, new_name);
5898                         plist2.add (ARDOUR::Properties::layer, 0);
5899
5900                         nr = RegionFactory::create (r->sources(), plist2); 
5901                         pl->add_region (nr, pos);
5902
5903                         break;
5904                 }
5905         }
5906
5907         pl->thaw ();
5908
5909         _session->add_command (new StatefulDiffCommand (pl));
5910 }
5911
5912 void
5913 Editor::tab_to_transient (bool forward)
5914 {
5915         AnalysisFeatureList positions;
5916
5917         if (!_session) {
5918                 return;
5919         }
5920
5921         nframes64_t pos = _session->audible_frame ();
5922
5923         if (!selection->tracks.empty()) {
5924
5925                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
5926
5927                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
5928
5929                         if (rtv) {
5930                                 boost::shared_ptr<Track> tr = rtv->track();
5931                                 if (tr) {
5932                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
5933                                         if (pl) {
5934                                                 nframes64_t result = pl->find_next_transient (pos, forward ? 1 : -1);
5935
5936                                                 if (result >= 0) {
5937                                                         positions.push_back (result);
5938                                                 }
5939                                         }
5940                                 }
5941                         }
5942                 }
5943
5944         } else {
5945
5946                 RegionSelection rs;
5947
5948                 get_regions_for_action (rs);
5949
5950                 if (rs.empty()) {
5951                         return;
5952                 }
5953
5954                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5955                         (*r)->region()->get_transients (positions);
5956                 }
5957         }
5958
5959         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
5960
5961         if (forward) {
5962                 AnalysisFeatureList::iterator x;
5963
5964                 for (x = positions.begin(); x != positions.end(); ++x) {
5965                         if ((*x) > pos) {
5966                                 break;
5967                         }
5968                 }
5969
5970                 if (x != positions.end ()) {
5971                         _session->request_locate (*x);
5972                 }
5973
5974         } else {
5975                 AnalysisFeatureList::reverse_iterator x;
5976
5977                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
5978                         if ((*x) < pos) {
5979                                 break;
5980                         }
5981                 }
5982
5983                 if (x != positions.rend ()) {
5984                         _session->request_locate (*x);
5985                 }
5986         }
5987 }
5988 void
5989 Editor::playhead_forward_to_grid ()
5990 {
5991         if (!_session) return;
5992         nframes64_t pos = playhead_cursor->current_frame;
5993         if (pos < max_frames - 1) {
5994                 pos += 2;
5995                 snap_to_internal (pos, 1, false);
5996                 _session->request_locate (pos);
5997         }
5998 }
5999
6000
6001 void
6002 Editor::playhead_backward_to_grid ()
6003 {
6004         if (!_session) return;
6005         nframes64_t pos = playhead_cursor->current_frame;
6006         if (pos > 2) {
6007                 pos -= 2;
6008                 snap_to_internal (pos, -1, false);
6009                 _session->request_locate (pos);
6010         }
6011 }
6012
6013 void
6014 Editor::set_track_height (uint32_t h)
6015 {
6016         TrackSelection& ts (selection->tracks);
6017
6018         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6019                 (*x)->set_height (h);
6020         }
6021 }
6022
6023 void
6024 Editor::toggle_tracks_active ()
6025 {
6026         TrackSelection& ts (selection->tracks);
6027         bool first = true;
6028         bool target = false;
6029
6030         if (ts.empty()) {
6031                 return;
6032         }
6033
6034         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6035                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6036
6037                 if (rtv) {
6038                         if (first) {
6039                                 target = !rtv->_route->active();
6040                                 first = false;
6041                         }
6042                         rtv->_route->set_active (target);
6043                 }
6044         }
6045 }
6046
6047 void
6048 Editor::remove_tracks ()
6049 {
6050         TrackSelection& ts (selection->tracks);
6051
6052         if (ts.empty()) {
6053                 return;
6054         }
6055
6056         vector<string> choices;
6057         string prompt;
6058         int ntracks = 0;
6059         int nbusses = 0;
6060         const char* trackstr;
6061         const char* busstr;
6062         vector<boost::shared_ptr<Route> > routes;
6063
6064         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6065                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6066                 if (rtv) {
6067                         if (rtv->is_track()) {
6068                                 ntracks++;
6069                         } else {
6070                                 nbusses++;
6071                         }
6072                 }
6073                 routes.push_back (rtv->_route);
6074         }
6075
6076         if (ntracks + nbusses == 0) {
6077                 return;
6078         }
6079
6080         if (ntracks > 1) {
6081                 trackstr = _("tracks");
6082         } else {
6083                 trackstr = _("track");
6084         }
6085
6086         if (nbusses > 1) {
6087                 busstr = _("busses");
6088         } else {
6089                 busstr = _("bus");
6090         }
6091
6092         if (ntracks) {
6093                 if (nbusses) {
6094                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6095                                                     "(You may also lose the playlists associated with the %2)\n\n"
6096                                                     "This action cannot be undone!"),
6097                                                   ntracks, trackstr, nbusses, busstr);
6098                 } else {
6099                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6100                                                     "(You may also lose the playlists associated with the %2)\n\n"
6101                                                     "This action cannot be undone!"),
6102                                                   ntracks, trackstr);
6103                 }
6104         } else if (nbusses) {
6105                 prompt  = string_compose (_("Do you really want to remove %1 %2?"),
6106                                           nbusses, busstr);
6107         }
6108
6109         choices.push_back (_("No, do nothing."));
6110         if (ntracks + nbusses > 1) {
6111                 choices.push_back (_("Yes, remove them."));
6112         } else {
6113                 choices.push_back (_("Yes, remove it."));
6114         }
6115
6116         string title;
6117         if (ntracks) {
6118                 title = string_compose (_("Remove %1"), trackstr);
6119         } else {
6120                 title = string_compose (_("Remove %1"), busstr);
6121         }
6122
6123         Choice prompter (title, prompt, choices);
6124
6125         if (prompter.run () != 1) {
6126                 return;
6127         }
6128
6129         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6130                 _session->remove_route (*x);
6131         }
6132 }
6133
6134 void
6135 Editor::do_insert_time ()
6136 {
6137         if (selection->tracks.empty()) {
6138                 return;
6139         }
6140
6141         ArdourDialog d (*this, _("Insert Time"));
6142
6143         nframes64_t const pos = get_preferred_edit_position ();
6144
6145         d.get_vbox()->set_border_width (12);
6146         d.get_vbox()->set_spacing (4);
6147
6148         Table table (2, 2);
6149         table.set_spacings (4);
6150
6151         Label time_label (_("Time to insert:"));
6152         time_label.set_alignment (1, 0.5);
6153         table.attach (time_label, 0, 1, 0, 1, FILL | EXPAND);
6154         AudioClock clock ("insertTimeClock", true, X_("InsertTimeClock"), true, false, true, true);
6155         clock.set (0);
6156         clock.set_session (_session);
6157         clock.set_bbt_reference (pos);
6158         table.attach (clock, 1, 2, 0, 1);
6159
6160         Label intersected_label (_("Intersected regions should:"));
6161         intersected_label.set_alignment (1, 0.5);
6162         table.attach (intersected_label, 0, 1, 1, 2, FILL | EXPAND);
6163         ComboBoxText intersected_combo;
6164         intersected_combo.append_text (_("stay in position"));
6165         intersected_combo.append_text (_("move"));
6166         intersected_combo.append_text (_("be split"));
6167         intersected_combo.set_active (0);
6168         table.attach (intersected_combo, 1, 2, 1, 2);
6169
6170         d.get_vbox()->pack_start (table);
6171
6172         CheckButton move_glued (_("Move glued regions"));
6173         d.get_vbox()->pack_start (move_glued);
6174         CheckButton move_markers (_("Move markers"));
6175         d.get_vbox()->pack_start (move_markers);
6176         CheckButton move_tempos (_("Move tempo and meter changes"));
6177         d.get_vbox()->pack_start (move_tempos);
6178
6179         d.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
6180         d.add_button (_("Insert time"), Gtk::RESPONSE_OK);
6181         d.show_all ();
6182
6183         int response = d.run ();
6184
6185         if (response != RESPONSE_OK) {
6186                 return;
6187         }
6188
6189         nframes64_t distance = clock.current_duration (pos);
6190
6191         if (distance == 0) {
6192                 return;
6193         }
6194
6195         InsertTimeOption opt;
6196
6197         switch (intersected_combo.get_active_row_number ()) {
6198         case 0:
6199                 opt = LeaveIntersected;
6200                 break;
6201         case 1:
6202                 opt = MoveIntersected;
6203                 break;
6204         case 2:
6205                 opt = SplitIntersected;
6206                 break;
6207         }
6208
6209         insert_time (pos, distance, opt, move_glued.get_active(), move_markers.get_active(), move_tempos.get_active());
6210 }
6211
6212 void
6213 Editor::insert_time (nframes64_t pos, nframes64_t frames, InsertTimeOption opt,
6214                      bool ignore_music_glue, bool markers_too, bool tempo_too)
6215 {
6216         bool commit = false;
6217
6218         if (Config->get_edit_mode() == Lock) {
6219                 return;
6220         }
6221
6222         begin_reversible_command (_("insert time"));
6223
6224         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6225                 /* regions */
6226                 boost::shared_ptr<Playlist> pl = (*x)->playlist();
6227
6228                 if (pl) {
6229
6230                         pl->clear_history ();
6231                         pl->clear_owned_history ();
6232
6233                         if (opt == SplitIntersected) {
6234                                 pl->split (pos);
6235                         }
6236
6237                         pl->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6238
6239                         vector<StatefulDiffCommand*> cmds;
6240                         
6241                         pl->rdiff (cmds);
6242                         
6243                         cerr << "Shift generated " << cmds.size() << " sdc's\n";
6244
6245                         for (vector<StatefulDiffCommand*>::iterator c = cmds.begin(); c != cmds.end(); ++c) {
6246                                 _session->add_command (*c);
6247                         }
6248                         
6249                         _session->add_command (new StatefulDiffCommand (pl));
6250                         commit = true;
6251                 }
6252
6253                 /* automation */
6254                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6255                 if (rtav) {
6256                         rtav->route ()->shift (pos, frames);
6257                         commit = true;
6258                 }
6259         }
6260
6261         /* markers */
6262         if (markers_too) {
6263                 bool moved = false;
6264                 XMLNode& before (_session->locations()->get_state());
6265                 Locations::LocationList copy (_session->locations()->list());
6266
6267                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6268
6269                         Locations::LocationList::const_iterator tmp;
6270
6271                         if ((*i)->start() >= pos) {
6272                                 (*i)->set_start ((*i)->start() + frames);
6273                                 if (!(*i)->is_mark()) {
6274                                         (*i)->set_end ((*i)->end() + frames);
6275                                 }
6276                                 moved = true;
6277                         }
6278                 }
6279
6280                 if (moved) {
6281                         XMLNode& after (_session->locations()->get_state());
6282                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6283                 }
6284         }
6285
6286         if (tempo_too) {
6287                 _session->tempo_map().insert_time (pos, frames);
6288         }
6289
6290         if (commit) {
6291                 commit_reversible_command ();
6292         }
6293 }
6294
6295 void
6296 Editor::fit_selected_tracks ()
6297 {
6298         fit_tracks (selection->tracks);
6299 }
6300
6301 void
6302 Editor::fit_tracks (TrackViewList & tracks)
6303 {
6304         if (tracks.empty()) {
6305                 return;
6306         }
6307
6308         uint32_t child_heights = 0;
6309
6310         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6311
6312                 if (!(*t)->marked_for_display()) {
6313                         continue;
6314                 }
6315
6316                 child_heights += (*t)->effective_height() - (*t)->current_height();
6317         }
6318
6319         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / tracks.size());
6320         double first_y_pos = DBL_MAX;
6321
6322         if (h < TimeAxisView::hSmall) {
6323                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6324                 /* too small to be displayed */
6325                 return;
6326         }
6327
6328         undo_visual_stack.push_back (current_visual_state());
6329
6330         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6331
6332         bool prev_was_selected = false;
6333         bool is_selected = tracks.contains (track_views.front());
6334         bool next_is_selected;
6335
6336         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
6337
6338                 TrackViewList::iterator next;
6339
6340                 next = t;
6341                 ++next;
6342
6343                 if (next != track_views.end()) {
6344                         next_is_selected = tracks.contains (*next);
6345                 } else {
6346                         next_is_selected = false;
6347                 }
6348
6349                 if (is_selected) {
6350                         (*t)->set_height (h);
6351                         first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6352                 } else {
6353                         if (prev_was_selected && next_is_selected) {
6354                                 hide_track_in_display (**t);
6355                         }
6356                 }
6357
6358                 prev_was_selected = is_selected;
6359                 is_selected = next_is_selected;
6360         }
6361
6362         /*
6363            set the controls_layout height now, because waiting for its size
6364            request signal handler will cause the vertical adjustment setting to fail
6365         */
6366
6367         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6368         vertical_adjustment.set_value (first_y_pos);
6369
6370         redo_visual_stack.push_back (current_visual_state());
6371 }
6372
6373 void
6374 Editor::save_visual_state (uint32_t n)
6375 {
6376         while (visual_states.size() <= n) {
6377                 visual_states.push_back (0);
6378         }
6379
6380         delete visual_states[n];
6381
6382         visual_states[n] = current_visual_state (true);
6383         gdk_beep ();
6384 }
6385
6386 void
6387 Editor::goto_visual_state (uint32_t n)
6388 {
6389         if (visual_states.size() <= n) {
6390                 return;
6391         }
6392
6393         if (visual_states[n] == 0) {
6394                 return;
6395         }
6396
6397         use_visual_state (*visual_states[n]);
6398 }
6399
6400 void
6401 Editor::start_visual_state_op (uint32_t n)
6402 {
6403         if (visual_state_op_connection.empty()) {
6404                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6405         }
6406 }
6407
6408 void
6409 Editor::cancel_visual_state_op (uint32_t n)
6410 {
6411         if (!visual_state_op_connection.empty()) {
6412                 visual_state_op_connection.disconnect();
6413                 goto_visual_state (n);
6414         }  else {
6415                 //we land here if called from the menu OR if end_visual_state_op has been called
6416                 //so check if we are already in visual state n
6417                 // XXX not yet checking it at all, but redoing does not hurt
6418                 goto_visual_state (n);
6419         }
6420 }
6421
6422 bool
6423 Editor::end_visual_state_op (uint32_t n)
6424 {
6425         visual_state_op_connection.disconnect();
6426         save_visual_state (n);
6427
6428         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6429         char buf[32];
6430         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6431         pup->set_text (buf);
6432         pup->touch();
6433
6434         return false; // do not call again
6435 }
6436