try to restore original semantics for scheduling butler transport work in Session...
[ardour.git] / gtk2_ardour / editor_ops.cc
index a07f16b5c8f393479e4f221916962870953167ed..2683020cbf0653f69df888bd77eaa39320ec9679 100644 (file)
@@ -24,6 +24,7 @@
 #include <cstdlib>
 #include <cmath>
 #include <string>
+#include <limits>
 #include <map>
 #include <set>
 
@@ -31,6 +32,7 @@
 #include "pbd/basename.h"
 #include "pbd/pthread_utils.h"
 #include "pbd/memento_command.h"
+#include "pbd/unwind.h"
 #include "pbd/whitespace.h"
 #include "pbd/stateful_diff_command.h"
 
 #include "ardour/dB.h"
 #include "ardour/location.h"
 #include "ardour/midi_region.h"
+#include "ardour/midi_track.h"
 #include "ardour/operations.h"
 #include "ardour/playlist_factory.h"
+#include "ardour/profile.h"
 #include "ardour/quantize.h"
+#include "ardour/legatize.h"
 #include "ardour/region_factory.h"
 #include "ardour/reverse.h"
-#include "ardour/route_group.h"
 #include "ardour/session.h"
 #include "ardour/session_playlists.h"
 #include "ardour/strip_silence.h"
 #include "ardour/transient_detector.h"
-#include "ardour/utils.h"
 
+#include "canvas/canvas.h"
+
+#include "actions.h"
 #include "ardour_ui.h"
-#include "debug.h"
-#include "editor.h"
-#include "time_axis_view.h"
-#include "route_time_axis.h"
+#include "audio_region_view.h"
+#include "audio_streamview.h"
 #include "audio_time_axis.h"
+#include "automation_region_view.h"
 #include "automation_time_axis.h"
-#include "streamview.h"
-#include "audio_streamview.h"
-#include "audio_region_view.h"
-#include "midi_region_view.h"
-#include "rgb_macros.h"
-#include "selection_templates.h"
-#include "selection.h"
+#include "control_point.h"
+#include "debug.h"
 #include "editing.h"
-#include "gtk-custom-hruler.h"
-#include "gui_thread.h"
-#include "keyboard.h"
-#include "utils.h"
+#include "editor.h"
+#include "editor_cursors.h"
 #include "editor_drag.h"
-#include "strip_silence_dialog.h"
-#include "editor_routes.h"
 #include "editor_regions.h"
-#include "quantize_dialog.h"
-#include "interthread_progress_window.h"
+#include "editor_routes.h"
+#include "gui_thread.h"
 #include "insert_time_dialog.h"
-#include "normalize_dialog.h"
-#include "editor_cursors.h"
+#include "interthread_progress_window.h"
+#include "item_counts.h"
+#include "keyboard.h"
+#include "midi_region_view.h"
+#include "mixer_strip.h"
 #include "mouse_cursors.h"
+#include "normalize_dialog.h"
+#include "note.h"
+#include "paste_context.h"
 #include "patch_change_dialog.h"
+#include "quantize_dialog.h"
+#include "region_gain_line.h"
+#include "rgb_macros.h"
+#include "route_time_axis.h"
+#include "selection.h"
+#include "selection_templates.h"
+#include "streamview.h"
+#include "strip_silence_dialog.h"
+#include "time_axis_view.h"
 #include "transpose_dialog.h"
+#include "transform_dialog.h"
 
 #include "i18n.h"
 
@@ -110,6 +122,11 @@ Editor::undo (uint32_t n)
        
        if (_session) {
                _session->undo (n);
+               if (_session->undo_depth() == 0) {
+                       undo_action->set_sensitive(false);
+               }
+               redo_action->set_sensitive(true);
+               begin_selection_op_history ();
        }
 }
 
@@ -122,6 +139,11 @@ Editor::redo (uint32_t n)
        
        if (_session) {
                _session->redo (n);
+               if (_session->redo_depth() == 0) {
+                       redo_action->set_sensitive(false);
+               }
+               undo_action->set_sensitive(true);
+               begin_selection_op_history ();
        }
 }
 
@@ -130,7 +152,11 @@ Editor::split_regions_at (framepos_t where, RegionSelection& regions)
 {
        bool frozen = false;
 
-       list <boost::shared_ptr<Playlist > > used_playlists;
+       RegionSelection pre_selected_regions = selection->regions;
+       bool working_on_selection = !pre_selected_regions.empty();
+
+       list<boost::shared_ptr<Playlist> > used_playlists;
+       list<RouteTimeAxisView*> used_trackviews;
 
        if (regions.empty()) {
                return;
@@ -185,9 +211,16 @@ Editor::split_regions_at (framepos_t where, RegionSelection& regions)
 
                        /* remember used playlists so we can thaw them later */
                        used_playlists.push_back(pl);
+
+                       TimeAxisView& tv = (*a)->get_time_axis_view();
+                       RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&tv);
+                       if (rtv) {
+                               used_trackviews.push_back (rtv);
+                       }
                        pl->freeze();
                }
 
+
                if (pl) {
                        pl->clear_changes ();
                        pl->split_region ((*a)->region(), where);
@@ -197,17 +230,68 @@ Editor::split_regions_at (framepos_t where, RegionSelection& regions)
                a = tmp;
        }
 
+       latest_regionviews.clear ();
+
+       vector<sigc::connection> region_added_connections;
+
+       for (list<RouteTimeAxisView*>::iterator i = used_trackviews.begin(); i != used_trackviews.end(); ++i) {
+               region_added_connections.push_back ((*i)->view()->RegionViewAdded.connect (sigc::mem_fun(*this, &Editor::collect_new_region_view)));
+       }
+       
        while (used_playlists.size() > 0) {
                list <boost::shared_ptr<Playlist > >::iterator i = used_playlists.begin();
                (*i)->thaw();
                used_playlists.pop_front();
        }
 
-       commit_reversible_command ();
+       for (vector<sigc::connection>::iterator c = region_added_connections.begin(); c != region_added_connections.end(); ++c) {
+               (*c).disconnect ();
+       }
 
        if (frozen){
                EditorThaw(); /* Emit Signal */
        }
+
+       if (working_on_selection) {
+               // IFF we were working on selected regions, try to reinstate the other region selections that existed before the freeze/thaw.
+
+               _ignore_follow_edits = true;  // a split will change the region selection in mysterious ways;  it's not practical or wanted to follow this edit
+               RegionSelectionAfterSplit rsas = Config->get_region_selection_after_split();
+               /* There are three classes of regions that we might want selected after
+                  splitting selected regions:
+                   - regions selected before the split operation, and unaffected by it
+                   - newly-created regions before the split
+                   - newly-created regions after the split
+                */
+
+               if (rsas & Existing) {
+                       // region selections that existed before the split.
+                       selection->add ( pre_selected_regions );
+               }
+
+               for (RegionSelection::iterator ri = latest_regionviews.begin(); ri != latest_regionviews.end(); ri++) {
+                       if ((*ri)->region()->position() < where) {
+                               // new regions created before the split
+                               if (rsas & NewlyCreatedLeft) {
+                                       selection->add (*ri);
+                               }
+                       } else {
+                               // new regions created after the split
+                               if (rsas & NewlyCreatedRight) {
+                                       selection->add (*ri);
+                               }
+                       }
+               }
+               _ignore_follow_edits = false;
+       } else {
+               _ignore_follow_edits = true;
+               if( working_on_selection ) {
+                       selection->add (latest_regionviews);  //these are the new regions created after the split
+               }
+               _ignore_follow_edits = false;
+       }
+
+       commit_reversible_command ();
 }
 
 /** Move one extreme of the current range selection.  If more than one range is selected,
@@ -356,8 +440,8 @@ Editor::nudge_forward (bool next, bool force_playhead)
                commit_reversible_command ();
 
        } else {
-               distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
-               _session->request_locate (playhead_cursor->current_frame + distance);
+               distance = get_nudge_distance (playhead_cursor->current_frame (), next_distance);
+               _session->request_locate (playhead_cursor->current_frame () + distance);
        }
 }
 
@@ -445,10 +529,10 @@ Editor::nudge_backward (bool next, bool force_playhead)
 
        } else {
 
-               distance = get_nudge_distance (playhead_cursor->current_frame, next_distance);
+               distance = get_nudge_distance (playhead_cursor->current_frame (), next_distance);
 
-               if (playhead_cursor->current_frame > distance) {
-                       _session->request_locate (playhead_cursor->current_frame - distance);
+               if (playhead_cursor->current_frame () > distance) {
+                       _session->request_locate (playhead_cursor->current_frame () - distance);
                } else {
                        _session->goto_start();
                }
@@ -488,7 +572,7 @@ Editor::nudge_backward_capture_offset ()
                return;
        }
 
-       begin_reversible_command (_("nudge forward"));
+       begin_reversible_command (_("nudge backward"));
 
        framepos_t const distance = _session->worst_output_latency();
 
@@ -508,6 +592,60 @@ Editor::nudge_backward_capture_offset ()
        commit_reversible_command ();
 }
 
+struct RegionSelectionPositionSorter {
+        bool operator() (RegionView* a, RegionView* b) {
+                return a->region()->position() < b->region()->position();
+        }
+};
+
+void
+Editor::sequence_regions ()
+{
+       framepos_t r_end;
+       framepos_t r_end_prev;
+
+       int iCount=0;
+
+       if (!_session) {
+               return;
+       }
+
+       RegionSelection rs = get_regions_from_selection_and_entered ();
+       rs.sort(RegionSelectionPositionSorter());
+
+       if (!rs.empty()) {
+
+               begin_reversible_command (_("sequence regions"));
+               for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
+                       boost::shared_ptr<Region> r ((*i)->region());
+
+                       r->clear_changes();
+
+                       if(r->locked())
+                       {
+                               continue;
+                       }
+                       if(r->position_locked())
+                       {
+                               continue;
+                       }
+                       if(iCount>0)
+                       {
+                               r_end_prev=r_end;
+                               r->set_position(r_end_prev);
+                       }
+
+                       _session->add_command (new StatefulDiffCommand (r));
+
+                       r_end=r->position() + r->length();
+
+                       iCount++;
+               }
+               commit_reversible_command ();
+       } 
+} 
+
+
 /* DISPLAY MOTION */
 
 void
@@ -554,7 +692,7 @@ Editor::build_region_boundary_cache ()
                break;
        default:
                fatal << string_compose (_("build_region_boundary_cache called with snap_type = %1"), _snap_type) << endmsg;
-               /*NOTREACHED*/
+               abort(); /*NOTREACHED*/
                return;
        }
 
