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