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