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