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