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