more MIDI editing tweaks ; flip mouse mode buttons around for MIDI so that "object...
[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 (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                 const double x = trackview.editor().frame_to_pixel(beats_to_frames(time));
765                 
766                 double height = midi_stream_view()->contents_height();
767                 
768                 boost::shared_ptr<CanvasSysEx> sysex = boost::shared_ptr<CanvasSysEx>(
769                                 new CanvasSysEx(*this, *group, text, height, x, 1.0));
770                 
771                 // Show unless program change is beyond the region bounds
772                 if (time - _region->start() >= _region->length() || time < _region->start()) {
773                         sysex->hide();
774                 } else {
775                         sysex->show();
776                 }
777                 
778                 _sys_exes.push_back(sysex);
779         }
780 }
781
782
783 MidiRegionView::~MidiRegionView ()
784 {
785         in_destructor = true;
786
787         RegionViewGoingAway (this); /* EMIT_SIGNAL */
788
789         if (_active_notes) {
790                 end_write();
791         }
792
793         _selection.clear();
794         clear_events();
795         delete _note_group;
796         delete _delta_command;
797 }
798
799 void
800 MidiRegionView::region_resized (Change what_changed)
801 {
802         RegionView::region_resized(what_changed);
803         
804         if (what_changed & ARDOUR::PositionChanged) {
805                 set_duration(_region->length(), 0);
806                 if (_enable_display) {
807                         redisplay_model();
808                 }
809         } 
810 }
811
812 void
813 MidiRegionView::reset_width_dependent_items (double pixel_width)
814 {
815         RegionView::reset_width_dependent_items(pixel_width);
816         assert(_pixel_width == pixel_width);
817
818         if (_enable_display) {
819                 redisplay_model();
820         }
821 }
822
823 void
824 MidiRegionView::set_height (double height)
825 {
826         static const double FUDGE = 2.0;
827         const double old_height = _height;
828         RegionView::set_height(height);
829         _height = height - FUDGE;
830         
831         apply_note_range(midi_stream_view()->lowest_note(),
832                          midi_stream_view()->highest_note(),
833                          height != old_height + FUDGE);
834         
835         if (name_pixbuf) {
836                 name_pixbuf->raise_to_top();
837         }
838 }
839
840
841 /** Apply the current note range from the stream view
842  * by repositioning/hiding notes as necessary
843  */
844 void
845 MidiRegionView::apply_note_range (uint8_t min, uint8_t max, bool force)
846 {
847         if (!_enable_display) {
848                 return;
849         }
850
851         if (!force && _current_range_min == min && _current_range_max == max) {
852                 return;
853         }
854         
855         _current_range_min = min;
856         _current_range_max = max;
857
858         for (Events::const_iterator i = _events.begin(); i != _events.end(); ++i) {
859                 CanvasNoteEvent* event = *i;
860                 Item* item = dynamic_cast<Item*>(event);
861                 assert(item);
862                 if (event && event->note()) {
863                         if (event->note()->note() < _current_range_min
864                                         || event->note()->note() > _current_range_max) {
865                                 if (canvas_item_visible(item)) {
866                                         item->hide();
867                                 }
868                         } else {
869                                 if (!canvas_item_visible(item)) {
870                                         item->show();
871                                 }
872
873                                 if (CanvasNote* note = dynamic_cast<CanvasNote*>(event)) {
874                                         const double y1 = midi_stream_view()->note_to_y(event->note()->note());
875                                         const double y2 = y1 + floor(midi_stream_view()->note_height());
876
877                                         note->property_y1() = y1;
878                                         note->property_y2() = y2;
879                                 } else if (CanvasHit* hit = dynamic_cast<CanvasHit*>(event)) {
880                                         double x = trackview.editor().frame_to_pixel(
881                                                         beats_to_frames(event->note()->time()) - _region->start());
882                                         const double diamond_size = midi_stream_view()->note_height() / 2.0;
883                                         double y = midi_stream_view()->note_to_y(event->note()->note()) 
884                                                          + ((diamond_size-2.0) / 4.0);
885                                         
886                                         hit->set_height(diamond_size);
887                                         hit->move(x-hit->x1(), y-hit->y1());
888                                         hit->show();
889                                 }
890                         }
891                 }
892         }
893         
894 }
895
896 GhostRegion*
897 MidiRegionView::add_ghost (TimeAxisView& tv)
898 {
899         CanvasNote* note;
900
901         double unit_position = _region->position () / samples_per_unit;
902         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
903         MidiGhostRegion* ghost;
904
905         if (mtv && mtv->midi_view()) {
906                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group
907                    to allow having midi notes on top of note lines and waveforms.
908                  */
909                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
910         } else {
911                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
912         }
913
914         ghost->set_height ();
915         ghost->set_duration (_region->length() / samples_per_unit);
916         ghosts.push_back (ghost);
917
918         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
919                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
920                         ghost->add_note(note);
921                 }
922         }
923
924         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
925
926         return ghost;
927 }
928
929
930 /** Begin tracking note state for successive calls to add_event
931  */
932 void
933 MidiRegionView::begin_write()
934 {
935         assert(!_active_notes);
936         _active_notes = new CanvasNote*[128];
937         for (unsigned i=0; i < 128; ++i) {
938                 _active_notes[i] = NULL;
939         }
940 }
941
942
943 /** Destroy note state for add_event
944  */
945 void
946 MidiRegionView::end_write()
947 {
948         delete[] _active_notes;
949         _active_notes = NULL;
950         _marked_for_selection.clear();
951         _marked_for_velocity.clear();
952 }
953
954
955 /** Resolve an active MIDI note (while recording).
956  */
957 void
958 MidiRegionView::resolve_note(uint8_t note, double end_time)
959 {
960         if (midi_view()->note_mode() != Sustained) {
961                 return;
962         }
963
964         if (_active_notes && _active_notes[note]) {
965                 const nframes64_t end_time_frames = beats_to_frames(end_time);
966                 _active_notes[note]->property_x2() = trackview.editor().frame_to_pixel(end_time_frames);
967                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
968                 _active_notes[note] = NULL;
969         }
970 }
971
972
973 /** Extend active notes to rightmost edge of region (if length is changed)
974  */
975 void
976 MidiRegionView::extend_active_notes()
977 {
978         if (!_active_notes) {
979                 return;
980         }
981
982         for (unsigned i=0; i < 128; ++i) {
983                 if (_active_notes[i]) {
984                         _active_notes[i]->property_x2() = trackview.editor().frame_to_pixel(_region->length());
985                 }
986         }
987 }
988
989 void 
990 MidiRegionView::play_midi_note(boost::shared_ptr<NoteType> note)
991 {
992         if (!trackview.editor().sound_notes()) {
993                 return;
994         }
995
996         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
997         assert(route_ui);
998         
999         route_ui->midi_track()->write_immediate_event(
1000                         note->on_event().size(), note->on_event().buffer());
1001         
1002         const double note_length_beats = (note->off_event().time() - note->on_event().time());
1003         nframes_t note_length_ms = beats_to_frames(note_length_beats)
1004                         * (1000 / (double)route_ui->session().nominal_frame_rate());
1005         Glib::signal_timeout().connect(bind(mem_fun(this, &MidiRegionView::play_midi_note_off), note),
1006                         note_length_ms, G_PRIORITY_DEFAULT);
1007 }
1008
1009 bool
1010 MidiRegionView::play_midi_note_off(boost::shared_ptr<NoteType> note)
1011 {
1012         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
1013         assert(route_ui);
1014         
1015         route_ui->midi_track()->write_immediate_event(
1016                         note->off_event().size(), note->off_event().buffer());
1017
1018         return false;
1019 }
1020
1021 bool
1022 MidiRegionView::note_in_visible_range(const boost::shared_ptr<NoteType> note) const
1023 {
1024         const nframes64_t note_start_frames = beats_to_frames(note->time());
1025         bool outside = (note_start_frames - _region->start() >= _region->length())
1026                         || (note_start_frames < _region->start())
1027                         || (note->note() < midi_stream_view()->lowest_note())
1028                         || (note->note() > midi_stream_view()->highest_note());
1029         return !outside;
1030 }
1031
1032 /** Add a MIDI note to the view (with length).
1033  *
1034  * If in sustained mode, notes with length 0 will be considered active
1035  * notes, and resolve_note should be called when the corresponding note off
1036  * event arrives, to properly display the note.
1037  */
1038 void
1039 MidiRegionView::add_note(const boost::shared_ptr<NoteType> note)
1040 {
1041         assert(note->time() >= 0);
1042         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
1043
1044         const nframes64_t note_start_frames = beats_to_frames(note->time());
1045         const nframes64_t note_end_frames   = beats_to_frames(note->end_time());
1046
1047         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
1048
1049         CanvasNoteEvent* event = 0;
1050         
1051         const double x = trackview.editor().frame_to_pixel(note_start_frames - _region->start());
1052         
1053         if (midi_view()->note_mode() == Sustained) {
1054                 const double y1 = midi_stream_view()->note_to_y(note->note());
1055                 const double note_endpixel = 
1056                         trackview.editor().frame_to_pixel(note_end_frames - _region->start());
1057                 
1058                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
1059                 ev_rect->property_x1() = x;
1060                 ev_rect->property_y1() = y1;
1061                 if (note->length() > 0) {
1062                         ev_rect->property_x2() = note_endpixel;
1063                 } else {
1064                         ev_rect->property_x2() = trackview.editor().frame_to_pixel(_region->length());
1065                 }
1066                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
1067
1068                 if (note->length() == 0) {
1069                         if (_active_notes) {
1070                                 assert(note->note() < 128);
1071                                 // If this note is already active there's a stuck note,
1072                                 // finish the old note rectangle
1073                                 if (_active_notes[note->note()]) {
1074                                         CanvasNote* const old_rect = _active_notes[note->note()];
1075                                         boost::shared_ptr<NoteType> old_note = old_rect->note();
1076                                         old_rect->property_x2() = x;
1077                                         old_rect->property_outline_what() = (guint32) 0xF;
1078                                 }
1079                                 _active_notes[note->note()] = ev_rect;
1080                         }
1081                         /* outline all but right edge */
1082                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
1083                 } else {
1084                         /* outline all edges */
1085                         ev_rect->property_outline_what() = (guint32) 0xF;
1086                 }
1087
1088                 event = ev_rect;
1089
1090                 MidiGhostRegion* gr;
1091                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
1092                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
1093                                 gr->add_note(ev_rect);
1094                         }
1095                 }
1096
1097         } else if (midi_view()->note_mode() == Percussive) {
1098                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
1099                 const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
1100
1101                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size, note);
1102                 ev_diamond->move(x, y);
1103                 event = ev_diamond;
1104         } else {
1105                 event = 0;
1106         }
1107
1108         if (event) {
1109                 if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
1110                         note_selected(event, true);
1111                 } 
1112
1113                 if (_marked_for_velocity.find(note) != _marked_for_velocity.end()) {
1114                         event->show_velocity();
1115                 }
1116                 event->on_channel_selection_change(_last_channel_selection);
1117                 _events.push_back(event);
1118
1119                 if (note_in_visible_range(note)) {
1120                         event->show();
1121                 } else {
1122                         event->hide ();
1123                 }
1124         }
1125 }
1126
1127 void
1128 MidiRegionView::add_pgm_change(PCEvent& program, const string& displaytext)
1129 {
1130         assert(program.time >= 0);
1131         
1132         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
1133         const double x = trackview.editor().frame_to_pixel(beats_to_frames(program.time));
1134         
1135         double height = midi_stream_view()->contents_height();
1136         
1137         boost::shared_ptr<CanvasProgramChange> pgm_change = boost::shared_ptr<CanvasProgramChange>(
1138                         new CanvasProgramChange(*this, *group,
1139                                         displaytext, 
1140                                         height, 
1141                                         x, 1.0, 
1142                                         _model_name, 
1143                                         _custom_device_mode, 
1144                                         program.time, program.channel, program.value));
1145         
1146         // Show unless program change is beyond the region bounds
1147         if (program.time - _region->start() >= _region->length() || program.time < _region->start()) {
1148                 pgm_change->hide();
1149         } else {
1150                 pgm_change->show();
1151         }
1152         
1153         _pgm_changes.push_back(pgm_change);
1154 }
1155
1156 void
1157 MidiRegionView::get_patch_key_at(double time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
1158 {
1159         cerr << "getting patch key at " << time << " for channel " << channel << endl;
1160         Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
1161         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1162         float msb = -1.0;
1163         if (msb_control != 0) {
1164                 msb = int(msb_control->get_float(true, time));
1165                 cerr << "got msb " << msb;
1166         }
1167
1168         Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
1169         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1170         float lsb = -1.0;
1171         if (lsb_control != 0) {
1172                 lsb = lsb_control->get_float(true, time);
1173                 cerr << " got lsb " << lsb;
1174         }
1175         
1176         Evoral::Parameter program_change(MidiPgmChangeAutomation, channel, 0);
1177         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1178         float program_number = -1.0;
1179         if (program_control != 0) {
1180                 program_number = program_control->get_float(true, time);
1181                 cerr << " got program " << program_number << endl;
1182         }
1183         
1184         key.msb = (int) floor(msb + 0.5);
1185         key.lsb = (int) floor(lsb + 0.5);
1186         key.program_number = (int) floor(program_number + 0.5);
1187         assert(key.is_sane());
1188 }
1189
1190
1191 void 
1192 MidiRegionView::alter_program_change(PCEvent& old_program, const MIDI::Name::PatchPrimaryKey& new_patch)
1193 {
1194         // TODO: Get the real event here and alter them at the original times
1195         Evoral::Parameter bank_select_msb(MidiCCAutomation, old_program.channel, MIDI_CTL_MSB_BANK);
1196         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1197         if (msb_control != 0) {
1198                 msb_control->set_float(float(new_patch.msb), true, old_program.time);
1199         }
1200
1201         // TODO: Get the real event here and alter them at the original times
1202         Evoral::Parameter bank_select_lsb(MidiCCAutomation, old_program.channel, MIDI_CTL_LSB_BANK);
1203         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1204         if (lsb_control != 0) {
1205                 lsb_control->set_float(float(new_patch.lsb), true, old_program.time);
1206         }
1207         
1208         Evoral::Parameter program_change(MidiPgmChangeAutomation, old_program.channel, 0);
1209         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1210         
1211         assert(program_control != 0);
1212         program_control->set_float(float(new_patch.program_number), true, old_program.time);
1213         
1214         redisplay_model();
1215 }
1216
1217 void
1218 MidiRegionView::program_selected(CanvasProgramChange& program, const MIDI::Name::PatchPrimaryKey& new_patch)
1219 {
1220         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1221         alter_program_change(program_change_event, new_patch);
1222 }
1223
1224 void 
1225 MidiRegionView::previous_program(CanvasProgramChange& program)
1226 {
1227         MIDI::Name::PatchPrimaryKey key;
1228         get_patch_key_at(program.event_time(), program.channel(), key);
1229         
1230         boost::shared_ptr<MIDI::Name::Patch> patch = 
1231                 MIDI::Name::MidiPatchManager::instance().previous_patch(
1232                                 _model_name,
1233                                 _custom_device_mode, 
1234                                 program.channel(), 
1235                                 key);
1236         
1237         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1238         if (patch) {
1239                 alter_program_change(program_change_event, patch->patch_primary_key());
1240         }
1241 }
1242
1243 void 
1244 MidiRegionView::next_program(CanvasProgramChange& program)
1245 {
1246         MIDI::Name::PatchPrimaryKey key;
1247         get_patch_key_at(program.event_time(), program.channel(), key);
1248         
1249         boost::shared_ptr<MIDI::Name::Patch> patch = 
1250                 MIDI::Name::MidiPatchManager::instance().next_patch(
1251                                 _model_name,
1252                                 _custom_device_mode, 
1253                                 program.channel(), 
1254                                 key);   
1255
1256         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1257         if (patch) {
1258                 alter_program_change(program_change_event, patch->patch_primary_key());
1259         }
1260 }
1261
1262 void
1263 MidiRegionView::delete_selection()
1264 {
1265         if (_selection.empty()) {
1266                 return;
1267         }
1268
1269         start_delta_command (_("delete selection"));
1270
1271         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1272                 if ((*i)->selected()) {
1273                         _delta_command->remove((*i)->note());
1274                 }
1275         }
1276
1277         _selection.clear();
1278
1279         apply_command ();
1280 }
1281
1282 void
1283 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasNoteEvent* ev)
1284 {
1285         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1286                 if ((*i)->selected() && (*i) != ev) {
1287                         (*i)->selected(false);
1288                         (*i)->hide_velocity();
1289                 }
1290         }
1291
1292         _selection.clear();
1293 }
1294
1295 void
1296 MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
1297 {
1298         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
1299
1300                 Selection::iterator tmp = i;
1301                 ++tmp;
1302
1303                 if ((*i) != ev) {
1304                         remove_from_selection (*i);
1305                 } 
1306
1307                 i = tmp;
1308         }
1309
1310         if (!ev->selected()) {
1311                 add_to_selection (ev);
1312         }
1313 }
1314
1315 void
1316 MidiRegionView::note_selected(ArdourCanvas::CanvasNoteEvent* ev, bool add, bool extend)
1317 {
1318         if (!add) {
1319                 clear_selection_except(ev);
1320         }
1321
1322         if (!extend) {
1323
1324                 if (!ev->selected()) {
1325                         add_to_selection (ev);
1326                 }
1327
1328         } else {
1329                 /* find end of latest note selected, select all between that and the start of "ev" */
1330
1331                 Evoral::MusicalTime earliest = DBL_MAX;
1332                 Evoral::MusicalTime latest = 0;
1333
1334                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1335                         if ((*i)->note()->end_time() > latest) {
1336                                 latest = (*i)->note()->end_time();
1337                         } 
1338                         if ((*i)->note()->time() < earliest) {
1339                                 earliest = (*i)->note()->time();
1340                         }
1341                 }
1342
1343                 if (ev->note()->end_time() > latest) {
1344                         latest = ev->note()->end_time();
1345                 }
1346
1347                 if (ev->note()->time() < earliest) {
1348                         earliest = ev->note()->time();
1349                 }
1350
1351
1352                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {           
1353                         
1354                         /* find notes entirely within OR spanning the earliest..latest range */
1355
1356                         if (((*i)->note()->time() >= earliest && (*i)->note()->end_time() <= latest) ||
1357                             ((*i)->note()->time() <= earliest && (*i)->note()->end_time() >= latest)) {
1358                                 add_to_selection (*i);
1359                         }                       
1360
1361                         if ((*i)->note()->time() > latest) {
1362                                 break;
1363                         }
1364                 }
1365         }
1366 }
1367
1368
1369 void
1370 MidiRegionView::note_deselected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1371 {
1372         if (!add) {
1373                 clear_selection_except(ev);
1374         }
1375
1376         remove_from_selection (ev);
1377 }
1378
1379
1380 void
1381 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2)
1382 {
1383         const double last_y = std::min(y1, y2);
1384         const double y      = std::max(y1, y2);
1385
1386         // TODO: Make this faster by storing the last updated selection rect, and only
1387         // adjusting things that are in the area that appears/disappeared.
1388         // We probably need a tree to be able to find events in O(log(n)) time.
1389
1390 #ifndef NDEBUG
1391         double last_x1 = 0.0;
1392 #endif
1393
1394         if (x1 < x2) {
1395                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1396 #ifndef NDEBUG
1397                         // Events should always be sorted by increasing x1() here
1398                         assert((*i)->x1() >= last_x1);
1399                         last_x1 = (*i)->x1();
1400 #endif
1401                         if ((*i)->x1() >= x1 && (*i)->x1() <= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1402                                 // Inside rectangle
1403                                 add_to_selection (*i);
1404                         } else if ((*i)->selected()) {
1405                                 // Not inside rectangle
1406                                 remove_from_selection (*i);
1407                         }
1408                 }
1409         } else {
1410                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1411 #ifndef NDEBUG
1412                         // Events should always be sorted by increasing x1() here
1413                         assert((*i)->x1() >= last_x1);
1414                         last_x1 = (*i)->x1();
1415 #endif
1416                         if ((*i)->x2() <= x1 && (*i)->x2() >= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1417                                 // Inside rectangle
1418                                 add_to_selection (*i);
1419                         } else if ((*i)->selected()) {
1420                                 // Not inside rectangle
1421                                 remove_from_selection (*i);
1422                         }
1423                 }
1424         }
1425 }
1426
1427 void
1428 MidiRegionView::remove_from_selection (CanvasNoteEvent* ev)
1429 {
1430         Selection::iterator i = _selection.find (ev);
1431
1432         if (i != _selection.end()) {
1433                 _selection.erase (i);
1434         }
1435
1436         ev->selected (false);
1437         ev->hide_velocity ();
1438         
1439         if (_selection.empty()) {
1440                 PublicEditor& editor (trackview.editor());
1441                 editor.get_selection().remove (this);
1442         }
1443 }
1444
1445 void
1446 MidiRegionView::add_to_selection (CanvasNoteEvent* ev)
1447 {
1448         bool add_mrv_selection = false;
1449
1450         if (_selection.empty()) {
1451                 add_mrv_selection = true;
1452         }
1453
1454         if (_selection.insert (ev).second) {
1455                 ev->selected (true);
1456                 play_midi_note ((ev)->note());
1457         }
1458
1459         if (add_mrv_selection) {
1460                 PublicEditor& editor (trackview.editor());
1461                 editor.get_selection().add (this);
1462         }
1463 }
1464
1465 void
1466 MidiRegionView::move_selection(double dx, double dy)
1467 {
1468         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1469                 (*i)->move_event(dx, dy);
1470         }
1471 }
1472
1473 void
1474 MidiRegionView::note_dropped(CanvasNoteEvent* ev, double dt, uint8_t dnote)
1475 {
1476         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
1477         if (_selection.find(ev) == _selection.end()) {
1478                 return;
1479         }
1480
1481         uint8_t lowest_note_in_selection  = midi_stream_view()->lowest_note();
1482         uint8_t highest_note_in_selection = midi_stream_view()->highest_note();
1483         uint8_t highest_note_difference = 0;
1484
1485         // find highest and lowest notes first
1486         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1487                 uint8_t pitch = (*i)->note()->note();
1488                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
1489                 highest_note_in_selection = std::max(highest_note_in_selection, pitch);
1490         }
1491         
1492         /*
1493         cerr << "dnote: " << (int) dnote << endl;
1494         cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note()) 
1495              << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
1496         cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): " 
1497              << int(highest_note_in_selection) << endl;
1498         cerr << "selection size: " << _selection.size() << endl;
1499         cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
1500         */
1501         
1502         // Make sure the note pitch does not exceed the MIDI standard range
1503         if (dnote <= 127 && (highest_note_in_selection + dnote > 127)) {
1504                 highest_note_difference = highest_note_in_selection - 127;
1505         }
1506         
1507         start_delta_command(_("move notes"));
1508
1509         for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
1510                 Selection::iterator next = i;
1511                 ++next;
1512
1513                 const boost::shared_ptr<NoteType> copy(new NoteType(*(*i)->note().get()));
1514
1515                 nframes64_t start_frames = beats_to_frames((*i)->note()->time());
1516
1517                 cerr << "starting at " << (*i)->note()->time() 
1518                      << " (" << start_frames << ") delta on drag = " << dt << endl;
1519
1520                 if (dt >= 0) {
1521                         cerr << "Motion was " << snap_frame_to_frame(trackview.editor().pixel_to_frame(dt)) << endl;
1522                         start_frames += snap_frame_to_frame(trackview.editor().pixel_to_frame(dt));
1523                 } else {
1524                         cerr << "rev Motion was " << snap_frame_to_frame(trackview.editor().pixel_to_frame(dt)) << endl;
1525                         start_frames -= snap_frame_to_frame(trackview.editor().pixel_to_frame(-dt));
1526                 }
1527
1528                 cerr << "start frame will be " << start_frames << " vs. region " 
1529                      << _region->position ()
1530                      << endl;
1531
1532                 Evoral::MusicalTime new_time = frames_to_beats(start_frames);
1533
1534                 if (new_time < 0) {
1535                         i = next;
1536                         continue;
1537                 }
1538
1539                 copy->set_time (new_time);
1540
1541                 cerr << "copy time = " << copy->time() << endl;
1542
1543                 uint8_t original_pitch = (*i)->note()->note();
1544                 uint8_t new_pitch      = original_pitch + dnote - highest_note_difference;
1545                 
1546                 // keep notes in standard midi range
1547                 clamp_to_0_127(new_pitch);
1548                 
1549                 // keep original pitch if note is dragged outside valid midi range
1550                 if ((original_pitch != 0 && new_pitch == 0)
1551                                 || (original_pitch != 127 && new_pitch == 127)) {
1552                         new_pitch = original_pitch;
1553                 }
1554
1555                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
1556                 highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
1557
1558                 copy->set_note(new_pitch);
1559                 
1560                 command_remove_note(*i);
1561                 cerr << "Adding note: " << *copy << endl;
1562                 command_add_note(copy, (*i)->selected());
1563
1564                 i = next;
1565         }
1566
1567         apply_command();
1568         
1569         // care about notes being moved beyond the upper/lower bounds on the canvas
1570         if (lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
1571                         highest_note_in_selection > midi_stream_view()->highest_note()) {
1572                 midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
1573         }
1574 }
1575
1576 nframes64_t
1577 MidiRegionView::snap_pixel_to_frame(double x)
1578 {
1579         PublicEditor& editor = trackview.editor();
1580         // x is region relative, convert it to global absolute frames
1581         nframes64_t frame = editor.pixel_to_frame(x) + _region->position();
1582         editor.snap_to(frame);
1583         return frame - _region->position(); // convert back to region relative
1584 }
1585
1586 nframes64_t
1587 MidiRegionView::snap_frame_to_frame(nframes64_t x)
1588 {
1589         PublicEditor& editor = trackview.editor();
1590         // x is region relative, convert it to global absolute frames
1591         nframes64_t frame = x + _region->position();
1592         editor.snap_to(frame);
1593         return frame - _region->position(); // convert back to region relative
1594 }
1595
1596 double
1597 MidiRegionView::snap_to_pixel(double x)
1598 {
1599         return (double) trackview.editor().frame_to_pixel(snap_pixel_to_frame(x));
1600 }
1601
1602 double
1603 MidiRegionView::get_position_pixels()
1604 {
1605         nframes64_t region_frame = get_position();
1606         return trackview.editor().frame_to_pixel(region_frame);
1607 }
1608
1609 nframes64_t
1610 MidiRegionView::beats_to_frames(double beats) const
1611 {
1612         return _time_converter.to(beats);
1613 }
1614
1615 double
1616 MidiRegionView::frames_to_beats(nframes64_t frames) const
1617 {
1618         return _time_converter.from(frames);
1619 }
1620
1621 void
1622 MidiRegionView::begin_resizing(CanvasNote::NoteEnd note_end)
1623 {
1624         _resize_data.clear();
1625
1626         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1627                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
1628
1629                 // only insert CanvasNotes into the map
1630                 if (note) {
1631                         NoteResizeData *resize_data = new NoteResizeData();
1632                         resize_data->canvas_note = note;
1633
1634                         // create a new SimpleRect from the note which will be the resize preview
1635                         SimpleRect *resize_rect = new SimpleRect(
1636                                         *group, note->x1(), note->y1(), note->x2(), note->y2());
1637
1638                         // calculate the colors: get the color settings
1639                         uint32_t fill_color = UINT_RGBA_CHANGE_A(
1640                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get(),
1641                                         128);
1642
1643                         // make the resize preview notes more transparent and bright
1644                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
1645
1646                         // calculate color based on note velocity
1647                         resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
1648                                         CanvasNoteEvent::meter_style_fill_color(note->note()->velocity()),
1649                                         fill_color,
1650                                         0.85);
1651
1652                         resize_rect->property_outline_color_rgba() = CanvasNoteEvent::calculate_outline(
1653                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get());
1654
1655                         resize_data->resize_rect = resize_rect;
1656
1657                         if (note_end == CanvasNote::NOTE_ON) {
1658                                 resize_data->current_x = note->x1();
1659                         } else { // NOTE_OFF
1660                                 resize_data->current_x = note->x2();
1661                         }
1662
1663                         _resize_data.push_back(resize_data);
1664                 }
1665         }
1666 }
1667
1668 void
1669 MidiRegionView::update_resizing(CanvasNote::NoteEnd note_end, double x, bool relative)
1670 {
1671         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1672                 SimpleRect* resize_rect = (*i)->resize_rect;
1673                 CanvasNote* canvas_note = (*i)->canvas_note;
1674
1675                 const double region_start = get_position_pixels();
1676
1677                 if (relative) {
1678                         (*i)->current_x = (*i)->current_x + x;
1679                 } else {
1680                         // x is in track relative, transform it to region relative
1681                         (*i)->current_x = x - region_start;
1682                 }
1683
1684                 double current_x = (*i)->current_x;
1685
1686                 if (note_end == CanvasNote::NOTE_ON) {
1687                         resize_rect->property_x1() = snap_to_pixel(current_x);
1688                         resize_rect->property_x2() = canvas_note->x2();
1689                 } else {
1690                         resize_rect->property_x2() = snap_to_pixel(current_x);
1691                         resize_rect->property_x1() = canvas_note->x1();
1692                 }
1693         }
1694 }
1695
1696 void
1697 MidiRegionView::commit_resizing(CanvasNote::NoteEnd note_end, double event_x, bool relative)
1698 {
1699         start_delta_command(_("resize notes"));
1700
1701         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1702                 CanvasNote*  canvas_note = (*i)->canvas_note;
1703                 SimpleRect*  resize_rect = (*i)->resize_rect;
1704                 double       current_x   = (*i)->current_x;
1705                 const double position    = get_position_pixels();
1706
1707                 if (!relative) {
1708                         // event_x is in track relative, transform it to region relative
1709                         current_x = event_x - position;
1710                 }
1711
1712                 // because snapping works on world coordinates we have to transform current_x
1713                 // to world coordinates before snapping and transform it back afterwards
1714                 nframes64_t current_frame = snap_pixel_to_frame(current_x);
1715                 // transform to region start relative
1716                 current_frame += _region->start();
1717                 
1718                 const boost::shared_ptr<NoteType> copy(new NoteType(*(canvas_note->note().get())));
1719
1720                 // resize beginning of note
1721                 if (note_end == CanvasNote::NOTE_ON && current_frame < copy->end_time()) {
1722                         command_remove_note(canvas_note);
1723                         copy->on_event().time() = current_frame;
1724                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1725                 }
1726                 // resize end of note
1727                 if (note_end == CanvasNote::NOTE_OFF && current_frame > copy->time()) {
1728                         command_remove_note(canvas_note);
1729                         copy->off_event().time() = current_frame;
1730                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1731                 }
1732
1733                 delete resize_rect;
1734                 delete (*i);
1735         }
1736
1737         _resize_data.clear();
1738         apply_command();
1739 }
1740
1741 void
1742 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
1743 {
1744         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1745
1746         if (relative) {
1747                 uint8_t new_velocity = copy->velocity() + velocity;
1748                 clamp_to_0_127(new_velocity);
1749                 copy->set_velocity(new_velocity);
1750         } else {
1751                 copy->set_velocity(velocity);                   
1752         }
1753
1754         command_remove_note(event);
1755         command_add_note(copy, event->selected(), true);
1756 }
1757
1758 void
1759 MidiRegionView::change_note_note (CanvasNoteEvent* event, int8_t note, bool relative)
1760 {
1761         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1762
1763         if (relative) {
1764                 uint8_t new_note = copy->note() + note;
1765                 clamp_to_0_127(new_note);
1766                 copy->set_note(new_note);
1767         } else {
1768                 copy->set_note(note);                   
1769         }
1770
1771         command_remove_note(event);
1772         command_add_note(copy, event->selected(), false);
1773 }
1774
1775 void
1776 MidiRegionView::trim_note (CanvasNoteEvent* event, Evoral::MusicalTime front_delta, Evoral::MusicalTime end_delta)
1777 {
1778         /* NOTE: the semantics of the two delta arguments are slightly subtle:
1779
1780            front_delta: if positive - move the start of the note later in time (shortening it)
1781                         if negative - move the start of the note earlier in time (lengthening it)
1782
1783            end_delta:   if positive - move the end of the note later in time (lengthening it)
1784                         if negative - move the end of the note earlier in time (shortening it)
1785          */
1786
1787         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1788
1789         cerr << "Trim front by " << front_delta << " end by " << end_delta << endl;
1790
1791         if (front_delta) {
1792                 if (front_delta < 0) {
1793                         if (copy->time() < -front_delta) {
1794                                 copy->set_time (0);
1795                         } else {
1796                                 copy->set_time (copy->time() + front_delta); // moves earlier
1797                         }
1798                         /* start moved toward zero, so move the end point out to where it used to be.
1799                            Note that front_delta is negative, so this increases the length.
1800                          */
1801                         copy->set_length (copy->length() - front_delta); 
1802                 } else {
1803                         Evoral::MusicalTime new_pos = copy->time() + front_delta;
1804
1805                         if (new_pos >= copy->end_time()) {
1806                                 return;
1807                         }
1808
1809                         copy->set_time (copy->time() + front_delta);
1810
1811                         /* start moved toward the end, so move the end point back to where it used to be */
1812                         copy->set_length (copy->length() - front_delta); 
1813                 }
1814
1815         }
1816
1817         if (end_delta) {
1818                 if (end_delta < 0) {
1819                         if (copy->length() < -end_delta) {
1820                                 return;
1821                         }
1822                 }
1823                 
1824                 copy->set_length (copy->length() + end_delta);
1825         }
1826
1827         command_remove_note(event);
1828         command_add_note(copy, event->selected(), false);
1829 }
1830
1831 void
1832 MidiRegionView::change_note_time (CanvasNoteEvent* event, Evoral::MusicalTime delta, bool relative)
1833 {
1834         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1835
1836         if (relative) {
1837                 if (delta < 0.0) {
1838                         if (copy->time() < -delta) {
1839                                 copy->set_time (0);
1840                         } else {
1841                                 copy->set_time (copy->time() + delta);
1842                         } 
1843                 } else {
1844                         copy->set_time (copy->time() + delta);
1845                 }
1846         } else {
1847                 copy->set_time (delta);
1848         }
1849
1850         command_remove_note(event);
1851         command_add_note(copy, event->selected(), false);
1852 }
1853
1854 void
1855 MidiRegionView::change_velocities (bool up, bool fine, bool allow_smush)
1856 {
1857         int8_t delta;
1858
1859         if (_selection.empty()) {
1860                 return;
1861         }
1862
1863         if (fine) {
1864                 delta = 1;
1865         } else {
1866                 delta = 10;
1867         }
1868
1869         if (!up) {
1870                 delta = -delta;
1871         }
1872
1873         if (!allow_smush) {
1874                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1875                         if ((*i)->note()->velocity() + delta == 0 || (*i)->note()->velocity() + delta == 127) {
1876                                 return;
1877                         }
1878                 }
1879         }
1880
1881         start_delta_command(_("change velocities"));
1882         
1883         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1884                 Selection::iterator next = i;
1885                 ++next;
1886                 change_note_velocity (*i, delta, true);
1887                 i = next;
1888         }
1889         
1890         apply_command();
1891 }
1892
1893
1894 void
1895 MidiRegionView::transpose (bool up, bool fine, bool allow_smush)
1896 {
1897         if (_selection.empty()) {
1898                 return;
1899         }
1900
1901         int8_t delta;
1902         
1903         if (fine) {
1904                 delta = 1;
1905         } else {
1906                 delta = 12;
1907         }
1908
1909         if (!up) {
1910                 delta = -delta;
1911         }
1912
1913         if (!allow_smush) {
1914                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1915                         if (!up) {
1916                                 if ((int8_t) (*i)->note()->note() + delta <= 0) {
1917                                         return;
1918                                 }
1919                         } else {
1920                                 if ((int8_t) (*i)->note()->note() + delta > 127) {
1921                                         return;
1922                                 }
1923                         }
1924                 }
1925         }
1926
1927         start_delta_command (_("transpose"));
1928
1929         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
1930                 Selection::iterator next = i;
1931                 ++next;
1932                 change_note_note (*i, delta, true);
1933                 i = next;
1934         }
1935
1936         apply_command ();
1937 }
1938
1939 void
1940 MidiRegionView::change_note_lengths (bool fine, bool shorter, bool start, bool end)
1941 {
1942         Evoral::MusicalTime delta;
1943
1944         if (fine) {
1945                 delta = 1.0/128.0;
1946         } else {
1947                 /* grab the current grid distance */
1948                 bool success;
1949                 delta = trackview.editor().get_grid_type_as_beats (success, _region->position());
1950                 if (!success) {
1951                         /* XXX cannot get grid type as beats ... should always be possible ... FIX ME */
1952                         cerr << "Grid type not available as beats - TO BE FIXED\n";
1953                         return;
1954                 }
1955         }
1956
1957         if (shorter) {
1958                 delta = -delta;
1959         }
1960
1961         start_delta_command (_("change note lengths"));
1962
1963         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
1964                 Selection::iterator next = i;
1965                 ++next;
1966                 
1967                 /* note the negation of the delta for start */
1968
1969                 trim_note (*i, (start ? -delta : 0), (end ? delta : 0));
1970                 i = next;
1971         }
1972
1973         apply_command ();
1974
1975 }
1976
1977 void
1978 MidiRegionView::nudge_notes (bool forward)
1979 {
1980         if (_selection.empty()) {
1981                 return;
1982         }
1983
1984         /* pick a note as the point along the timeline to get the nudge distance. 
1985            its not necessarily the earliest note, so we may want to pull the notes out 
1986            into a vector and sort before using the first one.
1987         */
1988
1989         nframes64_t ref_point = _region->position() + beats_to_frames ((*(_selection.begin()))->note()->time());
1990         nframes64_t unused;
1991         nframes64_t distance;
1992
1993         if ((distance = trackview.editor().get_nudge_distance (ref_point, unused)) == 0) {
1994
1995                 /* no nudge distance set - use grid */
1996
1997                 nframes64_t next_pos = ref_point;
1998                 
1999                 if (forward) {
2000                         /* XXX need check on max_frames, but that needs max_frames64 or something */
2001                         next_pos += 1;
2002                 } else { 
2003                         if (next_pos == 0) {
2004                                 return;
2005                         }
2006                         next_pos -= 1;
2007                 }
2008                 
2009                 cerr << "ref point was " << ref_point << " next was " << next_pos;
2010                 trackview.editor().snap_to (next_pos, (forward ? 1 : -1), false);
2011                 distance = ref_point - next_pos;
2012                 cerr << " final is " << next_pos << " distance = " << distance << endl;
2013         } 
2014                 
2015         if (distance == 0) {
2016                 return;
2017         }
2018
2019         Evoral::MusicalTime delta = frames_to_beats (fabs (distance));
2020
2021         if (!forward) {
2022                 delta = -delta;
2023         }
2024
2025         start_delta_command (_("nudge"));
2026
2027         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
2028                 Selection::iterator next = i;
2029                 ++next;
2030                 change_note_time (*i, delta, true);
2031                 i = next;
2032         }
2033
2034         apply_command ();
2035 }
2036
2037
2038 void
2039 MidiRegionView::change_channel(uint8_t channel)
2040 {
2041         start_delta_command(_("change channel"));
2042         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
2043                 Selection::iterator next = i;
2044                 ++next;
2045
2046                 CanvasNoteEvent* event = *i;
2047                 const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
2048
2049                 copy->set_channel(channel);
2050                 
2051                 command_remove_note(event);
2052                 command_add_note(copy, event->selected());
2053                 
2054                 i = next;
2055         }
2056         
2057         apply_command();
2058 }
2059
2060
2061 void
2062 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
2063 {
2064         if (_mouse_state == SelectTouchDragging) {
2065                 note_selected(ev, true);
2066         }
2067
2068         PublicEditor& editor (trackview.editor());
2069         editor.show_verbose_canvas_cursor_with (Evoral::midi_note_name (ev->note()->note()));
2070 }
2071
2072 void
2073 MidiRegionView::note_left (ArdourCanvas::CanvasNoteEvent* ev)
2074 {
2075         PublicEditor& editor (trackview.editor());
2076         editor.hide_verbose_canvas_cursor ();
2077 }
2078         
2079
2080 void
2081 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
2082 {
2083         boost::shared_ptr<MidiSource> msrc = boost::dynamic_pointer_cast<MidiSource>(src);
2084         if (msrc)
2085                 display_model(msrc->model());
2086 }
2087
2088 void
2089 MidiRegionView::set_frame_color()
2090 {
2091         if (frame) {
2092                 if (_selected && should_show_selection) {
2093                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
2094                 } else {
2095                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
2096                 }
2097         }
2098 }
2099
2100 void 
2101 MidiRegionView::midi_channel_mode_changed(ChannelMode mode, uint16_t mask)
2102 {
2103         switch (mode) {
2104         case AllChannels:
2105         case FilterChannels:
2106                 _force_channel = -1;
2107                 break;
2108         case ForceChannel:
2109                 _force_channel = mask;
2110                 mask = 0xFFFF; // Show all notes as active (below)
2111         };
2112
2113         // Update notes for selection
2114         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2115                 (*i)->on_channel_selection_change(mask);
2116         }
2117
2118         _last_channel_selection = mask;
2119 }
2120
2121 void 
2122 MidiRegionView::midi_patch_settings_changed(std::string model, std::string custom_device_mode)
2123 {
2124         _model_name         = model;
2125         _custom_device_mode = custom_device_mode;
2126         redisplay_model();
2127 }
2128
2129 void
2130 MidiRegionView::cut_copy_clear (Editing::CutCopyOp op)
2131 {
2132         if (_selection.empty()) {
2133                 return;
2134         }
2135
2136         PublicEditor& editor (trackview.editor());
2137
2138         switch (op) {
2139         case Cut:
2140         case Copy:
2141                 editor.get_cut_buffer().add (selection_as_cut_buffer());
2142                 break;
2143         default:
2144                 break;
2145         }
2146                 
2147         start_delta_command();
2148
2149         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2150                 switch (op) {
2151                 case Copy:
2152                         break;
2153                 case Cut:
2154                         command_remove_note (*i);
2155                         break;
2156                 case Clear:
2157                         break;
2158                 }
2159         }
2160
2161         apply_command();
2162 }
2163
2164 MidiCutBuffer*
2165 MidiRegionView::selection_as_cut_buffer () const
2166 {
2167         NoteList notes;
2168
2169         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
2170                 notes.push_back (boost::shared_ptr<NoteType> (new NoteType (*((*i)->note().get()))));
2171         }
2172
2173         /* sort them into time order */
2174
2175         Evoral::Sequence<Evoral::MusicalTime>::LaterNoteComparator cmp;
2176         sort (notes.begin(), notes.end(),  cmp);
2177
2178         MidiCutBuffer* cb = new MidiCutBuffer (trackview.session());
2179         cb->set (notes);
2180         
2181         return cb;
2182 }
2183
2184 void
2185 MidiRegionView::paste (nframes64_t pos, float times, const MidiCutBuffer& mcb)
2186 {
2187         if (mcb.empty()) {
2188                 return;
2189         }
2190
2191         start_delta_command (_("paste"));
2192
2193         Evoral::MusicalTime beat_delta;
2194         Evoral::MusicalTime paste_pos_beats;
2195         Evoral::MusicalTime duration;
2196         Evoral::MusicalTime end_point;
2197
2198         duration = mcb.notes().back()->end_time() - mcb.notes().front()->time();
2199         paste_pos_beats = frames_to_beats (pos - _region->position());
2200         beat_delta = mcb.notes().front()->time() - paste_pos_beats;
2201         paste_pos_beats = 0;
2202
2203         _selection.clear ();
2204
2205         for (int n = 0; n < (int) times; ++n) {
2206
2207                 for (NoteList::const_iterator i = mcb.notes().begin(); i != mcb.notes().end(); ++i) {
2208                         
2209                         boost::shared_ptr<NoteType> copied_note (new NoteType (*((*i).get())));
2210                         copied_note->set_time (paste_pos_beats + copied_note->time() - beat_delta);
2211
2212                         /* make all newly added notes selected */
2213
2214                         command_add_note (copied_note, true);
2215                         end_point = copied_note->end_time();
2216                 }
2217
2218                 paste_pos_beats += duration;
2219         }
2220
2221         /* if we pasted past the current end of the region, extend the region */
2222
2223         nframes64_t end_frame = _region->position() + beats_to_frames (end_point);
2224         nframes64_t region_end = _region->position() + _region->length() - 1;
2225
2226         if (end_frame > region_end) {
2227
2228                 trackview.session().begin_reversible_command (_("paste"));
2229
2230                 XMLNode& before (_region->get_state());
2231                 _region->set_length (end_frame, this);
2232                 trackview.session().add_command (new MementoCommand<Region>(*_region, &before, &_region->get_state()));
2233         }
2234         
2235         apply_command ();
2236 }
2237
2238 void
2239 MidiRegionView::goto_next_note ()
2240 {
2241         // nframes64_t pos = -1;
2242         bool use_next = false;
2243
2244         if (_events.back()->selected()) {
2245                 return;
2246         }
2247
2248         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2249                 if ((*i)->selected()) {
2250                         use_next = true;
2251                         continue;
2252                 } else if (use_next) {
2253                         unique_select (*i);
2254                         // pos = _region->position() + beats_to_frames ((*i)->note()->time());
2255                         return;
2256                 }
2257         }
2258
2259         /* use the first one */
2260
2261         unique_select (_events.front());
2262         
2263 }
2264
2265 void
2266 MidiRegionView::goto_previous_note ()
2267 {
2268         // nframes64_t pos = -1;
2269         bool use_next = false;
2270
2271         if (_events.front()->selected()) {
2272                 return;
2273         }
2274
2275         for (Events::reverse_iterator i = _events.rbegin(); i != _events.rend(); ++i) {
2276                 if ((*i)->selected()) {
2277                         use_next = true;
2278                         continue;
2279                 } else if (use_next) {
2280                         unique_select (*i);
2281                         // pos = _region->position() + beats_to_frames ((*i)->note()->time());
2282                         return;
2283                 }
2284         }
2285
2286         /* use the last one */
2287
2288         unique_select (*(_events.rbegin()));
2289 }
2290
2291 void
2292 MidiRegionView::selection_as_notelist (NoteList& selected) 
2293 {
2294         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
2295                 if ((*i)->selected()) {
2296                         /* make a copy of the original */
2297                         selected.push_back (boost::shared_ptr<Evoral::Note<Evoral::MusicalTime> >
2298                                             (new Evoral::Note<Evoral::MusicalTime> (*((*i)->note()))));
2299                 }
2300         }
2301 }
2302
2303 void
2304 MidiRegionView::replace_selected (NoteList& replacements)
2305 {
2306         start_delta_command ("whatever");
2307
2308         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
2309                 Selection::iterator tmp;
2310                 tmp = i;
2311                 ++tmp;
2312
2313                 command_remove_note (*i);
2314                 remove_from_selection (*i);
2315
2316                 i = tmp;
2317         }
2318
2319         _selection.clear ();
2320
2321         for (NoteList::iterator i = replacements.begin(); i != replacements.end(); ++i) {
2322                 command_add_note (*i, true, false);
2323         }
2324         
2325         apply_command_as_subcommand ();
2326 }
2327