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