clear_history -> clear_changes and some comments.
[ardour.git] / gtk2_ardour / midi_region_view.cc
index 4ea7aba4faaa88692abca2a88e564e01d7bc99a8..6aa83acf1140b5b2642d75e97ee47b6f9fd8f83c 100644 (file)
 #include <sigc++/signal.h>
 
 #include "pbd/memento_command.h"
+#include "pbd/stateful_diff_command.h"
 
 #include "ardour/playlist.h"
 #include "ardour/tempo.h"
 #include "ardour/midi_region.h"
 #include "ardour/midi_source.h"
-#include "ardour/midi_diskstream.h"
 #include "ardour/midi_model.h"
 #include "ardour/midi_patch_manager.h"
 #include "ardour/session.h"
 
 #include "evoral/Parameter.hpp"
+#include "evoral/MIDIParameters.hpp"
 #include "evoral/Control.hpp"
+#include "evoral/midi_util.h"
 
 #include "automation_region_view.h"
 #include "automation_time_axis.h"
@@ -58,6 +60,7 @@
 #include "midi_time_axis.h"
 #include "midi_util.h"
 #include "public_editor.h"
+#include "rgb_macros.h"
 #include "selection.h"
 #include "simpleline.h"
 #include "streamview.h"
@@ -76,15 +79,18 @@ MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &
        : RegionView (parent, tv, r, spu, basic_color)
        , _force_channel(-1)
        , _last_channel_selection(0xFFFF)
-       , _default_note_length(1.0)
        , _current_range_min(0)
        , _current_range_max(0)
        , _model_name(string())
        , _custom_device_mode(string())
        , _active_notes(0)
        , _note_group(new ArdourCanvas::Group(*parent))
-       , _delta_command(0)
        , _diff_command(0)
+       , _ghost_note(0)
+        , _drag_rect (0)
+        , _step_edit_cursor (0)
+        , _step_edit_cursor_width (1.0)
+        , _step_edit_cursor_position (0.0)
        , _mouse_state(None)
        , _pressed_button(0)
        , _sort_needed (true)
@@ -93,6 +99,7 @@ MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &
        , no_sound_notes (false)
 {
        _note_group->raise_to_top();
+        PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
 }
 
 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
@@ -101,37 +108,36 @@ MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &
        : RegionView (parent, tv, r, spu, basic_color, false, visibility)
        , _force_channel(-1)
        , _last_channel_selection(0xFFFF)
-       , _default_note_length(1.0)
        , _model_name(string())
        , _custom_device_mode(string())
        , _active_notes(0)
        , _note_group(new ArdourCanvas::Group(*parent))
-       , _delta_command(0)
        , _diff_command(0)
+       , _ghost_note(0)
+        , _drag_rect (0)
        , _mouse_state(None)
        , _pressed_button(0)
        , _sort_needed (true)
        , _optimization_iterator (_events.end())
        , _list_editor (0)
        , no_sound_notes (false)
-
 {
        _note_group->raise_to_top();
+        PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
 }
 
-
 MidiRegionView::MidiRegionView (const MidiRegionView& other)
        : sigc::trackable(other)
        , RegionView (other)
        , _force_channel(-1)
        , _last_channel_selection(0xFFFF)
-       , _default_note_length(1.0)
        , _model_name(string())
        , _custom_device_mode(string())
        , _active_notes(0)
        , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
-       , _delta_command(0)
        , _diff_command(0)
+       , _ghost_note(0)
+        , _drag_rect (0)
        , _mouse_state(None)
        , _pressed_button(0)
        , _sort_needed (true)
@@ -152,13 +158,13 @@ MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<M
        : RegionView (other, boost::shared_ptr<Region> (region))
        , _force_channel(-1)
        , _last_channel_selection(0xFFFF)
-       , _default_note_length(1.0)
        , _model_name(string())
        , _custom_device_mode(string())
        , _active_notes(0)
        , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
-       , _delta_command(0)
        , _diff_command(0)
+       , _ghost_note(0)
+        , _drag_rect (0)
        , _mouse_state(None)
        , _pressed_button(0)
        , _sort_needed (true)