@@ -771,7 +909,7 @@ Editor::get_region_boundary (framepos_t pos, int32_t dir, bool with_selection, b
 void
 Editor::cursor_to_region_boundary (bool with_selection, int32_t dir)
 {
-       framepos_t pos = playhead_cursor->current_frame;
+       framepos_t pos = playhead_cursor->current_frame ();
        framepos_t target;
 
        if (!_session) {
@@ -806,7 +944,7 @@ void
 Editor::cursor_to_region_point (EditorCursor* cursor, RegionPoint point, int32_t dir)
 {
        boost::shared_ptr<Region> r;
-       framepos_t pos = cursor->current_frame;
+       framepos_t pos = cursor->current_frame ();
 
        if (!_session) {
                return;
@@ -1142,8 +1280,8 @@ Editor::selected_marker_to_selection_end ()
 void
 Editor::scroll_playhead (bool forward)
 {
-       framepos_t pos = playhead_cursor->current_frame;
-       framecnt_t delta = (framecnt_t) floor (current_page_frames() / 0.8);
+       framepos_t pos = playhead_cursor->current_frame ();
+       framecnt_t delta = (framecnt_t) floor (current_page_samples() / 0.8);
 
        if (forward) {
                if (pos == max_framepos) {
@@ -1196,10 +1334,10 @@ Editor::cursor_align (bool playhead_to_edit)
                        Location* loc = find_location_from_marker (*i, ignored);
 
                        if (loc->is_mark()) {
-                               loc->set_start (playhead_cursor->current_frame);
+                               loc->set_start (playhead_cursor->current_frame ());
                        } else {
-                               loc->set (playhead_cursor->current_frame,
-                                         playhead_cursor->current_frame + loc->length());
+                               loc->set (playhead_cursor->current_frame (),
+                                         playhead_cursor->current_frame () + loc->length());
                        }
                }
        }
@@ -1208,7 +1346,7 @@ Editor::cursor_align (bool playhead_to_edit)
 void
 Editor::scroll_backward (float pages)
 {
-       framepos_t const one_page = (framepos_t) rint (_canvas_width * frames_per_unit);
+       framepos_t const one_page = (framepos_t) rint (_visible_canvas_width * samples_per_pixel);
        framepos_t const cnt = (framepos_t) floor (pages * one_page);
 
        framepos_t frame;
@@ -1224,7 +1362,7 @@ Editor::scroll_backward (float pages)
 void
 Editor::scroll_forward (float pages)
 {
-       framepos_t const one_page = (framepos_t) rint (_canvas_width * frames_per_unit);
+       framepos_t const one_page = (framepos_t) rint (_visible_canvas_width * samples_per_pixel);
        framepos_t const cnt = (framepos_t) floor (pages * one_page);
 
        framepos_t frame;
@@ -1241,8 +1379,8 @@ void
 Editor::scroll_tracks_down ()
 {
        double vert_value = vertical_adjustment.get_value() + vertical_adjustment.get_page_size();
-       if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
-               vert_value = vertical_adjustment.get_upper() - _canvas_height;
+       if (vert_value > vertical_adjustment.get_upper() - _visible_canvas_height) {
+               vert_value = vertical_adjustment.get_upper() - _visible_canvas_height;
        }
 
        vertical_adjustment.set_value (vert_value);
@@ -1259,8 +1397,8 @@ Editor::scroll_tracks_down_line ()
 {
        double vert_value = vertical_adjustment.get_value() + 60;
 
-       if (vert_value > vertical_adjustment.get_upper() - _canvas_height) {
-               vert_value = vertical_adjustment.get_upper() - _canvas_height;
+       if (vert_value > vertical_adjustment.get_upper() - _visible_canvas_height) {
+               vert_value = vertical_adjustment.get_upper() - _visible_canvas_height;
        }
 
        vertical_adjustment.set_value (vert_value);
@@ -1272,47 +1410,148 @@ Editor::scroll_tracks_up_line ()
        reset_y_origin (vertical_adjustment.get_value() - 60);
 }
 
+bool
+Editor::scroll_down_one_track ()
+{
+       TrackViewList::reverse_iterator next = track_views.rend();
+       std::pair<TimeAxisView*,double> res;
+       const double top_of_trackviews = vertical_adjustment.get_value();
+
+       for (TrackViewList::reverse_iterator t = track_views.rbegin(); t != track_views.rend(); ++t) {
+               if ((*t)->hidden()) {
+                       continue;
+               }
+
+
+               /* If this is the upper-most visible trackview, we want to display
+                  the one above it (next)
+               */
+
+               res = (*t)->covers_y_position (top_of_trackviews);
+
+               if (res.first) {
+                       break;
+               }
+               next = t;
+       }
+
+       /* move to the track below the first one that covers the */
+       
+       if (next != track_views.rend()) {
+               ensure_time_axis_view_is_visible (**next, true);
+               return true;
+       }
+
+       return false;
+}      
+
+bool
+Editor::scroll_up_one_track ()
+{
+       TrackViewList::iterator prev = track_views.end();
+       std::pair<TimeAxisView*,double> res;
+       double top_of_trackviews = vertical_adjustment.get_value ();
+       
+       for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
+
+               if ((*t)->hidden()) {
+                       continue;
+               }
+
+               /* find the trackview at the top of the trackview group */
+               res = (*t)->covers_y_position (top_of_trackviews);
+               
+               if (res.first) {
+                       break;
+               }
+
+               prev = t;
+       }
+       
+       if (prev != track_views.end()) {
+               ensure_time_axis_view_is_visible (**prev, true);
+               return true;
+       }
+
+       return false;
+}
+
 /* ZOOM */
 
 void
 Editor::tav_zoom_step (bool coarser)
 {
-       ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
+       DisplaySuspender ds;
 
-       _routes->suspend_redisplay ();
+       TrackViewList* ts;
 
-       for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
+       if (selection->tracks.empty()) {
+               ts = &track_views;
+       } else {
+               ts = &selection->tracks;
+       }
+       
+       for (TrackViewList::iterator i = ts->begin(); i != ts->end(); ++i) {
                TimeAxisView *tv = (static_cast<TimeAxisView*>(*i));
                        tv->step_height (coarser);
        }
+}
+
+void
+Editor::tav_zoom_smooth (bool coarser, bool force_all)
+{
+       DisplaySuspender ds;
+
+       TrackViewList* ts;
+
+       if (selection->tracks.empty() || force_all) {
+               ts = &track_views;
+       } else {
+               ts = &selection->tracks;
+       }
+       
+       for (TrackViewList::iterator i = ts->begin(); i != ts->end(); ++i) {
+               TimeAxisView *tv = (static_cast<TimeAxisView*>(*i));
+               uint32_t h = tv->current_height ();
 
-       _routes->resume_redisplay ();
+               if (coarser) {
+                       if (h > 5) {
+                               h -= 5; // pixels
+                               if (h >= TimeAxisView::preset_height (HeightSmall)) {
+                                       tv->set_height (h);
+                               }
+                       }
+               } else {
+                       tv->set_height (h + 5);
+               }
+       }
 }
 
+
 void
 Editor::temporal_zoom_step (bool coarser)
 {
        ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
 
-       double nfpu;
-
-       nfpu = frames_per_unit;
+       framecnt_t nspp = samples_per_pixel;
 
        if (coarser) {
-               nfpu *= 1.61803399;
+               nspp *= 2;
        } else {
-               nfpu = max(1.0,(nfpu/1.61803399));
+               nspp /= 2;
        }
 
-       temporal_zoom (nfpu);
+       temporal_zoom (nspp);
 }
 
 void
-Editor::temporal_zoom (gdouble fpu)
+Editor::temporal_zoom (framecnt_t fpp)
 {
-       if (!_session) return;
+       if (!_session) {
+               return;
+       }
 
-       framepos_t current_page = current_page_frames();
+       framepos_t current_page = current_page_samples();
        framepos_t current_leftmost = leftmost_frame;
        framepos_t current_rightmost;
        framepos_t current_center;
@@ -1321,18 +1560,25 @@ Editor::temporal_zoom (gdouble fpu)
        framepos_t leftmost_after_zoom = 0;
        framepos_t where;
        bool in_track_canvas;
-       double nfpu;
+       framecnt_t nfpp;
        double l;
 
-       /* XXX this limit is also in ::set_frames_per_unit() */
-
-       if (frames_per_unit <= 1.0 && fpu <= frames_per_unit) {
+       if (fpp == samples_per_pixel) {
                return;
        }
 
-       nfpu = fpu;
+       // Imposing an arbitrary limit to zoom out as too much zoom out produces 
+       // segfaults for lack of memory. If somebody decides this is not high enough I
+       // believe it can be raisen to higher values but some limit must be in place.
+       //
+       // This constant represents 1 day @ 48kHz on a 1600 pixel wide display
+       // all of which is used for the editor track displays. The whole day
+       // would be 4147200000 samples, so 2592000 samples per pixel.
 
-       new_page_size = (framepos_t) floor (_canvas_width * nfpu);
+       nfpp = min (fpp, (framecnt_t) 2592000);
+       nfpp = max ((framecnt_t) 1, nfpp);
+
+       new_page_size = (framepos_t) floor (_visible_canvas_width * nfpp);
        half_page_size = new_page_size / 2;
 
        switch (zoom_focus) {
@@ -1360,7 +1606,7 @@ Editor::temporal_zoom (gdouble fpu)
 
        case ZoomFocusPlayhead:
                /* centre playhead */
-               l = playhead_cursor->current_frame - (new_page_size * 0.5);
+               l = playhead_cursor->current_frame () - (new_page_size * 0.5);
 
                if (l < 0) {
                        leftmost_after_zoom = 0;
@@ -1376,7 +1622,7 @@ Editor::temporal_zoom (gdouble fpu)
 
                if (!mouse_frame (where, in_track_canvas)) {
                        /* use playhead instead */
-                       where = playhead_cursor->current_frame;
+                       where = playhead_cursor->current_frame ();
 
                        if (where < half_page_size) {
                                leftmost_after_zoom = 0;
@@ -1425,53 +1671,26 @@ Editor::temporal_zoom (gdouble fpu)
 
        // leftmost_after_zoom = min (leftmost_after_zoom, _session->current_end_frame());
 
-       reposition_and_zoom (leftmost_after_zoom, nfpu);
+       reposition_and_zoom (leftmost_after_zoom, nfpp);
 }
 
 void
-Editor::temporal_zoom_region (bool both_axes)
+Editor::calc_extra_zoom_edges(framepos_t &start, framepos_t &end)
 {
-       framepos_t start = max_framepos;
-       framepos_t end = 0;
-       set<TimeAxisView*> tracks;
-
-       RegionSelection rs = get_regions_from_selection_and_entered ();
-
-       if (rs.empty()) {
-               return;
-       }
-
-       for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
-
-               if ((*i)->region()->position() < start) {
-                       start = (*i)->region()->position();
-               }
-
-               if ((*i)->region()->last_frame() + 1 > end) {
-                       end = (*i)->region()->last_frame() + 1;
-               }
-
-               tracks.insert (&((*i)->get_time_axis_view()));
-       }
-
-       /* now comes an "interesting" hack ... make sure we leave a little space
+       /* this func helps make sure we leave a little space
           at each end of the editor so that the zoom doesn't fit the region
           precisely to the screen.
        */
 
        GdkScreen* screen = gdk_screen_get_default ();
-       gint pixwidth = gdk_screen_get_width (screen);
-       gint mmwidth = gdk_screen_get_width_mm (screen);
-       double pix_per_mm = (double) pixwidth/ (double) mmwidth;
-       double one_centimeter_in_pixels = pix_per_mm * 10.0;
-
-       if ((start == 0 && end == 0) || end < start) {
-               return;
-       }
+       const gint pixwidth = gdk_screen_get_width (screen);
+       const gint mmwidth = gdk_screen_get_width_mm (screen);
+       const double pix_per_mm = (double) pixwidth/ (double) mmwidth;
+       const double one_centimeter_in_pixels = pix_per_mm * 10.0;
 
-       framepos_t range = end - start;
-       double new_fpu = (double)range / (double)_canvas_width;
-       framepos_t extra_samples = (framepos_t) floor (one_centimeter_in_pixels * new_fpu);
+       const framepos_t range = end - start;
+       const framecnt_t new_fpp = (framecnt_t) ceil ((double) range / (double) _visible_canvas_width);
+       const framepos_t extra_samples = (framepos_t) floor (one_centimeter_in_pixels * new_fpp);
 
        if (start > extra_samples) {
                start -= extra_samples;
@@ -1484,19 +1703,31 @@ Editor::temporal_zoom_region (bool both_axes)
        } else {
                end = max_framepos;
        }
+}
 
-       if (both_axes) {
-               /* save visual state with track states included, and prevent
-                  set_frames_per_unit() from doing it again.
-               */
-               undo_visual_stack.push_back (current_visual_state(true));
-               no_save_visual = true;
-       }
+void
+Editor::temporal_zoom_region (bool both_axes)
+{
+       framepos_t start = max_framepos;
+       framepos_t end = 0;
+       set<TimeAxisView*> tracks;
+
+       if ( !get_selection_extents(start, end) )
+               return;
+       
+       calc_extra_zoom_edges (start, end);
 
-       temporal_zoom_by_frame (start, end, "zoom to region");
+       /* if we're zooming on both axes we need to save track heights etc.
+        */
 
+       undo_visual_stack.push_back (current_visual_state (both_axes));
+
+       PBD::Unwinder<bool> nsv (no_save_visual, true);
+
+       temporal_zoom_by_frame (start, end);
+       
        if (both_axes) {
-               uint32_t per_track_height = (uint32_t) floor ((_canvas_height - canvas_timebars_vsize - 10.0) / tracks.size());
+               uint32_t per_track_height = (uint32_t) floor ((_visible_canvas_height - 10.0) / tracks.size());
 
                /* set visible track heights appropriately */
 
@@ -1506,7 +1737,7 @@ Editor::temporal_zoom_region (bool both_axes)
 
                /* hide irrelevant tracks */
 
-               _routes->suspend_redisplay ();
+               DisplaySuspender ds;
 
                for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
                        if (find (tracks.begin(), tracks.end(), (*i)) == tracks.end()) {
@@ -1514,34 +1745,79 @@ Editor::temporal_zoom_region (bool both_axes)
                        }
                }
 
-               _routes->resume_redisplay ();
-
                vertical_adjustment.set_value (0.0);
-               no_save_visual = false;
        }
 
-       redo_visual_stack.push_back (current_visual_state());
+       redo_visual_stack.push_back (current_visual_state (both_axes));
 }
 
-void
-Editor::zoom_to_region (bool both_axes)
+
+bool
+Editor::get_selection_extents ( framepos_t &start, framepos_t &end )
 {
-       temporal_zoom_region (both_axes);
+       start = max_framepos;
+       end = 0;
+       bool ret = true;
+       
+       //ToDo:  if notes are selected, set extents to that selection
+
+       //ToDo:  if control points are selected, set extents to that selection
+
+       if ( !selection->regions.empty() ) {
+               RegionSelection rs = get_regions_from_selection_and_entered ();
+
+               for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
+
+                       if ((*i)->region()->position() < start) {
+                               start = (*i)->region()->position();
+                       }
+
+                       if ((*i)->region()->last_frame() + 1 > end) {
+                               end = (*i)->region()->last_frame() + 1;
+                       }
+               }
+
+       } else if (!selection->time.empty()) {
+               start = selection->time.start();
+               end = selection->time.end_frame();
+       } else 
+               ret = false;  //no selection found
+
+       //range check
+       if ((start == 0 && end == 0) || end < start) {
+               ret = false;
+       }
+       
+       return ret;     
 }
 
+
 void
-Editor::temporal_zoom_selection ()
+Editor::temporal_zoom_selection (bool both_axes)
 {
        if (!selection) return;
 
-       if (selection->time.empty()) {
-               return;
-       }
+       //ToDo:  if notes are selected, zoom to that
 
-       framepos_t start = selection->time[clicked_selection].start;
-       framepos_t end = selection->time[clicked_selection].end;
+       //ToDo:  if control points are selected, zoom to that
+
+       //if region(s) are selected, zoom to that
+       if ( !selection->regions.empty() )
+               temporal_zoom_region (both_axes);
+
+       //if a range is selected, zoom to that
+       if (!selection->time.empty()) {
+
+               framepos_t start,  end;
+               if (get_selection_extents (start, end)) {
+                       calc_extra_zoom_edges(start, end);
+                       temporal_zoom_by_frame (start, end);
+               }
+               
+               if (both_axes)
+                       fit_selection();
+       }
 
-       temporal_zoom_by_frame (start, end, "zoom to selection");
 }
 
 void
@@ -1550,18 +1826,33 @@ Editor::temporal_zoom_session ()
        ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_session)
 
        if (_session) {
-               framecnt_t const l = _session->current_end_frame() - _session->current_start_frame();
-               double s = _session->current_start_frame() - l * 0.01;
-               if (s < 0) {
-                       s = 0;
+               framecnt_t start = _session->current_start_frame();
+               framecnt_t end = _session->current_end_frame();
+
+               if (_session->actively_recording () ) {
+                       framepos_t cur = playhead_cursor->current_frame ();
+                       if (cur > end) {
+                               /* recording beyond the end marker; zoom out
+                                * by 5 seconds more so that if 'follow
+                                * playhead' is active we don't immediately
+                                * scroll.
+                                */
+                               end = cur + _session->frame_rate() * 5;
+                       }
                }
-               framecnt_t const e = _session->current_end_frame() + l * 0.01;
-               temporal_zoom_by_frame (framecnt_t (s), e, "zoom to _session");
+
+               if ((start == 0 && end == 0) || end < start) {
+                       return;
+               }
+
+               calc_extra_zoom_edges(start, end);
+
+               temporal_zoom_by_frame (start, end);
        }
 }
 
 void
-Editor::temporal_zoom_by_frame (framepos_t start, framepos_t end, const string & /*op*/)
+Editor::temporal_zoom_by_frame (framepos_t start, framepos_t end)
 {
        if (!_session) return;
 
@@ -1571,18 +1862,22 @@ Editor::temporal_zoom_by_frame (framepos_t start, framepos_t end, const string &
 
        framepos_t range = end - start;
 
-       double new_fpu = (double)range / (double)_canvas_width;
-
-       framepos_t new_page = (framepos_t) floor (_canvas_width * new_fpu);
-       framepos_t middle = (framepos_t) floor( (double)start + ((double)range / 2.0f ));
-       framepos_t new_leftmost = (framepos_t) floor( (double)middle - ((double)new_page/2.0f));
+       const framecnt_t new_fpp = (framecnt_t) ceil ((double) range / (double) _visible_canvas_width);
+       
+       framepos_t new_page = range;
+       framepos_t middle = (framepos_t) floor ((double) start + ((double) range / 2.0f));
+       framepos_t new_leftmost = (framepos_t) floor ((double) middle - ((double) new_page / 2.0f));
 
        if (new_leftmost > middle) {
                new_leftmost = 0;
        }
 
-       reposition_and_zoom (new_leftmost, new_fpu);
-}
+       if (new_leftmost < 0) {
+               new_leftmost = 0;
+       }
+
+       reposition_and_zoom (new_leftmost, new_fpp);
+}
 
 void
 Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
@@ -1590,23 +1885,38 @@ Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
        if (!_session) {
                return;
        }
-       double range_before = frame - leftmost_frame;
-       double new_fpu;
 
-       new_fpu = frames_per_unit;
+       framecnt_t range_before = frame - leftmost_frame;
+       framecnt_t new_spp;
 
        if (coarser) {
-               new_fpu *= 1.61803399;
-               range_before *= 1.61803399;
+               if (samples_per_pixel <= 1) {
+                       new_spp = 2;
+               } else {
+                       new_spp = samples_per_pixel + (samples_per_pixel/2);
+               }
+               range_before += range_before/2;
        } else {
-               new_fpu = max(1.0,(new_fpu/1.61803399));
-               range_before /= 1.61803399;
+               if (samples_per_pixel >= 1) {
+                       new_spp = samples_per_pixel - (samples_per_pixel/2);
+               } else {
+                       /* could bail out here since we cannot zoom any finer,
+                          but leave that to the equality test below
+                       */
+                       new_spp = samples_per_pixel;
+               }
+
+               range_before -= range_before/2;
        }
 
-       if (new_fpu == frames_per_unit)  {
+       if (new_spp == samples_per_pixel)  {
                return;
        }
 
+       /* zoom focus is automatically taken as @param frame when this
+          method is used.
+       */
+       
        framepos_t new_leftmost = frame - (framepos_t)range_before;
 
        if (new_leftmost > frame) {
@@ -1617,14 +1927,14 @@ Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
                new_leftmost = 0;
        }
 
-       reposition_and_zoom (new_leftmost, new_fpu);
+       reposition_and_zoom (new_leftmost, new_spp);
 }
 
 
 bool
 Editor::choose_new_marker_name(string &name) {
 
-       if (!Config->get_name_new_markers()) {
+       if (!ARDOUR_UI::config()->get_name_new_markers()) {
                /* don't prompt user for a new name */
                return true;
        }
@@ -1676,12 +1986,14 @@ Editor::add_location_from_selection ()
        _session->locations()->next_available_name(rangename,"selection");
        Location *location = new Location (*_session, start, end, rangename, Location::IsRangeMarker);
 
-       _session->begin_reversible_command (_("add marker"));
+       begin_reversible_command (_("add marker"));
+       
        XMLNode &before = _session->locations()->get_state();
        _session->locations()->add (location, true);
        XMLNode &after = _session->locations()->get_state();
        _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -1696,12 +2008,14 @@ Editor::add_location_mark (framepos_t where)
                return;
        }
        Location *location = new Location (*_session, where, where, markername, Location::IsMark);
-       _session->begin_reversible_command (_("add marker"));
+       begin_reversible_command (_("add marker"));
+       
        XMLNode &before = _session->locations()->get_state();
        _session->locations()->add (location, true);
        XMLNode &after = _session->locations()->get_state();
        _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -1710,6 +2024,37 @@ Editor::add_location_from_playhead_cursor ()
        add_location_mark (_session->audible_frame());
 }
 
+void
+Editor::remove_location_at_playhead_cursor ()
+{
+       if (_session) {
+
+               //set up for undo
+               begin_reversible_command (_("remove marker"));
+               
+               XMLNode &before = _session->locations()->get_state();
+               bool removed = false;
+
+               //find location(s) at this time
+               Locations::LocationList locs;
+               _session->locations()->find_all_between (_session->audible_frame(), _session->audible_frame()+1, locs, Location::Flags(0));
+               for (Locations::LocationList::iterator i = locs.begin(); i != locs.end(); ++i) {
+                       if ((*i)->is_mark()) {
+                               _session->locations()->remove (*i);
+                               removed = true;
+                       }
+               }
+               
+               //store undo
+               if (removed) {
+                       XMLNode &after = _session->locations()->get_state();
+                       _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
+                       
+                       commit_reversible_command ();
+               }
+       }
+}
+
 /** Add a range marker around each selected region */
 void
 Editor::add_locations_from_region ()
@@ -1720,7 +2065,8 @@ Editor::add_locations_from_region ()
                return;
        }
 
-       _session->begin_reversible_command (selection->regions.size () > 1 ? _("add markers") : _("add marker"));
+       begin_reversible_command (selection->regions.size () > 1 ? _("add markers") : _("add marker"));
+       
        XMLNode &before = _session->locations()->get_state();
 
        for (RegionSelection::iterator i = rs.begin (); i != rs.end (); ++i) {
@@ -1734,7 +2080,8 @@ Editor::add_locations_from_region ()
 
        XMLNode &after = _session->locations()->get_state();
        _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 /** Add a single range marker around all selected regions */
@@ -1747,7 +2094,8 @@ Editor::add_location_from_region ()
                return;
        }
 
-       _session->begin_reversible_command (_("add marker"));
+       begin_reversible_command (_("add marker"));
+       
        XMLNode &before = _session->locations()->get_state();
 
        string markername;
@@ -1770,7 +2118,8 @@ Editor::add_location_from_region ()
 
        XMLNode &after = _session->locations()->get_state();
        _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 /* MARKS */
@@ -1782,13 +2131,13 @@ Editor::jump_forward_to_mark ()
                return;
        }
 
-       Location *location = _session->locations()->first_location_after (playhead_cursor->current_frame);
+       framepos_t pos = _session->locations()->first_mark_after (playhead_cursor->current_frame());
 
-       if (location) {
-               _session->request_locate (location->start(), _session->transport_rolling());
-       } else {
-               _session->request_locate (_session->current_end_frame());
+       if (pos < 0) {
+               return;
        }
+       
+       _session->request_locate (pos, _session->transport_rolling());
 }
 
 void
@@ -1798,13 +2147,13 @@ Editor::jump_backward_to_mark ()
                return;
        }
 
-       Location *location = _session->locations()->first_location_before (playhead_cursor->current_frame);
+       framepos_t pos = _session->locations()->first_mark_before (playhead_cursor->current_frame());
 
-       if (location) {
-               _session->request_locate (location->start(), _session->transport_rolling());
-       } else {
-               _session->goto_start ();
+       if (pos < 0) {
+               return;
        }
+
+       _session->request_locate (pos, _session->transport_rolling());
 }
 
 void
@@ -1826,12 +2175,14 @@ void
 Editor::clear_markers ()
 {
        if (_session) {
-               _session->begin_reversible_command (_("clear markers"));
+               begin_reversible_command (_("clear markers"));
+               
                XMLNode &before = _session->locations()->get_state();
                _session->locations()->clear_markers ();
                XMLNode &after = _session->locations()->get_state();
                _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-               _session->commit_reversible_command ();
+               
+               commit_reversible_command ();
        }
 }
 
@@ -1839,35 +2190,30 @@ void
 Editor::clear_ranges ()
 {
        if (_session) {
-               _session->begin_reversible_command (_("clear ranges"));
+               begin_reversible_command (_("clear ranges"));
+               
                XMLNode &before = _session->locations()->get_state();
 
-               Location * looploc = _session->locations()->auto_loop_location();
-               Location * punchloc = _session->locations()->auto_punch_location();
-               Location * sessionloc = _session->locations()->session_range_location();
-
                _session->locations()->clear_ranges ();
-               // re-add these
-               if (looploc) _session->locations()->add (looploc);
-               if (punchloc) _session->locations()->add (punchloc);
-               if (sessionloc) _session->locations()->add (sessionloc);
 
                XMLNode &after = _session->locations()->get_state();
                _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-               _session->commit_reversible_command ();
+               
+               commit_reversible_command ();
        }
 }
 
 void
 Editor::clear_locations ()
 {
-       _session->begin_reversible_command (_("clear locations"));
+       begin_reversible_command (_("clear locations"));
+       
        XMLNode &before = _session->locations()->get_state();
        _session->locations()->clear ();
        XMLNode &after = _session->locations()->get_state();
        _session->add_command(new MementoCommand<Locations>(*(_session->locations()), &before, &after));
-       _session->commit_reversible_command ();
-       _session->locations()->clear ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -1894,93 +2240,6 @@ Editor::unhide_ranges ()
 
 /* INSERT/REPLACE */
 
-void
-Editor::insert_region_list_drag (boost::shared_ptr<Region> region, int x, int y)
-{
-       double wx, wy;
-       double cx, cy;
-       framepos_t where;
-       RouteTimeAxisView *rtv = 0;
-       boost::shared_ptr<Playlist> playlist;
-
-       track_canvas->window_to_world (x, y, wx, wy);
-
-       GdkEvent event;
-       event.type = GDK_BUTTON_RELEASE;
-       event.button.x = wx;
-       event.button.y = wy;
-
-       where = event_frame (&event, &cx, &cy);
-
-       if (where < leftmost_frame || where > leftmost_frame + current_page_frames()) {
-               /* clearly outside canvas area */
-               return;
-       }
-
-       std::pair<TimeAxisView*, int> tv = trackview_by_y_position (cy);
-       if (tv.first == 0) {
-               return;
-       }
-
-       if ((rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
-               return;
-       }
-
-       if ((playlist = rtv->playlist()) == 0) {
-               return;
-       }
-
-       snap_to (where);
-
-       begin_reversible_command (_("insert dragged region"));
-       playlist->clear_changes ();
-       playlist->add_region (RegionFactory::create (region, true), where, 1.0);
-       _session->add_command(new StatefulDiffCommand (playlist));
-       commit_reversible_command ();
-}
-
-void
-Editor::insert_route_list_drag (boost::shared_ptr<Route> route, int x, int y)
-{
-       double wx, wy;
-       double cx, cy;
-       RouteTimeAxisView *dest_rtv = 0;
-       RouteTimeAxisView *source_rtv = 0;
-
-       track_canvas->window_to_world (x, y, wx, wy);
-       wx += horizontal_position ();
-       wy += vertical_adjustment.get_value();
-
-       GdkEvent event;
-       event.type = GDK_BUTTON_RELEASE;
-       event.button.x = wx;
-       event.button.y = wy;
-
-       event_frame (&event, &cx, &cy);
-
-       std::pair<TimeAxisView*, int> const tv = trackview_by_y_position (cy);
-       if (tv.first == 0) {
-               return;
-       }
-
-       if ((dest_rtv = dynamic_cast<RouteTimeAxisView*> (tv.first)) == 0) {
-               return;
-       }
-
-       /* use this drag source to add underlay to a track. But we really don't care
-          about the Route, only the view of the route, so find it first */
-       for(TrackViewList::iterator it = track_views.begin(); it != track_views.end(); ++it) {
-               if((source_rtv = dynamic_cast<RouteTimeAxisView*>(*it)) == 0) {
-                       continue;
-               }
-
-               if(source_rtv->route() == route && source_rtv != dest_rtv) {
-                       dest_rtv->add_underlay(source_rtv->view());
-                       break;
-               }
-       }
-}
-
 void
 Editor::insert_region_list_selection (float times)
 {
@@ -2013,6 +2272,9 @@ Editor::insert_region_list_selection (float times)
        begin_reversible_command (_("insert region"));
        playlist->clear_changes ();
        playlist->add_region ((RegionFactory::create (region, true)), get_preferred_edit_position(), times);
+       if (Config->get_edit_mode() == Ripple)
+               playlist->ripple (get_preferred_edit_position(), region->length() * times, boost::shared_ptr<Region>());
+
        _session->add_command(new StatefulDiffCommand (playlist));
        commit_reversible_command ();
 }
@@ -2042,8 +2304,8 @@ Editor::transition_to_rolling (bool fwd)
        }
 
        if (_session->config.get_external_sync()) {
-               switch (_session->config.get_sync_source()) {
-               case JACK:
+               switch (Config->get_sync_source()) {
+               case Engine:
                        break;
                default:
                        /* transport controlled by the master */
@@ -2098,11 +2360,65 @@ Editor::play_from_edit_point_and_return ()
 void
 Editor::play_selection ()
 {
-       if (selection->time.empty()) {
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
                return;
-       }
 
-       _session->request_play_range (&selection->time, true);
+       AudioRange ar (start, end, 0);
+       list<AudioRange> lar;
+       lar.push_back (ar);
+
+       _session->request_play_range (&lar, true);
+}
+
+framepos_t
+Editor::get_preroll ()
+{
+       return 1.0 /*Config->get_edit_preroll_seconds()*/ * _session->frame_rate();
+}
+
+
+void
+Editor::maybe_locate_with_edit_preroll ( framepos_t location )
+{
+       if ( _session->transport_rolling() || !ARDOUR_UI::config()->get_follow_edits() || _ignore_follow_edits )
+               return;
+
+       location -= get_preroll();
+       
+       //don't try to locate before the beginning of time
+       if ( location < 0 ) 
+               location = 0;
+               
+       //if follow_playhead is on, keep the playhead on the screen
+       if ( _follow_playhead )
+               if ( location < leftmost_frame ) 
+                       location = leftmost_frame;
+
+       _session->request_locate( location );
+}
+
+void
+Editor::play_with_preroll ()
+{
+       {
+               framepos_t preroll = get_preroll();
+               
+               framepos_t start, end;
+               if (!get_selection_extents ( start, end))
+                       return;
+
+               if (start > preroll)
+                       start = start - preroll;
+               
+               end = end + preroll;  //"post-roll"
+               
+               AudioRange ar (start, end, 0);
+               list<AudioRange> lar;
+               lar.push_back (ar);
+
+               _session->request_play_range (&lar, true);
+       }
 }
 
 void
@@ -2128,33 +2444,106 @@ Editor::loop_location (Location& location)
                tll->set (location.start(), location.end());
 
                // enable looping, reposition and start rolling
-               _session->request_play_loop (true);
                _session->request_locate (tll->start(), true);
+               _session->request_play_loop (true);
+       }
+}
+
+void
+Editor::do_layer_operation (LayerOperation op)
+{
+       if (selection->regions.empty ()) {
+               return;
+       }
+
+       bool const multiple = selection->regions.size() > 1;
+       switch (op) {
+       case Raise:
+               if (multiple) {
+                       begin_reversible_command (_("raise regions"));
+               } else {
+                       begin_reversible_command (_("raise region"));
+               }
+               break;
+
+       case RaiseToTop:
+               if (multiple) {
+                       begin_reversible_command (_("raise regions to top"));
+               } else {
+                       begin_reversible_command (_("raise region to top"));
+               }
+               break;
+               
+       case Lower:
+               if (multiple) {
+                       begin_reversible_command (_("lower regions"));
+               } else {
+                       begin_reversible_command (_("lower region"));
+               }
+               break;
+               
+       case LowerToBottom:
+               if (multiple) {
+                       begin_reversible_command (_("lower regions to bottom"));
+               } else {
+                       begin_reversible_command (_("lower region"));
+               }
+               break;
+       }
+
+       set<boost::shared_ptr<Playlist> > playlists = selection->regions.playlists ();
+       for (set<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
+               (*i)->clear_owned_changes ();
+       }
+       
+       for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
+               boost::shared_ptr<Region> r = (*i)->region ();
+               switch (op) {
+               case Raise:
+                       r->raise ();
+                       break;
+               case RaiseToTop:
+                       r->raise_to_top ();
+                       break;
+               case Lower:
+                       r->lower ();
+                       break;
+               case LowerToBottom:
+                       r->lower_to_bottom ();
+               }
+       }
+
+       for (set<boost::shared_ptr<Playlist> >::iterator i = playlists.begin(); i != playlists.end(); ++i) {
+               vector<Command*> cmds;
+               (*i)->rdiff (cmds);
+               _session->add_commands (cmds);
        }
+       
+       commit_reversible_command ();
 }
 
 void
 Editor::raise_region ()
 {
-       selection->foreach_region (&Region::raise);
+       do_layer_operation (Raise);
 }
 
 void
 Editor::raise_region_to_top ()
 {
-       selection->foreach_region (&Region::raise_to_top);
+       do_layer_operation (RaiseToTop);
 }
 
 void
 Editor::lower_region ()
 {
-       selection->foreach_region (&Region::lower);
+       do_layer_operation (Lower);
 }
 
 void
 Editor::lower_region_to_bottom ()
 {
-       selection->foreach_region (&Region::lower_to_bottom);
+       do_layer_operation (LowerToBottom);
 }
 
 /** Show the region editor for the selected regions */
@@ -2196,7 +2585,6 @@ Editor::rename_region ()
        d.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
 
        d.set_size_request (300, -1);
-       d.set_position (Gtk::WIN_POS_MOUSE);
 
        entry.set_text (rs.front()->region()->name());
        entry.select_region (0, -1);
@@ -2336,8 +2724,14 @@ Editor::create_region_from_selection (vector<boost::shared_ptr<Region> >& new_re
                return;
        }
 
-       framepos_t start = selection->time[clicked_selection].start;
-       framepos_t end = selection->time[clicked_selection].end;
+       framepos_t start, end;
+       if (clicked_selection) {
+               start = selection->time[clicked_selection].start;
+               end = selection->time[clicked_selection].end;
+       } else {
+               start = selection->time.start();
+               end = selection->time.end_frame();
+       }
 
        TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
        sort_track_selection (ts);
@@ -2396,7 +2790,8 @@ static void
 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
 {
        switch (rv->region()->coverage (ar->start, ar->end - 1)) {
-       case OverlapNone:
+       // n.b. -1 because AudioRange::end is one past the end, but coverage expects inclusive ranges
+       case Evoral::OverlapNone:
                break;
        default:
                rs->push_back (rv);
@@ -2515,8 +2910,7 @@ Editor::separate_regions_between (const TimeSelection& ts)
        }
 
        if (in_command) {
-               selection->set (new_selection);
-               set_mouse_mode (MouseObject);
+//             selection->set (new_selection);
 
                commit_reversible_command ();
        }
@@ -2539,7 +2933,7 @@ Editor::separate_region_from_selection ()
           returns a single range.
        */
 
-       if (mouse_mode == MouseRange && !selection->time.empty()) {
+       if (!selection->time.empty()) {
 
                separate_regions_between (selection->time);
 
@@ -3087,15 +3481,10 @@ Editor::trim_region (bool front)
        framepos_t where = get_preferred_edit_position();
        RegionSelection rs = get_regions_from_selection_and_edit_point ();
 
-       cerr << "trim regions\n";
-
        if (rs.empty()) {
-               cerr << " no regions\n";
                return;
        }
 
-       cerr << "where = " << where << endl;
-
        begin_reversible_command (front ? _("trim front") : _("trim back"));
 
        for (list<RegionView*>::const_iterator i = rs.by_layer().begin(); i != rs.by_layer().end(); ++i) {
@@ -3105,8 +3494,10 @@ Editor::trim_region (bool front)
 
                        if (front) {
                                (*i)->region()->trim_front (where);
+                               maybe_locate_with_edit_preroll ( where );
                        } else {
                                (*i)->region()->trim_end (where);
+                               maybe_locate_with_edit_preroll ( where );
                        }
 
                        _session->add_command (new StatefulDiffCommand ((*i)->region()));
@@ -3149,7 +3540,7 @@ Editor::trim_region_to_location (const Location& loc, const char* str)
 
                /* require region to span proposed trim */
                switch (rv->region()->coverage (loc.start(), loc.end())) {
-               case OverlapInternal:
+               case Evoral::OverlapInternal:
                        break;
                default:
                        continue;
@@ -3269,14 +3660,15 @@ Editor::unfreeze_route ()
 void*
 Editor::_freeze_thread (void* arg)
 {
-       SessionEvent::create_per_thread_pool ("freeze events", 64);
-
        return static_cast<Editor*>(arg)->freeze_thread ();
 }
 
 void*
 Editor::freeze_thread ()
 {
+       /* create event pool because we may need to talk to the session */
+       SessionEvent::create_per_thread_pool ("freeze events", 64);
+       /* create per-thread buffers for process() tree to use */
        clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
        current_interthread_info->done = true;
        return 0;
@@ -3292,21 +3684,41 @@ Editor::freeze_route ()
        /* stop transport before we start. this is important */
 
        _session->request_transport_speed (0.0);
+       
+       /* wait for just a little while, because the above call is asynchronous */
+
+       Glib::usleep (250000);
 
        if (clicked_routeview == 0 || !clicked_routeview->is_audio_track()) {
                return;
        }
 
-       if (!clicked_routeview->track()->bounceable()) {
-               RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_routeview);
-               if (rtv && !rtv->track()->bounceable()) {
-                       MessageDialog d (
-                               _("This route cannot be frozen because it has more outputs than inputs.  "
-                                 "You can fix this by increasing the number of inputs.")
-                               );
-                       d.set_title (_("Cannot freeze"));
-                       d.run ();
+       if (!clicked_routeview->track()->bounceable (clicked_routeview->track()->main_outs(), true)) {
+               MessageDialog d (
+                       _("This track/bus cannot be frozen because the signal adds or loses channels before reaching the outputs.\n"
+                         "This is typically caused by plugins that generate stereo output from mono input or vice versa.")
+                       );
+               d.set_title (_("Cannot freeze"));
+               d.run ();
+               return;
+       }
+
+       if (clicked_routeview->track()->has_external_redirects()) {
+               MessageDialog d (string_compose (_("<b>%1</b>\n\nThis track has at least one send/insert/return as part of its signal flow.\n\n"
+                                                  "Freezing will only process the signal as far as the first send/insert/return."),
+                                                clicked_routeview->track()->name()), true, MESSAGE_INFO, BUTTONS_NONE, true);
+
+               d.add_button (_("Freeze anyway"), Gtk::RESPONSE_OK);
+               d.add_button (_("Don't freeze"), Gtk::RESPONSE_CANCEL);
+               d.set_title (_("Freeze Limits"));
+
+               int response = d.run ();
+
+               switch (response) {
+               case Gtk::RESPONSE_CANCEL:
                        return;
+               default:
+                       break;
                }
        }
 
@@ -3317,14 +3729,13 @@ Editor::freeze_route ()
 
        pthread_create_and_store (X_("freezer"), &itt.thread, _freeze_thread, this);
 
-       set_canvas_cursor (_cursors->wait);
+       CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
 
        while (!itt.done && !itt.cancel) {
                gtk_main_iteration ();
        }
 
        current_interthread_info = 0;
-       set_canvas_cursor (current_canvas_cursor);
 }
 
 void
@@ -3337,16 +3748,21 @@ Editor::bounce_range_selection (bool replace, bool enable_processing)
        TrackSelection views = selection->tracks;
 
        for (TrackViewList::iterator i = views.begin(); i != views.end(); ++i) {
-               RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
-               if (rtv && rtv->track() && replace && enable_processing && !rtv->track()->bounceable()) {
-                       MessageDialog d (
-                               _("You can't perform this operation because the processing of the signal "
-                                 "will cause one or more of the tracks will end up with a region with more channels than this track has inputs.\n\n"
-                                 "You can do this without processing, which is a different operation.")
-                               );
-                       d.set_title (_("Cannot bounce"));
-                       d.run ();
-                       return;
+
+               if (enable_processing) {
+
+                       RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*i);
+
+                       if (rtv && rtv->track() && replace && enable_processing && !rtv->track()->bounceable (rtv->track()->main_outs(), false)) {
+                               MessageDialog d (
+                                       _("You can't perform this operation because the processing of the signal "
+                                         "will cause one or more of the tracks to end up with a region with more channels than this track has inputs.\n\n"
+                                         "You can do this without processing, which is a different operation.")
+                                       );
+                               d.set_title (_("Cannot bounce"));
+                               d.run ();
+                               return;
+                       }
                }
        }
 
@@ -3375,7 +3791,13 @@ Editor::bounce_range_selection (bool replace, bool enable_processing)
                playlist->clear_changes ();
                playlist->clear_owned_changes ();
 
-               boost::shared_ptr<Region> r = rtv->track()->bounce_range (start, start+cnt, itt, enable_processing);
+               boost::shared_ptr<Region> r;
+
+               if (enable_processing) {
+                       r = rtv->track()->bounce_range (start, start+cnt, itt, rtv->track()->main_outs(), false);
+               } else {
+                       r = rtv->track()->bounce_range (start, start+cnt, itt, boost::shared_ptr<Processor>(), false);
+               }
 
                if (!r) {
                        continue;
@@ -3402,7 +3824,14 @@ Editor::bounce_range_selection (bool replace, bool enable_processing)
 void
 Editor::delete_ ()
 {
-       cut_copy (Delete);
+       //special case: if the user is pointing in the editor/mixer strip, they may be trying to delete a plugin.
+       //we need this because the editor-mixer strip is in the editor window, so it doesn't get the bindings from the mix window
+       bool deleted = false;
+       if ( current_mixer_strip && current_mixer_strip == MixerStrip::entered_mixer_strip() )
+               deleted = current_mixer_strip->delete_processors ();
+
+       if (!deleted)
+               cut_copy (Delete);
 }
 
 /** Cut selected regions, automation points or a time range */
@@ -3424,30 +3853,15 @@ Editor::copy ()
 bool
 Editor::can_cut_copy () const
 {
-       switch (current_mouse_mode()) {
-
-       case MouseObject:
-               if (!selection->regions.empty() || !selection->points.empty()) {
-                       return true;
-               }
-               break;
-
-       case MouseRange:
-               if (!selection->time.empty()) {
-                       return true;
-               }
-               break;
-
-       default:
-               break;
-       }
+       if (!selection->time.empty() || !selection->regions.empty() || !selection->points.empty())
+               return true;
 
        return false;
 }
 
 
 /** Cut, copy or clear selected regions, automation points or a time range.
- * @param op Operation (Cut, Copy or Clear)
+ * @param op Operation (Delete, Cut, Copy or Clear)
  */
 void
 Editor::cut_copy (CutCopyOp op)
@@ -3483,7 +3897,8 @@ Editor::cut_copy (CutCopyOp op)
                }
        }
 
-       cut_buffer->clear ();
+       if ( op != Delete )  //"Delete" doesn't change copy/paste buf
+               cut_buffer->clear ();
 
        if (entered_marker) {
 
@@ -3500,96 +3915,177 @@ Editor::cut_copy (CutCopyOp op)
                return;
        }
 
-       if (internal_editing()) {
-
-               switch (current_mouse_mode()) {
-               case MouseObject:
-               case MouseRange:
-                       cut_copy_midi (op);
-                       break;
-               default:
-                       break;
-               }
-
-       } else {
-
-               RegionSelection rs;
-
-               /* we only want to cut regions if some are selected */
-
-               switch (current_mouse_mode()) {
-               case MouseObject:
-                       rs = get_regions_from_selection ();
-                       if (!rs.empty() || !selection->points.empty()) {
-
-                               begin_reversible_command (opname + _(" objects"));
-
-                               if (!rs.empty()) {
-                                       cut_copy_regions (op, rs);
+       switch (mouse_mode) {
+       case MouseDraw:
+       case MouseContent:
+               begin_reversible_command (opname + ' ' + X_("MIDI"));
+               cut_copy_midi (op);
+               commit_reversible_command ();
+               return;
+       default:
+               break;
+       }
 
-                                       if (op == Cut || op == Delete) {
-                                               selection->clear_regions ();
-                                       }
-                               }
+       bool did_edit = false;
 
-                               if (!selection->points.empty()) {
-                                       cut_copy_points (op);
+       if (!selection->regions.empty() || !selection->points.empty()) {
+               begin_reversible_command (opname + ' ' + _("objects"));
+               did_edit = true;
 
-                                       if (op == Cut || op == Delete) {
-                                               selection->clear_points ();
-                                       }
-                               }
-                               commit_reversible_command ();
-                               break; // terminate case statement here
+               if (!selection->regions.empty()) {
+                       cut_copy_regions (op, selection->regions);
+                       
+                       if (op == Cut || op == Delete) {
+                               selection->clear_regions ();
                        }
-                       if (!selection->time.empty()) {
-                               /* don't cause suprises */
-                               break;
+               }
+               
+               if (!selection->points.empty()) {
+                       cut_copy_points (op);
+                       
+                       if (op == Cut || op == Delete) {
+                               selection->clear_points ();
                        }
-                       // fall thru if there was nothing selected
-
-               case MouseRange:
-                       if (selection->time.empty()) {
-                               framepos_t start, end;
-                               if (!get_edit_op_range (start, end)) {
-                                       return;
-                               }
-                               selection->set (start, end);
-                       }
-
-                       begin_reversible_command (opname + _(" range"));
-                       cut_copy_ranges (op);
-                       commit_reversible_command ();
-
-                       if (op == Cut || op == Delete) {
-                               selection->clear_time ();
-                       }
-
-                       break;
+               }
+       } else if (selection->time.empty()) {
+               framepos_t start, end;
+               /* no time selection, see if we can get an edit range
+                  and use that.
+               */
+               if (get_edit_op_range (start, end)) {
+                       selection->set (start, end);
+               }
+       } else if (!selection->time.empty()) {
+               begin_reversible_command (opname + ' ' + _("range"));
 
-               default:
-                       break;
+               did_edit = true;
+               cut_copy_ranges (op);
+               
+               if (op == Cut || op == Delete) {
+                       selection->clear_time ();
                }
        }
-
+       
+       if (did_edit) {
+               /* reset repeated paste state */
+               paste_count    = 0;
+               last_paste_pos = 0;
+               commit_reversible_command ();   
+       }
+       
        if (op == Delete || op == Cut || op == Clear) {
                _drags->abort ();
        }
 }
 
+struct AutomationRecord {
+       AutomationRecord () : state (0) , line(NULL) {}
+       AutomationRecord (XMLNode* s, const AutomationLine* l) : state (s) , line (l) {}
+       
+       XMLNode* state; ///< state before any operation
+       const AutomationLine* line; ///< line this came from
+       boost::shared_ptr<Evoral::ControlList> copy; ///< copied events for the cut buffer
+};
+
 /** Cut, copy or clear selected automation points.
- * @param op Operation (Cut, Copy or Clear)
+ *  @param op Operation (Cut, Copy or Clear)
  */
 void
-Editor::cut_copy_points (CutCopyOp op)
+Editor::cut_copy_points (Editing::CutCopyOp op, Evoral::Beats earliest, bool midi)
 {
+       if (selection->points.empty ()) {
+               return;
+       }
+
+       /* XXX: not ideal, as there may be more than one track involved in the point selection */
+       _last_cut_copy_source_track = &selection->points.front()->line().trackview;
+
+       /* Keep a record of the AutomationLists that we end up using in this operation */
+       typedef std::map<boost::shared_ptr<AutomationList>, AutomationRecord> Lists;
+       Lists lists;
+
+       /* Go through all selected points, making an AutomationRecord for each distinct AutomationList */
        for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
+               const AutomationLine&                   line = (*i)->line();
+               const boost::shared_ptr<AutomationList> al   = line.the_list();
+               if (lists.find (al) == lists.end ()) {
+                       /* We haven't seen this list yet, so make a record for it.  This includes
+                          taking a copy of its current state, in case this is needed for undo later.
+                       */
+                       lists[al] = AutomationRecord (&al->get_state (), &line);
+               }
+       }
+
+       if (op == Cut || op == Copy) {
+               /* This operation will involve putting things in the cut buffer, so create an empty
+                  ControlList for each of our source lists to put the cut buffer data in.
+               */
+               for (Lists::iterator i = lists.begin(); i != lists.end(); ++i) {
+                       i->second.copy = i->first->create (i->first->parameter (), i->first->descriptor());
+               }
+
+               /* Add all selected points to the relevant copy ControlLists */
+               framepos_t start = std::numeric_limits<framepos_t>::max();
+               for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
+                       boost::shared_ptr<AutomationList> al = (*i)->line().the_list();
+                       AutomationList::const_iterator    j  = (*i)->model();
+
+                       lists[al].copy->fast_simple_add ((*j)->when, (*j)->value);
+                       if (midi) {
+                               /* Update earliest MIDI start time in beats */
+                               earliest = std::min(earliest, Evoral::Beats((*j)->when));
+                       } else {
+                               /* Update earliest session start time in frames */
+                               start = std::min(start, (*i)->line().session_position(j));
+                       }
+               }
+
+               /* Snap start time backwards, so copy/paste is snap aligned. */
+               if (midi) {
+                       if (earliest == Evoral::Beats::max()) {
+                               earliest = Evoral::Beats();  // Weird... don't offset
+                       }
+                       earliest.round_down_to_beat();
+               } else {
+                       if (start == std::numeric_limits<double>::max()) {
+                               start = 0;  // Weird... don't offset
+                       }
+                       snap_to(start, RoundDownMaybe);
+               }
+
+               const double line_offset = midi ? earliest.to_double() : start;
+               for (Lists::iterator i = lists.begin(); i != lists.end(); ++i) {
+                       /* Correct this copy list so that it is relative to the earliest
+                          start time, so relative ordering between points is preserved
+                          when copying from several lists and the paste starts at the
+                          earliest copied piece of data. */
+                       for (AutomationList::iterator j = i->second.copy->begin(); j != i->second.copy->end(); ++j) {
+                               (*j)->when -= line_offset;
+                       }
+
+                       /* And add it to the cut buffer */
+                       cut_buffer->add (i->second.copy);
+               }
+       }
+               
+       if (op == Delete || op == Cut) {
+               /* This operation needs to remove things from the main AutomationList, so do that now */
+               
+               for (Lists::iterator i = lists.begin(); i != lists.end(); ++i) {
+                       i->first->freeze ();
+               }
 
-               AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
-               _last_cut_copy_source_track = atv;
+               /* Remove each selected point from its AutomationList */
+               for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
+                       boost::shared_ptr<AutomationList> al = (*i)->line().the_list();
+                       al->erase ((*i)->model ());
+               }
 
-               if (atv) {
-                       atv->cut_copy_clear_objects (selection->points, op);
+               /* Thaw the lists and add undo records for them */
+               for (Lists::iterator i = lists.begin(); i != lists.end(); ++i) {
+                       boost::shared_ptr<AutomationList> al = i->first;
+                       al->thaw ();
+                       _session->add_command (new MementoCommand<AutomationList> (*al.get(), i->second.state, &(al->get_state ())));
                }
        }
 }
@@ -3600,13 +4096,27 @@ Editor::cut_copy_points (CutCopyOp op)
 void
 Editor::cut_copy_midi (CutCopyOp op)
 {
+       Evoral::Beats earliest = Evoral::Beats::max();
        for (MidiRegionSelection::iterator i = selection->midi_regions.begin(); i != selection->midi_regions.end(); ++i) {
-               MidiRegionView* mrv = *i;
-               mrv->cut_copy_clear (op);
-       }
-}
+               MidiRegionView* mrv = dynamic_cast<MidiRegionView*>(*i);
+               if (mrv) {
+                       if (!mrv->selection().empty()) {
+                               earliest = std::min(earliest, (*mrv->selection().begin())->note()->time());
+                       }
+                       mrv->cut_copy_clear (op);
 
+                       /* XXX: not ideal, as there may be more than one track involved in the selection */
+                       _last_cut_copy_source_track = &mrv->get_time_axis_view();
+               }
+       }
 
+       if (!selection->points.empty()) {
+               cut_copy_points (op, earliest, true);
+               if (op == Cut || op == Delete) {
+                       selection->clear_points ();
+               }
+       }
+}
 
 struct lt_playlist {
     bool operator () (const PlaylistState& a, const PlaylistState& b) {
@@ -3629,11 +4139,23 @@ Editor::remove_clicked_region ()
                return;
        }
 
+       begin_reversible_command (_("remove region"));
+
        boost::shared_ptr<Playlist> playlist = clicked_routeview->playlist();
 
-       begin_reversible_command (_("remove region"));
        playlist->clear_changes ();
+       playlist->clear_owned_changes ();
        playlist->remove_region (clicked_regionview->region());
+       if (Config->get_edit_mode() == Ripple)
+               playlist->ripple (clicked_regionview->region()->position(), -clicked_regionview->region()->length(), boost::shared_ptr<Region>());
+
+       /* We might have removed regions, which alters other regions' layering_index,
+          so we need to do a recursive diff here.
+       */
+       vector<Command*> cmds;
+       playlist->rdiff (cmds);
+       _session->add_commands (cmds);
+       
        _session->add_command(new StatefulDiffCommand (playlist));
        commit_reversible_command ();
 }
@@ -3685,14 +4207,26 @@ Editor::remove_selected_regions ()
                playlists.push_back (playlist);
 
                playlist->clear_changes ();
+               playlist->clear_owned_changes ();
                playlist->freeze ();
                playlist->remove_region (*rl);
+               if (Config->get_edit_mode() == Ripple)
+                       playlist->ripple ((*rl)->position(), -(*rl)->length(), boost::shared_ptr<Region>());
+
        }
 
        vector<boost::shared_ptr<Playlist> >::iterator pl;
 
        for (pl = playlists.begin(); pl != playlists.end(); ++pl) {
                (*pl)->thaw ();
+
+               /* We might have removed regions, which alters other regions' layering_index,
+                  so we need to do a recursive diff here.
+               */
+               vector<Command*> cmds;
+               (*pl)->rdiff (cmds);
+               _session->add_commands (cmds);
+               
                _session->add_command(new StatefulDiffCommand (*pl));
        }
 
@@ -3739,6 +4273,7 @@ Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
 
                                if (fl == freezelist.end()) {
                                        pl->clear_changes();
+                                       pl->clear_owned_changes ();
                                        pl->freeze ();
                                        freezelist.insert (pl);
                                }
@@ -3807,12 +4342,16 @@ Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
                switch (op) {
                case Delete:
                        pl->remove_region (r);
+                       if (Config->get_edit_mode() == Ripple)
+                               pl->ripple (r->position(), -r->length(), boost::shared_ptr<Region>());
                        break;
                        
                case Cut:
                        _xx = RegionFactory::create (r);
                        npl->add_region (_xx, r->position() - first_position);
                        pl->remove_region (r);
+                       if (Config->get_edit_mode() == Ripple)
+                               pl->ripple (r->position(), -r->length(), boost::shared_ptr<Region>());
                        break;
 
                case Copy:
@@ -3821,7 +4360,9 @@ Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
                        break;
 
                case Clear:
-                       pl->remove_region (r);  
+                       pl->remove_region (r);
+                       if (Config->get_edit_mode() == Ripple)
+                               pl->ripple (r->position(), -r->length(), boost::shared_ptr<Region>());
                        break;
                }
 
@@ -3854,6 +4395,14 @@ Editor::cut_copy_regions (CutCopyOp op, RegionSelection& rs)
 
        for (FreezeList::iterator pl = freezelist.begin(); pl != freezelist.end(); ++pl) {
                (*pl)->thaw ();
+
+               /* We might have removed regions, which alters other regions' layering_index,
+                  so we need to do a recursive diff here.
+               */
+               vector<Command*> cmds;
+               (*pl)->rdiff (cmds);
+               _session->add_commands (cmds);
+               
                _session->add_command (new StatefulDiffCommand (*pl));
        }
 }
@@ -3884,10 +4433,11 @@ Editor::cut_copy_ranges (CutCopyOp op)
 }
 
 void
-Editor::paste (float times)
+Editor::paste (float times, bool from_context)
 {
         DEBUG_TRACE (DEBUG::CutNPaste, "paste to preferred edit pos\n");
-       paste_internal (get_preferred_edit_position(), times);
+
+       paste_internal (get_preferred_edit_position (false, from_context), times);
 }
 
 void
@@ -3909,14 +4459,8 @@ Editor::paste_internal (framepos_t position, float times)
 {
         DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("apparent paste position is %1\n", position));
 
-       if (internal_editing()) {
-               if (cut_buffer->midi_notes.empty()) {
-                       return;
-               }
-       } else {
-               if (cut_buffer->empty()) {
-                       return;
-               }
+       if (cut_buffer->empty(internal_editing())) {
+               return;
        }
 
        if (position == max_framepos) {
@@ -3924,57 +4468,99 @@ Editor::paste_internal (framepos_t position, float times)
                 DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("preferred edit position is %1\n", position));
        }
 
-       TrackViewList ts;
-       TrackViewList::iterator i;
-       size_t nth;
+       if (position == last_paste_pos) {
+               /* repeated paste in the same position */
+               ++paste_count;
+       } else {
+               /* paste in new location, reset repeated paste state */
+               paste_count = 0;
+               last_paste_pos = position;
+       }
 
        /* get everything in the correct order */
 
+       TrackViewList ts;
        if (!selection->tracks.empty()) {
-               /* there are some selected tracks, so paste to them */
+               /* If there is a track selection, paste into exactly those tracks and
+                  only those tracks.  This allows the user to be explicit and override
+                  the below "do the reasonable thing" logic. */
                ts = selection->tracks.filter_to_unique_playlists ();
                sort_track_selection (ts);
-       } else if (_last_cut_copy_source_track) {
-               /* otherwise paste to the track that the cut/copy came from;
-                  see discussion in mantis #3333.
-               */
-               ts.push_back (_last_cut_copy_source_track);
-       }
-
-       if (internal_editing ()) {
+       } else {
+               /* Figure out which track to base the paste at. */
+               TimeAxisView* base_track = NULL;
+               if (_edit_point == Editing::EditAtMouse && entered_track) {
+                       /* With the mouse edit point, paste onto the track under the mouse. */
+                       base_track = entered_track;
+               } else if (_edit_point == Editing::EditAtMouse && entered_regionview) {
+                       /* With the mouse edit point, paste onto the track of the region under the mouse. */
+                       base_track = &entered_regionview->get_time_axis_view();
+               } else if (_last_cut_copy_source_track) {
+                       /* Paste to the track that the cut/copy came from (see mantis #333). */
+                       base_track = _last_cut_copy_source_track;
+               } else {
+                       /* This is "impossible" since we've copied... well, do nothing. */
+                       return;
+               }
 
-               /* undo/redo is handled by individual tracks/regions */
+               /* Walk up to parent if necessary, so base track is a route. */
+               while (base_track->get_parent()) {
+                       base_track = base_track->get_parent();
+               }
 
-               for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
+               /* Add base track and all tracks below it.  The paste logic will select
+                  the appropriate object types from the cut buffer in relative order. */
+               for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
+                       if ((*i)->order() >= base_track->order()) {
+                               ts.push_back(*i);
+                       }
+               }
 
-                       RegionSelection rs;
-                       RegionSelection::iterator r;
-                       MidiNoteSelection::iterator cb;
+               /* Sort tracks so the nth track of type T will pick the nth object of type T. */
+               sort_track_selection (ts);
 
-                       get_regions_at (rs, position, ts);
+               /* Add automation children of each track in order, for pasting several lines. */
+               for (TrackViewList::iterator i = ts.begin(); i != ts.end();) {
+                       /* Add any automation children for pasting several lines */
+                       RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*i++);
+                       if (!rtv) {
+                               continue;
+                       }
 
-                       for (cb = cut_buffer->midi_notes.begin(), r = rs.begin();
-                            cb != cut_buffer->midi_notes.end() && r != rs.end(); ++r) {
-                               MidiRegionView* mrv = dynamic_cast<MidiRegionView*> (*r);
-                               if (mrv) {
-                                       mrv->paste (position, times, **cb);
-                                       ++cb;
-                               }
+                       typedef RouteTimeAxisView::AutomationTracks ATracks;
+                       const ATracks& atracks = rtv->automation_tracks();
+                       for (ATracks::const_iterator a = atracks.begin(); a != atracks.end(); ++a) {
+                               i = ts.insert(i, a->second.get());
+                               ++i;
                        }
                }
 
-       } else {
+               /* We now have a list of trackviews starting at base_track, including
+                  automation children, in the order shown in the editor, e.g. R1,
+                  R1.A1, R1.A2, R2, R2.A1, ... */
+       }
 
-               /* we do redo (do you do voodoo?) */
+       begin_reversible_command (Operations::paste);
 
-               begin_reversible_command (Operations::paste);
+       if (ts.size() == 1 && cut_buffer->lines.size() == 1 &&
+           dynamic_cast<AutomationTimeAxisView*>(ts.front())) {
+           /* Only one line copied, and one automation track selected.  Do a
+              "greedy" paste from one automation type to another. */
 
-               for (nth = 0, i = ts.begin(); i != ts.end(); ++i, ++nth) {
-                       (*i)->paste (position, times, *cut_buffer, nth);
-               }
+           PasteContext ctx(paste_count, times, ItemCounts(), true);
+           ts.front()->paste (position, *cut_buffer, ctx);
 
-               commit_reversible_command ();
+       } else {
+
+               /* Paste into tracks */
+
+               PasteContext ctx(paste_count, times, ItemCounts(), false);
+               for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
+                       (*i)->paste (position, *cut_buffer, ctx);
+               }
        }
+
+       commit_reversible_command ();
 }
 
 void
@@ -4010,11 +4596,11 @@ Editor::duplicate_some_regions (RegionSelection& regions, float times)
                foo.insert (foo.end(), latest_regionviews.begin(), latest_regionviews.end());
        }
 
-       commit_reversible_command ();
-
        if (!foo.empty()) {
                selection->set (foo);
        }
+
+       commit_reversible_command ();
 }
 
 void
@@ -4045,7 +4631,13 @@ Editor::duplicate_selection (float times)
                        continue;
                }
                playlist->clear_changes ();
-               playlist->duplicate (*ri, selection->time[clicked_selection].end, times);
+               framepos_t end;
+               if (clicked_selection) {
+                       end = selection->time[clicked_selection].end;
+               } else {
+                       end = selection->time.end_frame();
+               }
+               playlist->duplicate (*ri, end, times);
                _session->add_command (new StatefulDiffCommand (playlist));
 
                ++ri;
@@ -4057,32 +4649,27 @@ Editor::duplicate_selection (float times)
        commit_reversible_command ();
 }
 
+/** Reset all selected points to the relevant default value */
 void
 Editor::reset_point_selection ()
 {
-       /* reset all selected points to the relevant default value */
-
        for (PointSelection::iterator i = selection->points.begin(); i != selection->points.end(); ++i) {
-
-               AutomationTimeAxisView* atv = dynamic_cast<AutomationTimeAxisView*>((*i).track);
-
-               if (atv) {
-                       atv->reset_objects (selection->points);
-               }
+               ARDOUR::AutomationList::iterator j = (*i)->model ();
+               (*j)->value = (*i)->line().the_list()->default_value ();
        }
 }
 
 void
 Editor::center_playhead ()
 {
-       float page = _canvas_width * frames_per_unit;
-       center_screen_internal (playhead_cursor->current_frame, page);
+       float const page = _visible_canvas_width * samples_per_pixel;
+       center_screen_internal (playhead_cursor->current_frame (), page);
 }
 
 void
 Editor::center_edit_point ()
 {
-       float page = _canvas_width * frames_per_unit;
+       float const page = _visible_canvas_width * samples_per_pixel;
        center_screen_internal (get_preferred_edit_position(), page);
 }
 
@@ -4192,7 +4779,7 @@ Editor::normalize_region ()
                return;
        }
 
-       set_canvas_cursor (_cursors->wait);
+       CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
        gdk_flush ();
 
        /* XXX: should really only count audio regions here */
@@ -4211,7 +4798,6 @@ Editor::normalize_region ()
 
                        if (a == -1) {
                                /* the user cancelled the operation */
-                               set_canvas_cursor (current_canvas_cursor);
                                return;
                        }
 
@@ -4242,7 +4828,6 @@ Editor::normalize_region ()
        }
 
        commit_reversible_command ();
