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