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