-       set_canvas_cursor (current_canvas_cursor);
 }
 
 
@@ -4357,39 +4942,35 @@ Editor::strip_region_silence ()
 Command*
 Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv)
 {
-       Evoral::Sequence<Evoral::MusicalTime>::Notes selected;
+       Evoral::Sequence<Evoral::Beats>::Notes selected;
        mrv.selection_as_notelist (selected, true);
 
-       vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
+       vector<Evoral::Sequence<Evoral::Beats>::Notes> v;
        v.push_back (selected);
 
-       framepos_t pos_frames = mrv.midi_region()->position();
-       double     pos_beats  = _session->tempo_map().framewalk_to_beats(0, pos_frames);
+       framepos_t    pos_frames = mrv.midi_region()->position() - mrv.midi_region()->start();
+       Evoral::Beats pos_beats  = _session->tempo_map().framewalk_to_beats(0, pos_frames);
 
        return op (mrv.midi_region()->model(), pos_beats, v);
 }
 
 void
-Editor::apply_midi_note_edit_op (MidiOperator& op)
+Editor::apply_midi_note_edit_op (MidiOperator& op, const RegionSelection& rs)
 {
-       Command* cmd;
-
-       RegionSelection rs = get_regions_from_selection_and_entered ();
-
        if (rs.empty()) {
                return;
        }
 
        begin_reversible_command (op.name ());
 
-       for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
-               RegionSelection::iterator tmp = r;
+       for (RegionSelection::const_iterator r = rs.begin(); r != rs.end(); ) {
+               RegionSelection::const_iterator tmp = r;
                ++tmp;
 
                MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
 
                if (mrv) {
-                       cmd = apply_midi_note_edit_op_to_region (op, *mrv);
+                       Command* cmd = apply_midi_note_edit_op_to_region (op, *mrv);
                        if (cmd) {
                                (*cmd)();
                                _session->add_command (cmd);
@@ -4413,7 +4994,7 @@ Editor::fork_region ()
 
        begin_reversible_command (_("Fork Region(s)"));
 
-       set_canvas_cursor (_cursors->wait);
+       CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
        gdk_flush ();
 
        for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ) {
@@ -4423,76 +5004,120 @@ Editor::fork_region ()
                MidiRegionView* const mrv = dynamic_cast<MidiRegionView*>(*r);
 
                if (mrv) {
-                       boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
-                       boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone ();
-
-                       playlist->clear_changes ();
-                       playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
-                       _session->add_command(new StatefulDiffCommand (playlist));
+                       try {
+                               boost::shared_ptr<Playlist> playlist = mrv->region()->playlist();
+                               boost::shared_ptr<MidiSource> new_source = _session->create_midi_source_by_stealing_name (mrv->midi_view()->track());
+                               boost::shared_ptr<MidiRegion> newregion = mrv->midi_region()->clone (new_source);
+                               
+                               playlist->clear_changes ();
+                               playlist->replace_region (mrv->region(), newregion, mrv->region()->position());
+                               _session->add_command(new StatefulDiffCommand (playlist));
+                       } catch (...) {
+                               error << string_compose (_("Could not unlink %1"), mrv->region()->name()) << endmsg;
+                       }
                }
 
                r = tmp;
        }
 
        commit_reversible_command ();
-
-       set_canvas_cursor (current_canvas_cursor);
 }
 
 void
 Editor::quantize_region ()
 {
-       int selected_midi_region_cnt = 0;
+       if (_session) {
+               quantize_regions(get_regions_from_selection_and_entered ());
+       }
+}
 
-       if (!_session) {
+void
+Editor::quantize_regions (const RegionSelection& rs)
+{
+       if (rs.n_midi_regions() == 0) {
                return;
        }
 
-       RegionSelection rs = get_regions_from_selection_and_entered ();
+       QuantizeDialog* qd = new QuantizeDialog (*this);
 
-       if (rs.empty()) {
+       qd->present ();
+       const int r = qd->run ();
+       qd->hide ();
+
+       if (r == Gtk::RESPONSE_OK) {
+               Quantize quant (qd->snap_start(), qd->snap_end(),
+                               qd->start_grid_size(), qd->end_grid_size(),
+                               qd->strength(), qd->swing(), qd->threshold());
+
+               apply_midi_note_edit_op (quant, rs);
+       }
+}
+
+void
+Editor::legatize_region (bool shrink_only)
+{
+       if (_session) {
+               legatize_regions(get_regions_from_selection_and_entered (), shrink_only);
+       }
+}
+
+void
+Editor::legatize_regions (const RegionSelection& rs, bool shrink_only)
+{
+       if (rs.n_midi_regions() == 0) {
                return;
        }
 
-       for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
-               MidiRegionView* const mrv = dynamic_cast<MidiRegionView*> (*r);
-               if (mrv) {
-                       selected_midi_region_cnt++;
-               }
+       Legatize legatize(shrink_only);
+       apply_midi_note_edit_op (legatize, rs);
+}
+
+void
+Editor::transform_region ()
+{
+       if (_session) {
+               transform_regions(get_regions_from_selection_and_entered ());
        }
+}
 
-       if (selected_midi_region_cnt == 0) {
+void
+Editor::transform_regions (const RegionSelection& rs)
+{
+       if (rs.n_midi_regions() == 0) {
                return;
        }
 
-       QuantizeDialog* qd = new QuantizeDialog (*this);
+       TransformDialog* td = new TransformDialog();
 
-       qd->present ();
-       const int r = qd->run ();
-       qd->hide ();
+       td->present();
+       const int r = td->run();
+       td->hide();
 
        if (r == Gtk::RESPONSE_OK) {
-               Quantize quant (*_session, Plain,
-                               qd->snap_start(), qd->snap_end(),
-                               qd->start_grid_size(), qd->end_grid_size(),
-                               qd->strength(), qd->swing(), qd->threshold());
-
-               apply_midi_note_edit_op (quant);
+               Transform transform(td->get());
+               apply_midi_note_edit_op(transform, rs);
        }
 }
 
 void
-Editor::insert_patch_change ()
+Editor::insert_patch_change (bool from_context)
 {
        RegionSelection rs = get_regions_from_selection_and_entered ();
+
        if (rs.empty ()) {
                return;
        }
 
-       framepos_t const p = get_preferred_edit_position (false);
+       const framepos_t p = get_preferred_edit_position (false, from_context);
 
-       Evoral::PatchChange<Evoral::MusicalTime> empty (0, 0, 0, 0);
-       PatchChangeDialog d (0, _session, empty, Gtk::Stock::ADD);
+       /* XXX: bit of a hack; use the MIDNAM from the first selected region;
+          there may be more than one, but the PatchChangeDialog can only offer
+          one set of patch menus.
+       */
+       MidiRegionView* first = dynamic_cast<MidiRegionView*> (rs.front ());
+
+       Evoral::PatchChange<Evoral::Beats> empty (Evoral::Beats(), 0, 0, 0);
+        PatchChangeDialog d (0, _session, empty, first->instrument_info(), Gtk::Stock::ADD);
 
        if (d.run() == RESPONSE_CANCEL) {
                return;
@@ -4519,7 +5144,7 @@ Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress
 
        begin_reversible_command (command);
 
-       set_canvas_cursor (_cursors->wait);
+       CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
        gdk_flush ();
 
        int n = 0;
@@ -4540,6 +5165,7 @@ Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress
                        if (arv->audio_region()->apply (filter, progress) == 0) {
 
                                playlist->clear_changes ();
+                               playlist->clear_owned_changes ();
 
                                if (filter.results.empty ()) {
 
@@ -4562,9 +5188,16 @@ Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress
 
                                }
 
+                               /* We might have removed regions, which alters other regions' layering_index,
+                                  so we need to do a recursive diff here.
+                               */
+                               vector<Command*> cmds;
+                               playlist->rdiff (cmds);
+                               _session->add_commands (cmds);
+                               
                                _session->add_command(new StatefulDiffCommand (playlist));
                        } else {
-                               goto out;
+                               return;
                        }
 
                        if (progress) {
@@ -4577,9 +5210,6 @@ Editor::apply_filter (Filter& filter, string command, ProgressReporter* progress
        }
 
        commit_reversible_command ();
-
-  out:
-       set_canvas_cursor (current_canvas_cursor);
 }
 
 void
@@ -4597,8 +5227,8 @@ Editor::reset_region_gain_envelopes ()
                return;
        }
 
-       _session->begin_reversible_command (_("reset region gain"));
-
+       begin_reversible_command (_("reset region gain"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
                AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
                if (arv) {
@@ -4609,12 +5239,36 @@ Editor::reset_region_gain_envelopes ()
                        _session->add_command (new MementoCommand<AutomationList>(*arv->audio_region()->envelope().get(), &before, &alist->get_state()));
                }
        }
+       
+       commit_reversible_command ();
+}
 
-       _session->commit_reversible_command ();
+void
+Editor::set_region_gain_visibility (RegionView* rv)
+{
+       AudioRegionView* arv = dynamic_cast<AudioRegionView*> (rv);
+       if (arv) {
+               arv->update_envelope_visibility();
+       }
 }
 
 void
-Editor::toggle_gain_envelope_visibility ()
+Editor::set_gain_envelope_visibility ()
+{
+       if (!_session) {
+               return;
+       }
+
+       for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
+               AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
+               if (v) {
+                       v->audio_view()->foreach_regionview (sigc::mem_fun (this, &Editor::set_region_gain_visibility));
+               }
+       }
+}
+
+void
+Editor::toggle_gain_envelope_active ()
 {
        if (_ignore_region_action) {
                return;
@@ -4626,22 +5280,22 @@ Editor::toggle_gain_envelope_visibility ()
                return;
        }
 
-       _session->begin_reversible_command (_("region gain envelope visible"));
-
+       begin_reversible_command (_("region gain envelope active"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
                AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
                if (arv) {
                        arv->region()->clear_changes ();
-                       arv->set_envelope_visible (!arv->envelope_visible());
+                       arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
                        _session->add_command (new StatefulDiffCommand (arv->region()));
                }
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
-Editor::toggle_gain_envelope_active ()
+Editor::toggle_region_lock ()
 {
        if (_ignore_region_action) {
                return;
@@ -4653,22 +5307,19 @@ Editor::toggle_gain_envelope_active ()
                return;
        }
 
-       _session->begin_reversible_command (_("region gain envelope active"));
-
+       begin_reversible_command (_("toggle region lock"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
-               AudioRegionView* const arv = dynamic_cast<AudioRegionView*>(*i);
-               if (arv) {
-                       arv->region()->clear_changes ();
-                       arv->audio_region()->set_envelope_active (!arv->audio_region()->envelope_active());
-                       _session->add_command (new StatefulDiffCommand (arv->region()));
-               }
+               (*i)->region()->clear_changes ();
+               (*i)->region()->set_locked (!(*i)->region()->locked());
+               _session->add_command (new StatefulDiffCommand ((*i)->region()));
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
-Editor::toggle_region_lock ()
+Editor::toggle_region_video_lock ()
 {
        if (_ignore_region_action) {
                return;
@@ -4680,15 +5331,15 @@ Editor::toggle_region_lock ()
                return;
        }
 
-       _session->begin_reversible_command (_("toggle region lock"));
-
+       begin_reversible_command (_("Toggle Video Lock"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
                (*i)->region()->clear_changes ();
-               (*i)->region()->set_locked (!(*i)->region()->locked());
+               (*i)->region()->set_video_locked (!(*i)->region()->video_locked());
                _session->add_command (new StatefulDiffCommand ((*i)->region()));
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -4704,16 +5355,16 @@ Editor::toggle_region_lock_style ()
                return;
        }
 
-       _session->begin_reversible_command (_("region lock style"));
-
+       begin_reversible_command (_("region lock style"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
                (*i)->region()->clear_changes ();
                PositionLockStyle const ns = (*i)->region()->position_lock_style() == AudioTime ? MusicTime : AudioTime;
                (*i)->region()->set_position_lock_style (ns);
                _session->add_command (new StatefulDiffCommand ((*i)->region()));
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -4729,15 +5380,15 @@ Editor::toggle_opaque_region ()
                return;
        }
 
-       _session->begin_reversible_command (_("change region opacity"));
-
+       begin_reversible_command (_("change region opacity"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
                (*i)->region()->clear_changes ();
                (*i)->region()->set_opaque (!(*i)->region()->opaque());
                _session->add_command (new StatefulDiffCommand ((*i)->region()));
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -4805,16 +5456,32 @@ Editor::toggle_mute ()
                        first = false;
                }
 
-               rl->push_back (rtav->route());
+               rl->push_back (rtav->route());
+       }
+
+       _session->set_mute (rl, new_state, Session::rt_cleanup, true);
+}
+
+void
+Editor::toggle_solo_isolate ()
+{
+}
+
+
+void
+Editor::fade_range ()
+{
+       TrackViewList ts = selection->tracks.filter_to_unique_playlists ();
+
+       begin_reversible_command (_("fade range"));
+
+       for (TrackViewList::iterator i = ts.begin(); i != ts.end(); ++i) {
+               (*i)->fade_range (selection->time);
        }
 
-       _session->set_mute (rl, new_state, Session::rt_cleanup, true);
+       commit_reversible_command ();
 }
 
-void
-Editor::toggle_solo_isolate ()
-{
-}
 
 void
 Editor::set_fade_length (bool in)
@@ -5008,6 +5675,10 @@ Editor::set_fade_out_active (bool yn)
 void
 Editor::toggle_region_fades (int dir)
 {
+       if (_ignore_region_action) {
+               return;
+       }
+       
        boost::shared_ptr<AudioRegion> ar;
        bool yn = false;
 
@@ -5068,24 +5739,6 @@ Editor::update_region_fade_visibility ()
        }
 }
 
-/** Update crossfade visibility after its configuration has been changed */
-void
-Editor::update_xfade_visibility ()
-{
-       _xfade_visibility = _session->config.get_xfades_visible ();
-
-       for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
-               AudioTimeAxisView* v = dynamic_cast<AudioTimeAxisView*>(*i);
-               if (v) {
-                       if (_xfade_visibility) {
-                               v->show_all_xfades ();
-                       } else {
-                               v->hide_all_xfades ();
-                       }
-               }
-       }
-}
-
 void
 Editor::set_edit_point ()
 {
@@ -5132,51 +5785,39 @@ Editor::set_playhead_cursor ()
                        _session->request_locate (where, _session->transport_rolling());
                }
        }
+
+       if (ARDOUR_UI::config()->get_follow_edits()) {
+               cancel_time_selection();
+       }
 }
 
 void
 Editor::split_region ()
 {
-       if (((mouse_mode == MouseRange) ||
-            (mouse_mode != MouseObject && _join_object_range_state == JOIN_OBJECT_RANGE_RANGE)) &&
-           !selection->time.empty()) {
+       //if a range is selected, separate it
+       if ( !selection->time.empty()) {
                separate_regions_between (selection->time);
                return;
        }
 
-       RegionSelection rs = get_regions_from_selection_and_edit_point ();
-
-       framepos_t where = get_preferred_edit_position ();
-
-       if (rs.empty()) {
-               return;
-       }
-
-       split_regions_at (where, rs);
-}
+       //if no range was selected, try to find some regions to split
+       if (current_mouse_mode() == MouseObject) {  //don't try this for Internal Edit, Stretch, Draw, etc.
+       
+               RegionSelection rs = get_regions_from_selection_and_edit_point ();
 
-void
-Editor::ensure_entered_track_selected (bool op_really_wants_one_track_if_none_are_selected)
-{
-       if (entered_track && mouse_mode == MouseObject) {
-               if (!selection->tracks.empty()) {
-                       if (!selection->selected (entered_track)) {
-                               selection->add (entered_track);
-                       }
-               } else {
-                       /* there is no selection, but this operation requires/prefers selected objects */
+               framepos_t where = get_preferred_edit_position ();
 
-                       if (op_really_wants_one_track_if_none_are_selected) {
-                               selection->set (entered_track);
-                       }
+               if (rs.empty()) {
+                       return;
                }
+
+               split_regions_at (where, rs);
        }
 }
 
 struct EditorOrderRouteSorter {
     bool operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b) {
-           /* use of ">" forces the correct sort order */
-           return a->order_key ("editor") < b->order_key ("editor");
+           return a->order_key () < b->order_key ();
     }
 };
 
@@ -5209,7 +5850,7 @@ Editor::select_next_route()
 
        selection->set(current);
 
-       ensure_track_visible(current);
+       ensure_time_axis_view_is_visible (*current, false);
 }
 
 void
@@ -5240,158 +5881,91 @@ Editor::select_prev_route()
 
        selection->set (current);
 
-       ensure_track_visible(current);
-}
-
-void
-Editor::ensure_track_visible(TimeAxisView *track)
-{
-       if (track->hidden())
-               return;
-
-       double const current_view_min_y = vertical_adjustment.get_value();
-       double const current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size() - canvas_timebars_vsize;
-
-       double const track_min_y = track->y_position ();
-       double const track_max_y = track->y_position () + track->effective_height ();
-
-       if (track_min_y >= current_view_min_y &&
-           track_max_y <= current_view_max_y) {
-               return;
-       }
-
-       double new_value;
-
-       if (track_min_y < current_view_min_y) {
-               // Track is above the current view
-               new_value = track_min_y;
-       } else {
-               // Track is below the current view
-               new_value = track->y_position () + track->effective_height() + canvas_timebars_vsize - vertical_adjustment.get_page_size();
-       }
-
-       vertical_adjustment.set_value(new_value);
+       ensure_time_axis_view_is_visible (*current, false);
 }
 
 void
 Editor::set_loop_from_selection (bool play)
-{
-       if (_session == 0 || selection->time.empty()) {
-               return;
-       }
-
-       framepos_t start = selection->time[clicked_selection].start;
-       framepos_t end = selection->time[clicked_selection].end;
-
-       set_loop_range (start, end,  _("set loop range from selection"));
-
-       if (play) {
-               _session->request_play_loop (true);
-               _session->request_locate (start, true);
-       }
-}
-
-void
-Editor::set_loop_from_edit_range (bool play)
 {
        if (_session == 0) {
                return;
        }
 
-       framepos_t start;
-       framepos_t end;
-
-       if (!get_edit_op_range (start, end)) {
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
                return;
-       }
 
-       set_loop_range (start, end,  _("set loop range from edit range"));
+       set_loop_range (start, end,  _("set loop range from selection"));
 
        if (play) {
-               _session->request_play_loop (true);
-               _session->request_locate (start, true);
+               _session->request_play_loop (true, true);
        }
 }
 
 void
 Editor::set_loop_from_region (bool play)
 {
-       framepos_t start = max_framepos;
-       framepos_t end = 0;
-
-       RegionSelection rs = get_regions_from_selection_and_entered ();
-
-       if (rs.empty()) {
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
                return;
-       }
-
-       for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
-               if ((*i)->region()->position() < start) {
-                       start = (*i)->region()->position();
-               }
-               if ((*i)->region()->last_frame() + 1 > end) {
-                       end = (*i)->region()->last_frame() + 1;
-               }
-       }
 
        set_loop_range (start, end, _("set loop range from region"));
 
        if (play) {
-               _session->request_play_loop (true);
                _session->request_locate (start, true);
+               _session->request_play_loop (true);
        }
 }
 
 void
 Editor::set_punch_from_selection ()
 {
-       if (_session == 0 || selection->time.empty()) {
+       if (_session == 0) {
                return;
        }
 
-       framepos_t start = selection->time[clicked_selection].start;
-       framepos_t end = selection->time[clicked_selection].end;
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
+               return;
 
        set_punch_range (start, end,  _("set punch range from selection"));
 }
 
 void
-Editor::set_punch_from_edit_range ()
+Editor::set_session_extents_from_selection ()
 {
        if (_session == 0) {
                return;
        }
+       
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
+               return;
 
-       framepos_t start;
-       framepos_t end;
+       begin_reversible_command (_("set session start/stop from selection"));
 
-       if (!get_edit_op_range (start, end)) {
-               return;
-       }
+       Location* loc;
+       if ((loc = _session->locations()->session_range_location()) == 0) {
+               _session->set_session_extents ( start, end );  // this will create a new session range;  no need for UNDO
+       } else {
+               XMLNode &before = loc->get_state();
+
+               _session->set_session_extents ( start, end );
+
+               XMLNode &after = loc->get_state();
 
-       set_punch_range (start, end,  _("set punch range from edit range"));
+               _session->add_command (new MementoCommand<Location>(*loc, &before, &after));
+
+               commit_reversible_command ();
+       }
 }
 
 void
 Editor::set_punch_from_region ()
 {
-       framepos_t start = max_framepos;
-       framepos_t end = 0;
-
-       RegionSelection rs = get_regions_from_selection_and_entered ();
-
-       if (rs.empty()) {
+       framepos_t start, end;
+       if (!get_selection_extents ( start, end))
                return;
-       }
-
-       for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ++i) {
-               if ((*i)->region()->position() < start) {
-                       start = (*i)->region()->position();
-               }
-               if ((*i)->region()->last_frame() + 1 > end) {
-                       end = (*i)->region()->last_frame() + 1;
-               }
-       }
 
        set_punch_range (start, end, _("set punch range from region"));
 }
@@ -5541,7 +6115,9 @@ Editor::define_one_bar (framepos_t start, framepos_t end)
        } else if (t.frame() == start) {
                _session->tempo_map().change_existing_tempo_at (start, beats_per_minute, t.note_type());
        } else {
-               _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), start);
+               Timecode::BBT_Time bbt;
+               _session->tempo_map().bbt_time (start, bbt);
+               _session->tempo_map().add_tempo (Tempo (beats_per_minute, t.note_type()), bbt);
        }
 
        XMLNode& after (_session->tempo_map().get_state());
@@ -5561,8 +6137,8 @@ Editor::split_region_at_transients ()
                return;
        }
 
-       _session->begin_reversible_command (_("split regions"));
-
+       begin_reversible_command (_("split regions"));
+       
        for (RegionSelection::iterator i = rs.begin(); i != rs.end(); ) {
 
                RegionSelection::iterator tmp;
@@ -5579,8 +6155,8 @@ Editor::split_region_at_transients ()
 
                i = tmp;
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 
 }
 
@@ -5641,6 +6217,7 @@ Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList
        AnalysisFeatureList::const_iterator x;
 
        pl->clear_changes ();
+       pl->clear_owned_changes ();
 
        x = positions.begin();
 
@@ -5695,6 +6272,10 @@ Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList
                plist.add (ARDOUR::Properties::layer, 0);
 
                boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
+               /* because we set annouce to false, manually add the new region to the
+                  RegionFactory map
+               */
+               RegionFactory::map_add (nr);
 
                pl->add_region (nr, r->position() + pos);
 
@@ -5719,6 +6300,10 @@ Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList
        plist.add (ARDOUR::Properties::layer, 0);
 
        boost::shared_ptr<Region> nr = RegionFactory::create (r->sources(), plist, false);
+       /* because we set annouce to false, manually add the new region to the
+          RegionFactory map
+       */
+       RegionFactory::map_add (nr);
        pl->add_region (nr, r->position() + pos);
 
        if (select_new) {
@@ -5727,6 +6312,13 @@ Editor::split_region_at_points (boost::shared_ptr<Region> r, AnalysisFeatureList
 
        pl->thaw ();
 
+       /* We might have removed regions, which alters other regions' layering_index,
+          so we need to do a recursive diff here.
+       */
+       vector<Command*> cmds;
+       pl->rdiff (cmds);
+       _session->add_commands (cmds);
+       
        _session->add_command (new StatefulDiffCommand (pl));
 
        if (select_new) {
@@ -5752,14 +6344,14 @@ Editor::place_transient()
 
        framepos_t where = get_preferred_edit_position();
 
-       _session->begin_reversible_command (_("place transient"));
-
+       begin_reversible_command (_("place transient"));
+       
        for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
                framepos_t position = (*r)->region()->position();
                (*r)->region()->add_transient(where - position);
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -5787,8 +6379,8 @@ Editor::snap_regions_to_grid ()
                return;
        }
 
-       _session->begin_reversible_command (_("snap regions to grid"));
-
+       begin_reversible_command (_("snap regions to grid"));
+       
        for (RegionSelection::iterator r = rs.begin(); r != rs.end(); ++r) {
 
                boost::shared_ptr<Playlist> pl = (*r)->region()->playlist();
@@ -5811,8 +6403,8 @@ Editor::snap_regions_to_grid ()
                (*i)->thaw();
                used_playlists.pop_front();
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -5831,8 +6423,7 @@ Editor::close_region_gaps ()
        Table table (2, 3);
        table.set_spacings (12);
        table.set_border_width (12);
-       Label* l = manage (new Label (_("Crossfade length")));
-       l->set_alignment (0, 0.5);
+       Label* l = manage (left_aligned_label (_("Crossfade length")));
        table.attach (*l, 0, 1, 0, 1);
 
        SpinButton spin_crossfade (1, 0);
@@ -5843,8 +6434,7 @@ Editor::close_region_gaps ()
 
        table.attach (*manage (new Label (_("ms"))), 2, 3, 0, 1);
 
-       l = manage (new Label (_("Pull-back length")));
-       l->set_alignment (0, 0.5);
+       l = manage (left_aligned_label (_("Pull-back length")));
        table.attach (*l, 0, 1, 1, 2);
 
        SpinButton spin_pullback (1, 0);
@@ -5872,8 +6462,8 @@ Editor::close_region_gaps ()
 
        /* Iterate over the region list and make adjacent regions overlap by crossfade_len_ms */
 
-       _session->begin_reversible_command (_("close region gaps"));
-
+       begin_reversible_command (_("close region gaps"));
+       
        int idx = 0;
        boost::shared_ptr<Region> last_region;
 
@@ -5912,8 +6502,8 @@ Editor::close_region_gaps ()
                (*i)->thaw();
                used_playlists.pop_front();
        }
-
-       _session->commit_reversible_command ();
+       
+       commit_reversible_command ();
 }
 
 void
@@ -5999,11 +6589,14 @@ Editor::tab_to_transient (bool forward)
 void
 Editor::playhead_forward_to_grid ()
 {
-       if (!_session) return;
-       framepos_t pos = playhead_cursor->current_frame;
+       if (!_session) {
+               return;
+       }
+       
+       framepos_t pos = playhead_cursor->current_frame ();
        if (pos < max_framepos - 1) {
                pos += 2;
-               snap_to_internal (pos, 1, false);
+               snap_to_internal (pos, RoundUpAlways, false);
                _session->request_locate (pos);
        }
 }
@@ -6012,11 +6605,14 @@ Editor::playhead_forward_to_grid ()
 void
 Editor::playhead_backward_to_grid ()
 {
-       if (!_session) return;
-       framepos_t pos = playhead_cursor->current_frame;
+       if (!_session) {
+               return;
+       }
+       
+       framepos_t pos = playhead_cursor->current_frame ();
        if (pos > 2) {
                pos -= 2;
-               snap_to_internal (pos, -1, false);
+               snap_to_internal (pos, RoundDownAlways, false);
                _session->request_locate (pos);
        }
 }
@@ -6075,12 +6671,13 @@ Editor::remove_tracks ()
 
        for (TrackSelection::iterator x = ts.begin(); x != ts.end(); ++x) {
                RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*x);
-               if (rtv) {
-                       if (rtv->is_track()) {
-                               ntracks++;
-                       } else {
-                               nbusses++;
-                       }
+               if (!rtv) {
+                       continue;
+               }
+               if (rtv->is_track()) {
+                       ntracks++;
+               } else {
+                       nbusses++;
                }
                routes.push_back (rtv->_route);
 
@@ -6111,6 +6708,7 @@ edit your ardour.rc file to set the\n\
                return;
        }
 
+       // XXX should be using gettext plural forms, maybe?
        if (ntracks > 1) {
                trackstr = _("tracks");
        } else {
@@ -6137,7 +6735,7 @@ edit your ardour.rc file to set the\n\
                }
        } else if (nbusses) {
                prompt  = string_compose (_("Do you really want to remove %1 %2?\n\n"
-                                           "This action cannot be undon, and the session file will be overwritten"),
+                                           "This action cannot be undone, and the session file will be overwritten"),
                                          nbusses, busstr);
        }
 
@@ -6161,8 +6759,12 @@ edit your ardour.rc file to set the\n\
                return;
        }
 
-       for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
-               _session->remove_route (*x);
+       {
+               Session::StateProtector sp (_session);
+               DisplaySuspender ds;
+               for (vector<boost::shared_ptr<Route> >::iterator x = routes.begin(); x != routes.end(); ++x) {
+                       _session->remove_route (*x);
+               }
        }
 }
 
@@ -6315,7 +6917,7 @@ Editor::insert_time (
 }
 
 void
-Editor::fit_selected_tracks ()
+Editor::fit_selection ()
 {
         if (!selection->tracks.empty()) {
                 fit_tracks (selection->tracks);
@@ -6342,6 +6944,7 @@ Editor::fit_selected_tracks ()
                         }
                 }
         }
