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