Fix crash on "Consolidate Range" on MIDI tracks (#4226).
[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 (rs.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 (!r) {
3372                         continue;
3373                 }
3374
3375                 if (replace) {
3376                         list<AudioRange> ranges;
3377                         ranges.push_back (AudioRange (start, start+cnt, 0));
3378                         playlist->cut (ranges); // discard result
3379                         playlist->add_region (r, start);
3380                 }
3381
3382                 vector<Command*> cmds;
3383                 playlist->rdiff (cmds);
3384                 _session->add_commands (cmds);
3385
3386                 _session->add_command (new StatefulDiffCommand (playlist));
3387         }
3388
3389         commit_reversible_command ();
3390 }
3391
3392 /** Delete selected regions, automation points or a time range */
3393 void
3394 Editor::delete_ ()
3395 {
3396         cut_copy (Delete);
3397 }
3398
3399 /** Cut selected regions, automation points or a time range */
3400 void
3401 Editor::cut ()
3402 {
3403         cut_copy (Cut);
3404 }
3405
3406 /** Copy selected regions, automation points or a time range */
3407 void
3408 Editor::copy ()
3409 {
3410         cut_copy (Copy);
3411 }
3412
3413
3414 /** @return true if a Cut, Copy or Clear is possible */
3415 bool
3416 Editor::can_cut_copy () const
3417 {
3418         switch (current_mouse_mode()) {
3419
3420         case MouseObject:
3421                 if (!selection->regions.empty() || !selection->points.empty()) {
3422                         return true;
3423                 }
3424                 break;
3425
3426         case MouseRange:
3427                 if (!selection->time.empty()) {
3428                         return true;
3429                 }
3430                 break;
3431
3432         default:
3433                 break;
3434         }
3435
3436         return false;
3437 }
3438
3439
3440 /** Cut, copy or clear selected regions, automation points or a time range.
3441  * @param op Operation (Cut, Copy or Clear)
3442  */
3443 void
3444 Editor::cut_copy (CutCopyOp op)
3445 {
3446         /* only cancel selection if cut/copy is successful.*/
3447
3448         string opname;
3449
3450         switch (op) {
3451         case Delete:
3452                 opname = _("delete");
3453                 break;
3454         case Cut:
3455                 opname = _("cut");
3456                 break;
3457         case Copy:
3458                 opname = _("copy");
3459                 break;
3460         case Clear:
3461                 opname = _("clear");
3462                 break;
3463         }
3464
3465         /* if we're deleting something, and the mouse is still pressed,
3466            the thing we started a drag for will be gone when we release
3467            the mouse button(s). avoid this. see part 2 at the end of
3468            this function.
3469         */
3470
3471         if (op == Delete || op == Cut || op == Clear) {
3472                 if (_drags->active ()) {
3473                         _drags->abort ();
3474                 }
3475         }
3476
3477         cut_buffer->clear ();
3478
3479         if (entered_marker) {
3480
3481                 /* cut/delete op while pointing at a marker */
3482
3483                 bool ignored;
3484                 Location* loc = find_location_from_marker (entered_marker, ignored);
3485
3486                 if (_session && loc) {
3487                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3488                 }
3489
3490                 _drags->abort ();
3491                 return;
3492         }
3493
3494         if (internal_editing()) {
3495
3496                 switch (current_mouse_mode()) {
3497                 case MouseObject:
3498                 case MouseRange:
3499                         cut_copy_midi (op);
3500                         break;
3501                 default:
3502                         break;
3503                 }
3504
3505         } else {
3506
3507                 RegionSelection rs;
3508
3509                 /* we only want to cut regions if some are selected */
3510
3511                 if (!selection->regions.empty()) {
3512                         rs = selection->regions;
3513                 }
3514
3515                 switch (current_mouse_mode()) {
3516                 case MouseObject:
3517                         if (!rs.empty() || !selection->points.empty()) {
3518
3519                                 begin_reversible_command (opname + _(" objects"));
3520
3521                                 if (!rs.empty()) {
3522                                         cut_copy_regions (op, rs);
3523
3524                                         if (op == Cut || op == Delete) {
3525                                                 selection->clear_regions ();
3526                                         }
3527                                 }
3528
3529                                 if (!selection->points.empty()) {
3530                                         cut_copy_points (op);
3531
3532                                         if (op == Cut || op == Delete) {
3533                                                 selection->clear_points ();
3534                                         }
3535                                 }
3536                                 commit_reversible_command ();
3537                                 break; // terminate case statement here
3538                         }
3539                         if (!selection->time.empty()) {
3540                                 /* don't cause suprises */
3541                                 break;
3542                         }
3543                         // fall thru if there was nothing selected
3544
3545                 case MouseRange:
3546                         if (selection->time.empty()) {
3547                                 framepos_t start, end;
3548                                 if (!get_edit_op_range (start, end)) {
3549                                         return;
3550                                 }
3551                                 selection->set (start, end);
3552                         }
3553
3554                         begin_reversible_command (opname + _(" range"));
3555                         cut_copy_ranges (op);
3556                         commit_reversible_command ();
3557
3558                         if (op == Cut || op == Delete) {
3559                                 selection->clear_time ();
3560                         }
3561
3562                         break;
3563
3564                 default:
3565                         break;
3566                 }
3567         }
3568
3569         if (op == Delete || op == Cut || op == Clear) {
3570                 _drags->abort ();
3571         }
3572 }
3573
3574 /** Cut, copy or clear selected automation points.
3575  * @param op Operation (Cut, Copy or Clear)
3576  */
3577 void
3578 Editor::cut_copy_points (CutCopyOp op)
3579 {
3580         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3581
3582                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3583                 _last_cut_copy_source_track = atv;
3584
3585                 if (atv) {
3586                         atv->cut_copy_clear_objects (selection->points, op);
3587                 }
3588         }
3589 }
3590
3591 /** Cut, copy or clear selected automation points.
3592  * @param op Operation (Cut, Copy or Clear)
3593  */
3594 void
3595 Editor::cut_copy_midi (CutCopyOp op)
3596 {
3597         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3598                 MidiRegionView* mrv = *i;
3599                 mrv->cut_copy_clear (op);
3600         }
3601 }
3602
3603
3604
3605 struct lt_playlist {
3606     bool operator () (const PlaylistState& a, const PlaylistState& b) {
3607             return a.playlist < b.playlist;
3608     }
3609 };
3610
3611 struct PlaylistMapping {
3612     TimeAxisView* tv;
3613     boost::shared_ptr<Playlist> pl;
3614
3615     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3616 };
3617
3618 /** Remove `clicked_regionview' */
3619 void
3620 Editor::remove_clicked_region ()
3621 {
3622         if (clicked_routeview == 0 || clicked_regionview == 0) {
3623                 return;
3624         }
3625
3626         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3627
3628         begin_reversible_command (_("remove region"));
3629         playlist->clear_changes ();
3630         playlist->remove_region (clicked_regionview->region());
3631         _session->add_command(new StatefulDiffCommand (playlist));
3632         commit_reversible_command ();
3633 }
3634
3635
3636 /** Remove the selected regions */
3637 void
3638 Editor::remove_selected_regions ()
3639 {
3640         RegionSelection rs = get_regions_from_selection_and_entered ();
3641
3642         if (!_session || rs.empty()) {
3643                 return;
3644         }
3645
3646         begin_reversible_command (_("remove region"));
3647
3648         list<boost::shared_ptr<Region> > regions_to_remove;
3649
3650         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3651                 // we can't just remove the region(s) in this loop because
3652                 // this removes them from the RegionSelection, and they thus
3653                 // disappear from underneath the iterator, and the ++i above
3654                 // SEGVs in a puzzling fashion.
3655
3656                 // so, first iterate over the regions to be removed from rs and
3657                 // add them to the regions_to_remove list, and then
3658                 // iterate over the list to actually remove them.
3659
3660                 regions_to_remove.push_back ((*i)->region());
3661         }
3662
3663         vector<boost::shared_ptr<Playlist> > playlists;
3664
3665         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
3666
3667                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
3668
3669                 if (!playlist) {
3670                         // is this check necessary?
3671                         continue;
3672                 }
3673
3674                 vector<boost::shared_ptr<Playlist> >::iterator i;
3675
3676                 //only prep history if this is a new playlist.
3677                 for (i = playlists.begin(); i != playlists.end(); ++i) {
3678                         if ((*i) == playlist) {
3679                                 break;
3680                         }
3681                 }
3682
3683                 if (i == playlists.end()) {
3684
3685                         playlist->clear_changes ();
3686                         playlist->freeze ();
3687
3688                         playlists.push_back (playlist);
3689                 }
3690
3691                 playlist->remove_region (*rl);
3692         }
3693
3694         vector<boost::shared_ptr<Playlist> >::iterator pl;
3695
3696         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
3697                 (*pl)->thaw ();
3698                 _session->add_command(new StatefulDiffCommand (*pl));
3699         }
3700
3701         commit_reversible_command ();
3702 }
3703
3704 /** Cut, copy or clear selected regions.
3705  * @param op Operation (Cut, Copy or Clear)
3706  */
3707 void
3708 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
3709 {
3710         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
3711            a map when we want ordered access to both elements. i think.
3712         */
3713
3714         vector<PlaylistMapping> pmap;
3715
3716         framepos_t first_position = max_framepos;
3717
3718         typedef set<boost::shared_ptr<Playlist> > FreezeList;
3719         FreezeList freezelist;
3720
3721         /* get ordering correct before we cut/copy */
3722
3723         rs.sort_by_position_and_track ();
3724
3725         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3726
3727                 first_position = min ((framepos_t) (*x)->region()->position(), first_position);
3728
3729                 if (op == Cut || op == Clear || op == Delete) {
3730                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3731
3732                         if (pl) {
3733                                 FreezeList::iterator fl;
3734
3735                                 // only take state if this is a new playlist.
3736                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
3737                                         if ((*fl) == pl) {
3738                                                 break;
3739                                         }
3740                                 }
3741
3742                                 if (fl == freezelist.end()) {
3743                                         pl->clear_changes();
3744                                         pl->freeze ();
3745                                         freezelist.insert (pl);
3746                                 }
3747                         }
3748                 }
3749
3750                 TimeAxisView* tv = &(*x)->get_time_axis_view();
3751                 vector<PlaylistMapping>::iterator z;
3752
3753                 for (z = pmap.begin(); z != pmap.end(); ++z) {
3754                         if ((*z).tv == tv) {
3755                                 break;
3756                         }
3757                 }
3758
3759                 if (z == pmap.end()) {
3760                         pmap.push_back (PlaylistMapping (tv));
3761                 }
3762         }
3763
3764         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
3765
3766                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3767
3768                 if (!pl) {
3769                         /* region not yet associated with a playlist (e.g. unfinished
3770                            capture pass.
3771                         */
3772                         ++x;
3773                         continue;
3774                 }
3775
3776                 TimeAxisView& tv = (*x)->get_time_axis_view();
3777                 boost::shared_ptr<Playlist> npl;
3778                 RegionSelection::iterator tmp;
3779
3780                 tmp = x;
3781                 ++tmp;
3782
3783                 if (op != Delete) {
3784
3785                         vector<PlaylistMapping>::iterator z;
3786                         
3787                         for (z = pmap.begin(); z != pmap.end(); ++z) {
3788                                 if ((*z).tv == &tv) {
3789                                         break;
3790                                 }
3791                         }
3792                         
3793                         assert (z != pmap.end());
3794                         
3795                         if (!(*z).pl) {
3796                                 npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
3797                                 npl->freeze();
3798                                 (*z).pl = npl;
3799                         } else {
3800                                 npl = (*z).pl;
3801                         }
3802                 }
3803
3804                 boost::shared_ptr<Region> r = (*x)->region();
3805                 boost::shared_ptr<Region> _xx;
3806
3807                 assert (r != 0);
3808
3809                 switch (op) {
3810                 case Delete:
3811                         pl->remove_region (r);
3812                         break;
3813                         
3814                 case Cut:
3815                         _xx = RegionFactory::create (r);
3816                         npl->add_region (_xx, r->position() - first_position);
3817                         pl->remove_region (r);
3818                         break;
3819
3820                 case Copy:
3821                         /* copy region before adding, so we're not putting same object into two different playlists */
3822                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
3823                         break;
3824
3825                 case Clear:
3826                         pl->remove_region (r);  
3827                         break;
3828                 }
3829
3830                 x = tmp;
3831         }
3832
3833         if (op != Delete) {
3834
3835                 list<boost::shared_ptr<Playlist> > foo;
3836                 
3837                 /* the pmap is in the same order as the tracks in which selected regions occured */
3838                 
3839                 for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
3840                         if ((*i).pl) {
3841                                 (*i).pl->thaw();
3842                                 foo.push_back ((*i).pl);
3843                         }
3844                 }
3845                 
3846                 if (!foo.empty()) {
3847                         cut_buffer->set (foo);
3848                 }
3849                 
3850                 if (pmap.empty()) {
3851                         _last_cut_copy_source_track = 0;
3852                 } else {
3853                         _last_cut_copy_source_track = pmap.front().tv;
3854                 }
3855         }
3856
3857         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
3858                 (*pl)->thaw ();
3859                 _session->add_command (new StatefulDiffCommand (*pl));
3860         }
3861 }
3862
3863 void
3864 Editor::cut_copy_ranges (CutCopyOp op)
3865 {
3866         TrackViewList* ts;
3867         TrackViewList entered;
3868
3869         /* Sort the track selection now, so that it if is used, the playlists
3870            selected by the calls below to cut_copy_clear are in the order that
3871            their tracks appear in the editor.  This makes things like paste
3872            of ranges work properly.
3873         */
3874         sort_track_selection (&selection->tracks);
3875
3876         if (selection->tracks.empty()) {
3877                 if (!entered_track) {
3878                         return;
3879                 }
3880                 entered.push_back (entered_track);
3881                 ts = &entered;
3882         } else {
3883                 ts = &selection->tracks;
3884         }
3885
3886         for (TrackSelection::iterator i = ts->begin(); i != ts->end(); ++i) {
3887                 (*i)->cut_copy_clear (*selection, op);
3888         }
3889 }
3890
3891 void
3892 Editor::paste (float times)
3893 {
3894         DEBUG_TRACE (DEBUG::CutNPaste, "paste to preferred edit pos\n");
3895         paste_internal (get_preferred_edit_position(), times);
3896 }
3897
3898 void
3899 Editor::mouse_paste ()
3900 {
3901         framepos_t where;
3902         bool ignored;
3903
3904         if (!mouse_frame (where, ignored)) {
3905                 return;
3906         }
3907
3908         snap_to (where);
3909         paste_internal (where, 1);
3910 }
3911
3912 void
3913 Editor::paste_internal (framepos_t position, float times)
3914 {
3915         DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("apparent paste position is %1\n", position));
3916
3917         if (internal_editing()) {
3918                 if (cut_buffer->midi_notes.empty()) {
3919                         return;
3920                 }
3921         } else {
3922                 if (cut_buffer->empty()) {
3923                         return;
3924                 }
3925         }
3926
3927         if (position == max_framepos) {
3928                 position = get_preferred_edit_position();
3929                 DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("preferred edit position is %1\n", position));
3930         }
3931
3932         TrackViewList ts;
3933         TrackViewList::iterator i;
3934         size_t nth;
3935
3936         /* get everything in the correct order */
3937
3938         if (!selection->tracks.empty()) {
3939                 /* there are some selected tracks, so paste to them */
3940                 sort_track_selection ();
3941                 ts = selection->tracks;
3942         } else if (_last_cut_copy_source_track) {
3943                 /* otherwise paste to the track that the cut/copy came from;
3944                    see discussion in mantis #3333.
3945                 */
3946                 ts.push_back (_last_cut_copy_source_track);
3947         }
3948
3949         if (internal_editing ()) {
3950
3951                 /* undo/redo is handled by individual tracks/regions */
3952
3953                 for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
3954
3955                         RegionSelection rs;
3956                         RegionSelection::iterator r;
3957                         MidiNoteSelection::iterator cb;
3958
3959                         get_regions_at (rs, position, ts);
3960
3961                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
3962                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
3963                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
3964                                 if (mrv) {
3965                                         mrv->paste (position, times, **cb);
3966                                         ++cb;
3967                                 }
3968                         }
3969                 }
3970
3971         } else {
3972
3973                 /* we do redo (do you do voodoo?) */
3974
3975                 begin_reversible_command (Operations::paste);
3976
3977                 for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
3978                         (*i)->paste (position, times, *cut_buffer, nth);
3979                 }
3980
3981                 commit_reversible_command ();
3982         }
3983 }
3984
3985 void
3986 Editor::duplicate_some_regions (RegionSelection& regions, float times)
3987 {
3988         boost::shared_ptr<Playlist> playlist;
3989         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
3990         RegionSelection foo;
3991
3992         framepos_t const start_frame = regions.start ();
3993         framepos_t const end_frame = regions.end_frame ();
3994
3995         begin_reversible_command (Operations::duplicate_region);
3996
3997         selection->clear_regions ();
3998
3999         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4000
4001                 boost::shared_ptr<Region> r ((*i)->region());
4002
4003                 TimeAxisView& tv = (*i)->get_time_axis_view();
4004                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4005                 latest_regionviews.clear ();
4006                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4007
4008                 playlist = (*i)->region()->playlist();
4009                 playlist->clear_changes ();
4010                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame), times);
4011                 _session->add_command(new StatefulDiffCommand (playlist));
4012
4013                 c.disconnect ();
4014
4015                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4016         }
4017
4018         commit_reversible_command ();
4019
4020         if (!foo.empty()) {
4021                 selection->set (foo);
4022         }
4023 }
4024
4025 void
4026 Editor::duplicate_selection (float times)
4027 {
4028         if (selection->time.empty() || selection->tracks.empty()) {
4029                 return;
4030         }
4031
4032         boost::shared_ptr<Playlist> playlist;
4033         vector<boost::shared_ptr<Region> > new_regions;
4034         vector<boost::shared_ptr<Region> >::iterator ri;
4035
4036         create_region_from_selection (new_regions);
4037
4038         if (new_regions.empty()) {
4039                 return;
4040         }
4041
4042         begin_reversible_command (_("duplicate selection"));
4043
4044         ri = new_regions.begin();
4045
4046         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4047                 if ((playlist = (*i)->playlist()) == 0) {
4048                         continue;
4049                 }
4050                 playlist->clear_changes ();
4051                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4052                 _session->add_command (new StatefulDiffCommand (playlist));
4053
4054                 ++ri;
4055                 if (ri == new_regions.end()) {
4056                         --ri;
4057                 }
4058         }
4059
4060         commit_reversible_command ();
4061 }
4062
4063 void
4064 Editor::reset_point_selection ()
4065 {
4066         /* reset all selected points to the relevant default value */
4067
4068         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4069
4070                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4071
4072                 if (atv) {
4073                         atv->reset_objects (selection->points);
4074                 }
4075         }
4076 }
4077
4078 void
4079 Editor::center_playhead ()
4080 {
4081         float page = _canvas_width * frames_per_unit;
4082         center_screen_internal (playhead_cursor->current_frame, page);
4083 }
4084
4085 void
4086 Editor::center_edit_point ()
4087 {
4088         float page = _canvas_width * frames_per_unit;
4089         center_screen_internal (get_preferred_edit_position(), page);
4090 }
4091
4092 /** Caller must begin and commit a reversible command */
4093 void
4094 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4095 {
4096         playlist->clear_changes ();
4097         playlist->clear ();
4098         _session->add_command (new StatefulDiffCommand (playlist));
4099 }
4100
4101 void
4102 Editor::nudge_track (bool use_edit, bool forwards)
4103 {
4104         boost::shared_ptr<Playlist> playlist;
4105         framepos_t distance;
4106         framepos_t next_distance;
4107         framepos_t start;
4108
4109         if (use_edit) {
4110                 start = get_preferred_edit_position();
4111         } else {
4112                 start = 0;
4113         }
4114
4115         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4116                 return;
4117         }
4118
4119         if (selection->tracks.empty()) {
4120                 return;
4121         }
4122
4123         begin_reversible_command (_("nudge track"));
4124
4125         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4126
4127                 if ((playlist = (*i)->playlist()) == 0) {
4128                         continue;
4129                 }
4130
4131                 playlist->clear_changes ();
4132                 playlist->clear_owned_changes ();
4133
4134                 playlist->nudge_after (start, distance, forwards);
4135
4136                 vector<Command*> cmds;
4137
4138                 playlist->rdiff (cmds);
4139                 _session->add_commands (cmds);
4140
4141                 _session->add_command (new StatefulDiffCommand (playlist));
4142         }
4143
4144         commit_reversible_command ();
4145 }
4146
4147 void
4148 Editor::remove_last_capture ()
4149 {
4150         vector<string> choices;
4151         string prompt;
4152
4153         if (!_session) {
4154                 return;
4155         }
4156
4157         if (Config->get_verify_remove_last_capture()) {
4158                 prompt  = _("Do you really want to destroy the last capture?"
4159                             "\n(This is destructive and cannot be undone)");
4160
4161                 choices.push_back (_("No, do nothing."));
4162                 choices.push_back (_("Yes, destroy it."));
4163
4164                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4165
4166                 if (prompter.run () == 1) {
4167                         _session->remove_last_capture ();
4168                         _regions->redisplay ();
4169                 }
4170
4171         } else {
4172                 _session->remove_last_capture();
4173                 _regions->redisplay ();
4174         }
4175 }
4176
4177 void
4178 Editor::normalize_region ()
4179 {
4180         if (!_session) {
4181                 return;
4182         }
4183
4184         RegionSelection rs = get_regions_from_selection_and_entered ();
4185
4186         if (rs.empty()) {
4187                 return;
4188         }
4189
4190         NormalizeDialog dialog (rs.size() > 1);
4191
4192         if (dialog.run () == RESPONSE_CANCEL) {
4193                 return;
4194         }
4195
4196         set_canvas_cursor (_cursors->wait);
4197         gdk_flush ();
4198
4199         /* XXX: should really only count audio regions here */
4200         int const regions = rs.size ();
4201
4202         /* Make a list of the selected audio regions' maximum amplitudes, and also
4203            obtain the maximum amplitude of them all.
4204         */
4205         list<double> max_amps;
4206         double max_amp = 0;
4207         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
4208                 AudioRegionView const * arv = dynamic_cast<AudioRegionView const *> (*i);
4209                 if (arv) {
4210                         dialog.descend (1.0 / regions);
4211                         double const a = arv->audio_region()->maximum_amplitude (&dialog);
4212
4213                         if (a == -1) {
4214                                 /* the user cancelled the operation */
4215                                 set_canvas_cursor (current_canvas_cursor);
4216                                 return;
4217                         }
4218
4219                         max_amps.push_back (a);
4220                         max_amp = max (max_amp, a);
4221                         dialog.ascend ();
4222                 }
4223         }
4224
4225         begin_reversible_command (_("normalize"));
4226
4227         list<double>::const_iterator a = max_amps.begin ();
4228
4229         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4230                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4231                 if (!arv) {
4232                         continue;
4233                 }
4234
4235                 arv->region()->clear_changes ();
4236
4237                 double const amp = dialog.normalize_individually() ? *a : max_amp;
4238
4239                 arv->audio_region()->normalize (amp, dialog.target ());
4240                 _session->add_command (new StatefulDiffCommand (arv->region()));
4241
4242                 ++a;
4243         }
4244
4245         commit_reversible_command ();
4246         set_canvas_cursor (current_canvas_cursor);
4247 }
4248
4249
4250 void
4251 Editor::reset_region_scale_amplitude ()
4252 {
4253         if (!_session) {
4254                 return;
4255         }
4256
4257         RegionSelection rs = get_regions_from_selection_and_entered ();
4258
4259         if (rs.empty()) {
4260                 return;
4261         }
4262
4263         begin_reversible_command ("reset gain");
4264
4265         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4266                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4267                 if (!arv)
4268                         continue;
4269                 arv->region()->clear_changes ();
4270                 arv->audio_region()->set_scale_amplitude (1.0f);
4271                 _session->add_command (new StatefulDiffCommand (arv->region()));
4272         }
4273
4274         commit_reversible_command ();
4275 }
4276
4277 void
4278 Editor::adjust_region_gain (bool up)
4279 {
4280         RegionSelection rs = get_regions_from_selection_and_entered ();
4281
4282         if (!_session || rs.empty()) {
4283                 return;
4284         }
4285
4286         begin_reversible_command ("adjust region gain");
4287
4288         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4289                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4290                 if (!arv) {
4291                         continue;
4292                 }
4293
4294                 arv->region()->clear_changes ();
4295
4296                 double dB = accurate_coefficient_to_dB (arv->audio_region()->scale_amplitude ());
4297
4298                 if (up) {
4299                         dB += 1;
4300                 } else {
4301                         dB -= 1;
4302                 }
4303
4304                 arv->audio_region()->set_scale_amplitude (dB_to_coefficient (dB));
4305                 _session->add_command (new StatefulDiffCommand (arv->region()));
4306         }
4307
4308         commit_reversible_command ();
4309 }
4310
4311
4312 void
4313 Editor::reverse_region ()
4314 {
4315         if (!_session) {
4316                 return;
4317         }
4318
4319         Reverse rev (*_session);
4320         apply_filter (rev, _("reverse regions"));
4321 }
4322
4323 void
4324 Editor::strip_region_silence ()
4325 {
4326         if (!_session) {
4327                 return;
4328         }
4329
4330         RegionSelection rs = get_regions_from_selection_and_entered ();
4331
4332         if (rs.empty()) {
4333                 return;
4334         }
4335
4336         std::list<RegionView*> audio_only;
4337
4338         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4339                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4340                 if (arv) {
4341                         audio_only.push_back (arv);
4342                 }
4343         }
4344
4345         StripSilenceDialog d (_session, audio_only);
4346         int const r = d.run ();
4347
4348         d.drop_rects ();
4349
4350         if (r == Gtk::RESPONSE_OK) {
4351                 ARDOUR::AudioIntervalMap silences;
4352                 d.silences (silences);
4353                 StripSilence s (*_session, silences, d.fade_length());
4354                 apply_filter (s, _("strip silence"), &d);
4355         }
4356 }
4357
4358 Command*
4359 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4360 {
4361         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4362         mrv.selection_as_notelist (selected, true);
4363
4364         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4365         v.push_back (selected);
4366
4367         framepos_t pos_frames = mrv.midi_region()->position();
4368         double     pos_beats  = _session->tempo_map().framewalk_to_beats(0, pos_frames);
4369
4370         return op (mrv.midi_region()->model(), pos_beats, v);
4371 }
4372
4373 void
4374 Editor::apply_midi_note_edit_op (MidiOperator& op)
4375 {
4376         Command* cmd;
4377
4378         RegionSelection rs = get_regions_from_selection_and_entered ();
4379
4380         if (rs.empty()) {
4381                 return;
4382         }
4383
4384         begin_reversible_command (op.name ());
4385
4386         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4387                 RegionSelection::iterator tmp = r;
4388                 ++tmp;
4389
4390                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4391
4392                 if (mrv) {
4393                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4394                         if (cmd) {
4395                                 (*cmd)();
4396                                 _session->add_command (cmd);
4397                         }
4398                 }
4399
4400                 r = tmp;
4401         }
4402
4403         commit_reversible_command ();
4404 }
4405
4406 void
4407 Editor::fork_region ()
4408 {
4409         RegionSelection rs = get_regions_from_selection_and_entered ();
4410
4411         if (rs.empty()) {
4412                 return;
4413         }
4414
4415         begin_reversible_command (_("Fork Region(s)"));
4416
4417         set_canvas_cursor (_cursors->wait);
4418         gdk_flush ();
4419
4420         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4421                 RegionSelection::iterator tmp = r;
4422                 ++tmp;
4423
4424                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4425
4426                 if (mrv) {
4427                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4428                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4429
4430                         playlist->clear_changes ();
4431                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4432                         _session->add_command(new StatefulDiffCommand (playlist));
4433                 }
4434
4435                 r = tmp;
4436         }
4437
4438         commit_reversible_command ();
4439
4440         set_canvas_cursor (current_canvas_cursor);
4441 }
4442
4443 void
4444 Editor::quantize_region ()
4445 {
4446         int selected_midi_region_cnt = 0;
4447
4448         if (!_session) {
4449                 return;
4450         }
4451
4452         RegionSelection rs = get_regions_from_selection_and_entered ();
4453
4454         if (rs.empty()) {
4455                 return;
4456         }
4457
4458         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4459                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4460                 if (mrv) {
4461                         selected_midi_region_cnt++;
4462                 }
4463         }
4464
4465         if (selected_midi_region_cnt == 0) {
4466                 return;
4467         }
4468
4469         QuantizeDialog* qd = new QuantizeDialog (*this);
4470
4471         qd->present ();
4472         const int r = qd->run ();
4473         qd->hide ();
4474
4475         if (r == Gtk::RESPONSE_OK) {
4476                 Quantize quant (*_session, Plain,
4477                                 qd->snap_start(), qd->snap_end(),
4478                                 qd->start_grid_size(), qd->end_grid_size(),
4479                                 qd->strength(), qd->swing(), qd->threshold());
4480
4481                 apply_midi_note_edit_op (quant);
4482         }
4483 }
4484
4485 void
4486 Editor::insert_patch_change ()
4487 {
4488         RegionSelection rs = get_regions_from_selection_and_entered ();
4489         if (rs.empty ()) {
4490                 return;
4491         }
4492
4493         framepos_t const p = get_preferred_edit_position (false);
4494
4495         Evoral::PatchChange<Evoral::MusicalTime> empty (0, 0, 0, 0);
4496         PatchChangeDialog d (0, _session, empty, Gtk::Stock::ADD);
4497
4498         if (d.run() == RESPONSE_CANCEL) {
4499                 return;
4500         }
4501
4502         for (RegionSelection::iterator i = rs.begin (); i != rs.end(); ++i) {
4503                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*i);
4504                 if (mrv) {
4505                         if (p >= mrv->region()->first_frame() && p <= mrv->region()->last_frame()) {
4506                                 mrv->add_patch_change (p - mrv->region()->position(), d.patch ());
4507                         }
4508                 }
4509         }
4510 }
4511
4512 void
4513 Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress)
4514 {
4515         RegionSelection rs = get_regions_from_selection_and_entered ();
4516
4517         if (rs.empty()) {
4518                 return;
4519         }
4520
4521         begin_reversible_command (command);
4522
4523         set_canvas_cursor (_cursors->wait);
4524         gdk_flush ();
4525
4526         int n = 0;
4527         int const N = rs.size ();
4528
4529         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4530                 RegionSelection::iterator tmp = r;
4531                 ++tmp;
4532
4533                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4534                 if (arv) {
4535                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4536
4537                         if (progress) {
4538                                 progress->descend (1.0 / N);
4539                         }
4540
4541                         if (arv->audio_region()->apply (filter, progress) == 0) {
4542
4543                                 playlist->clear_changes ();
4544
4545                                 if (filter.results.empty ()) {
4546
4547                                         /* no regions returned; remove the old one */
4548                                         playlist->remove_region (arv->region ());
4549
4550                                 } else {
4551
4552                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4553
4554                                         /* first region replaces the old one */
4555                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4556                                         ++res;
4557
4558                                         /* add the rest */
4559                                         while (res != filter.results.end()) {
4560                                                 playlist->add_region (*res, (*res)->position());
4561                                                 ++res;
4562                                         }
4563
4564                                 }
4565
4566                                 _session->add_command(new StatefulDiffCommand (playlist));
4567                         } else {
4568                                 goto out;
4569                         }
4570
4571                         if (progress) {
4572                                 progress->ascend ();
4573                         }
4574                 }
4575
4576                 r = tmp;
4577                 ++n;
4578         }
4579
4580         commit_reversible_command ();
4581
4582   out:
4583         set_canvas_cursor (current_canvas_cursor);
4584 }
4585
4586 void
4587 Editor::external_edit_region ()
4588 {
4589         /* more to come */
4590 }
4591
4592 void
4593 Editor::reset_region_gain_envelopes ()
4594 {
4595         RegionSelection rs = get_regions_from_selection_and_entered ();
4596
4597         if (!_session || rs.empty()) {
4598                 return;
4599         }
4600
4601         _session->begin_reversible_command (_("reset region gain"));
4602
4603         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4604                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4605                 if (arv) {
4606                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4607                         XMLNode& before (alist->get_state());
4608
4609                         arv->audio_region()->set_default_envelope ();
4610                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4611                 }
4612         }
4613
4614         _session->commit_reversible_command ();
4615 }
4616
4617 void
4618 Editor::toggle_gain_envelope_visibility ()
4619 {
4620         if (_ignore_region_action) {
4621                 return;
4622         }
4623
4624         RegionSelection rs = get_regions_from_selection_and_entered ();
4625
4626         if (!_session || rs.empty()) {
4627                 return;
4628         }
4629
4630         _session->begin_reversible_command (_("region gain envelope visible"));
4631
4632         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4633                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4634                 if (arv) {
4635                         arv->region()->clear_changes ();
4636                         arv->set_envelope_visible (!arv->envelope_visible());
4637                         _session->add_command (new StatefulDiffCommand (arv->region()));
4638                 }
4639         }
4640
4641         _session->commit_reversible_command ();
4642 }
4643
4644 void
4645 Editor::toggle_gain_envelope_active ()
4646 {
4647         if (_ignore_region_action) {
4648                 return;
4649         }
4650
4651         RegionSelection rs = get_regions_from_selection_and_entered ();
4652
4653         if (!_session || rs.empty()) {
4654                 return;
4655         }
4656
4657         _session->begin_reversible_command (_("region gain envelope active"));
4658
4659         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4660                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4661                 if (arv) {
4662                         arv->region()->clear_changes ();
4663                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4664                         _session->add_command (new StatefulDiffCommand (arv->region()));
4665                 }
4666         }
4667
4668         _session->commit_reversible_command ();
4669 }
4670
4671 void
4672 Editor::toggle_region_lock ()
4673 {
4674         if (_ignore_region_action) {
4675                 return;
4676         }
4677
4678         RegionSelection rs = get_regions_from_selection_and_entered ();
4679
4680         if (!_session || rs.empty()) {
4681                 return;
4682         }
4683
4684         _session->begin_reversible_command (_("toggle region lock"));
4685
4686         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4687                 (*i)->region()->clear_changes ();
4688                 (*i)->region()->set_locked (!(*i)->region()->locked());
4689                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4690         }
4691
4692         _session->commit_reversible_command ();
4693 }
4694
4695 void
4696 Editor::toggle_region_lock_style ()
4697 {
4698         if (_ignore_region_action) {
4699                 return;
4700         }
4701
4702         RegionSelection rs = get_regions_from_selection_and_entered ();
4703
4704         if (!_session || rs.empty()) {
4705                 return;
4706         }
4707
4708         _session->begin_reversible_command (_("region lock style"));
4709
4710         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4711                 (*i)->region()->clear_changes ();
4712                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
4713                 (*i)->region()->set_position_lock_style (ns);
4714                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4715         }
4716
4717         _session->commit_reversible_command ();
4718 }
4719
4720 void
4721 Editor::toggle_opaque_region ()
4722 {
4723         if (_ignore_region_action) {
4724                 return;
4725         }
4726
4727         RegionSelection rs = get_regions_from_selection_and_entered ();
4728
4729         if (!_session || rs.empty()) {
4730                 return;
4731         }
4732
4733         _session->begin_reversible_command (_("change region opacity"));
4734
4735         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4736                 (*i)->region()->clear_changes ();
4737                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4738                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4739         }
4740
4741         _session->commit_reversible_command ();
4742 }
4743
4744 void
4745 Editor::toggle_record_enable ()
4746 {
4747         bool new_state = false;
4748         bool first = true;
4749         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4750                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4751                 if (!rtav)
4752                         continue;
4753                 if (!rtav->is_track())
4754                         continue;
4755
4756                 if (first) {
4757                         new_state = !rtav->track()->record_enabled();
4758                         first = false;
4759                 }
4760
4761                 rtav->track()->set_record_enabled (new_state, this);
4762         }
4763 }
4764
4765 void
4766 Editor::toggle_solo ()
4767 {
4768         bool new_state = false;
4769         bool first = true;
4770         boost::shared_ptr<RouteList> rl (new RouteList);
4771
4772         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4773                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4774
4775                 if (!rtav) {
4776                         continue;
4777                 }
4778
4779                 if (first) {
4780                         new_state = !rtav->route()->soloed ();
4781                         first = false;
4782                 }
4783
4784                 rl->push_back (rtav->route());
4785         }
4786
4787         _session->set_solo (rl, new_state, Session::rt_cleanup, true);
4788 }
4789
4790 void
4791 Editor::toggle_mute ()
4792 {
4793         bool new_state = false;
4794         bool first = true;
4795         boost::shared_ptr<RouteList> rl (new RouteList);
4796
4797         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4798                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4799
4800                 if (!rtav) {
4801                         continue;
4802                 }
4803
4804                 if (first) {
4805                         new_state = !rtav->route()->muted();
4806                         first = false;
4807                 }
4808
4809                 rl->push_back (rtav->route());
4810         }
4811
4812         _session->set_mute (rl, new_state, Session::rt_cleanup, true);
4813 }
4814
4815 void
4816 Editor::toggle_solo_isolate ()
4817 {
4818 }
4819
4820 void
4821 Editor::set_fade_length (bool in)
4822 {
4823         RegionSelection rs = get_regions_from_selection_and_entered ();
4824
4825         if (rs.empty()) {
4826                 return;
4827         }
4828
4829         /* we need a region to measure the offset from the start */
4830
4831         RegionView* rv = rs.front ();
4832
4833         framepos_t pos = get_preferred_edit_position();
4834         framepos_t len;
4835         char const * cmd;
4836
4837         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
4838                 /* edit point is outside the relevant region */
4839                 return;
4840         }
4841
4842         if (in) {
4843                 if (pos <= rv->region()->position()) {
4844                         /* can't do it */
4845                         return;
4846                 }
4847                 len = pos - rv->region()->position();
4848                 cmd = _("set fade in length");
4849         } else {
4850                 if (pos >= rv->region()->last_frame()) {
4851                         /* can't do it */
4852                         return;
4853                 }
4854                 len = rv->region()->last_frame() - pos;
4855                 cmd = _("set fade out length");
4856         }
4857
4858         begin_reversible_command (cmd);
4859
4860         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4861                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4862
4863                 if (!tmp) {
4864                         return;
4865                 }
4866
4867                 boost::shared_ptr<AutomationList> alist;
4868                 if (in) {
4869                         alist = tmp->audio_region()->fade_in();
4870                 } else {
4871                         alist = tmp->audio_region()->fade_out();
4872                 }
4873
4874                 XMLNode &before = alist->get_state();
4875
4876                 if (in) {
4877                         tmp->audio_region()->set_fade_in_length (len);
4878                         tmp->audio_region()->set_fade_in_active (true);
4879                 } else {
4880                         tmp->audio_region()->set_fade_out_length (len);
4881                         tmp->audio_region()->set_fade_out_active (true);
4882                 }
4883
4884                 XMLNode &after = alist->get_state();
4885                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
4886         }
4887
4888         commit_reversible_command ();
4889 }
4890
4891 void
4892 Editor::set_fade_in_shape (FadeShape shape)
4893 {
4894         RegionSelection rs = get_regions_from_selection_and_entered ();
4895
4896         if (rs.empty()) {
4897                 return;
4898         }
4899
4900         begin_reversible_command (_("set fade in shape"));
4901
4902         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4903                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4904
4905                 if (!tmp) {
4906                         return;
4907                 }
4908
4909                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
4910                 XMLNode &before = alist->get_state();
4911
4912                 tmp->audio_region()->set_fade_in_shape (shape);
4913
4914                 XMLNode &after = alist->get_state();
4915                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
4916         }
4917
4918         commit_reversible_command ();
4919
4920 }
4921
4922 void
4923 Editor::set_fade_out_shape (FadeShape shape)
4924 {
4925         RegionSelection rs = get_regions_from_selection_and_entered ();
4926
4927         if (rs.empty()) {
4928                 return;
4929         }
4930
4931         begin_reversible_command (_("set fade out shape"));
4932
4933         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4934                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4935
4936                 if (!tmp) {
4937                         return;
4938                 }
4939
4940                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
4941                 XMLNode &before = alist->get_state();
4942
4943                 tmp->audio_region()->set_fade_out_shape (shape);
4944
4945                 XMLNode &after = alist->get_state();
4946                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
4947         }
4948
4949         commit_reversible_command ();
4950 }
4951
4952 void
4953 Editor::set_fade_in_active (bool yn)
4954 {
4955         RegionSelection rs = get_regions_from_selection_and_entered ();
4956
4957         if (rs.empty()) {
4958                 return;
4959         }
4960
4961         begin_reversible_command (_("set fade in active"));
4962
4963         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4964                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4965
4966                 if (!tmp) {
4967                         return;
4968                 }
4969
4970
4971                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
4972
4973                 ar->clear_changes ();
4974                 ar->set_fade_in_active (yn);
4975                 _session->add_command (new StatefulDiffCommand (ar));
4976         }
4977
4978         commit_reversible_command ();
4979 }
4980
4981 void
4982 Editor::set_fade_out_active (bool yn)
4983 {
4984         RegionSelection rs = get_regions_from_selection_and_entered ();
4985
4986         if (rs.empty()) {
4987                 return;
4988         }
4989
4990         begin_reversible_command (_("set fade out active"));
4991
4992         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4993                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4994
4995                 if (!tmp) {
4996                         return;
4997                 }
4998
4999                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5000
5001                 ar->clear_changes ();
5002                 ar->set_fade_out_active (yn);
5003                 _session->add_command(new StatefulDiffCommand (ar));
5004         }
5005
5006         commit_reversible_command ();
5007 }
5008
5009 void
5010 Editor::toggle_region_fades (int dir)
5011 {
5012         boost::shared_ptr<AudioRegion> ar;
5013         bool yn = false;
5014
5015         RegionSelection rs = get_regions_from_selection_and_entered ();
5016
5017         if (rs.empty()) {
5018                 return;
5019         }
5020
5021         RegionSelection::iterator i;
5022         for (i = rs.begin(); i != rs.end(); ++i) {
5023                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5024                         if (dir == -1) {
5025                                 yn = ar->fade_out_active ();
5026                         } else {
5027                                 yn = ar->fade_in_active ();
5028                         }
5029                         break;
5030                 }
5031         }
5032
5033         if (i == rs.end()) {
5034                 return;
5035         }
5036
5037         /* XXX should this undo-able? */
5038
5039         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5040                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5041                         continue;
5042                 }
5043                 if (dir == 1 || dir == 0) {
5044                         ar->set_fade_in_active (!yn);
5045                 }
5046
5047                 if (dir == -1 || dir == 0) {
5048                         ar->set_fade_out_active (!yn);
5049                 }
5050         }
5051 }
5052
5053
5054 /** Update region fade visibility after its configuration has been changed */
5055 void
5056 Editor::update_region_fade_visibility ()
5057 {
5058         bool _fade_visibility = _session->config.get_show_region_fades ();
5059
5060         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5061                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5062                 if (v) {
5063                         if (_fade_visibility) {
5064                                 v->audio_view()->show_all_fades ();
5065                         } else {
5066                                 v->audio_view()->hide_all_fades ();
5067                         }
5068                 }
5069         }
5070 }
5071
5072 /** Update crossfade visibility after its configuration has been changed */
5073 void
5074 Editor::update_xfade_visibility ()
5075 {
5076         _xfade_visibility = _session->config.get_xfades_visible ();
5077
5078         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5079                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5080                 if (v) {
5081                         if (_xfade_visibility) {
5082                                 v->show_all_xfades ();
5083                         } else {
5084                                 v->hide_all_xfades ();
5085                         }
5086                 }
5087         }
5088 }
5089
5090 void
5091 Editor::set_edit_point ()
5092 {
5093         framepos_t where;
5094         bool ignored;
5095
5096         if (!mouse_frame (where, ignored)) {
5097                 return;
5098         }
5099
5100         snap_to (where);
5101
5102         if (selection->markers.empty()) {
5103
5104                 mouse_add_new_marker (where);
5105
5106         } else {
5107                 bool ignored;
5108
5109                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5110
5111                 if (loc) {
5112                         loc->move_to (where);
5113                 }
5114         }
5115 }
5116
5117 void
5118 Editor::set_playhead_cursor ()
5119 {
5120         if (entered_marker) {
5121                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5122         } else {
5123                 framepos_t where;
5124                 bool ignored;
5125
5126                 if (!mouse_frame (where, ignored)) {
5127                         return;
5128                 }
5129
5130                 snap_to (where);
5131
5132                 if (_session) {
5133                         _session->request_locate (where, _session->transport_rolling());
5134                 }
5135         }
5136 }
5137
5138 void
5139 Editor::split_region ()
5140 {
5141         if (((mouse_mode == MouseRange) ||
5142              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) &&
5143             !selection->time.empty()) {
5144                 separate_regions_between (selection->time);
5145                 return;
5146         }
5147
5148         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5149
5150         framepos_t where = get_preferred_edit_position ();
5151
5152         if (rs.empty()) {
5153                 return;
5154         }
5155
5156         split_regions_at (where, rs);
5157 }
5158
5159 void
5160 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5161 {
5162         if (entered_track && mouse_mode == MouseObject) {
5163                 if (!selection->tracks.empty()) {
5164                         if (!selection->selected (entered_track)) {
5165                                 selection->add (entered_track);
5166                         }
5167                 } else {
5168                         /* there is no selection, but this operation requires/prefers selected objects */
5169
5170                         if (op_really_wants_one_track_if_none_are_selected) {
5171                                 selection->set (entered_track);
5172                         }
5173                 }
5174         }
5175 }
5176
5177 struct EditorOrderRouteSorter {
5178     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5179             /* use of ">" forces the correct sort order */
5180             return a->order_key ("editor") < b->order_key ("editor");
5181     }
5182 };
5183
5184 void
5185 Editor::select_next_route()
5186 {
5187         if (selection->tracks.empty()) {
5188                 selection->set (track_views.front());
5189                 return;
5190         }
5191
5192         TimeAxisView* current = selection->tracks.front();
5193
5194         RouteUI *rui;
5195         do {
5196                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5197                         if (*i == current) {
5198                                 ++i;
5199                                 if (i != track_views.end()) {
5200                                         current = (*i);
5201                                 } else {
5202                                         current = (*(track_views.begin()));
5203                                         //selection->set (*(track_views.begin()));
5204                                 }
5205                                 break;
5206                         }
5207                 }
5208                 rui = dynamic_cast<RouteUI *>(current);
5209         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5210
5211         selection->set(current);
5212
5213         ensure_track_visible(current);
5214 }
5215
5216 void
5217 Editor::select_prev_route()
5218 {
5219         if (selection->tracks.empty()) {
5220                 selection->set (track_views.front());
5221                 return;
5222         }
5223
5224         TimeAxisView* current = selection->tracks.front();
5225
5226         RouteUI *rui;
5227         do {
5228                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5229                         if (*i == current) {
5230                                 ++i;
5231                                 if (i != track_views.rend()) {
5232                                         current = (*i);
5233                                 } else {
5234                                         current = *(track_views.rbegin());
5235                                 }
5236                                 break;
5237                         }
5238                 }
5239                 rui = dynamic_cast<RouteUI *>(current);
5240         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5241
5242         selection->set (current);
5243
5244         ensure_track_visible(current);
5245 }
5246
5247 void
5248 Editor::ensure_track_visible(TimeAxisView *track)
5249 {
5250         if (track->hidden())
5251                 return;
5252
5253         double const current_view_min_y = vertical_adjustment.get_value();
5254         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5255
5256         double const track_min_y = track->y_position ();
5257         double const track_max_y = track->y_position () + track->effective_height ();
5258
5259         if (track_min_y >= current_view_min_y &&
5260             track_max_y <= current_view_max_y) {
5261                 return;
5262         }
5263
5264         double new_value;
5265
5266         if (track_min_y < current_view_min_y) {
5267                 // Track is above the current view
5268                 new_value = track_min_y;
5269         } else {
5270                 // Track is below the current view
5271                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5272         }
5273
5274         vertical_adjustment.set_value(new_value);
5275 }
5276
5277 void
5278 Editor::set_loop_from_selection (bool play)
5279 {
5280         if (_session == 0 || selection->time.empty()) {
5281                 return;
5282         }
5283
5284         framepos_t start = selection->time[clicked_selection].start;
5285         framepos_t end = selection->time[clicked_selection].end;
5286
5287         set_loop_range (start, end,  _("set loop range from selection"));
5288
5289         if (play) {
5290                 _session->request_play_loop (true);
5291                 _session->request_locate (start, true);
5292         }
5293 }
5294
5295 void
5296 Editor::set_loop_from_edit_range (bool play)
5297 {
5298         if (_session == 0) {
5299                 return;
5300         }
5301
5302         framepos_t start;
5303         framepos_t end;
5304
5305         if (!get_edit_op_range (start, end)) {
5306                 return;
5307         }
5308
5309         set_loop_range (start, end,  _("set loop range from edit range"));
5310
5311         if (play) {
5312                 _session->request_play_loop (true);
5313                 _session->request_locate (start, true);
5314         }
5315 }
5316
5317 void
5318 Editor::set_loop_from_region (bool play)
5319 {
5320         framepos_t start = max_framepos;
5321         framepos_t end = 0;
5322
5323         RegionSelection rs = get_regions_from_selection_and_entered ();
5324
5325         if (rs.empty()) {
5326                 return;
5327         }
5328
5329         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5330                 if ((*i)->region()->position() < start) {
5331                         start = (*i)->region()->position();
5332                 }
5333                 if ((*i)->region()->last_frame() + 1 > end) {
5334                         end = (*i)->region()->last_frame() + 1;
5335                 }
5336         }
5337
5338         set_loop_range (start, end, _("set loop range from region"));
5339
5340         if (play) {
5341                 _session->request_play_loop (true);
5342                 _session->request_locate (start, true);
5343         }
5344 }
5345
5346 void
5347 Editor::set_punch_from_selection ()
5348 {
5349         if (_session == 0 || selection->time.empty()) {
5350                 return;
5351         }
5352
5353         framepos_t start = selection->time[clicked_selection].start;
5354         framepos_t end = selection->time[clicked_selection].end;
5355
5356         set_punch_range (start, end,  _("set punch range from selection"));
5357 }
5358
5359 void
5360 Editor::set_punch_from_edit_range ()
5361 {
5362         if (_session == 0) {
5363                 return;
5364         }
5365
5366         framepos_t start;
5367         framepos_t end;
5368
5369         if (!get_edit_op_range (start, end)) {
5370                 return;
5371         }
5372
5373         set_punch_range (start, end,  _("set punch range from edit range"));
5374 }
5375
5376 void
5377 Editor::set_punch_from_region ()
5378 {
5379         framepos_t start = max_framepos;
5380         framepos_t end = 0;
5381
5382         RegionSelection rs = get_regions_from_selection_and_entered ();
5383
5384         if (rs.empty()) {
5385                 return;
5386         }
5387
5388         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5389                 if ((*i)->region()->position() < start) {
5390                         start = (*i)->region()->position();
5391                 }
5392                 if ((*i)->region()->last_frame() + 1 > end) {
5393                         end = (*i)->region()->last_frame() + 1;
5394                 }
5395         }
5396
5397         set_punch_range (start, end, _("set punch range from region"));
5398 }
5399
5400 void
5401 Editor::pitch_shift_region ()
5402 {
5403         RegionSelection rs = get_regions_from_selection_and_entered ();
5404
5405         RegionSelection audio_rs;
5406         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5407                 if (dynamic_cast<AudioRegionView*> (*i)) {
5408                         audio_rs.push_back (*i);
5409                 }
5410         }
5411
5412         if (audio_rs.empty()) {
5413                 return;
5414         }
5415
5416         pitch_shift (audio_rs, 1.2);
5417 }
5418
5419 void
5420 Editor::transpose_region ()
5421 {
5422         RegionSelection rs = get_regions_from_selection_and_entered ();
5423
5424         list<MidiRegionView*> midi_region_views;
5425         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5426                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*i);
5427                 if (mrv) {
5428                         midi_region_views.push_back (mrv);
5429                 }
5430         }
5431
5432         TransposeDialog d;
5433         int const r = d.run ();
5434         if (r != RESPONSE_ACCEPT) {
5435                 return;
5436         }
5437
5438         for (list<MidiRegionView*>::iterator i = midi_region_views.begin(); i != midi_region_views.end(); ++i) {
5439                 (*i)->midi_region()->transpose (d.semitones ());
5440         }
5441 }
5442
5443 void
5444 Editor::set_tempo_from_region ()
5445 {
5446         RegionSelection rs = get_regions_from_selection_and_entered ();
5447
5448         if (!_session || rs.empty()) {
5449                 return;
5450         }
5451
5452         RegionView* rv = rs.front();
5453
5454         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5455 }
5456
5457 void
5458 Editor::use_range_as_bar ()
5459 {
5460         framepos_t start, end;
5461         if (get_edit_op_range (start, end)) {
5462                 define_one_bar (start, end);
5463         }
5464 }
5465
5466 void
5467 Editor::define_one_bar (framepos_t start, framepos_t end)
5468 {
5469         framepos_t length = end - start;
5470
5471         const Meter& m (_session->tempo_map().meter_at (start));
5472
5473         /* length = 1 bar */
5474
5475         /* now we want frames per beat.
5476            we have frames per bar, and beats per bar, so ...
5477         */
5478
5479         double frames_per_beat = length / m.beats_per_bar();
5480
5481         /* beats per minute = */
5482
5483         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5484
5485         /* now decide whether to:
5486
5487             (a) set global tempo
5488             (b) add a new tempo marker
5489
5490         */
5491
5492         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5493
5494         bool do_global = false;
5495
5496         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5497
5498                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5499                    at the start, or create a new marker
5500                 */
5501
5502                 vector<string> options;
5503                 options.push_back (_("Cancel"));
5504                 options.push_back (_("Add new marker"));
5505                 options.push_back (_("Set global tempo"));
5506
5507                 Choice c (
5508                         _("Define one bar"),
5509                         _("Do you want to set the global tempo or add a new tempo marker?"),
5510                         options
5511                         );
5512
5513                 c.set_default_response (2);
5514
5515                 switch (c.run()) {
5516                 case 0:
5517                         return;
5518
5519                 case 2:
5520                         do_global = true;
5521                         break;
5522
5523                 default:
5524                         do_global = false;
5525                 }
5526
5527         } else {
5528
5529                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5530                    if the marker is at the region starter, change it, otherwise add
5531                    a new tempo marker
5532                 */
5533         }
5534
5535         begin_reversible_command (_("set tempo from region"));
5536         XMLNode& before (_session->tempo_map().get_state());
5537
5538         if (do_global) {
5539                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5540         } else if (t.frame() == start) {
5541                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5542         } else {
5543                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5544         }
5545
5546         XMLNode& after (_session->tempo_map().get_state());
5547
5548         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5549         commit_reversible_command ();
5550 }
5551
5552 void
5553 Editor::split_region_at_transients ()
5554 {
5555         AnalysisFeatureList positions;
5556
5557         RegionSelection rs = get_regions_from_selection_and_entered ();
5558
5559         if (!_session || rs.empty()) {
5560                 return;
5561         }
5562
5563         _session->begin_reversible_command (_("split regions"));
5564
5565         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5566
5567                 RegionSelection::iterator tmp;
5568
5569                 tmp = i;
5570                 ++tmp;
5571
5572                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5573
5574                 if (ar && (ar->get_transients (positions) == 0)) {
5575                         split_region_at_points ((*i)->region(), positions, true);
5576                         positions.clear ();
5577                 }
5578
5579                 i = tmp;
5580         }
5581
5582         _session->commit_reversible_command ();
5583
5584 }
5585
5586 void
5587 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret, bool select_new)
5588 {
5589         bool use_rhythmic_rodent = false;
5590
5591         boost::shared_ptr<Playlist> pl = r->playlist();
5592
5593         list<boost::shared_ptr<Region> > new_regions;
5594
5595         if (!pl) {
5596                 return;
5597         }
5598
5599         if (positions.empty()) {
5600                 return;
5601         }
5602
5603
5604         if (positions.size() > 20 && can_ferret) {
5605                 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);
5606                 MessageDialog msg (msgstr,
5607                                    false,
5608                                    Gtk::MESSAGE_INFO,
5609                                    Gtk::BUTTONS_OK_CANCEL);
5610
5611                 if (can_ferret) {
5612                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5613                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5614                 } else {
5615                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5616                 }
5617
5618                 msg.set_title (_("Excessive split?"));
5619                 msg.present ();
5620
5621                 int response = msg.run();
5622                 msg.hide ();
5623
5624                 switch (response) {
5625                 case RESPONSE_OK:
5626                         break;
5627                 case RESPONSE_APPLY:
5628                         use_rhythmic_rodent = true;
5629                         break;
5630                 default:
5631                         return;
5632                 }
5633         }
5634
5635         if (use_rhythmic_rodent) {
5636                 show_rhythm_ferret ();
5637                 return;
5638         }
5639
5640         AnalysisFeatureList::const_iterator x;
5641
5642         pl->clear_changes ();
5643
5644         x = positions.begin();
5645
5646         if (x == positions.end()) {
5647                 return;
5648         }
5649
5650         pl->freeze ();
5651         pl->remove_region (r);
5652
5653         framepos_t pos = 0;
5654
5655         while (x != positions.end()) {
5656
5657                 /* deal with positons that are out of scope of present region bounds */
5658                 if (*x <= 0 || *x > r->length()) {
5659                         ++x;
5660                         continue;
5661                 }
5662
5663                 /* file start = original start + how far we from the initial position ?
5664                  */
5665
5666                 framepos_t file_start = r->start() + pos;
5667
5668                 /* length = next position - current position
5669                  */
5670
5671                 framepos_t len = (*x) - pos;
5672
5673                 /* XXX we do we really want to allow even single-sample regions?
5674                    shouldn't we have some kind of lower limit on region size?
5675                 */
5676
5677                 if (len <= 0) {
5678                         break;
5679                 }
5680
5681                 string new_name;
5682
5683                 if (RegionFactory::region_name (new_name, r->name())) {
5684                         break;
5685                 }
5686
5687                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5688
5689                 PropertyList plist;
5690
5691                 plist.add (ARDOUR::Properties::start, file_start);
5692                 plist.add (ARDOUR::Properties::length, len);
5693                 plist.add (ARDOUR::Properties::name, new_name);
5694                 plist.add (ARDOUR::Properties::layer, 0);
5695
5696                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5697
5698                 pl->add_region (nr, r->position() + pos);
5699
5700                 if (select_new) {
5701                         new_regions.push_front(nr);
5702                 }
5703
5704                 pos += len;
5705                 ++x;
5706         }
5707
5708         string new_name;
5709
5710         RegionFactory::region_name (new_name, r->name());
5711
5712         /* Add the final region */
5713         PropertyList plist;
5714
5715         plist.add (ARDOUR::Properties::start, r->start() + pos);
5716         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
5717         plist.add (ARDOUR::Properties::name, new_name);
5718         plist.add (ARDOUR::Properties::layer, 0);
5719
5720         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5721         pl->add_region (nr, r->position() + pos);
5722
5723         if (select_new) {
5724                 new_regions.push_front(nr);
5725         }
5726
5727         pl->thaw ();
5728
5729         _session->add_command (new StatefulDiffCommand (pl));
5730
5731         if (select_new) {
5732
5733                 for (list<boost::shared_ptr<Region> >::iterator i = new_regions.begin(); i != new_regions.end(); ++i){
5734                         set_selected_regionview_from_region_list ((*i), Selection::Add);
5735                 }
5736         }
5737 }
5738
5739 void
5740 Editor::place_transient()
5741 {
5742         if (!_session) {
5743                 return;
5744         }
5745
5746         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5747
5748         if (rs.empty()) {
5749                 return;
5750         }
5751
5752         framepos_t where = get_preferred_edit_position();
5753
5754         _session->begin_reversible_command (_("place transient"));
5755
5756         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5757                 framepos_t position = (*r)->region()->position();
5758                 (*r)->region()->add_transient(where - position);
5759         }
5760
5761         _session->commit_reversible_command ();
5762 }
5763
5764 void
5765 Editor::remove_transient(ArdourCanvas::Item* item)
5766 {
5767         if (!_session) {
5768                 return;
5769         }
5770
5771         ArdourCanvas::Line* _line = reinterpret_cast<ArdourCanvas::Line*> (item);
5772         assert (_line);
5773
5774         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
5775         _arv->remove_transient (*(float*) _line->get_data ("position"));
5776 }
5777
5778 void
5779 Editor::snap_regions_to_grid ()
5780 {
5781         list <boost::shared_ptr<Playlist > > used_playlists;
5782
5783         RegionSelection rs = get_regions_from_selection_and_entered ();
5784
5785         if (!_session || rs.empty()) {
5786                 return;
5787         }
5788
5789         _session->begin_reversible_command (_("snap regions to grid"));
5790
5791         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5792
5793                 boost::shared_ptr<Playlist> pl = (*r)->region()->playlist();
5794
5795                 if (!pl->frozen()) {
5796                         /* we haven't seen this playlist before */
5797
5798                         /* remember used playlists so we can thaw them later */
5799                         used_playlists.push_back(pl);
5800                         pl->freeze();
5801                 }
5802
5803                 framepos_t start_frame = (*r)->region()->first_frame ();
5804                 snap_to (start_frame);
5805                 (*r)->region()->set_position (start_frame);
5806         }
5807
5808         while (used_playlists.size() > 0) {
5809                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
5810                 (*i)->thaw();
5811                 used_playlists.pop_front();
5812         }
5813
5814         _session->commit_reversible_command ();
5815 }
5816
5817 void
5818 Editor::close_region_gaps ()
5819 {
5820         list <boost::shared_ptr<Playlist > > used_playlists;
5821
5822         RegionSelection rs = get_regions_from_selection_and_entered ();
5823
5824         if (!_session || rs.empty()) {
5825                 return;
5826         }
5827
5828         Dialog dialog (_("Close Region Gaps"));
5829
5830         Table table (2, 3);
5831         table.set_spacings (12);
5832         table.set_border_width (12);
5833         Label* l = manage (new Label (_("Crossfade length")));
5834         l->set_alignment (0, 0.5);
5835         table.attach (*l, 0, 1, 0, 1);
5836
5837         SpinButton spin_crossfade (1, 0);
5838         spin_crossfade.set_range (0, 15);
5839         spin_crossfade.set_increments (1, 1);
5840         spin_crossfade.set_value (5);
5841         table.attach (spin_crossfade, 1, 2, 0, 1);
5842
5843         table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
5844
5845         l = manage (new Label (_("Pull-back length")));
5846         l->set_alignment (0, 0.5);
5847         table.attach (*l, 0, 1, 1, 2);
5848
5849         SpinButton spin_pullback (1, 0);
5850         spin_pullback.set_range (0, 100);
5851         spin_pullback.set_increments (1, 1);
5852         spin_pullback.set_value(30);
5853         table.attach (spin_pullback, 1, 2, 1, 2);
5854
5855         table.attach (*manage (new Label (_("ms"))), 2, 3, 1, 2);
5856
5857         dialog.get_vbox()->pack_start (table);
5858         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
5859         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
5860         dialog.show_all ();
5861
5862         if (dialog.run () == RESPONSE_CANCEL) {
5863                 return;
5864         }
5865
5866         framepos_t crossfade_len = spin_crossfade.get_value();
5867         framepos_t pull_back_frames = spin_pullback.get_value();
5868
5869         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
5870         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
5871
5872         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
5873
5874         _session->begin_reversible_command (_("close region gaps"));
5875
5876         int idx = 0;
5877         boost::shared_ptr<Region> last_region;
5878
5879         rs.sort_by_position_and_track();
5880
5881         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5882
5883                 boost::shared_ptr<Playlist> pl = (*r)->region()->playlist();
5884
5885                 if (!pl->frozen()) {
5886                         /* we haven't seen this playlist before */
5887
5888                         /* remember used playlists so we can thaw them later */
5889                         used_playlists.push_back(pl);
5890                         pl->freeze();
5891                 }
5892
5893                 framepos_t position = (*r)->region()->position();
5894
5895                 if (idx == 0 || position < last_region->position()){
5896                         last_region = (*r)->region();
5897                         idx++;
5898                         continue;
5899                 }
5900
5901                 (*r)->region()->trim_front( (position - pull_back_frames));
5902                 last_region->trim_end( (position - pull_back_frames + crossfade_len));
5903
5904                 last_region = (*r)->region();
5905
5906                 idx++;
5907         }
5908
5909         while (used_playlists.size() > 0) {
5910                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
5911                 (*i)->thaw();
5912                 used_playlists.pop_front();
5913         }
5914
5915         _session->commit_reversible_command ();
5916 }
5917
5918 void
5919 Editor::tab_to_transient (bool forward)
5920 {
5921         AnalysisFeatureList positions;
5922
5923         RegionSelection rs = get_regions_from_selection_and_entered ();
5924
5925         if (!_session) {
5926                 return;
5927         }
5928
5929         framepos_t pos = _session->audible_frame ();
5930
5931         if (!selection->tracks.empty()) {
5932
5933                 for (TrackSelection::iterator t = selection->tracks.begin(); t != selection->tracks.end(); ++t) {
5934
5935                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
5936
5937                         if (rtv) {
5938                                 boost::shared_ptr<Track> tr = rtv->track();
5939                                 if (tr) {
5940                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
5941                                         if (pl) {
5942                                                 framepos_t result = pl->find_next_transient (pos, forward ? 1 : -1);
5943
5944                                                 if (result >= 0) {
5945                                                         positions.push_back (result);
5946                                                 }
5947                                         }
5948                                 }
5949                         }
5950                 }
5951
5952         } else {
5953
5954                 if (rs.empty()) {
5955                         return;
5956                 }
5957
5958                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5959                         (*r)->region()->get_transients (positions);
5960                 }
5961         }
5962
5963         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
5964
5965         if (forward) {
5966                 AnalysisFeatureList::iterator x;
5967
5968                 for (x = positions.begin(); x != positions.end(); ++x) {
5969                         if ((*x) > pos) {
5970                                 break;
5971                         }
5972                 }
5973
5974                 if (x != positions.end ()) {
5975                         _session->request_locate (*x);
5976                 }
5977
5978         } else {
5979                 AnalysisFeatureList::reverse_iterator x;
5980
5981                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
5982                         if ((*x) < pos) {
5983                                 break;
5984                         }
5985                 }
5986
5987                 if (x != positions.rend ()) {
5988                         _session->request_locate (*x);
5989                 }
5990         }
5991 }
5992
5993 void
5994 Editor::playhead_forward_to_grid ()
5995 {
5996         if (!_session) return;
5997         framepos_t pos = playhead_cursor->current_frame;
5998         if (pos < max_framepos - 1) {
5999                 pos += 2;
6000                 snap_to_internal (pos, 1, false);
6001                 _session->request_locate (pos);
6002         }
6003 }
6004
6005
6006 void
6007 Editor::playhead_backward_to_grid ()
6008 {
6009         if (!_session) return;
6010         framepos_t pos = playhead_cursor->current_frame;
6011         if (pos > 2) {
6012                 pos -= 2;
6013                 snap_to_internal (pos, -1, false);
6014                 _session->request_locate (pos);
6015         }
6016 }
6017
6018 void
6019 Editor::set_track_height (Height h)
6020 {
6021         TrackSelection& ts (selection->tracks);
6022
6023         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6024                 (*x)->set_height_enum (h);
6025         }
6026 }
6027
6028 void
6029 Editor::toggle_tracks_active ()
6030 {
6031         TrackSelection& ts (selection->tracks);
6032         bool first = true;
6033         bool target = false;
6034
6035         if (ts.empty()) {
6036                 return;
6037         }
6038
6039         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6040                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6041
6042                 if (rtv) {
6043                         if (first) {
6044                                 target = !rtv->_route->active();
6045                                 first = false;
6046                         }
6047                         rtv->_route->set_active (target, this);
6048                 }
6049         }
6050 }
6051
6052 void
6053 Editor::remove_tracks ()
6054 {
6055         TrackSelection& ts (selection->tracks);
6056
6057         if (ts.empty()) {
6058                 return;
6059         }
6060
6061         vector<string> choices;
6062         string prompt;
6063         int ntracks = 0;
6064         int nbusses = 0;
6065         const char* trackstr;
6066         const char* busstr;
6067         vector<boost::shared_ptr<Route> > routes;
6068         bool special_bus = false;
6069
6070         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6071                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6072                 if (rtv) {
6073                         if (rtv->is_track()) {
6074                                 ntracks++;
6075                         } else {
6076                                 nbusses++;
6077                         }
6078                 }
6079                 routes.push_back (rtv->_route);
6080
6081                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6082                         special_bus = true;
6083                 }
6084         }
6085
6086         if (special_bus && !Config->get_allow_special_bus_removal()) {
6087                 MessageDialog msg (_("That would be bad news ...."),
6088                                    false,
6089                                    Gtk::MESSAGE_INFO,
6090                                    Gtk::BUTTONS_OK);
6091                 msg.set_secondary_text (string_compose (_(
6092                                                                 "Removing the master or monitor bus is such a bad idea\n\
6093 that %1 is not going to allow it.\n\
6094 \n\
6095 If you really want to do this sort of thing\n\
6096 edit your ardour.rc file to set the\n\
6097 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6098
6099                 msg.present ();
6100                 msg.run ();
6101                 return;
6102         }
6103
6104         if (ntracks + nbusses == 0) {
6105                 return;
6106         }
6107
6108         if (ntracks > 1) {
6109                 trackstr = _("tracks");
6110         } else {
6111                 trackstr = _("track");
6112         }
6113
6114         if (nbusses > 1) {
6115                 busstr = _("busses");
6116         } else {
6117                 busstr = _("bus");
6118         }
6119
6120         if (ntracks) {
6121                 if (nbusses) {
6122                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6123                                                     "(You may also lose the playlists associated with the %2)\n\n"
6124                                                     "This action cannot be undone, and the session file will be overwritten!"),
6125                                                   ntracks, trackstr, nbusses, busstr);
6126                 } else {
6127                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6128                                                     "(You may also lose the playlists associated with the %2)\n\n"
6129                                                     "This action cannot be undone, and the session file will be overwritten!"),
6130                                                   ntracks, trackstr);
6131                 }
6132         } else if (nbusses) {
6133                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6134                                             "This action cannot be undon, and the session file will be overwritten"),
6135                                           nbusses, busstr);
6136         }
6137
6138         choices.push_back (_("No, do nothing."));
6139         if (ntracks + nbusses > 1) {
6140                 choices.push_back (_("Yes, remove them."));
6141         } else {
6142                 choices.push_back (_("Yes, remove it."));
6143         }
6144
6145         string title;
6146         if (ntracks) {
6147                 title = string_compose (_("Remove %1"), trackstr);
6148         } else {
6149                 title = string_compose (_("Remove %1"), busstr);
6150         }
6151
6152         Choice prompter (title, prompt, choices);
6153
6154         if (prompter.run () != 1) {
6155                 return;
6156         }
6157
6158         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6159                 _session->remove_route (*x);
6160         }
6161 }
6162
6163 void
6164 Editor::do_insert_time ()
6165 {
6166         if (selection->tracks.empty()) {
6167                 return;
6168         }
6169
6170         InsertTimeDialog d (*this);
6171         int response = d.run ();
6172
6173         if (response != RESPONSE_OK) {
6174                 return;
6175         }
6176
6177         if (d.distance() == 0) {
6178                 return;
6179         }
6180
6181         InsertTimeOption opt = d.intersected_region_action ();
6182
6183         insert_time (
6184                 get_preferred_edit_position(),
6185                 d.distance(),
6186                 opt,
6187                 d.all_playlists(),
6188                 d.move_glued(),
6189                 d.move_markers(),
6190                 d.move_glued_markers(),
6191                 d.move_locked_markers(),
6192                 d.move_tempos()
6193                 );
6194 }
6195
6196 void
6197 Editor::insert_time (
6198         framepos_t pos, framecnt_t frames, InsertTimeOption opt,
6199         bool all_playlists, bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too
6200         )
6201 {
6202         bool commit = false;
6203
6204         if (Config->get_edit_mode() == Lock) {
6205                 return;
6206         }
6207
6208         begin_reversible_command (_("insert time"));
6209
6210         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
6211
6212                 /* regions */
6213
6214                 vector<boost::shared_ptr<Playlist> > pl;
6215                 if (all_playlists) {
6216                         RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6217                         if (rtav) {
6218                                 pl = _session->playlists->playlists_for_track (rtav->track ());
6219                         }
6220                 } else {
6221                         if ((*x)->playlist ()) {
6222                                 pl.push_back ((*x)->playlist ());
6223                         }
6224                 }
6225
6226                 for (vector<boost::shared_ptr<Playlist> >::iterator i = pl.begin(); i != pl.end(); ++i) {
6227
6228                         (*i)->clear_changes ();
6229                         (*i)->clear_owned_changes ();
6230
6231                         if (opt == SplitIntersected) {
6232                                 (*i)->split (pos);
6233                         }
6234
6235                         (*i)->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6236
6237                         vector<Command*> cmds;
6238                         (*i)->rdiff (cmds);
6239                         _session->add_commands (cmds);
6240
6241                         _session->add_command (new StatefulDiffCommand (*i));
6242                         commit = true;
6243                 }
6244
6245                 /* automation */
6246                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6247                 if (rtav) {
6248                         rtav->route ()->shift (pos, frames);
6249                         commit = true;
6250                 }
6251         }
6252
6253         /* markers */
6254         if (markers_too) {
6255                 bool moved = false;
6256                 XMLNode& before (_session->locations()->get_state());
6257                 Locations::LocationList copy (_session->locations()->list());
6258
6259                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6260
6261                         Locations::LocationList::const_iterator tmp;
6262
6263                         bool const was_locked = (*i)->locked ();
6264                         if (locked_markers_too) {
6265                                 (*i)->unlock ();
6266                         }
6267
6268                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6269
6270                                 if ((*i)->start() >= pos) {
6271                                         (*i)->set_start ((*i)->start() + frames);
6272                                         if (!(*i)->is_mark()) {
6273                                                 (*i)->set_end ((*i)->end() + frames);
6274                                         }
6275                                         moved = true;
6276                                 }
6277
6278                         }
6279
6280                         if (was_locked) {
6281                                 (*i)->lock ();
6282                         }
6283                 }
6284
6285                 if (moved) {
6286                         XMLNode& after (_session->locations()->get_state());
6287                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6288                 }
6289         }
6290
6291         if (tempo_too) {
6292                 _session->tempo_map().insert_time (pos, frames);
6293         }
6294
6295         if (commit) {
6296                 commit_reversible_command ();
6297         }
6298 }
6299
6300 void
6301 Editor::fit_selected_tracks ()
6302 {
6303         if (!selection->tracks.empty()) {
6304                 fit_tracks (selection->tracks);
6305         } else {
6306                 TrackViewList tvl;
6307
6308                 /* no selected tracks - use tracks with selected regions */
6309
6310                 if (!selection->regions.empty()) {
6311                         for (RegionSelection::iterator r = selection->regions.begin(); r != selection->regions.end(); ++r) {
6312                                 tvl.push_back (&(*r)->get_time_axis_view ());
6313                         }
6314
6315                         if (!tvl.empty()) {
6316                                 fit_tracks (tvl);
6317                         }
6318                 } else if (internal_editing()) {
6319                         /* no selected tracks, or regions, but in internal edit mode, so follow the mouse and use
6320                            the entered track
6321                         */
6322                         if (entered_track) {
6323                                 tvl.push_back (entered_track);
6324                                 fit_tracks (tvl);
6325                         }
6326                 }
6327         }
6328 }
6329
6330 void
6331 Editor::fit_tracks (TrackViewList & tracks)
6332 {
6333         if (tracks.empty()) {
6334                 return;
6335         }
6336
6337         uint32_t child_heights = 0;
6338         int visible_tracks = 0;
6339
6340         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6341
6342                 if (!(*t)->marked_for_display()) {
6343                         continue;
6344                 }
6345
6346                 child_heights += (*t)->effective_height() - (*t)->current_height();
6347                 ++visible_tracks;
6348         }
6349
6350         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / visible_tracks);
6351         double first_y_pos = DBL_MAX;
6352
6353         if (h < TimeAxisView::preset_height (HeightSmall)) {
6354                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6355                 /* too small to be displayed */
6356                 return;
6357         }
6358
6359         undo_visual_stack.push_back (current_visual_state());
6360
6361         /* build a list of all tracks, including children */
6362
6363         TrackViewList all;
6364         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6365                 all.push_back (*i);
6366                 TimeAxisView::Children c = (*i)->get_child_list ();
6367                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6368                         all.push_back (j->get());
6369                 }
6370         }
6371
6372         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6373
6374         bool prev_was_selected = false;
6375         bool is_selected = tracks.contains (all.front());
6376         bool next_is_selected;
6377
6378         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6379
6380                 TrackViewList::iterator next;
6381
6382                 next = t;
6383                 ++next;
6384
6385                 if (next != all.end()) {
6386                         next_is_selected = tracks.contains (*next);
6387                 } else {
6388                         next_is_selected = false;
6389                 }
6390
6391                 if ((*t)->marked_for_display ()) {
6392                         if (is_selected) {
6393                                 (*t)->set_height (h);
6394                                 first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6395                         } else {
6396                                 if (prev_was_selected && next_is_selected) {
6397                                         hide_track_in_display (*t);
6398                                 }
6399                         }
6400                 }
6401
6402                 prev_was_selected = is_selected;
6403                 is_selected = next_is_selected;
6404         }
6405
6406         /*
6407            set the controls_layout height now, because waiting for its size
6408            request signal handler will cause the vertical adjustment setting to fail
6409         */
6410
6411         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6412         vertical_adjustment.set_value (first_y_pos);
6413
6414         redo_visual_stack.push_back (current_visual_state());
6415 }
6416
6417 void
6418 Editor::save_visual_state (uint32_t n)
6419 {
6420         while (visual_states.size() <= n) {
6421                 visual_states.push_back (0);
6422         }
6423
6424         delete visual_states[n];
6425
6426         visual_states[n] = current_visual_state (true);
6427         gdk_beep ();
6428 }
6429
6430 void
6431 Editor::goto_visual_state (uint32_t n)
6432 {
6433         if (visual_states.size() <= n) {
6434                 return;
6435         }
6436
6437         if (visual_states[n] == 0) {
6438                 return;
6439         }
6440
6441         use_visual_state (*visual_states[n]);
6442 }
6443
6444 void
6445 Editor::start_visual_state_op (uint32_t n)
6446 {
6447         if (visual_state_op_connection.empty()) {
6448                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6449         }
6450 }
6451
6452 void
6453 Editor::cancel_visual_state_op (uint32_t n)
6454 {
6455         if (!visual_state_op_connection.empty()) {
6456                 visual_state_op_connection.disconnect();
6457                 goto_visual_state (n);
6458         }  else {
6459                 //we land here if called from the menu OR if end_visual_state_op has been called
6460                 //so check if we are already in visual state n
6461                 // XXX not yet checking it at all, but redoing does not hurt
6462                 goto_visual_state (n);
6463         }
6464 }
6465
6466 bool
6467 Editor::end_visual_state_op (uint32_t n)
6468 {
6469         visual_state_op_connection.disconnect();
6470         save_visual_state (n);
6471
6472         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6473         char buf[32];
6474         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6475         pup->set_text (buf);
6476         pup->touch();
6477
6478         return false; // do not call again
6479 }
6480
6481 void
6482 Editor::toggle_region_mute ()
6483 {
6484         if (_ignore_region_action) {
6485                 return;
6486         }
6487
6488         RegionSelection rs = get_regions_from_selection_and_entered ();
6489
6490         if (rs.empty ()) {
6491                 return;
6492         }
6493
6494         if (rs.size() > 1) {
6495                 begin_reversible_command (_("mute regions"));
6496         } else {
6497                 begin_reversible_command (_("mute region"));
6498         }
6499
6500         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
6501
6502                 (*i)->region()->playlist()->clear_changes ();
6503                 (*i)->region()->set_muted (!(*i)->region()->muted ());
6504                 _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
6505
6506         }
6507
6508         commit_reversible_command ();
6509 }
6510
6511 void
6512 Editor::combine_regions ()
6513 {
6514         /* foreach track with selected regions, take all selected regions
6515            and join them into a new region containing the subregions (as a
6516            playlist)
6517         */
6518
6519         typedef set<RouteTimeAxisView*> RTVS;
6520         RTVS tracks;
6521
6522         if (selection->regions.empty()) {
6523                 return;
6524         }
6525
6526         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
6527                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&(*i)->get_time_axis_view());
6528
6529                 if (rtv) {
6530                         tracks.insert (rtv);
6531                 }
6532         }
6533
6534         begin_reversible_command (_("combine regions"));
6535
6536         vector<RegionView*> new_selection;
6537
6538         for (RTVS::iterator i = tracks.begin(); i != tracks.end(); ++i) {
6539                 RegionView* rv;
6540
6541                 if ((rv = (*i)->combine_regions ()) != 0) {
6542                         new_selection.push_back (rv);
6543                 }
6544         }
6545
6546         selection->clear_regions ();
6547         for (vector<RegionView*>::iterator i = new_selection.begin(); i != new_selection.end(); ++i) {
6548                 selection->add (*i);
6549         }
6550
6551         commit_reversible_command ();
6552 }
6553
6554 void
6555 Editor::uncombine_regions ()
6556 {
6557         typedef set<RouteTimeAxisView*> RTVS;
6558         RTVS tracks;
6559
6560         if (selection->regions.empty()) {
6561                 return;
6562         }
6563
6564         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
6565                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&(*i)->get_time_axis_view());
6566
6567                 if (rtv) {
6568                         tracks.insert (rtv);
6569                 }
6570         }
6571
6572         begin_reversible_command (_("uncombine regions"));
6573
6574         for (RTVS::iterator i = tracks.begin(); i != tracks.end(); ++i) {
6575                 (*i)->uncombine_regions ();
6576         }
6577
6578         commit_reversible_command ();
6579 }
6580