+
 }
 
 void
@@ -6364,7 +6967,13 @@ Editor::fit_tracks (TrackViewList & tracks)
                ++visible_tracks;
        }
 
-       uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / visible_tracks);
+       /* compute the per-track height from:
+
+          total canvas visible height - 
+                 height that will be taken by visible children of selected
+                 tracks - height of the ruler/hscroll area 
+       */
+       uint32_t h = (uint32_t) floor ((trackviews_height() - child_heights) / visible_tracks);
        double first_y_pos = DBL_MAX;
 
        if (h < TimeAxisView::preset_height (HeightSmall)) {
@@ -6373,7 +6982,8 @@ Editor::fit_tracks (TrackViewList & tracks)
                return;
        }
 
-       undo_visual_stack.push_back (current_visual_state());
+       undo_visual_stack.push_back (current_visual_state (true));
+       no_save_visual = true;
 
        /* build a list of all tracks, including children */
 
@@ -6386,8 +6996,6 @@ Editor::fit_tracks (TrackViewList & tracks)
                }
        }
 
-       /* operate on all tracks, hide unselected ones that are in the middle of selected ones */
-
        bool prev_was_selected = false;
        bool is_selected = tracks.contains (all.front());
        bool next_is_selected;
@@ -6425,10 +7033,12 @@ Editor::fit_tracks (TrackViewList & tracks)
           request signal handler will cause the vertical adjustment setting to fail
        */
 
