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