Merge branch 'cairocanvas' of git.ardour.org:ardour/ardour into cairocanvas
[ardour.git] / gtk2_ardour / editor_ops.cc
index 738737f46d193f8ebff8a0e428c9d196aab455ed..08d6297faae3162c388f7a76b9cf411307d224b1 100644 (file)
@@ -31,6 +31,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/quantize.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 "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_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 "gtk-custom-hruler.h"
+#include "gui_thread.h"
 #include "insert_time_dialog.h"
-#include "normalize_dialog.h"
-#include "editor_cursors.h"
+#include "interthread_progress_window.h"
+#include "keyboard.h"
+#include "midi_region_view.h"
 #include "mouse_cursors.h"
+#include "normalize_dialog.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 "utils.h"
 
 #include "i18n.h"
 
@@ -356,8 +360,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 +449,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 +492,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 +512,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
@@ -771,7 +829,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 +864,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 +1200,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 +1254,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 +1266,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 +1282,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 +1299,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 +1317,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,16 +1330,85 @@ Editor::scroll_tracks_up_line ()
        reset_y_origin (vertical_adjustment.get_value() - 60);
 }
 
+bool
+Editor::scroll_down_one_track ()
+{
+       double vertical_pos = vertical_adjustment.get_value () + vertical_adjustment.get_page_size() - 1.0; 
+
+       TrackViewList::reverse_iterator next = track_views.rend();
+       std::pair<TimeAxisView*,double> res;
+
+       for (TrackViewList::reverse_iterator t = track_views.rbegin(); t != track_views.rend(); ++t) {
+               if ((*t)->hidden()) {
+                       continue;
+               }
+               
+               res = (*t)->covers_y_position (vertical_pos);
+
+               if (res.first) {
+                       break;
+               }
+
+               next = t;
+       }
+
+       /* move to the track below the first one that covers the */
+       
+       if (next != track_views.rend()) {
+               ensure_track_visible (*next);
+               return true;
+       }
+
+       return false;
+}      
+
+bool
+Editor::scroll_up_one_track ()
+{
+       double vertical_pos = vertical_adjustment.get_value ();
+
+       TrackViewList::iterator prev = track_views.end();
+       std::pair<TimeAxisView*,double> res;
+
+       for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
+
+               if ((*t)->hidden()) {
+                       continue;
+               }
+
+               res = (*t)->covers_y_position(vertical_pos);
+               
+               if (res.first) {
+                       break;
+               }
+
+               prev = t;
+       }
+       
+       if (prev != track_views.end()) {
+               ensure_track_visible (*prev);
+               return true;
+       }
+
+       return false;
+}
+
 /* ZOOM */
 
 void
 Editor::tav_zoom_step (bool coarser)
 {
-       ENSURE_GUI_THREAD (*this, &Editor::temporal_zoom_step, coarser)
-
        _routes->suspend_redisplay ();
 
-       for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
+       TrackViewList* ts;
+
+       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);
        }
@@ -1289,30 +1416,80 @@ Editor::tav_zoom_step (bool coarser)
        _routes->resume_redisplay ();
 }
 
+void
+Editor::tav_zoom_smooth (bool coarser, bool force_all)
+{
+       _routes->suspend_redisplay ();
+
+       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 ();
+
+               if (coarser) {
+                       if (h > 5) {
+                               h -= 5; // pixels
+                               if (h >= TimeAxisView::preset_height (HeightSmall)) {
+                                       tv->set_height (h);
+                               }
+                       }
+               } else {
+                       tv->set_height (h + 5);
+               }
+       }
+
+       _routes->resume_redisplay ();
+}
+
+bool
+Editor::clamp_samples_per_pixel (framecnt_t& fpp) const
+{
+       bool clamped = false;
+       
+       if (fpp < 1) {
+               fpp = 1;
+               clamped = true;
+       }
+
+       if (max_framepos / fpp < 800) {
+               fpp = max_framepos / 800;
+               clamped = true;
+       }
+
+       return clamped;
+}
+
 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 +1498,26 @@ 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) {
+       clamp_samples_per_pixel (fpp);
+       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, fpp);
+
+       new_page_size = (framepos_t) floor (_visible_canvas_width * nfpp);
        half_page_size = new_page_size / 2;
 
        switch (zoom_focus) {
@@ -1360,7 +1545,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 +1561,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,7 +1610,7 @@ 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
@@ -1470,8 +1655,8 @@ Editor::temporal_zoom_region (bool both_axes)
        }
 
        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);
