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