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