-       controls_layout.property_height () = full_canvas_height - canvas_timebars_vsize;
+       controls_layout.property_height () = _full_canvas_height;
        vertical_adjustment.set_value (first_y_pos);
 
-       redo_visual_stack.push_back (current_visual_state());
+       redo_visual_stack.push_back (current_visual_state (true));
+
+       visible_tracks_selector.set_text (_("Sel"));
 }
 
 void
@@ -6438,7 +7048,9 @@ Editor::save_visual_state (uint32_t n)
                visual_states.push_back (0);
        }
 
-       delete visual_states[n];
+       if (visual_states[n] != 0) {
+               delete visual_states[n];
+       }
 
        visual_states[n] = current_visual_state (true);
        gdk_beep ();
@@ -6461,38 +7073,19 @@ Editor::goto_visual_state (uint32_t n)
 void
 Editor::start_visual_state_op (uint32_t n)
 {
-       if (visual_state_op_connection.empty()) {
-               visual_state_op_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::end_visual_state_op), n), 1000);
-       }
-}
-
-void
-Editor::cancel_visual_state_op (uint32_t n)
-{
-       if (!visual_state_op_connection.empty()) {
-               visual_state_op_connection.disconnect();
-               goto_visual_state (n);
-       }  else {
-               //we land here if called from the menu OR if end_visual_state_op has been called
-               //so check if we are already in visual state n
-               // XXX not yet checking it at all, but redoing does not hurt
-               goto_visual_state (n);
-       }
-}
-
-bool
-Editor::end_visual_state_op (uint32_t n)
-{
-       visual_state_op_connection.disconnect();
        save_visual_state (n);
-
+       
        PopUp* pup = new PopUp (WIN_POS_MOUSE, 1000, true);
        char buf[32];
        snprintf (buf, sizeof (buf), _("Saved view %u"), n+1);
        pup->set_text (buf);
        pup->touch();
+}
 
