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