* bugfix in midi editing: adding notes impossible after delete
[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
37 #include "streamview.h"
38 #include "midi_region_view.h"
39 #include "midi_streamview.h"
40 #include "midi_time_axis.h"
41 #include "simpleline.h"
42 #include "canvas-hit.h"
43 #include "public_editor.h"
44 #include "ghostregion.h"
45 #include "midi_time_axis.h"
46 #include "automation_time_axis.h"
47 #include "automation_region_view.h"
48 #include "utils.h"
49 #include "midi_util.h"
50 #include "gui_thread.h"
51 #include "keyboard.h"
52
53 #include "i18n.h"
54
55 using namespace sigc;
56 using namespace ARDOUR;
57 using namespace PBD;
58 using namespace Editing;
59 using namespace ArdourCanvas;
60
61 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color)
62         : RegionView (parent, tv, r, spu, basic_color)
63         , _default_note_length(0.0)
64         , _active_notes(0)
65         , _note_group(new ArdourCanvas::Group(*parent))
66         , _delta_command(NULL)
67         , _mouse_state(None)
68         , _pressed_button(0)
69 {
70         group->lower_to_bottom();
71         _note_group->raise_to_top();
72
73         frame->property_fill_color_rgba() = 0xff000033;
74 }
75
76 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color, TimeAxisViewItem::Visibility visibility)
77         : RegionView (parent, tv, r, spu, basic_color, visibility)
78         , _default_note_length(0.0)
79         , _active_notes(0)
80         , _note_group(new ArdourCanvas::Group(*parent))
81         , _delta_command(NULL)
82         , _mouse_state(None)
83         , _pressed_button(0)
84 {
85         _note_group->raise_to_top();
86 }
87
88 void
89 MidiRegionView::init (Gdk::Color& basic_color, bool wfd)
90 {
91         if (wfd)
92                 midi_region()->midi_source(0)->load_model();
93
94         const Meter& m = trackview.session().tempo_map().meter_at(_region->position());
95         const Tempo& t = trackview.session().tempo_map().tempo_at(_region->position());
96         _default_note_length = m.frames_per_bar(t, trackview.session().frame_rate())
97                         / m.beats_per_bar();
98
99         _model = midi_region()->midi_source(0)->model();
100         _enable_display = false;
101
102         RegionView::init(basic_color, false);
103
104         compute_colors (basic_color);
105
106         reset_width_dependent_items ((double) _region->length() / samples_per_unit);
107
108         set_y_position_and_height (0, trackview.height);
109
110         region_muted ();
111         region_resized (BoundsChanged);
112         region_locked ();
113
114         _region->StateChanged.connect (mem_fun(*this, &MidiRegionView::region_changed));
115
116         set_colors ();
117
118         _enable_display = true;
119
120         if (_model) {
121                 if (wfd) {
122                         redisplay_model();
123                 }
124                 _model->ContentsChanged.connect(sigc::mem_fun(this, &MidiRegionView::redisplay_model));
125         }
126
127         midi_region()->midi_source(0)->Switched.connect(sigc::mem_fun(this, &MidiRegionView::switch_source));
128
129         group->signal_event().connect (mem_fun (this, &MidiRegionView::canvas_event), false);
130
131 }
132
133 bool
134 MidiRegionView::canvas_event(GdkEvent* ev)
135 {
136         static bool delete_mod = false;
137         static Editing::MidiEditMode original_mode;
138
139         static double drag_start_x, drag_start_y;
140         static double last_x, last_y;
141         double event_x, event_y;
142         nframes_t event_frame = 0;
143
144         static ArdourCanvas::SimpleRect* drag_rect = NULL;
145
146         if (trackview.editor.current_mouse_mode() != MouseNote)
147                 return false;
148
149         // Mmmm, spaghetti
150
151         switch (ev->type) {
152         case GDK_KEY_PRESS:
153                 if (ev->key.keyval == GDK_Delete && !delete_mod) {
154                         delete_mod = true;
155                         original_mode = trackview.editor.current_midi_edit_mode();
156                         trackview.editor.set_midi_edit_mode(MidiEditErase);
157                         start_delta_command(_("erase notes"));
158                         _mouse_state = EraseTouchDragging;
159                         return true;
160                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
161                         _mouse_state = SelectTouchDragging;
162                         return true;
163                 } else if (ev->key.keyval == GDK_Escape) {
164                         clear_selection();
165                         _mouse_state = None;
166                 }
167                 return false;
168
169         case GDK_KEY_RELEASE:
170                 if (ev->key.keyval == GDK_Delete) {
171                         if (_mouse_state == EraseTouchDragging) {
172                                 delete_selection();
173                                 apply_command();
174                         }
175                         if (delete_mod) {
176                                 trackview.editor.set_midi_edit_mode(original_mode);
177                                 _mouse_state = None;
178                                 delete_mod = false;
179                         }
180                         return true;
181                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
182                         _mouse_state = None;
183                         return true;
184                 }
185                 return false;
186
187         case GDK_BUTTON_PRESS:
188                 if (_mouse_state != SelectTouchDragging && 
189                         _mouse_state != EraseTouchDragging &&
190                         ev->button.button == 1  ) {
191                         _pressed_button = ev->button.button;
192                         _mouse_state = Pressed;
193                         return true;
194                 }
195                 _pressed_button = ev->button.button;
196                 return false;
197
198         case GDK_ENTER_NOTIFY:
199                 /* FIXME: do this on switch to note tool, too, if the pointer is already in */
200                 Keyboard::magic_widget_grab_focus();
201                 group->grab_focus();
202                 break;
203
204         case GDK_MOTION_NOTIFY:
205                 event_x = ev->motion.x;
206                 event_y = ev->motion.y;
207                 group->w2i(event_x, event_y);
208
209                 // convert event_x to global frame
210                 event_frame = trackview.editor.pixel_to_frame(event_x) + _region->position();
211                 trackview.editor.snap_to(event_frame);
212                 // convert event_frame back to local coordinates relative to position
213                 event_frame -= _region->position();
214
215                 switch (_mouse_state) {
216                 case Pressed: // Drag start
217
218                         // Select drag start
219                         if (_pressed_button == 1 && trackview.editor.current_midi_edit_mode() == MidiEditSelect) {
220                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
221                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
222                                 last_x = event_x;
223                                 last_y = event_y;
224                                 drag_start_x = event_x;
225                                 drag_start_y = event_y;
226
227                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
228                                 drag_rect->property_x1() = event_x;
229                                 drag_rect->property_y1() = event_y;
230                                 drag_rect->property_x2() = event_x;
231                                 drag_rect->property_y2() = event_y;
232                                 drag_rect->property_outline_what() = 0xFF;
233                                 drag_rect->property_outline_color_rgba()
234                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
235                                 drag_rect->property_fill_color_rgba()
236                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
237
238                                 _mouse_state = SelectRectDragging;
239                                 return true;
240
241                         // Add note drag start
242                         } else if (trackview.editor.current_midi_edit_mode() == MidiEditPencil) {
243                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
244                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
245                                 last_x = event_x;
246                                 last_y = event_y;
247                                 drag_start_x = event_x;
248                                 drag_start_y = event_y;
249
250                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
251                                 drag_rect->property_x1() = trackview.editor.frame_to_pixel(event_frame);
252
253                                 drag_rect->property_y1() = midi_stream_view()->note_to_y(midi_stream_view()->y_to_note(event_y));
254                                 drag_rect->property_x2() = event_x;
255                                 drag_rect->property_y2() = drag_rect->property_y1() + floor(midi_stream_view()->note_height());
256                                 drag_rect->property_outline_what() = 0xFF;
257                                 drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
258
259                                 drag_rect->property_fill_color_rgba() = 0xFFFFFF66;
260
261                                 _mouse_state = AddDragging;
262                                 return true;
263                         }
264
265                         return false;
266
267                 case SelectRectDragging: // Select drag motion
268                 case AddDragging: // Add note drag motion
269                         if (ev->motion.is_hint) {
270                                 int t_x;
271                                 int t_y;
272                                 GdkModifierType state;
273                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
274                                 event_x = t_x;
275                                 event_y = t_y;
276                         }
277
278                         if (_mouse_state == AddDragging)
279                                 event_x = trackview.editor.frame_to_pixel(event_frame);
280
281                         if (drag_rect)
282                                 if (event_x > drag_start_x)
283                                         drag_rect->property_x2() = event_x;
284                                 else
285                                         drag_rect->property_x1() = event_x;
286
287                         if (drag_rect && _mouse_state == SelectRectDragging) {
288                                 if (event_y > drag_start_y)
289                                         drag_rect->property_y2() = event_y;
290                                 else
291                                         drag_rect->property_y1() = event_y;
292
293                                 update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
294                         }
295
296                         last_x = event_x;
297                         last_y = event_y;
298
299                 case EraseTouchDragging:
300                 case SelectTouchDragging:
301                         return false;
302
303                 default:
304                         break;
305                 }
306                 break;
307
308         case GDK_BUTTON_RELEASE:
309                 event_x = ev->motion.x;
310                 event_y = ev->motion.y;
311                 group->w2i(event_x, event_y);
312                 group->ungrab(ev->button.time);
313                 event_frame = trackview.editor.pixel_to_frame(event_x);
314
315                 if(_pressed_button != 1) {
316                         return false;
317                 }
318                         
319                 switch (_mouse_state) {
320                 case Pressed: // Clicked
321                         switch (trackview.editor.current_midi_edit_mode()) {
322                         case MidiEditSelect:
323                         case MidiEditResize:
324                                 clear_selection();
325                                 break;
326                         case MidiEditPencil:
327                                 create_note_at(event_x, event_y, _default_note_length);
328                         default:
329                                 break;
330                         }
331                         _mouse_state = None;
332                         return true;
333                 case SelectRectDragging: // Select drag done
334                         _mouse_state = None;
335                         delete drag_rect;
336                         drag_rect = NULL;
337                         return true;
338                 case AddDragging: // Add drag done
339                         _mouse_state = None;
340                         if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
341                                 const double x      = drag_rect->property_x1();
342                                 const double length = trackview.editor.pixel_to_frame(
343                                                         drag_rect->property_x2() - drag_rect->property_x1());
344                                         
345                                 create_note_at(x, drag_rect->property_y1(), length);
346                         }
347
348                         delete drag_rect;
349                         drag_rect = NULL;
350                         return true;
351                 default:
352                         break;
353                 }
354
355         default:
356                 break;
357         }
358
359         return false;
360 }
361
362
363 /** Add a note to the model, and the view, at a canvas (click) coordinate */
364 void
365 MidiRegionView::create_note_at(double x, double y, double duration)
366 {
367         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
368         MidiStreamView* const view = mtv->midi_view();
369
370         double note = midi_stream_view()->y_to_note(y);
371
372         assert(note >= 0.0);
373         assert(note <= 127.0);
374
375         nframes_t new_note_time = trackview.editor.pixel_to_frame (x);
376         assert(new_note_time >= 0);
377         new_note_time += _region->start();
378
379         /*
380         const Meter& m = trackview.session().tempo_map().meter_at(new_note_time);
381         const Tempo& t = trackview.session().tempo_map().tempo_at(new_note_time);
382         double duration = m.frames_per_bar(t, trackview.session().frame_rate()) / m.beats_per_bar();
383         */
384         
385         // we need to snap here again in nframes_t in order to be sample accurate 
386         // since note time is region-absolute but snap_to_frame expects position-relative
387         // time we have to coordinate transform back and forth here.
388         nframes_t new_note_time_position_relative = new_note_time      - _region->start(); 
389         new_note_time = snap_to_frame(new_note_time_position_relative) + _region->start();
390         
391         // we need to snap the duration too to be sample accurate
392         nframes_t new_note_duration = nframes_t(duration);
393         new_note_duration = snap_to_frame(new_note_time_position_relative + new_note_duration) + _region->start() 
394                             - new_note_time;
395
396         const boost::shared_ptr<Note> new_note(new Note(0, new_note_time, new_note_duration, (uint8_t)note, 0x40));
397         view->update_bounds(new_note->note());
398
399         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
400         cmd->add(new_note);
401         _model->apply_command(cmd);
402
403         //add_note(new_note);
404 }
405
406
407 void
408 MidiRegionView::clear_events()
409 {
410         clear_selection();
411
412         MidiGhostRegion* gr;
413         for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
414                 if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
415                         gr->clear_events();
416                 }
417         }
418
419         for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i)
420                 delete *i;
421
422         _events.clear();
423 }
424
425
426 void
427 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
428 {
429         _model = model;
430
431         if (_enable_display)
432                 redisplay_model();
433 }
434
435
436 void
437 MidiRegionView::redisplay_model()
438 {
439         // Don't redisplay the model if we're currently recording and displaying that
440         if (_active_notes)
441                 return;
442
443         if (_model) {
444
445                 clear_events();
446                 begin_write();
447
448                 _model->read_lock();
449
450                 /*
451                 MidiModel::Notes notes = _model->notes();
452                 cerr << endl << "Model contains " << notes.size() << " Notes:" << endl;
453                 for(MidiModel::Notes::iterator i = notes.begin(); i != notes.end(); ++i) {
454                         Note note = *(*i).get();
455                         cerr << "MODEL: Note time: " << note.time() << " duration: " << note.duration() 
456                              << "   end-time: " << note.end_time() 
457                              << "   velocity: " << int(note.velocity()) 
458                              //<< " Note-on: " << note.on_event(). 
459                              //<< " Note-off: " << note.off_event() 
460                              << endl;
461                 }*/
462                 
463                 for (size_t i=0; i < _model->n_notes(); ++i) {
464                         add_note(_model->note_at(i));
465                 }
466
467                 end_write();
468
469                 /*for (Automatable::Controls::const_iterator i = _model->controls().begin();
470                                 i != _model->controls().end(); ++i) {
471
472                         assert(i->second);
473
474                         boost::shared_ptr<AutomationTimeAxisView> at
475                                 = midi_view()->automation_child(i->second->parameter());
476                         if (!at)
477                                 continue;
478
479                         Gdk::Color col = midi_stream_view()->get_region_color();
480
481                         boost::shared_ptr<AutomationRegionView> arv;
482
483                         {
484                                 Glib::Mutex::Lock list_lock (i->second->list()->lock());
485
486                                 arv = boost::shared_ptr<AutomationRegionView>(
487                                                 new AutomationRegionView(at->canvas_display,
488                                                         *at.get(), _region, i->second->list(),
489                                                         midi_stream_view()->get_samples_per_unit(), col));
490                         }
491
492                         arv->set_duration(_region->length(), this);
493                         arv->init(col, true);
494
495                         _automation_children.insert(std::make_pair(i->second->parameter(), arv));
496                 }*/
497
498                 _model->read_unlock();
499
500         } else {
501                 cerr << "MidiRegionView::redisplay_model called without a model" << endmsg;
502         }
503 }
504
505
506 MidiRegionView::~MidiRegionView ()
507 {
508         in_destructor = true;
509
510         RegionViewGoingAway (this); /* EMIT_SIGNAL */
511
512         if (_active_notes)
513                 end_write();
514
515         _selection.clear();
516         clear_events();
517         delete _note_group;
518         delete _delta_command;
519 }
520
521
522 void
523 MidiRegionView::region_resized (Change what_changed)
524 {
525         RegionView::region_resized(what_changed);
526         
527         if (what_changed & ARDOUR::PositionChanged) {
528                 if (_enable_display)
529                         redisplay_model();
530         } 
531 }
532
533 void
534 MidiRegionView::reset_width_dependent_items (double pixel_width)
535 {
536         RegionView::reset_width_dependent_items(pixel_width);
537         assert(_pixel_width == pixel_width);
538
539         if (_enable_display)
540                 redisplay_model();
541 }
542
543 void
544 MidiRegionView::set_y_position_and_height (double y, double h)
545 {
546         RegionView::set_y_position_and_height(y, h - 1);
547
548         if (_enable_display) {
549
550                 _model->read_lock();
551
552                 for (std::vector<CanvasMidiEvent*>::const_iterator i = _events.begin(); i != _events.end(); ++i) {
553                         CanvasNote* note = dynamic_cast<CanvasNote*>(*i);
554                         if (note && note->note()) {
555                                 if (note->note()->note() < midi_stream_view()->lowest_note() ||
556                                    note->note()->note() > midi_stream_view()->highest_note()) {
557                                         if (canvas_item_visible(note)) {
558                                                 note->hide();
559                                         }
560                                 }
561                                 else {
562                                         const double y1 = midi_stream_view()->note_to_y(note->note()->note());
563                                         const double y2 = y1 + floor(midi_stream_view()->note_height());
564
565                                         if (!canvas_item_visible(note)) {
566                                                 note->show();
567                                         }
568
569                                         note->hide_velocity();
570                                         note->property_y1() = y1;
571                                         note->property_y2() = y2;
572                                         if(note->selected()) {
573                                                 note->show_velocity();
574                                 }
575                         }
576                 }
577                 }
578
579                 _model->read_unlock();
580         }
581
582         if (name_text) {
583                 name_text->raise_to_top();
584         }
585 }
586
587 GhostRegion*
588 MidiRegionView::add_ghost (TimeAxisView& tv)
589 {
590         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
591         CanvasNote* note;
592         assert(rtv);
593
594         double unit_position = _region->position () / samples_per_unit;
595         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
596         MidiGhostRegion* ghost;
597
598         if (mtv && mtv->midi_view()) {
599                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group.
600                    this is because it's nice to have midi notes on top of the note lines and
601                    audio waveforms under it.
602                  */
603                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
604         }
605         else {
606                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
607         }
608
609         ghost->set_height ();
610         ghost->set_duration (_region->length() / samples_per_unit);
611         ghosts.push_back (ghost);
612
613         for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i) {
614                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
615                         ghost->add_note(note);
616                 }
617         }
618
619         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
620
621         return ghost;
622 }
623
624
625 /** Begin tracking note state for successive calls to add_event
626  */
627 void
628 MidiRegionView::begin_write()
629 {
630         assert(!_active_notes);
631         _active_notes = new CanvasNote*[128];
632         for (unsigned i=0; i < 128; ++i)
633                 _active_notes[i] = NULL;
634 }
635
636
637 /** Destroy note state for add_event
638  */
639 void
640 MidiRegionView::end_write()
641 {
642         delete[] _active_notes;
643         _active_notes = NULL;
644         _marked_for_selection.clear();
645 }
646
647
648 /** Resolve an active MIDI note (while recording).
649  */
650 void
651 MidiRegionView::resolve_note(uint8_t note, double end_time)
652 {
653         if (midi_view()->note_mode() != Sustained)
654                 return;
655
656         if (_active_notes && _active_notes[note]) {
657                 _active_notes[note]->property_x2() = trackview.editor.frame_to_pixel((nframes_t)end_time);
658                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
659                 _active_notes[note] = NULL;
660         }
661 }
662
663
664 /** Extend active notes to rightmost edge of region (if length is changed)
665  */
666 void
667 MidiRegionView::extend_active_notes()
668 {
669         if (!_active_notes)
670                 return;
671
672         for (unsigned i=0; i < 128; ++i)
673                 if (_active_notes[i])
674                         _active_notes[i]->property_x2() = trackview.editor.frame_to_pixel(_region->length());
675 }
676
677
678 /** Add a MIDI note to the view (with duration).
679  *
680  * If in sustained mode, notes with duration 0 will be considered active
681  * notes, and resolve_note should be called when the corresponding note off
682  * event arrives, to properly display the note.
683  */
684 void
685 MidiRegionView::add_note(const boost::shared_ptr<Note> note)
686 {
687         assert(note->time() >= 0);
688         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
689         
690         // dont display notes beyond the region bounds
691         if(
692                         note->time() - _region->start() >= _region->length() ||
693                         note->time() <  _region->start() ||
694                         note->note() < midi_stream_view()->lowest_note() ||
695                         note->note() > midi_stream_view()->highest_note()
696           ) {
697                 return;
698         }
699         
700         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
701
702         CanvasMidiEvent *event = 0;
703         
704         const double x = trackview.editor.frame_to_pixel((nframes_t)note->time() - _region->start());
705         
706         if (midi_view()->note_mode() == Sustained) {
707
708                 //cerr << "MRV::add_note sustained " << note->note() << " @ " << note->time()
709                 //      << " .. " << note->end_time() << endl;
710                 
711                 const double y1 = midi_stream_view()->note_to_y(note->note());
712                 const double note_endpixel = 
713                         trackview.editor.frame_to_pixel((nframes_t)note->end_time() - _region->start());
714                 
715                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
716                 ev_rect->property_x1() = x;
717                 ev_rect->property_y1() = y1;
718                 if (note->duration() > 0)
719                         ev_rect->property_x2() = note_endpixel;
720                 else
721                         ev_rect->property_x2() = trackview.editor.frame_to_pixel(_region->length());
722                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
723
724                 ev_rect->property_fill_color_rgba() = note_fill_color(note->velocity());
725                 ev_rect->property_outline_color_rgba() = note_outline_color(note->velocity());
726
727                 if (note->duration() == 0) {
728                         _active_notes[note->note()] = ev_rect;
729                         /* outline all but right edge */
730                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
731                 } else {
732                         /* outline all edges */
733                         ev_rect->property_outline_what() = (guint32) 0xF;
734                 }
735
736                 ev_rect->show();
737                 _events.push_back(ev_rect);
738                 event = ev_rect;
739
740                 MidiGhostRegion* gr;
741
742                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
743                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
744                                 gr->add_note(ev_rect);
745                         }
746                 }
747
748         } else if (midi_view()->note_mode() == Percussive) {
749
750                 //cerr << "MRV::add_note percussive " << note->note() << " @ " << note->time()
751                 //      << " .. " << note->end_time() << endl;
752
753                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
754                 const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
755
756                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size);
757                 ev_diamond->move(x, y);
758                 ev_diamond->show();
759                 ev_diamond->property_fill_color_rgba() = note_fill_color(note->velocity());
760                 ev_diamond->property_outline_color_rgba() = note_outline_color(note->velocity());
761                 _events.push_back(ev_diamond);
762                 event = ev_diamond;
763         } else {
764                 event = 0;
765         }
766
767         if(event) {                     
768                 if(_marked_for_selection.find(event->note()) != _marked_for_selection.end()) {
769                                 note_selected(event, true);
770                 }
771         }
772 }
773
774 void
775 MidiRegionView::delete_selection()
776 {
777         assert(_delta_command);
778
779         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
780                 if ((*i)->selected())
781                         _delta_command->remove((*i)->note());
782
783         _selection.clear();
784 }
785
786 void
787 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasMidiEvent* ev)
788 {
789         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
790                 if ((*i)->selected() && (*i) != ev)
791                         (*i)->selected(false);
792
793         _selection.clear();
794 }
795
796 void
797 MidiRegionView::unique_select(ArdourCanvas::CanvasMidiEvent* ev)
798 {
799         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
800                 if ((*i) != ev)
801                         (*i)->selected(false);
802
803         _selection.clear();
804         _selection.insert(ev);
805
806         if ( ! ev->selected())
807                 ev->selected(true);
808 }
809
810 void
811 MidiRegionView::note_selected(ArdourCanvas::CanvasMidiEvent* ev, bool add)
812 {
813         if ( ! add)
814                 clear_selection_except(ev);
815
816         _selection.insert(ev);
817
818         if ( ! ev->selected())
819                 ev->selected(true);
820 }
821
822
823 void
824 MidiRegionView::note_deselected(ArdourCanvas::CanvasMidiEvent* ev, bool add)
825 {
826         if ( ! add)
827                 clear_selection_except(ev);
828
829         _selection.erase(ev);
830
831         if (ev->selected())
832                 ev->selected(false);
833 }
834
835
836 void
837 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2)
838 {
839         const double last_y = std::min(y1, y2);
840         const double y      = std::max(y1, y2);
841
842         // FIXME: so, so, so much slower than this should be
843
844         if (x1 < x2) {
845                 for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i) {
846                         if ((*i)->x1() >= x1 && (*i)->x1() <= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
847                                 (*i)->selected(true);
848                                 _selection.insert(*i);
849                         } else {
850                                 (*i)->selected(false);
851                                 _selection.erase(*i);
852                         }
853                 }
854         } else {
855                 for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i) {
856                         if ((*i)->x2() <= x1 && (*i)->x2() >= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
857                                 (*i)->selected(true);
858                                 _selection.insert(*i);
859                         } else {
860                                 (*i)->selected(false);
861                                 _selection.erase(*i);
862                         }
863                 }
864         }
865 }
866
867
868 void
869 MidiRegionView::move_selection(double dx, double dy)
870 {
871         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
872                 (*i)->move_event(dx, dy);
873 }
874
875
876 void
877 MidiRegionView::note_dropped(CanvasMidiEvent* ev, double dt, uint8_t dnote)
878 {
879         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
880         if (_selection.find(ev) != _selection.end()) {
881                 uint8_t lowest_note_in_selection  = midi_stream_view()->lowest_note();
882                 uint8_t highest_note_in_selection = midi_stream_view()->highest_note();
883                 uint8_t highest_note_difference = 0;
884
885                 // find highest and lowest notes first
886                 for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
887                         Selection::iterator next = i;
888                         ++next;
889                         
890                         uint8_t pitch = (*i)->note()->note();
891                         lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
892                         highest_note_in_selection = std::max(highest_note_in_selection, pitch);
893
894                         i = next;
895                 }
896                 
897                 /*
898                 cerr << "dnote: " << (int) dnote << endl;
899                 cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note()) 
900                      << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
901                 cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): " 
902                      << int(highest_note_in_selection) << endl;
903                 cerr << "selection size: " << _selection.size() << endl;
904                 cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
905                 */
906                 
907                 // Make sure the note pitch does not exceed the MIDI standard range
908                 if (dnote <= 127 && (highest_note_in_selection + dnote > 127)) {
909                         highest_note_difference = highest_note_in_selection - 127;
910                 }
911                 
912                 start_delta_command(_("move notes"));
913
914                 for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
915                         Selection::iterator next = i;
916                         ++next;
917
918                         const boost::shared_ptr<Note> copy(new Note(*(*i)->note().get()));
919
920                         // we need to snap here again in nframes_t in order to be sample accurate 
921                         double new_note_time = (*i)->note()->time();
922                         new_note_time +=  dt;
923
924                         // keep notes inside region if dragged beyond left region bound
925                         if(new_note_time < _region->start()) {                          
926                                 new_note_time = _region->start();
927                         }
928                         
929                         // since note time is region-absolute but snap_to_frame expects position-relative
930                         // time we have to coordinate transform back and forth here.
931                         new_note_time = snap_to_frame(nframes_t(new_note_time) - _region->start()) + _region->start();
932                         
933                         copy->set_time(new_note_time);
934
935                         uint8_t original_pitch = (*i)->note()->note();
936                         uint8_t new_pitch =  original_pitch + dnote - highest_note_difference;
937                         
938                         // keep notes in standard midi range
939                         clamp_0_to_127(new_pitch);
940                         
941                         //notes which are dragged beyond the standard midi range snap back to their original place
942                         if((original_pitch != 0 && new_pitch == 0) || (original_pitch != 127 && new_pitch == 127)) {
943                                 new_pitch = original_pitch;
944                         }
945
946                         lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
947                         highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
948
949                         copy->set_note(new_pitch);
950                         
951                         command_remove_note(*i);
952                         command_add_note(copy);
953
954                         _marked_for_selection.insert(copy);
955                         i = next;
956                 }
957                 apply_command();
958                 
959                 // care about notes being moved beyond the upper/lower bounds on the canvas
960                 if(lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
961                    highest_note_in_selection > midi_stream_view()->highest_note()
962                 ) {
963                         midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
964         }
965 }
966 }
967
968 nframes_t
969 MidiRegionView::snap_to_frame(double x)
970 {
971         PublicEditor &editor = trackview.editor;
972         // x is region relative
973         // convert x to global frame
974         nframes_t frame = editor.pixel_to_frame(x) + _region->position();
975         editor.snap_to(frame);
976         // convert event_frame back to local coordinates relative to position
977         frame -= _region->position();
978         return frame;
979 }
980
981 nframes_t
982 MidiRegionView::snap_to_frame(nframes_t x)
983 {
984         PublicEditor &editor = trackview.editor;
985         // x is region relative
986         // convert x to global frame
987         nframes_t frame = x + _region->position();
988         editor.snap_to(frame);
989         // convert event_frame back to local coordinates relative to position
990         frame -= _region->position();
991         return frame;
992 }
993
994 double
995 MidiRegionView::snap_to_pixel(double x)
996 {
997         return (double) trackview.editor.frame_to_pixel(snap_to_frame(x));
998 }
999
1000 double
1001 MidiRegionView::get_position_pixels(void)
1002 {
1003         nframes_t  region_frame  = get_position();
1004         return trackview.editor.frame_to_pixel(region_frame);
1005 }
1006
1007 void
1008 MidiRegionView::begin_resizing(CanvasNote::NoteEnd note_end)
1009 {
1010         _resize_data.clear();
1011
1012         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1013                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
1014
1015                 // only insert CanvasNotes into the map
1016                 if(note) {
1017                         NoteResizeData *resize_data = new NoteResizeData();
1018                         resize_data->canvas_note = note;
1019
1020                         // create a new SimpleRect from the note which will be the resize preview
1021                         SimpleRect *resize_rect =
1022                                 new SimpleRect(
1023                                                 *group,
1024                                                 note->x1(),
1025                                                 note->y1(),
1026                                                 note->x2(),
1027                                                 note->y2());
1028
1029                         // calculate the colors: get the color settings
1030                         uint fill_color =
1031                                 UINT_RGBA_CHANGE_A(
1032                                                 ARDOUR_UI::config()->canvasvar_MidiNoteSelectedOutline.get(),
1033                                                 128);
1034
1035                         // make the resize preview notes more transparent and bright
1036                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
1037
1038                         // calculate color based on note velocity
1039                         resize_rect->property_fill_color_rgba() =
1040                                 UINT_INTERPOLATE(
1041                                         note_fill_color(note->note()->velocity()),
1042                                         fill_color,
1043                                         0.85);
1044
1045                         resize_rect->property_outline_color_rgba() =
1046                                 ARDOUR_UI::config()->canvasvar_MidiNoteSelectedOutline.get();
1047
1048                         resize_data->resize_rect = resize_rect;
1049
1050                         if(note_end == CanvasNote::NOTE_ON) {
1051                                 resize_data->current_x = note->x1();
1052                         } else { // NOTE_OFF
1053                                 resize_data->current_x = note->x2();
1054                         }
1055
1056                         _resize_data.push_back(resize_data);
1057                 }
1058         }
1059 }
1060
1061 void
1062 MidiRegionView::update_resizing(CanvasNote::NoteEnd note_end, double x, bool relative)
1063 {
1064         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1065                 SimpleRect     *resize_rect = (*i)->resize_rect;
1066                 CanvasNote     *canvas_note = (*i)->canvas_note;
1067
1068                 const double region_start = get_position_pixels();
1069
1070                 if(relative) {
1071                         (*i)->current_x = (*i)->current_x + x;
1072                 } else {
1073                         // x is in track relative, transform it to region relative
1074                         (*i)->current_x = x - region_start;
1075                 }
1076
1077                 double current_x = (*i)->current_x;
1078
1079                 if(note_end == CanvasNote::NOTE_ON) {
1080                         resize_rect->property_x1() = snap_to_pixel(current_x);
1081                         resize_rect->property_x2() = canvas_note->x2();
1082                 } else {
1083                         resize_rect->property_x2() = snap_to_pixel(current_x);
1084                         resize_rect->property_x1() = canvas_note->x1();
1085                 }
1086         }
1087 }
1088
1089 void
1090 MidiRegionView::commit_resizing(CanvasNote::NoteEnd note_end, double event_x, bool relative)
1091 {
1092         start_delta_command(_("resize notes"));
1093
1094         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1095                 CanvasNote *canvas_note = (*i)->canvas_note;
1096                 SimpleRect *resize_rect = (*i)->resize_rect;
1097                 double      current_x   = (*i)->current_x;
1098                 const double position = get_position_pixels();
1099
1100                 if(!relative) {
1101                         // event_x is in track relative, transform it to region relative
1102                         current_x = event_x - position;
1103                 }
1104
1105                 // because snapping works on world coordinates we have to transform current_x
1106                 // to world coordinates before snapping and transform it back afterwards
1107                 nframes_t current_frame = snap_to_frame(current_x);
1108                 // transform to region start relative
1109                 current_frame += _region->start();
1110                 
1111                 const boost::shared_ptr<Note> copy(new Note(*(canvas_note->note().get())));
1112
1113                 // resize beginning of note
1114                 if (note_end == CanvasNote::NOTE_ON && current_frame < copy->end_time()) {
1115                         command_remove_note(canvas_note);
1116                         copy->on_event().time() = current_frame;
1117                         command_add_note(copy);
1118                         _marked_for_selection.insert(copy);
1119                 }
1120                 // resize end of note
1121                 if (note_end == CanvasNote::NOTE_OFF && current_frame > copy->time()) {
1122                         command_remove_note(canvas_note);
1123                         command_remove_note(canvas_note);
1124                         copy->off_event().time() = current_frame;
1125                         command_add_note(copy);
1126                         _marked_for_selection.insert(copy);
1127                 }
1128
1129                 delete resize_rect;
1130                 delete (*i);
1131         }
1132
1133         _resize_data.clear();
1134         apply_command();
1135 }
1136
1137
1138 void
1139 MidiRegionView::change_velocity(uint8_t velocity, bool relative)
1140 {
1141         start_delta_command(_("change velocity"));
1142         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1143                 Selection::iterator next = i;
1144                 ++next;
1145
1146                 CanvasMidiEvent *event = *i;
1147                 const boost::shared_ptr<Note> copy(new Note(*(event->note().get())));
1148
1149                 if(relative) {
1150                         uint8_t new_velocity = copy->velocity() + velocity;
1151                         clamp_0_to_127(new_velocity);
1152                                 
1153                         copy->set_velocity(new_velocity);
1154                 } else { // absolute
1155                         copy->set_velocity(velocity);                   
1156                 }
1157                 
1158                 command_remove_note(event);
1159                 command_add_note(copy);
1160                 
1161                 _marked_for_selection.insert(copy);
1162                 i = next;
1163         }
1164         
1165         // dont keep notes selected if tweaking a single note
1166         if(_marked_for_selection.size() == 1) {
1167                 _marked_for_selection.clear();
1168         }
1169         
1170         apply_command();
1171 }
1172
1173 void
1174 MidiRegionView::change_channel(uint8_t channel)
1175 {
1176         start_delta_command(_("change channel"));
1177         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1178                 Selection::iterator next = i;
1179                 ++next;
1180
1181                 CanvasMidiEvent *event = *i;
1182                 const boost::shared_ptr<Note> copy(new Note(*(event->note().get())));
1183
1184                 copy->set_channel(channel);
1185                 
1186                 command_remove_note(event);
1187                 command_add_note(copy);
1188                 
1189                 _marked_for_selection.insert(copy);
1190                 i = next;
1191         }
1192         
1193         // dont keep notes selected if tweaking a single note
1194         if(_marked_for_selection.size() == 1) {
1195                 _marked_for_selection.clear();
1196         }
1197         
1198         apply_command();
1199 }
1200
1201
1202 void
1203 MidiRegionView::note_entered(ArdourCanvas::CanvasMidiEvent* ev)
1204 {
1205         if (ev->note() && _mouse_state == EraseTouchDragging) {
1206                 start_delta_command(_("note entered"));
1207                 ev->selected(true);
1208                 _delta_command->remove(ev->note());
1209         } else if (_mouse_state == SelectTouchDragging) {
1210                 note_selected(ev, true);
1211         }
1212 }
1213
1214
1215 void
1216 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
1217 {
1218         boost::shared_ptr<MidiSource> msrc = boost::dynamic_pointer_cast<MidiSource>(src);
1219         if (msrc)
1220                 display_model(msrc->model());
1221 }
1222
1223 void
1224 MidiRegionView::set_frame_color()
1225 {
1226         if (frame) {
1227                 if (_selected && should_show_selection) {
1228                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
1229                 } else {
1230                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
1231                 }
1232         }
1233 }