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