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