@@ -178,6 +184,12 @@ MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<M
 void
 MidiRegionView::init (Gdk::Color const & basic_color, bool wfd)
 {
+        PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
+
+        CanvasNoteEvent::CanvasNoteEventDeleted.connect (note_delete_connection, MISSING_INVALIDATOR, 
+                                                         ui_bind (&MidiRegionView::maybe_remove_deleted_note_from_selection, this, _1),
+                                                         gui_context());
+
        if (wfd) {
                midi_region()->midi_source(0)->load_model();
        }
@@ -215,311 +227,410 @@ MidiRegionView::init (Gdk::Color const & basic_color, bool wfd)
 
        midi_view()->signal_midi_patch_settings_changed().connect(
                        sigc::mem_fun(this, &MidiRegionView::midi_patch_settings_changed));
+
+       trackview.editor().SnapChanged.connect (snap_changed_connection, invalidator (*this), ui_bind (&MidiRegionView::snap_changed, this), gui_context ());
 }
 
 bool
 MidiRegionView::canvas_event(GdkEvent* ev)
 {
-       PublicEditor& editor (trackview.editor());
-
-       if (!editor.internal_editing()) {
+       if (!trackview.editor().internal_editing()) {
                return false;
        }
 
-       static double drag_start_x, drag_start_y;
-       static double last_x, last_y;
-       double event_x, event_y;
-       nframes64_t event_frame = 0;
-       bool fine;
-
-       static ArdourCanvas::SimpleRect* drag_rect = 0;
-
-       /* XXX: note that as of August 2009, the GnomeCanvas does not propagate scroll events
+       /* XXX: note that until version 2.30, the GnomeCanvas did not propagate scroll events
           to its items, which means that ev->type == GDK_SCROLL will never be seen
        */
 
        switch (ev->type) {
        case GDK_SCROLL:
-               fine = Keyboard::modifier_state_equals (ev->scroll.state, Keyboard::Level4Modifier);
-
-               if (ev->scroll.direction == GDK_SCROLL_UP) {
-                       change_velocities (true, fine, false);
-                       return true;
-               } else if (ev->scroll.direction == GDK_SCROLL_DOWN) {
-                       change_velocities (false, fine, false);
-                       return true;
-               } else {
-                       return false;
-               }
-               break;
+                return scroll (&ev->scroll);
 
        case GDK_KEY_PRESS:
+                return key_press (&ev->key);
 
-               /* since GTK bindings are generally activated on press, and since
-                  detectable auto-repeat is the name of the game and only sends
-                  repeated presses, carry out key actions at key press, not release.
-               */
-
-               if (ev->key.keyval == GDK_Alt_L || ev->key.keyval == GDK_Alt_R){
-                       _mouse_state = SelectTouchDragging;
-                       return true;
-
-               } else if (ev->key.keyval == GDK_Escape) {
-                       clear_selection();
-                       _mouse_state = None;
-
-               } else if (ev->key.keyval == GDK_comma || ev->key.keyval == GDK_period) {
-
-                       bool start = (ev->key.keyval == GDK_comma);
-                       bool end = (ev->key.keyval == GDK_period);
-                       bool shorter = Keyboard::modifier_state_contains (ev->key.state, Keyboard::PrimaryModifier);
-                       fine = Keyboard::modifier_state_contains (ev->key.state, Keyboard::SecondaryModifier);
-
-                       change_note_lengths (fine, shorter, start, end);
-
-                       return true;
-
-               } else if (ev->key.keyval == GDK_Delete) {
-
-                       delete_selection();
-                       return true;
+       case GDK_KEY_RELEASE:
+                return key_release (&ev->key);
 
-               } else if (ev->key.keyval == GDK_Tab) {
+       case GDK_BUTTON_PRESS:
+                return button_press (&ev->button);
 
-                       if (Keyboard::modifier_state_equals (ev->key.state, Keyboard::PrimaryModifier)) {
-                               goto_previous_note ();
-                       } else {
-                               goto_next_note ();
-                       }
-                       return true;
+       case GDK_2BUTTON_PRESS:
+               return true;
 
-               } else if (ev->key.keyval == GDK_Up) {
+       case GDK_BUTTON_RELEASE:
+                return button_release (&ev->button);
+               
+       case GDK_ENTER_NOTIFY:
+                return enter_notify (&ev->crossing);
 
-                       bool allow_smush = Keyboard::modifier_state_contains (ev->key.state, Keyboard::SecondaryModifier);
-                       bool fine = Keyboard::modifier_state_contains (ev->key.state, Keyboard::TertiaryModifier);
+       case GDK_LEAVE_NOTIFY:
+                return leave_notify (&ev->crossing);
 
-                       if (Keyboard::modifier_state_contains (ev->key.state, Keyboard::PrimaryModifier)) {
-                               change_velocities (true, fine, allow_smush);
-                       } else {
-                               transpose (true, fine, allow_smush);
-                       }
-                       return true;
+       case GDK_MOTION_NOTIFY:
+                return motion (&ev->motion);
 
-               } else if (ev->key.keyval == GDK_Down) {
+       default: 
+                break;
+       }
 
-                       bool allow_smush = Keyboard::modifier_state_contains (ev->key.state, Keyboard::SecondaryModifier);
-                       fine = Keyboard::modifier_state_contains (ev->key.state, Keyboard::TertiaryModifier);
+       return false;
+}
 
-                       if (Keyboard::modifier_state_contains (ev->key.state, Keyboard::PrimaryModifier)) {
-                               change_velocities (false, fine, allow_smush);
-                       } else {
-                               transpose (false, fine, allow_smush);
-                       }
-                       return true;
+bool
+MidiRegionView::enter_notify (GdkEventCrossing* ev)
+{
+        /* FIXME: do this on switch to note tool, too, if the pointer is already in */
 
-               } else if (ev->key.keyval == GDK_Left) {
+        Keyboard::magic_widget_grab_focus();
+        group->grab_focus();
+        
+        if (trackview.editor().current_mouse_mode() == MouseRange) {
+                create_ghost_note (ev->x, ev->y);
+        }
 
-                       nudge_notes (false);
-                       return true;
+        return false;
+}
 
-               } else if (ev->key.keyval == GDK_Right) {
+bool
+MidiRegionView::leave_notify (GdkEventCrossing* ev)
+{
+        trackview.editor().hide_verbose_canvas_cursor ();
+        delete _ghost_note;
+        _ghost_note = 0;
+        return false;
+}
 
-                       nudge_notes (true);
-                       return true;
+bool
+MidiRegionView::button_press (GdkEventButton* ev)
+{
+        _last_x = ev->x;
+        _last_y = ev->y;
+        group->w2i (_last_x, _last_y);
+        
+        if (_mouse_state != SelectTouchDragging && ev->button == 1) {
+                _pressed_button = ev->button;
+                _mouse_state = Pressed;
+                return true;
+        }
+        
+        _pressed_button = ev->button;
 
-               } else if (ev->key.keyval == GDK_Control_L) {
-                       return true;
+        return true;
+}
 
-               } else if (ev->key.keyval == GDK_r) {
-                       /* if we're not step editing, this really doesn't matter */
-                       midi_view()->step_edit_rest ();
-                       return true;
-               }
+bool
+MidiRegionView::button_release (GdkEventButton* ev)
+{
+       double event_x, event_y;
+       nframes64_t event_frame = 0;
 
-               return false;
+        event_x = ev->x;
+        event_y = ev->y;
+        group->w2i(event_x, event_y);
+        group->ungrab(ev->time);
+        event_frame = trackview.editor().pixel_to_frame(event_x);
+
+        if (ev->button == 3) {
+                return false;
+        } else if (_pressed_button != 1) {
+                return false;
+        }
+
+        switch (_mouse_state) {
+        case Pressed: // Clicked
+                switch (trackview.editor().current_mouse_mode()) {
+                case MouseObject:
+                case MouseTimeFX:
+                        clear_selection();
+                        maybe_select_by_position (ev, event_x, event_y);
+                        break;
+
+                case MouseRange:
+                {
+                        bool success;
+                        Evoral::MusicalTime beats = trackview.editor().get_grid_type_as_beats (success, trackview.editor().pixel_to_frame (event_x));
+                        if (!success) {
+                                beats = 1;
+                        }
+                        create_note_at (event_x, event_y, beats, true);
+                        break;
+                }
+                default:
+                        break;
+                }
+                _mouse_state = None;
+                break;
+        case SelectRectDragging: // Select drag done
+                _mouse_state = None;
+                delete _drag_rect;
+                _drag_rect = 0;
+                break;
+
+        case AddDragging: // Add drag done
+                _mouse_state = None;
+                if (_drag_rect->property_x2() > _drag_rect->property_x1() + 2) {
+                        const double x      = _drag_rect->property_x1();
+                        const double length = trackview.editor().pixel_to_frame 
+                                (_drag_rect->property_x2() - _drag_rect->property_x1());
+
+                        create_note_at (x, _drag_rect->property_y1(), frames_to_beats(length), false);
+                }
+
+                delete _drag_rect;
+                _drag_rect = 0;
+
+                create_ghost_note (ev->x, ev->y);
+
+        default:
+                break;
+        }
+
+        return false;
+}
 
-       case GDK_KEY_RELEASE:
-               if (ev->key.keyval == GDK_Alt_L || ev->key.keyval == GDK_Alt_R) {
-                       _mouse_state = None;
-                       return true;
-               }
-               return false;
+bool
+MidiRegionView::motion (GdkEventMotion* ev)
+{
+       double event_x, event_y;
+       nframes64_t event_frame = 0;
 
-       case GDK_BUTTON_PRESS:
-               if (_mouse_state != SelectTouchDragging && ev->button.button == 1) {
-                       _pressed_button = ev->button.button;
-                       _mouse_state = Pressed;
-                       return true;
-               }
-               _pressed_button = ev->button.button;
-               return true;
+        event_x = ev->x;
+        event_y = ev->y;
+        group->w2i(event_x, event_y);
 
-       case GDK_2BUTTON_PRESS:
-               return true;
+        // convert event_x to global frame
+        event_frame = trackview.editor().pixel_to_frame(event_x) + _region->position();
+        trackview.editor().snap_to(event_frame);
+        // convert event_frame back to local coordinates relative to position
+        event_frame -= _region->position();
 
-       case GDK_ENTER_NOTIFY:
-               /* FIXME: do this on switch to note tool, too, if the pointer is already in */
-               Keyboard::magic_widget_grab_focus();
-               group->grab_focus();
-               break;
+        if (_ghost_note) {
+                update_ghost_note (ev->x, ev->y);
+        }
 
-       case GDK_MOTION_NOTIFY:
-               event_x = ev->motion.x;
-               event_y = ev->motion.y;
-               group->w2i(event_x, event_y);
-
-               // convert event_x to global frame
-               event_frame = trackview.editor().pixel_to_frame(event_x) + _region->position();
-               trackview.editor().snap_to(event_frame);
-               // convert event_frame back to local coordinates relative to position
-               event_frame -= _region->position();
-
-               switch (_mouse_state) {
-               case Pressed: // Drag start
-
-                       // Select drag start
-                       if (_pressed_button == 1 && editor.current_mouse_mode() == MouseObject) {
-                               group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
-                                               Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
-                               last_x = event_x;
-                               last_y = event_y;
-                               drag_start_x = event_x;
-                               drag_start_y = event_y;
-
-                               drag_rect = new ArdourCanvas::SimpleRect(*group);
-                               drag_rect->property_x1() = event_x;
-                               drag_rect->property_y1() = event_y;
-                               drag_rect->property_x2() = event_x;
-                               drag_rect->property_y2() = event_y;
-                               drag_rect->property_outline_what() = 0xFF;
-                               drag_rect->property_outline_color_rgba()
-                                       = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
-                               drag_rect->property_fill_color_rgba()
-                                       = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
-
-                               _mouse_state = SelectRectDragging;
-                               return true;
+        /* any motion immediately hides velocity text that may have been visible */
+               
+       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
+               (*i)->hide_velocity ();
+       }
+
+        switch (_mouse_state) {
+        case Pressed: // Maybe start a drag, if we've moved a bit
+
+                if (fabs (event_x - _last_x) < 1 && fabs (event_y - _last_y) < 1) {
+                        /* no appreciable movement since the button was pressed */
+                        return false;
+                }
+
+                // Select drag start
+                if (_pressed_button == 1 && trackview.editor().current_mouse_mode() == MouseObject) {
+                        group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
+                                    Gdk::Cursor(Gdk::FLEUR), ev->time);
+                        _last_x = event_x;
+                        _last_y = event_y;
+                        _drag_start_x = event_x;
+                        _drag_start_y = event_y;
+
+                        _drag_rect = new ArdourCanvas::SimpleRect(*group);
+                        _drag_rect->property_x1() = event_x;
+                        _drag_rect->property_y1() = event_y;
+                        _drag_rect->property_x2() = event_x;
+                        _drag_rect->property_y2() = event_y;
+                        _drag_rect->property_outline_what() = 0xFF;
+                        _drag_rect->property_outline_color_rgba()
+                                = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
+                        _drag_rect->property_fill_color_rgba()
+                                = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
+
+                        _mouse_state = SelectRectDragging;
+                        return true;
 
                        // Add note drag start
-                       } else if (editor.current_mouse_mode() == MouseRange) {
-                               group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
-                                               Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
-                               last_x = event_x;
-                               last_y = event_y;
-                               drag_start_x = event_x;
-                               drag_start_y = event_y;
-
-                               drag_rect = new ArdourCanvas::SimpleRect(*group);
-                               drag_rect->property_x1() = trackview.editor().frame_to_pixel(event_frame);
-
-                               drag_rect->property_y1() = midi_stream_view()->note_to_y(
-                                               midi_stream_view()->y_to_note(event_y));
-                               drag_rect->property_x2() = event_x;
-                               drag_rect->property_y2() = drag_rect->property_y1()
-                                                        + floor(midi_stream_view()->note_height());
-                               drag_rect->property_outline_what() = 0xFF;
-                               drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
-                               drag_rect->property_fill_color_rgba()    = 0xFFFFFF66;
-
-                               _mouse_state = AddDragging;
-                               return true;
-                       }
-
-                       return false;
-
-               case SelectRectDragging: // Select drag motion
-               case AddDragging: // Add note drag motion
-                       if (ev->motion.is_hint) {
-                               int t_x;
-                               int t_y;
-                               GdkModifierType state;
-                               gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
-                               event_x = t_x;
-                               event_y = t_y;
-                       }
-
-                       if (_mouse_state == AddDragging)
-                               event_x = trackview.editor().frame_to_pixel(event_frame);
-
-                       if (drag_rect) {
-                               if (event_x > drag_start_x)
-                                       drag_rect->property_x2() = event_x;
-                               else
-                                       drag_rect->property_x1() = event_x;
-                       }
-
-                       if (drag_rect && _mouse_state == SelectRectDragging) {
-                               if (event_y > drag_start_y)
-                                       drag_rect->property_y2() = event_y;
-                               else
-                                       drag_rect->property_y1() = event_y;
-
-                               update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
-                       }
-
-                       last_x = event_x;
-                       last_y = event_y;
-
-               case SelectTouchDragging:
-                       return false;
+                } else if (trackview.editor().internal_editing()) {
+
+                        delete _ghost_note;
+                        _ghost_note = 0;
+                               
+                        group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
+                                    Gdk::Cursor(Gdk::FLEUR), ev->time);
+                        _last_x = event_x;
+                        _last_y = event_y;
+                        _drag_start_x = event_x;
+                        _drag_start_y = event_y;
+
+                        _drag_rect = new ArdourCanvas::SimpleRect(*group);
+                        _drag_rect->property_x1() = trackview.editor().frame_to_pixel(event_frame);
+
+                        _drag_rect->property_y1() = midi_stream_view()->note_to_y(
+                                midi_stream_view()->y_to_note(event_y));
+                        _drag_rect->property_x2() = trackview.editor().frame_to_pixel(event_frame);
+                        _drag_rect->property_y2() = _drag_rect->property_y1()
+                                + floor(midi_stream_view()->note_height());
+                        _drag_rect->property_outline_what() = 0xFF;
+                        _drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
+                        _drag_rect->property_fill_color_rgba()    = 0xFFFFFF66;
+
+                        _mouse_state = AddDragging;
+                        return true;
+                }
+
+                return false;
+
+        case SelectRectDragging: // Select drag motion
+        case AddDragging: // Add note drag motion
+                if (ev->is_hint) {
+                        int t_x;
+                        int t_y;
+                        GdkModifierType state;
+                        gdk_window_get_pointer(ev->window, &t_x, &t_y, &state);
+                        event_x = t_x;
+                        event_y = t_y;
+                }
+
+                if (_mouse_state == AddDragging)
+                        event_x = trackview.editor().frame_to_pixel(event_frame);
+
+                if (_drag_rect) {
+                        if (event_x > _drag_start_x)
+                                _drag_rect->property_x2() = event_x;
+                        else
+                                _drag_rect->property_x1() = event_x;
+                }
+
+                if (_drag_rect && _mouse_state == SelectRectDragging) {
+                        if (event_y > _drag_start_y)
+                                _drag_rect->property_y2() = event_y;
+                        else
+                                _drag_rect->property_y1() = event_y;
+
+                        update_drag_selection(_drag_start_x, event_x, _drag_start_y, event_y);
+                }
+
+                _last_x = event_x;
+                _last_y = event_y;
+
+        case SelectTouchDragging:
+                return false;
+
+        default:
+                break;
+        }
+
+        return false;
+}
 
