centralize use of "from-context-menu" in Editor::get_preferred_edit_position(), and...
[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         reposition_and_zoom (new_leftmost, new_fpu);
1585 }
1586
1587 void
1588 Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
1589 {
1590         if (!_session) {
1591                 return;
1592         }
1593         double range_before = frame - leftmost_frame;
1594         double new_fpu;
1595
1596         new_fpu = frames_per_unit;
1597
1598         if (coarser) {
1599                 new_fpu *= 1.61803399;
1600                 range_before *= 1.61803399;
1601         } else {
1602                 new_fpu = max(1.0,(new_fpu/1.61803399));
1603                 range_before /= 1.61803399;
1604         }
1605
1606         if (new_fpu == frames_per_unit)  {
1607                 return;
1608         }
1609
1610         framepos_t new_leftmost = frame - (framepos_t)range_before;
1611
1612         if (new_leftmost > frame) {
1613                 new_leftmost = 0;
1614         }
1615
1616         if (new_leftmost < 0) {
1617                 new_leftmost = 0;
1618         }
1619
1620         reposition_and_zoom (new_leftmost, new_fpu);
1621 }
1622
1623
1624 bool
1625 Editor::choose_new_marker_name(string &name) {
1626
1627         if (!Config->get_name_new_markers()) {
1628                 /* don't prompt user for a new name */
1629                 return true;
1630         }
1631
1632         ArdourPrompter dialog (true);
1633
1634         dialog.set_prompt (_("New Name:"));
1635
1636         dialog.set_title (_("New Location Marker"));
1637
1638         dialog.set_name ("MarkNameWindow");
1639         dialog.set_size_request (250, -1);
1640         dialog.set_position (Gtk::WIN_POS_MOUSE);
1641
1642         dialog.add_button (Stock::OK, RESPONSE_ACCEPT);
1643         dialog.set_initial_text (name);
1644
1645         dialog.show ();
1646
1647         switch (dialog.run ()) {
1648         case RESPONSE_ACCEPT:
1649                 break;
1650         default:
1651                 return false;
1652         }
1653
1654         dialog.get_result(name);
1655         return true;
1656
1657 }
1658
1659
1660 void
1661 Editor::add_location_from_selection ()
1662 {
1663         string rangename;
1664
1665         if (selection->time.empty()) {
1666                 return;
1667         }
1668
1669         if (_session == 0 || clicked_axisview == 0) {
1670                 return;
1671         }
1672
1673         framepos_t start = selection->time[clicked_selection].start;
1674         framepos_t end = selection->time[clicked_selection].end;
1675
1676         _session->locations()->next_available_name(rangename,"selection");
1677         Location *location = new Location (*_session, start, end, rangename, Location::IsRangeMarker);
1678
1679         _session->begin_reversible_command (_("add marker"));
1680         XMLNode &before = _session->locations()->get_state();
1681         _session->locations()->add (location, true);
1682         XMLNode &after = _session->locations()->get_state();
1683         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1684         _session->commit_reversible_command ();
1685 }
1686
1687 void
1688 Editor::add_location_mark (framepos_t where)
1689 {
1690         string markername;
1691
1692         select_new_marker = true;
1693
1694         _session->locations()->next_available_name(markername,"mark");
1695         if (!choose_new_marker_name(markername)) {
1696                 return;
1697         }
1698         Location *location = new Location (*_session, where, where, markername, Location::IsMark);
1699         _session->begin_reversible_command (_("add marker"));
1700         XMLNode &before = _session->locations()->get_state();
1701         _session->locations()->add (location, true);
1702         XMLNode &after = _session->locations()->get_state();
1703         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1704         _session->commit_reversible_command ();
1705 }
1706
1707 void
1708 Editor::add_location_from_playhead_cursor ()
1709 {
1710         add_location_mark (_session->audible_frame());
1711 }
1712
1713 /** Add a range marker around each selected region */
1714 void
1715 Editor::add_locations_from_region ()
1716 {
1717         RegionSelection rs = get_regions_from_selection_and_entered ();
1718
1719         if (rs.empty()) {
1720                 return;
1721         }
1722
1723         _session->begin_reversible_command (selection->regions.size () > 1 ? _("add markers") : _("add marker"));
1724         XMLNode &before = _session->locations()->get_state();
1725
1726         for (RegionSelection::iterator i = rs.begin (); i != rs.end (); ++i) {
1727
1728                 boost::shared_ptr<Region> region = (*i)->region ();
1729
1730                 Location *location = new Location (*_session, region->position(), region->last_frame(), region->name(), Location::IsRangeMarker);
1731
1732                 _session->locations()->add (location, true);
1733         }
1734
1735         XMLNode &after = _session->locations()->get_state();
1736         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1737         _session->commit_reversible_command ();
1738 }
1739
1740 /** Add a single range marker around all selected regions */
1741 void
1742 Editor::add_location_from_region ()
1743 {
1744         RegionSelection rs = get_regions_from_selection_and_entered ();
1745
1746         if (rs.empty()) {
1747                 return;
1748         }
1749
1750         _session->begin_reversible_command (_("add marker"));
1751         XMLNode &before = _session->locations()->get_state();
1752
1753         string markername;
1754
1755         if (rs.size() > 1) {
1756                 _session->locations()->next_available_name(markername, "regions");
1757         } else {
1758                 RegionView* rv = *(rs.begin());
1759                 boost::shared_ptr<Region> region = rv->region();
1760                 markername = region->name();
1761         }
1762
1763         if (!choose_new_marker_name(markername)) {
1764                 return;
1765         }
1766
1767         // single range spanning all selected
1768         Location *location = new Location (*_session, selection->regions.start(), selection->regions.end_frame(), markername, Location::IsRangeMarker);
1769         _session->locations()->add (location, true);
1770
1771         XMLNode &after = _session->locations()->get_state();
1772         _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1773         _session->commit_reversible_command ();
1774 }
1775
1776 /* MARKS */
1777
1778 void
1779 Editor::jump_forward_to_mark ()
1780 {
1781         if (!_session) {
1782                 return;
1783         }
1784
1785         Location *location = _session->locations()->first_location_after (playhead_cursor->current_frame);
1786
1787         if (location) {
1788                 _session->request_locate (location->start(), _session->transport_rolling());
1789         } else {
1790                 _session->request_locate (_session->current_end_frame());
1791         }
1792 }
1793
1794 void
1795 Editor::jump_backward_to_mark ()
1796 {
1797         if (!_session) {
1798                 return;
1799         }
1800
1801         Location *location = _session->locations()->first_location_before (playhead_cursor->current_frame);
1802
1803         if (location) {
1804                 _session->request_locate (location->start(), _session->transport_rolling());
1805         } else {
1806                 _session->goto_start ();
1807         }
1808 }
1809
1810 void
1811 Editor::set_mark ()
1812 {
1813         framepos_t const pos = _session->audible_frame ();
1814
1815         string markername;
1816         _session->locations()->next_available_name (markername, "mark");
1817
1818         if (!choose_new_marker_name (markername)) {
1819                 return;
1820         }
1821
1822         _session->locations()->add (new Location (*_session, pos, 0, markername, Location::IsMark), true);
1823 }
1824
1825 void
1826 Editor::clear_markers ()
1827 {
1828         if (_session) {
1829                 _session->begin_reversible_command (_("clear markers"));
1830                 XMLNode &before = _session->locations()->get_state();
1831                 _session->locations()->clear_markers ();
1832                 XMLNode &after = _session->locations()->get_state();
1833                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1834                 _session->commit_reversible_command ();
1835         }
1836 }
1837
1838 void
1839 Editor::clear_ranges ()
1840 {
1841         if (_session) {
1842                 _session->begin_reversible_command (_("clear ranges"));
1843                 XMLNode &before = _session->locations()->get_state();
1844
1845                 Location * looploc = _session->locations()->auto_loop_location();
1846                 Location * punchloc = _session->locations()->auto_punch_location();
1847                 Location * sessionloc = _session->locations()->session_range_location();
1848
1849                 _session->locations()->clear_ranges ();
1850                 // re-add these
1851                 if (looploc) _session->locations()->add (looploc);
1852                 if (punchloc) _session->locations()->add (punchloc);
1853                 if (sessionloc) _session->locations()->add (sessionloc);
1854
1855                 XMLNode &after = _session->locations()->get_state();
1856                 _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1857                 _session->commit_reversible_command ();
1858         }
1859 }
1860
1861 void
1862 Editor::clear_locations ()
1863 {
1864         _session->begin_reversible_command (_("clear locations"));
1865         XMLNode &before = _session->locations()->get_state();
1866         _session->locations()->clear ();
1867         XMLNode &after = _session->locations()->get_state();
1868         _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
1869         _session->commit_reversible_command ();
1870         _session->locations()->clear ();
1871 }
1872
1873 void
1874 Editor::unhide_markers ()
1875 {
1876         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
1877                 Location *l = (*i).first;
1878                 if (l->is_hidden() && l->is_mark()) {
1879                         l->set_hidden(false, this);
1880                 }
1881         }
1882 }
1883
1884 void
1885 Editor::unhide_ranges ()
1886 {
1887         for (LocationMarkerMap::iterator i = location_markers.begin(); i != location_markers.end(); ++i) {
1888                 Location *l = (*i).first;
1889                 if (l->is_hidden() && l->is_range_marker()) {
1890                         l->set_hidden(false, this);
1891                 }
1892         }
1893 }
1894
1895 /* INSERT/REPLACE */
1896
1897 void
1898 Editor::insert_region_list_drag (boost::shared_ptr<Region> region, int x, int y)
1899 {
1900         double wx, wy;
1901         double cx, cy;
1902         framepos_t where;
1903         RouteTimeAxisView *rtv = 0;
1904         boost::shared_ptr<Playlist> playlist;
1905
1906         track_canvas->window_to_world (x, y, wx, wy);
1907
1908         GdkEvent event;
1909         event.type = GDK_BUTTON_RELEASE;
1910         event.button.x = wx;
1911         event.button.y = wy;
1912
1913         where = event_frame (&event, &cx, &cy);
1914
1915         if (where < leftmost_frame || where > leftmost_frame + current_page_frames()) {
1916                 /* clearly outside canvas area */
1917                 return;
1918         }
1919
1920         std::pair<TimeAxisView*, int> tv = trackview_by_y_position (cy);
1921         if (tv.first == 0) {
1922                 return;
1923         }
1924
1925         if ((rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
1926                 return;
1927         }
1928
1929         if ((playlist = rtv->playlist()) == 0) {
1930                 return;
1931         }
1932
1933         snap_to (where);
1934
1935         begin_reversible_command (_("insert dragged region"));
1936         playlist->clear_changes ();
1937         playlist->add_region (RegionFactory::create (region, true), where, 1.0);
1938         _session->add_command(new StatefulDiffCommand (playlist));
1939         commit_reversible_command ();
1940 }
1941
1942 void
1943 Editor::insert_route_list_drag (boost::shared_ptr<Route> route, int x, int y)
1944 {
1945         double wx, wy;
1946         double cx, cy;
1947         RouteTimeAxisView *dest_rtv = 0;
1948         RouteTimeAxisView *source_rtv = 0;
1949
1950         track_canvas->window_to_world (x, y, wx, wy);
1951         wx += horizontal_position ();
1952         wy += vertical_adjustment.get_value();
1953
1954         GdkEvent event;
1955         event.type = GDK_BUTTON_RELEASE;
1956         event.button.x = wx;
1957         event.button.y = wy;
1958
1959         event_frame (&event, &cx, &cy);
1960
1961         std::pair<TimeAxisView*, int> const tv = trackview_by_y_position (cy);
1962         if (tv.first == 0) {
1963                 return;
1964         }
1965
1966         if ((dest_rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
1967                 return;
1968         }
1969
1970         /* use this drag source to add underlay to a track. But we really don't care
1971            about the Route, only the view of the route, so find it first */
1972         for(TrackViewList::iterator it = track_views.begin(); it != track_views.end(); ++it) {
1973                 if((source_rtv = dynamic_cast<RouteTimeAxisView*>(*it)) == 0) {
1974                         continue;
1975                 }
1976
1977                 if(source_rtv->route() == route && source_rtv != dest_rtv) {
1978                         dest_rtv->add_underlay(source_rtv->view());
1979                         break;
1980                 }
1981         }
1982 }
1983
1984 void
1985 Editor::insert_region_list_selection (float times)
1986 {
1987         RouteTimeAxisView *tv = 0;
1988         boost::shared_ptr<Playlist> playlist;
1989
1990         if (clicked_routeview != 0) {
1991                 tv = clicked_routeview;
1992         } else if (!selection->tracks.empty()) {
1993                 if ((tv = dynamic_cast<RouteTimeAxisView*>(selection->tracks.front())) == 0) {
1994                         return;
1995                 }
1996         } else if (entered_track != 0) {
1997                 if ((tv = dynamic_cast<RouteTimeAxisView*>(entered_track)) == 0) {
1998                         return;
1999                 }
2000         } else {
2001                 return;
2002         }
2003
2004         if ((playlist = tv->playlist()) == 0) {
2005                 return;
2006         }
2007
2008         boost::shared_ptr<Region> region = _regions->get_single_selection ();
2009         if (region == 0) {
2010                 return;
2011         }
2012
2013         begin_reversible_command (_("insert region"));
2014         playlist->clear_changes ();
2015         playlist->add_region ((RegionFactory::create (region, true)), get_preferred_edit_position(), times);
2016         _session->add_command(new StatefulDiffCommand (playlist));
2017         commit_reversible_command ();
2018 }
2019
2020 /* BUILT-IN EFFECTS */
2021
2022 void
2023 Editor::reverse_selection ()
2024 {
2025
2026 }
2027
2028 /* GAIN ENVELOPE EDITING */
2029
2030 void
2031 Editor::edit_envelope ()
2032 {
2033 }
2034
2035 /* PLAYBACK */
2036
2037 void
2038 Editor::transition_to_rolling (bool fwd)
2039 {
2040         if (!_session) {
2041                 return;
2042         }
2043
2044         if (_session->config.get_external_sync()) {
2045                 switch (_session->config.get_sync_source()) {
2046                 case JACK:
2047                         break;
2048                 default:
2049                         /* transport controlled by the master */
2050                         return;
2051                 }
2052         }
2053
2054         if (_session->is_auditioning()) {
2055                 _session->cancel_audition ();
2056                 return;
2057         }
2058
2059         _session->request_transport_speed (fwd ? 1.0f : -1.0f);
2060 }
2061
2062 void
2063 Editor::play_from_start ()
2064 {
2065         _session->request_locate (_session->current_start_frame(), true);
2066 }
2067
2068 void
2069 Editor::play_from_edit_point ()
2070 {
2071         _session->request_locate (get_preferred_edit_position(), true);
2072 }
2073
2074 void
2075 Editor::play_from_edit_point_and_return ()
2076 {
2077         framepos_t start_frame;
2078         framepos_t return_frame;
2079
2080         start_frame = get_preferred_edit_position (true);
2081
2082         if (_session->transport_rolling()) {
2083                 _session->request_locate (start_frame, false);
2084                 return;
2085         }
2086
2087         /* don't reset the return frame if its already set */
2088
2089         if ((return_frame = _session->requested_return_frame()) < 0) {
2090                 return_frame = _session->audible_frame();
2091         }
2092
2093         if (start_frame >= 0) {
2094                 _session->request_roll_at_and_return (start_frame, return_frame);
2095         }
2096 }
2097
2098 void
2099 Editor::play_selection ()
2100 {
2101         if (selection->time.empty()) {
2102                 return;
2103         }
2104
2105         _session->request_play_range (&selection->time, true);
2106 }
2107
2108 void
2109 Editor::play_location (Location& location)
2110 {
2111         if (location.start() <= location.end()) {
2112                 return;
2113         }
2114
2115         _session->request_bounded_roll (location.start(), location.end());
2116 }
2117
2118 void
2119 Editor::loop_location (Location& location)
2120 {
2121         if (location.start() <= location.end()) {
2122                 return;
2123         }
2124
2125         Location* tll;
2126
2127         if ((tll = transport_loop_location()) != 0) {
2128                 tll->set (location.start(), location.end());
2129
2130                 // enable looping, reposition and start rolling
2131                 _session->request_play_loop (true);
2132                 _session->request_locate (tll->start(), true);
2133         }
2134 }
2135
2136 void
2137 Editor::do_layer_operation (LayerOperation op)
2138 {
2139         if (selection->regions.empty ()) {
2140                 return;
2141         }
2142
2143         bool const multiple = selection->regions.size() > 1;
2144         switch (op) {
2145         case Raise:
2146                 if (multiple) {
2147                         begin_reversible_command (_("raise regions"));
2148                 } else {
2149                         begin_reversible_command (_("raise region"));
2150                 }
2151                 break;
2152
2153         case RaiseToTop:
2154                 if (multiple) {
2155                         begin_reversible_command (_("raise regions to top"));
2156                 } else {
2157                         begin_reversible_command (_("raise region to top"));
2158                 }
2159                 break;
2160                 
2161         case Lower:
2162                 if (multiple) {
2163                         begin_reversible_command (_("lower regions"));
2164                 } else {
2165                         begin_reversible_command (_("lower region"));
2166                 }
2167                 break;
2168                 
2169         case LowerToBottom:
2170                 if (multiple) {
2171                         begin_reversible_command (_("lower regions to bottom"));
2172                 } else {
2173                         begin_reversible_command (_("lower region"));
2174                 }
2175                 break;
2176         }
2177
2178         set<boost::shared_ptr<Playlist> > playlists = selection->regions.playlists ();
2179         for (set<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2180                 (*i)->clear_owned_changes ();
2181         }
2182         
2183         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
2184                 boost::shared_ptr<Region> r = (*i)->region ();
2185                 switch (op) {
2186                 case Raise:
2187                         r->raise ();
2188                         break;
2189                 case RaiseToTop:
2190                         r->raise_to_top ();
2191                         break;
2192                 case Lower:
2193                         r->lower ();
2194                         break;
2195                 case LowerToBottom:
2196                         r->lower_to_bottom ();
2197                 }
2198         }
2199
2200         for (set<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2201                 vector<Command*> cmds;
2202                 (*i)->rdiff (cmds);
2203                 _session->add_commands (cmds);
2204         }
2205         
2206         commit_reversible_command ();
2207 }
2208
2209 void
2210 Editor::raise_region ()
2211 {
2212         do_layer_operation (Raise);
2213 }
2214
2215 void
2216 Editor::raise_region_to_top ()
2217 {
2218         do_layer_operation (RaiseToTop);
2219 }
2220
2221 void
2222 Editor::lower_region ()
2223 {
2224         do_layer_operation (Lower);
2225 }
2226
2227 void
2228 Editor::lower_region_to_bottom ()
2229 {
2230         do_layer_operation (LowerToBottom);
2231 }
2232
2233 /** Show the region editor for the selected regions */
2234 void
2235 Editor::show_region_properties ()
2236 {
2237         selection->foreach_regionview (&RegionView::show_region_editor);
2238 }
2239
2240 /** Show the midi list editor for the selected MIDI regions */
2241 void
2242 Editor::show_midi_list_editor ()
2243 {
2244         selection->foreach_midi_regionview (&MidiRegionView::show_list_editor);
2245 }
2246
2247 void
2248 Editor::rename_region ()
2249 {
2250         RegionSelection rs = get_regions_from_selection_and_entered ();
2251
2252         if (rs.empty()) {
2253                 return;
2254         }
2255
2256         ArdourDialog d (*this, _("Rename Region"), true, false);
2257         Entry entry;
2258         Label label (_("New name:"));
2259         HBox hbox;
2260
2261         hbox.set_spacing (6);
2262         hbox.pack_start (label, false, false);
2263         hbox.pack_start (entry, true, true);
2264
2265         d.get_vbox()->set_border_width (12);
2266         d.get_vbox()->pack_start (hbox, false, false);
2267
2268         d.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2269         d.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
2270
2271         d.set_size_request (300, -1);
2272         d.set_position (Gtk::WIN_POS_MOUSE);
2273
2274         entry.set_text (rs.front()->region()->name());
2275         entry.select_region (0, -1);
2276
2277         entry.signal_activate().connect (sigc::bind (sigc::mem_fun (d, &Dialog::response), RESPONSE_OK));
2278
2279         d.show_all ();
2280
2281         entry.grab_focus();
2282
2283         int const ret = d.run();
2284
2285         d.hide ();
2286
2287         if (ret != RESPONSE_OK) {
2288                 return;
2289         }
2290
2291         std::string str = entry.get_text();
2292         strip_whitespace_edges (str);
2293         if (!str.empty()) {
2294                 rs.front()->region()->set_name (str);
2295                 _regions->redisplay ();
2296         }
2297 }
2298
2299 void
2300 Editor::audition_playlist_region_via_route (boost::shared_ptr<Region> region, Route& route)
2301 {
2302         if (_session->is_auditioning()) {
2303                 _session->cancel_audition ();
2304         }
2305
2306         // note: some potential for creativity here, because region doesn't
2307         // have to belong to the playlist that Route is handling
2308
2309         // bool was_soloed = route.soloed();
2310
2311         route.set_solo (true, this);
2312
2313         _session->request_bounded_roll (region->position(), region->position() + region->length());
2314
2315         /* XXX how to unset the solo state ? */
2316 }
2317
2318 /** Start an audition of the first selected region */
2319 void
2320 Editor::play_edit_range ()
2321 {
2322         framepos_t start, end;
2323
2324         if (get_edit_op_range (start, end)) {
2325                 _session->request_bounded_roll (start, end);
2326         }
2327 }
2328
2329 void
2330 Editor::play_selected_region ()
2331 {
2332         framepos_t start = max_framepos;
2333         framepos_t end = 0;
2334
2335         RegionSelection rs = get_regions_from_selection_and_entered ();
2336
2337         if (rs.empty()) {
2338                 return;
2339         }
2340
2341         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2342                 if ((*i)->region()->position() < start) {
2343                         start = (*i)->region()->position();
2344                 }
2345                 if ((*i)->region()->last_frame() + 1 > end) {
2346                         end = (*i)->region()->last_frame() + 1;
2347                 }
2348         }
2349
2350         _session->request_bounded_roll (start, end);
2351 }
2352
2353 void
2354 Editor::audition_playlist_region_standalone (boost::shared_ptr<Region> region)
2355 {
2356         _session->audition_region (region);
2357 }
2358
2359 void
2360 Editor::region_from_selection ()
2361 {
2362         if (clicked_axisview == 0) {
2363                 return;
2364         }
2365
2366         if (selection->time.empty()) {
2367                 return;
2368         }
2369
2370         framepos_t start = selection->time[clicked_selection].start;
2371         framepos_t end = selection->time[clicked_selection].end;
2372
2373         TrackViewList tracks = get_tracks_for_range_action ();
2374
2375         framepos_t selection_cnt = end - start + 1;
2376
2377         for (TrackSelection::iterator i = tracks.begin(); i != tracks.end(); ++i) {
2378                 boost::shared_ptr<Region> current;
2379                 boost::shared_ptr<Playlist> pl;
2380                 framepos_t internal_start;
2381                 string new_name;
2382
2383                 if ((pl = (*i)->playlist()) == 0) {
2384                         continue;
2385                 }
2386
2387                 if ((current = pl->top_region_at (start)) == 0) {
2388                         continue;
2389                 }
2390
2391                 internal_start = start - current->position();
2392                 RegionFactory::region_name (new_name, current->name(), true);
2393
2394                 PropertyList plist;
2395
2396                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2397                 plist.add (ARDOUR::Properties::length, selection_cnt);
2398                 plist.add (ARDOUR::Properties::name, new_name);
2399                 plist.add (ARDOUR::Properties::layer, 0);
2400
2401                 boost::shared_ptr<Region> region (RegionFactory::create (current, plist));
2402         }
2403 }
2404
2405 void
2406 Editor::create_region_from_selection (vector<boost::shared_ptr<Region> >& new_regions)
2407 {
2408         if (selection->time.empty() || selection->tracks.empty()) {
2409                 return;
2410         }
2411
2412         framepos_t start = selection->time[clicked_selection].start;
2413         framepos_t end = selection->time[clicked_selection].end;
2414
2415         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
2416         sort_track_selection (ts);
2417
2418         for (TrackSelection::iterator i = ts.begin(); i != ts.end(); ++i) {
2419                 boost::shared_ptr<Region> current;
2420                 boost::shared_ptr<Playlist> playlist;
2421                 framepos_t internal_start;
2422                 string new_name;
2423
2424                 if ((playlist = (*i)->playlist()) == 0) {
2425                         continue;
2426                 }
2427
2428                 if ((current = playlist->top_region_at(start)) == 0) {
2429                         continue;
2430                 }
2431
2432                 internal_start = start - current->position();
2433                 RegionFactory::region_name (new_name, current->name(), true);
2434
2435                 PropertyList plist;
2436
2437                 plist.add (ARDOUR::Properties::start, current->start() + internal_start);
2438                 plist.add (ARDOUR::Properties::length, end - start + 1);
2439                 plist.add (ARDOUR::Properties::name, new_name);
2440
2441                 new_regions.push_back (RegionFactory::create (current, plist));
2442         }
2443 }
2444
2445 void
2446 Editor::split_multichannel_region ()
2447 {
2448         RegionSelection rs = get_regions_from_selection_and_entered ();
2449
2450         if (rs.empty()) {
2451                 return;
2452         }
2453
2454         vector< boost::shared_ptr<Region> > v;
2455
2456         for (list<RegionView*>::iterator x = rs.begin(); x != rs.end(); ++x) {
2457                 (*x)->region()->separate_by_channel (*_session, v);
2458         }
2459 }
2460
2461 void
2462 Editor::new_region_from_selection ()
2463 {
2464         region_from_selection ();
2465         cancel_selection ();
2466 }
2467
2468 static void
2469 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
2470 {
2471         switch (rv->region()->coverage (ar->start, ar->end - 1)) {
2472         case OverlapNone:
2473                 break;
2474         default:
2475                 rs->push_back (rv);
2476         }
2477 }
2478
2479 /** Return either:
2480  *    - selected tracks, or if there are none...
2481  *    - tracks containing selected regions, or if there are none...
2482  *    - all tracks
2483  * @return tracks.
2484  */
2485 TrackViewList
2486 Editor::get_tracks_for_range_action () const
2487 {
2488         TrackViewList t;
2489
2490         if (selection->tracks.empty()) {
2491
2492                 /* use tracks with selected regions */
2493
2494                 RegionSelection rs = selection->regions;
2495
2496                 for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2497                         TimeAxisView* tv = &(*i)->get_time_axis_view();
2498
2499                         if (!t.contains (tv)) {
2500                                 t.push_back (tv);
2501                         }
2502                 }
2503
2504                 if (t.empty()) {
2505                         /* no regions and no tracks: use all tracks */
2506                         t = track_views;
2507                 }
2508
2509         } else {
2510
2511                 t = selection->tracks;
2512         }
2513
2514         return t.filter_to_unique_playlists();
2515 }
2516
2517 void
2518 Editor::separate_regions_between (const TimeSelection& ts)
2519 {
2520         bool in_command = false;
2521         boost::shared_ptr<Playlist> playlist;
2522         RegionSelection new_selection;
2523
2524         TrackViewList tmptracks = get_tracks_for_range_action ();
2525         sort_track_selection (tmptracks);
2526
2527         for (TrackSelection::iterator i = tmptracks.begin(); i != tmptracks.end(); ++i) {
2528
2529                 RouteTimeAxisView* rtv;
2530
2531                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2532
2533                         if (rtv->is_track()) {
2534
2535                                 /* no edits to destructive tracks */
2536
2537                                 if (rtv->track()->destructive()) {
2538                                         continue;
2539                                 }
2540
2541                                 if ((playlist = rtv->playlist()) != 0) {
2542
2543                                         playlist->clear_changes ();
2544
2545                                         /* XXX need to consider musical time selections here at some point */
2546
2547                                         double speed = rtv->track()->speed();
2548
2549
2550                                         for (list<AudioRange>::const_iterator t = ts.begin(); t != ts.end(); ++t) {
2551
2552                                                 sigc::connection c = rtv->view()->RegionViewAdded.connect (
2553                                                                 sigc::mem_fun(*this, &Editor::collect_new_region_view));
2554
2555                                                 latest_regionviews.clear ();
2556
2557                                                 playlist->partition ((framepos_t)((*t).start * speed),
2558                                                                 (framepos_t)((*t).end * speed), false);
2559
2560                                                 c.disconnect ();
2561
2562                                                 if (!latest_regionviews.empty()) {
2563
2564                                                         rtv->view()->foreach_regionview (sigc::bind (
2565                                                                                 sigc::ptr_fun (add_if_covered),
2566                                                                                 &(*t), &new_selection));
2567
2568                                                         if (!in_command) {
2569                                                                 begin_reversible_command (_("separate"));
2570                                                                 in_command = true;
2571                                                         }
2572
2573                                                         /* pick up changes to existing regions */
2574
2575                                                         vector<Command*> cmds;
2576                                                         playlist->rdiff (cmds);
2577                                                         _session->add_commands (cmds);
2578
2579                                                         /* pick up changes to the playlist itself (adds/removes)
2580                                                          */
2581
2582                                                         _session->add_command(new StatefulDiffCommand (playlist));
2583                                                 }
2584                                         }
2585                                 }
2586                         }
2587                 }
2588         }
2589
2590         if (in_command) {
2591                 selection->set (new_selection);
2592                 set_mouse_mode (MouseObject);
2593
2594                 commit_reversible_command ();
2595         }
2596 }
2597
2598 struct PlaylistState {
2599     boost::shared_ptr<Playlist> playlist;
2600     XMLNode*  before;
2601 };
2602
2603 /** Take tracks from get_tracks_for_range_action and cut any regions
2604  *  on those tracks so that the tracks are empty over the time
2605  *  selection.
2606  */
2607 void
2608 Editor::separate_region_from_selection ()
2609 {
2610         /* preferentially use *all* ranges in the time selection if we're in range mode
2611            to allow discontiguous operation, since get_edit_op_range() currently
2612            returns a single range.
2613         */
2614
2615         if (mouse_mode == MouseRange && !selection->time.empty()) {
2616
2617                 separate_regions_between (selection->time);
2618
2619         } else {
2620
2621                 framepos_t start;
2622                 framepos_t end;
2623
2624                 if (get_edit_op_range (start, end)) {
2625
2626                         AudioRange ar (start, end, 1);
2627                         TimeSelection ts;
2628                         ts.push_back (ar);
2629
2630                         separate_regions_between (ts);
2631                 }
2632         }
2633 }
2634
2635 void
2636 Editor::separate_region_from_punch ()
2637 {
2638         Location* loc  = _session->locations()->auto_punch_location();
2639         if (loc) {
2640                 separate_regions_using_location (*loc);
2641         }
2642 }
2643
2644 void
2645 Editor::separate_region_from_loop ()
2646 {
2647         Location* loc  = _session->locations()->auto_loop_location();
2648         if (loc) {
2649                 separate_regions_using_location (*loc);
2650         }
2651 }
2652
2653 void
2654 Editor::separate_regions_using_location (Location& loc)
2655 {
2656         if (loc.is_mark()) {
2657                 return;
2658         }
2659
2660         AudioRange ar (loc.start(), loc.end(), 1);
2661         TimeSelection ts;
2662
2663         ts.push_back (ar);
2664
2665         separate_regions_between (ts);
2666 }
2667
2668 /** Separate regions under the selected region */
2669 void
2670 Editor::separate_under_selected_regions ()
2671 {
2672         vector<PlaylistState> playlists;
2673
2674         RegionSelection rs;
2675
2676         rs = get_regions_from_selection_and_entered();
2677
2678         if (!_session || rs.empty()) {
2679                 return;
2680         }
2681
2682         begin_reversible_command (_("separate region under"));
2683
2684         list<boost::shared_ptr<Region> > regions_to_remove;
2685
2686         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2687                 // we can't just remove the region(s) in this loop because
2688                 // this removes them from the RegionSelection, and they thus
2689                 // disappear from underneath the iterator, and the ++i above
2690                 // SEGVs in a puzzling fashion.
2691
2692                 // so, first iterate over the regions to be removed from rs and
2693                 // add them to the regions_to_remove list, and then
2694                 // iterate over the list to actually remove them.
2695
2696                 regions_to_remove.push_back ((*i)->region());
2697         }
2698
2699         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
2700
2701                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
2702
2703                 if (!playlist) {
2704                         // is this check necessary?
2705                         continue;
2706                 }
2707
2708                 vector<PlaylistState>::iterator i;
2709
2710                 //only take state if this is a new playlist.
2711                 for (i = playlists.begin(); i != playlists.end(); ++i) {
2712                         if ((*i).playlist == playlist) {
2713                                 break;
2714                         }
2715                 }
2716
2717                 if (i == playlists.end()) {
2718
2719                         PlaylistState before;
2720                         before.playlist = playlist;
2721                         before.before = &playlist->get_state();
2722
2723                         playlist->freeze ();
2724                         playlists.push_back(before);
2725                 }
2726
2727                 //Partition on the region bounds
2728                 playlist->partition ((*rl)->first_frame() - 1, (*rl)->last_frame() + 1, true);
2729
2730                 //Re-add region that was just removed due to the partition operation
2731                 playlist->add_region( (*rl), (*rl)->first_frame() );
2732         }
2733
2734         vector<PlaylistState>::iterator pl;
2735
2736         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
2737                 (*pl).playlist->thaw ();
2738                 _session->add_command(new MementoCommand<Playlist>(*(*pl).playlist, (*pl).before, &(*pl).playlist->get_state()));
2739         }
2740
2741         commit_reversible_command ();
2742 }
2743
2744 void
2745 Editor::crop_region_to_selection ()
2746 {
2747         if (!selection->time.empty()) {
2748
2749                 crop_region_to (selection->time.start(), selection->time.end_frame());
2750
2751         } else {
2752
2753                 framepos_t start;
2754                 framepos_t end;
2755
2756                 if (get_edit_op_range (start, end)) {
2757                         crop_region_to (start, end);
2758                 }
2759         }
2760
2761 }
2762
2763 void
2764 Editor::crop_region_to (framepos_t start, framepos_t end)
2765 {
2766         vector<boost::shared_ptr<Playlist> > playlists;
2767         boost::shared_ptr<Playlist> playlist;
2768         TrackViewList ts;
2769
2770         if (selection->tracks.empty()) {
2771                 ts = track_views.filter_to_unique_playlists();
2772         } else {
2773                 ts = selection->tracks.filter_to_unique_playlists ();
2774         }
2775
2776         sort_track_selection (ts);
2777
2778         for (TrackSelection::iterator i = ts.begin(); i != ts.end(); ++i) {
2779
2780                 RouteTimeAxisView* rtv;
2781
2782                 if ((rtv = dynamic_cast<RouteTimeAxisView*> ((*i))) != 0) {
2783
2784                         boost::shared_ptr<Track> t = rtv->track();
2785
2786                         if (t != 0 && ! t->destructive()) {
2787
2788                                 if ((playlist = rtv->playlist()) != 0) {
2789                                         playlists.push_back (playlist);
2790                                 }
2791                         }
2792                 }
2793         }
2794
2795         if (playlists.empty()) {
2796                 return;
2797         }
2798
2799         framepos_t the_start;
2800         framepos_t the_end;
2801         framepos_t cnt;
2802
2803         begin_reversible_command (_("trim to selection"));
2804
2805         for (vector<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2806
2807                 boost::shared_ptr<Region> region;
2808
2809                 the_start = start;
2810
2811                 if ((region = (*i)->top_region_at(the_start)) == 0) {
2812                         continue;
2813                 }
2814
2815                 /* now adjust lengths to that we do the right thing
2816                    if the selection extends beyond the region
2817                 */
2818
2819                 the_start = max (the_start, (framepos_t) region->position());
2820                 if (max_framepos - the_start < region->length()) {
2821                         the_end = the_start + region->length() - 1;
2822                 } else {
2823                         the_end = max_framepos;
2824                 }
2825                 the_end = min (end, the_end);
2826                 cnt = the_end - the_start + 1;
2827
2828                 region->clear_changes ();
2829                 region->trim_to (the_start, cnt);
2830                 _session->add_command (new StatefulDiffCommand (region));
2831         }
2832
2833         commit_reversible_command ();
2834 }
2835
2836 void
2837 Editor::region_fill_track ()
2838 {
2839         RegionSelection rs = get_regions_from_selection_and_entered ();
2840
2841         if (!_session || rs.empty()) {
2842                 return;
2843         }
2844
2845         framepos_t const end = _session->current_end_frame ();
2846
2847         begin_reversible_command (Operations::region_fill);
2848
2849         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2850
2851                 boost::shared_ptr<Region> region ((*i)->region());
2852
2853                 boost::shared_ptr<Playlist> pl = region->playlist();
2854
2855                 if (end <= region->last_frame()) {
2856                         return;
2857                 }
2858
2859                 double times = (double) (end - region->last_frame()) / (double) region->length();
2860
2861                 if (times == 0) {
2862                         return;
2863                 }
2864
2865                 pl->clear_changes ();
2866                 pl->add_region (RegionFactory::create (region, true), region->last_frame(), times);
2867                 _session->add_command (new StatefulDiffCommand (pl));
2868         }
2869
2870         commit_reversible_command ();
2871 }
2872
2873 void
2874 Editor::region_fill_selection ()
2875 {
2876         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
2877                 return;
2878         }
2879
2880         if (selection->time.empty()) {
2881                 return;
2882         }
2883
2884         boost::shared_ptr<Region> region = _regions->get_single_selection ();
2885         if (region == 0) {
2886                 return;
2887         }
2888
2889         framepos_t start = selection->time[clicked_selection].start;
2890         framepos_t end = selection->time[clicked_selection].end;
2891
2892         boost::shared_ptr<Playlist> playlist;
2893
2894         if (selection->tracks.empty()) {
2895                 return;
2896         }
2897
2898         framepos_t selection_length = end - start;
2899         float times = (float)selection_length / region->length();
2900
2901         begin_reversible_command (Operations::fill_selection);
2902
2903         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
2904
2905         for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
2906
2907                 if ((playlist = (*i)->playlist()) == 0) {
2908                         continue;
2909                 }
2910
2911                 playlist->clear_changes ();
2912                 playlist->add_region (RegionFactory::create (region, true), start, times);
2913                 _session->add_command (new StatefulDiffCommand (playlist));
2914         }
2915
2916         commit_reversible_command ();
2917 }
2918
2919 void
2920 Editor::set_region_sync_position ()
2921 {
2922         set_sync_point (get_preferred_edit_position (), get_regions_from_selection_and_edit_point ());
2923 }
2924
2925 void
2926 Editor::set_sync_point (framepos_t where, const RegionSelection& rs)
2927 {
2928         bool in_command = false;
2929
2930         for (RegionSelection::const_iterator r = rs.begin(); r != rs.end(); ++r) {
2931
2932                 if (!(*r)->region()->covers (where)) {
2933                         continue;
2934                 }
2935
2936                 boost::shared_ptr<Region> region ((*r)->region());
2937
2938                 if (!in_command) {
2939                         begin_reversible_command (_("set sync point"));
2940                         in_command = true;
2941                 }
2942
2943                 region->clear_changes ();
2944                 region->set_sync_position (where);
2945                 _session->add_command(new StatefulDiffCommand (region));
2946         }
2947
2948         if (in_command) {
2949                 commit_reversible_command ();
2950         }
2951 }
2952
2953 /** Remove the sync positions of the selection */
2954 void
2955 Editor::remove_region_sync ()
2956 {
2957         RegionSelection rs = get_regions_from_selection_and_entered ();
2958
2959         if (rs.empty()) {
2960                 return;
2961         }
2962
2963         begin_reversible_command (_("remove region sync"));
2964
2965         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2966
2967                 (*i)->region()->clear_changes ();
2968                 (*i)->region()->clear_sync_position ();
2969                 _session->add_command(new StatefulDiffCommand ((*i)->region()));
2970         }
2971
2972         commit_reversible_command ();
2973 }
2974
2975 void
2976 Editor::naturalize_region ()
2977 {
2978         RegionSelection rs = get_regions_from_selection_and_entered ();
2979
2980         if (rs.empty()) {
2981                 return;
2982         }
2983
2984         if (rs.size() > 1) {
2985                 begin_reversible_command (_("move regions to original position"));
2986         } else {
2987                 begin_reversible_command (_("move region to original position"));
2988         }
2989
2990         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
2991                 (*i)->region()->clear_changes ();
2992                 (*i)->region()->move_to_natural_position ();
2993                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
2994         }
2995
2996         commit_reversible_command ();
2997 }
2998
2999 void
3000 Editor::align_regions (RegionPoint what)
3001 {
3002         RegionSelection const rs = get_regions_from_selection_and_edit_point ();
3003
3004         if (rs.empty()) {
3005                 return;
3006         }
3007
3008         begin_reversible_command (_("align selection"));
3009
3010         framepos_t const position = get_preferred_edit_position ();
3011
3012         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
3013                 align_region_internal ((*i)->region(), what, position);
3014         }
3015
3016         commit_reversible_command ();
3017 }
3018
3019 struct RegionSortByTime {
3020     bool operator() (const RegionView* a, const RegionView* b) {
3021             return a->region()->position() < b->region()->position();
3022     }
3023 };
3024
3025 void
3026 Editor::align_regions_relative (RegionPoint point)
3027 {
3028         RegionSelection const rs = get_regions_from_selection_and_edit_point ();
3029
3030         if (rs.empty()) {
3031                 return;
3032         }
3033
3034         framepos_t const position = get_preferred_edit_position ();
3035
3036         framepos_t distance = 0;
3037         framepos_t pos = 0;
3038         int dir = 1;
3039
3040         list<RegionView*> sorted;
3041         rs.by_position (sorted);
3042
3043         boost::shared_ptr<Region> r ((*sorted.begin())->region());
3044
3045         switch (point) {
3046         case Start:
3047                 pos = position;
3048                 if (position > r->position()) {
3049                         distance = position - r->position();
3050                 } else {
3051                         distance = r->position() - position;
3052                         dir = -1;
3053                 }
3054                 break;
3055
3056         case End:
3057                 if (position > r->last_frame()) {
3058                         distance = position - r->last_frame();
3059                         pos = r->position() + distance;
3060                 } else {
3061                         distance = r->last_frame() - position;
3062                         pos = r->position() - distance;
3063                         dir = -1;
3064                 }
3065                 break;
3066
3067         case SyncPoint:
3068                 pos = r->adjust_to_sync (position);
3069                 if (pos > r->position()) {
3070                         distance = pos - r->position();
3071                 } else {
3072                         distance = r->position() - pos;
3073                         dir = -1;
3074                 }
3075                 break;
3076         }
3077
3078         if (pos == r->position()) {
3079                 return;
3080         }
3081
3082         begin_reversible_command (_("align selection (relative)"));
3083
3084         /* move first one specially */
3085
3086         r->clear_changes ();
3087         r->set_position (pos);
3088         _session->add_command(new StatefulDiffCommand (r));
3089
3090         /* move rest by the same amount */
3091
3092         sorted.pop_front();
3093
3094         for (list<RegionView*>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
3095
3096                 boost::shared_ptr<Region> region ((*i)->region());
3097
3098                 region->clear_changes ();
3099
3100                 if (dir > 0) {
3101                         region->set_position (region->position() + distance);
3102                 } else {
3103                         region->set_position (region->position() - distance);
3104                 }
3105
3106                 _session->add_command(new StatefulDiffCommand (region));
3107
3108         }
3109
3110         commit_reversible_command ();
3111 }
3112
3113 void
3114 Editor::align_region (boost::shared_ptr<Region> region, RegionPoint point, framepos_t position)
3115 {
3116         begin_reversible_command (_("align region"));
3117         align_region_internal (region, point, position);
3118         commit_reversible_command ();
3119 }
3120
3121 void
3122 Editor::align_region_internal (boost::shared_ptr<Region> region, RegionPoint point, framepos_t position)
3123 {
3124         region->clear_changes ();
3125
3126         switch (point) {
3127         case SyncPoint:
3128                 region->set_position (region->adjust_to_sync (position));
3129                 break;
3130
3131         case End:
3132                 if (position > region->length()) {
3133                         region->set_position (position - region->length());
3134                 }
3135                 break;
3136
3137         case Start:
3138                 region->set_position (position);
3139                 break;
3140         }
3141
3142         _session->add_command(new StatefulDiffCommand (region));
3143 }
3144
3145 void
3146 Editor::trim_region_front ()
3147 {
3148         trim_region (true);
3149 }
3150
3151 void
3152 Editor::trim_region_back ()
3153 {
3154         trim_region (false);
3155 }
3156
3157 void
3158 Editor::trim_region (bool front)
3159 {
3160         framepos_t where = get_preferred_edit_position();
3161         RegionSelection rs = get_regions_from_selection_and_edit_point ();
3162
3163         cerr << "trim regions\n";
3164
3165         if (rs.empty()) {
3166                 cerr << " no regions\n";
3167                 return;
3168         }
3169
3170         cerr << "where = " << where << endl;
3171
3172         begin_reversible_command (front ? _("trim front") : _("trim back"));
3173
3174         for (list<RegionView*>::const_iterator i = rs.by_layer().begin(); i != rs.by_layer().end(); ++i) {
3175                 if (!(*i)->region()->locked()) {
3176
3177                         (*i)->region()->clear_changes ();
3178
3179                         if (front) {
3180                                 (*i)->region()->trim_front (where);
3181                         } else {
3182                                 (*i)->region()->trim_end (where);
3183                         }
3184
3185                         _session->add_command (new StatefulDiffCommand ((*i)->region()));
3186                 }
3187         }
3188
3189         commit_reversible_command ();
3190 }
3191
3192 /** Trim the end of the selected regions to the position of the edit cursor */
3193 void
3194 Editor::trim_region_to_loop ()
3195 {
3196         Location* loc = _session->locations()->auto_loop_location();
3197         if (!loc) {
3198                 return;
3199         }
3200         trim_region_to_location (*loc, _("trim to loop"));
3201 }
3202
3203 void
3204 Editor::trim_region_to_punch ()
3205 {
3206         Location* loc = _session->locations()->auto_punch_location();
3207         if (!loc) {
3208                 return;
3209         }
3210         trim_region_to_location (*loc, _("trim to punch"));
3211 }
3212
3213 void
3214 Editor::trim_region_to_location (const Location& loc, const char* str)
3215 {
3216         RegionSelection rs = get_regions_from_selection_and_entered ();
3217
3218         begin_reversible_command (str);
3219
3220         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3221                 RegionView* rv = (*x);
3222
3223                 /* require region to span proposed trim */
3224                 switch (rv->region()->coverage (loc.start(), loc.end())) {
3225                 case OverlapInternal:
3226                         break;
3227                 default:
3228                         continue;
3229                 }
3230
3231                 RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (&rv->get_time_axis_view());
3232                 if (!tav) {
3233                         return;
3234                 }
3235
3236                 float speed = 1.0;
3237                 framepos_t start;
3238                 framepos_t end;
3239
3240                 if (tav->track() != 0) {
3241                         speed = tav->track()->speed();
3242                 }
3243
3244                 start = session_frame_to_track_frame (loc.start(), speed);
3245                 end = session_frame_to_track_frame (loc.end(), speed);
3246
3247                 rv->region()->clear_changes ();
3248                 rv->region()->trim_to (start, (end - start));
3249                 _session->add_command(new StatefulDiffCommand (rv->region()));
3250         }
3251
3252         commit_reversible_command ();
3253 }
3254
3255 void
3256 Editor::trim_region_to_previous_region_end ()
3257 {
3258         return trim_to_region(false);
3259 }
3260
3261 void
3262 Editor::trim_region_to_next_region_start ()
3263 {
3264         return trim_to_region(true);
3265 }
3266
3267 void
3268 Editor::trim_to_region(bool forward)
3269 {
3270         RegionSelection rs = get_regions_from_selection_and_entered ();
3271
3272         begin_reversible_command (_("trim to region"));
3273
3274         boost::shared_ptr<Region> next_region;
3275
3276         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3277
3278                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*x);
3279
3280                 if (!arv) {
3281                         continue;
3282                 }
3283
3284                 AudioTimeAxisView* atav = dynamic_cast<AudioTimeAxisView*> (&arv->get_time_axis_view());
3285
3286                 if (!atav) {
3287                         return;
3288                 }
3289
3290                 float speed = 1.0;
3291
3292                 if (atav->track() != 0) {
3293                         speed = atav->track()->speed();
3294                 }
3295
3296
3297                 boost::shared_ptr<Region> region = arv->region();
3298                 boost::shared_ptr<Playlist> playlist (region->playlist());
3299
3300                 region->clear_changes ();
3301
3302                 if (forward) {
3303
3304                     next_region = playlist->find_next_region (region->first_frame(), Start, 1);
3305
3306                     if (!next_region) {
3307                         continue;
3308                     }
3309
3310                     region->trim_end((framepos_t) ( (next_region->first_frame() - 1) * speed));
3311                     arv->region_changed (PropertyChange (ARDOUR::Properties::length));
3312                 }
3313                 else {
3314
3315                     next_region = playlist->find_next_region (region->first_frame(), Start, 0);
3316
3317                     if(!next_region){
3318                         continue;
3319                     }
3320
3321                     region->trim_front((framepos_t) ((next_region->last_frame() + 1) * speed));
3322
3323                     arv->region_changed (ARDOUR::bounds_change);
3324                 }
3325
3326                 _session->add_command(new StatefulDiffCommand (region));
3327         }
3328
3329         commit_reversible_command ();
3330 }
3331
3332 void
3333 Editor::unfreeze_route ()
3334 {
3335         if (clicked_routeview == 0 || !clicked_routeview->is_track()) {
3336                 return;
3337         }
3338
3339         clicked_routeview->track()->unfreeze ();
3340 }
3341
3342 void*
3343 Editor::_freeze_thread (void* arg)
3344 {
3345         SessionEvent::create_per_thread_pool ("freeze events", 64);
3346
3347         return static_cast<Editor*>(arg)->freeze_thread ();
3348 }
3349
3350 void*
3351 Editor::freeze_thread ()
3352 {
3353         clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
3354         current_interthread_info->done = true;
3355         return 0;
3356 }
3357
3358 void
3359 Editor::freeze_route ()
3360 {
3361         if (!_session) {
3362                 return;
3363         }
3364
3365         /* stop transport before we start. this is important */
3366
3367         _session->request_transport_speed (0.0);
3368
3369         if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
3370                 return;
3371         }
3372
3373         if (!clicked_routeview->track()->bounceable()) {
3374                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_routeview);
3375                 if (rtv && !rtv->track()->bounceable()) {
3376                         MessageDialog d (
3377                                 _("This route cannot be frozen because it has more outputs than inputs.  "
3378                                   "You can fix this by increasing the number of inputs.")
3379                                 );
3380                         d.set_title (_("Cannot freeze"));
3381                         d.run ();
3382                         return;
3383                 }
3384         }
3385
3386         InterThreadInfo itt;
3387         current_interthread_info = &itt;
3388
3389         InterthreadProgressWindow ipw (current_interthread_info, _("Freeze"), _("Cancel Freeze"));
3390
3391         pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
3392
3393         set_canvas_cursor (_cursors->wait);
3394
3395         while (!itt.done && !itt.cancel) {
3396                 gtk_main_iteration ();
3397         }
3398
3399         current_interthread_info = 0;
3400         set_canvas_cursor (current_canvas_cursor);
3401 }
3402
3403 void
3404 Editor::bounce_range_selection (bool replace, bool enable_processing)
3405 {
3406         if (selection->time.empty()) {
3407                 return;
3408         }
3409
3410         TrackSelection views = selection->tracks;
3411
3412         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3413                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
3414                 if (rtv && rtv->track() && replace && enable_processing && !rtv->track()->bounceable()) {
3415                         MessageDialog d (
3416                                 _("You can't perform this operation because the processing of the signal "
3417                                   "will cause one or more of the tracks will end up with a region with more channels than this track has inputs.\n\n"
3418                                   "You can do this without processing, which is a different operation.")
3419                                 );
3420                         d.set_title (_("Cannot bounce"));
3421                         d.run ();
3422                         return;
3423                 }
3424         }
3425
3426         framepos_t start = selection->time[clicked_selection].start;
3427         framepos_t end = selection->time[clicked_selection].end;
3428         framepos_t cnt = end - start + 1;
3429
3430         begin_reversible_command (_("bounce range"));
3431
3432         for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
3433
3434                 RouteTimeAxisView* rtv;
3435
3436                 if ((rtv = dynamic_cast<RouteTimeAxisView*> (*i)) == 0) {
3437                         continue;
3438                 }
3439
3440                 boost::shared_ptr<Playlist> playlist;
3441
3442                 if ((playlist = rtv->playlist()) == 0) {
3443                         return;
3444                 }
3445
3446                 InterThreadInfo itt;
3447
3448                 playlist->clear_changes ();
3449                 playlist->clear_owned_changes ();
3450
3451                 boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
3452
3453                 if (!r) {
3454                         continue;
3455                 }
3456
3457                 if (replace) {
3458                         list<AudioRange> ranges;
3459                         ranges.push_back (AudioRange (start, start+cnt, 0));
3460                         playlist->cut (ranges); // discard result
3461                         playlist->add_region (r, start);
3462                 }
3463
3464                 vector<Command*> cmds;
3465                 playlist->rdiff (cmds);
3466                 _session->add_commands (cmds);
3467
3468                 _session->add_command (new StatefulDiffCommand (playlist));
3469         }
3470
3471         commit_reversible_command ();
3472 }
3473
3474 /** Delete selected regions, automation points or a time range */
3475 void
3476 Editor::delete_ ()
3477 {
3478         cut_copy (Delete);
3479 }
3480
3481 /** Cut selected regions, automation points or a time range */
3482 void
3483 Editor::cut ()
3484 {
3485         cut_copy (Cut);
3486 }
3487
3488 /** Copy selected regions, automation points or a time range */
3489 void
3490 Editor::copy ()
3491 {
3492         cut_copy (Copy);
3493 }
3494
3495
3496 /** @return true if a Cut, Copy or Clear is possible */
3497 bool
3498 Editor::can_cut_copy () const
3499 {
3500         switch (current_mouse_mode()) {
3501
3502         case MouseObject:
3503                 if (!selection->regions.empty() || !selection->points.empty()) {
3504                         return true;
3505                 }
3506                 break;
3507
3508         case MouseRange:
3509                 if (!selection->time.empty()) {
3510                         return true;
3511                 }
3512                 break;
3513
3514         default:
3515                 break;
3516         }
3517
3518         return false;
3519 }
3520
3521
3522 /** Cut, copy or clear selected regions, automation points or a time range.
3523  * @param op Operation (Cut, Copy or Clear)
3524  */
3525 void
3526 Editor::cut_copy (CutCopyOp op)
3527 {
3528         /* only cancel selection if cut/copy is successful.*/
3529
3530         string opname;
3531
3532         switch (op) {
3533         case Delete:
3534                 opname = _("delete");
3535                 break;
3536         case Cut:
3537                 opname = _("cut");
3538                 break;
3539         case Copy:
3540                 opname = _("copy");
3541                 break;
3542         case Clear:
3543                 opname = _("clear");
3544                 break;
3545         }
3546
3547         /* if we're deleting something, and the mouse is still pressed,
3548            the thing we started a drag for will be gone when we release
3549            the mouse button(s). avoid this. see part 2 at the end of
3550            this function.
3551         */
3552
3553         if (op == Delete || op == Cut || op == Clear) {
3554                 if (_drags->active ()) {
3555                         _drags->abort ();
3556                 }
3557         }
3558
3559         cut_buffer->clear ();
3560
3561         if (entered_marker) {
3562
3563                 /* cut/delete op while pointing at a marker */
3564
3565                 bool ignored;
3566                 Location* loc = find_location_from_marker (entered_marker, ignored);
3567
3568                 if (_session && loc) {
3569                         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun(*this, &Editor::really_remove_marker), loc));
3570                 }
3571
3572                 _drags->abort ();
3573                 return;
3574         }
3575
3576         if (internal_editing()) {
3577
3578                 switch (current_mouse_mode()) {
3579                 case MouseObject:
3580                 case MouseRange:
3581                         cut_copy_midi (op);
3582                         break;
3583                 default:
3584                         break;
3585                 }
3586
3587         } else {
3588
3589                 RegionSelection rs;
3590
3591                 /* we only want to cut regions if some are selected */
3592
3593                 switch (current_mouse_mode()) {
3594                 case MouseObject:
3595                         rs = get_regions_from_selection ();
3596                         if (!rs.empty() || !selection->points.empty()) {
3597
3598                                 begin_reversible_command (opname + _(" objects"));
3599
3600                                 if (!rs.empty()) {
3601                                         cut_copy_regions (op, rs);
3602
3603                                         if (op == Cut || op == Delete) {
3604                                                 selection->clear_regions ();
3605                                         }
3606                                 }
3607
3608                                 if (!selection->points.empty()) {
3609                                         cut_copy_points (op);
3610
3611                                         if (op == Cut || op == Delete) {
3612                                                 selection->clear_points ();
3613                                         }
3614                                 }
3615                                 commit_reversible_command ();
3616                                 break; // terminate case statement here
3617                         }
3618                         if (!selection->time.empty()) {
3619                                 /* don't cause suprises */
3620                                 break;
3621                         }
3622                         // fall thru if there was nothing selected
3623
3624                 case MouseRange:
3625                         if (selection->time.empty()) {
3626                                 framepos_t start, end;
3627                                 if (!get_edit_op_range (start, end)) {
3628                                         return;
3629                                 }
3630                                 selection->set (start, end);
3631                         }
3632
3633                         begin_reversible_command (opname + _(" range"));
3634                         cut_copy_ranges (op);
3635                         commit_reversible_command ();
3636
3637                         if (op == Cut || op == Delete) {
3638                                 selection->clear_time ();
3639                         }
3640
3641                         break;
3642
3643                 default:
3644                         break;
3645                 }
3646         }
3647
3648         if (op == Delete || op == Cut || op == Clear) {
3649                 _drags->abort ();
3650         }
3651 }
3652
3653 /** Cut, copy or clear selected automation points.
3654  * @param op Operation (Cut, Copy or Clear)
3655  */
3656 void
3657 Editor::cut_copy_points (CutCopyOp op)
3658 {
3659         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
3660
3661                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
3662                 _last_cut_copy_source_track = atv;
3663
3664                 if (atv) {
3665                         atv->cut_copy_clear_objects (selection->points, op);
3666                 }
3667         }
3668 }
3669
3670 /** Cut, copy or clear selected automation points.
3671  * @param op Operation (Cut, Copy or Clear)
3672  */
3673 void
3674 Editor::cut_copy_midi (CutCopyOp op)
3675 {
3676         for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
3677                 MidiRegionView* mrv = *i;
3678                 mrv->cut_copy_clear (op);
3679         }
3680 }
3681
3682
3683
3684 struct lt_playlist {
3685     bool operator () (const PlaylistState& a, const PlaylistState& b) {
3686             return a.playlist < b.playlist;
3687     }
3688 };
3689
3690 struct PlaylistMapping {
3691     TimeAxisView* tv;
3692     boost::shared_ptr<Playlist> pl;
3693
3694     PlaylistMapping (TimeAxisView* tvp) : tv (tvp) {}
3695 };
3696
3697 /** Remove `clicked_regionview' */
3698 void
3699 Editor::remove_clicked_region ()
3700 {
3701         if (clicked_routeview == 0 || clicked_regionview == 0) {
3702                 return;
3703         }
3704
3705         boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
3706
3707         begin_reversible_command (_("remove region"));
3708         playlist->clear_changes ();
3709         playlist->remove_region (clicked_regionview->region());
3710         _session->add_command(new StatefulDiffCommand (playlist));
3711         commit_reversible_command ();
3712 }
3713
3714
3715 /** Remove the selected regions */
3716 void
3717 Editor::remove_selected_regions ()
3718 {
3719         RegionSelection rs = get_regions_from_selection_and_entered ();
3720
3721         if (!_session || rs.empty()) {
3722                 return;
3723         }
3724
3725         begin_reversible_command (_("remove region"));
3726
3727         list<boost::shared_ptr<Region> > regions_to_remove;
3728
3729         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
3730                 // we can't just remove the region(s) in this loop because
3731                 // this removes them from the RegionSelection, and they thus
3732                 // disappear from underneath the iterator, and the ++i above
3733                 // SEGVs in a puzzling fashion.
3734
3735                 // so, first iterate over the regions to be removed from rs and
3736                 // add them to the regions_to_remove list, and then
3737                 // iterate over the list to actually remove them.
3738
3739                 regions_to_remove.push_back ((*i)->region());
3740         }
3741
3742         vector<boost::shared_ptr<Playlist> > playlists;
3743
3744         for (list<boost::shared_ptr<Region> >::iterator rl = regions_to_remove.begin(); rl != regions_to_remove.end(); ++rl) {
3745
3746                 boost::shared_ptr<Playlist> playlist = (*rl)->playlist();
3747
3748                 if (!playlist) {
3749                         // is this check necessary?
3750                         continue;
3751                 }
3752
3753                 /* get_regions_from_selection_and_entered() guarantees that
3754                    the playlists involved are unique, so there is no need
3755                    to check here.
3756                 */
3757
3758                 playlists.push_back (playlist);
3759
3760                 playlist->clear_changes ();
3761                 playlist->freeze ();
3762                 playlist->remove_region (*rl);
3763         }
3764
3765         vector<boost::shared_ptr<Playlist> >::iterator pl;
3766
3767         for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
3768                 (*pl)->thaw ();
3769                 _session->add_command(new StatefulDiffCommand (*pl));
3770         }
3771
3772         commit_reversible_command ();
3773 }
3774
3775 /** Cut, copy or clear selected regions.
3776  * @param op Operation (Cut, Copy or Clear)
3777  */
3778 void
3779 Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
3780 {
3781         /* we can't use a std::map here because the ordering is important, and we can't trivially sort
3782            a map when we want ordered access to both elements. i think.
3783         */
3784
3785         vector<PlaylistMapping> pmap;
3786
3787         framepos_t first_position = max_framepos;
3788
3789         typedef set<boost::shared_ptr<Playlist> > FreezeList;
3790         FreezeList freezelist;
3791
3792         /* get ordering correct before we cut/copy */
3793
3794         rs.sort_by_position_and_track ();
3795
3796         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
3797
3798                 first_position = min ((framepos_t) (*x)->region()->position(), first_position);
3799
3800                 if (op == Cut || op == Clear || op == Delete) {
3801                         boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3802
3803                         if (pl) {
3804                                 FreezeList::iterator fl;
3805
3806                                 // only take state if this is a new playlist.
3807                                 for (fl = freezelist.begin(); fl != freezelist.end(); ++fl) {
3808                                         if ((*fl) == pl) {
3809                                                 break;
3810                                         }
3811                                 }
3812
3813                                 if (fl == freezelist.end()) {
3814                                         pl->clear_changes();
3815                                         pl->freeze ();
3816                                         freezelist.insert (pl);
3817                                 }
3818                         }
3819                 }
3820
3821                 TimeAxisView* tv = &(*x)->get_time_axis_view();
3822                 vector<PlaylistMapping>::iterator z;
3823
3824                 for (z = pmap.begin(); z != pmap.end(); ++z) {
3825                         if ((*z).tv == tv) {
3826                                 break;
3827                         }
3828                 }
3829
3830                 if (z == pmap.end()) {
3831                         pmap.push_back (PlaylistMapping (tv));
3832                 }
3833         }
3834
3835         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ) {
3836
3837                 boost::shared_ptr<Playlist> pl = (*x)->region()->playlist();
3838
3839                 if (!pl) {
3840                         /* region not yet associated with a playlist (e.g. unfinished
3841                            capture pass.
3842                         */
3843                         ++x;
3844                         continue;
3845                 }
3846
3847                 TimeAxisView& tv = (*x)->get_time_axis_view();
3848                 boost::shared_ptr<Playlist> npl;
3849                 RegionSelection::iterator tmp;
3850
3851                 tmp = x;
3852                 ++tmp;
3853
3854                 if (op != Delete) {
3855
3856                         vector<PlaylistMapping>::iterator z;
3857                         
3858                         for (z = pmap.begin(); z != pmap.end(); ++z) {
3859                                 if ((*z).tv == &tv) {
3860                                         break;
3861                                 }
3862                         }
3863                         
3864                         assert (z != pmap.end());
3865                         
3866                         if (!(*z).pl) {
3867                                 npl = PlaylistFactory::create (pl->data_type(), *_session, "cutlist", true);
3868                                 npl->freeze();
3869                                 (*z).pl = npl;
3870                         } else {
3871                                 npl = (*z).pl;
3872                         }
3873                 }
3874
3875                 boost::shared_ptr<Region> r = (*x)->region();
3876                 boost::shared_ptr<Region> _xx;
3877
3878                 assert (r != 0);
3879
3880                 switch (op) {
3881                 case Delete:
3882                         pl->remove_region (r);
3883                         break;
3884                         
3885                 case Cut:
3886                         _xx = RegionFactory::create (r);
3887                         npl->add_region (_xx, r->position() - first_position);
3888                         pl->remove_region (r);
3889                         break;
3890
3891                 case Copy:
3892                         /* copy region before adding, so we're not putting same object into two different playlists */
3893                         npl->add_region (RegionFactory::create (r), r->position() - first_position);
3894                         break;
3895
3896                 case Clear:
3897                         pl->remove_region (r);  
3898                         break;
3899                 }
3900
3901                 x = tmp;
3902         }
3903
3904         if (op != Delete) {
3905
3906                 list<boost::shared_ptr<Playlist> > foo;
3907                 
3908                 /* the pmap is in the same order as the tracks in which selected regions occured */
3909                 
3910                 for (vector<PlaylistMapping>::iterator i = pmap.begin(); i != pmap.end(); ++i) {
3911                         if ((*i).pl) {
3912                                 (*i).pl->thaw();
3913                                 foo.push_back ((*i).pl);
3914                         }
3915                 }
3916                 
3917                 if (!foo.empty()) {
3918                         cut_buffer->set (foo);
3919                 }
3920                 
3921                 if (pmap.empty()) {
3922                         _last_cut_copy_source_track = 0;
3923                 } else {
3924                         _last_cut_copy_source_track = pmap.front().tv;
3925                 }
3926         }
3927
3928         for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
3929                 (*pl)->thaw ();
3930                 _session->add_command (new StatefulDiffCommand (*pl));
3931         }
3932 }
3933
3934 void
3935 Editor::cut_copy_ranges (CutCopyOp op)
3936 {
3937         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
3938
3939         /* Sort the track selection now, so that it if is used, the playlists
3940            selected by the calls below to cut_copy_clear are in the order that
3941            their tracks appear in the editor.  This makes things like paste
3942            of ranges work properly.
3943         */
3944
3945         sort_track_selection (ts);
3946
3947         if (ts.empty()) {
3948                 if (!entered_track) {
3949                         return;
3950                 }
3951                 ts.push_back (entered_track);
3952         } 
3953
3954         for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
3955                 (*i)->cut_copy_clear (*selection, op);
3956         }
3957 }
3958
3959 void
3960 Editor::paste (float times, bool from_context)
3961 {
3962         DEBUG_TRACE (DEBUG::CutNPaste, "paste to preferred edit pos\n");
3963
3964         paste_internal (get_preferred_edit_position (false, from_context), times);
3965 }
3966
3967 void
3968 Editor::mouse_paste ()
3969 {
3970         framepos_t where;
3971         bool ignored;
3972
3973         if (!mouse_frame (where, ignored)) {
3974                 return;
3975         }
3976
3977         snap_to (where);
3978         paste_internal (where, 1);
3979 }
3980
3981 void
3982 Editor::paste_internal (framepos_t position, float times)
3983 {
3984         DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("apparent paste position is %1\n", position));
3985
3986         if (internal_editing()) {
3987                 if (cut_buffer->midi_notes.empty()) {
3988                         return;
3989                 }
3990         } else {
3991                 if (cut_buffer->empty()) {
3992                         return;
3993                 }
3994         }
3995
3996         if (position == max_framepos) {
3997                 position = get_preferred_edit_position();
3998                 DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("preferred edit position is %1\n", position));
3999         }
4000
4001         TrackViewList ts;
4002         TrackViewList::iterator i;
4003         size_t nth;
4004
4005         /* get everything in the correct order */
4006
4007         if (!selection->tracks.empty()) {
4008                 /* there are some selected tracks, so paste to them */
4009                 ts = selection->tracks.filter_to_unique_playlists ();
4010                 sort_track_selection (ts);
4011         } else if (_last_cut_copy_source_track) {
4012                 /* otherwise paste to the track that the cut/copy came from;
4013                    see discussion in mantis #3333.
4014                 */
4015                 ts.push_back (_last_cut_copy_source_track);
4016         }
4017
4018         if (internal_editing ()) {
4019
4020                 /* undo/redo is handled by individual tracks/regions */
4021
4022                 for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4023
4024                         RegionSelection rs;
4025                         RegionSelection::iterator r;
4026                         MidiNoteSelection::iterator cb;
4027
4028                         get_regions_at (rs, position, ts);
4029
4030                         for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
4031                              cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
4032                                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
4033                                 if (mrv) {
4034                                         mrv->paste (position, times, **cb);
4035                                         ++cb;
4036                                 }
4037                         }
4038                 }
4039
4040         } else {
4041
4042                 /* we do redo (do you do voodoo?) */
4043
4044                 begin_reversible_command (Operations::paste);
4045
4046                 for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
4047                         (*i)->paste (position, times, *cut_buffer, nth);
4048                 }
4049
4050                 commit_reversible_command ();
4051         }
4052 }
4053
4054 void
4055 Editor::duplicate_some_regions (RegionSelection& regions, float times)
4056 {
4057         boost::shared_ptr<Playlist> playlist;
4058         RegionSelection sel = regions; // clear (below) may  clear the argument list if its the current region selection
4059         RegionSelection foo;
4060
4061         framepos_t const start_frame = regions.start ();
4062         framepos_t const end_frame = regions.end_frame ();
4063
4064         begin_reversible_command (Operations::duplicate_region);
4065
4066         selection->clear_regions ();
4067
4068         for (RegionSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
4069
4070                 boost::shared_ptr<Region> r ((*i)->region());
4071
4072                 TimeAxisView& tv = (*i)->get_time_axis_view();
4073                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
4074                 latest_regionviews.clear ();
4075                 sigc::connection c = rtv->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view));
4076
4077                 playlist = (*i)->region()->playlist();
4078                 playlist->clear_changes ();
4079                 playlist->duplicate (r, end_frame + (r->first_frame() - start_frame), times);
4080                 _session->add_command(new StatefulDiffCommand (playlist));
4081
4082                 c.disconnect ();
4083
4084                 foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
4085         }
4086
4087         commit_reversible_command ();
4088
4089         if (!foo.empty()) {
4090                 selection->set (foo);
4091         }
4092 }
4093
4094 void
4095 Editor::duplicate_selection (float times)
4096 {
4097         if (selection->time.empty() || selection->tracks.empty()) {
4098                 return;
4099         }
4100
4101         boost::shared_ptr<Playlist> playlist;
4102         vector<boost::shared_ptr<Region> > new_regions;
4103         vector<boost::shared_ptr<Region> >::iterator ri;
4104
4105         create_region_from_selection (new_regions);
4106
4107         if (new_regions.empty()) {
4108                 return;
4109         }
4110
4111         begin_reversible_command (_("duplicate selection"));
4112
4113         ri = new_regions.begin();
4114
4115         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
4116
4117         for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
4118                 if ((playlist = (*i)->playlist()) == 0) {
4119                         continue;
4120                 }
4121                 playlist->clear_changes ();
4122                 playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
4123                 _session->add_command (new StatefulDiffCommand (playlist));
4124
4125                 ++ri;
4126                 if (ri == new_regions.end()) {
4127                         --ri;
4128                 }
4129         }
4130
4131         commit_reversible_command ();
4132 }
4133
4134 void
4135 Editor::reset_point_selection ()
4136 {
4137         /* reset all selected points to the relevant default value */
4138
4139         for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
4140
4141                 AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
4142
4143                 if (atv) {
4144                         atv->reset_objects (selection->points);
4145                 }
4146         }
4147 }
4148
4149 void
4150 Editor::center_playhead ()
4151 {
4152         float page = _canvas_width * frames_per_unit;
4153         center_screen_internal (playhead_cursor->current_frame, page);
4154 }
4155
4156 void
4157 Editor::center_edit_point ()
4158 {
4159         float page = _canvas_width * frames_per_unit;
4160         center_screen_internal (get_preferred_edit_position(), page);
4161 }
4162
4163 /** Caller must begin and commit a reversible command */
4164 void
4165 Editor::clear_playlist (boost::shared_ptr<Playlist> playlist)
4166 {
4167         playlist->clear_changes ();
4168         playlist->clear ();
4169         _session->add_command (new StatefulDiffCommand (playlist));
4170 }
4171
4172 void
4173 Editor::nudge_track (bool use_edit, bool forwards)
4174 {
4175         boost::shared_ptr<Playlist> playlist;
4176         framepos_t distance;
4177         framepos_t next_distance;
4178         framepos_t start;
4179
4180         if (use_edit) {
4181                 start = get_preferred_edit_position();
4182         } else {
4183                 start = 0;
4184         }
4185
4186         if ((distance = get_nudge_distance (start, next_distance)) == 0) {
4187                 return;
4188         }
4189
4190         if (selection->tracks.empty()) {
4191                 return;
4192         }
4193
4194         begin_reversible_command (_("nudge track"));
4195
4196         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
4197
4198         for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
4199
4200                 if ((playlist = (*i)->playlist()) == 0) {
4201                         continue;
4202                 }
4203
4204                 playlist->clear_changes ();
4205                 playlist->clear_owned_changes ();
4206
4207                 playlist->nudge_after (start, distance, forwards);
4208
4209                 vector<Command*> cmds;
4210
4211                 playlist->rdiff (cmds);
4212                 _session->add_commands (cmds);
4213
4214                 _session->add_command (new StatefulDiffCommand (playlist));
4215         }
4216
4217         commit_reversible_command ();
4218 }
4219
4220 void
4221 Editor::remove_last_capture ()
4222 {
4223         vector<string> choices;
4224         string prompt;
4225
4226         if (!_session) {
4227                 return;
4228         }
4229
4230         if (Config->get_verify_remove_last_capture()) {
4231                 prompt  = _("Do you really want to destroy the last capture?"
4232                             "\n(This is destructive and cannot be undone)");
4233
4234                 choices.push_back (_("No, do nothing."));
4235                 choices.push_back (_("Yes, destroy it."));
4236
4237                 Gtkmm2ext::Choice prompter (_("Destroy last capture"), prompt, choices);
4238
4239                 if (prompter.run () == 1) {
4240                         _session->remove_last_capture ();
4241                         _regions->redisplay ();
4242                 }
4243
4244         } else {
4245                 _session->remove_last_capture();
4246                 _regions->redisplay ();
4247         }
4248 }
4249
4250 void
4251 Editor::normalize_region ()
4252 {
4253         if (!_session) {
4254                 return;
4255         }
4256
4257         RegionSelection rs = get_regions_from_selection_and_entered ();
4258
4259         if (rs.empty()) {
4260                 return;
4261         }
4262
4263         NormalizeDialog dialog (rs.size() > 1);
4264
4265         if (dialog.run () == RESPONSE_CANCEL) {
4266                 return;
4267         }
4268
4269         set_canvas_cursor (_cursors->wait);
4270         gdk_flush ();
4271
4272         /* XXX: should really only count audio regions here */
4273         int const regions = rs.size ();
4274
4275         /* Make a list of the selected audio regions' maximum amplitudes, and also
4276            obtain the maximum amplitude of them all.
4277         */
4278         list<double> max_amps;
4279         double max_amp = 0;
4280         for (RegionSelection::const_iterator i = rs.begin(); i != rs.end(); ++i) {
4281                 AudioRegionView const * arv = dynamic_cast<AudioRegionView const *> (*i);
4282                 if (arv) {
4283                         dialog.descend (1.0 / regions);
4284                         double const a = arv->audio_region()->maximum_amplitude (&dialog);
4285
4286                         if (a == -1) {
4287                                 /* the user cancelled the operation */
4288                                 set_canvas_cursor (current_canvas_cursor);
4289                                 return;
4290                         }
4291
4292                         max_amps.push_back (a);
4293                         max_amp = max (max_amp, a);
4294                         dialog.ascend ();
4295                 }
4296         }
4297
4298         begin_reversible_command (_("normalize"));
4299
4300         list<double>::const_iterator a = max_amps.begin ();
4301
4302         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4303                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*r);
4304                 if (!arv) {
4305                         continue;
4306                 }
4307
4308                 arv->region()->clear_changes ();
4309
4310                 double const amp = dialog.normalize_individually() ? *a : max_amp;
4311
4312                 arv->audio_region()->normalize (amp, dialog.target ());
4313                 _session->add_command (new StatefulDiffCommand (arv->region()));
4314
4315                 ++a;
4316         }
4317
4318         commit_reversible_command ();
4319         set_canvas_cursor (current_canvas_cursor);
4320 }
4321
4322
4323 void
4324 Editor::reset_region_scale_amplitude ()
4325 {
4326         if (!_session) {
4327                 return;
4328         }
4329
4330         RegionSelection rs = get_regions_from_selection_and_entered ();
4331
4332         if (rs.empty()) {
4333                 return;
4334         }
4335
4336         begin_reversible_command ("reset gain");
4337
4338         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4339                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4340                 if (!arv)
4341                         continue;
4342                 arv->region()->clear_changes ();
4343                 arv->audio_region()->set_scale_amplitude (1.0f);
4344                 _session->add_command (new StatefulDiffCommand (arv->region()));
4345         }
4346
4347         commit_reversible_command ();
4348 }
4349
4350 void
4351 Editor::adjust_region_gain (bool up)
4352 {
4353         RegionSelection rs = get_regions_from_selection_and_entered ();
4354
4355         if (!_session || rs.empty()) {
4356                 return;
4357         }
4358
4359         begin_reversible_command ("adjust region gain");
4360
4361         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4362                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4363                 if (!arv) {
4364                         continue;
4365                 }
4366
4367                 arv->region()->clear_changes ();
4368
4369                 double dB = accurate_coefficient_to_dB (arv->audio_region()->scale_amplitude ());
4370
4371                 if (up) {
4372                         dB += 1;
4373                 } else {
4374                         dB -= 1;
4375                 }
4376
4377                 arv->audio_region()->set_scale_amplitude (dB_to_coefficient (dB));
4378                 _session->add_command (new StatefulDiffCommand (arv->region()));
4379         }
4380
4381         commit_reversible_command ();
4382 }
4383
4384
4385 void
4386 Editor::reverse_region ()
4387 {
4388         if (!_session) {
4389                 return;
4390         }
4391
4392         Reverse rev (*_session);
4393         apply_filter (rev, _("reverse regions"));
4394 }
4395
4396 void
4397 Editor::strip_region_silence ()
4398 {
4399         if (!_session) {
4400                 return;
4401         }
4402
4403         RegionSelection rs = get_regions_from_selection_and_entered ();
4404
4405         if (rs.empty()) {
4406                 return;
4407         }
4408
4409         std::list<RegionView*> audio_only;
4410
4411         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4412                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (*i);
4413                 if (arv) {
4414                         audio_only.push_back (arv);
4415                 }
4416         }
4417
4418         StripSilenceDialog d (_session, audio_only);
4419         int const r = d.run ();
4420
4421         d.drop_rects ();
4422
4423         if (r == Gtk::RESPONSE_OK) {
4424                 ARDOUR::AudioIntervalMap silences;
4425                 d.silences (silences);
4426                 StripSilence s (*_session, silences, d.fade_length());
4427                 apply_filter (s, _("strip silence"), &d);
4428         }
4429 }
4430
4431 Command*
4432 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
4433 {
4434         Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
4435         mrv.selection_as_notelist (selected, true);
4436
4437         vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
4438         v.push_back (selected);
4439
4440         framepos_t pos_frames = mrv.midi_region()->position();
4441         double     pos_beats  = _session->tempo_map().framewalk_to_beats(0, pos_frames);
4442
4443         return op (mrv.midi_region()->model(), pos_beats, v);
4444 }
4445
4446 void
4447 Editor::apply_midi_note_edit_op (MidiOperator& op)
4448 {
4449         Command* cmd;
4450
4451         RegionSelection rs = get_regions_from_selection_and_entered ();
4452
4453         if (rs.empty()) {
4454                 return;
4455         }
4456
4457         begin_reversible_command (op.name ());
4458
4459         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4460                 RegionSelection::iterator tmp = r;
4461                 ++tmp;
4462
4463                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4464
4465                 if (mrv) {
4466                         cmd = apply_midi_note_edit_op_to_region (op, *mrv);
4467                         if (cmd) {
4468                                 (*cmd)();
4469                                 _session->add_command (cmd);
4470                         }
4471                 }
4472
4473                 r = tmp;
4474         }
4475
4476         commit_reversible_command ();
4477 }
4478
4479 void
4480 Editor::fork_region ()
4481 {
4482         RegionSelection rs = get_regions_from_selection_and_entered ();
4483
4484         if (rs.empty()) {
4485                 return;
4486         }
4487
4488         begin_reversible_command (_("Fork Region(s)"));
4489
4490         set_canvas_cursor (_cursors->wait);
4491         gdk_flush ();
4492
4493         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4494                 RegionSelection::iterator tmp = r;
4495                 ++tmp;
4496
4497                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
4498
4499                 if (mrv) {
4500                         boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
4501                         boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
4502
4503                         playlist->clear_changes ();
4504                         playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
4505                         _session->add_command(new StatefulDiffCommand (playlist));
4506                 }
4507
4508                 r = tmp;
4509         }
4510
4511         commit_reversible_command ();
4512
4513         set_canvas_cursor (current_canvas_cursor);
4514 }
4515
4516 void
4517 Editor::quantize_region ()
4518 {
4519         int selected_midi_region_cnt = 0;
4520
4521         if (!_session) {
4522                 return;
4523         }
4524
4525         RegionSelection rs = get_regions_from_selection_and_entered ();
4526
4527         if (rs.empty()) {
4528                 return;
4529         }
4530
4531         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
4532                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
4533                 if (mrv) {
4534                         selected_midi_region_cnt++;
4535                 }
4536         }
4537
4538         if (selected_midi_region_cnt == 0) {
4539                 return;
4540         }
4541
4542         QuantizeDialog* qd = new QuantizeDialog (*this);
4543
4544         qd->present ();
4545         const int r = qd->run ();
4546         qd->hide ();
4547
4548         if (r == Gtk::RESPONSE_OK) {
4549                 Quantize quant (*_session, Plain,
4550                                 qd->snap_start(), qd->snap_end(),
4551                                 qd->start_grid_size(), qd->end_grid_size(),
4552                                 qd->strength(), qd->swing(), qd->threshold());
4553
4554                 apply_midi_note_edit_op (quant);
4555         }
4556 }
4557
4558 void
4559 Editor::insert_patch_change (bool from_context)
4560 {
4561         RegionSelection rs = get_regions_from_selection_and_entered ();
4562
4563         if (rs.empty ()) {
4564                 return;
4565         }
4566
4567         const framepos_t p = get_preferred_edit_position (false, from_context);
4568
4569         Evoral::PatchChange<Evoral::MusicalTime> empty (0, 0, 0, 0);
4570         PatchChangeDialog d (0, _session, empty, Gtk::Stock::ADD);
4571
4572         if (d.run() == RESPONSE_CANCEL) {
4573                 return;
4574         }
4575
4576         for (RegionSelection::iterator i = rs.begin (); i != rs.end(); ++i) {
4577                 MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*i);
4578                 if (mrv) {
4579                         if (p >= mrv->region()->first_frame() && p <= mrv->region()->last_frame()) {
4580                                 mrv->add_patch_change (p - mrv->region()->position(), d.patch ());
4581                         }
4582                 }
4583         }
4584 }
4585
4586 void
4587 Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress)
4588 {
4589         RegionSelection rs = get_regions_from_selection_and_entered ();
4590
4591         if (rs.empty()) {
4592                 return;
4593         }
4594
4595         begin_reversible_command (command);
4596
4597         set_canvas_cursor (_cursors->wait);
4598         gdk_flush ();
4599
4600         int n = 0;
4601         int const N = rs.size ();
4602
4603         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
4604                 RegionSelection::iterator tmp = r;
4605                 ++tmp;
4606
4607                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*r);
4608                 if (arv) {
4609                         boost::shared_ptr<Playlist> playlist = arv->region()->playlist();
4610
4611                         if (progress) {
4612                                 progress->descend (1.0 / N);
4613                         }
4614
4615                         if (arv->audio_region()->apply (filter, progress) == 0) {
4616
4617                                 playlist->clear_changes ();
4618
4619                                 if (filter.results.empty ()) {
4620
4621                                         /* no regions returned; remove the old one */
4622                                         playlist->remove_region (arv->region ());
4623
4624                                 } else {
4625
4626                                         std::vector<boost::shared_ptr<Region> >::iterator res = filter.results.begin ();
4627
4628                                         /* first region replaces the old one */
4629                                         playlist->replace_region (arv->region(), *res, (*res)->position());
4630                                         ++res;
4631
4632                                         /* add the rest */
4633                                         while (res != filter.results.end()) {
4634                                                 playlist->add_region (*res, (*res)->position());
4635                                                 ++res;
4636                                         }
4637
4638                                 }
4639
4640                                 _session->add_command(new StatefulDiffCommand (playlist));
4641                         } else {
4642                                 goto out;
4643                         }
4644
4645                         if (progress) {
4646                                 progress->ascend ();
4647                         }
4648                 }
4649
4650                 r = tmp;
4651                 ++n;
4652         }
4653
4654         commit_reversible_command ();
4655
4656   out:
4657         set_canvas_cursor (current_canvas_cursor);
4658 }
4659
4660 void
4661 Editor::external_edit_region ()
4662 {
4663         /* more to come */
4664 }
4665
4666 void
4667 Editor::reset_region_gain_envelopes ()
4668 {
4669         RegionSelection rs = get_regions_from_selection_and_entered ();
4670
4671         if (!_session || rs.empty()) {
4672                 return;
4673         }
4674
4675         _session->begin_reversible_command (_("reset region gain"));
4676
4677         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4678                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4679                 if (arv) {
4680                         boost::shared_ptr<AutomationList> alist (arv->audio_region()->envelope());
4681                         XMLNode& before (alist->get_state());
4682
4683                         arv->audio_region()->set_default_envelope ();
4684                         _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
4685                 }
4686         }
4687
4688         _session->commit_reversible_command ();
4689 }
4690
4691 void
4692 Editor::toggle_gain_envelope_visibility ()
4693 {
4694         if (_ignore_region_action) {
4695                 return;
4696         }
4697
4698         RegionSelection rs = get_regions_from_selection_and_entered ();
4699
4700         if (!_session || rs.empty()) {
4701                 return;
4702         }
4703
4704         _session->begin_reversible_command (_("region gain envelope visible"));
4705
4706         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4707                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4708                 if (arv) {
4709                         arv->region()->clear_changes ();
4710                         arv->set_envelope_visible (!arv->envelope_visible());
4711                         _session->add_command (new StatefulDiffCommand (arv->region()));
4712                 }
4713         }
4714
4715         _session->commit_reversible_command ();
4716 }
4717
4718 void
4719 Editor::toggle_gain_envelope_active ()
4720 {
4721         if (_ignore_region_action) {
4722                 return;
4723         }
4724
4725         RegionSelection rs = get_regions_from_selection_and_entered ();
4726
4727         if (!_session || rs.empty()) {
4728                 return;
4729         }
4730
4731         _session->begin_reversible_command (_("region gain envelope active"));
4732
4733         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4734                 AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
4735                 if (arv) {
4736                         arv->region()->clear_changes ();
4737                         arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
4738                         _session->add_command (new StatefulDiffCommand (arv->region()));
4739                 }
4740         }
4741
4742         _session->commit_reversible_command ();
4743 }
4744
4745 void
4746 Editor::toggle_region_lock ()
4747 {
4748         if (_ignore_region_action) {
4749                 return;
4750         }
4751
4752         RegionSelection rs = get_regions_from_selection_and_entered ();
4753
4754         if (!_session || rs.empty()) {
4755                 return;
4756         }
4757
4758         _session->begin_reversible_command (_("toggle region lock"));
4759
4760         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4761                 (*i)->region()->clear_changes ();
4762                 (*i)->region()->set_locked (!(*i)->region()->locked());
4763                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4764         }
4765
4766         _session->commit_reversible_command ();
4767 }
4768
4769 void
4770 Editor::toggle_region_lock_style ()
4771 {
4772         if (_ignore_region_action) {
4773                 return;
4774         }
4775
4776         RegionSelection rs = get_regions_from_selection_and_entered ();
4777
4778         if (!_session || rs.empty()) {
4779                 return;
4780         }
4781
4782         _session->begin_reversible_command (_("region lock style"));
4783
4784         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4785                 (*i)->region()->clear_changes ();
4786                 PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
4787                 (*i)->region()->set_position_lock_style (ns);
4788                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4789         }
4790
4791         _session->commit_reversible_command ();
4792 }
4793
4794 void
4795 Editor::toggle_opaque_region ()
4796 {
4797         if (_ignore_region_action) {
4798                 return;
4799         }
4800
4801         RegionSelection rs = get_regions_from_selection_and_entered ();
4802
4803         if (!_session || rs.empty()) {
4804                 return;
4805         }
4806
4807         _session->begin_reversible_command (_("change region opacity"));
4808
4809         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
4810                 (*i)->region()->clear_changes ();
4811                 (*i)->region()->set_opaque (!(*i)->region()->opaque());
4812                 _session->add_command (new StatefulDiffCommand ((*i)->region()));
4813         }
4814
4815         _session->commit_reversible_command ();
4816 }
4817
4818 void
4819 Editor::toggle_record_enable ()
4820 {
4821         bool new_state = false;
4822         bool first = true;
4823         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4824                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4825                 if (!rtav)
4826                         continue;
4827                 if (!rtav->is_track())
4828                         continue;
4829
4830                 if (first) {
4831                         new_state = !rtav->track()->record_enabled();
4832                         first = false;
4833                 }
4834
4835                 rtav->track()->set_record_enabled (new_state, this);
4836         }
4837 }
4838
4839 void
4840 Editor::toggle_solo ()
4841 {
4842         bool new_state = false;
4843         bool first = true;
4844         boost::shared_ptr<RouteList> rl (new RouteList);
4845
4846         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4847                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4848
4849                 if (!rtav) {
4850                         continue;
4851                 }
4852
4853                 if (first) {
4854                         new_state = !rtav->route()->soloed ();
4855                         first = false;
4856                 }
4857
4858                 rl->push_back (rtav->route());
4859         }
4860
4861         _session->set_solo (rl, new_state, Session::rt_cleanup, true);
4862 }
4863
4864 void
4865 Editor::toggle_mute ()
4866 {
4867         bool new_state = false;
4868         bool first = true;
4869         boost::shared_ptr<RouteList> rl (new RouteList);
4870
4871         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4872                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
4873
4874                 if (!rtav) {
4875                         continue;
4876                 }
4877
4878                 if (first) {
4879                         new_state = !rtav->route()->muted();
4880                         first = false;
4881                 }
4882
4883                 rl->push_back (rtav->route());
4884         }
4885
4886         _session->set_mute (rl, new_state, Session::rt_cleanup, true);
4887 }
4888
4889 void
4890 Editor::toggle_solo_isolate ()
4891 {
4892 }
4893
4894 void
4895 Editor::set_fade_length (bool in)
4896 {
4897         RegionSelection rs = get_regions_from_selection_and_entered ();
4898
4899         if (rs.empty()) {
4900                 return;
4901         }
4902
4903         /* we need a region to measure the offset from the start */
4904
4905         RegionView* rv = rs.front ();
4906
4907         framepos_t pos = get_preferred_edit_position();
4908         framepos_t len;
4909         char const * cmd;
4910
4911         if (pos > rv->region()->last_frame() || pos < rv->region()->first_frame()) {
4912                 /* edit point is outside the relevant region */
4913                 return;
4914         }
4915
4916         if (in) {
4917                 if (pos <= rv->region()->position()) {
4918                         /* can't do it */
4919                         return;
4920                 }
4921                 len = pos - rv->region()->position();
4922                 cmd = _("set fade in length");
4923         } else {
4924                 if (pos >= rv->region()->last_frame()) {
4925                         /* can't do it */
4926                         return;
4927                 }
4928                 len = rv->region()->last_frame() - pos;
4929                 cmd = _("set fade out length");
4930         }
4931
4932         begin_reversible_command (cmd);
4933
4934         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4935                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4936
4937                 if (!tmp) {
4938                         return;
4939                 }
4940
4941                 boost::shared_ptr<AutomationList> alist;
4942                 if (in) {
4943                         alist = tmp->audio_region()->fade_in();
4944                 } else {
4945                         alist = tmp->audio_region()->fade_out();
4946                 }
4947
4948                 XMLNode &before = alist->get_state();
4949
4950                 if (in) {
4951                         tmp->audio_region()->set_fade_in_length (len);
4952                         tmp->audio_region()->set_fade_in_active (true);
4953                 } else {
4954                         tmp->audio_region()->set_fade_out_length (len);
4955                         tmp->audio_region()->set_fade_out_active (true);
4956                 }
4957
4958                 XMLNode &after = alist->get_state();
4959                 _session->add_command(new MementoCommand<AutomationList>(*alist, &before, &after));
4960         }
4961
4962         commit_reversible_command ();
4963 }
4964
4965 void
4966 Editor::set_fade_in_shape (FadeShape shape)
4967 {
4968         RegionSelection rs = get_regions_from_selection_and_entered ();
4969
4970         if (rs.empty()) {
4971                 return;
4972         }
4973
4974         begin_reversible_command (_("set fade in shape"));
4975
4976         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
4977                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
4978
4979                 if (!tmp) {
4980                         return;
4981                 }
4982
4983                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
4984                 XMLNode &before = alist->get_state();
4985
4986                 tmp->audio_region()->set_fade_in_shape (shape);
4987
4988                 XMLNode &after = alist->get_state();
4989                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
4990         }
4991
4992         commit_reversible_command ();
4993
4994 }
4995
4996 void
4997 Editor::set_fade_out_shape (FadeShape shape)
4998 {
4999         RegionSelection rs = get_regions_from_selection_and_entered ();
5000
5001         if (rs.empty()) {
5002                 return;
5003         }
5004
5005         begin_reversible_command (_("set fade out shape"));
5006
5007         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5008                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5009
5010                 if (!tmp) {
5011                         return;
5012                 }
5013
5014                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
5015                 XMLNode &before = alist->get_state();
5016
5017                 tmp->audio_region()->set_fade_out_shape (shape);
5018
5019                 XMLNode &after = alist->get_state();
5020                 _session->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
5021         }
5022
5023         commit_reversible_command ();
5024 }
5025
5026 void
5027 Editor::set_fade_in_active (bool yn)
5028 {
5029         RegionSelection rs = get_regions_from_selection_and_entered ();
5030
5031         if (rs.empty()) {
5032                 return;
5033         }
5034
5035         begin_reversible_command (_("set fade in active"));
5036
5037         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5038                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5039
5040                 if (!tmp) {
5041                         return;
5042                 }
5043
5044
5045                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5046
5047                 ar->clear_changes ();
5048                 ar->set_fade_in_active (yn);
5049                 _session->add_command (new StatefulDiffCommand (ar));
5050         }
5051
5052         commit_reversible_command ();
5053 }
5054
5055 void
5056 Editor::set_fade_out_active (bool yn)
5057 {
5058         RegionSelection rs = get_regions_from_selection_and_entered ();
5059
5060         if (rs.empty()) {
5061                 return;
5062         }
5063
5064         begin_reversible_command (_("set fade out active"));
5065
5066         for (RegionSelection::iterator x = rs.begin(); x != rs.end(); ++x) {
5067                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (*x);
5068
5069                 if (!tmp) {
5070                         return;
5071                 }
5072
5073                 boost::shared_ptr<AudioRegion> ar (tmp->audio_region());
5074
5075                 ar->clear_changes ();
5076                 ar->set_fade_out_active (yn);
5077                 _session->add_command(new StatefulDiffCommand (ar));
5078         }
5079
5080         commit_reversible_command ();
5081 }
5082
5083 void
5084 Editor::toggle_region_fades (int dir)
5085 {
5086         boost::shared_ptr<AudioRegion> ar;
5087         bool yn = false;
5088
5089         RegionSelection rs = get_regions_from_selection_and_entered ();
5090
5091         if (rs.empty()) {
5092                 return;
5093         }
5094
5095         RegionSelection::iterator i;
5096         for (i = rs.begin(); i != rs.end(); ++i) {
5097                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) != 0) {
5098                         if (dir == -1) {
5099                                 yn = ar->fade_out_active ();
5100                         } else {
5101                                 yn = ar->fade_in_active ();
5102                         }
5103                         break;
5104                 }
5105         }
5106
5107         if (i == rs.end()) {
5108                 return;
5109         }
5110
5111         /* XXX should this undo-able? */
5112
5113         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5114                 if ((ar = boost::dynamic_pointer_cast<AudioRegion>((*i)->region())) == 0) {
5115                         continue;
5116                 }
5117                 if (dir == 1 || dir == 0) {
5118                         ar->set_fade_in_active (!yn);
5119                 }
5120
5121                 if (dir == -1 || dir == 0) {
5122                         ar->set_fade_out_active (!yn);
5123                 }
5124         }
5125 }
5126
5127
5128 /** Update region fade visibility after its configuration has been changed */
5129 void
5130 Editor::update_region_fade_visibility ()
5131 {
5132         bool _fade_visibility = _session->config.get_show_region_fades ();
5133
5134         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5135                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5136                 if (v) {
5137                         if (_fade_visibility) {
5138                                 v->audio_view()->show_all_fades ();
5139                         } else {
5140                                 v->audio_view()->hide_all_fades ();
5141                         }
5142                 }
5143         }
5144 }
5145
5146 /** Update crossfade visibility after its configuration has been changed */
5147 void
5148 Editor::update_xfade_visibility ()
5149 {
5150         _xfade_visibility = _session->config.get_xfades_visible ();
5151
5152         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5153                 AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
5154                 if (v) {
5155                         if (_xfade_visibility) {
5156                                 v->show_all_xfades ();
5157                         } else {
5158                                 v->hide_all_xfades ();
5159                         }
5160                 }
5161         }
5162 }
5163
5164 void
5165 Editor::set_edit_point ()
5166 {
5167         framepos_t where;
5168         bool ignored;
5169
5170         if (!mouse_frame (where, ignored)) {
5171                 return;
5172         }
5173
5174         snap_to (where);
5175
5176         if (selection->markers.empty()) {
5177
5178                 mouse_add_new_marker (where);
5179
5180         } else {
5181                 bool ignored;
5182
5183                 Location* loc = find_location_from_marker (selection->markers.front(), ignored);
5184
5185                 if (loc) {
5186                         loc->move_to (where);
5187                 }
5188         }
5189 }
5190
5191 void
5192 Editor::set_playhead_cursor ()
5193 {
5194         if (entered_marker) {
5195                 _session->request_locate (entered_marker->position(), _session->transport_rolling());
5196         } else {
5197                 framepos_t where;
5198                 bool ignored;
5199
5200                 if (!mouse_frame (where, ignored)) {
5201                         return;
5202                 }
5203
5204                 snap_to (where);
5205
5206                 if (_session) {
5207                         _session->request_locate (where, _session->transport_rolling());
5208                 }
5209         }
5210 }
5211
5212 void
5213 Editor::split_region ()
5214 {
5215         if (((mouse_mode == MouseRange) ||
5216              (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) &&
5217             !selection->time.empty()) {
5218                 separate_regions_between (selection->time);
5219                 return;
5220         }
5221
5222         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5223
5224         framepos_t where = get_preferred_edit_position ();
5225
5226         if (rs.empty()) {
5227                 return;
5228         }
5229
5230         split_regions_at (where, rs);
5231 }
5232
5233 void
5234 Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
5235 {
5236         if (entered_track && mouse_mode == MouseObject) {
5237                 if (!selection->tracks.empty()) {
5238                         if (!selection->selected (entered_track)) {
5239                                 selection->add (entered_track);
5240                         }
5241                 } else {
5242                         /* there is no selection, but this operation requires/prefers selected objects */
5243
5244                         if (op_really_wants_one_track_if_none_are_selected) {
5245                                 selection->set (entered_track);
5246                         }
5247                 }
5248         }
5249 }
5250
5251 struct EditorOrderRouteSorter {
5252     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
5253             /* use of ">" forces the correct sort order */
5254             return a->order_key ("editor") < b->order_key ("editor");
5255     }
5256 };
5257
5258 void
5259 Editor::select_next_route()
5260 {
5261         if (selection->tracks.empty()) {
5262                 selection->set (track_views.front());
5263                 return;
5264         }
5265
5266         TimeAxisView* current = selection->tracks.front();
5267
5268         RouteUI *rui;
5269         do {
5270                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5271                         if (*i == current) {
5272                                 ++i;
5273                                 if (i != track_views.end()) {
5274                                         current = (*i);
5275                                 } else {
5276                                         current = (*(track_views.begin()));
5277                                         //selection->set (*(track_views.begin()));
5278                                 }
5279                                 break;
5280                         }
5281                 }
5282                 rui = dynamic_cast<RouteUI *>(current);
5283         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5284
5285         selection->set(current);
5286
5287         ensure_track_visible(current);
5288 }
5289
5290 void
5291 Editor::select_prev_route()
5292 {
5293         if (selection->tracks.empty()) {
5294                 selection->set (track_views.front());
5295                 return;
5296         }
5297
5298         TimeAxisView* current = selection->tracks.front();
5299
5300         RouteUI *rui;
5301         do {
5302                 for (TrackViewList::reverse_iterator i = track_views.rbegin(); i != track_views.rend(); ++i) {
5303                         if (*i == current) {
5304                                 ++i;
5305                                 if (i != track_views.rend()) {
5306                                         current = (*i);
5307                                 } else {
5308                                         current = *(track_views.rbegin());
5309                                 }
5310                                 break;
5311                         }
5312                 }
5313                 rui = dynamic_cast<RouteUI *>(current);
5314         } while ( current->hidden() || (rui != NULL && !rui->route()->active()));
5315
5316         selection->set (current);
5317
5318         ensure_track_visible(current);
5319 }
5320
5321 void
5322 Editor::ensure_track_visible(TimeAxisView *track)
5323 {
5324         if (track->hidden())
5325                 return;
5326
5327         double const current_view_min_y = vertical_adjustment.get_value();
5328         double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
5329
5330         double const track_min_y = track->y_position ();
5331         double const track_max_y = track->y_position () + track->effective_height ();
5332
5333         if (track_min_y >= current_view_min_y &&
5334             track_max_y <= current_view_max_y) {
5335                 return;
5336         }
5337
5338         double new_value;
5339
5340         if (track_min_y < current_view_min_y) {
5341                 // Track is above the current view
5342                 new_value = track_min_y;
5343         } else {
5344                 // Track is below the current view
5345                 new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
5346         }
5347
5348         vertical_adjustment.set_value(new_value);
5349 }
5350
5351 void
5352 Editor::set_loop_from_selection (bool play)
5353 {
5354         if (_session == 0 || selection->time.empty()) {
5355                 return;
5356         }
5357
5358         framepos_t start = selection->time[clicked_selection].start;
5359         framepos_t end = selection->time[clicked_selection].end;
5360
5361         set_loop_range (start, end,  _("set loop range from selection"));
5362
5363         if (play) {
5364                 _session->request_play_loop (true);
5365                 _session->request_locate (start, true);
5366         }
5367 }
5368
5369 void
5370 Editor::set_loop_from_edit_range (bool play)
5371 {
5372         if (_session == 0) {
5373                 return;
5374         }
5375
5376         framepos_t start;
5377         framepos_t end;
5378
5379         if (!get_edit_op_range (start, end)) {
5380                 return;
5381         }
5382
5383         set_loop_range (start, end,  _("set loop range from edit range"));
5384
5385         if (play) {
5386                 _session->request_play_loop (true);
5387                 _session->request_locate (start, true);
5388         }
5389 }
5390
5391 void
5392 Editor::set_loop_from_region (bool play)
5393 {
5394         framepos_t start = max_framepos;
5395         framepos_t end = 0;
5396
5397         RegionSelection rs = get_regions_from_selection_and_entered ();
5398
5399         if (rs.empty()) {
5400                 return;
5401         }
5402
5403         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5404                 if ((*i)->region()->position() < start) {
5405                         start = (*i)->region()->position();
5406                 }
5407                 if ((*i)->region()->last_frame() + 1 > end) {
5408                         end = (*i)->region()->last_frame() + 1;
5409                 }
5410         }
5411
5412         set_loop_range (start, end, _("set loop range from region"));
5413
5414         if (play) {
5415                 _session->request_play_loop (true);
5416                 _session->request_locate (start, true);
5417         }
5418 }
5419
5420 void
5421 Editor::set_punch_from_selection ()
5422 {
5423         if (_session == 0 || selection->time.empty()) {
5424                 return;
5425         }
5426
5427         framepos_t start = selection->time[clicked_selection].start;
5428         framepos_t end = selection->time[clicked_selection].end;
5429
5430         set_punch_range (start, end,  _("set punch range from selection"));
5431 }
5432
5433 void
5434 Editor::set_punch_from_edit_range ()
5435 {
5436         if (_session == 0) {
5437                 return;
5438         }
5439
5440         framepos_t start;
5441         framepos_t end;
5442
5443         if (!get_edit_op_range (start, end)) {
5444                 return;
5445         }
5446
5447         set_punch_range (start, end,  _("set punch range from edit range"));
5448 }
5449
5450 void
5451 Editor::set_punch_from_region ()
5452 {
5453         framepos_t start = max_framepos;
5454         framepos_t end = 0;
5455
5456         RegionSelection rs = get_regions_from_selection_and_entered ();
5457
5458         if (rs.empty()) {
5459                 return;
5460         }
5461
5462         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5463                 if ((*i)->region()->position() < start) {
5464                         start = (*i)->region()->position();
5465                 }
5466                 if ((*i)->region()->last_frame() + 1 > end) {
5467                         end = (*i)->region()->last_frame() + 1;
5468                 }
5469         }
5470
5471         set_punch_range (start, end, _("set punch range from region"));
5472 }
5473
5474 void
5475 Editor::pitch_shift_region ()
5476 {
5477         RegionSelection rs = get_regions_from_selection_and_entered ();
5478
5479         RegionSelection audio_rs;
5480         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5481                 if (dynamic_cast<AudioRegionView*> (*i)) {
5482                         audio_rs.push_back (*i);
5483                 }
5484         }
5485
5486         if (audio_rs.empty()) {
5487                 return;
5488         }
5489
5490         pitch_shift (audio_rs, 1.2);
5491 }
5492
5493 void
5494 Editor::transpose_region ()
5495 {
5496         RegionSelection rs = get_regions_from_selection_and_entered ();
5497
5498         list<MidiRegionView*> midi_region_views;
5499         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
5500                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*i);
5501                 if (mrv) {
5502                         midi_region_views.push_back (mrv);
5503                 }
5504         }
5505
5506         TransposeDialog d;
5507         int const r = d.run ();
5508         if (r != RESPONSE_ACCEPT) {
5509                 return;
5510         }
5511
5512         for (list<MidiRegionView*>::iterator i = midi_region_views.begin(); i != midi_region_views.end(); ++i) {
5513                 (*i)->midi_region()->transpose (d.semitones ());
5514         }
5515 }
5516
5517 void
5518 Editor::set_tempo_from_region ()
5519 {
5520         RegionSelection rs = get_regions_from_selection_and_entered ();
5521
5522         if (!_session || rs.empty()) {
5523                 return;
5524         }
5525
5526         RegionView* rv = rs.front();
5527
5528         define_one_bar (rv->region()->position(), rv->region()->last_frame() + 1);
5529 }
5530
5531 void
5532 Editor::use_range_as_bar ()
5533 {
5534         framepos_t start, end;
5535         if (get_edit_op_range (start, end)) {
5536                 define_one_bar (start, end);
5537         }
5538 }
5539
5540 void
5541 Editor::define_one_bar (framepos_t start, framepos_t end)
5542 {
5543         framepos_t length = end - start;
5544
5545         const Meter& m (_session->tempo_map().meter_at (start));
5546
5547         /* length = 1 bar */
5548
5549         /* now we want frames per beat.
5550            we have frames per bar, and beats per bar, so ...
5551         */
5552
5553         /* XXXX METER MATH */
5554
5555         double frames_per_beat = length / m.divisions_per_bar();
5556
5557         /* beats per minute = */
5558
5559         double beats_per_minute = (_session->frame_rate() * 60.0) / frames_per_beat;
5560
5561         /* now decide whether to:
5562
5563             (a) set global tempo
5564             (b) add a new tempo marker
5565
5566         */
5567
5568         const TempoSection& t (_session->tempo_map().tempo_section_at (start));
5569
5570         bool do_global = false;
5571
5572         if ((_session->tempo_map().n_tempos() == 1) && (_session->tempo_map().n_meters() == 1)) {
5573
5574                 /* only 1 tempo & 1 meter: ask if the user wants to set the tempo
5575                    at the start, or create a new marker
5576                 */
5577
5578                 vector<string> options;
5579                 options.push_back (_("Cancel"));
5580                 options.push_back (_("Add new marker"));
5581                 options.push_back (_("Set global tempo"));
5582
5583                 Choice c (
5584                         _("Define one bar"),
5585                         _("Do you want to set the global tempo or add a new tempo marker?"),
5586                         options
5587                         );
5588
5589                 c.set_default_response (2);
5590
5591                 switch (c.run()) {
5592                 case 0:
5593                         return;
5594
5595                 case 2:
5596                         do_global = true;
5597                         break;
5598
5599                 default:
5600                         do_global = false;
5601                 }
5602
5603         } else {
5604
5605                 /* more than 1 tempo and/or meter section already, go ahead do the "usual":
5606                    if the marker is at the region starter, change it, otherwise add
5607                    a new tempo marker
5608                 */
5609         }
5610
5611         begin_reversible_command (_("set tempo from region"));
5612         XMLNode& before (_session->tempo_map().get_state());
5613
5614         if (do_global) {
5615                 _session->tempo_map().change_initial_tempo (beats_per_minute, t.note_type());
5616         } else if (t.frame() == start) {
5617                 _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
5618         } else {
5619                 _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
5620         }
5621
5622         XMLNode& after (_session->tempo_map().get_state());
5623
5624         _session->add_command (new MementoCommand<TempoMap>(_session->tempo_map(), &before, &after));
5625         commit_reversible_command ();
5626 }
5627
5628 void
5629 Editor::split_region_at_transients ()
5630 {
5631         AnalysisFeatureList positions;
5632
5633         RegionSelection rs = get_regions_from_selection_and_entered ();
5634
5635         if (!_session || rs.empty()) {
5636                 return;
5637         }
5638
5639         _session->begin_reversible_command (_("split regions"));
5640
5641         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
5642
5643                 RegionSelection::iterator tmp;
5644
5645                 tmp = i;
5646                 ++tmp;
5647
5648                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i)->region());
5649
5650                 if (ar && (ar->get_transients (positions) == 0)) {
5651                         split_region_at_points ((*i)->region(), positions, true);
5652                         positions.clear ();
5653                 }
5654
5655                 i = tmp;
5656         }
5657
5658         _session->commit_reversible_command ();
5659
5660 }
5661
5662 void
5663 Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList& positions, bool can_ferret, bool select_new)
5664 {
5665         bool use_rhythmic_rodent = false;
5666
5667         boost::shared_ptr<Playlist> pl = r->playlist();
5668
5669         list<boost::shared_ptr<Region> > new_regions;
5670
5671         if (!pl) {
5672                 return;
5673         }
5674
5675         if (positions.empty()) {
5676                 return;
5677         }
5678
5679
5680         if (positions.size() > 20 && can_ferret) {
5681                 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);
5682                 MessageDialog msg (msgstr,
5683                                    false,
5684                                    Gtk::MESSAGE_INFO,
5685                                    Gtk::BUTTONS_OK_CANCEL);
5686
5687                 if (can_ferret) {
5688                         msg.add_button (_("Call for the Ferret!"), RESPONSE_APPLY);
5689                         msg.set_secondary_text (_("Press OK to continue with this split operation\nor ask the Ferret dialog to tune the analysis"));
5690                 } else {
5691                         msg.set_secondary_text (_("Press OK to continue with this split operation"));
5692                 }
5693
5694                 msg.set_title (_("Excessive split?"));
5695                 msg.present ();
5696
5697                 int response = msg.run();
5698                 msg.hide ();
5699
5700                 switch (response) {
5701                 case RESPONSE_OK:
5702                         break;
5703                 case RESPONSE_APPLY:
5704                         use_rhythmic_rodent = true;
5705                         break;
5706                 default:
5707                         return;
5708                 }
5709         }
5710
5711         if (use_rhythmic_rodent) {
5712                 show_rhythm_ferret ();
5713                 return;
5714         }
5715
5716         AnalysisFeatureList::const_iterator x;
5717
5718         pl->clear_changes ();
5719
5720         x = positions.begin();
5721
5722         if (x == positions.end()) {
5723                 return;
5724         }
5725
5726         pl->freeze ();
5727         pl->remove_region (r);
5728
5729         framepos_t pos = 0;
5730
5731         while (x != positions.end()) {
5732
5733                 /* deal with positons that are out of scope of present region bounds */
5734                 if (*x <= 0 || *x > r->length()) {
5735                         ++x;
5736                         continue;
5737                 }
5738
5739                 /* file start = original start + how far we from the initial position ?
5740                  */
5741
5742                 framepos_t file_start = r->start() + pos;
5743
5744                 /* length = next position - current position
5745                  */
5746
5747                 framepos_t len = (*x) - pos;
5748
5749                 /* XXX we do we really want to allow even single-sample regions?
5750                    shouldn't we have some kind of lower limit on region size?
5751                 */
5752
5753                 if (len <= 0) {
5754                         break;
5755                 }
5756
5757                 string new_name;
5758
5759                 if (RegionFactory::region_name (new_name, r->name())) {
5760                         break;
5761                 }
5762
5763                 /* do NOT announce new regions 1 by one, just wait till they are all done */
5764
5765                 PropertyList plist;
5766
5767                 plist.add (ARDOUR::Properties::start, file_start);
5768                 plist.add (ARDOUR::Properties::length, len);
5769                 plist.add (ARDOUR::Properties::name, new_name);
5770                 plist.add (ARDOUR::Properties::layer, 0);
5771
5772                 boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5773
5774                 pl->add_region (nr, r->position() + pos);
5775
5776                 if (select_new) {
5777                         new_regions.push_front(nr);
5778                 }
5779
5780                 pos += len;
5781                 ++x;
5782         }
5783
5784         string new_name;
5785
5786         RegionFactory::region_name (new_name, r->name());
5787
5788         /* Add the final region */
5789         PropertyList plist;
5790
5791         plist.add (ARDOUR::Properties::start, r->start() + pos);
5792         plist.add (ARDOUR::Properties::length, r->last_frame() - (r->position() + pos) + 1);
5793         plist.add (ARDOUR::Properties::name, new_name);
5794         plist.add (ARDOUR::Properties::layer, 0);
5795
5796         boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
5797         pl->add_region (nr, r->position() + pos);
5798
5799         if (select_new) {
5800                 new_regions.push_front(nr);
5801         }
5802
5803         pl->thaw ();
5804
5805         _session->add_command (new StatefulDiffCommand (pl));
5806
5807         if (select_new) {
5808
5809                 for (list<boost::shared_ptr<Region> >::iterator i = new_regions.begin(); i != new_regions.end(); ++i){
5810                         set_selected_regionview_from_region_list ((*i), Selection::Add);
5811                 }
5812         }
5813 }
5814
5815 void
5816 Editor::place_transient()
5817 {
5818         if (!_session) {
5819                 return;
5820         }
5821
5822         RegionSelection rs = get_regions_from_selection_and_edit_point ();
5823
5824         if (rs.empty()) {
5825                 return;
5826         }
5827
5828         framepos_t where = get_preferred_edit_position();
5829
5830         _session->begin_reversible_command (_("place transient"));
5831
5832         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5833                 framepos_t position = (*r)->region()->position();
5834                 (*r)->region()->add_transient(where - position);
5835         }
5836
5837         _session->commit_reversible_command ();
5838 }
5839
5840 void
5841 Editor::remove_transient(ArdourCanvas::Item* item)
5842 {
5843         if (!_session) {
5844                 return;
5845         }
5846
5847         ArdourCanvas::Line* _line = reinterpret_cast<ArdourCanvas::Line*> (item);
5848         assert (_line);
5849
5850         AudioRegionView* _arv = reinterpret_cast<AudioRegionView*> (item->get_data ("regionview"));
5851         _arv->remove_transient (*(float*) _line->get_data ("position"));
5852 }
5853
5854 void
5855 Editor::snap_regions_to_grid ()
5856 {
5857         list <boost::shared_ptr<Playlist > > used_playlists;
5858
5859         RegionSelection rs = get_regions_from_selection_and_entered ();
5860
5861         if (!_session || rs.empty()) {
5862                 return;
5863         }
5864
5865         _session->begin_reversible_command (_("snap regions to grid"));
5866
5867         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5868
5869                 boost::shared_ptr<Playlist> pl = (*r)->region()->playlist();
5870
5871                 if (!pl->frozen()) {
5872                         /* we haven't seen this playlist before */
5873
5874                         /* remember used playlists so we can thaw them later */
5875                         used_playlists.push_back(pl);
5876                         pl->freeze();
5877                 }
5878
5879                 framepos_t start_frame = (*r)->region()->first_frame ();
5880                 snap_to (start_frame);
5881                 (*r)->region()->set_position (start_frame);
5882         }
5883
5884         while (used_playlists.size() > 0) {
5885                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
5886                 (*i)->thaw();
5887                 used_playlists.pop_front();
5888         }
5889
5890         _session->commit_reversible_command ();
5891 }
5892
5893 void
5894 Editor::close_region_gaps ()
5895 {
5896         list <boost::shared_ptr<Playlist > > used_playlists;
5897
5898         RegionSelection rs = get_regions_from_selection_and_entered ();
5899
5900         if (!_session || rs.empty()) {
5901                 return;
5902         }
5903
5904         Dialog dialog (_("Close Region Gaps"));
5905
5906         Table table (2, 3);
5907         table.set_spacings (12);
5908         table.set_border_width (12);
5909         Label* l = manage (new Label (_("Crossfade length")));
5910         l->set_alignment (0, 0.5);
5911         table.attach (*l, 0, 1, 0, 1);
5912
5913         SpinButton spin_crossfade (1, 0);
5914         spin_crossfade.set_range (0, 15);
5915         spin_crossfade.set_increments (1, 1);
5916         spin_crossfade.set_value (5);
5917         table.attach (spin_crossfade, 1, 2, 0, 1);
5918
5919         table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
5920
5921         l = manage (new Label (_("Pull-back length")));
5922         l->set_alignment (0, 0.5);
5923         table.attach (*l, 0, 1, 1, 2);
5924
5925         SpinButton spin_pullback (1, 0);
5926         spin_pullback.set_range (0, 100);
5927         spin_pullback.set_increments (1, 1);
5928         spin_pullback.set_value(30);
5929         table.attach (spin_pullback, 1, 2, 1, 2);
5930
5931         table.attach (*manage (new Label (_("ms"))), 2, 3, 1, 2);
5932
5933         dialog.get_vbox()->pack_start (table);
5934         dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL);
5935         dialog.add_button (_("Ok"), RESPONSE_ACCEPT);
5936         dialog.show_all ();
5937
5938         if (dialog.run () == RESPONSE_CANCEL) {
5939                 return;
5940         }
5941
5942         framepos_t crossfade_len = spin_crossfade.get_value();
5943         framepos_t pull_back_frames = spin_pullback.get_value();
5944
5945         crossfade_len = lrintf (crossfade_len * _session->frame_rate()/1000);
5946         pull_back_frames = lrintf (pull_back_frames * _session->frame_rate()/1000);
5947
5948         /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
5949
5950         _session->begin_reversible_command (_("close region gaps"));
5951
5952         int idx = 0;
5953         boost::shared_ptr<Region> last_region;
5954
5955         rs.sort_by_position_and_track();
5956
5957         for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
5958
5959                 boost::shared_ptr<Playlist> pl = (*r)->region()->playlist();
5960
5961                 if (!pl->frozen()) {
5962                         /* we haven't seen this playlist before */
5963
5964                         /* remember used playlists so we can thaw them later */
5965                         used_playlists.push_back(pl);
5966                         pl->freeze();
5967                 }
5968
5969                 framepos_t position = (*r)->region()->position();
5970
5971                 if (idx == 0 || position < last_region->position()){
5972                         last_region = (*r)->region();
5973                         idx++;
5974                         continue;
5975                 }
5976
5977                 (*r)->region()->trim_front( (position - pull_back_frames));
5978                 last_region->trim_end( (position - pull_back_frames + crossfade_len));
5979
5980                 last_region = (*r)->region();
5981
5982                 idx++;
5983         }
5984
5985         while (used_playlists.size() > 0) {
5986                 list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
5987                 (*i)->thaw();
5988                 used_playlists.pop_front();
5989         }
5990
5991         _session->commit_reversible_command ();
5992 }
5993
5994 void
5995 Editor::tab_to_transient (bool forward)
5996 {
5997         AnalysisFeatureList positions;
5998
5999         RegionSelection rs = get_regions_from_selection_and_entered ();
6000
6001         if (!_session) {
6002                 return;
6003         }
6004
6005         framepos_t pos = _session->audible_frame ();
6006
6007         if (!selection->tracks.empty()) {
6008
6009                 /* don't waste time searching for transients in duplicate playlists.
6010                  */
6011
6012                 TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
6013
6014                 for (TrackViewList::iterator t = ts.begin(); t != ts.end(); ++t) {
6015
6016                         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*t);
6017
6018                         if (rtv) {
6019                                 boost::shared_ptr<Track> tr = rtv->track();
6020                                 if (tr) {
6021                                         boost::shared_ptr<Playlist> pl = tr->playlist ();
6022                                         if (pl) {
6023                                                 framepos_t result = pl->find_next_transient (pos, forward ? 1 : -1);
6024
6025                                                 if (result >= 0) {
6026                                                         positions.push_back (result);
6027                                                 }
6028                                         }
6029                                 }
6030                         }
6031                 }
6032
6033         } else {
6034
6035                 if (rs.empty()) {
6036                         return;
6037                 }
6038
6039                 for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
6040                         (*r)->region()->get_transients (positions);
6041                 }
6042         }
6043
6044         TransientDetector::cleanup_transients (positions, _session->frame_rate(), 3.0);
6045
6046         if (forward) {
6047                 AnalysisFeatureList::iterator x;
6048
6049                 for (x = positions.begin(); x != positions.end(); ++x) {
6050                         if ((*x) > pos) {
6051                                 break;
6052                         }
6053                 }
6054
6055                 if (x != positions.end ()) {
6056                         _session->request_locate (*x);
6057                 }
6058
6059         } else {
6060                 AnalysisFeatureList::reverse_iterator x;
6061
6062                 for (x = positions.rbegin(); x != positions.rend(); ++x) {
6063                         if ((*x) < pos) {
6064                                 break;
6065                         }
6066                 }
6067
6068                 if (x != positions.rend ()) {
6069                         _session->request_locate (*x);
6070                 }
6071         }
6072 }
6073
6074 void
6075 Editor::playhead_forward_to_grid ()
6076 {
6077         if (!_session) return;
6078         framepos_t pos = playhead_cursor->current_frame;
6079         if (pos < max_framepos - 1) {
6080                 pos += 2;
6081                 snap_to_internal (pos, 1, false);
6082                 _session->request_locate (pos);
6083         }
6084 }
6085
6086
6087 void
6088 Editor::playhead_backward_to_grid ()
6089 {
6090         if (!_session) return;
6091         framepos_t pos = playhead_cursor->current_frame;
6092         if (pos > 2) {
6093                 pos -= 2;
6094                 snap_to_internal (pos, -1, false);
6095                 _session->request_locate (pos);
6096         }
6097 }
6098
6099 void
6100 Editor::set_track_height (Height h)
6101 {
6102         TrackSelection& ts (selection->tracks);
6103
6104         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6105                 (*x)->set_height_enum (h);
6106         }
6107 }
6108
6109 void
6110 Editor::toggle_tracks_active ()
6111 {
6112         TrackSelection& ts (selection->tracks);
6113         bool first = true;
6114         bool target = false;
6115
6116         if (ts.empty()) {
6117                 return;
6118         }
6119
6120         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6121                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*x);
6122
6123                 if (rtv) {
6124                         if (first) {
6125                                 target = !rtv->_route->active();
6126                                 first = false;
6127                         }
6128                         rtv->_route->set_active (target, this);
6129                 }
6130         }
6131 }
6132
6133 void
6134 Editor::remove_tracks ()
6135 {
6136         TrackSelection& ts (selection->tracks);
6137
6138         if (ts.empty()) {
6139                 return;
6140         }
6141
6142         vector<string> choices;
6143         string prompt;
6144         int ntracks = 0;
6145         int nbusses = 0;
6146         const char* trackstr;
6147         const char* busstr;
6148         vector<boost::shared_ptr<Route> > routes;
6149         bool special_bus = false;
6150
6151         for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
6152                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
6153                 if (rtv) {
6154                         if (rtv->is_track()) {
6155                                 ntracks++;
6156                         } else {
6157                                 nbusses++;
6158                         }
6159                 }
6160                 routes.push_back (rtv->_route);
6161
6162                 if (rtv->route()->is_master() || rtv->route()->is_monitor()) {
6163                         special_bus = true;
6164                 }
6165         }
6166
6167         if (special_bus && !Config->get_allow_special_bus_removal()) {
6168                 MessageDialog msg (_("That would be bad news ...."),
6169                                    false,
6170                                    Gtk::MESSAGE_INFO,
6171                                    Gtk::BUTTONS_OK);
6172                 msg.set_secondary_text (string_compose (_(
6173                                                                 "Removing the master or monitor bus is such a bad idea\n\
6174 that %1 is not going to allow it.\n\
6175 \n\
6176 If you really want to do this sort of thing\n\
6177 edit your ardour.rc file to set the\n\
6178 \"allow-special-bus-removal\" option to be \"yes\""), PROGRAM_NAME));
6179
6180                 msg.present ();
6181                 msg.run ();
6182                 return;
6183         }
6184
6185         if (ntracks + nbusses == 0) {
6186                 return;
6187         }
6188
6189         if (ntracks > 1) {
6190                 trackstr = _("tracks");
6191         } else {
6192                 trackstr = _("track");
6193         }
6194
6195         if (nbusses > 1) {
6196                 busstr = _("busses");
6197         } else {
6198                 busstr = _("bus");
6199         }
6200
6201         if (ntracks) {
6202                 if (nbusses) {
6203                         prompt  = string_compose (_("Do you really want to remove %1 %2 and %3 %4?\n"
6204                                                     "(You may also lose the playlists associated with the %2)\n\n"
6205                                                     "This action cannot be undone, and the session file will be overwritten!"),
6206                                                   ntracks, trackstr, nbusses, busstr);
6207                 } else {
6208                         prompt  = string_compose (_("Do you really want to remove %1 %2?\n"
6209                                                     "(You may also lose the playlists associated with the %2)\n\n"
6210                                                     "This action cannot be undone, and the session file will be overwritten!"),
6211                                                   ntracks, trackstr);
6212                 }
6213         } else if (nbusses) {
6214                 prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
6215                                             "This action cannot be undon, and the session file will be overwritten"),
6216                                           nbusses, busstr);
6217         }
6218
6219         choices.push_back (_("No, do nothing."));
6220         if (ntracks + nbusses > 1) {
6221                 choices.push_back (_("Yes, remove them."));
6222         } else {
6223                 choices.push_back (_("Yes, remove it."));
6224         }
6225
6226         string title;
6227         if (ntracks) {
6228                 title = string_compose (_("Remove %1"), trackstr);
6229         } else {
6230                 title = string_compose (_("Remove %1"), busstr);
6231         }
6232
6233         Choice prompter (title, prompt, choices);
6234
6235         if (prompter.run () != 1) {
6236                 return;
6237         }
6238
6239         for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
6240                 _session->remove_route (*x);
6241         }
6242 }
6243
6244 void
6245 Editor::do_insert_time ()
6246 {
6247         if (selection->tracks.empty()) {
6248                 return;
6249         }
6250
6251         InsertTimeDialog d (*this);
6252         int response = d.run ();
6253
6254         if (response != RESPONSE_OK) {
6255                 return;
6256         }
6257
6258         if (d.distance() == 0) {
6259                 return;
6260         }
6261
6262         InsertTimeOption opt = d.intersected_region_action ();
6263
6264         insert_time (
6265                 get_preferred_edit_position(),
6266                 d.distance(),
6267                 opt,
6268                 d.all_playlists(),
6269                 d.move_glued(),
6270                 d.move_markers(),
6271                 d.move_glued_markers(),
6272                 d.move_locked_markers(),
6273                 d.move_tempos()
6274                 );
6275 }
6276
6277 void
6278 Editor::insert_time (
6279         framepos_t pos, framecnt_t frames, InsertTimeOption opt,
6280         bool all_playlists, bool ignore_music_glue, bool markers_too, bool glued_markers_too, bool locked_markers_too, bool tempo_too
6281         )
6282 {
6283         bool commit = false;
6284
6285         if (Config->get_edit_mode() == Lock) {
6286                 return;
6287         }
6288
6289         begin_reversible_command (_("insert time"));
6290
6291         TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
6292
6293         for (TrackViewList::iterator x = ts.begin(); x != ts.end(); ++x) {
6294
6295                 /* regions */
6296
6297                 /* don't operate on any playlist more than once, which could
6298                  * happen if "all playlists" is enabled, but there is more
6299                  * than 1 track using playlists "from" a given track.
6300                  */
6301
6302                 set<boost::shared_ptr<Playlist> > pl;
6303
6304                 if (all_playlists) {
6305                         RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6306                         if (rtav) {
6307                                 vector<boost::shared_ptr<Playlist> > all = _session->playlists->playlists_for_track (rtav->track ());
6308                                 for (vector<boost::shared_ptr<Playlist> >::iterator p = all.begin(); p != all.end(); ++p) {
6309                                         pl.insert (*p);
6310                                 }
6311                         }
6312                 } else {
6313                         if ((*x)->playlist ()) {
6314                                 pl.insert ((*x)->playlist ());
6315                         }
6316                 }
6317                 
6318                 for (set<boost::shared_ptr<Playlist> >::iterator i = pl.begin(); i != pl.end(); ++i) {
6319
6320                         (*i)->clear_changes ();
6321                         (*i)->clear_owned_changes ();
6322
6323                         if (opt == SplitIntersected) {
6324                                 (*i)->split (pos);
6325                         }
6326
6327                         (*i)->shift (pos, frames, (opt == MoveIntersected), ignore_music_glue);
6328
6329                         vector<Command*> cmds;
6330                         (*i)->rdiff (cmds);
6331                         _session->add_commands (cmds);
6332
6333                         _session->add_command (new StatefulDiffCommand (*i));
6334                         commit = true;
6335                 }
6336
6337                 /* automation */
6338                 RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (*x);
6339                 if (rtav) {
6340                         rtav->route ()->shift (pos, frames);
6341                         commit = true;
6342                 }
6343         }
6344
6345         /* markers */
6346         if (markers_too) {
6347                 bool moved = false;
6348                 XMLNode& before (_session->locations()->get_state());
6349                 Locations::LocationList copy (_session->locations()->list());
6350
6351                 for (Locations::LocationList::iterator i = copy.begin(); i != copy.end(); ++i) {
6352
6353                         Locations::LocationList::const_iterator tmp;
6354
6355                         bool const was_locked = (*i)->locked ();
6356                         if (locked_markers_too) {
6357                                 (*i)->unlock ();
6358                         }
6359
6360                         if ((*i)->position_lock_style() == AudioTime || glued_markers_too) {
6361
6362                                 if ((*i)->start() >= pos) {
6363                                         (*i)->set_start ((*i)->start() + frames);
6364                                         if (!(*i)->is_mark()) {
6365                                                 (*i)->set_end ((*i)->end() + frames);
6366                                         }
6367                                         moved = true;
6368                                 }
6369
6370                         }
6371
6372                         if (was_locked) {
6373                                 (*i)->lock ();
6374                         }
6375                 }
6376
6377                 if (moved) {
6378                         XMLNode& after (_session->locations()->get_state());
6379                         _session->add_command (new MementoCommand<Locations>(*_session->locations(), &before, &after));
6380                 }
6381         }
6382
6383         if (tempo_too) {
6384                 _session->tempo_map().insert_time (pos, frames);
6385         }
6386
6387         if (commit) {
6388                 commit_reversible_command ();
6389         }
6390 }
6391
6392 void
6393 Editor::fit_selected_tracks ()
6394 {
6395         if (!selection->tracks.empty()) {
6396                 fit_tracks (selection->tracks);
6397         } else {
6398                 TrackViewList tvl;
6399
6400                 /* no selected tracks - use tracks with selected regions */
6401
6402                 if (!selection->regions.empty()) {
6403                         for (RegionSelection::iterator r = selection->regions.begin(); r != selection->regions.end(); ++r) {
6404                                 tvl.push_back (&(*r)->get_time_axis_view ());
6405                         }
6406
6407                         if (!tvl.empty()) {
6408                                 fit_tracks (tvl);
6409                         }
6410                 } else if (internal_editing()) {
6411                         /* no selected tracks, or regions, but in internal edit mode, so follow the mouse and use
6412                            the entered track
6413                         */
6414                         if (entered_track) {
6415                                 tvl.push_back (entered_track);
6416                                 fit_tracks (tvl);
6417                         }
6418                 }
6419         }
6420 }
6421
6422 void
6423 Editor::fit_tracks (TrackViewList & tracks)
6424 {
6425         if (tracks.empty()) {
6426                 return;
6427         }
6428
6429         uint32_t child_heights = 0;
6430         int visible_tracks = 0;
6431
6432         for (TrackSelection::iterator t = tracks.begin(); t != tracks.end(); ++t) {
6433
6434                 if (!(*t)->marked_for_display()) {
6435                         continue;
6436                 }
6437
6438                 child_heights += (*t)->effective_height() - (*t)->current_height();
6439                 ++visible_tracks;
6440         }
6441
6442         uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / visible_tracks);
6443         double first_y_pos = DBL_MAX;
6444
6445         if (h < TimeAxisView::preset_height (HeightSmall)) {
6446                 MessageDialog msg (*this, _("There are too many tracks to fit in the current window"));
6447                 /* too small to be displayed */
6448                 return;
6449         }
6450
6451         undo_visual_stack.push_back (current_visual_state());
6452
6453         /* build a list of all tracks, including children */
6454
6455         TrackViewList all;
6456         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
6457                 all.push_back (*i);
6458                 TimeAxisView::Children c = (*i)->get_child_list ();
6459                 for (TimeAxisView::Children::iterator j = c.begin(); j != c.end(); ++j) {
6460                         all.push_back (j->get());
6461                 }
6462         }
6463
6464         /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
6465
6466         bool prev_was_selected = false;
6467         bool is_selected = tracks.contains (all.front());
6468         bool next_is_selected;
6469
6470         for (TrackViewList::iterator t = all.begin(); t != all.end(); ++t) {
6471
6472                 TrackViewList::iterator next;
6473
6474                 next = t;
6475                 ++next;
6476
6477                 if (next != all.end()) {
6478                         next_is_selected = tracks.contains (*next);
6479                 } else {
6480                         next_is_selected = false;
6481                 }
6482
6483                 if ((*t)->marked_for_display ()) {
6484                         if (is_selected) {
6485                                 (*t)->set_height (h);
6486                                 first_y_pos = std::min ((*t)->y_position (), first_y_pos);
6487                         } else {
6488                                 if (prev_was_selected && next_is_selected) {
6489                                         hide_track_in_display (*t);
6490                                 }
6491                         }
6492                 }
6493
6494                 prev_was_selected = is_selected;
6495                 is_selected = next_is_selected;
6496         }
6497
6498         /*
6499            set the controls_layout height now, because waiting for its size
6500            request signal handler will cause the vertical adjustment setting to fail
6501         */
6502
6503         controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
6504         vertical_adjustment.set_value (first_y_pos);
6505
6506         redo_visual_stack.push_back (current_visual_state());
6507 }
6508
6509 void
6510 Editor::save_visual_state (uint32_t n)
6511 {
6512         while (visual_states.size() <= n) {
6513                 visual_states.push_back (0);
6514         }
6515
6516         delete visual_states[n];
6517
6518         visual_states[n] = current_visual_state (true);
6519         gdk_beep ();
6520 }
6521
6522 void
6523 Editor::goto_visual_state (uint32_t n)
6524 {
6525         if (visual_states.size() <= n) {
6526                 return;
6527         }
6528
6529         if (visual_states[n] == 0) {
6530                 return;
6531         }
6532
6533         use_visual_state (*visual_states[n]);
6534 }
6535
6536 void
6537 Editor::start_visual_state_op (uint32_t n)
6538 {
6539         if (visual_state_op_connection.empty()) {
6540                 visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
6541         }
6542 }
6543
6544 void
6545 Editor::cancel_visual_state_op (uint32_t n)
6546 {
6547         if (!visual_state_op_connection.empty()) {
6548                 visual_state_op_connection.disconnect();
6549                 goto_visual_state (n);
6550         }  else {
6551                 //we land here if called from the menu OR if end_visual_state_op has been called
6552                 //so check if we are already in visual state n
6553                 // XXX not yet checking it at all, but redoing does not hurt
6554                 goto_visual_state (n);
6555         }
6556 }
6557
6558 bool
6559 Editor::end_visual_state_op (uint32_t n)
6560 {
6561         visual_state_op_connection.disconnect();
6562         save_visual_state (n);
6563
6564         PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
6565         char buf[32];
6566         snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
6567         pup->set_text (buf);
6568         pup->touch();
6569
6570         return false; // do not call again
6571 }
6572
6573 void
6574 Editor::toggle_region_mute ()
6575 {
6576         if (_ignore_region_action) {
6577                 return;
6578         }
6579
6580         RegionSelection rs = get_regions_from_selection_and_entered ();
6581
6582         if (rs.empty ()) {
6583                 return;
6584         }
6585
6586         if (rs.size() > 1) {
6587                 begin_reversible_command (_("mute regions"));
6588         } else {
6589                 begin_reversible_command (_("mute region"));
6590         }
6591
6592         for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
6593
6594                 (*i)->region()->playlist()->clear_changes ();
6595                 (*i)->region()->set_muted (!(*i)->region()->muted ());
6596                 _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
6597
6598         }
6599
6600         commit_reversible_command ();
6601 }
6602
6603 void
6604 Editor::combine_regions ()
6605 {
6606         /* foreach track with selected regions, take all selected regions
6607            and join them into a new region containing the subregions (as a
6608            playlist)
6609         */
6610
6611         typedef set<RouteTimeAxisView*> RTVS;
6612         RTVS tracks;
6613
6614         if (selection->regions.empty()) {
6615                 return;
6616         }
6617
6618         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
6619                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&(*i)->get_time_axis_view());
6620
6621                 if (rtv) {
6622                         tracks.insert (rtv);
6623                 }
6624         }
6625
6626         begin_reversible_command (_("combine regions"));
6627
6628         vector<RegionView*> new_selection;
6629
6630         for (RTVS::iterator i = tracks.begin(); i != tracks.end(); ++i) {
6631                 RegionView* rv;
6632
6633                 if ((rv = (*i)->combine_regions ()) != 0) {
6634                         new_selection.push_back (rv);
6635                 }
6636         }
6637
6638         selection->clear_regions ();
6639         for (vector<RegionView*>::iterator i = new_selection.begin(); i != new_selection.end(); ++i) {
6640                 selection->add (*i);
6641         }
6642
6643         commit_reversible_command ();
6644 }
6645
6646 void
6647 Editor::uncombine_regions ()
6648 {
6649         typedef set<RouteTimeAxisView*> RTVS;
6650         RTVS tracks;
6651
6652         if (selection->regions.empty()) {
6653                 return;
6654         }
6655
6656         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
6657                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&(*i)->get_time_axis_view());
6658
6659                 if (rtv) {
6660                         tracks.insert (rtv);
6661                 }
6662         }
6663
6664         begin_reversible_command (_("uncombine regions"));
6665
6666         for (RTVS::iterator i = tracks.begin(); i != tracks.end(); ++i) {
6667                 (*i)->uncombine_regions ();
6668         }
6669
6670         commit_reversible_command ();
6671 }
6672