+       double new_fpp = (double) range / (double) _visible_canvas_width;
+       framepos_t extra_samples = (framepos_t) floor (one_centimeter_in_pixels * new_fpp);
 
        if (start > extra_samples) {
                start -= extra_samples;
@@ -1485,18 +1670,17 @@ Editor::temporal_zoom_region (bool both_axes)
                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;
-       }
+       /* if we're zooming on both axes we need to save track heights etc.
+        */
 
-       temporal_zoom_by_frame (start, end, "zoom to region");
+       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 */
 
@@ -1517,10 +1701,9 @@ 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
@@ -1541,7 +1724,7 @@ Editor::temporal_zoom_selection ()
        framepos_t start = selection->time[clicked_selection].start;
        framepos_t end = selection->time[clicked_selection].end;
 
-       temporal_zoom_by_frame (start, end, "zoom to selection");
+       temporal_zoom_by_frame (start, end);
 }
 
 void
@@ -1556,12 +1739,12 @@ Editor::temporal_zoom_session ()
                        s = 0;
                }
                framecnt_t const e = _session->current_end_frame() + l * 0.01;
-               temporal_zoom_by_frame (framecnt_t (s), e, "zoom to _session");
+               temporal_zoom_by_frame (framecnt_t (s), e);
        }
 }
 
 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,17 +1754,21 @@ 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;
+       double const new_fpp = (double) range / (double) _visible_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));
+       framepos_t new_page = (framepos_t) floor (_visible_canvas_width * new_fpp);
+       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
@@ -1591,19 +1778,19 @@ Editor::temporal_zoom_to_frame (bool coarser, framepos_t frame)
                return;
        }
        double range_before = frame - leftmost_frame;
-       double new_fpu;
+       double new_fpp;
 
-       new_fpu = frames_per_unit;
+       new_fpp = samples_per_pixel;
 
        if (coarser) {
-               new_fpu *= 1.61803399;
+               new_fpp *= 1.61803399;
                range_before *= 1.61803399;
        } else {
-               new_fpu = max(1.0,(new_fpu/1.61803399));
+               new_fpp = max(1.0,(new_fpp/1.61803399));
                range_before /= 1.61803399;
        }
 
-       if (new_fpu == frames_per_unit)  {
+       if (new_fpp == samples_per_pixel)  {
                return;
        }
 
@@ -1617,7 +1804,7 @@ 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_fpp);
 }
 
 
@@ -1782,13 +1969,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 +1985,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
@@ -1897,22 +2084,19 @@ Editor::unhide_ranges ()
 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;
+       event.button.x = x;
+       event.button.y = y;
 
-       where = event_frame (&event, &cx, &cy);
+       where = window_event_sample (&event, &cx, &cy);
 
-       if (where < leftmost_frame || where > leftmost_frame + current_page_frames()) {
+       if (where < leftmost_frame || where > leftmost_frame + current_page_samples()) {
                /* clearly outside canvas area */
                return;
        }
@@ -1942,21 +2126,16 @@ Editor::insert_region_list_drag (boost::shared_ptr<Region> region, int x, int y)
 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.button.x = x;
+       event.button.y = y;
 
-       event_frame (&event, &cx, &cy);
+       window_event_sample (&event, &cx, &cy);
 
        std::pair<TimeAxisView*, int> const tv = trackview_by_y_position (cy);
        if (tv.first == 0) {
@@ -2042,8 +2221,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 */
@@ -2105,6 +2284,55 @@ Editor::play_selection ()
        _session->request_play_range (&selection->time, 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() || !Config->get_always_play_range() )
+               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 ()
+{
+       if (selection->time.empty()) {
+               return;
+       } else {
+               framepos_t preroll = get_preroll();
+               
+               framepos_t start = 0;
+               if (selection->time[clicked_selection].start > preroll)
+                       start = selection->time[clicked_selection].start - preroll;
+               
+               framepos_t end = selection->time[clicked_selection].end + preroll;
+               
+               AudioRange ar (start, end, 0);
+               list<AudioRange> lar;
+               lar.push_back (ar);
+
+               _session->request_play_range (&lar, true);
+       }
+}
+
 void
 Editor::play_location (Location& location)
 {
@@ -2133,28 +2361,101 @@ Editor::loop_location (Location& location)
        }
 }
 
+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 +2497,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);
@@ -2396,7 +2696,7 @@ static void
 add_if_covered (RegionView* rv, const AudioRange* ar, RegionSelection* rs)
 {
        switch (rv->region()->coverage (ar->start, ar->end - 1)) {
-       case OverlapNone:
+       case Evoral::OverlapNone:
                break;
        default:
                rs->push_back (rv);
@@ -2539,7 +2839,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 +3387,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 +3400,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 +3446,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,16 +3566,19 @@ 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 */
+       current_interthread_info->process_thread.get_buffers ();
        clicked_routeview->audio_track()->freeze_me (*current_interthread_info);
        current_interthread_info->done = true;
+       current_interthread_info->process_thread.drop_buffers();
        return 0;
 }
 
@@ -3292,21 +3592,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;
                }
        }
 