-               default:
-                       break;
-               }
-               break;
 
-       case GDK_BUTTON_RELEASE:
-               event_x = ev->motion.x;
-               event_y = ev->motion.y;
-               group->w2i(event_x, event_y);
-               group->ungrab(ev->button.time);
-               event_frame = trackview.editor().pixel_to_frame(event_x);
-
-               if (ev->button.button == 3) {
-                       return false;
-               } else if (_pressed_button != 1) {
-                       return false;
-               }
+bool
+MidiRegionView::scroll (GdkEventScroll* ev)
+{
+        if (_selection.empty()) {
+                return false;
+        }
 
-               switch (_mouse_state) {
-               case Pressed: // Clicked
-                       switch (editor.current_mouse_mode()) {
-                       case MouseObject:
-                       case MouseTimeFX:
-                               clear_selection();
-                               break;
-                       case MouseRange:
-                               create_note_at(event_x, event_y, _default_note_length);
-                               break;
-                       default:
-                               break;
-                       }
-                       _mouse_state = None;
-                       break;
-               case SelectRectDragging: // Select drag done
-                       _mouse_state = None;
-                       delete drag_rect;
-                       drag_rect = 0;
-                       break;
-               case AddDragging: // Add drag done
-                       _mouse_state = None;
-                       if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
-                               const double x      = drag_rect->property_x1();
-                               const double length = trackview.editor().pixel_to_frame(
-                                                       drag_rect->property_x2() - drag_rect->property_x1());
-
-                               create_note_at(x, drag_rect->property_y1(), frames_to_beats(length));
-                       }
+       trackview.editor().hide_verbose_canvas_cursor ();
 
-                       delete drag_rect;
-                       drag_rect = 0;
-               default: break;
-               }
+        bool fine = !Keyboard::modifier_state_equals (ev->state, Keyboard::SecondaryModifier);
+        
+        if (ev->direction == GDK_SCROLL_UP) {
+                change_velocities (true, fine, false);
+        } else if (ev->direction == GDK_SCROLL_DOWN) {
+                change_velocities (false, fine, false);
+        } 
+        return true;
+}
 
-       default: break;
-       }
+bool
+MidiRegionView::key_press (GdkEventKey* ev)
+{ 
+        /* since GTK bindings are generally activated on press, and since
+           detectable auto-repeat is the name of the game and only sends
+           repeated presses, carry out key actions at key press, not release.
+        */
+        
+        if (ev->keyval == GDK_Alt_L || ev->keyval == GDK_Alt_R){
+                _mouse_state = SelectTouchDragging;
+                return true;
+                
+        } else if (ev->keyval == GDK_Escape) {
+                clear_selection();
+                _mouse_state = None;
+                
+        } else if (ev->keyval == GDK_comma || ev->keyval == GDK_period) {
+                
+                bool start = (ev->keyval == GDK_comma);
+                bool end = (ev->keyval == GDK_period);
+                bool shorter = Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier);
+                bool fine = Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
+                
+                change_note_lengths (fine, shorter, 0.0, start, end);
+                
+                return true;
+                
+        } else if (ev->keyval == GDK_Delete) {
+                
+                delete_selection();
+                return true;
+                
+        } else if (ev->keyval == GDK_Tab) {
+                
+                if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
+                        goto_previous_note ();
+                } else {
+                        goto_next_note ();
+                }
+                return true;
+                
+        } else if (ev->keyval == GDK_Up) {
+                
+                bool allow_smush = Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier);
+                bool fine = !Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
+                
+                if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
+                        change_velocities (true, fine, allow_smush);
+                } else {
+                        transpose (true, fine, allow_smush);
+                }
+                return true;
+                
+        } else if (ev->keyval == GDK_Down) {
+                
+                bool allow_smush = Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier);
+                bool fine = !Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
+                
+                if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
+                        change_velocities (false, fine, allow_smush);
+                } else {
+                        transpose (false, fine, allow_smush);
+                }
+                return true;
+                
+        } else if (ev->keyval == GDK_Left) {
+                
+                nudge_notes (false);
+                return true;
+                
+        } else if (ev->keyval == GDK_Right) {
+                
+                nudge_notes (true);
+                return true;
+                
+        } else if (ev->keyval == GDK_Control_L) {
+                return true;
+
+        }
+        
+        return false;
+}
 
