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