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