-       return false;
+bool
+MidiRegionView::key_release (GdkEventKey* ev)
+{
+        if (ev->keyval == GDK_Alt_L || ev->keyval == GDK_Alt_R) {
+                _mouse_state = None;
+                return true;
+        }
+        return false;
 }
 
 void
@@ -534,9 +645,11 @@ MidiRegionView::show_list_editor ()
 /** Add a note to the model, and the view, at a canvas (click) coordinate.
  * \param x horizontal position in pixels
  * \param y vertical position in pixels
- * \param length duration of the note in beats */
+ * \param length duration of the note in beats, which will be snapped to the grid
+ * \param sh true to make the note 1 frame shorter than the snapped version of \a length.
+ */
 void
-MidiRegionView::create_note_at(double x, double y, double length)
+MidiRegionView::create_note_at(double x, double y, double length, bool sh)
 {
        MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
        MidiStreamView* const view = mtv->midi_view();
@@ -547,20 +660,49 @@ MidiRegionView::create_note_at(double x, double y, double length)
        assert(note <= 127.0);
 
        // Start of note in frames relative to region start
-       nframes64_t start_frames = snap_frame_to_frame(trackview.editor().pixel_to_frame(x));
+       nframes64_t const start_frames = snap_frame_to_frame(trackview.editor().pixel_to_frame(x));
        assert(start_frames >= 0);
 
        // Snap length
        length = frames_to_beats(
                        snap_frame_to_frame(start_frames + beats_to_frames(length)) - start_frames);
 
-       const boost::shared_ptr<NoteType> new_note(new NoteType(0,
-                       frames_to_beats(start_frames + _region->start()), length,
-                       (uint8_t)note, 0x40));
+       assert (length != 0);
+
+       if (sh) {
+               length = frames_to_beats (beats_to_frames (length) - 1);
+       }
+
+       uint16_t chn_mask = mtv->channel_selector().get_selected_channels();
+        int chn_cnt = 0;
+        uint8_t channel = 0;
+
+        /* pick the highest selected channel, unless all channels are selected,
+           which is interpreted to mean channel 1 (zero)
+        */
+
+        for (uint16_t i = 0; i < 16; ++i) {
+                if (chn_mask & (1<<i)) {
+                        channel = i;
+                        chn_cnt++;
+                }
+        }
+
+        if (chn_cnt == 16) {
+                channel = 0;
+        }
+
+       const boost::shared_ptr<NoteType> new_note (new NoteType (channel,
+                                                                  frames_to_beats(start_frames + _region->start()), length,
+                                                                  (uint8_t)note, 0x40));
+
+        if (_model->contains (new_note)) {
+                return;
+        }
 
        view->update_note_range(new_note->note());
 
-       MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
+       MidiModel::DiffCommand* cmd = _model->new_diff_command("add note");
        cmd->add(new_note);
        _model->apply_command(*trackview.session(), cmd);
 
@@ -595,7 +737,7 @@ MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
 {
        _model = model;
        content_connection.disconnect ();
-       _model->ContentsChanged.connect (content_connection, boost::bind (&MidiRegionView::redisplay_model, this), gui_context());
+       _model->ContentsChanged.connect (content_connection, invalidator (*this), boost::bind (&MidiRegionView::redisplay_model, this), gui_context());
 
        clear_events ();
 
@@ -604,15 +746,6 @@ MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
        }
 }
 
-
-void
-MidiRegionView::start_delta_command(string name)
-{
-       if (!_delta_command) {
-               _delta_command = _model->new_delta_command(name);
-       }
-}
-
 void
 MidiRegionView::start_diff_command(string name)
 {
@@ -622,10 +755,10 @@ MidiRegionView::start_diff_command(string name)
 }
 
 void
-MidiRegionView::delta_add_note(const boost::shared_ptr<NoteType> note, bool selected, bool show_velocity)
+MidiRegionView::diff_add_note(const boost::shared_ptr<NoteType> note, bool selected, bool show_velocity)
 {
-       if (_delta_command) {
-               _delta_command->add(note);
+       if (_diff_command) {
+               _diff_command->add(note);
        }
        if (selected) {
                _marked_for_selection.insert(note);
@@ -636,10 +769,10 @@ MidiRegionView::delta_add_note(const boost::shared_ptr<NoteType> note, bool sele
 }
 
 void
-MidiRegionView::delta_remove_note(ArdourCanvas::CanvasNoteEvent* ev)
+MidiRegionView::diff_remove_note(ArdourCanvas::CanvasNoteEvent* ev)
 {
-       if (_delta_command && ev->note()) {
-               _delta_command->remove(ev->note());
+       if (_diff_command && ev->note()) {
+               _diff_command->remove(ev->note());
        }
 }
 
@@ -663,85 +796,63 @@ MidiRegionView::diff_add_change (ArdourCanvas::CanvasNoteEvent* ev,
        }
 }
 
-void
-MidiRegionView::apply_delta()
-{
-       if (!_delta_command) {
-               return;
-       }
-
-       // Mark all selected notes for selection when model reloads
-       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
-               _marked_for_selection.insert((*i)->note());
-       }
-
-       _model->apply_command(*trackview.session(), _delta_command);
-       _delta_command = 0;
-       midi_view()->midi_track()->diskstream()->playlist_modified();
-
-       _marked_for_selection.clear();
-       _marked_for_velocity.clear();
-}
-
 void
 MidiRegionView::apply_diff ()
 {
+        bool add_or_remove;
+
        if (!_diff_command) {
                return;
        }
 
+        if ((add_or_remove = _diff_command->adds_or_removes())) {
+                // Mark all selected notes for selection when model reloads
+                for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
+                        _marked_for_selection.insert((*i)->note());
+                }
+        }
+
        _model->apply_command(*trackview.session(), _diff_command);
        _diff_command = 0;
-       midi_view()->midi_track()->diskstream()->playlist_modified();
+       midi_view()->midi_track()->playlist_modified();
+        
+        if (add_or_remove) {
+               _marked_for_selection.clear();
+        }
 
        _marked_for_velocity.clear();
 }
 
-void
-MidiRegionView::apply_delta_as_subcommand()
-{
-       if (!_delta_command) {
-               return;
-       }
-
-       // Mark all selected notes for selection when model reloads
-       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
-               _marked_for_selection.insert((*i)->note());
-       }
-
-       _model->apply_command_as_subcommand(*trackview.session(), _delta_command);
-       _delta_command = 0;
-       midi_view()->midi_track()->diskstream()->playlist_modified();
-
-       _marked_for_selection.clear();
-       _marked_for_velocity.clear();
-}
-
 void
 MidiRegionView::apply_diff_as_subcommand()
 {
+        bool add_or_remove;
+
        if (!_diff_command) {
                return;
        }
 
-       // Mark all selected notes for selection when model reloads
-       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
-               _marked_for_selection.insert((*i)->note());
-       }
+        if ((add_or_remove = _diff_command->adds_or_removes())) {
+                // Mark all selected notes for selection when model reloads
+                for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
+                        _marked_for_selection.insert((*i)->note());
+                }
+        }
 
        _model->apply_command_as_subcommand(*trackview.session(), _diff_command);
        _diff_command = 0;
-       midi_view()->midi_track()->diskstream()->playlist_modified();
+       midi_view()->midi_track()->playlist_modified();
 
-       _marked_for_selection.clear();
+        if (add_or_remove) {
+                _marked_for_selection.clear();
+        }
        _marked_for_velocity.clear();
 }
 
+
 void
 MidiRegionView::abort_command()
 {
-       delete _delta_command;
-       _delta_command = 0;
        delete _diff_command;
        _diff_command = 0;
        clear_selection();
@@ -767,6 +878,20 @@ MidiRegionView::find_canvas_note (boost::shared_ptr<NoteType> note)
        return 0;
 }
 
+void
+MidiRegionView::get_events (Events& e, Evoral::Sequence<Evoral::MusicalTime>::NoteOperator op, uint8_t val, int chan_mask)
+{
+        MidiModel::Notes notes;
+        _model->get_notes (notes, op, val, chan_mask);
+
+        for (MidiModel::Notes::iterator n = notes.begin(); n != notes.end(); ++n) {
+                CanvasNoteEvent* cne = find_canvas_note (*n);
+                if (cne) {
+                        e.push_back (cne);
+                }
+        }
+}
+
 void
 MidiRegionView::redisplay_model()
 {
@@ -830,6 +955,7 @@ MidiRegionView::redisplay_model()
                }
        }
 
+
        /* remove note items that are no longer valid */
 
        for (Events::iterator i = _events.begin(); i != _events.end(); ) {
@@ -841,6 +967,9 @@ MidiRegionView::redisplay_model()
                }
        }
 
