af3203ec9b2a71c723147debb123fb2a721daf7f
[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
24 #include <gtkmm.h>
25
26 #include <gtkmm2ext/gtk_ui.h>
27
28 #include <sigc++/signal.h>
29
30 #include <ardour/playlist.h>
31 #include <ardour/tempo.h>
32 #include <ardour/midi_region.h>
33 #include <ardour/midi_source.h>
34 #include <ardour/midi_diskstream.h>
35 #include <ardour/midi_model.h>
36 #include <ardour/midi_patch_manager.h>
37
38 #include <evoral/Parameter.hpp>
39 #include <evoral/Control.hpp>
40
41 #include "streamview.h"
42 #include "midi_region_view.h"
43 #include "midi_streamview.h"
44 #include "midi_time_axis.h"
45 #include "simpleline.h"
46 #include "canvas-hit.h"
47 #include "canvas-note.h"
48 #include "canvas-program-change.h"
49 #include "public_editor.h"
50 #include "ghostregion.h"
51 #include "midi_time_axis.h"
52 #include "automation_time_axis.h"
53 #include "automation_region_view.h"
54 #include "utils.h"
55 #include "midi_util.h"
56 #include "gui_thread.h"
57 #include "keyboard.h"
58
59 #include "i18n.h"
60
61 using namespace sigc;
62 using namespace ARDOUR;
63 using namespace PBD;
64 using namespace Editing;
65 using namespace ArdourCanvas;
66
67 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
68                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color)
69         : RegionView (parent, tv, r, spu, basic_color)
70         , _force_channel(-1)
71         , _last_channel_selection(0xFFFF)
72         , _default_note_length(1.0)
73         , _current_range_min(0)
74         , _current_range_max(0)
75         , _model_name(string())
76         , _custom_device_mode(string())
77         , _active_notes(0)
78         , _note_group(new ArdourCanvas::Group(*parent))
79         , _delta_command(NULL)
80         , _mouse_state(None)
81         , _pressed_button(0)
82 {
83         _note_group->raise_to_top();
84 }
85
86 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
87                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color,
88                 TimeAxisViewItem::Visibility visibility)
89         : RegionView (parent, tv, r, spu, basic_color, false, visibility)
90         , _force_channel(-1)
91         , _last_channel_selection(0xFFFF)
92         , _default_note_length(1.0)
93         , _model_name(string())
94         , _custom_device_mode(string())
95         , _active_notes(0)
96         , _note_group(new ArdourCanvas::Group(*parent))
97         , _delta_command(NULL)
98         , _mouse_state(None)
99         , _pressed_button(0)
100         
101 {
102         _note_group->raise_to_top();
103 }
104
105
106 MidiRegionView::MidiRegionView (const MidiRegionView& other)
107         : RegionView (other)
108         , _force_channel(-1)
109         , _last_channel_selection(0xFFFF)
110         , _default_note_length(1.0)
111         , _model_name(string())
112         , _custom_device_mode(string())
113         , _active_notes(0)
114         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
115         , _delta_command(NULL)
116         , _mouse_state(None)
117         , _pressed_button(0)
118 {
119         Gdk::Color c;
120         int r,g,b,a;
121
122         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
123         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
124         
125         init (c, false);
126 }
127
128 MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<MidiRegion> region)
129         : RegionView (other, boost::shared_ptr<Region> (region))
130         , _force_channel(-1)
131         , _last_channel_selection(0xFFFF)
132         , _default_note_length(1.0)
133         , _model_name(string())
134         , _custom_device_mode(string())
135         , _active_notes(0)
136         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
137         , _delta_command(NULL)
138         , _mouse_state(None)
139         , _pressed_button(0)
140 {
141         Gdk::Color c;
142         int r,g,b,a;
143
144         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
145         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
146
147         init (c, true);
148 }
149
150 void
151 MidiRegionView::init (Gdk::Color& basic_color, bool wfd)
152 {
153         if (wfd) {
154                 midi_region()->midi_source(0)->load_model();
155         }
156
157         _model = midi_region()->midi_source(0)->model();
158         _enable_display = false;
159
160         RegionView::init (basic_color, false);
161
162         compute_colors (basic_color);
163
164         set_height (trackview.current_height());
165
166         region_muted ();
167         region_sync_changed ();
168         region_resized (BoundsChanged);
169         region_locked ();
170         
171         reset_width_dependent_items (_pixel_width);
172         //reset_width_dependent_items ((double) _region->length() / samples_per_unit);
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 }
479
480
481 void
482 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
483 {
484         _model = model;
485         if (_enable_display) {
486                 redisplay_model();
487         }
488 }
489         
490         
491 void
492 MidiRegionView::start_delta_command(string name)
493 {
494         if (!_delta_command) {
495                 _delta_command = _model->new_delta_command(name);
496         }
497 }
498
499 void
500 MidiRegionView::command_add_note(const boost::shared_ptr<NoteType> note, bool selected)
501 {
502         if (_delta_command) {
503                 _delta_command->add(note);
504         }
505         if (selected) {
506                 _marked_for_selection.insert(note);
507         }
508 }
509
510 void
511 MidiRegionView::command_remove_note(ArdourCanvas::CanvasNoteEvent* ev)
512 {
513         if (_delta_command && ev->note()) {
514                 _delta_command->remove(ev->note());
515         }
516 }
517         
518 void
519 MidiRegionView::apply_command()
520 {
521         if (!_delta_command) {
522                 return;
523         }
524
525         // Mark all selected notes for selection when model reloads
526         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
527                 _marked_for_selection.insert((*i)->note());
528         }
529         
530         _model->apply_command(trackview.session(), _delta_command);
531         _delta_command = NULL; 
532         midi_view()->midi_track()->diskstream()->playlist_modified();
533
534         _marked_for_selection.clear();
535 }
536         
537
538 void
539 MidiRegionView::abort_command()
540 {
541         delete _delta_command;
542         _delta_command = NULL;
543         clear_selection();
544 }
545
546
547 void
548 MidiRegionView::redisplay_model()
549 {
550         // Don't redisplay the model if we're currently recording and displaying that
551         if (_active_notes) {
552                 return;
553         }
554
555         if (_model) {
556                 clear_events();
557                 _model->read_lock();
558                 
559                 MidiModel::Notes notes = _model->notes();
560                 /*
561                 cerr << _model->midi_source()->name() << " : redisplaying " << notes.size() << endl;
562                 for (MidiModel::Notes::iterator i = notes.begin(); i != notes.end(); ++i) {
563                         cerr << "NOTE  time: " << (*i)->time()
564                                  << "  pitch: " << int((*i)->note()) 
565                              << "  length: " << (*i)->length() 
566                              << "  end-time: " << (*i)->end_time() 
567                              << "  velocity: " << int((*i)->velocity()) 
568                              << endl;
569                 }
570                 */
571                 
572                 for (size_t i = 0; i < _model->n_notes(); ++i) {
573                         add_note(_model->note_at(i));
574                 }
575                 
576                 display_program_change_flags();
577
578                 _model->read_unlock();
579
580         } else {
581                 cerr << "MidiRegionView::redisplay_model called without a model" << endmsg;
582         }
583 }
584
585 void
586 MidiRegionView::display_program_change_flags()
587 {
588         for (Automatable::Controls::iterator control = _model->controls().begin();
589                         control != _model->controls().end(); ++control) {
590                 if (control->first.type() == MidiPgmChangeAutomation) {
591                         Glib::Mutex::Lock list_lock (control->second->list()->lock());
592
593                         uint8_t channel = control->first.channel();
594                         
595                         for (AutomationList::const_iterator event = control->second->list()->begin();
596                                         event != control->second->list()->end(); ++event) {
597                                 double event_time     = (*event)->when;
598                                 double program_number = floor((*event)->value + 0.5);
599
600                                 //cerr << " got program change on channel " << int(channel)
601                                 //              << " time: " << event_time << " number: " << program_number << endl;
602                                 
603                                 // find bank select msb and lsb for the program change                          
604                                 Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
605                                 boost::shared_ptr<Evoral::Control>  msb_control = _model->control(bank_select_msb);
606                                 uint8_t msb = 0;
607                                 if (msb_control != 0) {
608                                         msb = uint8_t(floor(msb_control->get_float(true, event_time) + 0.5));
609                                 }
610
611                                 Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
612                                 boost::shared_ptr<Evoral::Control>  lsb_control = _model->control(bank_select_lsb);
613                                 uint8_t lsb = 0;
614                                 if (lsb_control != 0) {
615                                         lsb = uint8_t(floor(lsb_control->get_float(true, event_time) + 0.5));
616                                 }
617                                         
618                                 //cerr << " got msb " << int(msb) << " and lsb " << int(lsb)
619                                 //              << " thread_id: " << pthread_self() << endl;
620                                         
621                                 MIDI::Name::PatchPrimaryKey patch_key(msb, lsb, program_number);
622                                 
623                                 boost::shared_ptr<MIDI::Name::Patch> patch = 
624                                         MIDI::Name::MidiPatchManager::instance().find_patch(
625                                                         _model_name,
626                                                         _custom_device_mode, 
627                                                         channel, 
628                                                         patch_key);
629                                 
630                                 ControlEvent program_change(nframes_t(event_time), uint8_t(program_number), channel);
631                                 
632                                 if (patch != 0) {
633                                         //cerr << " got patch with name " << patch->name()
634                                         //              << " number " << patch->number() << endl;
635                                         add_pgm_change(program_change, patch->name());
636                                 } else {
637                                         char buf[4];
638                                         snprintf(buf, 4, "%d", int(program_number));
639                                         add_pgm_change(program_change, buf);
640                                 }
641                         }
642                         break;
643                 } else if (control->first.type() == MidiCCAutomation) {
644                         //cerr << " found CC Automation of channel " << int(control->first.channel())
645                         //              << " and id " << control->first.id() << endl;
646                 }
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                 if (_enable_display) {
675                         redisplay_model();
676                 }
677         } 
678 }
679
680 void
681 MidiRegionView::reset_width_dependent_items (double pixel_width)
682 {
683         RegionView::reset_width_dependent_items(pixel_width);
684         assert(_pixel_width == pixel_width);
685
686         if (_enable_display) {
687                 redisplay_model();
688         }
689 }
690
691 void
692 MidiRegionView::set_height (double height)
693 {
694         static const double FUDGE = 2.0;
695         const double old_height = _height;
696         RegionView::set_height(height);
697         _height = height - FUDGE;
698         
699         apply_note_range(midi_stream_view()->lowest_note(),
700                          midi_stream_view()->highest_note(),
701                          height != old_height + FUDGE);
702         
703         if (name_text) {
704                 name_text->raise_to_top();
705         }
706 }
707
708
709 /** Apply the current note range from the stream view
710  * by repositioning/hiding notes as necessary
711  */
712 void
713 MidiRegionView::apply_note_range (uint8_t min, uint8_t max, bool force)
714 {
715         if (_enable_display) {
716                 if (!force && _current_range_min == min && _current_range_max == max) {
717                         return;
718                 }
719                 
720                 _current_range_min = min;
721                 _current_range_max = max;
722
723                 for (Events::const_iterator i = _events.begin(); i != _events.end(); ++i) {
724                         CanvasNoteEvent* event = *i;
725                         Item* item = dynamic_cast<Item*>(event);
726                         assert(item);
727                         if (event && event->note()) {
728                                 if (event->note()->note() < _current_range_min
729                                                 || event->note()->note() > _current_range_max) {
730                                         if (canvas_item_visible(item)) {
731                                                 item->hide();
732                                         }
733                                 } else {
734                                         if (!canvas_item_visible(item)) {
735                                                 item->show();
736                                         }
737
738                                         event->hide_velocity();
739                                         if (CanvasNote* note = dynamic_cast<CanvasNote*>(event)) {
740                                                 const double y1 = midi_stream_view()->note_to_y(event->note()->note());
741                                                 const double y2 = y1 + floor(midi_stream_view()->note_height());
742
743                                                 note->property_y1() = y1;
744                                                 note->property_y2() = y2;
745                                         } else if (CanvasHit* hit = dynamic_cast<CanvasHit*>(event)) {
746                                                 double x = trackview.editor().frame_to_pixel((nframes64_t)
747                                                                 event->note()->time() - _region->start());
748                                                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
749                                                 double y = midi_stream_view()->note_to_y(event->note()->note()) 
750                                                                  + ((diamond_size-2.0) / 4.0);
751                                                 
752                                                 hit->set_height(diamond_size);
753                                                 hit->move(x-hit->x1(), y-hit->y1());
754                                                 hit->show();
755                                         }
756                                         if (event->selected()) {
757                                                 event->show_velocity();
758                                         }
759                                 }
760                         }
761                 }
762         }
763 }
764
765 GhostRegion*
766 MidiRegionView::add_ghost (TimeAxisView& tv)
767 {
768         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
769         CanvasNote* note;
770         assert(rtv);
771
772         double unit_position = _region->position () / samples_per_unit;
773         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
774         MidiGhostRegion* ghost;
775
776         if (mtv && mtv->midi_view()) {
777                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group.
778                    this is because it's nice to have midi notes on top of the note lines and
779                    audio waveforms under it.
780                  */
781                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
782         } else {
783                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
784         }
785
786         ghost->set_height ();
787         ghost->set_duration (_region->length() / samples_per_unit);
788         ghosts.push_back (ghost);
789
790         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
791                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
792                         ghost->add_note(note);
793                 }
794         }
795
796         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
797
798         return ghost;
799 }
800
801
802 /** Begin tracking note state for successive calls to add_event
803  */
804 void
805 MidiRegionView::begin_write()
806 {
807         assert(!_active_notes);
808         _active_notes = new CanvasNote*[128];
809         for (unsigned i=0; i < 128; ++i) {
810                 _active_notes[i] = NULL;
811         }
812 }
813
814
815 /** Destroy note state for add_event
816  */
817 void
818 MidiRegionView::end_write()
819 {
820         delete[] _active_notes;
821         _active_notes = NULL;
822         _marked_for_selection.clear();
823 }
824
825
826 /** Resolve an active MIDI note (while recording).
827  */
828 void
829 MidiRegionView::resolve_note(uint8_t note, double end_time)
830 {
831         if (midi_view()->note_mode() != Sustained) {
832                 return;
833         }
834
835         if (_active_notes && _active_notes[note]) {
836                 _active_notes[note]->property_x2() = trackview.editor().frame_to_pixel((nframes64_t)end_time);
837                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
838                 _active_notes[note] = NULL;
839         }
840 }
841
842
843 /** Extend active notes to rightmost edge of region (if length is changed)
844  */
845 void
846 MidiRegionView::extend_active_notes()
847 {
848         if (!_active_notes) {
849                 return;
850         }
851
852         for (unsigned i=0; i < 128; ++i) {
853                 if (_active_notes[i]) {
854                         _active_notes[i]->property_x2() = trackview.editor().frame_to_pixel(_region->length());
855                 }
856         }
857 }
858
859 void 
860 MidiRegionView::play_midi_note(boost::shared_ptr<NoteType> note)
861 {
862         if (!trackview.editor().sound_notes()) {
863                 return;
864         }
865
866         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
867         assert(route_ui);
868         
869         route_ui->midi_track()->write_immediate_event(
870                         note->on_event().size(), note->on_event().buffer());
871         
872         const double note_length_beats = (note->off_event().time() - note->on_event().time());
873         nframes_t note_length_ms = beats_to_frames(note_length_beats)
874                         * (1000 / (double)route_ui->session().nominal_frame_rate());
875         Glib::signal_timeout().connect(bind(mem_fun(this, &MidiRegionView::play_midi_note_off), note),
876                         note_length_ms, G_PRIORITY_DEFAULT);
877 }
878
879 bool
880 MidiRegionView::play_midi_note_off(boost::shared_ptr<NoteType> note)
881 {
882         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
883         assert(route_ui);
884         
885         route_ui->midi_track()->write_immediate_event(
886                         note->off_event().size(), note->off_event().buffer());
887
888         return false;
889 }
890
891 bool
892 MidiRegionView::note_in_visible_range(const boost::shared_ptr<NoteType> note) const
893 {
894         const nframes64_t note_start_frames = beats_to_frames(note->time());
895         bool outside = (note_start_frames - _region->start() >= _region->length())
896                         || (note_start_frames < _region->start())
897                         || (note->note() < midi_stream_view()->lowest_note())
898                         || (note->note() > midi_stream_view()->highest_note());
899         return !outside;
900 }
901
902 /** Add a MIDI note to the view (with length).
903  *
904  * If in sustained mode, notes with length 0 will be considered active
905  * notes, and resolve_note should be called when the corresponding note off
906  * event arrives, to properly display the note.
907  */
908 void
909 MidiRegionView::add_note(const boost::shared_ptr<NoteType> note)
910 {
911         assert(note->time() >= 0);
912         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
913         
914         const nframes64_t note_start_frames = beats_to_frames(note->time());
915         const nframes64_t note_end_frames   = beats_to_frames(note->end_time());
916
917         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
918
919         CanvasNoteEvent* event = 0;
920         
921         const double x = trackview.editor().frame_to_pixel(note_start_frames - _region->start());
922         
923         if (midi_view()->note_mode() == Sustained) {
924                 const double y1 = midi_stream_view()->note_to_y(note->note());
925                 const double note_endpixel = 
926                         trackview.editor().frame_to_pixel(note_end_frames - _region->start());
927                 
928                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
929                 ev_rect->property_x1() = x;
930                 ev_rect->property_y1() = y1;
931                 if (note->length() > 0) {
932                         ev_rect->property_x2() = note_endpixel;
933                 } else {
934                         ev_rect->property_x2() = trackview.editor().frame_to_pixel(_region->length());
935                 }
936                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
937
938                 if (note->length() == 0) {
939                         if (_active_notes) {
940                                 assert(note->note() < 128);
941                                 // If this note is already active there's a stuck note,
942                                 // finish the old note rectangle
943                                 if (_active_notes[note->note()]) {
944                                         CanvasNote* const old_rect = _active_notes[note->note()];
945                                         boost::shared_ptr<NoteType> old_note = old_rect->note();
946                                         cerr << "MidiModel: WARNING: Note has length 0: chan " << old_note->channel()
947                                                 << "note " << (int)old_note->note() << " @ " << old_note->time() << endl;
948                                         /* FIXME: How large to make it?  Make it a diamond? */
949                                         old_rect->property_x2() = old_rect->property_x1() + 2.0;
950                                         old_rect->property_outline_what() = (guint32) 0xF;
951                                 }
952                                 _active_notes[note->note()] = ev_rect;
953                         }
954                         /* outline all but right edge */
955                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
956                 } else {
957                         /* outline all edges */
958                         ev_rect->property_outline_what() = (guint32) 0xF;
959                 }
960
961                 event = ev_rect;
962
963                 MidiGhostRegion* gr;
964                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
965                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
966                                 gr->add_note(ev_rect);
967                         }
968                 }
969
970         } else if (midi_view()->note_mode() == Percussive) {
971                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
972                 const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
973
974                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size, note);
975                 ev_diamond->move(x, y);
976                 event = ev_diamond;
977         } else {
978                 event = 0;
979         }
980
981         if (event) {
982                 if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
983                         note_selected(event, true);
984                 }
985                 event->on_channel_selection_change(_last_channel_selection);
986                 _events.push_back(event);
987                 if (note_in_visible_range(note)) {
988                         event->show();
989                 } else {
990                         event->hide();
991                 }
992         }
993 }
994
995 void
996 MidiRegionView::add_pgm_change(ControlEvent& program, string displaytext)
997 {
998         assert(program.time >= 0);
999         
1000         // dont display program changes beyond the region bounds
1001         if (program.time - _region->start() >= _region->length() || program.time <  _region->start()) 
1002                 return;
1003         
1004         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
1005         const double x = trackview.editor().frame_to_pixel((nframes64_t)program.time - _region->start());
1006         
1007         double height = midi_stream_view()->contents_height();
1008         
1009         boost::shared_ptr<CanvasProgramChange> pgm_change = boost::shared_ptr<CanvasProgramChange>(
1010                         new CanvasProgramChange(
1011                                         *this, 
1012                                         *group, 
1013                                         displaytext, 
1014                                         height, 
1015                                         x, 
1016                                         1.0, 
1017                                         _model_name, 
1018                                         _custom_device_mode, 
1019                                         program.time, 
1020                                         program.channel, 
1021                                         program.value));
1022         
1023         _pgm_changes.push_back(pgm_change);
1024 }
1025
1026 void
1027 MidiRegionView::get_patch_key_at(double time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
1028 {
1029         cerr << "getting patch key at " << time << " for channel " << channel << endl;
1030         Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
1031         boost::shared_ptr<Evoral::Control>  msb_control = _model->control(bank_select_msb);
1032         float msb = -1.0;
1033         if (msb_control != 0) {
1034                 msb = int(msb_control->get_float(true, time));
1035                 cerr << "got msb " << msb;
1036         }
1037
1038         Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
1039         boost::shared_ptr<Evoral::Control>  lsb_control = _model->control(bank_select_lsb);
1040         float lsb = -1.0;
1041         if (lsb_control != 0) {
1042                 lsb = lsb_control->get_float(true, time);
1043                 cerr << " got lsb " << lsb;
1044         }
1045         
1046         Evoral::Parameter program_change(MidiPgmChangeAutomation, channel, 0);
1047         boost::shared_ptr<Evoral::Control>  program_control = _model->control(program_change);
1048         float program_number = -1.0;
1049         if (program_control != 0) {
1050                 program_number = program_control->get_float(true, time);
1051                 cerr << " got program " << program_number << endl;
1052         }
1053         
1054         key.msb = (int) floor(msb + 0.5);
1055         key.lsb = (int) floor(lsb + 0.5);
1056         key.program_number = (int) floor(program_number + 0.5);
1057         assert(key.is_sane());
1058 }
1059
1060
1061 void 
1062 MidiRegionView::alter_program_change(ControlEvent& old_program, const MIDI::Name::PatchPrimaryKey& new_patch)
1063 {
1064         // TODO: Get the real event here and alter them at the original times
1065         Evoral::Parameter bank_select_msb(MidiCCAutomation, old_program.channel, MIDI_CTL_MSB_BANK);
1066         boost::shared_ptr<Evoral::Control>  msb_control = _model->control(bank_select_msb);
1067         if (msb_control != 0) {
1068                 msb_control->set_float(float(new_patch.msb), true, old_program.time);
1069         }
1070
1071         // TODO: Get the real event here and alter them at the original times
1072         Evoral::Parameter bank_select_lsb(MidiCCAutomation, old_program.channel, MIDI_CTL_LSB_BANK);
1073         boost::shared_ptr<Evoral::Control>  lsb_control = _model->control(bank_select_lsb);
1074         if (lsb_control != 0) {
1075                 lsb_control->set_float(float(new_patch.lsb), true, old_program.time);
1076         }
1077         
1078         Evoral::Parameter program_change(MidiPgmChangeAutomation, old_program.channel, 0);
1079         boost::shared_ptr<Evoral::Control>  program_control = _model->control(program_change);
1080         
1081         assert(program_control != 0);
1082         program_control->set_float(float(new_patch.program_number), true, old_program.time);
1083         
1084         redisplay_model();
1085 }
1086
1087 void
1088 MidiRegionView::program_selected(CanvasProgramChange& program, const MIDI::Name::PatchPrimaryKey& new_patch)
1089 {
1090         ControlEvent program_change_event(program.event_time(), program.program(), program.channel());
1091         alter_program_change(program_change_event, new_patch);
1092 }
1093
1094 void 
1095 MidiRegionView::previous_program(CanvasProgramChange& program)
1096 {
1097         MIDI::Name::PatchPrimaryKey key;
1098         get_patch_key_at(program.event_time(), program.channel(), key);
1099         
1100         boost::shared_ptr<MIDI::Name::Patch> patch = 
1101                 MIDI::Name::MidiPatchManager::instance().previous_patch(
1102                                 _model_name,
1103                                 _custom_device_mode, 
1104                                 program.channel(), 
1105                                 key);
1106         
1107         ControlEvent program_change_event(program.event_time(), program.program(), program.channel());
1108         if (patch) {
1109                 alter_program_change(program_change_event, patch->patch_primary_key());
1110         }
1111 }
1112
1113 void 
1114 MidiRegionView::next_program(CanvasProgramChange& program)
1115 {
1116         MIDI::Name::PatchPrimaryKey key;
1117         get_patch_key_at(program.event_time(), program.channel(), key);
1118         
1119         boost::shared_ptr<MIDI::Name::Patch> patch = 
1120                 MIDI::Name::MidiPatchManager::instance().next_patch(
1121                                 _model_name,
1122                                 _custom_device_mode, 
1123                                 program.channel(), 
1124                                 key);   
1125         ControlEvent program_change_event(program.event_time(), program.program(), program.channel());
1126         if (patch) {
1127                 alter_program_change(program_change_event, patch->patch_primary_key());
1128         }
1129 }
1130
1131 void
1132 MidiRegionView::delete_selection()
1133 {
1134         assert(_delta_command);
1135
1136         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1137                 if ((*i)->selected()) {
1138                         _delta_command->remove((*i)->note());
1139                 }
1140         }
1141
1142         _selection.clear();
1143 }
1144
1145 void
1146 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasNoteEvent* ev)
1147 {
1148         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1149                 if ((*i)->selected() && (*i) != ev) {
1150                         (*i)->selected(false);
1151                 }
1152         }
1153
1154         _selection.clear();
1155 }
1156
1157 void
1158 MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
1159 {
1160         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1161                 if ((*i) != ev) {
1162                         (*i)->selected(false);
1163                 }
1164         }
1165
1166         _selection.clear();
1167         _selection.insert(ev);
1168
1169         if ( ! ev->selected()) {
1170                 ev->selected(true);
1171         }
1172 }
1173
1174 void
1175 MidiRegionView::note_selected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1176 {
1177         if ( ! add) {
1178                 clear_selection_except(ev);
1179         }
1180
1181         if (_selection.insert(ev).second) {
1182                 play_midi_note(ev->note());
1183         }
1184
1185         if ( ! ev->selected()) {
1186                 ev->selected(true);
1187         }
1188 }
1189
1190
1191 void
1192 MidiRegionView::note_deselected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1193 {
1194         if ( ! add) {
1195                 clear_selection_except(ev);
1196         }
1197
1198         _selection.erase(ev);
1199
1200         if (ev->selected()) {
1201                 ev->selected(false);
1202         }
1203 }
1204
1205
1206 void
1207 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2)
1208 {
1209         const double last_y = std::min(y1, y2);
1210         const double y      = std::max(y1, y2);
1211
1212         // TODO: Make this faster by storing the last updated selection rect, and only
1213         // adjusting things that are in the area that appears/disappeared.
1214         // We probably need a tree to be able to find events in O(log(n)) time.
1215
1216 #ifndef NDEBUG
1217         double last_x1 = 0.0;
1218 #endif
1219
1220         if (x1 < x2) {
1221                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1222 #ifndef NDEBUG
1223                         // Events should always be sorted by increasing x1() here
1224                         assert((*i)->x1() >= last_x1);
1225                         last_x1 = (*i)->x1();
1226 #endif
1227                         // Inside rectangle
1228                         if ((*i)->x1() >= x1 && (*i)->x1() <= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1229                                 if (!(*i)->selected()) {
1230                                         (*i)->selected(true);
1231                                         _selection.insert(*i);
1232                                         play_midi_note((*i)->note());
1233                                 }
1234                         // Not inside rectangle
1235                         } else if ((*i)->selected()) {
1236                                 (*i)->selected(false);
1237                                 _selection.erase(*i);
1238                         }
1239                 }
1240         } else {
1241                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1242 #ifndef NDEBUG
1243                         // Events should always be sorted by increasing x1() here
1244                         assert((*i)->x1() >= last_x1);
1245                         last_x1 = (*i)->x1();
1246 #endif
1247                         // Inside rectangle
1248                         if ((*i)->x2() <= x1 && (*i)->x2() >= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1249                                 if (!(*i)->selected()) {
1250                                         (*i)->selected(true);
1251                                         _selection.insert(*i);
1252                                         play_midi_note((*i)->note());
1253                                 }
1254                         // Not inside rectangle
1255                         } else if ((*i)->selected()) {
1256                                 (*i)->selected(false);
1257                                 _selection.erase(*i);
1258                         }
1259                 }
1260         }
1261 }
1262
1263
1264 void
1265 MidiRegionView::move_selection(double dx, double dy)
1266 {
1267         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
1268                 (*i)->move_event(dx, dy);
1269 }
1270
1271
1272 void
1273 MidiRegionView::note_dropped(CanvasNoteEvent* ev, double dt, uint8_t dnote)
1274 {
1275         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
1276         if (_selection.find(ev) != _selection.end()) {
1277                 uint8_t lowest_note_in_selection  = midi_stream_view()->lowest_note();
1278                 uint8_t highest_note_in_selection = midi_stream_view()->highest_note();
1279                 uint8_t highest_note_difference = 0;
1280
1281                 // find highest and lowest notes first
1282                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1283                         uint8_t pitch = (*i)->note()->note();
1284                         lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
1285                         highest_note_in_selection = std::max(highest_note_in_selection, pitch);
1286                 }
1287                 
1288                 /*
1289                 cerr << "dnote: " << (int) dnote << endl;
1290                 cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note()) 
1291                      << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
1292                 cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): " 
1293                      << int(highest_note_in_selection) << endl;
1294                 cerr << "selection size: " << _selection.size() << endl;
1295                 cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
1296                 */
1297                 
1298                 // Make sure the note pitch does not exceed the MIDI standard range
1299                 if (dnote <= 127 && (highest_note_in_selection + dnote > 127)) {
1300                         highest_note_difference = highest_note_in_selection - 127;
1301                 }
1302                 
1303                 start_delta_command(_("move notes"));
1304
1305                 for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
1306                         Selection::iterator next = i;
1307                         ++next;
1308
1309                         const boost::shared_ptr<NoteType> copy(new NoteType(*(*i)->note().get()));
1310
1311                         // we need to snap here again in nframes64_t in order to be sample accurate 
1312                         double start_frames = snap_to_frame(beats_to_frames((*i)->note()->time()) + dt);
1313
1314                         // keep notes inside region if dragged beyond left region bound
1315                         if (start_frames < _region->start()) {                          
1316                                 start_frames = _region->start();
1317                         }
1318                         
1319                         copy->set_time(frames_to_beats(start_frames));
1320
1321                         uint8_t original_pitch = (*i)->note()->note();
1322                         uint8_t new_pitch = original_pitch + dnote - highest_note_difference;
1323                         
1324                         // keep notes in standard midi range
1325                         clamp_to_0_127(new_pitch);
1326                         
1327                         // keep original pitch if note is dragged outside valid midi range
1328                         if ((original_pitch != 0 && new_pitch == 0)
1329                                         || (original_pitch != 127 && new_pitch == 127)) {
1330                                 new_pitch = original_pitch;
1331                         }
1332
1333                         lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
1334                         highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
1335
1336                         copy->set_note(new_pitch);
1337                         
1338                         command_remove_note(*i);
1339                         command_add_note(copy, (*i)->selected());
1340
1341                         i = next;
1342                 }
1343
1344                 apply_command();
1345                 
1346                 // care about notes being moved beyond the upper/lower bounds on the canvas
1347                 if (lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
1348                                 highest_note_in_selection > midi_stream_view()->highest_note()) {
1349                         midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
1350                 }
1351         }
1352 }
1353
1354 nframes64_t
1355 MidiRegionView::snap_to_frame(double x)
1356 {
1357         PublicEditor &editor = trackview.editor();
1358         // x is region relative, convert it to global absolute frames
1359         nframes64_t frame = editor.pixel_to_frame(x) + _region->position();
1360         editor.snap_to(frame);
1361         return frame - _region->position(); // convert back to region relative
1362 }
1363
1364 nframes64_t
1365 MidiRegionView::snap_to_frame(nframes64_t x)
1366 {
1367         PublicEditor &editor = trackview.editor();
1368         // x is region relative
1369         // convert x to global frame
1370         nframes64_t frame = x + _region->position();
1371         editor.snap_to(frame);
1372         // convert event_frame back to local coordinates relative to position
1373         frame -= _region->position();
1374         return frame;
1375 }
1376
1377 double
1378 MidiRegionView::snap_to_pixel(double x)
1379 {
1380         return (double) trackview.editor().frame_to_pixel(snap_to_frame(x));
1381 }
1382
1383 double
1384 MidiRegionView::get_position_pixels()
1385 {
1386         nframes64_t region_frame = get_position();
1387         return trackview.editor().frame_to_pixel(region_frame);
1388 }
1389
1390 nframes64_t
1391 MidiRegionView::beats_to_frames(double beats) const
1392 {
1393         const Meter& m = trackview.session().tempo_map().meter_at(_region->position());
1394         const Tempo& t = trackview.session().tempo_map().tempo_at(_region->position());
1395         return lrint(beats * m.frames_per_bar(t, trackview.session().frame_rate()) / m.beats_per_bar());
1396 }
1397
1398 double
1399 MidiRegionView::frames_to_beats(nframes64_t frames) const
1400 {
1401         const Meter& m = trackview.session().tempo_map().meter_at(_region->position());
1402         const Tempo& t = trackview.session().tempo_map().tempo_at(_region->position());
1403         return frames / m.frames_per_bar(t, trackview.session().frame_rate()) * m.beats_per_bar();
1404 }
1405
1406 void
1407 MidiRegionView::begin_resizing(CanvasNote::NoteEnd note_end)
1408 {
1409         _resize_data.clear();
1410
1411         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1412                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
1413
1414                 // only insert CanvasNotes into the map
1415                 if (note) {
1416                         NoteResizeData *resize_data = new NoteResizeData();
1417                         resize_data->canvas_note = note;
1418
1419                         // create a new SimpleRect from the note which will be the resize preview
1420                         SimpleRect *resize_rect = new SimpleRect(
1421                                         *group, note->x1(), note->y1(), note->x2(), note->y2());
1422
1423                         // calculate the colors: get the color settings
1424                         uint32_t fill_color = UINT_RGBA_CHANGE_A(
1425                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get(),
1426                                         128);
1427
1428                         // make the resize preview notes more transparent and bright
1429                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
1430
1431                         // calculate color based on note velocity
1432                         resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
1433                                         CanvasNoteEvent::meter_style_fill_color(note->note()->velocity()),
1434                                         fill_color,
1435                                         0.85);
1436
1437                         resize_rect->property_outline_color_rgba() = CanvasNoteEvent::calculate_outline(
1438                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get());
1439
1440                         resize_data->resize_rect = resize_rect;
1441
1442                         if (note_end == CanvasNote::NOTE_ON) {
1443                                 resize_data->current_x = note->x1();
1444                         } else { // NOTE_OFF
1445                                 resize_data->current_x = note->x2();
1446                         }
1447
1448                         _resize_data.push_back(resize_data);
1449                 }
1450         }
1451 }
1452
1453 void
1454 MidiRegionView::update_resizing(CanvasNote::NoteEnd note_end, double x, bool relative)
1455 {
1456         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1457                 SimpleRect* resize_rect = (*i)->resize_rect;
1458                 CanvasNote* canvas_note = (*i)->canvas_note;
1459
1460                 const double region_start = get_position_pixels();
1461
1462                 if (relative) {
1463                         (*i)->current_x = (*i)->current_x + x;
1464                 } else {
1465                         // x is in track relative, transform it to region relative
1466                         (*i)->current_x = x - region_start;
1467                 }
1468
1469                 double current_x = (*i)->current_x;
1470
1471                 if (note_end == CanvasNote::NOTE_ON) {
1472                         resize_rect->property_x1() = snap_to_pixel(current_x);
1473                         resize_rect->property_x2() = canvas_note->x2();
1474                 } else {
1475                         resize_rect->property_x2() = snap_to_pixel(current_x);
1476                         resize_rect->property_x1() = canvas_note->x1();
1477                 }
1478         }
1479 }
1480
1481 void
1482 MidiRegionView::commit_resizing(CanvasNote::NoteEnd note_end, double event_x, bool relative)
1483 {
1484         start_delta_command(_("resize notes"));
1485
1486         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1487                 CanvasNote*  canvas_note = (*i)->canvas_note;
1488                 SimpleRect*  resize_rect = (*i)->resize_rect;
1489                 double       current_x   = (*i)->current_x;
1490                 const double position    = get_position_pixels();
1491
1492                 if (!relative) {
1493                         // event_x is in track relative, transform it to region relative
1494                         current_x = event_x - position;
1495                 }
1496
1497                 // because snapping works on world coordinates we have to transform current_x
1498                 // to world coordinates before snapping and transform it back afterwards
1499                 nframes64_t current_frame = snap_to_frame(current_x);
1500                 // transform to region start relative
1501                 current_frame += _region->start();
1502                 
1503                 const boost::shared_ptr<NoteType> copy(new NoteType(*(canvas_note->note().get())));
1504
1505                 // resize beginning of note
1506                 if (note_end == CanvasNote::NOTE_ON && current_frame < copy->end_time()) {
1507                         command_remove_note(canvas_note);
1508                         copy->on_event().time() = current_frame;
1509                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1510                 }
1511                 // resize end of note
1512                 if (note_end == CanvasNote::NOTE_OFF && current_frame > copy->time()) {
1513                         command_remove_note(canvas_note);
1514                         copy->off_event().time() = current_frame;
1515                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1516                 }
1517
1518                 delete resize_rect;
1519                 delete (*i);
1520         }
1521
1522         _resize_data.clear();
1523         apply_command();
1524 }
1525
1526 void
1527 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
1528 {
1529         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1530
1531         if (relative) {
1532                 uint8_t new_velocity = copy->velocity() + velocity;
1533                 clamp_to_0_127(new_velocity);
1534                 copy->set_velocity(new_velocity);
1535         } else {
1536                 copy->set_velocity(velocity);                   
1537         }
1538
1539         command_remove_note(event);
1540         command_add_note(copy, event->selected());
1541 }
1542
1543 void
1544 MidiRegionView::change_velocity(CanvasNoteEvent* ev, int8_t velocity, bool relative)
1545 {
1546         start_delta_command(_("change velocity"));
1547         
1548         change_note_velocity(ev, velocity, relative);
1549
1550         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1551                 Selection::iterator next = i;
1552                 ++next;
1553                 if ( !(*((*i)->note()) == *(ev->note())) ) {
1554                         change_note_velocity(*i, velocity, relative);
1555                 }
1556                 i = next;
1557         }
1558         
1559         apply_command();
1560 }
1561
1562 void
1563 MidiRegionView::change_channel(uint8_t channel)
1564 {
1565         start_delta_command(_("change channel"));
1566         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1567                 Selection::iterator next = i;
1568                 ++next;
1569
1570                 CanvasNoteEvent* event = *i;
1571                 const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1572
1573                 copy->set_channel(channel);
1574                 
1575                 command_remove_note(event);
1576                 command_add_note(copy, event->selected());
1577                 
1578                 i = next;
1579         }
1580         
1581         apply_command();
1582 }
1583
1584
1585 void
1586 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
1587 {
1588         if (ev->note() && _mouse_state == EraseTouchDragging) {
1589                 start_delta_command(_("note entered"));
1590                 ev->selected(true);
1591                 _delta_command->remove(ev->note());
1592         } else if (_mouse_state == SelectTouchDragging) {
1593                 note_selected(ev, true);
1594         }
1595 }
1596
1597
1598 void
1599 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
1600 {
1601         boost::shared_ptr<MidiSource> msrc = boost::dynamic_pointer_cast<MidiSource>(src);
1602         if (msrc)
1603                 display_model(msrc->model());
1604 }
1605
1606 void
1607 MidiRegionView::set_frame_color()
1608 {
1609         if (frame) {
1610                 if (_selected && should_show_selection) {
1611                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
1612                 } else {
1613                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
1614                 }
1615         }
1616 }
1617
1618 void 
1619 MidiRegionView::midi_channel_mode_changed(ChannelMode mode, uint16_t mask)
1620 {
1621         switch (mode) {
1622         case AllChannels:
1623         case FilterChannels:
1624                 _force_channel = -1;
1625                 break;
1626         case ForceChannel:
1627                 _force_channel = mask;
1628                 mask = 0xFFFF; // Show all notes as active (below)
1629         };
1630
1631         // Update notes for selection
1632         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1633                 (*i)->on_channel_selection_change(mask);
1634         }
1635
1636         _last_channel_selection = mask;
1637 }
1638
1639 void 
1640 MidiRegionView::midi_patch_settings_changed(std::string model, std::string custom_device_mode)
1641 {
1642         _model_name         = model;
1643         _custom_device_mode = custom_device_mode;
1644         redisplay_model();
1645 }
1646