@@ -3337,16 +3657,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 +3700,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;
@@ -3424,7 +3755,7 @@ Editor::copy ()
 bool
 Editor::can_cut_copy () const
 {
-       switch (current_mouse_mode()) {
+       switch (effective_mouse_mode()) {
 
        case MouseObject:
                if (!selection->regions.empty() || !selection->points.empty()) {
@@ -3483,7 +3814,8 @@ Editor::cut_copy (CutCopyOp op)
                }
        }
 
-       cut_buffer->clear ();
+       if ( op != Clear )  //"Delete" doesn't change copy/paste buf
+               cut_buffer->clear ();
 
        if (entered_marker) {
 
@@ -3502,94 +3834,185 @@ Editor::cut_copy (CutCopyOp op)
 
        if (internal_editing()) {
 
-               switch (current_mouse_mode()) {
+               switch (effective_mouse_mode()) {
                case MouseObject:
                case MouseRange:
+                       begin_reversible_command (opname + ' ' + X_("MIDI"));
                        cut_copy_midi (op);
+                       commit_reversible_command ();
                        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()) {
+               return;
+       }
 
-                               begin_reversible_command (opname + _(" objects"));
+       bool did_edit = false;
 
-                               if (!rs.empty()) {
-                                       cut_copy_regions (op, rs);
+       switch (effective_mouse_mode()) {
+       case MouseGain:
+               if (!selection->points.empty()) {
+                       begin_reversible_command (opname + _(" points"));
+                       did_edit = true;
+                       cut_copy_points (op);
+                       if (op == Cut || op == Delete) {
+                               selection->clear_points ();
+                       }
+               }
+               break;
+               
+       case MouseObject: 
 
-                                       if (op == Cut || op == Delete) {
-                                               selection->clear_regions ();
-                                       }
-                               }
+               if (!selection->regions.empty() || !selection->points.empty()) {
 
-                               if (!selection->points.empty()) {
-                                       cut_copy_points (op);
+                       string thing_name;
 
-                                       if (op == Cut || op == Delete) {
-                                               selection->clear_points ();
-                                       }
-                               }
-                               commit_reversible_command ();
-                               break; // terminate case statement here
+                       if (selection->regions.empty()) {
+                               thing_name = _("points");
+                       } else if (selection->points.empty()) {
+                               thing_name = _("regions");
+                       } else {
+                               thing_name = _("objects");
                        }
-                       if (!selection->time.empty()) {
-                               /* don't cause suprises */
-                               break;
+               
+                       begin_reversible_command (opname + ' ' + thing_name);
+                       did_edit = true;
+
+                       if (!selection->regions.empty()) {
+                               cut_copy_regions (op, selection->regions);
+                               
+                               if (op == Cut || op == Delete) {
+                                       selection->clear_regions ();
+                               }
                        }
-                       // 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;
+                       
+                       if (!selection->points.empty()) {
+                               cut_copy_points (op);
+                               
+                               if (op == Cut || op == Delete) {
+                                       selection->clear_points ();
                                }
+                       }
+               } 
+               break;
+                       
+       case MouseRange:
+               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);
                        }
-
+               }
+               if (!selection->time.empty()) {
                        begin_reversible_command (opname + _(" range"));
-                       cut_copy_ranges (op);
-                       commit_reversible_command ();
 
+                       did_edit = true;
+                       cut_copy_ranges (op);
+                       
                        if (op == Cut || op == Delete) {
                                selection->clear_time ();
                        }
-
-                       break;
-
-               default:
-                       break;
                }
+               break;
+               
+       default:
+               break;
        }
-
+       
+       if (did_edit) {
+               commit_reversible_command ();   
+       }
+       
        if (op == Delete || op == Cut || op == Clear) {
                _drags->abort ();
        }
 }
 
+struct AutomationRecord {
+       AutomationRecord () : state (0) {}
+       AutomationRecord (XMLNode* s) : state (s) {}
+       
+       XMLNode* state; ///< state before any operation
+       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)
 {
+       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) {
+               boost::shared_ptr<AutomationList> al = (*i)->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 ());
+               }
+       }
+
+       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 ());
+               }
+
+               /* Add all selected points to the relevant copy ControlLists */
+               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->add ((*j)->when, (*j)->value);
+               }
+
+               for (Lists::iterator i = lists.begin(); i != lists.end(); ++i) {
+                       /* Correct this copy list so that it starts at time 0 */
+                       double const start = i->second.copy->front()->when;
+                       for (AutomationList::iterator j = i->second.copy->begin(); j != i->second.copy->end(); ++j) {
+                               (*j)->when -= start;
+                       }
+
+                       /* 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 ())));
                }
        }
 }
@@ -3633,7 +4056,16 @@ Editor::remove_clicked_region ()
 
        begin_reversible_command (_("remove region"));
        playlist->clear_changes ();
+       playlist->clear_owned_changes ();
        playlist->remove_region (clicked_regionview->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,6 +4117,7 @@ Editor::remove_selected_regions ()
                playlists.push_back (playlist);
 
                playlist->clear_changes ();
+               playlist->clear_owned_changes ();
                playlist->freeze ();
                playlist->remove_region (*rl);
        }
@@ -3693,6 +4126,14 @@ Editor::remove_selected_regions ()
 
        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 +4180,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);
                                }
@@ -3854,6 +4296,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 +4334,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
@@ -3930,12 +4381,15 @@ Editor::paste_internal (framepos_t position, float times)
 
        /* get everything in the correct order */
 
-       if (!selection->tracks.empty()) {
-               /* there are some selected tracks, so paste to them */
+       if (_edit_point == Editing::EditAtMouse && entered_track) {
+               /* With the mouse edit point, paste onto the track under the mouse */
+               ts.push_back (entered_track);
+       } else if (!selection->tracks.empty()) {
+               /* Otherwise, if there are some selected tracks, paste to them */
                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;
+               /* Otherwise paste to the track that the cut/copy came from;
                   see discussion in mantis #3333.
                */
                ts.push_back (_last_cut_copy_source_track);
@@ -4057,32 +4511,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);
 }
 
@@ -4363,7 +4812,7 @@ Editor::apply_midi_note_edit_op_to_region (MidiOperator& op, MidiRegionView& mrv
        vector<Evoral::Sequence<Evoral::MusicalTime>::Notes> v;
        v.push_back (selected);
 
-       framepos_t pos_frames = mrv.midi_region()->position();
+       framepos_t pos_frames = mrv.midi_region()->position() - mrv.midi_region()->start();
        double     pos_beats  = _session->tempo_map().framewalk_to_beats(0, pos_frames);
 
        return op (mrv.midi_region()->model(), pos_beats, v);
@@ -4423,12 +4872,17 @@ 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;
@@ -4472,8 +4926,7 @@ Editor::quantize_region ()
        qd->hide ();
 
        if (r == Gtk::RESPONSE_OK) {
-               Quantize quant (*_session, Plain,
-                               qd->snap_start(), qd->snap_end(),
+               Quantize quant (*_session, qd->snap_start(), qd->snap_end(),
                                qd->start_grid_size(), qd->end_grid_size(),
                                qd->strength(), qd->swing(), qd->threshold());
 
@@ -4482,17 +4935,24 @@ Editor::quantize_region ()
 }
 
 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);
+
+       /* 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::MusicalTime> empty (0, 0, 0, 0);
-       PatchChangeDialog d (0, _session, empty, Gtk::Stock::ADD);
+        PatchChangeDialog d (0, _session, empty, first->instrument_info(), Gtk::Stock::ADD);
 
        if (d.run() == RESPONSE_CANCEL) {
                return;
@@ -4540,6 +5000,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,6 +5023,13 @@ 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;
@@ -4614,7 +5082,31 @@ Editor::reset_region_gain_envelopes ()
 }
 
 void
-Editor::toggle_gain_envelope_visibility ()
+Editor::set_region_gain_visibility (RegionView* rv)
+{
+       AudioRegionView* arv = dynamic_cast<AudioRegionView*> (rv);
+       if (arv) {
+               arv->update_envelope_visibility();
+       }
+}
+
+void
+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,13 +5118,13 @@ Editor::toggle_gain_envelope_visibility ()
                return;
        }
 
-       _session->begin_reversible_command (_("region gain envelope visible"));
+       _session->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()));
                }
        }
@@ -4641,7 +5133,7 @@ Editor::toggle_gain_envelope_visibility ()
 }
 
 void
-Editor::toggle_gain_envelope_active ()
+Editor::toggle_region_lock ()
 {
        if (_ignore_region_action) {
                return;
@@ -4653,22 +5145,19 @@ Editor::toggle_gain_envelope_active ()
                return;
        }
 
-       _session->begin_reversible_command (_("region gain envelope active"));
+       _session->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 ();
 }
 
 void
-Editor::toggle_region_lock ()
+Editor::toggle_region_video_lock ()
 {
        if (_ignore_region_action) {
                return;
@@ -4680,11 +5169,11 @@ Editor::toggle_region_lock ()
                return;
        }
 
-       _session->begin_reversible_command (_("toggle region lock"));
+       _session->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()));
        }
 
@@ -5008,6 +5497,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 +5561,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,14 +5607,15 @@ Editor::set_playhead_cursor ()
                        _session->request_locate (where, _session->transport_rolling());
                }
        }
+
+       if ( Config->get_always_play_range() )
+               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 ( !selection->time.empty()) {
                separate_regions_between (selection->time);
                return;
        }
@@ -5155,28 +5631,9 @@ Editor::split_region ()
        split_regions_at (where, rs);
 }
 
-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 */
-
-                       if (op_really_wants_one_track_if_none_are_selected) {
-                               selection->set (entered_track);
-                       }
-               }
-       }
-}
-
 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 ();
     }
 };
 