+       _pgm_changes.clear();
+       _sys_exes.clear();
+       
        display_sysexes();
        display_program_changes();
 
@@ -858,15 +987,28 @@ MidiRegionView::redisplay_model()
 void
 MidiRegionView::display_program_changes()
 {
-       boost::shared_ptr<Evoral::Control> control = _model->control(MidiPgmChangeAutomation);
+       MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
+       uint16_t chn_mask = mtv->channel_selector().get_selected_channels();
+
+        for (uint8_t i = 0; i < 16; ++i) {
+                if (chn_mask & (1<<i)) {
+                        display_program_changes_on_channel (i);
+                }
+        }
+}
+
+void
+MidiRegionView::display_program_changes_on_channel(uint8_t channel)
+{
+       boost::shared_ptr<Evoral::Control> control = 
+                _model->control(Evoral::MIDI::ProgramChange (MidiPgmChangeAutomation, channel));
+
        if (!control) {
                return;
        }
 
        Glib::Mutex::Lock lock (control->list()->lock());
 
-       uint8_t channel = control->parameter().channel();
-
        for (AutomationList::const_iterator event = control->list()->begin();
                        event != control->list()->end(); ++event) {
                double event_time     = (*event)->when;
@@ -877,7 +1019,7 @@ MidiRegionView::display_program_changes()
                boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
                uint8_t msb = 0;
                if (msb_control != 0) {
-                       msb = uint8_t(floor(msb_control->get_float(true, event_time) + 0.5));
+                       msb = uint8_t(floor(msb_control->get_double(true, event_time) + 0.5));
                }
 
                // Get current value of bank select LSB at time of the program change
@@ -885,7 +1027,7 @@ MidiRegionView::display_program_changes()
                boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
                uint8_t lsb = 0;
                if (lsb_control != 0) {
-                       lsb = uint8_t(floor(lsb_control->get_float(true, event_time) + 0.5));
+                       lsb = uint8_t(floor(lsb_control->get_double(true, event_time) + 0.5));
                }
 
                MIDI::Name::PatchPrimaryKey patch_key(msb, lsb, program_number);
@@ -900,7 +1042,8 @@ MidiRegionView::display_program_changes()
                        add_pgm_change(program_change, patch->name());
                } else {
                        char buf[4];
-                       snprintf(buf, 4, "%d", int(program_number));
+                        // program_number is zero-based: convert to one-based
+                       snprintf(buf, 4, "%d", int(program_number+1));
                        add_pgm_change(program_change, buf);
                }
        }
@@ -948,6 +1091,10 @@ MidiRegionView::~MidiRegionView ()
 {
        in_destructor = true;
 
+       trackview.editor().hide_verbose_canvas_cursor ();
+
+        note_delete_connection.disconnect ();
+
        delete _list_editor;
 
        RegionViewGoingAway (this); /* EMIT_SIGNAL */
@@ -958,8 +1105,10 @@ MidiRegionView::~MidiRegionView ()
 
        _selection.clear();
        clear_events();
+
        delete _note_group;
-       delete _delta_command;
+       delete _diff_command;
+        delete _step_edit_cursor;
 }
 
 void
@@ -984,6 +1133,9 @@ MidiRegionView::reset_width_dependent_items (double pixel_width)
        if (_enable_display) {
                redisplay_model();
        }
+        
+        move_step_edit_cursor (_step_edit_cursor_position);
+        set_step_edit_cursor_width (_step_edit_cursor_width);
 }
 
 void
@@ -1001,6 +1153,14 @@ MidiRegionView::set_height (double height)
        if (name_pixbuf) {
                name_pixbuf->raise_to_top();
        }
+        
+        for (PgmChanges::iterator x = _pgm_changes.begin(); x != _pgm_changes.end(); ++x) {
+                (*x)->set_height (midi_stream_view()->contents_height());
+        }
+
+        if (_step_edit_cursor) {
+                _step_edit_cursor->property_y2() = midi_stream_view()->contents_height();
+        }
 }
 
 
@@ -1083,7 +1243,7 @@ MidiRegionView::add_ghost (TimeAxisView& tv)
                }
        }
 
-       GhostRegion::CatchDeletion.connect (*this, ui_bind (&RegionView::remove_ghost, this, _1), gui_context());
+       GhostRegion::CatchDeletion.connect (*this, invalidator (*this), ui_bind (&RegionView::remove_ghost, this, _1), gui_context());
 
        return ghost;
 }
@@ -1200,12 +1360,13 @@ MidiRegionView::update_note (CanvasNote* ev)
        boost::shared_ptr<NoteType> note = ev->note();
 
        const nframes64_t note_start_frames = beats_to_frames(note->time());
-       const nframes64_t note_end_frames   = beats_to_frames(note->end_time());
+
+       /* trim note display to not overlap the end of its region */
+       const nframes64_t note_end_frames = min (beats_to_frames (note->end_time()), _region->start() + _region->length());
 
        const double x = trackview.editor().frame_to_pixel(note_start_frames - _region->start());
        const double y1 = midi_stream_view()->note_to_y(note->note());
-       const double note_endpixel =
-               trackview.editor().frame_to_pixel(note_end_frames - _region->start());
+       const double note_endpixel = trackview.editor().frame_to_pixel(note_end_frames - _region->start());
 
        ev->property_x1() = x;
        ev->property_y1() = y1;
@@ -1299,7 +1460,7 @@ MidiRegionView::add_note(const boost::shared_ptr<NoteType> note, bool visible)
        if (event) {
                if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
                        note_selected(event, true);
-               }
+                }
 
                if (_marked_for_velocity.find(note) != _marked_for_velocity.end()) {
                        event->show_velocity();
@@ -1316,25 +1477,34 @@ MidiRegionView::add_note(const boost::shared_ptr<NoteType> note, bool visible)
 }
 
 void
-MidiRegionView::add_note (uint8_t channel, uint8_t number, uint8_t velocity,
-                         Evoral::MusicalTime pos, Evoral::MusicalTime len)
+MidiRegionView::step_add_note (uint8_t channel, uint8_t number, uint8_t velocity,
+                               Evoral::MusicalTime pos, Evoral::MusicalTime len)
 {
        boost::shared_ptr<NoteType> new_note (new NoteType (channel, pos, len, number, velocity));
 
-       start_delta_command (_("step add"));
-       delta_add_note (new_note, true, false);
-       apply_delta();
-
        /* potentially extend region to hold new note */
 
        nframes64_t end_frame = _region->position() + beats_to_frames (new_note->end_time());
        nframes64_t region_end = _region->position() + _region->length() - 1;
 
        if (end_frame > region_end) {
-               _region->set_length (end_frame, this);
-       } else {
-               redisplay_model ();
+               _region->set_length (end_frame - _region->position(), this);
        }
+
+        _marked_for_selection.clear ();
+        clear_selection ();
+
+       start_diff_command (_("step add"));
+       diff_add_note (new_note, true, false);
+       apply_diff();
+
+        // last_step_edit_note = new_note;
+}
+
+void
+MidiRegionView::step_sustain (Evoral::MusicalTime beats)
+{
+        change_note_lengths (false, false, beats, false, true);
 }
 
 void
