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