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