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