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