6fe9768febd2d1531cc541c60768579cf84e675e
[ardour.git] / gtk2_ardour / midi_region_view.cc
1 /*
2     Copyright (C) 2001-2011 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <cmath>
21 #include <cassert>
22 #include <algorithm>
23 #include <ostream>
24
25 #include <gtkmm.h>
26
27 #include <gtkmm2ext/gtk_ui.h>
28
29 #include <sigc++/signal.h>
30
31 #include "pbd/memento_command.h"
32 #include "pbd/stateful_diff_command.h"
33
34 #include "ardour/playlist.h"
35 #include "ardour/tempo.h"
36 #include "ardour/midi_region.h"
37 #include "ardour/midi_source.h"
38 #include "ardour/midi_model.h"
39 #include "ardour/midi_patch_manager.h"
40 #include "ardour/session.h"
41
42 #include "evoral/Parameter.hpp"
43 #include "evoral/MIDIParameters.hpp"
44 #include "evoral/Control.hpp"
45 #include "evoral/midi_util.h"
46
47 #include "automation_region_view.h"
48 #include "automation_time_axis.h"
49 #include "canvas-hit.h"
50 #include "canvas-note.h"
51 #include "canvas_patch_change.h"
52 #include "debug.h"
53 #include "editor.h"
54 #include "ghostregion.h"
55 #include "gui_thread.h"
56 #include "keyboard.h"
57 #include "midi_channel_dialog.h"
58 #include "midi_cut_buffer.h"
59 #include "midi_list_editor.h"
60 #include "midi_region_view.h"
61 #include "midi_streamview.h"
62 #include "midi_time_axis.h"
63 #include "midi_util.h"
64 #include "note_player.h"
65 #include "public_editor.h"
66 #include "rgb_macros.h"
67 #include "selection.h"
68 #include "simpleline.h"
69 #include "streamview.h"
70 #include "utils.h"
71 #include "mouse_cursors.h"
72 #include "patch_change_dialog.h"
73 #include "verbose_cursor.h"
74
75 #include "i18n.h"
76
77 using namespace ARDOUR;
78 using namespace PBD;
79 using namespace Editing;
80 using namespace ArdourCanvas;
81 using Gtkmm2ext::Keyboard;
82
83 PBD::Signal1<void, MidiRegionView *> MidiRegionView::SelectionCleared;
84
85 #define MIDI_BP_ZERO ((Config->get_first_midi_bank_is_zero())?0:1)
86
87 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
88                                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color const & basic_color)
89         : RegionView (parent, tv, r, spu, basic_color)
90         , _force_channel(-1)
91         , _last_channel_selection(0xFFFF)
92         , _current_range_min(0)
93         , _current_range_max(0)
94         , _model_name(string())
95         , _custom_device_mode(string())
96         , _active_notes(0)
97         , _note_group(new ArdourCanvas::Group(*group))
98         , _note_diff_command (0)
99         , _ghost_note(0)
100         , _drag_rect (0)
101         , _step_edit_cursor (0)
102         , _step_edit_cursor_width (1.0)
103         , _step_edit_cursor_position (0.0)
104         , _channel_selection_scoped_note (0)
105         , _temporary_note_group (0)
106         , _mouse_state(None)
107         , _pressed_button(0)
108         , _sort_needed (true)
109         , _optimization_iterator (_events.end())
110         , _list_editor (0)
111         , _no_sound_notes (false)
112         , _last_event_x (0)
113         , _last_event_y (0)
114         , _pre_enter_cursor (0)
115 {
116         _note_group->raise_to_top();
117         PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
118
119         Config->ParameterChanged.connect (*this, invalidator (*this), ui_bind (&MidiRegionView::parameter_changed, this, _1), gui_context());
120         connect_to_diskstream ();
121
122         SelectionCleared.connect (_selection_cleared_connection, invalidator (*this), ui_bind (&MidiRegionView::selection_cleared, this, _1), gui_context ());
123 }
124
125 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
126                                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color,
127                                 TimeAxisViewItem::Visibility visibility)
128         : RegionView (parent, tv, r, spu, basic_color, false, visibility)
129         , _force_channel(-1)
130         , _last_channel_selection(0xFFFF)
131         , _model_name(string())
132         , _custom_device_mode(string())
133         , _active_notes(0)
134         , _note_group(new ArdourCanvas::Group(*parent))
135         , _note_diff_command (0)
136         , _ghost_note(0)
137         , _drag_rect (0)
138         , _step_edit_cursor (0)
139         , _step_edit_cursor_width (1.0)
140         , _step_edit_cursor_position (0.0)
141         , _channel_selection_scoped_note (0)
142         , _temporary_note_group (0)
143         , _mouse_state(None)
144         , _pressed_button(0)
145         , _sort_needed (true)
146         , _optimization_iterator (_events.end())
147         , _list_editor (0)
148         , _no_sound_notes (false)
149         , _last_event_x (0)
150         , _last_event_y (0)
151 {
152         _note_group->raise_to_top();
153         PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
154
155         connect_to_diskstream ();
156
157         SelectionCleared.connect (_selection_cleared_connection, invalidator (*this), ui_bind (&MidiRegionView::selection_cleared, this, _1), gui_context ());
158 }
159
160 void
161 MidiRegionView::parameter_changed (std::string const & p)
162 {
163         if (p == "diplay-first-midi-bank-as-zero") {
164                 if (_enable_display) {
165                         redisplay_model();
166                 }
167         }
168 }
169
170 MidiRegionView::MidiRegionView (const MidiRegionView& other)
171         : sigc::trackable(other)
172         , RegionView (other)
173         , _force_channel(-1)
174         , _last_channel_selection(0xFFFF)
175         , _model_name(string())
176         , _custom_device_mode(string())
177         , _active_notes(0)
178         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
179         , _note_diff_command (0)
180         , _ghost_note(0)
181         , _drag_rect (0)
182         , _step_edit_cursor (0)
183         , _step_edit_cursor_width (1.0)
184         , _step_edit_cursor_position (0.0)
185         , _channel_selection_scoped_note (0)
186         , _temporary_note_group (0)
187         , _mouse_state(None)
188         , _pressed_button(0)
189         , _sort_needed (true)
190         , _optimization_iterator (_events.end())
191         , _list_editor (0)
192         , _no_sound_notes (false)
193         , _last_event_x (0)
194         , _last_event_y (0)
195 {
196         Gdk::Color c;
197         int r,g,b,a;
198
199         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
200         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
201
202         init (c, false);
203 }
204
205 MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<MidiRegion> region)
206         : RegionView (other, boost::shared_ptr<Region> (region))
207         , _force_channel(-1)
208         , _last_channel_selection(0xFFFF)
209         , _model_name(string())
210         , _custom_device_mode(string())
211         , _active_notes(0)
212         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
213         , _note_diff_command (0)
214         , _ghost_note(0)
215         , _drag_rect (0)
216         , _step_edit_cursor (0)
217         , _step_edit_cursor_width (1.0)
218         , _step_edit_cursor_position (0.0)
219         , _channel_selection_scoped_note (0)
220         , _temporary_note_group (0)
221         , _mouse_state(None)
222         , _pressed_button(0)
223         , _sort_needed (true)
224         , _optimization_iterator (_events.end())
225         , _list_editor (0)
226         , _no_sound_notes (false)
227         , _last_event_x (0)
228         , _last_event_y (0)
229 {
230         Gdk::Color c;
231         int r,g,b,a;
232
233         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
234         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
235
236         init (c, true);
237 }
238
239 void
240 MidiRegionView::init (Gdk::Color const & basic_color, bool wfd)
241 {
242         PublicEditor::DropDownKeys.connect (sigc::mem_fun (*this, &MidiRegionView::drop_down_keys));
243
244         CanvasNoteEvent::CanvasNoteEventDeleted.connect (note_delete_connection, MISSING_INVALIDATOR,
245                                                          ui_bind (&MidiRegionView::maybe_remove_deleted_note_from_selection, this, _1),
246                                                          gui_context());
247
248         if (wfd) {
249                 midi_region()->midi_source(0)->load_model();
250         }
251
252         _model = midi_region()->midi_source(0)->model();
253         _enable_display = false;
254
255         RegionView::init (basic_color, false);
256
257         compute_colors (basic_color);
258
259         set_height (trackview.current_height());
260
261         region_muted ();
262         region_sync_changed ();
263         region_resized (ARDOUR::bounds_change);
264         region_locked ();
265
266         reset_width_dependent_items (_pixel_width);
267
268         set_colors ();
269
270         _enable_display = true;
271         if (_model) {
272                 if (wfd) {
273                         display_model (_model);
274                 }
275         }
276
277         group->raise_to_top();
278         group->signal_event().connect(
279                 sigc::mem_fun(this, &MidiRegionView::canvas_event), false);
280
281         midi_view()->signal_channel_mode_changed().connect(
282                 sigc::mem_fun(this, &MidiRegionView::midi_channel_mode_changed));
283
284         midi_view()->signal_midi_patch_settings_changed().connect(
285                 sigc::mem_fun(this, &MidiRegionView::midi_patch_settings_changed));
286
287         trackview.editor().SnapChanged.connect(snap_changed_connection, invalidator(*this),
288                                                ui_bind(&MidiRegionView::snap_changed, this),
289                                                gui_context());
290
291         Config->ParameterChanged.connect (*this, invalidator (*this), ui_bind (&MidiRegionView::parameter_changed, this, _1), gui_context());
292         connect_to_diskstream ();
293
294         SelectionCleared.connect (_selection_cleared_connection, invalidator (*this), ui_bind (&MidiRegionView::selection_cleared, this, _1), gui_context ());
295 }
296
297 void
298 MidiRegionView::connect_to_diskstream ()
299 {
300         midi_view()->midi_track()->DataRecorded.connect(
301                 *this, invalidator(*this),
302                 ui_bind(&MidiRegionView::data_recorded, this, _1, _2),
303                 gui_context());
304 }
305
306 bool
307 MidiRegionView::canvas_event(GdkEvent* ev)
308 {
309         switch (ev->type) {
310         case GDK_ENTER_NOTIFY:
311         case GDK_LEAVE_NOTIFY:
312                 _last_event_x = ev->crossing.x;
313                 _last_event_y = ev->crossing.y;
314                 break;
315         case GDK_MOTION_NOTIFY:
316                 _last_event_x = ev->motion.x;
317                 _last_event_y = ev->motion.y;
318                 break;
319         default:
320                 break;
321         }
322
323         if (!trackview.editor().internal_editing()) {
324                 return false;
325         }
326
327         switch (ev->type) {
328         case GDK_SCROLL:
329                 return scroll (&ev->scroll);
330
331         case GDK_KEY_PRESS:
332                 return key_press (&ev->key);
333
334         case GDK_KEY_RELEASE:
335                 return key_release (&ev->key);
336
337         case GDK_BUTTON_PRESS:
338                 return button_press (&ev->button);
339
340         case GDK_2BUTTON_PRESS:
341                 return true;
342
343         case GDK_BUTTON_RELEASE:
344                 return button_release (&ev->button);
345
346         case GDK_ENTER_NOTIFY:
347                 return enter_notify (&ev->crossing);
348
349         case GDK_LEAVE_NOTIFY:
350                 return leave_notify (&ev->crossing);
351
352         case GDK_MOTION_NOTIFY:
353                 return motion (&ev->motion);
354
355         default:
356                 break;
357         }
358
359         return false;
360 }
361
362 void
363 MidiRegionView::remove_ghost_note ()
364 {
365         delete _ghost_note;
366         _ghost_note = 0;
367 }
368
369 bool
370 MidiRegionView::enter_notify (GdkEventCrossing* ev)
371 {
372         trackview.editor().MouseModeChanged.connect (
373                 _mouse_mode_connection, invalidator (*this), ui_bind (&MidiRegionView::mouse_mode_changed, this), gui_context ()
374                 );
375
376         if (trackview.editor().current_mouse_mode() == MouseRange) {
377                 create_ghost_note (ev->x, ev->y);
378         }
379
380         if (!trackview.editor().internal_editing()) {
381                 Keyboard::magic_widget_drop_focus();
382         } else {
383                 Keyboard::magic_widget_grab_focus();
384                 group->grab_focus();
385         }
386
387         return false;
388 }
389
390 bool
391 MidiRegionView::leave_notify (GdkEventCrossing* ev)
392 {
393         _mouse_mode_connection.disconnect ();
394
395         trackview.editor().verbose_cursor()->hide ();
396         remove_ghost_note ();
397
398         return false;
399 }
400
401 void
402 MidiRegionView::mouse_mode_changed ()
403 {
404         if (trackview.editor().current_mouse_mode() == MouseRange && trackview.editor().internal_editing()) {
405                 create_ghost_note (_last_event_x, _last_event_y);
406         } else {
407                 remove_ghost_note ();
408                 trackview.editor().verbose_cursor()->hide ();
409         }
410
411         if (!trackview.editor().internal_editing()) {
412                 Keyboard::magic_widget_drop_focus();
413         } else {
414                 Keyboard::magic_widget_grab_focus();
415                 group->grab_focus();
416         }
417 }
418
419 bool
420 MidiRegionView::button_press (GdkEventButton* ev)
421 {
422         if (ev->button != 1) {
423                 return false;
424         }
425
426         _last_x = ev->x;
427         _last_y = ev->y;
428
429         group->w2i (_last_x, _last_y);
430
431         if (_mouse_state != SelectTouchDragging) {
432
433                 _pressed_button = ev->button;
434                 _mouse_state = Pressed;
435
436                 return true;
437         }
438
439         _pressed_button = ev->button;
440
441         return true;
442 }
443
444 bool
445 MidiRegionView::button_release (GdkEventButton* ev)
446 {
447         double event_x, event_y;
448
449         if (ev->button != 1) {
450                 return false;
451         }
452
453         event_x = ev->x;
454         event_y = ev->y;
455
456         group->w2i(event_x, event_y);
457         group->ungrab(ev->time);
458
459         switch (_mouse_state) {
460         case Pressed: // Clicked
461
462                 switch (trackview.editor().current_mouse_mode()) {
463                 case MouseObject:
464                 case MouseTimeFX:
465                         {
466                                 clear_selection();
467
468                                 if (Keyboard::is_insert_note_event(ev)) {
469
470                                         double event_x, event_y;
471
472                                         event_x = ev->x;
473                                         event_y = ev->y;
474                                         group->w2i(event_x, event_y);
475
476                                         bool success;
477                                         Evoral::MusicalTime beats = trackview.editor().get_grid_type_as_beats (success, trackview.editor().pixel_to_frame (event_x));
478
479                                         if (!success) {
480                                                 beats = 1;
481                                         }
482
483                                         create_note_at (event_x, event_y, beats, true, true);
484                                 }
485
486                                 break;
487                         }
488                 case MouseRange:
489                         {
490                                 bool success;
491                                 Evoral::MusicalTime beats = trackview.editor().get_grid_type_as_beats (success, trackview.editor().pixel_to_frame (event_x));
492
493                                 if (!success) {
494                                         beats = 1;
495                                 }
496
497                                 create_note_at (event_x, event_y, beats, true, true);
498
499                                 break;
500                         }
501                 default:
502                         break;
503                 }
504
505                 _mouse_state = None;
506                 break;
507
508         case SelectRectDragging: // Select drag done
509
510                 _mouse_state = None;
511                 delete _drag_rect;
512                 _drag_rect = 0;
513                 break;
514
515         case AddDragging: // Add drag done
516
517                 _mouse_state = None;
518
519                 if (Keyboard::is_insert_note_event(ev) || trackview.editor().current_mouse_mode() == MouseRange) {
520
521                         if (_drag_rect->property_x2() > _drag_rect->property_x1() + 2) {
522
523                                 const double x  = _drag_rect->property_x1();
524                                 const double length = trackview.editor().pixel_to_frame (_drag_rect->property_x2() - _drag_rect->property_x1());
525
526                                 create_note_at (x, _drag_rect->property_y1(), region_frames_to_region_beats(length), true, false);
527                         }
528                 }
529
530                 delete _drag_rect;
531                 _drag_rect = 0;
532
533                 create_ghost_note (ev->x, ev->y);
534
535         default:
536                 break;
537         }
538
539         return false;
540 }
541
542 bool
543 MidiRegionView::motion (GdkEventMotion* ev)
544 {
545         double event_x, event_y;
546         framepos_t event_frame = 0;
547
548         event_x = ev->x;
549         event_y = ev->y;
550         group->w2i(event_x, event_y);
551
552         PublicEditor& editor = trackview.editor ();
553         
554         // convert event_x to global frame
555         framecnt_t grid_frames;
556         event_frame = snap_frame_to_grid_underneath (editor.pixel_to_frame (event_x), grid_frames);
557
558         if (!_ghost_note && editor.current_mouse_mode() != MouseRange
559             && Keyboard::modifier_state_contains (ev->state, Keyboard::insert_note_modifier())
560             && _mouse_state != AddDragging) {
561
562                 create_ghost_note (ev->x, ev->y);
563         } else if (_ghost_note && editor.current_mouse_mode() != MouseRange
564                    && Keyboard::modifier_state_contains (ev->state, Keyboard::insert_note_modifier())) {
565
566                 update_ghost_note (ev->x, ev->y);
567         } else if (_ghost_note && editor.current_mouse_mode() != MouseRange) {
568
569                 delete _ghost_note;
570                 _ghost_note = 0;
571
572                 editor.verbose_cursor()->hide ();
573         } else if (_ghost_note && editor.current_mouse_mode() == MouseRange) {
574                 update_ghost_note (ev->x, ev->y);
575         }
576
577         /* any motion immediately hides velocity text that may have been visible */
578
579         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
580                 (*i)->hide_velocity ();
581         }
582
583         switch (_mouse_state) {
584         case Pressed: // Maybe start a drag, if we've moved a bit
585
586                 if (fabs (event_x - _last_x) < 1 && fabs (event_y - _last_y) < 1) {
587                         /* no appreciable movement since the button was pressed */
588                         return false;
589                 }
590
591                 if (_pressed_button == 1 && editor.current_mouse_mode() == MouseObject
592                     && !Keyboard::modifier_state_contains (ev->state, Keyboard::insert_note_modifier())) {
593                         // Select drag start
594
595                         group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
596                                     Gdk::Cursor(Gdk::FLEUR), ev->time);
597
598                         _last_x = event_x;
599                         _last_y = event_y;
600                         _drag_start_x = event_x;
601                         _drag_start_y = event_y;
602
603                         _drag_rect = new ArdourCanvas::SimpleRect(*group);
604                         _drag_rect->property_x1() = event_x;
605                         _drag_rect->property_y1() = event_y;
606                         _drag_rect->property_x2() = event_x;
607                         _drag_rect->property_y2() = event_y;
608                         _drag_rect->property_outline_what() = 0xFF;
609                         _drag_rect->property_outline_color_rgba()
610                                 = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
611                         _drag_rect->property_fill_color_rgba()
612                                 = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
613
614                         _mouse_state = SelectRectDragging;
615                         return true;
616
617                 } else if (editor.internal_editing()) {
618                         // Add note drag start
619
620                         group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
621                                     Gdk::Cursor(Gdk::FLEUR), ev->time);
622
623                         _last_x = event_x;
624                         _last_y = event_y;
625                         _drag_start_x = event_x;
626                         _drag_start_y = event_y;
627
628                         _drag_rect = new ArdourCanvas::SimpleRect(*group);
629                         _drag_rect->property_x1() = editor.frame_to_pixel(event_frame);
630
631                         _drag_rect->property_y1() = midi_stream_view()->note_to_y(
632                                 midi_stream_view()->y_to_note(event_y));
633                         _drag_rect->property_x2() = editor.frame_to_pixel(event_frame);
634                         
635                         _drag_rect->property_y2() = _drag_rect->property_y1()
636                                 + floor(midi_stream_view()->note_height());
637                         _drag_rect->property_outline_what() = 0xFF;
638                         _drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
639                         _drag_rect->property_fill_color_rgba()    = 0xFFFFFF66;
640
641                         _mouse_state = AddDragging;
642                         
643                         delete _ghost_note;
644                         _ghost_note = 0;
645
646                         editor.verbose_cursor()->hide ();
647
648                         return true;
649                 }
650
651                 return false;
652
653         case SelectRectDragging: // Select drag motion
654         case AddDragging: // Add note drag motion
655
656                 if (ev->is_hint) {
657                         int t_x;
658                         int t_y;
659                         GdkModifierType state;
660                         gdk_window_get_pointer(ev->window, &t_x, &t_y, &state);
661                         event_x = t_x;
662                         event_y = t_y;
663                 }
664
665                 if (_mouse_state == AddDragging) {
666                         event_x = editor.frame_to_pixel(event_frame);
667
668                         if (editor.snap_mode() == SnapNormal) {
669                                 /* event_frame will have been snapped to the start of the note we are under;
670                                    it's more intuitive if we use the end of that note here
671                                 */
672                                 event_x = editor.frame_to_pixel (event_frame + grid_frames);
673                         } else {
674                                 event_x = editor.frame_to_pixel (event_frame);
675                         }
676                         
677                 }
678
679                 if (_drag_rect) {
680
681                         if (event_x > _drag_start_x) {
682                                 _drag_rect->property_x2() = event_x;
683                         }
684                         else {
685                                 _drag_rect->property_x1() = event_x;
686                         }
687                 }
688
689                 if (_drag_rect && _mouse_state == SelectRectDragging) {
690
691                         if (event_y > _drag_start_y) {
692                                 _drag_rect->property_y2() = event_y;
693                         }
694                         else {
695                                 _drag_rect->property_y1() = event_y;
696                         }
697
698                         update_drag_selection(_drag_start_x, event_x, _drag_start_y, event_y, Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier));
699                 }
700
701                 _last_x = event_x;
702                 _last_y = event_y;
703
704         case SelectTouchDragging:
705                 return false;
706
707         default:
708                 break;
709         }
710
711         return false;
712 }
713
714
715 bool
716 MidiRegionView::scroll (GdkEventScroll* ev)
717 {
718         if (_selection.empty()) {
719                 return false;
720         }
721
722         trackview.editor().verbose_cursor()->hide ();
723
724         bool fine = !Keyboard::modifier_state_equals (ev->state, Keyboard::SecondaryModifier);
725
726         if (ev->direction == GDK_SCROLL_UP) {
727                 change_velocities (true, fine, false);
728         } else if (ev->direction == GDK_SCROLL_DOWN) {
729                 change_velocities (false, fine, false);
730         }
731         return true;
732 }
733
734 bool
735 MidiRegionView::key_press (GdkEventKey* ev)
736 {
737         /* since GTK bindings are generally activated on press, and since
738            detectable auto-repeat is the name of the game and only sends
739            repeated presses, carry out key actions at key press, not release.
740         */
741
742         bool unmodified = Keyboard::no_modifier_keys_pressed (ev);
743         
744         if (unmodified && (ev->keyval == GDK_Alt_L || ev->keyval == GDK_Alt_R)) {
745                 _mouse_state = SelectTouchDragging;
746                 return true;
747
748         } else if (ev->keyval == GDK_Escape && unmodified) {
749                 clear_selection();
750                 _mouse_state = None;
751
752         } else if (unmodified && (ev->keyval == GDK_comma || ev->keyval == GDK_period)) {
753
754                 bool start = (ev->keyval == GDK_comma);
755                 bool end = (ev->keyval == GDK_period);
756                 bool shorter = Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier);
757                 bool fine = Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
758
759                 change_note_lengths (fine, shorter, 0.0, start, end);
760
761                 return true;
762
763         } else if (ev->keyval == GDK_Delete && unmodified) {
764
765                 delete_selection();
766                 return true;
767
768         } else if (ev->keyval == GDK_Tab) {
769
770                 if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
771                         goto_previous_note (Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier));
772                 } else {
773                         goto_next_note (Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier));
774                 }
775                 return true;
776
777         } else if (ev->keyval == GDK_ISO_Left_Tab) {
778
779                 /* Shift-TAB generates ISO Left Tab, for some reason */
780
781                 if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
782                         goto_previous_note (Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier));
783                 } else {
784                         goto_next_note (Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier));
785                 }
786                 return true;
787
788
789
790         } else if (ev->keyval == GDK_Up) {
791
792                 bool allow_smush = Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier);
793                 bool fine = !Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
794
795                 if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
796                         change_velocities (true, fine, allow_smush);
797                 } else {
798                         transpose (true, fine, allow_smush);
799                 }
800                 return true;
801
802         } else if (ev->keyval == GDK_Down) {
803
804                 bool allow_smush = Keyboard::modifier_state_contains (ev->state, Keyboard::TertiaryModifier);
805                 bool fine = !Keyboard::modifier_state_contains (ev->state, Keyboard::SecondaryModifier);
806
807                 if (Keyboard::modifier_state_contains (ev->state, Keyboard::PrimaryModifier)) {
808                         change_velocities (false, fine, allow_smush);
809                 } else {
810                         transpose (false, fine, allow_smush);
811                 }
812                 return true;
813
814         } else if (ev->keyval == GDK_Left && unmodified) {
815
816                 nudge_notes (false);
817                 return true;
818
819         } else if (ev->keyval == GDK_Right && unmodified) {
820
821                 nudge_notes (true);
822                 return true;
823
824         } else if (ev->keyval == GDK_c && unmodified) {
825                 channel_edit ();
826                 return true;
827         }
828
829         return false;
830 }
831
832 bool
833 MidiRegionView::key_release (GdkEventKey* ev)
834 {
835         if ((_mouse_state == SelectTouchDragging) && (ev->keyval == GDK_Alt_L || ev->keyval == GDK_Alt_R)) {
836                 _mouse_state = None;
837                 return true;
838         }
839         return false;
840 }
841
842 void
843 MidiRegionView::channel_edit ()
844 {
845         bool first = true;
846         uint8_t current_channel;
847
848         if (_selection.empty()) {
849                 return;
850         }
851         
852         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
853                 if (first) {
854                         current_channel = (*i)->note()->channel ();
855                         first = false;
856                 }
857         }
858
859         MidiChannelDialog channel_dialog (current_channel);
860         int ret = channel_dialog.run ();
861
862         switch (ret) {
863         case Gtk::RESPONSE_OK:
864                 break;
865         default:
866                 return;
867         }
868
869         uint8_t new_channel = channel_dialog.active_channel ();
870
871         start_note_diff_command (_("channel edit"));
872
873         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
874                 Selection::iterator next = i;
875                 ++next;
876                 change_note_channel (*i, new_channel);
877                 i = next;
878         }
879
880         apply_diff ();
881 }
882
883 void
884 MidiRegionView::show_list_editor ()
885 {
886         if (!_list_editor) {
887                 _list_editor = new MidiListEditor (trackview.session(), midi_region());
888         }
889         _list_editor->present ();
890 }
891
892 /** Add a note to the model, and the view, at a canvas (click) coordinate.
893  * \param x horizontal position in pixels
894  * \param y vertical position in pixels
895  * \param length duration of the note in beats, which will be snapped to the grid
896  * \param sh true to make the note 1 frame shorter than the snapped version of \a length.
897  * \param snap_x true to snap x to the grid, otherwise false.
898  */
899 void
900 MidiRegionView::create_note_at (double x, double y, double length, bool sh, bool snap_x)
901 {
902         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
903         MidiStreamView* const view = mtv->midi_view();
904
905         double note = view->y_to_note(y);
906
907         assert(note >= 0.0);
908         assert(note <= 127.0);
909
910         // Start of note in frames relative to region start
911         framepos_t start_frames = trackview.editor().pixel_to_frame (x);
912         if (snap_x) {
913                 framecnt_t grid_frames;
914                 start_frames = snap_frame_to_grid_underneath (start_frames, grid_frames);
915         }
916         assert(start_frames >= 0);
917
918         // Snap length
919         length = region_frames_to_region_beats(
920                 snap_frame_to_frame (start_frames + region_beats_to_region_frames(length)) - start_frames);
921
922         assert (length != 0);
923
924         if (sh) {
925                 length = region_frames_to_region_beats (region_beats_to_region_frames (length) - 1);
926         }
927
928         const boost::shared_ptr<NoteType> new_note (new NoteType (mtv->get_channel_for_add (),
929                                                                   region_frames_to_region_beats(start_frames + _region->start()), length,
930                                                                   (uint8_t)note, 0x40));
931
932         if (_model->contains (new_note)) {
933                 return;
934         }
935
936         view->update_note_range(new_note->note());
937
938         MidiModel::NoteDiffCommand* cmd = _model->new_note_diff_command("add note");
939         cmd->add (new_note);
940         _model->apply_command(*trackview.session(), cmd);
941
942         play_midi_note (new_note);
943 }
944
945 void
946 MidiRegionView::clear_events()
947 {
948         clear_selection();
949
950         MidiGhostRegion* gr;
951         for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
952                 if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
953                         gr->clear_events();
954                 }
955         }
956
957         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
958                 delete *i;
959         }
960
961         _events.clear();
962         _patch_changes.clear();
963         _sys_exes.clear();
964         _optimization_iterator = _events.end();
965 }
966
967 void
968 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
969 {
970         _model = model;
971
972         content_connection.disconnect ();
973         _model->ContentsChanged.connect (content_connection, invalidator (*this), boost::bind (&MidiRegionView::redisplay_model, this), gui_context());
974
975         clear_events ();
976
977         if (_enable_display) {
978                 redisplay_model();
979         }
980 }
981
982 void
983 MidiRegionView::start_note_diff_command (string name)
984 {
985         if (!_note_diff_command) {
986                 _note_diff_command = _model->new_note_diff_command (name);
987         }
988 }
989
990 void
991 MidiRegionView::note_diff_add_note (const boost::shared_ptr<NoteType> note, bool selected, bool show_velocity)
992 {
993         if (_note_diff_command) {
994                 _note_diff_command->add (note);
995         }
996         if (selected) {
997                 _marked_for_selection.insert(note);
998         }
999         if (show_velocity) {
1000                 _marked_for_velocity.insert(note);
1001         }
1002 }
1003
1004 void
1005 MidiRegionView::note_diff_remove_note (ArdourCanvas::CanvasNoteEvent* ev)
1006 {
1007         if (_note_diff_command && ev->note()) {
1008                 _note_diff_command->remove(ev->note());
1009         }
1010 }
1011
1012 void
1013 MidiRegionView::note_diff_add_change (ArdourCanvas::CanvasNoteEvent* ev,
1014                                       MidiModel::NoteDiffCommand::Property property,
1015                                       uint8_t val)
1016 {
1017         if (_note_diff_command) {
1018                 _note_diff_command->change (ev->note(), property, val);
1019         }
1020 }
1021
1022 void
1023 MidiRegionView::note_diff_add_change (ArdourCanvas::CanvasNoteEvent* ev,
1024                                       MidiModel::NoteDiffCommand::Property property,
1025                                       Evoral::MusicalTime val)
1026 {
1027         if (_note_diff_command) {
1028                 _note_diff_command->change (ev->note(), property, val);
1029         }
1030 }
1031
1032 void
1033 MidiRegionView::apply_diff (bool as_subcommand)
1034 {
1035         bool add_or_remove;
1036
1037         if (!_note_diff_command) {
1038                 return;
1039         }
1040
1041         if ((add_or_remove = _note_diff_command->adds_or_removes())) {
1042                 // Mark all selected notes for selection when model reloads
1043                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1044                         _marked_for_selection.insert((*i)->note());
1045                 }
1046         }
1047
1048         if (as_subcommand) {
1049                 _model->apply_command_as_subcommand (*trackview.session(), _note_diff_command);
1050         } else {
1051                 _model->apply_command (*trackview.session(), _note_diff_command);
1052         }
1053
1054         _note_diff_command = 0;
1055         midi_view()->midi_track()->playlist_modified();
1056
1057         if (add_or_remove) {
1058                 _marked_for_selection.clear();
1059         }
1060
1061         _marked_for_velocity.clear();
1062 }
1063
1064 void
1065 MidiRegionView::abort_command()
1066 {
1067         delete _note_diff_command;
1068         _note_diff_command = 0;
1069         clear_selection();
1070 }
1071
1072 CanvasNoteEvent*
1073 MidiRegionView::find_canvas_note (boost::shared_ptr<NoteType> note)
1074 {
1075         if (_optimization_iterator != _events.end()) {
1076                 ++_optimization_iterator;
1077         }
1078
1079         if (_optimization_iterator != _events.end() && (*_optimization_iterator)->note() == note) {
1080                 return *_optimization_iterator;
1081         }
1082
1083         for (_optimization_iterator = _events.begin(); _optimization_iterator != _events.end(); ++_optimization_iterator) {
1084                 if ((*_optimization_iterator)->note() == note) {
1085                         return *_optimization_iterator;
1086                 }
1087         }
1088
1089         return 0;
1090 }
1091
1092 void
1093 MidiRegionView::get_events (Events& e, Evoral::Sequence<Evoral::MusicalTime>::NoteOperator op, uint8_t val, int chan_mask)
1094 {
1095         MidiModel::Notes notes;
1096         _model->get_notes (notes, op, val, chan_mask);
1097
1098         for (MidiModel::Notes::iterator n = notes.begin(); n != notes.end(); ++n) {
1099                 CanvasNoteEvent* cne = find_canvas_note (*n);
1100                 if (cne) {
1101                         e.push_back (cne);
1102                 }
1103         }
1104 }
1105
1106 void
1107 MidiRegionView::redisplay_model()
1108 {
1109         // Don't redisplay the model if we're currently recording and displaying that
1110         if (_active_notes) {
1111                 return;
1112         }
1113
1114         if (!_model) {
1115                 return;
1116         }
1117
1118         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1119                 (*i)->invalidate ();
1120         }
1121
1122         MidiModel::ReadLock lock(_model->read_lock());
1123
1124         MidiModel::Notes& notes (_model->notes());
1125         _optimization_iterator = _events.begin();
1126
1127         for (MidiModel::Notes::iterator n = notes.begin(); n != notes.end(); ++n) {
1128
1129                 boost::shared_ptr<NoteType> note (*n);
1130                 CanvasNoteEvent* cne;
1131                 bool visible;
1132
1133                 if (note_in_region_range (note, visible)) {
1134
1135                         if ((cne = find_canvas_note (note)) != 0) {
1136
1137                                 cne->validate ();
1138
1139                                 CanvasNote* cn;
1140                                 CanvasHit* ch;
1141
1142                                 if ((cn = dynamic_cast<CanvasNote*>(cne)) != 0) {
1143                                         update_note (cn);
1144                                 } else if ((ch = dynamic_cast<CanvasHit*>(cne)) != 0) {
1145                                         update_hit (ch);
1146                                 }
1147
1148                                 if (visible) {
1149                                         cne->show ();
1150                                 } else {
1151                                         cne->hide ();
1152                                 }
1153
1154                         } else {
1155
1156                                 add_note (note, visible);
1157                         }
1158
1159                 } else {
1160
1161                         if ((cne = find_canvas_note (note)) != 0) {
1162                                 cne->validate ();
1163                                 cne->hide ();
1164                         }
1165                 }
1166         }
1167
1168
1169         /* remove note items that are no longer valid */
1170
1171         for (Events::iterator i = _events.begin(); i != _events.end(); ) {
1172                 if (!(*i)->valid ()) {
1173                         delete *i;
1174                         i = _events.erase (i);
1175                 } else {
1176                         ++i;
1177                 }
1178         }
1179
1180         _patch_changes.clear();
1181         _sys_exes.clear();
1182
1183         display_sysexes();
1184         display_patch_changes ();
1185
1186         _marked_for_selection.clear ();
1187         _marked_for_velocity.clear ();
1188
1189         /* we may have caused _events to contain things out of order (e.g. if a note
1190            moved earlier or later). we don't generally need them in time order, but
1191            make a note that a sort is required for those cases that require it.
1192         */
1193
1194         _sort_needed = true;
1195 }
1196
1197 void
1198 MidiRegionView::display_patch_changes ()
1199 {
1200         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
1201         uint16_t chn_mask = mtv->channel_selector().get_selected_channels();
1202
1203         for (uint8_t i = 0; i < 16; ++i) {
1204                 if (chn_mask & (1<<i)) {
1205                         display_patch_changes_on_channel (i);
1206                 }
1207                 /* TODO gray-out patch instad of not displaying it */
1208         }
1209 }
1210
1211 void
1212 MidiRegionView::display_patch_changes_on_channel (uint8_t channel)
1213 {
1214         for (MidiModel::PatchChanges::const_iterator i = _model->patch_changes().begin(); i != _model->patch_changes().end(); ++i) {
1215
1216                 if ((*i)->channel() != channel) {
1217                         continue;
1218                 }
1219
1220                 MIDI::Name::PatchPrimaryKey patch_key ((*i)->bank_msb (), (*i)->bank_lsb (), (*i)->program ());
1221
1222                 boost::shared_ptr<MIDI::Name::Patch> patch =
1223                         MIDI::Name::MidiPatchManager::instance().find_patch(
1224                                 _model_name, _custom_device_mode, channel, patch_key);
1225
1226                 if (patch != 0) {
1227                         add_canvas_patch_change (*i, patch->name());
1228                 } else {
1229                         char buf[16];
1230                         /* program and bank numbers are zero-based: convert to one-based: MIDI_BP_ZERO */
1231                         snprintf (buf, 16, "%d %d", (*i)->program() + MIDI_BP_ZERO , (*i)->bank() + MIDI_BP_ZERO);
1232                         add_canvas_patch_change (*i, buf);
1233                 }
1234         }
1235 }
1236
1237 void
1238 MidiRegionView::display_sysexes()
1239 {
1240         for (MidiModel::SysExes::const_iterator i = _model->sysexes().begin(); i != _model->sysexes().end(); ++i) {
1241                 Evoral::MusicalTime time = (*i)->time();
1242                 assert(time >= 0);
1243
1244                 ostringstream str;
1245                 str << hex;
1246                 for (uint32_t b = 0; b < (*i)->size(); ++b) {
1247                         str << int((*i)->buffer()[b]);
1248                         if (b != (*i)->size() -1) {
1249                                 str << " ";
1250                         }
1251                 }
1252                 string text = str.str();
1253
1254                 const double x = trackview.editor().frame_to_pixel(source_beats_to_absolute_frames(time));
1255
1256                 double height = midi_stream_view()->contents_height();
1257
1258                 boost::shared_ptr<CanvasSysEx> sysex = boost::shared_ptr<CanvasSysEx>(
1259                         new CanvasSysEx(*this, *_note_group, text, height, x, 1.0));
1260
1261                 // Show unless patch change is beyond the region bounds
1262                 if (time - _region->start() >= _region->length() || time < _region->start()) {
1263                         sysex->hide();
1264                 } else {
1265                         sysex->show();
1266                 }
1267
1268                 _sys_exes.push_back(sysex);
1269         }
1270 }
1271
1272
1273 MidiRegionView::~MidiRegionView ()
1274 {
1275         in_destructor = true;
1276
1277         trackview.editor().verbose_cursor()->hide ();
1278
1279         note_delete_connection.disconnect ();
1280
1281         delete _list_editor;
1282
1283         RegionViewGoingAway (this); /* EMIT_SIGNAL */
1284
1285         if (_active_notes) {
1286                 end_write();
1287         }
1288
1289         _selection.clear();
1290         clear_events();
1291
1292         delete _note_group;
1293         delete _note_diff_command;
1294         delete _step_edit_cursor;
1295         delete _temporary_note_group;
1296 }
1297
1298 void
1299 MidiRegionView::region_resized (const PropertyChange& what_changed)
1300 {
1301         RegionView::region_resized(what_changed);
1302
1303         if (what_changed.contains (ARDOUR::Properties::position)) {
1304                 set_duration(_region->length(), 0);
1305                 if (_enable_display) {
1306                         redisplay_model();
1307                 }
1308         }
1309 }
1310
1311 void
1312 MidiRegionView::reset_width_dependent_items (double pixel_width)
1313 {
1314         RegionView::reset_width_dependent_items(pixel_width);
1315         assert(_pixel_width == pixel_width);
1316
1317         if (_enable_display) {
1318                 redisplay_model();
1319         }
1320
1321         move_step_edit_cursor (_step_edit_cursor_position);
1322         set_step_edit_cursor_width (_step_edit_cursor_width);
1323 }
1324
1325 void
1326 MidiRegionView::set_height (double height)
1327 {
1328         static const double FUDGE = 2.0;
1329         const double old_height = _height;
1330         RegionView::set_height(height);
1331         _height = height - FUDGE;
1332
1333         apply_note_range(midi_stream_view()->lowest_note(),
1334                          midi_stream_view()->highest_note(),
1335                          height != old_height + FUDGE);
1336
1337         if (name_pixbuf) {
1338                 name_pixbuf->raise_to_top();
1339         }
1340
1341         for (PatchChanges::iterator x = _patch_changes.begin(); x != _patch_changes.end(); ++x) {
1342                 (*x)->set_height (midi_stream_view()->contents_height());
1343         }
1344
1345         if (_step_edit_cursor) {
1346                 _step_edit_cursor->property_y2() = midi_stream_view()->contents_height();
1347         }
1348 }
1349
1350
1351 /** Apply the current note range from the stream view
1352  * by repositioning/hiding notes as necessary
1353  */
1354 void
1355 MidiRegionView::apply_note_range (uint8_t min, uint8_t max, bool force)
1356 {
1357         if (!_enable_display) {
1358                 return;
1359         }
1360
1361         if (!force && _current_range_min == min && _current_range_max == max) {
1362                 return;
1363         }
1364
1365         _current_range_min = min;
1366         _current_range_max = max;
1367
1368         for (Events::const_iterator i = _events.begin(); i != _events.end(); ++i) {
1369                 CanvasNoteEvent* event = *i;
1370                 boost::shared_ptr<NoteType> note (event->note());
1371
1372                 if (note->note() < _current_range_min ||
1373                     note->note() > _current_range_max) {
1374                         event->hide();
1375                 } else {
1376                         event->show();
1377                 }
1378
1379                 if (CanvasNote* cnote = dynamic_cast<CanvasNote*>(event)) {
1380
1381                         const double y1 = midi_stream_view()->note_to_y(note->note());
1382                         const double y2 = y1 + floor(midi_stream_view()->note_height());
1383
1384                         cnote->property_y1() = y1;
1385                         cnote->property_y2() = y2;
1386
1387                 } else if (CanvasHit* chit = dynamic_cast<CanvasHit*>(event)) {
1388
1389                         const double diamond_size = update_hit (chit);
1390
1391                         chit->set_height (diamond_size);
1392                 }
1393         }
1394 }
1395
1396 GhostRegion*
1397 MidiRegionView::add_ghost (TimeAxisView& tv)
1398 {
1399         CanvasNote* note;
1400
1401         double unit_position = _region->position () / samples_per_unit;
1402         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
1403         MidiGhostRegion* ghost;
1404
1405         if (mtv && mtv->midi_view()) {
1406                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group
1407                    to allow having midi notes on top of note lines and waveforms.
1408                 */
1409                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
1410         } else {
1411                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
1412         }
1413
1414         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1415                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
1416                         ghost->add_note(note);
1417                 }
1418         }
1419
1420         ghost->set_height ();
1421         ghost->set_duration (_region->length() / samples_per_unit);
1422         ghosts.push_back (ghost);
1423
1424         GhostRegion::CatchDeletion.connect (*this, invalidator (*this), ui_bind (&RegionView::remove_ghost, this, _1), gui_context());
1425
1426         return ghost;
1427 }
1428
1429
1430 /** Begin tracking note state for successive calls to add_event
1431  */
1432 void
1433 MidiRegionView::begin_write()
1434 {
1435         assert(!_active_notes);
1436         _active_notes = new CanvasNote*[128];
1437         for (unsigned i=0; i < 128; ++i) {
1438                 _active_notes[i] = 0;
1439         }
1440 }
1441
1442
1443 /** Destroy note state for add_event
1444  */
1445 void
1446 MidiRegionView::end_write()
1447 {
1448         delete[] _active_notes;
1449         _active_notes = 0;
1450         _marked_for_selection.clear();
1451         _marked_for_velocity.clear();
1452 }
1453
1454
1455 /** Resolve an active MIDI note (while recording).
1456  */
1457 void
1458 MidiRegionView::resolve_note(uint8_t note, double end_time)
1459 {
1460         if (midi_view()->note_mode() != Sustained) {
1461                 return;
1462         }
1463
1464         if (_active_notes && _active_notes[note]) {
1465
1466                 /* XXX is end_time really region-centric? I think so, because
1467                    this is a new region that we're recording, so source zero is
1468                    the same as region zero
1469                 */
1470                 const framepos_t end_time_frames = region_beats_to_region_frames(end_time);
1471
1472                 _active_notes[note]->property_x2() = trackview.editor().frame_to_pixel(end_time_frames);
1473                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
1474                 _active_notes[note] = 0;
1475         }
1476 }
1477
1478
1479 /** Extend active notes to rightmost edge of region (if length is changed)
1480  */
1481 void
1482 MidiRegionView::extend_active_notes()
1483 {
1484         if (!_active_notes) {
1485                 return;
1486         }
1487
1488         for (unsigned i=0; i < 128; ++i) {
1489                 if (_active_notes[i]) {
1490                         _active_notes[i]->property_x2() = trackview.editor().frame_to_pixel(_region->length());
1491                 }
1492         }
1493 }
1494
1495
1496 void
1497 MidiRegionView::play_midi_note(boost::shared_ptr<NoteType> note)
1498 {
1499         if (_no_sound_notes || !trackview.editor().sound_notes()) {
1500                 return;
1501         }
1502
1503         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
1504
1505         if (!route_ui || !route_ui->midi_track()) {
1506                 return;
1507         }
1508
1509         NotePlayer* np = new NotePlayer (route_ui->midi_track());
1510         np->add (note);
1511         np->play ();
1512 }
1513
1514 void
1515 MidiRegionView::play_midi_chord (vector<boost::shared_ptr<NoteType> > notes)
1516 {
1517         if (_no_sound_notes || !trackview.editor().sound_notes()) {
1518                 return;
1519         }
1520
1521         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
1522
1523         if (!route_ui || !route_ui->midi_track()) {
1524                 return;
1525         }
1526
1527         NotePlayer* np = new NotePlayer (route_ui->midi_track());
1528
1529         for (vector<boost::shared_ptr<NoteType> >::iterator n = notes.begin(); n != notes.end(); ++n) {
1530                 np->add (*n);
1531         }
1532
1533         np->play ();
1534 }
1535
1536
1537 bool
1538 MidiRegionView::note_in_region_range (const boost::shared_ptr<NoteType> note, bool& visible) const
1539 {
1540         const framepos_t note_start_frames = source_beats_to_region_frames (note->time());
1541         bool outside = (note_start_frames  < 0) || (note_start_frames > _region->last_frame());
1542
1543         visible = (note->note() >= midi_stream_view()->lowest_note()) &&
1544                 (note->note() <= midi_stream_view()->highest_note());
1545
1546         return !outside;
1547 }
1548
1549 /** Update a canvas note's size from its model note.
1550  *  @param ev Canvas note to update.
1551  *  @param update_ghost_regions true to update the note in any ghost regions that we have, otherwise false.
1552  */
1553 void
1554 MidiRegionView::update_note (CanvasNote* ev, bool update_ghost_regions)
1555 {
1556         boost::shared_ptr<NoteType> note = ev->note();
1557
1558         const double x = trackview.editor().frame_to_pixel (source_beats_to_region_frames (note->time()));
1559         const double y1 = midi_stream_view()->note_to_y(note->note());
1560
1561         ev->property_x1() = x;
1562         ev->property_y1() = y1;
1563
1564         /* trim note display to not overlap the end of its region */
1565
1566         if (note->length() > 0) {
1567                 const framepos_t note_end_frames = min (source_beats_to_region_frames (note->end_time()), _region->length());
1568                 ev->property_x2() = trackview.editor().frame_to_pixel (note_end_frames);
1569         } else {
1570                 ev->property_x2() = trackview.editor().frame_to_pixel (_region->length());
1571         }
1572
1573         ev->property_y2() = y1 + floor(midi_stream_view()->note_height());
1574
1575         if (note->length() == 0) {
1576                 if (_active_notes) {
1577                         assert(note->note() < 128);
1578                         // If this note is already active there's a stuck note,
1579                         // finish the old note rectangle
1580                         if (_active_notes[note->note()]) {
1581                                 CanvasNote* const old_rect = _active_notes[note->note()];
1582                                 boost::shared_ptr<NoteType> old_note = old_rect->note();
1583                                 old_rect->property_x2() = x;
1584                                 old_rect->property_outline_what() = (guint32) 0xF;
1585                         }
1586                         _active_notes[note->note()] = ev;
1587                 }
1588                 /* outline all but right edge */
1589                 ev->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
1590         } else {
1591                 /* outline all edges */
1592                 ev->property_outline_what() = (guint32) 0xF;
1593         }
1594
1595         if (update_ghost_regions) {
1596                 for (std::vector<GhostRegion*>::iterator i = ghosts.begin(); i != ghosts.end(); ++i) {
1597                         MidiGhostRegion* gr = dynamic_cast<MidiGhostRegion*> (*i);
1598                         if (gr) {
1599                                 gr->update_note (ev);
1600                         }
1601                 }
1602         }
1603 }
1604
1605 double
1606 MidiRegionView::update_hit (CanvasHit* ev)
1607 {
1608         boost::shared_ptr<NoteType> note = ev->note();
1609
1610         const framepos_t note_start_frames = source_beats_to_region_frames(note->time());
1611         const double x = trackview.editor().frame_to_pixel(note_start_frames);
1612         const double diamond_size = midi_stream_view()->note_height() / 2.0;
1613         const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
1614
1615         ev->move_to (x, y);
1616
1617         return diamond_size;
1618 }
1619
1620 /** Add a MIDI note to the view (with length).
1621  *
1622  * If in sustained mode, notes with length 0 will be considered active
1623  * notes, and resolve_note should be called when the corresponding note off
1624  * event arrives, to properly display the note.
1625  */
1626 void
1627 MidiRegionView::add_note(const boost::shared_ptr<NoteType> note, bool visible)
1628 {
1629         CanvasNoteEvent* event = 0;
1630
1631         assert(note->time() >= 0);
1632         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
1633
1634         //ArdourCanvas::Group* const group = (ArdourCanvas::Group*) get_canvas_group();
1635
1636         if (midi_view()->note_mode() == Sustained) {
1637
1638                 CanvasNote* ev_rect = new CanvasNote(*this, *_note_group, note);
1639
1640                 update_note (ev_rect);
1641
1642                 event = ev_rect;
1643
1644                 MidiGhostRegion* gr;
1645
1646                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
1647                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
1648                                 gr->add_note(ev_rect);
1649                         }
1650                 }
1651
1652         } else if (midi_view()->note_mode() == Percussive) {
1653
1654                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
1655
1656                 CanvasHit* ev_diamond = new CanvasHit (*this, *_note_group, diamond_size, note);
1657
1658                 update_hit (ev_diamond);
1659
1660                 event = ev_diamond;
1661
1662         } else {
1663                 event = 0;
1664         }
1665
1666         if (event) {
1667                 if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
1668                         note_selected(event, true);
1669                 }
1670
1671                 if (_marked_for_velocity.find(note) != _marked_for_velocity.end()) {
1672                         event->show_velocity();
1673                 }
1674
1675                 event->on_channel_selection_change(_last_channel_selection);
1676                 _events.push_back(event);
1677
1678                 if (visible) {
1679                         event->show();
1680                 } else {
1681                         event->hide ();
1682                 }
1683         }
1684
1685         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
1686         MidiStreamView* const view = mtv->midi_view();
1687
1688         view->update_note_range (note->note());
1689 }
1690
1691 void
1692 MidiRegionView::step_add_note (uint8_t channel, uint8_t number, uint8_t velocity,
1693                                Evoral::MusicalTime pos, Evoral::MusicalTime len)
1694 {
1695         boost::shared_ptr<NoteType> new_note (new NoteType (channel, pos, len, number, velocity));
1696
1697         /* potentially extend region to hold new note */
1698
1699         framepos_t end_frame = source_beats_to_absolute_frames (new_note->end_time());
1700         framepos_t region_end = _region->last_frame();
1701
1702         if (end_frame > region_end) {
1703                 _region->set_length (end_frame - _region->position());
1704         }
1705
1706         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
1707         MidiStreamView* const view = mtv->midi_view();
1708
1709         view->update_note_range(new_note->note());
1710
1711         _marked_for_selection.clear ();
1712         clear_selection ();
1713
1714         start_note_diff_command (_("step add"));
1715         note_diff_add_note (new_note, true, false);
1716         apply_diff();
1717
1718         // last_step_edit_note = new_note;
1719 }
1720
1721 void
1722 MidiRegionView::step_sustain (Evoral::MusicalTime beats)
1723 {
1724         change_note_lengths (false, false, beats, false, true);
1725 }
1726
1727 void
1728 MidiRegionView::add_canvas_patch_change (MidiModel::PatchChangePtr patch, const string& displaytext)
1729 {
1730         assert (patch->time() >= 0);
1731
1732         const double x = trackview.editor().frame_to_pixel (source_beats_to_region_frames (patch->time()));
1733
1734         double const height = midi_stream_view()->contents_height();
1735
1736         boost::shared_ptr<CanvasPatchChange> patch_change = boost::shared_ptr<CanvasPatchChange>(
1737                 new CanvasPatchChange(*this, *_note_group,
1738                                       displaytext,
1739                                       height,
1740                                       x, 1.0,
1741                                       _model_name,
1742                                       _custom_device_mode,
1743                                       patch)
1744                           );
1745
1746         // Show unless patch change is beyond the region bounds
1747         if (patch->time() - _region->start() >= _region->length() || patch->time() < _region->start()) {
1748                 patch_change->hide();
1749         } else {
1750                 patch_change->show();
1751         }
1752
1753         _patch_changes.push_back (patch_change);
1754 }
1755
1756 void
1757 MidiRegionView::get_patch_key_at (Evoral::MusicalTime time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
1758 {
1759         MidiModel::PatchChanges::iterator i = _model->patch_change_lower_bound (time);
1760         while (i != _model->patch_changes().end() && (*i)->channel() != channel) {
1761                 ++i;
1762         }
1763
1764         if (i != _model->patch_changes().end()) {
1765                 key.msb = (*i)->bank_msb ();
1766                 key.lsb = (*i)->bank_lsb ();
1767                 key.program_number = (*i)->program ();
1768         } else {
1769                 key.msb = key.lsb = key.program_number = 0;
1770         }
1771
1772         assert (key.is_sane());
1773 }
1774
1775
1776 void
1777 MidiRegionView::change_patch_change (CanvasPatchChange& pc, const MIDI::Name::PatchPrimaryKey& new_patch)
1778 {
1779         MidiModel::PatchChangeDiffCommand* c = _model->new_patch_change_diff_command (_("alter patch change"));
1780
1781         if (pc.patch()->program() != new_patch.program_number) {
1782                 c->change_program (pc.patch (), new_patch.program_number);
1783         }
1784
1785         int const new_bank = (new_patch.msb << 7) | new_patch.lsb;
1786         if (pc.patch()->bank() != new_bank) {
1787                 c->change_bank (pc.patch (), new_bank);
1788         }
1789
1790         _model->apply_command (*trackview.session(), c);
1791
1792         _patch_changes.clear ();
1793         display_patch_changes ();
1794 }
1795
1796 void
1797 MidiRegionView::change_patch_change (MidiModel::PatchChangePtr old_change, const Evoral::PatchChange<Evoral::MusicalTime> & new_change)
1798 {
1799         MidiModel::PatchChangeDiffCommand* c = _model->new_patch_change_diff_command (_("alter patch change"));
1800
1801         if (old_change->time() != new_change.time()) {
1802                 c->change_time (old_change, new_change.time());
1803         }
1804
1805         if (old_change->channel() != new_change.channel()) {
1806                 c->change_channel (old_change, new_change.channel());
1807         }
1808
1809         if (old_change->program() != new_change.program()) {
1810                 c->change_program (old_change, new_change.program());
1811         }
1812
1813         if (old_change->bank() != new_change.bank()) {
1814                 c->change_bank (old_change, new_change.bank());
1815         }
1816
1817         _model->apply_command (*trackview.session(), c);
1818
1819         _patch_changes.clear ();
1820         display_patch_changes ();
1821 }
1822
1823 /** Add a patch change to the region.
1824  *  @param t Time in frames relative to region position
1825  *  @param patch Patch to add; time and channel are ignored (time is converted from t, and channel comes from
1826  *  MidiTimeAxisView::get_channel_for_add())
1827  */
1828 void
1829 MidiRegionView::add_patch_change (framecnt_t t, Evoral::PatchChange<Evoral::MusicalTime> const & patch)
1830 {
1831         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
1832
1833         MidiModel::PatchChangeDiffCommand* c = _model->new_patch_change_diff_command (_("add patch change"));
1834         c->add (MidiModel::PatchChangePtr (
1835                         new Evoral::PatchChange<Evoral::MusicalTime> (
1836                                 absolute_frames_to_source_beats (_region->position() + t),
1837                                 mtv->get_channel_for_add(), patch.program(), patch.bank()
1838                                 )
1839                         )
1840                 );
1841
1842         _model->apply_command (*trackview.session(), c);
1843
1844         _patch_changes.clear ();
1845         display_patch_changes ();
1846 }
1847
1848 void
1849 MidiRegionView::move_patch_change (CanvasPatchChange& pc, Evoral::MusicalTime t)
1850 {
1851         MidiModel::PatchChangeDiffCommand* c = _model->new_patch_change_diff_command (_("move patch change"));
1852         c->change_time (pc.patch (), t);
1853         _model->apply_command (*trackview.session(), c);
1854
1855         _patch_changes.clear ();
1856         display_patch_changes ();
1857 }
1858
1859 void
1860 MidiRegionView::delete_patch_change (CanvasPatchChange* pc)
1861 {
1862         MidiModel::PatchChangeDiffCommand* c = _model->new_patch_change_diff_command (_("delete patch change"));
1863         c->remove (pc->patch ());
1864         _model->apply_command (*trackview.session(), c);
1865
1866         _patch_changes.clear ();
1867         display_patch_changes ();
1868 }
1869
1870 void
1871 MidiRegionView::previous_patch (CanvasPatchChange& patch)
1872 {
1873         if (patch.patch()->program() < 127) {
1874                 MIDI::Name::PatchPrimaryKey key;
1875                 get_patch_key_at (patch.patch()->time(), patch.patch()->channel(), key);
1876                 key.program_number++;
1877                 change_patch_change (patch, key);
1878         }
1879 }
1880
1881 void
1882 MidiRegionView::next_patch (CanvasPatchChange& patch)
1883 {
1884         if (patch.patch()->program() > 0) {
1885                 MIDI::Name::PatchPrimaryKey key;
1886                 get_patch_key_at (patch.patch()->time(), patch.patch()->channel(), key);
1887                 key.program_number--;
1888                 change_patch_change (patch, key);
1889         }
1890 }
1891
1892 void
1893 MidiRegionView::previous_bank (CanvasPatchChange& patch)
1894 {
1895         if (patch.patch()->program() < 127) {
1896                 MIDI::Name::PatchPrimaryKey key;
1897                 get_patch_key_at (patch.patch()->time(), patch.patch()->channel(), key);
1898                 if (key.lsb > 0) {
1899                         key.lsb--;
1900                         change_patch_change (patch, key);
1901                 } else {
1902                         if (key.msb > 0) {
1903                                 key.lsb = 127;
1904                                 key.msb--;
1905                                 change_patch_change (patch, key);
1906                         }
1907                 }
1908         }
1909 }
1910
1911 void
1912 MidiRegionView::next_bank (CanvasPatchChange& patch)
1913 {
1914         if (patch.patch()->program() > 0) {
1915                 MIDI::Name::PatchPrimaryKey key;
1916                 get_patch_key_at (patch.patch()->time(), patch.patch()->channel(), key);
1917                 if (key.lsb < 127) {
1918                         key.lsb++;
1919                         change_patch_change (patch, key);
1920                 } else {
1921                         if (key.msb < 127) {
1922                                 key.lsb = 0;
1923                                 key.msb++;
1924                                 change_patch_change (patch, key);
1925                         }
1926                 }
1927         }
1928 }
1929
1930 void
1931 MidiRegionView::maybe_remove_deleted_note_from_selection (CanvasNoteEvent* cne)
1932 {
1933         if (_selection.empty()) {
1934                 return;
1935         }
1936
1937         _selection.erase (cne);
1938 }
1939
1940 void
1941 MidiRegionView::delete_selection()
1942 {
1943         if (_selection.empty()) {
1944                 return;
1945         }
1946
1947         start_note_diff_command (_("delete selection"));
1948
1949         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1950                 if ((*i)->selected()) {
1951                         _note_diff_command->remove((*i)->note());
1952                 }
1953         }
1954
1955         _selection.clear();
1956
1957         apply_diff ();
1958 }
1959
1960 void
1961 MidiRegionView::delete_note (boost::shared_ptr<NoteType> n)
1962 {
1963         start_note_diff_command (_("delete note"));
1964         _note_diff_command->remove (n);
1965         apply_diff ();
1966
1967         trackview.editor().verbose_cursor()->hide ();
1968 }
1969
1970 void
1971 MidiRegionView::clear_selection_except (ArdourCanvas::CanvasNoteEvent* ev, bool signal)
1972 {
1973         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
1974                 if ((*i) != ev) {
1975                         Selection::iterator tmp = i;
1976                         ++tmp;
1977
1978                         (*i)->set_selected (false);
1979                         (*i)->hide_velocity ();
1980                         _selection.erase (i);
1981                         
1982                         i = tmp;
1983                 } else {
1984                         ++i;
1985                 }
1986         }
1987
1988         /* this does not change the status of this regionview w.r.t the editor
1989            selection.
1990         */
1991
1992         if (signal) {
1993                 SelectionCleared (this); /* EMIT SIGNAL */
1994         }
1995 }
1996
1997 void
1998 MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
1999 {
2000         clear_selection_except (ev);
2001
2002         /* don't bother with checking to see if we should remove this
2003            regionview from the editor selection, since we're about to add
2004            another note, and thus put/keep this regionview in the editor
2005            selection anyway.
2006         */
2007
2008         if (!ev->selected()) {
2009                 add_to_selection (ev);
2010         }
2011 }
2012
2013 void
2014 MidiRegionView::select_all_notes ()
2015 {
2016         clear_selection ();
2017
2018         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2019                 add_to_selection (*i);
2020         }
2021 }
2022
2023 void
2024 MidiRegionView::select_matching_notes (uint8_t notenum, uint16_t channel_mask, bool add, bool extend)
2025 {
2026         uint8_t low_note = 127;
2027         uint8_t high_note = 0;
2028         MidiModel::Notes& notes (_model->notes());
2029         _optimization_iterator = _events.begin();
2030
2031         if (!add) {
2032                 clear_selection ();
2033         }
2034
2035         if (extend && _selection.empty()) {
2036                 extend = false;
2037         }
2038
2039         if (extend) {
2040
2041                 /* scan existing selection to get note range */
2042
2043                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2044                         if ((*i)->note()->note() < low_note) {
2045                                 low_note = (*i)->note()->note();
2046                         }
2047                         if ((*i)->note()->note() > high_note) {
2048                                 high_note = (*i)->note()->note();
2049                         }
2050                 }
2051
2052                 low_note = min (low_note, notenum);
2053                 high_note = max (high_note, notenum);
2054         }
2055
2056         _no_sound_notes = true;
2057
2058         for (MidiModel::Notes::iterator n = notes.begin(); n != notes.end(); ++n) {
2059
2060                 boost::shared_ptr<NoteType> note (*n);
2061                 CanvasNoteEvent* cne;
2062                 bool select = false;
2063
2064                 if (((1 << note->channel()) & channel_mask) != 0) {
2065                         if (extend) {
2066                                 if ((note->note() >= low_note && note->note() <= high_note)) {
2067                                         select = true;
2068                                 }
2069                         } else if (note->note() == notenum) {
2070                                 select = true;
2071                         }
2072                 }
2073
2074                 if (select) {
2075                         if ((cne = find_canvas_note (note)) != 0) {
2076                                 // extend is false because we've taken care of it,
2077                                 // since it extends by time range, not pitch.
2078                                 note_selected (cne, add, false);
2079                         }
2080                 }
2081
2082                 add = true; // we need to add all remaining matching notes, even if the passed in value was false (for "set")
2083
2084         }
2085
2086         _no_sound_notes = false;
2087 }
2088
2089 void
2090 MidiRegionView::toggle_matching_notes (uint8_t notenum, uint16_t channel_mask)
2091 {
2092         MidiModel::Notes& notes (_model->notes());
2093         _optimization_iterator = _events.begin();
2094
2095         for (MidiModel::Notes::iterator n = notes.begin(); n != notes.end(); ++n) {
2096
2097                 boost::shared_ptr<NoteType> note (*n);
2098                 CanvasNoteEvent* cne;
2099
2100                 if (note->note() == notenum && (((0x0001 << note->channel()) & channel_mask) != 0)) {
2101                         if ((cne = find_canvas_note (note)) != 0) {
2102                                 if (cne->selected()) {
2103                                         note_deselected (cne);
2104                                 } else {
2105                                         note_selected (cne, true, false);
2106                                 }
2107                         }
2108                 }
2109         }
2110 }
2111
2112 void
2113 MidiRegionView::note_selected (ArdourCanvas::CanvasNoteEvent* ev, bool add, bool extend)
2114 {
2115         if (!add) {
2116                 clear_selection_except (ev);
2117                 if (!_selection.empty()) {
2118                         PublicEditor& editor (trackview.editor());
2119                         editor.get_selection().add (this);
2120                 }
2121         }
2122
2123         if (!extend) {
2124
2125                 if (!ev->selected()) {
2126                         add_to_selection (ev);
2127                 }
2128
2129         } else {
2130                 /* find end of latest note selected, select all between that and the start of "ev" */
2131
2132                 Evoral::MusicalTime earliest = Evoral::MaxMusicalTime;
2133                 Evoral::MusicalTime latest = 0;
2134
2135                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2136                         if ((*i)->note()->end_time() > latest) {
2137                                 latest = (*i)->note()->end_time();
2138                         }
2139                         if ((*i)->note()->time() < earliest) {
2140                                 earliest = (*i)->note()->time();
2141                         }
2142                 }
2143
2144                 if (ev->note()->end_time() > latest) {
2145                         latest = ev->note()->end_time();
2146                 }
2147
2148                 if (ev->note()->time() < earliest) {
2149                         earliest = ev->note()->time();
2150                 }
2151
2152                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2153
2154                         /* find notes entirely within OR spanning the earliest..latest range */
2155
2156                         if (((*i)->note()->time() >= earliest && (*i)->note()->end_time() <= latest) ||
2157                             ((*i)->note()->time() <= earliest && (*i)->note()->end_time() >= latest)) {
2158                                 add_to_selection (*i);
2159                         }
2160
2161                 }
2162         }
2163 }
2164
2165 void
2166 MidiRegionView::note_deselected(ArdourCanvas::CanvasNoteEvent* ev)
2167 {
2168         remove_from_selection (ev);
2169 }
2170
2171 void
2172 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2, bool extend)
2173 {
2174         if (x1 > x2) {
2175                 swap (x1, x2);
2176         }
2177
2178         if (y1 > y2) {
2179                 swap (y1, y2);
2180         }
2181
2182         // TODO: Make this faster by storing the last updated selection rect, and only
2183         // adjusting things that are in the area that appears/disappeared.
2184         // We probably need a tree to be able to find events in O(log(n)) time.
2185
2186         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2187
2188                 /* check if any corner of the note is inside the rect
2189
2190                    Notes:
2191                    1) this is computing "touched by", not "contained by" the rect.
2192                    2) this does not require that events be sorted in time.
2193                 */
2194
2195                 const double ix1 = (*i)->x1();
2196                 const double ix2 = (*i)->x2();
2197                 const double iy1 = (*i)->y1();
2198                 const double iy2 = (*i)->y2();
2199
2200                 if ((ix1 >= x1 && ix1 <= x2 && iy1 >= y1 && iy1 <= y2) ||
2201                     (ix1 >= x1 && ix1 <= x2 && iy2 >= y1 && iy2 <= y2) ||
2202                     (ix2 >= x1 && ix2 <= x2 && iy1 >= y1 && iy1 <= y2) ||
2203                     (ix2 >= x1 && ix2 <= x2 && iy2 >= y1 && iy2 <= y2)) {
2204
2205                         // Inside rectangle
2206                         if (!(*i)->selected()) {
2207                                 add_to_selection (*i);
2208                         }
2209                 } else if ((*i)->selected() && !extend) {
2210                         // Not inside rectangle
2211                         remove_from_selection (*i);
2212                 }
2213         }
2214 }
2215
2216 void
2217 MidiRegionView::remove_from_selection (CanvasNoteEvent* ev)
2218 {
2219         Selection::iterator i = _selection.find (ev);
2220
2221         if (i != _selection.end()) {
2222                 _selection.erase (i);
2223         }
2224
2225         ev->set_selected (false);
2226         ev->hide_velocity ();
2227
2228         if (_selection.empty()) {
2229                 PublicEditor& editor (trackview.editor());
2230                 editor.get_selection().remove (this);
2231         }
2232 }
2233
2234 void
2235 MidiRegionView::add_to_selection (CanvasNoteEvent* ev)
2236 {
2237         bool add_mrv_selection = false;
2238
2239         if (_selection.empty()) {
2240                 add_mrv_selection = true;
2241         }
2242
2243         if (_selection.insert (ev).second) {
2244                 ev->set_selected (true);
2245                 play_midi_note ((ev)->note());
2246         }
2247
2248         if (add_mrv_selection) {
2249                 PublicEditor& editor (trackview.editor());
2250                 editor.get_selection().add (this);
2251         }
2252 }
2253
2254 void
2255 MidiRegionView::move_selection(double dx, double dy, double cumulative_dy)
2256 {
2257         typedef vector<boost::shared_ptr<NoteType> > PossibleChord;
2258         PossibleChord to_play;
2259         Evoral::MusicalTime earliest = Evoral::MaxMusicalTime;
2260
2261         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2262                 if ((*i)->note()->time() < earliest) {
2263                         earliest = (*i)->note()->time();
2264                 }
2265         }
2266
2267         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2268                 if (Evoral::musical_time_equal ((*i)->note()->time(), earliest)) {
2269                         to_play.push_back ((*i)->note());
2270                 }
2271                 (*i)->move_event(dx, dy);
2272         }
2273
2274         if (dy && !_selection.empty() && !_no_sound_notes && trackview.editor().sound_notes()) {
2275
2276                 if (to_play.size() > 1) {
2277
2278                         PossibleChord shifted;
2279
2280                         for (PossibleChord::iterator n = to_play.begin(); n != to_play.end(); ++n) {
2281                                 boost::shared_ptr<NoteType> moved_note (new NoteType (**n));
2282                                 moved_note->set_note (moved_note->note() + cumulative_dy);
2283                                 shifted.push_back (moved_note);
2284                         }
2285
2286                         play_midi_chord (shifted);
2287
2288                 } else if (!to_play.empty()) {
2289
2290                         boost::shared_ptr<NoteType> moved_note (new NoteType (*to_play.front()));
2291                         moved_note->set_note (moved_note->note() + cumulative_dy);
2292                         play_midi_note (moved_note);
2293                 }
2294         }
2295 }
2296
2297 void
2298 MidiRegionView::note_dropped(CanvasNoteEvent *, frameoffset_t dt, int8_t dnote)
2299 {
2300         assert (!_selection.empty());
2301
2302         uint8_t lowest_note_in_selection  = 127;
2303         uint8_t highest_note_in_selection = 0;
2304         uint8_t highest_note_difference = 0;
2305
2306         // find highest and lowest notes first
2307
2308         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2309                 uint8_t pitch = (*i)->note()->note();
2310                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
2311                 highest_note_in_selection = std::max(highest_note_in_selection, pitch);
2312         }
2313
2314         /*
2315           cerr << "dnote: " << (int) dnote << endl;
2316           cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note())
2317           << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
2318           cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): "
2319           << int(highest_note_in_selection) << endl;
2320           cerr << "selection size: " << _selection.size() << endl;
2321           cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
2322         */
2323
2324         // Make sure the note pitch does not exceed the MIDI standard range
2325         if (highest_note_in_selection + dnote > 127) {
2326                 highest_note_difference = highest_note_in_selection - 127;
2327         }
2328
2329         start_note_diff_command (_("move notes"));
2330
2331         for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ++i) {
2332
2333                 Evoral::MusicalTime new_time = absolute_frames_to_source_beats (source_beats_to_absolute_frames ((*i)->note()->time()) + dt);
2334
2335                 if (new_time < 0) {
2336                         continue;
2337                 }
2338
2339                 note_diff_add_change (*i, MidiModel::NoteDiffCommand::StartTime, new_time);
2340
2341                 uint8_t original_pitch = (*i)->note()->note();
2342                 uint8_t new_pitch      = original_pitch + dnote - highest_note_difference;
2343
2344                 // keep notes in standard midi range
2345                 clamp_to_0_127(new_pitch);
2346
2347                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
2348                 highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
2349
2350                 note_diff_add_change (*i, MidiModel::NoteDiffCommand::NoteNumber, new_pitch);
2351         }
2352
2353         apply_diff();
2354
2355         // care about notes being moved beyond the upper/lower bounds on the canvas
2356         if (lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
2357             highest_note_in_selection > midi_stream_view()->highest_note()) {
2358                 midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
2359         }
2360 }
2361
2362 framepos_t
2363 MidiRegionView::snap_pixel_to_frame(double x)
2364 {
2365         PublicEditor& editor (trackview.editor());
2366         return snap_frame_to_frame (editor.pixel_to_frame (x));
2367 }
2368
2369 double
2370 MidiRegionView::snap_to_pixel(double x)
2371 {
2372         return (double) trackview.editor().frame_to_pixel(snap_pixel_to_frame(x));
2373 }
2374
2375 double
2376 MidiRegionView::get_position_pixels()
2377 {
2378         framepos_t region_frame = get_position();
2379         return trackview.editor().frame_to_pixel(region_frame);
2380 }
2381
2382 double
2383 MidiRegionView::get_end_position_pixels()
2384 {
2385         framepos_t frame = get_position() + get_duration ();
2386         return trackview.editor().frame_to_pixel(frame);
2387 }
2388
2389 framepos_t
2390 MidiRegionView::source_beats_to_absolute_frames(double beats) const
2391 {
2392         /* the time converter will return the frame corresponding to `beats'
2393            relative to the start of the source. The start of the source
2394            is an implied position given by region->position - region->start
2395         */
2396         const framepos_t source_start = _region->position() - _region->start();
2397         return  source_start +  _source_relative_time_converter.to (beats);
2398 }
2399
2400 double
2401 MidiRegionView::absolute_frames_to_source_beats(framepos_t frames) const
2402 {
2403         /* the `frames' argument needs to be converted into a frame count
2404            relative to the start of the source before being passed in to the
2405            converter.
2406         */
2407         const framepos_t source_start = _region->position() - _region->start();
2408         return  _source_relative_time_converter.from (frames - source_start);
2409 }
2410
2411 framepos_t
2412 MidiRegionView::region_beats_to_region_frames(double beats) const
2413 {
2414         return _region_relative_time_converter.to(beats);
2415 }
2416
2417 double
2418 MidiRegionView::region_frames_to_region_beats(framepos_t frames) const
2419 {
2420         return _region_relative_time_converter.from(frames);
2421 }
2422
2423 void
2424 MidiRegionView::begin_resizing (bool /*at_front*/)
2425 {
2426         _resize_data.clear();
2427
2428         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2429                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
2430
2431                 // only insert CanvasNotes into the map
2432                 if (note) {
2433                         NoteResizeData *resize_data = new NoteResizeData();
2434                         resize_data->canvas_note = note;
2435
2436                         // create a new SimpleRect from the note which will be the resize preview
2437                         SimpleRect *resize_rect = new SimpleRect(
2438                                 *_note_group, note->x1(), note->y1(), note->x2(), note->y2());
2439
2440                         // calculate the colors: get the color settings
2441                         uint32_t fill_color = UINT_RGBA_CHANGE_A(
2442                                 ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get(),
2443                                 128);
2444
2445                         // make the resize preview notes more transparent and bright
2446                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
2447
2448                         // calculate color based on note velocity
2449                         resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
2450                                 CanvasNoteEvent::meter_style_fill_color(note->note()->velocity(), note->selected()),
2451                                 fill_color,
2452                                 0.85);
2453
2454                         resize_rect->property_outline_color_rgba() = CanvasNoteEvent::calculate_outline(
2455                                 ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get());
2456
2457                         resize_data->resize_rect = resize_rect;
2458                         _resize_data.push_back(resize_data);
2459                 }
2460         }
2461 }
2462
2463 /** Update resizing notes while user drags.
2464  * @param primary `primary' note for the drag; ie the one that is used as the reference in non-relative mode.
2465  * @param at_front which end of the note (true == note on, false == note off)
2466  * @param delta_x change in mouse position since the start of the drag
2467  * @param relative true if relative resizing is taking place, false if absolute resizing.  This only makes
2468  * a difference when multiple notes are being resized; in relative mode, each note's length is changed by the
2469  * amount of the drag.  In non-relative mode, all selected notes are set to have the same start or end point
2470  * as the \a primary note.
2471  */
2472 void
2473 MidiRegionView::update_resizing (ArdourCanvas::CanvasNoteEvent* primary, bool at_front, double delta_x, bool relative)
2474 {
2475         bool cursor_set = false;
2476
2477         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
2478                 SimpleRect* resize_rect = (*i)->resize_rect;
2479                 CanvasNote* canvas_note = (*i)->canvas_note;
2480                 double current_x;
2481
2482                 if (at_front) {
2483                         if (relative) {
2484                                 current_x = canvas_note->x1() + delta_x;
2485                         } else {
2486                                 current_x = primary->x1() + delta_x;
2487                         }
2488                 } else {
2489                         if (relative) {
2490                                 current_x = canvas_note->x2() + delta_x;
2491                         } else {
2492                                 current_x = primary->x2() + delta_x;
2493                         }
2494                 }
2495
2496                 if (at_front) {
2497                         resize_rect->property_x1() = snap_to_pixel(current_x);
2498                         resize_rect->property_x2() = canvas_note->x2();
2499                 } else {
2500                         resize_rect->property_x2() = snap_to_pixel(current_x);
2501                         resize_rect->property_x1() = canvas_note->x1();
2502                 }
2503
2504                 if (!cursor_set) {
2505                         double beats;
2506
2507                         beats = snap_pixel_to_frame (current_x);
2508                         /* XXX not sure this is correct - snap_pixel_to_frame()
2509                            returns an absolute frame.
2510                         */
2511                         beats = region_frames_to_region_beats (beats);
2512
2513                         double len;
2514
2515                         if (at_front) {
2516                                 if (beats < canvas_note->note()->end_time()) {
2517                                         len = canvas_note->note()->time() - beats;
2518                                         len += canvas_note->note()->length();
2519                                 } else {
2520                                         len = 0;
2521                                 }
2522                         } else {
2523                                 if (beats >= canvas_note->note()->time()) {
2524                                         len = beats - canvas_note->note()->time();
2525                                 } else {
2526                                         len = 0;
2527                                 }
2528                         }
2529
2530                         char buf[16];
2531                         snprintf (buf, sizeof (buf), "%.3g beats", len);
2532                         show_verbose_cursor (buf, 0, 0);
2533
2534                         cursor_set = true;
2535                 }
2536
2537         }
2538 }
2539
2540
2541 /** Finish resizing notes when the user releases the mouse button.
2542  *  Parameters the same as for \a update_resizing().
2543  */
2544 void
2545 MidiRegionView::commit_resizing (ArdourCanvas::CanvasNoteEvent* primary, bool at_front, double delta_x, bool relative)
2546 {
2547         start_note_diff_command (_("resize notes"));
2548
2549         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
2550                 CanvasNote*  canvas_note = (*i)->canvas_note;
2551                 SimpleRect*  resize_rect = (*i)->resize_rect;
2552
2553                 /* Get the new x position for this resize, which is in pixels relative
2554                  * to the region position.
2555                  */
2556                 
2557                 double current_x;
2558
2559                 if (at_front) {
2560                         if (relative) {
2561                                 current_x = canvas_note->x1() + delta_x;
2562                         } else {
2563                                 current_x = primary->x1() + delta_x;
2564                         }
2565                 } else {
2566                         if (relative) {
2567                                 current_x = canvas_note->x2() + delta_x;
2568                         } else {
2569                                 current_x = primary->x2() + delta_x;
2570                         }
2571                 }
2572
2573                 /* Convert that to a frame within the region */
2574                 current_x = snap_pixel_to_frame (current_x) + _region->start ();
2575
2576                 /* and then to beats */
2577                 /* XXX not sure this is correct - snap_pixel_to_frame()
2578                    returns an absolute frame.
2579                 */
2580                 current_x = region_frames_to_region_beats (current_x);
2581
2582                 if (at_front && current_x < canvas_note->note()->end_time()) {
2583                         note_diff_add_change (canvas_note, MidiModel::NoteDiffCommand::StartTime, current_x);
2584
2585                         double len = canvas_note->note()->time() - current_x;
2586                         len += canvas_note->note()->length();
2587
2588                         if (len > 0) {
2589                                 /* XXX convert to beats */
2590                                 note_diff_add_change (canvas_note, MidiModel::NoteDiffCommand::Length, len);
2591                         }
2592                 }
2593
2594                 if (!at_front) {
2595                         double len = current_x - canvas_note->note()->time();
2596
2597                         if (len > 0) {
2598                                 /* XXX convert to beats */
2599                                 note_diff_add_change (canvas_note, MidiModel::NoteDiffCommand::Length, len);
2600                         }
2601                 }
2602
2603                 delete resize_rect;
2604                 delete (*i);
2605         }
2606
2607         _resize_data.clear();
2608         apply_diff();
2609 }
2610
2611 void
2612 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
2613 {
2614         uint8_t new_velocity;
2615
2616         if (relative) {
2617                 new_velocity = event->note()->velocity() + velocity;
2618                 clamp_to_0_127(new_velocity);
2619         } else {
2620                 new_velocity = velocity;
2621         }
2622
2623         event->set_selected (event->selected()); // change color
2624
2625         note_diff_add_change (event, MidiModel::NoteDiffCommand::Velocity, new_velocity);
2626 }
2627
2628 void
2629 MidiRegionView::change_note_note (CanvasNoteEvent* event, int8_t note, bool relative)
2630 {
2631         uint8_t new_note;
2632
2633         if (relative) {
2634                 new_note = event->note()->note() + note;
2635         } else {
2636                 new_note = note;
2637         }
2638
2639         clamp_to_0_127 (new_note);
2640         note_diff_add_change (event, MidiModel::NoteDiffCommand::NoteNumber, new_note);
2641 }
2642
2643 void
2644 MidiRegionView::trim_note (CanvasNoteEvent* event, Evoral::MusicalTime front_delta, Evoral::MusicalTime end_delta)
2645 {
2646         bool change_start = false;
2647         bool change_length = false;
2648         Evoral::MusicalTime new_start = 0;
2649         Evoral::MusicalTime new_length = 0;
2650
2651         /* NOTE: the semantics of the two delta arguments are slightly subtle:
2652
2653            front_delta: if positive - move the start of the note later in time (shortening it)
2654            if negative - move the start of the note earlier in time (lengthening it)
2655
2656            end_delta:   if positive - move the end of the note later in time (lengthening it)
2657            if negative - move the end of the note earlier in time (shortening it)
2658         */
2659
2660         if (front_delta) {
2661                 if (front_delta < 0) {
2662
2663                         if (event->note()->time() < -front_delta) {
2664                                 new_start = 0;
2665                         } else {
2666                                 new_start = event->note()->time() + front_delta; // moves earlier
2667                         }
2668
2669                         /* start moved toward zero, so move the end point out to where it used to be.
2670                            Note that front_delta is negative, so this increases the length.
2671                         */
2672
2673                         new_length = event->note()->length() - front_delta;
2674                         change_start = true;
2675                         change_length = true;
2676
2677                 } else {
2678
2679                         Evoral::MusicalTime new_pos = event->note()->time() + front_delta;
2680
2681                         if (new_pos < event->note()->end_time()) {
2682                                 new_start = event->note()->time() + front_delta;
2683                                 /* start moved toward the end, so move the end point back to where it used to be */
2684                                 new_length = event->note()->length() - front_delta;
2685                                 change_start = true;
2686                                 change_length = true;
2687                         }
2688                 }
2689
2690         }
2691
2692         if (end_delta) {
2693                 bool can_change = true;
2694                 if (end_delta < 0) {
2695                         if (event->note()->length() < -end_delta) {
2696                                 can_change = false;
2697                         }
2698                 }
2699
2700                 if (can_change) {
2701                         new_length = event->note()->length() + end_delta;
2702                         change_length = true;
2703                 }
2704         }
2705
2706         if (change_start) {
2707                 note_diff_add_change (event, MidiModel::NoteDiffCommand::StartTime, new_start);
2708         }
2709
2710         if (change_length) {
2711                 note_diff_add_change (event, MidiModel::NoteDiffCommand::Length, new_length);
2712         }
2713 }
2714
2715 void
2716 MidiRegionView::change_note_channel (CanvasNoteEvent* event, int8_t chn, bool relative)
2717 {
2718         uint8_t new_channel;
2719
2720         if (relative) {
2721                 if (chn < 0.0) {
2722                         if (event->note()->channel() < -chn) {
2723                                 new_channel = 0;
2724                         } else {
2725                                 new_channel = event->note()->channel() + chn;
2726                         }
2727                 } else {
2728                         new_channel = event->note()->channel() + chn;
2729                 }
2730         } else {
2731                 new_channel = (uint8_t) chn;
2732         }
2733
2734         note_diff_add_change (event, MidiModel::NoteDiffCommand::Channel, new_channel);
2735 }
2736
2737 void
2738 MidiRegionView::change_note_time (CanvasNoteEvent* event, Evoral::MusicalTime delta, bool relative)
2739 {
2740         Evoral::MusicalTime new_time;
2741
2742         if (relative) {
2743                 if (delta < 0.0) {
2744                         if (event->note()->time() < -delta) {
2745                                 new_time = 0;
2746                         } else {
2747                                 new_time = event->note()->time() + delta;
2748                         }
2749                 } else {
2750                         new_time = event->note()->time() + delta;
2751                 }
2752         } else {
2753                 new_time = delta;
2754         }
2755
2756         note_diff_add_change (event, MidiModel::NoteDiffCommand::StartTime, new_time);
2757 }
2758
2759 void
2760 MidiRegionView::change_note_length (CanvasNoteEvent* event, Evoral::MusicalTime t)
2761 {
2762         note_diff_add_change (event, MidiModel::NoteDiffCommand::Length, t);
2763 }
2764
2765 void
2766 MidiRegionView::change_velocities (bool up, bool fine, bool allow_smush)
2767 {
2768         int8_t delta;
2769
2770         if (_selection.empty()) {
2771                 return;
2772         }
2773
2774         if (fine) {
2775                 delta = 1;
2776         } else {
2777                 delta = 10;
2778         }
2779
2780         if (!up) {
2781                 delta = -delta;
2782         }
2783
2784         if (!allow_smush) {
2785                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2786                         if ((*i)->note()->velocity() + delta == 0 || (*i)->note()->velocity() + delta == 127) {
2787                                 return;
2788                         }
2789                 }
2790         }
2791
2792         start_note_diff_command (_("change velocities"));
2793
2794         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
2795                 Selection::iterator next = i;
2796                 ++next;
2797                 change_note_velocity (*i, delta, true);
2798                 i = next;
2799         }
2800
2801         apply_diff();
2802
2803         if (!_selection.empty()) {
2804                 char buf[24];
2805                 snprintf (buf, sizeof (buf), "Vel %d",
2806                           (int) (*_selection.begin())->note()->velocity());
2807                 show_verbose_cursor (buf, 10, 10);
2808         }
2809 }
2810
2811
2812 void
2813 MidiRegionView::transpose (bool up, bool fine, bool allow_smush)
2814 {
2815         if (_selection.empty()) {
2816                 return;
2817         }
2818
2819         int8_t delta;
2820
2821         if (fine) {
2822                 delta = 1;
2823         } else {
2824                 delta = 12;
2825         }
2826
2827         if (!up) {
2828                 delta = -delta;
2829         }
2830
2831         if (!allow_smush) {
2832                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2833                         if (!up) {
2834                                 if ((int8_t) (*i)->note()->note() + delta <= 0) {
2835                                         return;
2836                                 }
2837                         } else {
2838                                 if ((int8_t) (*i)->note()->note() + delta > 127) {
2839                                         return;
2840                                 }
2841                         }
2842                 }
2843         }
2844
2845         start_note_diff_command (_("transpose"));
2846
2847         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
2848                 Selection::iterator next = i;
2849                 ++next;
2850                 change_note_note (*i, delta, true);
2851                 i = next;
2852         }
2853
2854         apply_diff ();
2855 }
2856
2857 void
2858 MidiRegionView::change_note_lengths (bool fine, bool shorter, Evoral::MusicalTime delta, bool start, bool end)
2859 {
2860         if (delta == 0.0) {
2861                 if (fine) {
2862                         delta = 1.0/128.0;
2863                 } else {
2864                         /* grab the current grid distance */
2865                         bool success;
2866                         delta = trackview.editor().get_grid_type_as_beats (success, _region->position());
2867                         if (!success) {
2868                                 /* XXX cannot get grid type as beats ... should always be possible ... FIX ME */
2869                                 cerr << "Grid type not available as beats - TO BE FIXED\n";
2870                                 return;
2871                         }
2872                 }
2873         }
2874
2875         if (shorter) {
2876                 delta = -delta;
2877         }
2878
2879         start_note_diff_command (_("change note lengths"));
2880
2881         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
2882                 Selection::iterator next = i;
2883                 ++next;
2884
2885                 /* note the negation of the delta for start */
2886
2887                 trim_note (*i, (start ? -delta : 0), (end ? delta : 0));
2888                 i = next;
2889         }
2890
2891         apply_diff ();
2892
2893 }
2894
2895 void
2896 MidiRegionView::nudge_notes (bool forward)
2897 {
2898         if (_selection.empty()) {
2899                 return;
2900         }
2901
2902         /* pick a note as the point along the timeline to get the nudge distance.
2903            its not necessarily the earliest note, so we may want to pull the notes out
2904            into a vector and sort before using the first one.
2905         */
2906
2907         framepos_t ref_point = source_beats_to_absolute_frames ((*(_selection.begin()))->note()->time());
2908         framepos_t unused;
2909         framepos_t distance;
2910
2911         if (trackview.editor().snap_mode() == Editing::SnapOff) {
2912
2913                 /* grid is off - use nudge distance */
2914
2915                 distance = trackview.editor().get_nudge_distance (ref_point, unused);
2916
2917         } else {
2918
2919                 /* use grid */
2920
2921                 framepos_t next_pos = ref_point;
2922
2923                 if (forward) {
2924                         if (max_framepos - 1 < next_pos) {
2925                                 next_pos += 1;
2926                         }
2927                 } else {
2928                         if (next_pos == 0) {
2929                                 return;
2930                         }
2931                         next_pos -= 1;
2932                 }
2933
2934                 trackview.editor().snap_to (next_pos, (forward ? 1 : -1), false);
2935                 distance = ref_point - next_pos;
2936         }
2937
2938         if (distance == 0) {
2939                 return;
2940         }
2941
2942         Evoral::MusicalTime delta = region_frames_to_region_beats (fabs (distance));
2943
2944         if (!forward) {
2945                 delta = -delta;
2946         }
2947
2948         start_note_diff_command (_("nudge"));
2949
2950         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
2951                 Selection::iterator next = i;
2952                 ++next;
2953                 change_note_time (*i, delta, true);
2954                 i = next;
2955         }
2956
2957         apply_diff ();
2958 }
2959
2960 void
2961 MidiRegionView::change_channel(uint8_t channel)
2962 {
2963         start_note_diff_command(_("change channel"));
2964         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2965                 note_diff_add_change (*i, MidiModel::NoteDiffCommand::Channel, channel);
2966         }
2967
2968         apply_diff();
2969 }
2970
2971
2972 void
2973 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
2974 {
2975         Editor* editor = dynamic_cast<Editor*>(&trackview.editor());
2976
2977         _pre_enter_cursor = editor->get_canvas_cursor ();
2978
2979         if (_mouse_state == SelectTouchDragging) {
2980                 note_selected (ev, true);
2981         }
2982
2983         show_verbose_cursor (ev->note ());
2984 }
2985
2986 void
2987 MidiRegionView::note_left (ArdourCanvas::CanvasNoteEvent*)
2988 {
2989         Editor* editor = dynamic_cast<Editor*>(&trackview.editor());
2990
2991         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2992                 (*i)->hide_velocity ();
2993         }
2994
2995         editor->verbose_cursor()->hide ();
2996
2997         if (_pre_enter_cursor) {
2998                 editor->set_canvas_cursor (_pre_enter_cursor);
2999                 _pre_enter_cursor = 0;
3000         }
3001 }
3002
3003 void
3004 MidiRegionView::patch_entered (ArdourCanvas::CanvasPatchChange* ev)
3005 {
3006         ostringstream s;
3007         /* XXX should get patch name if we can */
3008         s << _("Bank:") << (ev->patch()->bank() + MIDI_BP_ZERO) << '\n' << _("Program:") << ((int) ev->patch()->program()) + MIDI_BP_ZERO << '\n' << _("Channel:") << ((int) ev->patch()->channel() + 1);
3009         show_verbose_cursor (s.str(), 10, 20);
3010 }
3011
3012 void
3013 MidiRegionView::patch_left (ArdourCanvas::CanvasPatchChange *)
3014 {
3015         trackview.editor().verbose_cursor()->hide ();
3016 }
3017
3018 void
3019 MidiRegionView::note_mouse_position (float x_fraction, float /*y_fraction*/, bool can_set_cursor)
3020 {
3021         Editor* editor = dynamic_cast<Editor*>(&trackview.editor());
3022
3023         if (x_fraction > 0.0 && x_fraction < 0.25) {
3024                 editor->set_canvas_cursor (editor->cursors()->left_side_trim);
3025         } else if (x_fraction >= 0.75 && x_fraction < 1.0) {
3026                 editor->set_canvas_cursor (editor->cursors()->right_side_trim);
3027         } else {
3028                 if (_pre_enter_cursor && can_set_cursor) {
3029                         editor->set_canvas_cursor (_pre_enter_cursor);
3030                 }
3031         }
3032 }
3033
3034 void
3035 MidiRegionView::set_frame_color()
3036 {
3037         uint32_t f;
3038
3039         TimeAxisViewItem::set_frame_color ();
3040
3041         if (!frame) {
3042                 return;
3043         }
3044
3045         if (_selected) {
3046                 f = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
3047         } else if (high_enough_for_name) {
3048                 f= ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
3049         } else {
3050                 f = fill_color;
3051         }
3052
3053         if (!rect_visible) {
3054                 f = UINT_RGBA_CHANGE_A (f, 0);
3055         }
3056
3057         frame->property_fill_color_rgba() = f;
3058 }
3059
3060 void
3061 MidiRegionView::midi_channel_mode_changed(ChannelMode mode, uint16_t mask)
3062 {
3063         switch (mode) {
3064         case AllChannels:
3065         case FilterChannels:
3066                 _force_channel = -1;
3067                 break;
3068         case ForceChannel:
3069                 _force_channel = mask;
3070                 mask = 0xFFFF; // Show all notes as active (below)
3071         };
3072
3073         // Update notes for selection
3074         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
3075                 (*i)->on_channel_selection_change(mask);
3076         }
3077
3078         _last_channel_selection = mask;
3079
3080         _patch_changes.clear ();
3081         display_patch_changes ();
3082 }
3083
3084 void
3085 MidiRegionView::midi_patch_settings_changed(std::string model, std::string custom_device_mode)
3086 {
3087         _model_name         = model;
3088         _custom_device_mode = custom_device_mode;
3089         redisplay_model();
3090 }
3091
3092 void
3093 MidiRegionView::cut_copy_clear (Editing::CutCopyOp op)
3094 {
3095         if (_selection.empty()) {
3096                 return;
3097         }
3098
3099         PublicEditor& editor (trackview.editor());
3100
3101         switch (op) {
3102         case Delete:
3103                 /* XXX what to do ? */
3104                 break;
3105         case Cut:
3106         case Copy:
3107                 editor.get_cut_buffer().add (selection_as_cut_buffer());
3108                 break;
3109         default:
3110                 break;
3111         }
3112
3113         if (op != Copy) {
3114
3115                 start_note_diff_command();
3116
3117                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
3118                         switch (op) {
3119                         case Copy:
3120                                 break;
3121                         case Delete:
3122                         case Cut:
3123                         case Clear:
3124                                 note_diff_remove_note (*i);
3125                                 break;
3126                         }
3127                 }
3128
3129                 apply_diff();
3130         }
3131 }
3132
3133 MidiCutBuffer*
3134 MidiRegionView::selection_as_cut_buffer () const
3135 {
3136         Notes notes;
3137
3138         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
3139                 NoteType* n = (*i)->note().get();
3140                 notes.insert (boost::shared_ptr<NoteType> (new NoteType (*n)));
3141         }
3142
3143         MidiCutBuffer* cb = new MidiCutBuffer (trackview.session());
3144         cb->set (notes);
3145
3146         return cb;
3147 }
3148
3149 /** This method handles undo */
3150 void
3151 MidiRegionView::paste (framepos_t pos, float times, const MidiCutBuffer& mcb)
3152 {
3153         if (mcb.empty()) {
3154                 return;
3155         }
3156
3157         DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("MIDI paste @ %1 times %2\n", pos, times));
3158
3159         trackview.session()->begin_reversible_command (_("paste"));
3160
3161         start_note_diff_command (_("paste"));
3162
3163         Evoral::MusicalTime beat_delta;
3164         Evoral::MusicalTime paste_pos_beats;
3165         Evoral::MusicalTime duration;
3166         Evoral::MusicalTime end_point = 0;
3167
3168         duration = (*mcb.notes().rbegin())->end_time() - (*mcb.notes().begin())->time();
3169         paste_pos_beats = region_frames_to_region_beats (pos - _region->position());
3170         beat_delta = (*mcb.notes().begin())->time() - paste_pos_beats;
3171         paste_pos_beats = 0;
3172
3173         DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("Paste data spans from %1 to %2 (%3) ; paste pos beats = %4 (based on %5 - %6 ; beat delta = %7\n",
3174                                                        (*mcb.notes().begin())->time(),
3175                                                        (*mcb.notes().rbegin())->end_time(),
3176                                                        duration, pos, _region->position(),
3177                                                        paste_pos_beats, beat_delta));
3178
3179         clear_selection ();
3180
3181         for (int n = 0; n < (int) times; ++n) {
3182
3183                 for (Notes::const_iterator i = mcb.notes().begin(); i != mcb.notes().end(); ++i) {
3184
3185                         boost::shared_ptr<NoteType> copied_note (new NoteType (*((*i).get())));
3186                         copied_note->set_time (paste_pos_beats + copied_note->time() - beat_delta);
3187
3188                         /* make all newly added notes selected */
3189
3190                         note_diff_add_note (copied_note, true);
3191                         end_point = copied_note->end_time();
3192                 }
3193
3194                 paste_pos_beats += duration;
3195         }
3196
3197         /* if we pasted past the current end of the region, extend the region */
3198
3199         framepos_t end_frame = source_beats_to_absolute_frames (end_point);
3200         framepos_t region_end = _region->position() + _region->length() - 1;
3201
3202         if (end_frame > region_end) {
3203
3204                 DEBUG_TRACE (DEBUG::CutNPaste, string_compose ("Paste extended region from %1 to %2\n", region_end, end_frame));
3205
3206                 _region->clear_changes ();
3207                 _region->set_length (end_frame);
3208                 trackview.session()->add_command (new StatefulDiffCommand (_region));
3209         }
3210
3211         apply_diff (true);
3212
3213         trackview.session()->commit_reversible_command ();
3214 }
3215
3216 struct EventNoteTimeEarlyFirstComparator {
3217         bool operator() (CanvasNoteEvent* a, CanvasNoteEvent* b) {
3218                 return a->note()->time() < b->note()->time();
3219         }
3220 };
3221
3222 void
3223 MidiRegionView::time_sort_events ()
3224 {
3225         if (!_sort_needed) {
3226                 return;
3227         }
3228
3229         EventNoteTimeEarlyFirstComparator cmp;
3230         _events.sort (cmp);
3231
3232         _sort_needed = false;
3233 }
3234
3235 void
3236 MidiRegionView::goto_next_note (bool add_to_selection)
3237 {
3238         bool use_next = false;
3239
3240         if (_events.back()->selected()) {
3241                 return;
3242         }
3243
3244         time_sort_events ();
3245
3246         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
3247                 if ((*i)->selected()) {
3248                         use_next = true;
3249                         continue;
3250                 } else if (use_next) {
3251                         if (!add_to_selection) {
3252                                 unique_select (*i);
3253                         } else {
3254                                 note_selected (*i, true, false);
3255                         }
3256                         return;
3257                 }
3258         }
3259
3260         /* use the first one */
3261
3262         unique_select (_events.front());
3263
3264 }
3265
3266 void
3267 MidiRegionView::goto_previous_note (bool add_to_selection)
3268 {
3269         bool use_next = false;
3270
3271         if (_events.front()->selected()) {
3272                 return;
3273         }
3274
3275         time_sort_events ();
3276
3277         for (Events::reverse_iterator i = _events.rbegin(); i != _events.rend(); ++i) {
3278                 if ((*i)->selected()) {
3279                         use_next = true;
3280                         continue;
3281                 } else if (use_next) {
3282                         if (!add_to_selection) {
3283                                 unique_select (*i);
3284                         } else {
3285                                 note_selected (*i, true, false);
3286                         }
3287                         return;
3288                 }
3289         }
3290
3291         /* use the last one */
3292
3293         unique_select (*(_events.rbegin()));
3294 }
3295
3296 void
3297 MidiRegionView::selection_as_notelist (Notes& selected, bool allow_all_if_none_selected)
3298 {
3299         bool had_selected = false;
3300
3301         time_sort_events ();
3302
3303         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
3304                 if ((*i)->selected()) {
3305                         selected.insert ((*i)->note());
3306                         had_selected = true;
3307                 }
3308         }
3309
3310         if (allow_all_if_none_selected && !had_selected) {
3311                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
3312                         selected.insert ((*i)->note());
3313                 }
3314         }
3315 }
3316
3317 void
3318 MidiRegionView::update_ghost_note (double x, double y)
3319 {
3320         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
3321
3322         _last_ghost_x = x;
3323         _last_ghost_y = y;
3324
3325         _note_group->w2i (x, y);
3326
3327         PublicEditor& editor = trackview.editor ();
3328         
3329         framepos_t const unsnapped_frame = editor.pixel_to_frame (x);
3330         framecnt_t grid_frames;
3331         framepos_t const f = snap_frame_to_grid_underneath (unsnapped_frame, grid_frames);
3332         
3333         /* use region_frames... because we are converting a delta within the region
3334         */
3335          
3336         double length = region_frames_to_region_beats (snap_frame_to_frame (f + grid_frames) - f);
3337
3338         /* note that this sets the time of the ghost note in beats relative to
3339            the start of the source; that is how all note times are stored.
3340         */
3341         _ghost_note->note()->set_time (absolute_frames_to_source_beats (f + _region->position ()));
3342         _ghost_note->note()->set_length (length);
3343         _ghost_note->note()->set_note (midi_stream_view()->y_to_note (y));
3344         _ghost_note->note()->set_channel (mtv->get_channel_for_add ());
3345
3346         /* the ghost note does not appear in ghost regions, so pass false in here */
3347         update_note (_ghost_note, false);
3348
3349         show_verbose_cursor (_ghost_note->note ());
3350 }
3351
3352 void
3353 MidiRegionView::create_ghost_note (double x, double y)
3354 {
3355         delete _ghost_note;
3356         _ghost_note = 0;
3357
3358         boost::shared_ptr<NoteType> g (new NoteType);
3359         _ghost_note = new NoEventCanvasNote (*this, *_note_group, g);
3360         _ghost_note->property_outline_color_rgba() = 0x000000aa;
3361         update_ghost_note (x, y);
3362         _ghost_note->show ();
3363
3364         _last_ghost_x = x;
3365         _last_ghost_y = y;
3366
3367         show_verbose_cursor (_ghost_note->note ());
3368 }
3369
3370 void
3371 MidiRegionView::snap_changed ()
3372 {
3373         if (!_ghost_note) {
3374                 return;
3375         }
3376
3377         create_ghost_note (_last_ghost_x, _last_ghost_y);
3378 }
3379
3380 void
3381 MidiRegionView::drop_down_keys ()
3382 {
3383         _mouse_state = None;
3384 }
3385
3386 void
3387 MidiRegionView::maybe_select_by_position (GdkEventButton* ev, double /*x*/, double y)
3388 {
3389         double note = midi_stream_view()->y_to_note(y);
3390         Events e;
3391         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
3392
3393         uint16_t chn_mask = mtv->channel_selector().get_selected_channels();
3394
3395         if (Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)) {
3396                 get_events (e, Evoral::Sequence<Evoral::MusicalTime>::PitchGreaterThanOrEqual, (uint8_t) floor (note), chn_mask);
3397         } else if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
3398                 get_events (e, Evoral::Sequence<Evoral::MusicalTime>::PitchLessThanOrEqual, (uint8_t) floor (note), chn_mask);
3399         } else {
3400                 return;
3401         }
3402
3403         bool add_mrv_selection = false;
3404
3405         if (_selection.empty()) {
3406                 add_mrv_selection = true;
3407         }
3408
3409         for (Events::iterator i = e.begin(); i != e.end(); ++i) {
3410                 if (_selection.insert (*i).second) {
3411                         (*i)->set_selected (true);
3412                 }
3413         }
3414
3415         if (add_mrv_selection) {
3416                 PublicEditor& editor (trackview.editor());
3417                 editor.get_selection().add (this);
3418         }
3419 }
3420
3421 void
3422 MidiRegionView::color_handler ()
3423 {
3424         RegionView::color_handler ();
3425
3426         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
3427                 (*i)->set_selected ((*i)->selected()); // will change color
3428         }
3429
3430         /* XXX probably more to do here */
3431 }
3432
3433 void
3434 MidiRegionView::enable_display (bool yn)
3435 {
3436         RegionView::enable_display (yn);
3437         if (yn) {
3438                 redisplay_model ();
3439         }
3440 }
3441
3442 void
3443 MidiRegionView::show_step_edit_cursor (Evoral::MusicalTime pos)
3444 {
3445         if (_step_edit_cursor == 0) {
3446                 ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
3447
3448                 _step_edit_cursor = new ArdourCanvas::SimpleRect (*group);
3449                 _step_edit_cursor->property_y1() = 0;
3450                 _step_edit_cursor->property_y2() = midi_stream_view()->contents_height();
3451                 _step_edit_cursor->property_fill_color_rgba() = RGBA_TO_UINT (45,0,0,90);
3452                 _step_edit_cursor->property_outline_color_rgba() = RGBA_TO_UINT (85,0,0,90);
3453         }
3454
3455         move_step_edit_cursor (pos);
3456         _step_edit_cursor->show ();
3457 }
3458
3459 void
3460 MidiRegionView::move_step_edit_cursor (Evoral::MusicalTime pos)
3461 {
3462         _step_edit_cursor_position = pos;
3463
3464         if (_step_edit_cursor) {
3465                 double pixel = trackview.editor().frame_to_pixel (region_beats_to_region_frames (pos));
3466                 _step_edit_cursor->property_x1() = pixel;
3467                 set_step_edit_cursor_width (_step_edit_cursor_width);
3468         }
3469 }
3470
3471 void
3472 MidiRegionView::hide_step_edit_cursor ()
3473 {
3474         if (_step_edit_cursor) {
3475                 _step_edit_cursor->hide ();
3476         }
3477 }
3478
3479 void
3480 MidiRegionView::set_step_edit_cursor_width (Evoral::MusicalTime beats)
3481 {
3482         _step_edit_cursor_width = beats;
3483
3484         if (_step_edit_cursor) {
3485                 _step_edit_cursor->property_x2() = _step_edit_cursor->property_x1() + trackview.editor().frame_to_pixel (region_beats_to_region_frames (beats));
3486         }
3487 }
3488
3489 /** Called when a diskstream on our track has received some data.  Update the view, if applicable.
3490  *  @param buf Data that has been recorded.
3491  *  @param w Source that this data will end up in.
3492  */
3493 void
3494 MidiRegionView::data_recorded (boost::shared_ptr<MidiBuffer> buf, boost::weak_ptr<MidiSource> w)
3495 {
3496         if (!_active_notes) {
3497                 /* we aren't actively being recorded to */
3498                 return;
3499         }
3500
3501         boost::shared_ptr<MidiSource> src = w.lock ();
3502         if (!src || src != midi_region()->midi_source()) {
3503                 /* recorded data was not destined for our source */
3504                 return;
3505         }
3506
3507         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*> (&trackview);
3508         BeatsFramesConverter converter (trackview.session()->tempo_map(), mtv->midi_track()->get_capture_start_frame (0));
3509
3510         framepos_t back = max_framepos;
3511
3512         for (MidiBuffer::iterator i = buf->begin(); i != buf->end(); ++i) {
3513                 Evoral::MIDIEvent<MidiBuffer::TimeType> const ev (*i, false);
3514                 assert (ev.buffer ());
3515
3516                 Evoral::MusicalTime const time_beats = converter.from (ev.time () - converter.origin_b ());
3517
3518                 if (ev.type() == MIDI_CMD_NOTE_ON) {
3519
3520                         boost::shared_ptr<NoteType> note (
3521                                 new NoteType (ev.channel(), time_beats, 0, ev.note(), ev.velocity())
3522                                                           );
3523
3524                         add_note (note, true);
3525
3526                         /* fix up our note range */
3527                         if (ev.note() < _current_range_min) {
3528                                 midi_stream_view()->apply_note_range (ev.note(), _current_range_max, true);
3529                         } else if (ev.note() > _current_range_max) {
3530                                 midi_stream_view()->apply_note_range (_current_range_min, ev.note(), true);
3531                         }
3532
3533                 } else if (ev.type() == MIDI_CMD_NOTE_OFF) {
3534                         resolve_note (ev.note (), time_beats);
3535                 }
3536
3537                 back = ev.time ();
3538         }
3539
3540         midi_stream_view()->check_record_layers (region(), back);
3541 }
3542
3543 void
3544 MidiRegionView::trim_front_starting ()
3545 {
3546         /* Reparent the note group to the region view's parent, so that it doesn't change
3547            when the region view is trimmed.
3548         */
3549         _temporary_note_group = new ArdourCanvas::Group (*group->property_parent ());
3550         _temporary_note_group->move (group->property_x(), group->property_y());
3551         _note_group->reparent (*_temporary_note_group);
3552 }
3553
3554 void
3555 MidiRegionView::trim_front_ending ()
3556 {
3557         _note_group->reparent (*group);
3558         delete _temporary_note_group;
3559         _temporary_note_group = 0;
3560
3561         if (_region->start() < 0) {
3562                 /* Trim drag made start time -ve; fix this */
3563                 midi_region()->fix_negative_start ();
3564         }
3565 }
3566
3567 void
3568 MidiRegionView::edit_patch_change (ArdourCanvas::CanvasPatchChange* pc)
3569 {
3570         PatchChangeDialog d (&_source_relative_time_converter, trackview.session(), *pc->patch (), Gtk::Stock::APPLY);
3571         if (d.run () != Gtk::RESPONSE_ACCEPT) {
3572                 return;
3573         }
3574
3575         change_patch_change (pc->patch(), d.patch ());
3576 }
3577
3578
3579 void
3580 MidiRegionView::show_verbose_cursor (boost::shared_ptr<NoteType> n) const
3581 {
3582         char buf[24];
3583         snprintf (buf, sizeof (buf), "%s (%d) Chn %d\nVel %d",
3584                   Evoral::midi_note_name (n->note()).c_str(),
3585                   (int) n->note (),
3586                   (int) n->channel() + 1,
3587                   (int) n->velocity());
3588
3589         show_verbose_cursor (buf, 10, 20);
3590 }
3591
3592 void
3593 MidiRegionView::show_verbose_cursor (string const & text, double xoffset, double yoffset) const
3594 {
3595         double wx, wy;
3596
3597         trackview.editor().get_pointer_position (wx, wy);
3598
3599         wx += xoffset;
3600         wy += yoffset;
3601
3602         /* Flip the cursor above the mouse pointer if it would overlap the bottom of the canvas */
3603
3604         double x1, y1, x2, y2;
3605         trackview.editor().verbose_cursor()->canvas_item()->get_bounds (x1, y1, x2, y2);
3606
3607         if ((wy + y2 - y1) > trackview.editor().canvas_height()) {
3608                 wy -= (y2 - y1) + 2 * yoffset;
3609         }
3610
3611         trackview.editor().verbose_cursor()->set (text, wx, wy);
3612         trackview.editor().verbose_cursor()->show ();
3613 }
3614
3615 /** @param p A session framepos.
3616  *  @param grid_frames Filled in with the number of frames that a grid interval is at p.
3617  *  @return p snapped to the grid subdivision underneath it.
3618  */
3619 framepos_t
3620 MidiRegionView::snap_frame_to_grid_underneath (framepos_t p, framecnt_t& grid_frames) const
3621 {
3622         PublicEditor& editor = trackview.editor ();
3623         
3624         bool success;
3625         Evoral::MusicalTime grid_beats = editor.get_grid_type_as_beats (success, p);
3626
3627         if (!success) {
3628                 grid_beats = 1;
3629         }
3630         
3631         grid_frames = region_beats_to_region_frames (grid_beats);
3632
3633         /* Hack so that we always snap to the note that we are over, instead of snapping
3634            to the next one if we're more than halfway through the one we're over.
3635         */
3636         if (editor.snap_mode() == SnapNormal && p >= grid_frames / 2) {
3637                 p -= grid_frames / 2;
3638         }
3639
3640         return snap_frame_to_frame (p);
3641 }
3642
3643 /** Called when the selection has been cleared in any MidiRegionView.
3644  *  @param rv MidiRegionView that the selection was cleared in.
3645  */
3646 void
3647 MidiRegionView::selection_cleared (MidiRegionView* rv)
3648 {
3649         if (rv == this) {
3650                 return;
3651         }
3652
3653         /* Clear our selection in sympathy; but don't signal the fact */
3654         clear_selection (false);
3655 }