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