@@ -1369,29 +1539,25 @@ MidiRegionView::add_pgm_change(PCEvent& program, const string& displaytext)
 void
 MidiRegionView::get_patch_key_at(double time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
 {
-       cerr << "getting patch key at " << time << " for channel " << channel << endl;
        Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
        boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
-       float msb = -1.0;
+       double msb = 0.0;
        if (msb_control != 0) {
-               msb = int(msb_control->get_float(true, time));
-               cerr << "got msb " << msb;
+               msb = int(msb_control->get_double(true, time));
        }
 
        Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
        boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
-       float lsb = -1.0;
+       double lsb = 0.0;
        if (lsb_control != 0) {
-               lsb = lsb_control->get_float(true, time);
-               cerr << " got lsb " << lsb;
+               lsb = lsb_control->get_double(true, time);
        }
 
        Evoral::Parameter program_change(MidiPgmChangeAutomation, channel, 0);
        boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
-       float program_number = -1.0;
+       double program_number = -1.0;
        if (program_control != 0) {
-               program_number = program_control->get_float(true, time);
-               cerr << " got program " << program_number << endl;
+               program_number = program_control->get_double(true, time);
        }
 
        key.msb = (int) floor(msb + 0.5);
@@ -1408,23 +1574,24 @@ MidiRegionView::alter_program_change(PCEvent& old_program, const MIDI::Name::Pat
        Evoral::Parameter bank_select_msb(MidiCCAutomation, old_program.channel, MIDI_CTL_MSB_BANK);
        boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
        if (msb_control != 0) {
-               msb_control->set_float(float(new_patch.msb), true, old_program.time);
+               msb_control->set_double(double(new_patch.msb), true, old_program.time);
        }
 
        // TODO: Get the real event here and alter them at the original times
        Evoral::Parameter bank_select_lsb(MidiCCAutomation, old_program.channel, MIDI_CTL_LSB_BANK);
        boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
        if (lsb_control != 0) {
-               lsb_control->set_float(float(new_patch.lsb), true, old_program.time);
+               lsb_control->set_double(double(new_patch.lsb), true, old_program.time);
        }
 
        Evoral::Parameter program_change(MidiPgmChangeAutomation, old_program.channel, 0);
        boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
 
        assert(program_control != 0);
-       program_control->set_float(float(new_patch.program_number), true, old_program.time);
+       program_control->set_double(float(new_patch.program_number), true, old_program.time);
 
-       redisplay_model();
+        _pgm_changes.clear ();
+        display_program_changes (); // XXX would be nice to limit to just old_program.channel
 }
 
 void
@@ -1437,39 +1604,39 @@ MidiRegionView::program_selected(CanvasProgramChange& program, const MIDI::Name:
 void
 MidiRegionView::previous_program(CanvasProgramChange& program)
 {
-       MIDI::Name::PatchPrimaryKey key;
-       get_patch_key_at(program.event_time(), program.channel(), key);
-
-       boost::shared_ptr<MIDI::Name::Patch> patch =
-               MIDI::Name::MidiPatchManager::instance().previous_patch(
-                               _model_name,
-                               _custom_device_mode,
-                               program.channel(),
-                               key);
+        if (program.program() < 127) {
+                MIDI::Name::PatchPrimaryKey key;
+                get_patch_key_at(program.event_time(), program.channel(), key);
+                PCEvent program_change_event(program.event_time(), program.program(), program.channel());
 
-       PCEvent program_change_event(program.event_time(), program.program(), program.channel());
-       if (patch) {
-               alter_program_change(program_change_event, patch->patch_primary_key());
-       }
+                key.program_number++;
+                alter_program_change(program_change_event, key);
+        }
 }
 
 void
 MidiRegionView::next_program(CanvasProgramChange& program)
 {
-       MIDI::Name::PatchPrimaryKey key;
-       get_patch_key_at(program.event_time(), program.channel(), key);
+        if (program.program() > 0) {
+                MIDI::Name::PatchPrimaryKey key;
+                get_patch_key_at(program.event_time(), program.channel(), key);
+                PCEvent program_change_event(program.event_time(), program.program(), program.channel());
 
-       boost::shared_ptr<MIDI::Name::Patch> patch =
-               MIDI::Name::MidiPatchManager::instance().next_patch(
-                               _model_name,
-                               _custom_device_mode,
-                               program.channel(),
-                               key);
+                key.program_number--;
+                alter_program_change(program_change_event, key);
+        }
+}
 
-       PCEvent program_change_event(program.event_time(), program.program(), program.channel());
-       if (patch) {
-               alter_program_change(program_change_event, patch->patch_primary_key());
-       }
+void
+MidiRegionView::maybe_remove_deleted_note_from_selection (CanvasNoteEvent* cne)
+{
+        if (_selection.empty()) {
+                return;
+        }
+        if (_selection.erase (cne) > 0) {
+                cerr << "Erased a CNE from selection\n";
+        }
 }
 
 void
@@ -1479,17 +1646,27 @@ MidiRegionView::delete_selection()
                return;
        }
 
-       start_delta_command (_("delete selection"));
+       start_diff_command (_("delete selection"));
 
        for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
                if ((*i)->selected()) {
-                       _delta_command->remove((*i)->note());
+                       _diff_command->remove((*i)->note());
                }
        }
 
        _selection.clear();
 
-       apply_delta ();
+       apply_diff ();
+}
+
+void
+MidiRegionView::delete_note (boost::shared_ptr<NoteType> n)
+{
+       start_diff_command (_("delete note"));
+       _diff_command->remove (n);
+       apply_diff ();
+
+       trackview.editor().hide_verbose_canvas_cursor ();
 }
 
 void
@@ -1497,7 +1674,7 @@ MidiRegionView::clear_selection_except(ArdourCanvas::CanvasNoteEvent* ev)
 {
        for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
                if ((*i)->selected() && (*i) != ev) {
-                       (*i)->selected(false);
+                       (*i)->set_selected(false);
                        (*i)->hide_velocity();
                }
        }
@@ -1514,7 +1691,7 @@ MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
                        Selection::iterator tmp = i;
                        ++tmp;
 
-                       (*i)->selected (false);
+                       (*i)->set_selected (false);
                        _selection.erase (i);
 
                        i = tmp;
@@ -1542,6 +1719,10 @@ MidiRegionView::select_matching_notes (uint8_t notenum, uint16_t channel_mask, b
        MidiModel::Notes& notes (_model->notes());
        _optimization_iterator = _events.begin();
 
+        if (!add) {
+                clear_selection ();
+        }
+
        if (extend && _selection.empty()) {
                extend = false;
        }
@@ -1571,7 +1752,7 @@ MidiRegionView::select_matching_notes (uint8_t notenum, uint16_t channel_mask, b
                CanvasNoteEvent* cne;
                bool select = false;
 
-               if (((0x0001 << note->channel()) & channel_mask) != 0) {
+               if (((1 << note->channel()) & channel_mask) != 0) {
                        if (extend) {
                                if ((note->note() >= low_note && note->note() <= high_note)) {
                                        select = true;
@@ -1737,7 +1918,7 @@ MidiRegionView::remove_from_selection (CanvasNoteEvent* ev)
                _selection.erase (i);
        }
 
-       ev->selected (false);
+       ev->set_selected (false);
        ev->hide_velocity ();
 
        if (_selection.empty()) {
@@ -1756,7 +1937,7 @@ MidiRegionView::add_to_selection (CanvasNoteEvent* ev)
        }
 
        if (_selection.insert (ev).second) {
-               ev->selected (true);
+               ev->set_selected (true);
                play_midi_note ((ev)->note());
        }
 
@@ -1775,7 +1956,7 @@ MidiRegionView::move_selection(double dx, double dy)
 }
 
 void
-MidiRegionView::note_dropped(CanvasNoteEvent *, double dt, int8_t dnote)
+MidiRegionView::note_dropped(CanvasNoteEvent *, frameoffset_t dt, int8_t dnote)
 {
        assert (!_selection.empty());
 
@@ -1810,15 +1991,7 @@ MidiRegionView::note_dropped(CanvasNoteEvent *, double dt, int8_t dnote)
 
        for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ++i) {
 
-               nframes64_t start_frames = beats_to_frames((*i)->note()->time());
-
-               if (dt >= 0) {
-                       start_frames += snap_frame_to_frame(trackview.editor().pixel_to_frame(dt));
-               } else {
-                       start_frames -= snap_frame_to_frame(trackview.editor().pixel_to_frame(-dt));
-               }
-
-               Evoral::MusicalTime new_time = frames_to_beats(start_frames);
+               Evoral::MusicalTime new_time = frames_to_beats (beats_to_frames ((*i)->note()->time()) + dt);
 
                if (new_time < 0) {
                        continue;
@@ -1932,7 +2105,7 @@ MidiRegionView::begin_resizing (bool /*at_front*/)
 
                        // calculate color based on note velocity
                        resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
-                                       CanvasNoteEvent::meter_style_fill_color(note->note()->velocity()),
+                                CanvasNoteEvent::meter_style_fill_color(note->note()->velocity(), note->selected()),
                                        fill_color,
                                        0.85);
 
@@ -1945,9 +2118,20 @@ MidiRegionView::begin_resizing (bool /*at_front*/)
        }
 }
 
+/** Update resizing notes while user drags.
+ * @param primary `primary' note for the drag; ie the one that is used as the reference in non-relative mode.
+ * @param at_front which end of the note (true == note on, false == note off)
+ * @param delta_x change in mouse position since the start of the drag 
+ * @param relative true if relative resizing is taking place, false if absolute resizing.  This only makes
+ * a difference when multiple notes are being resized; in relative mode, each note's length is changed by the
+ * amount of the drag.  In non-relative mode, all selected notes are set to have the same start or end point
+ * as the \a primary note.
+ */
 void
-MidiRegionView::update_resizing (bool at_front, double delta_x, bool relative)
+MidiRegionView::update_resizing (ArdourCanvas::CanvasNote* primary, bool at_front, double delta_x, bool relative)
 {
+        bool cursor_set = false;
+
        for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
                SimpleRect* resize_rect = (*i)->resize_rect;
                CanvasNote* canvas_note = (*i)->canvas_note;
@@ -1957,15 +2141,13 @@ MidiRegionView::update_resizing (bool at_front, double delta_x, bool relative)
                        if (relative) {
                                current_x = canvas_note->x1() + delta_x;
                        } else {
-                               // x is in track relative, transform it to region relative
-                               current_x = delta_x - get_position_pixels();
+                               current_x = primary->x1() + delta_x;
                        }
                } else {
                        if (relative) {
                                current_x = canvas_note->x2() + delta_x;
                        } else {
-                               // x is in track relative, transform it to region relative
-                               current_x = delta_x - get_end_position_pixels ();
+                               current_x = primary->x2() + delta_x;
                        }
                }
 
@@ -1976,33 +2158,65 @@ MidiRegionView::update_resizing (bool at_front, double delta_x, bool relative)
                        resize_rect->property_x2() = snap_to_pixel(current_x);
                        resize_rect->property_x1() = canvas_note->x1();
                }
+
+                if (!cursor_set) {
+                        double beats;
+
+                        beats = snap_pixel_to_frame (current_x);
+                        beats = frames_to_beats (beats);
+                        
+                        double len;
+
+                        if (at_front) {
+                                if (beats < canvas_note->note()->end_time()) {
+                                        len = canvas_note->note()->time() - beats;
+                                        len += canvas_note->note()->length();
+                                } else {
+                                        len = 0;
+                                }
+                        } else {
+                                if (beats >= canvas_note->note()->end_time()) { 
+                                        len = beats - canvas_note->note()->time();
+                                } else {
+                                        len = 0;
+                                }
+                        }
+
+                        char buf[16];
+                        snprintf (buf, sizeof (buf), "%.3g beats", len);
+                        trackview.editor().show_verbose_canvas_cursor_with (buf);
+
+                        cursor_set = true;
+                }
+
        }
 }
 