@@ -5250,7 +5707,7 @@ Editor::ensure_track_visible(TimeAxisView *track)
                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 current_view_max_y = vertical_adjustment.get_value() + vertical_adjustment.get_page_size();
 
        double const track_min_y = track->y_position ();
        double const track_max_y = track->y_position () + track->effective_height ();
@@ -5267,7 +5724,7 @@ Editor::ensure_track_visible(TimeAxisView *track)
                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();
+               new_value = track->y_position () + track->effective_height() - vertical_adjustment.get_page_size();
        }
 
        vertical_adjustment.set_value(new_value);
@@ -5475,7 +5932,9 @@ Editor::define_one_bar (framepos_t start, framepos_t end)
           we have frames per bar, and beats per bar, so ...
        */
 
-       double frames_per_beat = length / m.beats_per_bar();
+       /* XXXX METER MATH */
+
+       double frames_per_beat = length / m.divisions_per_bar();
 
        /* beats per minute = */
 
@@ -5539,7 +5998,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());
@@ -5639,6 +6100,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();
 
@@ -5693,6 +6155,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);
 
@@ -5717,6 +6183,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) {
@@ -5725,6 +6195,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) {
@@ -5829,8 +6306,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);
@@ -5841,8 +6317,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);
@@ -5997,8 +6472,11 @@ 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);
@@ -6010,8 +6488,11 @@ 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);
@@ -6073,12 +6554,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);
 
@@ -6362,7 +6844,7 @@ Editor::fit_tracks (TrackViewList & tracks)
                ++visible_tracks;
        }
 
-       uint32_t h = (uint32_t) floor ((_canvas_height - child_heights - canvas_timebars_vsize) / visible_tracks);
+       uint32_t h = (uint32_t) floor ((_visible_canvas_height - child_heights) / visible_tracks);
        double first_y_pos = DBL_MAX;
 
        if (h < TimeAxisView::preset_height (HeightSmall)) {
@@ -6371,7 +6853,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 */
 
@@ -6423,10 +6906,10 @@ 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));
 }
 
 void
@@ -6436,7 +6919,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 ();
@@ -6459,38 +6944,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
@@ -6593,3 +7059,26 @@ 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);
+}