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