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