+
+/** Finish resizing notes when the user releases the mouse button.
+ *  Parameters the same as for \a update_resizing().
+ */
 void
-MidiRegionView::commit_resizing (bool at_front, double delta_x, bool relative)
+MidiRegionView::commit_resizing (ArdourCanvas::CanvasNote* primary, bool at_front, double delta_x, bool relative)
 {
        start_diff_command(_("resize notes"));
 
        for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
                CanvasNote*  canvas_note = (*i)->canvas_note;
                SimpleRect*  resize_rect = (*i)->resize_rect;
-               const double region_start = get_position_pixels();
                double current_x;
 
                if (at_front) {
                        if (relative) {
                                current_x = canvas_note->x1() + delta_x;
                        } else {
-                               // x is in track relative, transform it to region relative
-                               current_x = region_start + delta_x;
+                               current_x = primary->x1() + delta_x;
                        }
                } else {
                        if (relative) {
                                current_x = canvas_note->x2() + delta_x;
                        } else {
-                               // x is in track relative, transform it to region relative
-                               current_x = region_start + delta_x;
+                               current_x = primary->x2() + delta_x;
                        }
                }
 
@@ -2038,6 +2252,12 @@ MidiRegionView::commit_resizing (bool at_front, double delta_x, bool relative)
        apply_diff();
 }
 
+void
+MidiRegionView::change_note_channel (CanvasNoteEvent* event, int8_t channel)
+{
+       diff_add_change (event, MidiModel::DiffCommand::Channel, (uint8_t) channel);
+}
+
 void
 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
 {
@@ -2050,6 +2270,8 @@ MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bo
                new_velocity = velocity;
        }
 
+        event->set_selected (event->selected()); // change color 
+        
        diff_add_change (event, MidiModel::DiffCommand::Velocity, new_velocity);
 }
 
@@ -2073,8 +2295,8 @@ MidiRegionView::trim_note (CanvasNoteEvent* event, Evoral::MusicalTime front_del
 {
        bool change_start = false;
        bool change_length = false;
-       Evoral::MusicalTime new_start;
-       Evoral::MusicalTime new_length;
+       Evoral::MusicalTime new_start = 0;
+       Evoral::MusicalTime new_length = 0;
 
        /* NOTE: the semantics of the two delta arguments are slightly subtle:
 
@@ -2162,6 +2384,12 @@ MidiRegionView::change_note_time (CanvasNoteEvent* event, Evoral::MusicalTime de
        diff_add_change (event, MidiModel::DiffCommand::StartTime, new_time);
 }
 
+void
+MidiRegionView::change_note_length (CanvasNoteEvent* event, Evoral::MusicalTime t)
+{
+       diff_add_change (event, MidiModel::DiffCommand::Length, t);
+}
+
 void
 MidiRegionView::change_velocities (bool up, bool fine, bool allow_smush)
 {
@@ -2199,6 +2427,13 @@ MidiRegionView::change_velocities (bool up, bool fine, bool allow_smush)
        }
 
        apply_diff();
+       
+        if (!_selection.empty()) {
+                char buf[24];
+                snprintf (buf, sizeof (buf), "Vel %d", 
+                          (int) (*_selection.begin())->note()->velocity());
+                trackview.editor().show_verbose_canvas_cursor_with (buf);
+        }
 }
 
 
@@ -2248,22 +2483,22 @@ MidiRegionView::transpose (bool up, bool fine, bool allow_smush)
 }
 
 void
-MidiRegionView::change_note_lengths (bool fine, bool shorter, bool start, bool end)
+MidiRegionView::change_note_lengths (bool fine, bool shorter, Evoral::MusicalTime delta, bool start, bool end)
 {
-       Evoral::MusicalTime delta;
-
-       if (fine) {
-               delta = 1.0/128.0;
-       } else {
-               /* grab the current grid distance */
-               bool success;
-               delta = trackview.editor().get_grid_type_as_beats (success, _region->position());
-               if (!success) {
-                       /* XXX cannot get grid type as beats ... should always be possible ... FIX ME */
-                       cerr << "Grid type not available as beats - TO BE FIXED\n";
-                       return;
-               }
-       }
+        if (delta == 0.0) {
+                if (fine) {
+                        delta = 1.0/128.0;
+                } else {
+                        /* grab the current grid distance */
+                        bool success;
+                        delta = trackview.editor().get_grid_type_as_beats (success, _region->position());
+                        if (!success) {
+                                /* XXX cannot get grid type as beats ... should always be possible ... FIX ME */
+                                cerr << "Grid type not available as beats - TO BE FIXED\n";
+                                return;
+                        }
+                }
+        }
 
        if (shorter) {
                delta = -delta;
@@ -2323,10 +2558,8 @@ MidiRegionView::nudge_notes (bool forward)
                        next_pos -= 1;
                }
 
-               cerr << "ref point was " << ref_point << " next was " << next_pos;
                trackview.editor().snap_to (next_pos, (forward ? 1 : -1), false);
                distance = ref_point - next_pos;
-               cerr << " final is " << next_pos << " distance = " << distance << endl;
        }
 
        if (distance == 0) {
@@ -2358,6 +2591,7 @@ MidiRegionView::change_channel(uint8_t channel)
        for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
                diff_add_change (*i, MidiModel::DiffCommand::Channel, channel);
        }
+
        apply_diff();
 }
 
@@ -2366,24 +2600,21 @@ void
 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
 {
        if (_mouse_state == SelectTouchDragging) {
-               note_selected(ev, true);
+               note_selected (ev, true);
        }
 
-       char buf[4];
-       snprintf (buf, sizeof (buf), "%d", (int) ev->note()->note());
-       // This causes an infinite loop on note add sometimes
-       //PublicEditor& editor (trackview.editor());
-       //editor.show_verbose_canvas_cursor_with (Evoral::midi_note_name (ev->note()->note()));
-       //editor.show_verbose_canvas_cursor_with (buf);
+       show_verbose_canvas_cursor (ev->note ());
 }
 
 void
-MidiRegionView::note_left (ArdourCanvas::CanvasNoteEvent*)
+MidiRegionView::note_left (ArdourCanvas::CanvasNoteEvent* note)
 {
-       PublicEditor& editor (trackview.editor());
-       editor.hide_verbose_canvas_cursor ();
-}
+       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
+               (*i)->hide_velocity ();
+       }
 
+       trackview.editor().hide_verbose_canvas_cursor ();
+}
 
 void
 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
@@ -2452,21 +2683,23 @@ MidiRegionView::cut_copy_clear (Editing::CutCopyOp op)
                break;
        }
 
