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