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