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