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