69f756f3ca6c7156fdc56b07a5d8150655377ebf
[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_force_channel_changed().connect(
139                         mem_fun(this, &MidiRegionView::midi_force_channel_changed));
140         midi_view()->signal_channel_selection_changed().connect(
141                         mem_fun(this, &MidiRegionView::midi_channel_selection_changed));
142 }
143
144 bool
145 MidiRegionView::canvas_event(GdkEvent* ev)
146 {
147         static bool delete_mod = false;
148         static Editing::MidiEditMode original_mode;
149
150         static double drag_start_x, drag_start_y;
151         static double last_x, last_y;
152         double event_x, event_y;
153         nframes_t event_frame = 0;
154
155         static ArdourCanvas::SimpleRect* drag_rect = NULL;
156
157         if (trackview.editor.current_mouse_mode() != MouseNote)
158                 return false;
159
160         // Mmmm, spaghetti
161
162         switch (ev->type) {
163         case GDK_KEY_PRESS:
164                 if (ev->key.keyval == GDK_Delete && !delete_mod) {
165                         delete_mod = true;
166                         original_mode = trackview.editor.current_midi_edit_mode();
167                         trackview.editor.set_midi_edit_mode(MidiEditErase);
168                         start_delta_command(_("erase notes"));
169                         _mouse_state = EraseTouchDragging;
170                         return true;
171                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
172                         _mouse_state = SelectTouchDragging;
173                         return true;
174                 } else if (ev->key.keyval == GDK_Escape) {
175                         clear_selection();
176                         _mouse_state = None;
177                 }
178                 return false;
179
180         case GDK_KEY_RELEASE:
181                 if (ev->key.keyval == GDK_Delete) {
182                         if (_mouse_state == EraseTouchDragging) {
183                                 delete_selection();
184                                 apply_command();
185                         }
186                         if (delete_mod) {
187                                 trackview.editor.set_midi_edit_mode(original_mode);
188                                 _mouse_state = None;
189                                 delete_mod = false;
190                         }
191                         return true;
192                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
193                         _mouse_state = None;
194                         return true;
195                 }
196                 return false;
197
198         case GDK_BUTTON_PRESS:
199                 if (_mouse_state != SelectTouchDragging && 
200                         _mouse_state != EraseTouchDragging &&
201                         ev->button.button == 1  ) {
202                         _pressed_button = ev->button.button;
203                         _mouse_state = Pressed;
204                         return true;
205                 }
206                 _pressed_button = ev->button.button;
207                 return false;
208
209         case GDK_ENTER_NOTIFY:
210                 /* FIXME: do this on switch to note tool, too, if the pointer is already in */
211                 Keyboard::magic_widget_grab_focus();
212                 group->grab_focus();
213                 break;
214
215         case GDK_MOTION_NOTIFY:
216                 event_x = ev->motion.x;
217                 event_y = ev->motion.y;
218                 group->w2i(event_x, event_y);
219
220                 // convert event_x to global frame
221                 event_frame = trackview.editor.pixel_to_frame(event_x) + _region->position();
222                 trackview.editor.snap_to(event_frame);
223                 // convert event_frame back to local coordinates relative to position
224                 event_frame -= _region->position();
225
226                 switch (_mouse_state) {
227                 case Pressed: // Drag start
228
229                         // Select drag start
230                         if (_pressed_button == 1 && trackview.editor.current_midi_edit_mode() == MidiEditSelect) {
231                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
232                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
233                                 last_x = event_x;
234                                 last_y = event_y;
235                                 drag_start_x = event_x;
236                                 drag_start_y = event_y;
237
238                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
239                                 drag_rect->property_x1() = event_x;
240                                 drag_rect->property_y1() = event_y;
241                                 drag_rect->property_x2() = event_x;
242                                 drag_rect->property_y2() = event_y;
243                                 drag_rect->property_outline_what() = 0xFF;
244                                 drag_rect->property_outline_color_rgba()
245                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
246                                 drag_rect->property_fill_color_rgba()
247                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
248
249                                 _mouse_state = SelectRectDragging;
250                                 return true;
251
252                         // Add note drag start
253                         } else if (trackview.editor.current_midi_edit_mode() == MidiEditPencil) {
254                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
255                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
256                                 last_x = event_x;
257                                 last_y = event_y;
258                                 drag_start_x = event_x;
259                                 drag_start_y = event_y;
260
261                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
262                                 drag_rect->property_x1() = trackview.editor.frame_to_pixel(event_frame);
263
264                                 drag_rect->property_y1() = midi_stream_view()->note_to_y(midi_stream_view()->y_to_note(event_y));
265                                 drag_rect->property_x2() = event_x;
266                                 drag_rect->property_y2() = drag_rect->property_y1() + floor(midi_stream_view()->note_height());
267                                 drag_rect->property_outline_what() = 0xFF;
268                                 drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
269
270                                 drag_rect->property_fill_color_rgba() = 0xFFFFFF66;
271
272                                 _mouse_state = AddDragging;
273                                 return true;
274                         }
275
276                         return false;
277
278                 case SelectRectDragging: // Select drag motion
279                 case AddDragging: // Add note drag motion
280                         if (ev->motion.is_hint) {
281                                 int t_x;
282                                 int t_y;
283                                 GdkModifierType state;
284                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
285                                 event_x = t_x;
286                                 event_y = t_y;
287                         }
288
289                         if (_mouse_state == AddDragging)
290                                 event_x = trackview.editor.frame_to_pixel(event_frame);
291
292                         if (drag_rect) {
293                                 if (event_x > drag_start_x)
294                                         drag_rect->property_x2() = event_x;
295                                 else
296                                         drag_rect->property_x1() = event_x;
297                         }
298
299                         if (drag_rect && _mouse_state == SelectRectDragging) {
300                                 if (event_y > drag_start_y)
301                                         drag_rect->property_y2() = event_y;
302                                 else
303                                         drag_rect->property_y1() = event_y;
304
305                                 update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
306                         }
307
308                         last_x = event_x;
309                         last_y = event_y;
310
311                 case EraseTouchDragging:
312                 case SelectTouchDragging:
313                         return false;
314
315                 default:
316                         break;
317                 }
318                 break;
319
320         case GDK_BUTTON_RELEASE:
321                 event_x = ev->motion.x;
322                 event_y = ev->motion.y;
323                 group->w2i(event_x, event_y);
324                 group->ungrab(ev->button.time);
325                 event_frame = trackview.editor.pixel_to_frame(event_x);
326
327                 if(_pressed_button != 1) {
328                         return false;
329                 }
330                         
331                 switch (_mouse_state) {
332                 case Pressed: // Clicked
333                         switch (trackview.editor.current_midi_edit_mode()) {
334                         case MidiEditSelect:
335                         case MidiEditResize:
336                                 clear_selection();
337                                 break;
338                         case MidiEditPencil:
339                                 create_note_at(event_x, event_y, _default_note_length);
340                         default:
341                                 break;
342                         }
343                         _mouse_state = None;
344                         return true;
345                 case SelectRectDragging: // Select drag done
346                         _mouse_state = None;
347                         delete drag_rect;
348                         drag_rect = NULL;
349                         return true;
350                 case AddDragging: // Add drag done
351                         _mouse_state = None;
352                         if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
353                                 const double x      = drag_rect->property_x1();
354                                 const double length = trackview.editor.pixel_to_frame(
355                                                         drag_rect->property_x2() - drag_rect->property_x1());
356                                         
357                                 create_note_at(x, drag_rect->property_y1(), length);
358                         }
359
360                         delete drag_rect;
361                         drag_rect = NULL;
362                         return true;
363                 default:
364                         break;
365                 }
366
367         default:
368                 break;
369         }
370
371         return false;
372 }
373
374
375 /** Add a note to the model, and the view, at a canvas (click) coordinate */
376 void
377 MidiRegionView::create_note_at(double x, double y, double duration)
378 {
379         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
380         MidiStreamView* const view = mtv->midi_view();
381
382         double note = midi_stream_view()->y_to_note(y);
383
384         assert(note >= 0.0);
385         assert(note <= 127.0);
386
387         nframes_t new_note_time = trackview.editor.pixel_to_frame (x);
388         assert(new_note_time >= 0);
389         new_note_time += _region->start();
390
391         /*
392         const Meter& m = trackview.session().tempo_map().meter_at(new_note_time);
393         const Tempo& t = trackview.session().tempo_map().tempo_at(new_note_time);
394         double duration = m.frames_per_bar(t, trackview.session().frame_rate()) / m.beats_per_bar();
395         */
396         
397         // we need to snap here again in nframes_t in order to be sample accurate 
398         // since note time is region-absolute but snap_to_frame expects position-relative
399         // time we have to coordinate transform back and forth here.
400         nframes_t new_note_time_position_relative = new_note_time      - _region->start(); 
401         new_note_time = snap_to_frame(new_note_time_position_relative) + _region->start();
402         
403         // we need to snap the duration too to be sample accurate
404         nframes_t new_note_duration = nframes_t(duration);
405         new_note_duration = snap_to_frame(new_note_time_position_relative + new_note_duration) + _region->start() 
406                             - new_note_time;
407
408         const boost::shared_ptr<Note> new_note(new Note(0, new_note_time, new_note_duration, (uint8_t)note, 0x40));
409         view->update_bounds(new_note->note());
410
411         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
412         cmd->add(new_note);
413         _model->apply_command(cmd);
414
415         //add_note(new_note);
416 }
417
418
419 void
420 MidiRegionView::clear_events()
421 {
422         clear_selection();
423
424         MidiGhostRegion* gr;
425         for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
426                 if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
427                         gr->clear_events();
428                 }
429         }
430
431         for (std::vector<CanvasNoteEvent*>::iterator i = _events.begin(); i != _events.end(); ++i)
432                 delete *i;
433
434         _events.clear();
435         _pgm_changes.clear();
436 }
437
438
439 void
440 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
441 {
442         _model = model;
443
444         if (_enable_display)
445                 redisplay_model();
446 }
447
448
449 void
450 MidiRegionView::redisplay_model()
451 {
452         // Don't redisplay the model if we're currently recording and displaying that
453         if (_active_notes)
454                 return;
455
456         if (_model) {
457
458                 clear_events();
459                 _model->read_lock();
460                 
461                 MidiModel::Notes notes = _model->notes();
462                 cerr << endl << "Model contains " << notes.size() << " Notes:" << endl;
463                 for(MidiModel::Notes::iterator i = notes.begin(); i != notes.end(); ++i) {
464                         cerr << "MODEL: Note time: " << (*i)->time()
465                                  << " pitch: " << int((*i)->note()) 
466                              << " duration: " << (*i)->duration() 
467                              << "   end-time: " << (*i)->end_time() 
468                              << "   velocity: " << int((*i)->velocity()) 
469                              //<< " Note-on: " << note.on_event(). 
470                              //<< " Note-off: " << note.off_event() 
471                              << endl;
472                 }
473                 
474                 for (size_t i = 0; i < _model->n_notes(); ++i) {
475                         add_note(_model->note_at(i));
476                 }
477
478                 for (Automatable::Controls::iterator 
479                      control = _model->controls().begin();
480                                 control != _model->controls().end(); ++control) {
481
482                         if( control->first.type() == MidiPgmChangeAutomation ) {
483                                 Glib::Mutex::Lock list_lock (control->second->list()->lock());
484                                 
485                                 for(AutomationList::const_iterator event = control->second->list()->begin();
486                                 event != control->second->list()->end(); ++event) {
487                                         boost::shared_ptr<MIDI::Event> midi_event(new MIDI::Event());
488                                         MidiControlIterator iter(control->second->list(), (*event)->when, (*event)->value);
489                                         _model->control_to_midi_event(*midi_event, iter);
490                                         add_pgm_change(midi_event);
491                                 }
492                                 break;
493                         }
494                 }
495
496                 // Is this necessary ??????????
497                 /*for (Automatable::Controls::const_iterator i = _model->controls().begin();
498                                 i != _model->controls().end(); ++i) {
499
500                         assert(i->second);
501
502                         boost::shared_ptr<AutomationTimeAxisView> at
503                                 = midi_view()->automation_child(i->second->parameter());
504                         if (!at)
505                                 continue;
506
507                         Gdk::Color col = midi_stream_view()->get_region_color();
508
509                         boost::shared_ptr<AutomationRegionView> arv;
510
511                         {
512                                 Glib::Mutex::Lock list_lock (i->second->list()->lock());
513
514                                 arv = boost::shared_ptr<AutomationRegionView>(
515                                                 new AutomationRegionView(at->canvas_display,
516                                                         *at.get(), _region, i->second->list(),
517                                                         midi_stream_view()->get_samples_per_unit(), col));
518                         }
519
520                         arv->set_duration(_region->length(), this);
521                         arv->init(col, true);
522
523                         _automation_children.insert(std::make_pair(i->second->parameter(), arv));
524                 }*/
525
526                 _model->read_unlock();
527
528         } else {
529                 cerr << "MidiRegionView::redisplay_model called without a model" << endmsg;
530         }
531 }
532
533
534 MidiRegionView::~MidiRegionView ()
535 {
536         in_destructor = true;
537
538         RegionViewGoingAway (this); /* EMIT_SIGNAL */
539
540         if (_active_notes)
541                 end_write();
542
543         _selection.clear();
544         clear_events();
545         delete _note_group;
546         delete _delta_command;
547 }
548
549
550 void
551 MidiRegionView::region_resized (Change what_changed)
552 {
553         RegionView::region_resized(what_changed);
554         
555         if (what_changed & ARDOUR::PositionChanged) {
556                 if (_enable_display)
557                         redisplay_model();
558         } 
559 }
560
561 void
562 MidiRegionView::reset_width_dependent_items (double pixel_width)
563 {
564         RegionView::reset_width_dependent_items(pixel_width);
565         assert(_pixel_width == pixel_width);
566
567         if (_enable_display)
568                 redisplay_model();
569 }
570
571 void
572 MidiRegionView::set_y_position_and_height (double y, double h)
573 {
574         RegionView::set_y_position_and_height(y, h - 1);
575
576         if (_enable_display) {
577
578                 _model->read_lock();
579
580                 for (std::vector<CanvasNoteEvent*>::const_iterator i = _events.begin(); i != _events.end(); ++i) {
581                         CanvasNoteEvent* event = *i;
582                         Item* item = dynamic_cast<Item*>(event);
583                         assert(item);
584                         if (event && event->note()) {
585                                 if (event->note()->note() < midi_stream_view()->lowest_note() ||
586                                    event->note()->note() > midi_stream_view()->highest_note()) {
587                                         
588                                         if (canvas_item_visible(item)) {
589                                                 item->hide();
590                                         }
591                                 } else {
592                                         if (!canvas_item_visible(item)) {
593                                                 item->show();
594                                         }
595
596                                         event->hide_velocity();
597                                         if(CanvasNote* note = dynamic_cast<CanvasNote*>(event)) {
598                                                 const double y1 = midi_stream_view()->note_to_y(event->note()->note());
599                                                 const double y2 = y1 + floor(midi_stream_view()->note_height());
600
601                                                 note->property_y1() = y1;
602                                                 note->property_y2() = y2;
603                                         }
604                                         if(CanvasHit* hit = dynamic_cast<CanvasHit*>(event)) {
605                                                 double x = trackview.editor.frame_to_pixel((nframes_t)
606                                                                 event->note()->time() - _region->start());
607                                                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
608                                                 double y = midi_stream_view()->note_to_y(event->note()->note()) 
609                                                                  + ((diamond_size-2.0) / 4.0);
610                                                 
611                                                 hit->set_height(diamond_size);
612                                                 hit->move(x-hit->x1(), y-hit->y1());
613                                                 hit->show();
614                                         }
615                                         if(event->selected()) {
616                                                 event->show_velocity();
617                                         }
618                                 }
619                         }
620                 }
621
622                 _model->read_unlock();
623         }
624
625         if (name_text) {
626                 name_text->raise_to_top();
627         }
628 }
629
630 GhostRegion*
631 MidiRegionView::add_ghost (TimeAxisView& tv)
632 {
633         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
634         CanvasNote* note;
635         assert(rtv);
636
637         double unit_position = _region->position () / samples_per_unit;
638         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
639         MidiGhostRegion* ghost;
640
641         if (mtv && mtv->midi_view()) {
642                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group.
643                    this is because it's nice to have midi notes on top of the note lines and
644                    audio waveforms under it.
645                  */
646                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
647         }
648         else {
649                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
650         }
651
652         ghost->set_height ();
653         ghost->set_duration (_region->length() / samples_per_unit);
654         ghosts.push_back (ghost);
655
656         for (std::vector<CanvasNoteEvent*>::iterator i = _events.begin(); i != _events.end(); ++i) {
657                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
658                         ghost->add_note(note);
659                 }
660         }
661
662         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
663
664         return ghost;
665 }
666
667
668 /** Begin tracking note state for successive calls to add_event
669  */
670 void
671 MidiRegionView::begin_write()
672 {
673         assert(!_active_notes);
674         _active_notes = new CanvasNote*[128];
675         for (unsigned i=0; i < 128; ++i)
676                 _active_notes[i] = NULL;
677 }
678
679
680 /** Destroy note state for add_event
681  */
682 void
683 MidiRegionView::end_write()
684 {
685         delete[] _active_notes;
686         _active_notes = NULL;
687         _marked_for_selection.clear();
688 }
689
690
691 /** Resolve an active MIDI note (while recording).
692  */
693 void
694 MidiRegionView::resolve_note(uint8_t note, double end_time)
695 {
696         if (midi_view()->note_mode() != Sustained)
697                 return;
698
699         if (_active_notes && _active_notes[note]) {
700                 _active_notes[note]->property_x2() = trackview.editor.frame_to_pixel((nframes_t)end_time);
701                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
702                 _active_notes[note] = NULL;
703         }
704 }
705
706
707 /** Extend active notes to rightmost edge of region (if length is changed)
708  */
709 void
710 MidiRegionView::extend_active_notes()
711 {
712         if (!_active_notes)
713                 return;
714
715         for (unsigned i=0; i < 128; ++i)
716                 if (_active_notes[i])
717                         _active_notes[i]->property_x2() = trackview.editor.frame_to_pixel(_region->length());
718 }
719
720
721 /** Add a MIDI note to the view (with duration).
722  *
723  * If in sustained mode, notes with duration 0 will be considered active
724  * notes, and resolve_note should be called when the corresponding note off
725  * event arrives, to properly display the note.
726  */
727 void
728 MidiRegionView::add_note(const boost::shared_ptr<Note> note)
729 {
730         assert(note->time() >= 0);
731         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
732         
733         // dont display notes beyond the region bounds
734         if(
735                         note->time() - _region->start() >= _region->length() ||
736                         note->time() <  _region->start() ||
737                         note->note() < midi_stream_view()->lowest_note() ||
738                         note->note() > midi_stream_view()->highest_note()
739           ) {
740                 return;
741         }
742         
743         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
744
745         CanvasNoteEvent *event = 0;
746         
747         const double x = trackview.editor.frame_to_pixel((nframes_t)note->time() - _region->start());
748         
749         if (midi_view()->note_mode() == Sustained) {
750
751                 //cerr << "MRV::add_note sustained " << note->note() << " @ " << note->time()
752                 //      << " .. " << note->end_time() << endl;
753                 
754                 const double y1 = midi_stream_view()->note_to_y(note->note());
755                 const double note_endpixel = 
756                         trackview.editor.frame_to_pixel((nframes_t)note->end_time() - _region->start());
757                 
758                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
759                 ev_rect->property_x1() = x;
760                 ev_rect->property_y1() = y1;
761                 if (note->duration() > 0)
762                         ev_rect->property_x2() = note_endpixel;
763                 else
764                         ev_rect->property_x2() = trackview.editor.frame_to_pixel(_region->length());
765                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
766
767                 if (note->duration() == 0) {
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_force_channel_changed(int8_t channel)
1309 {
1310         force_channel = channel;
1311 }
1312
1313 void 
1314 MidiRegionView::midi_channel_selection_changed(uint16_t selection)
1315 {
1316         if(force_channel >= 0) {
1317                 selection = 0xFFFF;
1318         }
1319                 
1320         for(std::vector<ArdourCanvas::CanvasNoteEvent*>::iterator i = _events.begin();
1321                 i != _events.end();
1322                 ++i) {
1323                 (*i)->on_channel_selection_change(selection);
1324         }
1325         last_channel_selection = selection;
1326 }