-       start_delta_command();
-
-       for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
-               switch (op) {
-               case Copy:
-                       break;
-               case Cut:
-                       delta_remove_note (*i);
-                       break;
-               case Clear:
-                       break;
-               }
-       }
+        if (op != Copy) {
 
-       apply_delta();
+                start_diff_command();
+                
+                for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
+                        switch (op) {
+                        case Copy:
+                                break;
+                        case Cut:
+                        case Clear:
+                                diff_remove_note (*i);
+                                break;
+                        }
+                }
+                
+                apply_diff();
+        }
 }
 
 MidiCutBuffer*
@@ -2475,7 +2708,8 @@ MidiRegionView::selection_as_cut_buffer () const
        Notes notes;
 
        for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
-               notes.insert (boost::shared_ptr<NoteType> (new NoteType (*((*i)->note().get()))));
+                NoteType* n = (*i)->note().get();
+               notes.insert (boost::shared_ptr<NoteType> (new NoteType (*n)));
        }
 
        MidiCutBuffer* cb = new MidiCutBuffer (trackview.session());
@@ -2491,12 +2725,12 @@ MidiRegionView::paste (nframes64_t pos, float times, const MidiCutBuffer& mcb)
                return;
        }
 
-       start_delta_command (_("paste"));
+       start_diff_command (_("paste"));
 
        Evoral::MusicalTime beat_delta;
        Evoral::MusicalTime paste_pos_beats;
        Evoral::MusicalTime duration;
-       Evoral::MusicalTime end_point;
+       Evoral::MusicalTime end_point = 0;
 
        duration = (*mcb.notes().rbegin())->end_time() - (*mcb.notes().begin())->time();
        paste_pos_beats = frames_to_beats (pos - _region->position());
@@ -2514,7 +2748,7 @@ MidiRegionView::paste (nframes64_t pos, float times, const MidiCutBuffer& mcb)
 
                        /* make all newly added notes selected */
 
-                       delta_add_note (copied_note, true);
+                       diff_add_note (copied_note, true);
                        end_point = copied_note->end_time();
                }
 
@@ -2530,12 +2764,12 @@ MidiRegionView::paste (nframes64_t pos, float times, const MidiCutBuffer& mcb)
 
                trackview.session()->begin_reversible_command (_("paste"));
 
-               XMLNode& before (_region->get_state());
+                _region->clear_changes ();
                _region->set_length (end_frame, this);
-               trackview.session()->add_command (new MementoCommand<Region>(*_region, &before, &_region->get_state()));
+               trackview.session()->add_command (new StatefulDiffCommand (_region));
        }
 
-       apply_delta ();
+       apply_diff ();
 }
 
 struct EventNoteTimeEarlyFirstComparator {
@@ -2615,13 +2849,200 @@ MidiRegionView::goto_previous_note ()
 }
 
 void
-MidiRegionView::selection_as_notelist (Notes& selected)
+MidiRegionView::selection_as_notelist (Notes& selected, bool allow_all_if_none_selected)
 {
+        bool had_selected = false;
+
        time_sort_events ();
 
        for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
                if ((*i)->selected()) {
                        selected.insert ((*i)->note());
+                        had_selected = true;
                }
        }
+        
+        if (allow_all_if_none_selected && !had_selected) {
+                for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
+                        selected.insert ((*i)->note());
+               }
+       }
+}
+
+void
+MidiRegionView::update_ghost_note (double x, double y)
+{
+       _last_ghost_x = x;
+       _last_ghost_y = y;
+       
+       group->w2i (x, y);
+       nframes64_t f = trackview.editor().pixel_to_frame (x) + _region->position ();
+       trackview.editor().snap_to (f);
+       f -= _region->position ();
+
+       bool success;
+       Evoral::MusicalTime beats = trackview.editor().get_grid_type_as_beats (success, f);
+       if (!success) {
+               beats = 1;
+       }
+       
+       double length = frames_to_beats (snap_frame_to_frame (f + beats_to_frames (beats)) - f);
+       
+       _ghost_note->note()->set_time (frames_to_beats (f + _region->start()));
+       _ghost_note->note()->set_length (length);
+       _ghost_note->note()->set_note (midi_stream_view()->y_to_note (y));
+
+       update_note (_ghost_note);
+
+       show_verbose_canvas_cursor (_ghost_note->note ());
+}
+
+void
+MidiRegionView::create_ghost_note (double x, double y)
+{
+       delete _ghost_note;
+       _ghost_note = 0;
+
+       boost::shared_ptr<NoteType> g (new NoteType);
+       _ghost_note = new NoEventCanvasNote (*this, *group, g);
+       update_ghost_note (x, y);
+       _ghost_note->show ();
+
+       _last_ghost_x = x;
+       _last_ghost_y = y;
+
+       show_verbose_canvas_cursor (_ghost_note->note ());
+}
+
+void
+MidiRegionView::snap_changed ()
+{
+       if (!_ghost_note) {
+               return;
+       }
+       
+       create_ghost_note (_last_ghost_x, _last_ghost_y);
+}
+
+void
+MidiRegionView::show_verbose_canvas_cursor (boost::shared_ptr<NoteType> n) const
+{
+       char buf[24];
+       snprintf (buf, sizeof (buf), "%s (%d)\nVel %d", 
+                  Evoral::midi_note_name (n->note()).c_str(), 
+                  (int) n->note (),
+                  (int) n->velocity());
+       trackview.editor().show_verbose_canvas_cursor_with (buf);
+}
+
+void
+MidiRegionView::drop_down_keys ()
+{
+        _mouse_state = None;
+}
+
+void
+MidiRegionView::maybe_select_by_position (GdkEventButton* ev, double x, double y)
+{
+       double note = midi_stream_view()->y_to_note(y);
+        Events e;
+       MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
+        
+        cerr << "Selecting by position\n";
+
+       uint16_t chn_mask = mtv->channel_selector().get_selected_channels();
+
+        if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
+                get_events (e, Evoral::Sequence<Evoral::MusicalTime>::PitchGreaterThanOrEqual, (uint8_t) floor (note), chn_mask);
+        } else if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
+                get_events (e, Evoral::Sequence<Evoral::MusicalTime>::PitchLessThanOrEqual, (uint8_t) floor (note), chn_mask);
+        } else {
+                return;
+        }
+
+       bool add_mrv_selection = false;
+
+       if (_selection.empty()) {
+               add_mrv_selection = true;
+       }
+
+        for (Events::iterator i = e.begin(); i != e.end(); ++i) {
+                if (_selection.insert (*i).second) {
+                        (*i)->set_selected (true);
+                }
+       }
+
+       if (add_mrv_selection) {
+               PublicEditor& editor (trackview.editor());
+               editor.get_selection().add (this);
+       }
+}                
+
+void
+MidiRegionView::color_handler ()
+{
+        RegionView::color_handler ();
+
+       for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
+                (*i)->set_selected ((*i)->selected()); // will change color
+        }
+
+        /* XXX probably more to do here */
+}
+
+void
+MidiRegionView::enable_display (bool yn)
+{
+       RegionView::enable_display (yn);
+       if (yn) {
+               redisplay_model ();
+       }
 }
+
+void
+MidiRegionView::show_step_edit_cursor (Evoral::MusicalTime pos)
+{
+        if (_step_edit_cursor == 0) {
+                ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
+
+                _step_edit_cursor = new ArdourCanvas::SimpleRect (*group);
+                _step_edit_cursor->property_y1() = 0;
+                _step_edit_cursor->property_y2() = midi_stream_view()->contents_height();
+                _step_edit_cursor->property_fill_color_rgba() = RGBA_TO_UINT (45,0,0,90);
+                _step_edit_cursor->property_outline_color_rgba() = RGBA_TO_UINT (85,0,0,90);
+        }
+
+        move_step_edit_cursor (pos);
+        _step_edit_cursor->show ();
+}
+
+void
+MidiRegionView::move_step_edit_cursor (Evoral::MusicalTime pos)
+{
+        _step_edit_cursor_position = pos;
+
+        if (_step_edit_cursor) {
+                double pixel = trackview.editor().frame_to_pixel (beats_to_frames (pos));
+                _step_edit_cursor->property_x1() = pixel;
+                set_step_edit_cursor_width (_step_edit_cursor_width);
+        }
+}
+
+void
+MidiRegionView::hide_step_edit_cursor ()
+{
+        if (_step_edit_cursor) {
+                _step_edit_cursor->hide ();
+        }
+}
+
+void
+MidiRegionView::set_step_edit_cursor_width (Evoral::MusicalTime beats)
+{
+        _step_edit_cursor_width = beats;
+
+        if (_step_edit_cursor) {
+                _step_edit_cursor->property_x2() = _step_edit_cursor->property_x1() + trackview.editor().frame_to_pixel (beats_to_frames (beats));
+        }
+}
+