more MIDI paste improvements, plus move region-mute binding to PRIMARY-m and use...
[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 "ardour/playlist.h"
32 #include "ardour/tempo.h"
33 #include "ardour/midi_region.h"
34 #include "ardour/midi_source.h"
35 #include "ardour/midi_diskstream.h"
36 #include "ardour/midi_model.h"
37 #include "ardour/midi_patch_manager.h"
38
39 #include "evoral/Parameter.hpp"
40 #include "evoral/Control.hpp"
41
42 #include "automation_region_view.h"
43 #include "automation_time_axis.h"
44 #include "canvas-hit.h"
45 #include "canvas-note.h"
46 #include "canvas-program-change.h"
47 #include "ghostregion.h"
48 #include "gui_thread.h"
49 #include "keyboard.h"
50 #include "midi_cut_buffer.h"
51 #include "midi_region_view.h"
52 #include "midi_streamview.h"
53 #include "midi_time_axis.h"
54 #include "midi_time_axis.h"
55 #include "midi_util.h"
56 #include "public_editor.h"
57 #include "selection.h"
58 #include "simpleline.h"
59 #include "streamview.h"
60 #include "utils.h"
61
62 #include "i18n.h"
63
64 using namespace sigc;
65 using namespace ARDOUR;
66 using namespace PBD;
67 using namespace Editing;
68 using namespace ArdourCanvas;
69
70 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
71                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color const & basic_color)
72         : RegionView (parent, tv, r, spu, basic_color)
73         , _force_channel(-1)
74         , _last_channel_selection(0xFFFF)
75         , _default_note_length(1.0)
76         , _current_range_min(0)
77         , _current_range_max(0)
78         , _model_name(string())
79         , _custom_device_mode(string())
80         , _active_notes(0)
81         , _note_group(new ArdourCanvas::Group(*parent))
82         , _delta_command(NULL)
83         , _mouse_state(None)
84         , _pressed_button(0)
85 {
86         _note_group->raise_to_top();
87 }
88
89 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
90                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color,
91                 TimeAxisViewItem::Visibility visibility)
92         : RegionView (parent, tv, r, spu, basic_color, false, visibility)
93         , _force_channel(-1)
94         , _last_channel_selection(0xFFFF)
95         , _default_note_length(1.0)
96         , _model_name(string())
97         , _custom_device_mode(string())
98         , _active_notes(0)
99         , _note_group(new ArdourCanvas::Group(*parent))
100         , _delta_command(NULL)
101         , _mouse_state(None)
102         , _pressed_button(0)
103         
104 {
105         _note_group->raise_to_top();
106 }
107
108
109 MidiRegionView::MidiRegionView (const MidiRegionView& other)
110         : sigc::trackable(other)
111         , RegionView (other)
112         , _force_channel(-1)
113         , _last_channel_selection(0xFFFF)
114         , _default_note_length(1.0)
115         , _model_name(string())
116         , _custom_device_mode(string())
117         , _active_notes(0)
118         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
119         , _delta_command(NULL)
120         , _mouse_state(None)
121         , _pressed_button(0)
122 {
123         Gdk::Color c;
124         int r,g,b,a;
125
126         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
127         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
128         
129         init (c, false);
130 }
131
132 MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<MidiRegion> region)
133         : RegionView (other, boost::shared_ptr<Region> (region))
134         , _force_channel(-1)
135         , _last_channel_selection(0xFFFF)
136         , _default_note_length(1.0)
137         , _model_name(string())
138         , _custom_device_mode(string())
139         , _active_notes(0)
140         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
141         , _delta_command(NULL)
142         , _mouse_state(None)
143         , _pressed_button(0)
144 {
145         Gdk::Color c;
146         int r,g,b,a;
147
148         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
149         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
150
151         init (c, true);
152 }
153
154 void
155 MidiRegionView::init (Gdk::Color const & basic_color, bool wfd)
156 {
157         if (wfd) {
158                 midi_region()->midi_source(0)->load_model();
159         }
160
161         _model = midi_region()->midi_source(0)->model();
162         _enable_display = false;
163
164         RegionView::init (basic_color, false);
165
166         compute_colors (basic_color);
167
168         set_height (trackview.current_height());
169
170         region_muted ();
171         region_sync_changed ();
172         region_resized (BoundsChanged);
173         region_locked ();
174         
175         reset_width_dependent_items (_pixel_width);
176
177         set_colors ();
178
179         _enable_display = true;
180         if (_model) {
181                 if (wfd) {
182                         redisplay_model();
183                 }
184                 _model->ContentsChanged.connect(sigc::mem_fun(this, &MidiRegionView::redisplay_model));
185         }
186
187         group->raise_to_top();
188         group->signal_event().connect (mem_fun (this, &MidiRegionView::canvas_event), false);
189
190         midi_view()->signal_channel_mode_changed().connect(
191                         mem_fun(this, &MidiRegionView::midi_channel_mode_changed));
192         
193         midi_view()->signal_midi_patch_settings_changed().connect(
194                         mem_fun(this, &MidiRegionView::midi_patch_settings_changed));
195 }
196
197 bool
198 MidiRegionView::canvas_event(GdkEvent* ev)
199 {
200         PublicEditor& editor (trackview.editor());
201
202         if (!editor.internal_editing()) {
203                 return false;
204         }
205
206         static double drag_start_x, drag_start_y;
207         static double last_x, last_y;
208         double event_x, event_y;
209         nframes64_t event_frame = 0;
210
211         static ArdourCanvas::SimpleRect* drag_rect = NULL;
212
213         switch (ev->type) {
214         case GDK_KEY_PRESS:
215                 if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
216                         _mouse_state = SelectTouchDragging;
217                         return true;
218                 } else if (ev->key.keyval == GDK_Escape) {
219                         clear_selection();
220                         _mouse_state = None;
221                 }
222                 return false;
223
224         case GDK_KEY_RELEASE:
225                 if (ev->key.keyval == GDK_Delete) {
226                         delete_selection();
227                         apply_command();
228                         return true;
229                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
230                         _mouse_state = None;
231                         return true;
232                 }
233                 return false;
234
235         case GDK_BUTTON_PRESS:
236                 if (_mouse_state != SelectTouchDragging && ev->button.button == 1) {
237                         _pressed_button = ev->button.button;
238                         _mouse_state = Pressed;
239                         return true;
240                 }
241                 _pressed_button = ev->button.button;
242                 return true;
243
244         case GDK_2BUTTON_PRESS:
245                 return true;
246
247         case GDK_ENTER_NOTIFY:
248                 /* FIXME: do this on switch to note tool, too, if the pointer is already in */
249                 Keyboard::magic_widget_grab_focus();
250                 group->grab_focus();
251                 break;
252
253         case GDK_MOTION_NOTIFY:
254                 event_x = ev->motion.x;
255                 event_y = ev->motion.y;
256                 group->w2i(event_x, event_y);
257
258                 // convert event_x to global frame
259                 event_frame = trackview.editor().pixel_to_frame(event_x) + _region->position();
260                 trackview.editor().snap_to(event_frame);
261                 // convert event_frame back to local coordinates relative to position
262                 event_frame -= _region->position();
263
264                 switch (_mouse_state) {
265                 case Pressed: // Drag start
266
267                         // Select drag start
268                         if (_pressed_button == 1 && editor.current_mouse_mode() == MouseRange) {
269                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
270                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
271                                 last_x = event_x;
272                                 last_y = event_y;
273                                 drag_start_x = event_x;
274                                 drag_start_y = event_y;
275
276                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
277                                 drag_rect->property_x1() = event_x;
278                                 drag_rect->property_y1() = event_y;
279                                 drag_rect->property_x2() = event_x;
280                                 drag_rect->property_y2() = event_y;
281                                 drag_rect->property_outline_what() = 0xFF;
282                                 drag_rect->property_outline_color_rgba()
283                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
284                                 drag_rect->property_fill_color_rgba()
285                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
286
287                                 _mouse_state = SelectRectDragging;
288                                 return true;
289
290                         // Add note drag start
291                         } else if (editor.current_mouse_mode() == MouseObject) {
292                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
293                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
294                                 last_x = event_x;
295                                 last_y = event_y;
296                                 drag_start_x = event_x;
297                                 drag_start_y = event_y;
298
299                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
300                                 drag_rect->property_x1() = trackview.editor().frame_to_pixel(event_frame);
301
302                                 drag_rect->property_y1() = midi_stream_view()->note_to_y(
303                                                 midi_stream_view()->y_to_note(event_y));
304                                 drag_rect->property_x2() = event_x;
305                                 drag_rect->property_y2() = drag_rect->property_y1()
306                                                          + floor(midi_stream_view()->note_height());
307                                 drag_rect->property_outline_what() = 0xFF;
308                                 drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
309                                 drag_rect->property_fill_color_rgba()    = 0xFFFFFF66;
310
311                                 _mouse_state = AddDragging;
312                                 return true;
313                         }
314
315                         return false;
316
317                 case SelectRectDragging: // Select drag motion
318                 case AddDragging: // Add note drag motion
319                         if (ev->motion.is_hint) {
320                                 int t_x;
321                                 int t_y;
322                                 GdkModifierType state;
323                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
324                                 event_x = t_x;
325                                 event_y = t_y;
326                         }
327
328                         if (_mouse_state == AddDragging)
329                                 event_x = trackview.editor().frame_to_pixel(event_frame);
330
331                         if (drag_rect) {
332                                 if (event_x > drag_start_x)
333                                         drag_rect->property_x2() = event_x;
334                                 else
335                                         drag_rect->property_x1() = event_x;
336                         }
337
338                         if (drag_rect && _mouse_state == SelectRectDragging) {
339                                 if (event_y > drag_start_y)
340                                         drag_rect->property_y2() = event_y;
341                                 else
342                                         drag_rect->property_y1() = event_y;
343
344                                 update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
345                         }
346
347                         last_x = event_x;
348                         last_y = event_y;
349
350                 case SelectTouchDragging:
351                         return false;
352
353                 default:
354                         break;
355                 }
356                 break;
357
358         case GDK_BUTTON_RELEASE:
359                 event_x = ev->motion.x;
360                 event_y = ev->motion.y;
361                 group->w2i(event_x, event_y);
362                 group->ungrab(ev->button.time);
363                 event_frame = trackview.editor().pixel_to_frame(event_x);
364
365                 if (_pressed_button != 1) {
366                         return false;
367                 }
368                         
369                 switch (_mouse_state) {
370                 case Pressed: // Clicked
371                         switch (editor.current_mouse_mode()) {
372                         case MouseRange:
373                         case MouseTimeFX:
374                                 clear_selection();
375                                 break;
376                         case MouseObject:
377                                 create_note_at(event_x, event_y, _default_note_length);
378                         default: break;
379                         }
380                         _mouse_state = None;
381                         break;
382                 case SelectRectDragging: // Select drag done
383                         _mouse_state = None;
384                         delete drag_rect;
385                         drag_rect = NULL;
386                         break;
387                 case AddDragging: // Add drag done
388                         _mouse_state = None;
389                         if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
390                                 const double x      = drag_rect->property_x1();
391                                 const double length = trackview.editor().pixel_to_frame(
392                                                         drag_rect->property_x2() - drag_rect->property_x1());
393                                         
394                                 create_note_at(x, drag_rect->property_y1(), frames_to_beats(length));
395                         }
396
397                         delete drag_rect;
398                         drag_rect = NULL;
399                 default: break;
400                 }
401
402         default: break;
403         }
404
405         return false;
406 }
407
408
409 /** Add a note to the model, and the view, at a canvas (click) coordinate.
410  * \param x horizontal position in pixels
411  * \param y vertical position in pixels
412  * \param length duration of the note in beats */
413 void
414 MidiRegionView::create_note_at(double x, double y, double length)
415 {
416         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
417         MidiStreamView* const view = mtv->midi_view();
418
419         double note = midi_stream_view()->y_to_note(y);
420
421         assert(note >= 0.0);
422         assert(note <= 127.0);
423
424         // Start of note in frames relative to region start
425         nframes64_t start_frames = snap_frame_to_frame(trackview.editor().pixel_to_frame(x));
426         assert(start_frames >= 0);
427
428         // Snap length
429         length = frames_to_beats(
430                         snap_frame_to_frame(start_frames + beats_to_frames(length)) - start_frames);
431
432         const boost::shared_ptr<NoteType> new_note(new NoteType(0,
433                         frames_to_beats(start_frames + _region->start()), length,
434                         (uint8_t)note, 0x40));
435
436         view->update_note_range(new_note->note());
437
438         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
439         cmd->add(new_note);
440         _model->apply_command(trackview.session(), cmd);
441 }
442
443
444 void
445 MidiRegionView::clear_events()
446 {
447         clear_selection();
448
449         MidiGhostRegion* gr;
450         for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
451                 if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
452                         gr->clear_events();
453                 }
454         }
455
456         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
457                 delete *i;
458         }
459
460         _events.clear();
461         _pgm_changes.clear();
462         _sys_exes.clear();
463 }
464
465
466 void
467 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
468 {
469         _model = model;
470         if (_enable_display) {
471                 redisplay_model();
472         }
473 }
474         
475         
476 void
477 MidiRegionView::start_delta_command(string name)
478 {
479         if (!_delta_command) {
480                 _delta_command = _model->new_delta_command(name);
481         }
482 }
483
484 void
485 MidiRegionView::command_add_note(const boost::shared_ptr<NoteType> note, bool selected, bool show_velocity)
486 {
487         if (_delta_command) {
488                 _delta_command->add(note);
489         }
490         if (selected) {
491                 _marked_for_selection.insert(note);
492         }
493         if (show_velocity) {
494                 _marked_for_velocity.insert(note);
495         }
496 }
497
498 void
499 MidiRegionView::command_remove_note(ArdourCanvas::CanvasNoteEvent* ev)
500 {
501         if (_delta_command && ev->note()) {
502                 _delta_command->remove(ev->note());
503         }
504 }
505         
506 void
507 MidiRegionView::apply_command()
508 {
509         if (!_delta_command) {
510                 return;
511         }
512
513         // Mark all selected notes for selection when model reloads
514         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
515                 _marked_for_selection.insert((*i)->note());
516         }
517         
518         _model->apply_command(trackview.session(), _delta_command);
519         _delta_command = NULL; 
520         midi_view()->midi_track()->diskstream()->playlist_modified();
521
522         _marked_for_selection.clear();
523         _marked_for_velocity.clear();
524 }
525         
526
527 void
528 MidiRegionView::abort_command()
529 {
530         delete _delta_command;
531         _delta_command = NULL;
532         clear_selection();
533 }
534
535
536 void
537 MidiRegionView::redisplay_model()
538 {
539         // Don't redisplay the model if we're currently recording and displaying that
540         if (_active_notes) {
541                 return;
542         }
543
544         if (_model) {
545                 clear_events();
546                 _model->read_lock();
547                 
548                 MidiModel::Notes notes = _model->notes();
549                 
550                 for (size_t i = 0; i < _model->n_notes(); ++i) {
551                         add_note(_model->note_at(i));
552                 }
553                 
554                 display_sysexes();
555
556                 display_program_changes();
557
558                 _model->read_unlock();
559
560         } else {
561                 cerr << "MidiRegionView::redisplay_model called without a model" << endmsg;
562         }
563 }
564
565 void
566 MidiRegionView::display_program_changes()
567 {
568         boost::shared_ptr<Evoral::Control> control = _model->control(MidiPgmChangeAutomation);
569         if (!control) {
570                 return;
571         }
572
573         Glib::Mutex::Lock lock (control->list()->lock());
574
575         uint8_t channel = control->parameter().channel();
576
577         for (AutomationList::const_iterator event = control->list()->begin();
578                         event != control->list()->end(); ++event) {
579                 double event_time     = (*event)->when;
580                 double program_number = floor((*event)->value + 0.5);
581
582                 // Get current value of bank select MSB at time of the program change
583                 Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
584                 boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
585                 uint8_t msb = 0;
586                 if (msb_control != 0) {
587                         msb = uint8_t(floor(msb_control->get_float(true, event_time) + 0.5));
588                 }
589
590                 // Get current value of bank select LSB at time of the program change
591                 Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
592                 boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
593                 uint8_t lsb = 0;
594                 if (lsb_control != 0) {
595                         lsb = uint8_t(floor(lsb_control->get_float(true, event_time) + 0.5));
596                 }
597
598                 MIDI::Name::PatchPrimaryKey patch_key(msb, lsb, program_number);
599
600                 boost::shared_ptr<MIDI::Name::Patch> patch = 
601                         MIDI::Name::MidiPatchManager::instance().find_patch(
602                                         _model_name, _custom_device_mode, channel, patch_key);
603
604                 PCEvent program_change(event_time, uint8_t(program_number), channel);
605
606                 if (patch != 0) {
607                         add_pgm_change(program_change, patch->name());
608                 } else {
609                         char buf[4];
610                         snprintf(buf, 4, "%d", int(program_number));
611                         add_pgm_change(program_change, buf);
612                 }
613         }
614 }
615
616 void 
617 MidiRegionView::display_sysexes()
618 {
619         for (MidiModel::SysExes::const_iterator i = _model->sysexes().begin(); i != _model->sysexes().end(); ++i) {
620                 ARDOUR::MidiModel::TimeType time = (*i)->time();
621                 assert(time >= 0);
622                 
623                 ostringstream str;
624                 str << hex;
625                 for (uint32_t b = 0; b < (*i)->size(); ++b) {
626                         str << int((*i)->buffer()[b]);
627                         if (b != (*i)->size() -1) {
628                                 str << " ";
629                         }
630                 }
631                 string text = str.str();
632                 
633                 ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
634                 const double x = trackview.editor().frame_to_pixel(beats_to_frames(time));
635                 
636                 double height = midi_stream_view()->contents_height();
637                 
638                 boost::shared_ptr<CanvasSysEx> sysex = boost::shared_ptr<CanvasSysEx>(
639                                 new CanvasSysEx(*this, *group, text, height, x, 1.0));
640                 
641                 // Show unless program change is beyond the region bounds
642                 if (time - _region->start() >= _region->length() || time < _region->start()) {
643                         sysex->hide();
644                 } else {
645                         sysex->show();
646                 }
647                 
648                 _sys_exes.push_back(sysex);
649         }
650 }
651
652
653 MidiRegionView::~MidiRegionView ()
654 {
655         in_destructor = true;
656
657         RegionViewGoingAway (this); /* EMIT_SIGNAL */
658
659         if (_active_notes) {
660                 end_write();
661         }
662
663         _selection.clear();
664         clear_events();
665         delete _note_group;
666         delete _delta_command;
667 }
668
669 void
670 MidiRegionView::region_resized (Change what_changed)
671 {
672         RegionView::region_resized(what_changed);
673         
674         if (what_changed & ARDOUR::PositionChanged) {
675                 set_duration(_region->length(), 0);
676                 if (_enable_display) {
677                         redisplay_model();
678                 }
679         } 
680 }
681
682 void
683 MidiRegionView::reset_width_dependent_items (double pixel_width)
684 {
685         RegionView::reset_width_dependent_items(pixel_width);
686         assert(_pixel_width == pixel_width);
687
688         if (_enable_display) {
689                 redisplay_model();
690         }
691 }
692
693 void
694 MidiRegionView::set_height (double height)
695 {
696         static const double FUDGE = 2.0;
697         const double old_height = _height;
698         RegionView::set_height(height);
699         _height = height - FUDGE;
700         
701         apply_note_range(midi_stream_view()->lowest_note(),
702                          midi_stream_view()->highest_note(),
703                          height != old_height + FUDGE);
704         
705         if (name_pixbuf) {
706                 name_pixbuf->raise_to_top();
707         }
708 }
709
710
711 /** Apply the current note range from the stream view
712  * by repositioning/hiding notes as necessary
713  */
714 void
715 MidiRegionView::apply_note_range (uint8_t min, uint8_t max, bool force)
716 {
717         if (!_enable_display) {
718                 return;
719         }
720
721         if (!force && _current_range_min == min && _current_range_max == max) {
722                 return;
723         }
724         
725         _current_range_min = min;
726         _current_range_max = max;
727
728         for (Events::const_iterator i = _events.begin(); i != _events.end(); ++i) {
729                 CanvasNoteEvent* event = *i;
730                 Item* item = dynamic_cast<Item*>(event);
731                 assert(item);
732                 if (event && event->note()) {
733                         if (event->note()->note() < _current_range_min
734                                         || event->note()->note() > _current_range_max) {
735                                 if (canvas_item_visible(item)) {
736                                         item->hide();
737                                 }
738                         } else {
739                                 if (!canvas_item_visible(item)) {
740                                         item->show();
741                                 }
742
743                                 if (CanvasNote* note = dynamic_cast<CanvasNote*>(event)) {
744                                         const double y1 = midi_stream_view()->note_to_y(event->note()->note());
745                                         const double y2 = y1 + floor(midi_stream_view()->note_height());
746
747                                         note->property_y1() = y1;
748                                         note->property_y2() = y2;
749                                 } else if (CanvasHit* hit = dynamic_cast<CanvasHit*>(event)) {
750                                         double x = trackview.editor().frame_to_pixel(
751                                                         beats_to_frames(event->note()->time()) - _region->start());
752                                         const double diamond_size = midi_stream_view()->note_height() / 2.0;
753                                         double y = midi_stream_view()->note_to_y(event->note()->note()) 
754                                                          + ((diamond_size-2.0) / 4.0);
755                                         
756                                         hit->set_height(diamond_size);
757                                         hit->move(x-hit->x1(), y-hit->y1());
758                                         hit->show();
759                                 }
760                         }
761                 }
762         }
763         
764 }
765
766 GhostRegion*
767 MidiRegionView::add_ghost (TimeAxisView& tv)
768 {
769         CanvasNote* note;
770
771         double unit_position = _region->position () / samples_per_unit;
772         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
773         MidiGhostRegion* ghost;
774
775         if (mtv && mtv->midi_view()) {
776                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group
777                    to allow having midi notes on top of note lines and waveforms.
778                  */
779                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
780         } else {
781                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
782         }
783
784         ghost->set_height ();
785         ghost->set_duration (_region->length() / samples_per_unit);
786         ghosts.push_back (ghost);
787
788         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
789                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
790                         ghost->add_note(note);
791                 }
792         }
793
794         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
795
796         return ghost;
797 }
798
799
800 /** Begin tracking note state for successive calls to add_event
801  */
802 void
803 MidiRegionView::begin_write()
804 {
805         assert(!_active_notes);
806         _active_notes = new CanvasNote*[128];
807         for (unsigned i=0; i < 128; ++i) {
808                 _active_notes[i] = NULL;
809         }
810 }
811
812
813 /** Destroy note state for add_event
814  */
815 void
816 MidiRegionView::end_write()
817 {
818         delete[] _active_notes;
819         _active_notes = NULL;
820         _marked_for_selection.clear();
821         _marked_for_velocity.clear();
822 }
823
824
825 /** Resolve an active MIDI note (while recording).
826  */
827 void
828 MidiRegionView::resolve_note(uint8_t note, double end_time)
829 {
830         if (midi_view()->note_mode() != Sustained) {
831                 return;
832         }
833
834         if (_active_notes && _active_notes[note]) {
835                 const nframes64_t end_time_frames = beats_to_frames(end_time);
836                 _active_notes[note]->property_x2() = trackview.editor().frame_to_pixel(end_time_frames);
837                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
838                 _active_notes[note] = NULL;
839         }
840 }
841
842
843 /** Extend active notes to rightmost edge of region (if length is changed)
844  */
845 void
846 MidiRegionView::extend_active_notes()
847 {
848         if (!_active_notes) {
849                 return;
850         }
851
852         for (unsigned i=0; i < 128; ++i) {
853                 if (_active_notes[i]) {
854                         _active_notes[i]->property_x2() = trackview.editor().frame_to_pixel(_region->length());
855                 }
856         }
857 }
858
859 void 
860 MidiRegionView::play_midi_note(boost::shared_ptr<NoteType> note)
861 {
862         if (!trackview.editor().sound_notes()) {
863                 return;
864         }
865
866         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
867         assert(route_ui);
868         
869         route_ui->midi_track()->write_immediate_event(
870                         note->on_event().size(), note->on_event().buffer());
871         
872         const double note_length_beats = (note->off_event().time() - note->on_event().time());
873         nframes_t note_length_ms = beats_to_frames(note_length_beats)
874                         * (1000 / (double)route_ui->session().nominal_frame_rate());
875         Glib::signal_timeout().connect(bind(mem_fun(this, &MidiRegionView::play_midi_note_off), note),
876                         note_length_ms, G_PRIORITY_DEFAULT);
877 }
878
879 bool
880 MidiRegionView::play_midi_note_off(boost::shared_ptr<NoteType> note)
881 {
882         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
883         assert(route_ui);
884         
885         route_ui->midi_track()->write_immediate_event(
886                         note->off_event().size(), note->off_event().buffer());
887
888         return false;
889 }
890
891 bool
892 MidiRegionView::note_in_visible_range(const boost::shared_ptr<NoteType> note) const
893 {
894         const nframes64_t note_start_frames = beats_to_frames(note->time());
895         bool outside = (note_start_frames - _region->start() >= _region->length())
896                         || (note_start_frames < _region->start())
897                         || (note->note() < midi_stream_view()->lowest_note())
898                         || (note->note() > midi_stream_view()->highest_note());
899         return !outside;
900 }
901
902 /** Add a MIDI note to the view (with length).
903  *
904  * If in sustained mode, notes with length 0 will be considered active
905  * notes, and resolve_note should be called when the corresponding note off
906  * event arrives, to properly display the note.
907  */
908 void
909 MidiRegionView::add_note(const boost::shared_ptr<NoteType> note)
910 {
911         assert(note->time() >= 0);
912         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
913         
914         const nframes64_t note_start_frames = beats_to_frames(note->time());
915         const nframes64_t note_end_frames   = beats_to_frames(note->end_time());
916
917         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
918
919         CanvasNoteEvent* event = 0;
920         
921         const double x = trackview.editor().frame_to_pixel(note_start_frames - _region->start());
922         
923         if (midi_view()->note_mode() == Sustained) {
924                 const double y1 = midi_stream_view()->note_to_y(note->note());
925                 const double note_endpixel = 
926                         trackview.editor().frame_to_pixel(note_end_frames - _region->start());
927                 
928                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
929                 ev_rect->property_x1() = x;
930                 ev_rect->property_y1() = y1;
931                 if (note->length() > 0) {
932                         ev_rect->property_x2() = note_endpixel;
933                 } else {
934                         ev_rect->property_x2() = trackview.editor().frame_to_pixel(_region->length());
935                 }
936                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
937
938                 if (note->length() == 0) {
939                         if (_active_notes) {
940                                 assert(note->note() < 128);
941                                 // If this note is already active there's a stuck note,
942                                 // finish the old note rectangle
943                                 if (_active_notes[note->note()]) {
944                                         CanvasNote* const old_rect = _active_notes[note->note()];
945                                         boost::shared_ptr<NoteType> old_note = old_rect->note();
946                                         old_rect->property_x2() = x;
947                                         old_rect->property_outline_what() = (guint32) 0xF;
948                                 }
949                                 _active_notes[note->note()] = ev_rect;
950                         }
951                         /* outline all but right edge */
952                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
953                 } else {
954                         /* outline all edges */
955                         ev_rect->property_outline_what() = (guint32) 0xF;
956                 }
957
958                 event = ev_rect;
959
960                 MidiGhostRegion* gr;
961                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
962                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
963                                 gr->add_note(ev_rect);
964                         }
965                 }
966
967         } else if (midi_view()->note_mode() == Percussive) {
968                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
969                 const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
970
971                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size, note);
972                 ev_diamond->move(x, y);
973                 event = ev_diamond;
974         } else {
975                 event = 0;
976         }
977
978         if (event) {
979                 if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
980                         note_selected(event, true);
981                 }
982                 if (_marked_for_velocity.find(note) != _marked_for_velocity.end()) {
983                         event->show_velocity();
984                 }
985                 event->on_channel_selection_change(_last_channel_selection);
986                 _events.push_back(event);
987                 if (note_in_visible_range(note)) {
988                         event->show();
989                 } else {
990                         event->hide();
991                 }
992         }
993 }
994
995 void
996 MidiRegionView::add_pgm_change(PCEvent& program, const string& displaytext)
997 {
998         assert(program.time >= 0);
999         
1000         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
1001         const double x = trackview.editor().frame_to_pixel(beats_to_frames(program.time));
1002         
1003         double height = midi_stream_view()->contents_height();
1004         
1005         boost::shared_ptr<CanvasProgramChange> pgm_change = boost::shared_ptr<CanvasProgramChange>(
1006                         new CanvasProgramChange(*this, *group,
1007                                         displaytext, 
1008                                         height, 
1009                                         x, 1.0, 
1010                                         _model_name, 
1011                                         _custom_device_mode, 
1012                                         program.time, program.channel, program.value));
1013         
1014         // Show unless program change is beyond the region bounds
1015         if (program.time - _region->start() >= _region->length() || program.time < _region->start()) {
1016                 pgm_change->hide();
1017         } else {
1018                 pgm_change->show();
1019         }
1020         
1021         _pgm_changes.push_back(pgm_change);
1022 }
1023
1024 void
1025 MidiRegionView::get_patch_key_at(double time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
1026 {
1027         cerr << "getting patch key at " << time << " for channel " << channel << endl;
1028         Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
1029         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1030         float msb = -1.0;
1031         if (msb_control != 0) {
1032                 msb = int(msb_control->get_float(true, time));
1033                 cerr << "got msb " << msb;
1034         }
1035
1036         Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
1037         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1038         float lsb = -1.0;
1039         if (lsb_control != 0) {
1040                 lsb = lsb_control->get_float(true, time);
1041                 cerr << " got lsb " << lsb;
1042         }
1043         
1044         Evoral::Parameter program_change(MidiPgmChangeAutomation, channel, 0);
1045         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1046         float program_number = -1.0;
1047         if (program_control != 0) {
1048                 program_number = program_control->get_float(true, time);
1049                 cerr << " got program " << program_number << endl;
1050         }
1051         
1052         key.msb = (int) floor(msb + 0.5);
1053         key.lsb = (int) floor(lsb + 0.5);
1054         key.program_number = (int) floor(program_number + 0.5);
1055         assert(key.is_sane());
1056 }
1057
1058
1059 void 
1060 MidiRegionView::alter_program_change(PCEvent& old_program, const MIDI::Name::PatchPrimaryKey& new_patch)
1061 {
1062         // TODO: Get the real event here and alter them at the original times
1063         Evoral::Parameter bank_select_msb(MidiCCAutomation, old_program.channel, MIDI_CTL_MSB_BANK);
1064         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1065         if (msb_control != 0) {
1066                 msb_control->set_float(float(new_patch.msb), true, old_program.time);
1067         }
1068
1069         // TODO: Get the real event here and alter them at the original times
1070         Evoral::Parameter bank_select_lsb(MidiCCAutomation, old_program.channel, MIDI_CTL_LSB_BANK);
1071         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1072         if (lsb_control != 0) {
1073                 lsb_control->set_float(float(new_patch.lsb), true, old_program.time);
1074         }
1075         
1076         Evoral::Parameter program_change(MidiPgmChangeAutomation, old_program.channel, 0);
1077         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1078         
1079         assert(program_control != 0);
1080         program_control->set_float(float(new_patch.program_number), true, old_program.time);
1081         
1082         redisplay_model();
1083 }
1084
1085 void
1086 MidiRegionView::program_selected(CanvasProgramChange& program, const MIDI::Name::PatchPrimaryKey& new_patch)
1087 {
1088         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1089         alter_program_change(program_change_event, new_patch);
1090 }
1091
1092 void 
1093 MidiRegionView::previous_program(CanvasProgramChange& program)
1094 {
1095         MIDI::Name::PatchPrimaryKey key;
1096         get_patch_key_at(program.event_time(), program.channel(), key);
1097         
1098         boost::shared_ptr<MIDI::Name::Patch> patch = 
1099                 MIDI::Name::MidiPatchManager::instance().previous_patch(
1100                                 _model_name,
1101                                 _custom_device_mode, 
1102                                 program.channel(), 
1103                                 key);
1104         
1105         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1106         if (patch) {
1107                 alter_program_change(program_change_event, patch->patch_primary_key());
1108         }
1109 }
1110
1111 void 
1112 MidiRegionView::next_program(CanvasProgramChange& program)
1113 {
1114         MIDI::Name::PatchPrimaryKey key;
1115         get_patch_key_at(program.event_time(), program.channel(), key);
1116         
1117         boost::shared_ptr<MIDI::Name::Patch> patch = 
1118                 MIDI::Name::MidiPatchManager::instance().next_patch(
1119                                 _model_name,
1120                                 _custom_device_mode, 
1121                                 program.channel(), 
1122                                 key);   
1123
1124         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1125         if (patch) {
1126                 alter_program_change(program_change_event, patch->patch_primary_key());
1127         }
1128 }
1129
1130 void
1131 MidiRegionView::delete_selection()
1132 {
1133         if (_selection.empty()) {
1134                 return;
1135         }
1136
1137         if (!_delta_command) {
1138                 _delta_command = _model->new_delta_command("delete selection");
1139         }
1140
1141         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1142                 if ((*i)->selected()) {
1143                         _delta_command->remove((*i)->note());
1144                 }
1145         }
1146
1147         _selection.clear();
1148 }
1149
1150 void
1151 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasNoteEvent* ev)
1152 {
1153         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1154                 if ((*i)->selected() && (*i) != ev) {
1155                         (*i)->selected(false);
1156                         (*i)->hide_velocity();
1157                 }
1158         }
1159
1160         _selection.clear();
1161 }
1162
1163 void
1164 MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
1165 {
1166         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ) {
1167
1168                 Selection::iterator tmp = i;
1169                 ++tmp;
1170
1171                 if ((*i) != ev) {
1172                         remove_from_selection (*i);
1173                 } 
1174
1175                 i = tmp;
1176         }
1177
1178         if (!ev->selected()) {
1179                 add_to_selection (ev);
1180         }
1181 }
1182
1183 void
1184 MidiRegionView::note_selected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1185 {
1186         if (!add) {
1187                 clear_selection_except(ev);
1188         }
1189
1190         if (!ev->selected()) {
1191                 add_to_selection (ev);
1192         }
1193 }
1194
1195
1196 void
1197 MidiRegionView::note_deselected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1198 {
1199         if (!add) {
1200                 clear_selection_except(ev);
1201         }
1202
1203         remove_from_selection (ev);
1204 }
1205
1206
1207 void
1208 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2)
1209 {
1210         const double last_y = std::min(y1, y2);
1211         const double y      = std::max(y1, y2);
1212
1213         // TODO: Make this faster by storing the last updated selection rect, and only
1214         // adjusting things that are in the area that appears/disappeared.
1215         // We probably need a tree to be able to find events in O(log(n)) time.
1216
1217 #ifndef NDEBUG
1218         double last_x1 = 0.0;
1219 #endif
1220
1221         if (x1 < x2) {
1222                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1223 #ifndef NDEBUG
1224                         // Events should always be sorted by increasing x1() here
1225                         assert((*i)->x1() >= last_x1);
1226                         last_x1 = (*i)->x1();
1227 #endif
1228                         if ((*i)->x1() >= x1 && (*i)->x1() <= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1229                                 // Inside rectangle
1230                                 add_to_selection (*i);
1231                         } else if ((*i)->selected()) {
1232                                 // Not inside rectangle
1233                                 remove_from_selection (*i);
1234                         }
1235                 }
1236         } else {
1237                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1238 #ifndef NDEBUG
1239                         // Events should always be sorted by increasing x1() here
1240                         assert((*i)->x1() >= last_x1);
1241                         last_x1 = (*i)->x1();
1242 #endif
1243                         if ((*i)->x2() <= x1 && (*i)->x2() >= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1244                                 // Inside rectangle
1245                                 add_to_selection (*i);
1246                         } else if ((*i)->selected()) {
1247                                 // Not inside rectangle
1248                                 remove_from_selection (*i);
1249                         }
1250                 }
1251         }
1252 }
1253
1254 void
1255 MidiRegionView::remove_from_selection (CanvasNoteEvent* ev)
1256 {
1257         Selection::iterator i = _selection.find (ev);
1258
1259         if (i != _selection.end()) {
1260                 _selection.erase (i);
1261         }
1262
1263         ev->selected (false);
1264         ev->hide_velocity ();
1265         
1266         if (_selection.empty()) {
1267                 PublicEditor& editor (trackview.editor());
1268                 editor.get_selection().remove (this);
1269         }
1270 }
1271
1272 void
1273 MidiRegionView::add_to_selection (CanvasNoteEvent* ev)
1274 {
1275         bool add_mrv_selection = false;
1276
1277         if (_selection.empty()) {
1278                 add_mrv_selection = true;
1279         }
1280
1281         if (_selection.insert (ev).second) {
1282                 ev->selected (true);
1283                 play_midi_note ((ev)->note());
1284         }
1285
1286         if (add_mrv_selection) {
1287                 PublicEditor& editor (trackview.editor());
1288                 editor.get_selection().add (this);
1289         }
1290 }
1291
1292 void
1293 MidiRegionView::move_selection(double dx, double dy)
1294 {
1295         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1296                 (*i)->move_event(dx, dy);
1297         }
1298 }
1299
1300 void
1301 MidiRegionView::note_dropped(CanvasNoteEvent* ev, double dt, uint8_t dnote)
1302 {
1303         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
1304         if (_selection.find(ev) == _selection.end()) {
1305                 return;
1306         }
1307
1308         uint8_t lowest_note_in_selection  = midi_stream_view()->lowest_note();
1309         uint8_t highest_note_in_selection = midi_stream_view()->highest_note();
1310         uint8_t highest_note_difference = 0;
1311
1312         // find highest and lowest notes first
1313         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1314                 uint8_t pitch = (*i)->note()->note();
1315                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
1316                 highest_note_in_selection = std::max(highest_note_in_selection, pitch);
1317         }
1318         
1319         /*
1320         cerr << "dnote: " << (int) dnote << endl;
1321         cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note()) 
1322              << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
1323         cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): " 
1324              << int(highest_note_in_selection) << endl;
1325         cerr << "selection size: " << _selection.size() << endl;
1326         cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
1327         */
1328         
1329         // Make sure the note pitch does not exceed the MIDI standard range
1330         if (dnote <= 127 && (highest_note_in_selection + dnote > 127)) {
1331                 highest_note_difference = highest_note_in_selection - 127;
1332         }
1333         
1334         start_delta_command(_("move notes"));
1335
1336         for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
1337                 Selection::iterator next = i;
1338                 ++next;
1339
1340                 const boost::shared_ptr<NoteType> copy(new NoteType(*(*i)->note().get()));
1341
1342                 nframes64_t start_frames = beats_to_frames((*i)->note()->time());
1343                 if (dt >= 0) {
1344                         start_frames += snap_frame_to_frame(trackview.editor().pixel_to_frame(dt));
1345                 } else {
1346                         start_frames -= snap_frame_to_frame(trackview.editor().pixel_to_frame(-dt));
1347                 }
1348
1349                 copy->set_time(frames_to_beats(start_frames));
1350
1351                 uint8_t original_pitch = (*i)->note()->note();
1352                 uint8_t new_pitch      = original_pitch + dnote - highest_note_difference;
1353                 
1354                 // keep notes in standard midi range
1355                 clamp_to_0_127(new_pitch);
1356                 
1357                 // keep original pitch if note is dragged outside valid midi range
1358                 if ((original_pitch != 0 && new_pitch == 0)
1359                                 || (original_pitch != 127 && new_pitch == 127)) {
1360                         new_pitch = original_pitch;
1361                 }
1362
1363                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
1364                 highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
1365
1366                 copy->set_note(new_pitch);
1367                 
1368                 command_remove_note(*i);
1369                 command_add_note(copy, (*i)->selected());
1370
1371                 i = next;
1372         }
1373
1374         apply_command();
1375         
1376         // care about notes being moved beyond the upper/lower bounds on the canvas
1377         if (lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
1378                         highest_note_in_selection > midi_stream_view()->highest_note()) {
1379                 midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
1380         }
1381 }
1382
1383 nframes64_t
1384 MidiRegionView::snap_pixel_to_frame(double x)
1385 {
1386         PublicEditor& editor = trackview.editor();
1387         // x is region relative, convert it to global absolute frames
1388         nframes64_t frame = editor.pixel_to_frame(x) + _region->position();
1389         editor.snap_to(frame);
1390         return frame - _region->position(); // convert back to region relative
1391 }
1392
1393 nframes64_t
1394 MidiRegionView::snap_frame_to_frame(nframes64_t x)
1395 {
1396         PublicEditor& editor = trackview.editor();
1397         // x is region relative, convert it to global absolute frames
1398         nframes64_t frame = x + _region->position();
1399         editor.snap_to(frame);
1400         return frame - _region->position(); // convert back to region relative
1401 }
1402
1403 double
1404 MidiRegionView::snap_to_pixel(double x)
1405 {
1406         return (double) trackview.editor().frame_to_pixel(snap_pixel_to_frame(x));
1407 }
1408
1409 double
1410 MidiRegionView::get_position_pixels()
1411 {
1412         nframes64_t region_frame = get_position();
1413         return trackview.editor().frame_to_pixel(region_frame);
1414 }
1415
1416 nframes64_t
1417 MidiRegionView::beats_to_frames(double beats) const
1418 {
1419         return _time_converter.to(beats);
1420 }
1421
1422 double
1423 MidiRegionView::frames_to_beats(nframes64_t frames) const
1424 {
1425         return _time_converter.from(frames);
1426 }
1427
1428 void
1429 MidiRegionView::begin_resizing(CanvasNote::NoteEnd note_end)
1430 {
1431         _resize_data.clear();
1432
1433         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1434                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
1435
1436                 // only insert CanvasNotes into the map
1437                 if (note) {
1438                         NoteResizeData *resize_data = new NoteResizeData();
1439                         resize_data->canvas_note = note;
1440
1441                         // create a new SimpleRect from the note which will be the resize preview
1442                         SimpleRect *resize_rect = new SimpleRect(
1443                                         *group, note->x1(), note->y1(), note->x2(), note->y2());
1444
1445                         // calculate the colors: get the color settings
1446                         uint32_t fill_color = UINT_RGBA_CHANGE_A(
1447                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get(),
1448                                         128);
1449
1450                         // make the resize preview notes more transparent and bright
1451                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
1452
1453                         // calculate color based on note velocity
1454                         resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
1455                                         CanvasNoteEvent::meter_style_fill_color(note->note()->velocity()),
1456                                         fill_color,
1457                                         0.85);
1458
1459                         resize_rect->property_outline_color_rgba() = CanvasNoteEvent::calculate_outline(
1460                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get());
1461
1462                         resize_data->resize_rect = resize_rect;
1463
1464                         if (note_end == CanvasNote::NOTE_ON) {
1465                                 resize_data->current_x = note->x1();
1466                         } else { // NOTE_OFF
1467                                 resize_data->current_x = note->x2();
1468                         }
1469
1470                         _resize_data.push_back(resize_data);
1471                 }
1472         }
1473 }
1474
1475 void
1476 MidiRegionView::update_resizing(CanvasNote::NoteEnd note_end, double x, bool relative)
1477 {
1478         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1479                 SimpleRect* resize_rect = (*i)->resize_rect;
1480                 CanvasNote* canvas_note = (*i)->canvas_note;
1481
1482                 const double region_start = get_position_pixels();
1483
1484                 if (relative) {
1485                         (*i)->current_x = (*i)->current_x + x;
1486                 } else {
1487                         // x is in track relative, transform it to region relative
1488                         (*i)->current_x = x - region_start;
1489                 }
1490
1491                 double current_x = (*i)->current_x;
1492
1493                 if (note_end == CanvasNote::NOTE_ON) {
1494                         resize_rect->property_x1() = snap_to_pixel(current_x);
1495                         resize_rect->property_x2() = canvas_note->x2();
1496                 } else {
1497                         resize_rect->property_x2() = snap_to_pixel(current_x);
1498                         resize_rect->property_x1() = canvas_note->x1();
1499                 }
1500         }
1501 }
1502
1503 void
1504 MidiRegionView::commit_resizing(CanvasNote::NoteEnd note_end, double event_x, bool relative)
1505 {
1506         start_delta_command(_("resize notes"));
1507
1508         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1509                 CanvasNote*  canvas_note = (*i)->canvas_note;
1510                 SimpleRect*  resize_rect = (*i)->resize_rect;
1511                 double       current_x   = (*i)->current_x;
1512                 const double position    = get_position_pixels();
1513
1514                 if (!relative) {
1515                         // event_x is in track relative, transform it to region relative
1516                         current_x = event_x - position;
1517                 }
1518
1519                 // because snapping works on world coordinates we have to transform current_x
1520                 // to world coordinates before snapping and transform it back afterwards
1521                 nframes64_t current_frame = snap_pixel_to_frame(current_x);
1522                 // transform to region start relative
1523                 current_frame += _region->start();
1524                 
1525                 const boost::shared_ptr<NoteType> copy(new NoteType(*(canvas_note->note().get())));
1526
1527                 // resize beginning of note
1528                 if (note_end == CanvasNote::NOTE_ON && current_frame < copy->end_time()) {
1529                         command_remove_note(canvas_note);
1530                         copy->on_event().time() = current_frame;
1531                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1532                 }
1533                 // resize end of note
1534                 if (note_end == CanvasNote::NOTE_OFF && current_frame > copy->time()) {
1535                         command_remove_note(canvas_note);
1536                         copy->off_event().time() = current_frame;
1537                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1538                 }
1539
1540                 delete resize_rect;
1541                 delete (*i);
1542         }
1543
1544         _resize_data.clear();
1545         apply_command();
1546 }
1547
1548 void
1549 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
1550 {
1551         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1552
1553         if (relative) {
1554                 uint8_t new_velocity = copy->velocity() + velocity;
1555                 clamp_to_0_127(new_velocity);
1556                 copy->set_velocity(new_velocity);
1557         } else {
1558                 copy->set_velocity(velocity);                   
1559         }
1560
1561         command_remove_note(event);
1562         command_add_note(copy, event->selected(), true);
1563 }
1564
1565 void
1566 MidiRegionView::change_velocity(CanvasNoteEvent* ev, int8_t velocity, bool relative)
1567 {
1568         start_delta_command(_("change velocity"));
1569         
1570         change_note_velocity(ev, velocity, relative);
1571
1572         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1573                 Selection::iterator next = i;
1574                 ++next;
1575                 if ( !(*((*i)->note()) == *(ev->note())) ) {
1576                         change_note_velocity(*i, velocity, relative);
1577                 }
1578                 i = next;
1579         }
1580         
1581         apply_command();
1582 }
1583
1584 void
1585 MidiRegionView::change_channel(uint8_t channel)
1586 {
1587         start_delta_command(_("change channel"));
1588         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1589                 Selection::iterator next = i;
1590                 ++next;
1591
1592                 CanvasNoteEvent* event = *i;
1593                 const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1594
1595                 copy->set_channel(channel);
1596                 
1597                 command_remove_note(event);
1598                 command_add_note(copy, event->selected());
1599                 
1600                 i = next;
1601         }
1602         
1603         apply_command();
1604 }
1605
1606
1607 void
1608 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
1609 {
1610         if (_mouse_state == SelectTouchDragging) {
1611                 note_selected(ev, true);
1612         }
1613 }
1614
1615
1616 void
1617 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
1618 {
1619         boost::shared_ptr<MidiSource> msrc = boost::dynamic_pointer_cast<MidiSource>(src);
1620         if (msrc)
1621                 display_model(msrc->model());
1622 }
1623
1624 void
1625 MidiRegionView::set_frame_color()
1626 {
1627         if (frame) {
1628                 if (_selected && should_show_selection) {
1629                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
1630                 } else {
1631                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
1632                 }
1633         }
1634 }
1635
1636 void 
1637 MidiRegionView::midi_channel_mode_changed(ChannelMode mode, uint16_t mask)
1638 {
1639         switch (mode) {
1640         case AllChannels:
1641         case FilterChannels:
1642                 _force_channel = -1;
1643                 break;
1644         case ForceChannel:
1645                 _force_channel = mask;
1646                 mask = 0xFFFF; // Show all notes as active (below)
1647         };
1648
1649         // Update notes for selection
1650         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1651                 (*i)->on_channel_selection_change(mask);
1652         }
1653
1654         _last_channel_selection = mask;
1655 }
1656
1657 void 
1658 MidiRegionView::midi_patch_settings_changed(std::string model, std::string custom_device_mode)
1659 {
1660         _model_name         = model;
1661         _custom_device_mode = custom_device_mode;
1662         redisplay_model();
1663 }
1664
1665 void
1666 MidiRegionView::cut_copy_clear (Editing::CutCopyOp op)
1667 {
1668         if (_selection.empty()) {
1669                 return;
1670         }
1671
1672         PublicEditor& editor (trackview.editor());
1673
1674         switch (op) {
1675         case Cut:
1676         case Copy:
1677                 editor.get_cut_buffer().add (selection_as_cut_buffer());
1678                 break;
1679         default:
1680                 break;
1681         }
1682                 
1683         start_delta_command();
1684
1685         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1686                 switch (op) {
1687                 case Copy:
1688                         break;
1689                 case Cut:
1690                         command_remove_note (*i);
1691                         break;
1692                 case Clear:
1693                         break;
1694                 }
1695         }
1696
1697         apply_command();
1698 }
1699
1700 MidiCutBuffer*
1701 MidiRegionView::selection_as_cut_buffer () const
1702 {
1703         Evoral::Sequence<MidiModel::TimeType>::Notes notes;
1704
1705         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1706                 notes.push_back (boost::shared_ptr<NoteType> (new NoteType (*((*i)->note().get()))));
1707         }
1708
1709         /* sort them into time order */
1710
1711         sort (notes.begin(), notes.end(), Evoral::Sequence<MidiModel::TimeType>::note_time_comparator);
1712
1713         MidiCutBuffer* cb = new MidiCutBuffer (trackview.session());
1714         cb->set (notes);
1715         
1716         return cb;
1717 }
1718
1719 void
1720 MidiRegionView::paste (nframes64_t pos, float times, const MidiCutBuffer& mcb)
1721 {
1722         if (mcb.empty()) {
1723                 return;
1724         }
1725
1726         start_delta_command (_("paste"));
1727
1728         MidiModel::TimeType beat_delta;
1729         MidiModel::TimeType paste_pos_beats;
1730         MidiModel::TimeType duration;
1731
1732         duration = mcb.notes().back()->end_time() - mcb.notes().front()->time();
1733         paste_pos_beats = frames_to_beats (pos);
1734         beat_delta = mcb.notes().front()->time() - paste_pos_beats;
1735         paste_pos_beats = 0;
1736
1737         _selection.clear ();
1738
1739         for (int n = 0; n < (int) times; ++n) {
1740
1741                 for (Evoral::Sequence<MidiModel::TimeType>::Notes::const_iterator i = mcb.notes().begin(); i != mcb.notes().end(); ++i) {
1742                         
1743                         boost::shared_ptr<NoteType> copied_note (new NoteType (*((*i).get())));
1744                         copied_note->set_time (paste_pos_beats + copied_note->time() - beat_delta);
1745
1746                         /* make all newly added notes selected */
1747
1748                         command_add_note (copied_note, true);
1749                 }
1750
1751                 paste_pos_beats += duration;
1752         }
1753         
1754         apply_command ();
1755 }