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