-       return false; // do not call again
+void
+Editor::cancel_visual_state_op (uint32_t n)
+{
+        goto_visual_state (n);
 }
 
 void
@@ -6518,7 +7111,7 @@ Editor::toggle_region_mute ()
 
                (*i)->region()->playlist()->clear_changes ();
                (*i)->region()->set_muted (!(*i)->region()->muted ());
-               _session->add_command (new StatefulDiffCommand ((*i)->region()->playlist()));
+               _session->add_command (new StatefulDiffCommand ((*i)->region()));
 
        }
 
@@ -6595,3 +7188,106 @@ Editor::uncombine_regions ()
        commit_reversible_command ();
 }
 
+void
+Editor::toggle_midi_input_active (bool flip_others)
+{
+       bool onoff = false;
+       boost::shared_ptr<RouteList> rl (new RouteList);
+
+       for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
+               RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView *>(*i);
+
+               if (!rtav) {
+                       continue;
+               }
+
+               boost::shared_ptr<MidiTrack> mt = rtav->midi_track();
+
+               if (mt) {
+                       rl->push_back (rtav->route());
+                       onoff = !mt->input_active();
+               }
+       }
+       
+       _session->set_exclusive_input_active (rl, onoff, flip_others);
+}
+
+void
+Editor::lock ()
+{
+       if (!lock_dialog) {
+               lock_dialog = new Gtk::Dialog (string_compose (_("%1: Locked"), PROGRAM_NAME), true);
+
+               Gtk::Image* padlock = manage (new Gtk::Image (ARDOUR_UI_UTILS::get_icon ("padlock_closed")));
+               lock_dialog->get_vbox()->pack_start (*padlock);
+
+               ArdourButton* b = manage (new ArdourButton);
+               b->set_name ("lock button");
+               b->set_text (_("Click to unlock"));
+               b->signal_clicked.connect (sigc::mem_fun (*this, &Editor::unlock));
+               lock_dialog->get_vbox()->pack_start (*b);
+               
+               lock_dialog->get_vbox()->show_all ();
+               lock_dialog->set_size_request (200, 200);
+       }
+       
+#ifdef __APPLE__
+       /* The global menu bar continues to be accessible to applications
+          with modal dialogs, which means that we need to desensitize
+          all items in the menu bar. Since those items are really just
+          proxies for actions, that means disabling all actions.
+       */
+       ActionManager::disable_all_actions ();
+#endif
+       lock_dialog->present ();
+}
+
+void
+Editor::unlock ()
+{
+       lock_dialog->hide ();
+       
+#ifdef __APPLE__
+       ActionManager::pop_action_state ();
+#endif 
+
+       if (ARDOUR_UI::config()->get_lock_gui_after_seconds()) {
+               start_lock_event_timing ();
+       }
+}
+
+void
+Editor::bring_in_callback (Gtk::Label* label, uint32_t n, uint32_t total, string name)
+{
+       Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&Editor::update_bring_in_message, this, label, n, total, name));
+}
+
+void
+Editor::update_bring_in_message (Gtk::Label* label, uint32_t n, uint32_t total, string name)
+{
+       label->set_text (string_compose ("Copying %1, %2 of %3", name, n, total));
+       Gtkmm2ext::UI::instance()->flush_pending ();
+}
+
+void
+Editor::bring_all_sources_into_session ()
+{
+       if (!_session) {
+               return;
+       }
+
+       Gtk::Label msg;
+       ArdourDialog w (_("Moving embedded files into session folder"));
+       w.get_vbox()->pack_start (msg);
+       w.present ();
+       
+       /* flush all pending GUI events because we're about to start copying
+        * files
+        */
+       
+       Gtkmm2ext::UI::instance()->flush_pending ();
+
+       cerr << " Do it\n";
+
+       _session->bring_all_sources_into_session (boost::bind (&Editor::bring_in_callback, this, &msg, _1, _2, _3));
+}