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