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