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