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