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