first pass (ok, third really) at internal send+return - audio routing inside ardour...
[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 #include <ostream>
24
25 #include <gtkmm.h>
26
27 #include <gtkmm2ext/gtk_ui.h>
28
29 #include <sigc++/signal.h>
30
31 #include "ardour/playlist.h"
32 #include "ardour/tempo.h"
33 #include "ardour/midi_region.h"
34 #include "ardour/midi_source.h"
35 #include "ardour/midi_diskstream.h"
36 #include "ardour/midi_model.h"
37 #include "ardour/midi_patch_manager.h"
38
39 #include "evoral/Parameter.hpp"
40 #include "evoral/Control.hpp"
41
42 #include "streamview.h"
43 #include "midi_region_view.h"
44 #include "midi_streamview.h"
45 #include "midi_time_axis.h"
46 #include "simpleline.h"
47 #include "canvas-hit.h"
48 #include "canvas-note.h"
49 #include "canvas-program-change.h"
50 #include "public_editor.h"
51 #include "ghostregion.h"
52 #include "midi_time_axis.h"
53 #include "automation_time_axis.h"
54 #include "automation_region_view.h"
55 #include "utils.h"
56 #include "midi_util.h"
57 #include "gui_thread.h"
58 #include "keyboard.h"
59
60 #include "i18n.h"
61
62 using namespace sigc;
63 using namespace ARDOUR;
64 using namespace PBD;
65 using namespace Editing;
66 using namespace ArdourCanvas;
67
68 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
69                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color const & basic_color)
70         : RegionView (parent, tv, r, spu, basic_color)
71         , _force_channel(-1)
72         , _last_channel_selection(0xFFFF)
73         , _default_note_length(1.0)
74         , _current_range_min(0)
75         , _current_range_max(0)
76         , _model_name(string())
77         , _custom_device_mode(string())
78         , _active_notes(0)
79         , _note_group(new ArdourCanvas::Group(*parent))
80         , _delta_command(NULL)
81         , _mouse_state(None)
82         , _pressed_button(0)
83 {
84         _note_group->raise_to_top();
85 }
86
87 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv,
88                 boost::shared_ptr<MidiRegion> r, double spu, Gdk::Color& basic_color,
89                 TimeAxisViewItem::Visibility visibility)
90         : RegionView (parent, tv, r, spu, basic_color, false, visibility)
91         , _force_channel(-1)
92         , _last_channel_selection(0xFFFF)
93         , _default_note_length(1.0)
94         , _model_name(string())
95         , _custom_device_mode(string())
96         , _active_notes(0)
97         , _note_group(new ArdourCanvas::Group(*parent))
98         , _delta_command(NULL)
99         , _mouse_state(None)
100         , _pressed_button(0)
101         
102 {
103         _note_group->raise_to_top();
104 }
105
106
107 MidiRegionView::MidiRegionView (const MidiRegionView& other)
108         : sigc::trackable(other)
109         , RegionView (other)
110         , _force_channel(-1)
111         , _last_channel_selection(0xFFFF)
112         , _default_note_length(1.0)
113         , _model_name(string())
114         , _custom_device_mode(string())
115         , _active_notes(0)
116         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
117         , _delta_command(NULL)
118         , _mouse_state(None)
119         , _pressed_button(0)
120 {
121         Gdk::Color c;
122         int r,g,b,a;
123
124         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
125         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
126         
127         init (c, false);
128 }
129
130 MidiRegionView::MidiRegionView (const MidiRegionView& other, boost::shared_ptr<MidiRegion> region)
131         : RegionView (other, boost::shared_ptr<Region> (region))
132         , _force_channel(-1)
133         , _last_channel_selection(0xFFFF)
134         , _default_note_length(1.0)
135         , _model_name(string())
136         , _custom_device_mode(string())
137         , _active_notes(0)
138         , _note_group(new ArdourCanvas::Group(*get_canvas_group()))
139         , _delta_command(NULL)
140         , _mouse_state(None)
141         , _pressed_button(0)
142 {
143         Gdk::Color c;
144         int r,g,b,a;
145
146         UINT_TO_RGBA (other.fill_color, &r, &g, &b, &a);
147         c.set_rgb_p (r/255.0, g/255.0, b/255.0);
148
149         init (c, true);
150 }
151
152 void
153 MidiRegionView::init (Gdk::Color const & basic_color, bool wfd)
154 {
155         if (wfd) {
156                 midi_region()->midi_source(0)->load_model();
157         }
158
159         _model = midi_region()->midi_source(0)->model();
160         _enable_display = false;
161
162         RegionView::init (basic_color, false);
163
164         compute_colors (basic_color);
165
166         set_height (trackview.current_height());
167
168         region_muted ();
169         region_sync_changed ();
170         region_resized (BoundsChanged);
171         region_locked ();
172         
173         reset_width_dependent_items (_pixel_width);
174
175         set_colors ();
176
177         _enable_display = true;
178         if (_model) {
179                 if (wfd) {
180                         redisplay_model();
181                 }
182                 _model->ContentsChanged.connect(sigc::mem_fun(this, &MidiRegionView::redisplay_model));
183         }
184
185         group->raise_to_top();
186         group->signal_event().connect (mem_fun (this, &MidiRegionView::canvas_event), false);
187
188         midi_view()->signal_channel_mode_changed().connect(
189                         mem_fun(this, &MidiRegionView::midi_channel_mode_changed));
190         
191         midi_view()->signal_midi_patch_settings_changed().connect(
192                         mem_fun(this, &MidiRegionView::midi_patch_settings_changed));
193 }
194
195 bool
196 MidiRegionView::canvas_event(GdkEvent* ev)
197 {
198         static double drag_start_x, drag_start_y;
199         static double last_x, last_y;
200         double event_x, event_y;
201         nframes64_t event_frame = 0;
202
203         static ArdourCanvas::SimpleRect* drag_rect = NULL;
204
205         if (trackview.editor().current_mouse_mode() != MouseNote)
206                 return false;
207         
208         const Editing::MidiEditMode midi_edit_mode = trackview.editor().current_midi_edit_mode();
209
210         switch (ev->type) {
211         case GDK_KEY_PRESS:
212                 if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
213                         _mouse_state = SelectTouchDragging;
214                         return true;
215                 } else if (ev->key.keyval == GDK_Escape) {
216                         clear_selection();
217                         _mouse_state = None;
218                 }
219                 return false;
220
221         case GDK_KEY_RELEASE:
222                 if (ev->key.keyval == GDK_Delete) {
223                         delete_selection();
224                         apply_command();
225                         return true;
226                 } else if (ev->key.keyval == GDK_Shift_L || ev->key.keyval == GDK_Control_L) {
227                         _mouse_state = None;
228                         return true;
229                 }
230                 return false;
231
232         case GDK_BUTTON_PRESS:
233                 if (_mouse_state != SelectTouchDragging && ev->button.button == 1) {
234                         _pressed_button = ev->button.button;
235                         _mouse_state = Pressed;
236                         return true;
237                 }
238                 _pressed_button = ev->button.button;
239                 return true;
240
241         case GDK_2BUTTON_PRESS:
242                 return true;
243
244         case GDK_ENTER_NOTIFY:
245                 /* FIXME: do this on switch to note tool, too, if the pointer is already in */
246                 Keyboard::magic_widget_grab_focus();
247                 group->grab_focus();
248                 break;
249
250         case GDK_MOTION_NOTIFY:
251                 event_x = ev->motion.x;
252                 event_y = ev->motion.y;
253                 group->w2i(event_x, event_y);
254
255                 // convert event_x to global frame
256                 event_frame = trackview.editor().pixel_to_frame(event_x) + _region->position();
257                 trackview.editor().snap_to(event_frame);
258                 // convert event_frame back to local coordinates relative to position
259                 event_frame -= _region->position();
260
261                 switch (_mouse_state) {
262                 case Pressed: // Drag start
263
264                         // Select drag start
265                         if (_pressed_button == 1 && midi_edit_mode == MidiEditSelect) {
266                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
267                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
268                                 last_x = event_x;
269                                 last_y = event_y;
270                                 drag_start_x = event_x;
271                                 drag_start_y = event_y;
272
273                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
274                                 drag_rect->property_x1() = event_x;
275                                 drag_rect->property_y1() = event_y;
276                                 drag_rect->property_x2() = event_x;
277                                 drag_rect->property_y2() = event_y;
278                                 drag_rect->property_outline_what() = 0xFF;
279                                 drag_rect->property_outline_color_rgba()
280                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
281                                 drag_rect->property_fill_color_rgba()
282                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
283
284                                 _mouse_state = SelectRectDragging;
285                                 return true;
286
287                         // Add note drag start
288                         } else if (midi_edit_mode == MidiEditPencil) {
289                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
290                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
291                                 last_x = event_x;
292                                 last_y = event_y;
293                                 drag_start_x = event_x;
294                                 drag_start_y = event_y;
295
296                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
297                                 drag_rect->property_x1() = trackview.editor().frame_to_pixel(event_frame);
298
299                                 drag_rect->property_y1() = midi_stream_view()->note_to_y(
300                                                 midi_stream_view()->y_to_note(event_y));
301                                 drag_rect->property_x2() = event_x;
302                                 drag_rect->property_y2() = drag_rect->property_y1()
303                                                          + floor(midi_stream_view()->note_height());
304                                 drag_rect->property_outline_what() = 0xFF;
305                                 drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
306                                 drag_rect->property_fill_color_rgba()    = 0xFFFFFF66;
307
308                                 _mouse_state = AddDragging;
309                                 return true;
310                         }
311
312                         return false;
313
314                 case SelectRectDragging: // Select drag motion
315                 case AddDragging: // Add note drag motion
316                         if (ev->motion.is_hint) {
317                                 int t_x;
318                                 int t_y;
319                                 GdkModifierType state;
320                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
321                                 event_x = t_x;
322                                 event_y = t_y;
323                         }
324
325                         if (_mouse_state == AddDragging)
326                                 event_x = trackview.editor().frame_to_pixel(event_frame);
327
328                         if (drag_rect) {
329                                 if (event_x > drag_start_x)
330                                         drag_rect->property_x2() = event_x;
331                                 else
332                                         drag_rect->property_x1() = event_x;
333                         }
334
335                         if (drag_rect && _mouse_state == SelectRectDragging) {
336                                 if (event_y > drag_start_y)
337                                         drag_rect->property_y2() = event_y;
338                                 else
339                                         drag_rect->property_y1() = event_y;
340
341                                 update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
342                         }
343
344                         last_x = event_x;
345                         last_y = event_y;
346
347                 case SelectTouchDragging:
348                         return false;
349
350                 default:
351                         break;
352                 }
353                 break;
354
355         case GDK_BUTTON_RELEASE:
356                 event_x = ev->motion.x;
357                 event_y = ev->motion.y;
358                 group->w2i(event_x, event_y);
359                 group->ungrab(ev->button.time);
360                 event_frame = trackview.editor().pixel_to_frame(event_x);
361
362                 if (_pressed_button != 1) {
363                         return false;
364                 }
365                         
366                 switch (_mouse_state) {
367                 case Pressed: // Clicked
368                         switch (midi_edit_mode) {
369                         case MidiEditSelect:
370                         case MidiEditResize:
371                                 clear_selection();
372                                 break;
373                         case MidiEditPencil:
374                                 create_note_at(event_x, event_y, _default_note_length);
375                         default: break;
376                         }
377                         _mouse_state = None;
378                         break;
379                 case SelectRectDragging: // Select drag done
380                         _mouse_state = None;
381                         delete drag_rect;
382                         drag_rect = NULL;
383                         break;
384                 case AddDragging: // Add drag done
385                         _mouse_state = None;
386                         if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
387                                 const double x      = drag_rect->property_x1();
388                                 const double length = trackview.editor().pixel_to_frame(
389                                                         drag_rect->property_x2() - drag_rect->property_x1());
390                                         
391                                 create_note_at(x, drag_rect->property_y1(), frames_to_beats(length));
392                         }
393
394                         delete drag_rect;
395                         drag_rect = NULL;
396                 default: break;
397                 }
398
399         default: break;
400         }
401
402         return false;
403 }
404
405
406 /** Add a note to the model, and the view, at a canvas (click) coordinate.
407  * \param x horizontal position in pixels
408  * \param y vertical position in pixels
409  * \param length duration of the note in beats */
410 void
411 MidiRegionView::create_note_at(double x, double y, double length)
412 {
413         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
414         MidiStreamView* const view = mtv->midi_view();
415
416         double note = midi_stream_view()->y_to_note(y);
417
418         assert(note >= 0.0);
419         assert(note <= 127.0);
420
421         // Start of note in frames relative to region start
422         nframes64_t start_frames = snap_frame_to_frame(trackview.editor().pixel_to_frame(x));
423         assert(start_frames >= 0);
424
425         // Snap length
426         length = frames_to_beats(
427                         snap_frame_to_frame(start_frames + beats_to_frames(length)) - start_frames);
428
429         const boost::shared_ptr<NoteType> new_note(new NoteType(0,
430                         frames_to_beats(start_frames + _region->start()), length,
431                         (uint8_t)note, 0x40));
432
433         view->update_note_range(new_note->note());
434
435         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
436         cmd->add(new_note);
437         _model->apply_command(trackview.session(), cmd);
438 }
439
440
441 void
442 MidiRegionView::clear_events()
443 {
444         clear_selection();
445
446         MidiGhostRegion* gr;
447         for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
448                 if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
449                         gr->clear_events();
450                 }
451         }
452
453         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
454                 delete *i;
455         }
456
457         _events.clear();
458         _pgm_changes.clear();
459         _sys_exes.clear();
460 }
461
462
463 void
464 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
465 {
466         _model = model;
467         if (_enable_display) {
468                 redisplay_model();
469         }
470 }
471         
472         
473 void
474 MidiRegionView::start_delta_command(string name)
475 {
476         if (!_delta_command) {
477                 _delta_command = _model->new_delta_command(name);
478         }
479 }
480
481 void
482 MidiRegionView::command_add_note(const boost::shared_ptr<NoteType> note, bool selected, bool show_velocity)
483 {
484         if (_delta_command) {
485                 _delta_command->add(note);
486         }
487         if (selected) {
488                 _marked_for_selection.insert(note);
489         }
490         if (show_velocity) {
491                 _marked_for_velocity.insert(note);
492         }
493 }
494
495 void
496 MidiRegionView::command_remove_note(ArdourCanvas::CanvasNoteEvent* ev)
497 {
498         if (_delta_command && ev->note()) {
499                 _delta_command->remove(ev->note());
500         }
501 }
502         
503 void
504 MidiRegionView::apply_command()
505 {
506         if (!_delta_command) {
507                 return;
508         }
509
510         // Mark all selected notes for selection when model reloads
511         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
512                 _marked_for_selection.insert((*i)->note());
513         }
514         
515         _model->apply_command(trackview.session(), _delta_command);
516         _delta_command = NULL; 
517         midi_view()->midi_track()->diskstream()->playlist_modified();
518
519         _marked_for_selection.clear();
520         _marked_for_velocity.clear();
521 }
522         
523
524 void
525 MidiRegionView::abort_command()
526 {
527         delete _delta_command;
528         _delta_command = NULL;
529         clear_selection();
530 }
531
532
533 void
534 MidiRegionView::redisplay_model()
535 {
536         // Don't redisplay the model if we're currently recording and displaying that
537         if (_active_notes) {
538                 return;
539         }
540
541         if (_model) {
542                 clear_events();
543                 _model->read_lock();
544                 
545                 MidiModel::Notes notes = _model->notes();
546                 
547                 for (size_t i = 0; i < _model->n_notes(); ++i) {
548                         add_note(_model->note_at(i));
549                 }
550                 
551                 display_sysexes();
552
553                 display_program_changes();
554
555                 _model->read_unlock();
556
557         } else {
558                 cerr << "MidiRegionView::redisplay_model called without a model" << endmsg;
559         }
560 }
561
562 void
563 MidiRegionView::display_program_changes()
564 {
565         boost::shared_ptr<Evoral::Control> control = _model->control(MidiPgmChangeAutomation);
566         if (!control) {
567                 return;
568         }
569
570         Glib::Mutex::Lock lock (control->list()->lock());
571
572         uint8_t channel = control->parameter().channel();
573
574         for (AutomationList::const_iterator event = control->list()->begin();
575                         event != control->list()->end(); ++event) {
576                 double event_time     = (*event)->when;
577                 double program_number = floor((*event)->value + 0.5);
578
579                 // Get current value of bank select MSB at time of the program change
580                 Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
581                 boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
582                 uint8_t msb = 0;
583                 if (msb_control != 0) {
584                         msb = uint8_t(floor(msb_control->get_float(true, event_time) + 0.5));
585                 }
586
587                 // Get current value of bank select LSB at time of the program change
588                 Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
589                 boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
590                 uint8_t lsb = 0;
591                 if (lsb_control != 0) {
592                         lsb = uint8_t(floor(lsb_control->get_float(true, event_time) + 0.5));
593                 }
594
595                 MIDI::Name::PatchPrimaryKey patch_key(msb, lsb, program_number);
596
597                 boost::shared_ptr<MIDI::Name::Patch> patch = 
598                         MIDI::Name::MidiPatchManager::instance().find_patch(
599                                         _model_name, _custom_device_mode, channel, patch_key);
600
601                 PCEvent program_change(event_time, uint8_t(program_number), channel);
602
603                 if (patch != 0) {
604                         add_pgm_change(program_change, patch->name());
605                 } else {
606                         char buf[4];
607                         snprintf(buf, 4, "%d", int(program_number));
608                         add_pgm_change(program_change, buf);
609                 }
610         }
611 }
612
613 void 
614 MidiRegionView::display_sysexes()
615 {
616         for (MidiModel::SysExes::const_iterator i = _model->sysexes().begin(); i != _model->sysexes().end(); ++i) {
617                 ARDOUR::MidiModel::TimeType time = (*i)->time();
618                 assert(time >= 0);
619                 
620                 ostringstream str;
621                 str << hex;
622                 for (uint32_t b = 0; b < (*i)->size(); ++b) {
623                         str << int((*i)->buffer()[b]);
624                         if (b != (*i)->size() -1) {
625                                 str << " ";
626                         }
627                 }
628                 string text = str.str();
629                 
630                 ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
631                 const double x = trackview.editor().frame_to_pixel(beats_to_frames(time));
632                 
633                 double height = midi_stream_view()->contents_height();
634                 
635                 boost::shared_ptr<CanvasSysEx> sysex = boost::shared_ptr<CanvasSysEx>(
636                                 new CanvasSysEx(*this, *group, text, height, x, 1.0));
637                 
638                 // Show unless program change is beyond the region bounds
639                 if (time - _region->start() >= _region->length() || time < _region->start()) {
640                         sysex->hide();
641                 } else {
642                         sysex->show();
643                 }
644                 
645                 _sys_exes.push_back(sysex);
646         }
647 }
648
649
650 MidiRegionView::~MidiRegionView ()
651 {
652         in_destructor = true;
653
654         RegionViewGoingAway (this); /* EMIT_SIGNAL */
655
656         if (_active_notes) {
657                 end_write();
658         }
659
660         _selection.clear();
661         clear_events();
662         delete _note_group;
663         delete _delta_command;
664 }
665
666
667 void
668 MidiRegionView::region_resized (Change what_changed)
669 {
670         RegionView::region_resized(what_changed);
671         
672         if (what_changed & ARDOUR::PositionChanged) {
673                 set_duration(_region->length(), 0);
674                 if (_enable_display) {
675                         redisplay_model();
676                 }
677         } 
678 }
679
680 void
681 MidiRegionView::reset_width_dependent_items (double pixel_width)
682 {
683         RegionView::reset_width_dependent_items(pixel_width);
684         assert(_pixel_width == pixel_width);
685
686         if (_enable_display) {
687                 redisplay_model();
688         }
689 }
690
691 void
692 MidiRegionView::set_height (double height)
693 {
694         static const double FUDGE = 2.0;
695         const double old_height = _height;
696         RegionView::set_height(height);
697         _height = height - FUDGE;
698         
699         apply_note_range(midi_stream_view()->lowest_note(),
700                          midi_stream_view()->highest_note(),
701                          height != old_height + FUDGE);
702         
703         if (name_pixbuf) {
704                 name_pixbuf->raise_to_top();
705         }
706 }
707
708
709 /** Apply the current note range from the stream view
710  * by repositioning/hiding notes as necessary
711  */
712 void
713 MidiRegionView::apply_note_range (uint8_t min, uint8_t max, bool force)
714 {
715         if (!_enable_display) {
716                 return;
717         }
718
719         if (!force && _current_range_min == min && _current_range_max == max) {
720                 return;
721         }
722         
723         _current_range_min = min;
724         _current_range_max = max;
725
726         for (Events::const_iterator i = _events.begin(); i != _events.end(); ++i) {
727                 CanvasNoteEvent* event = *i;
728                 Item* item = dynamic_cast<Item*>(event);
729                 assert(item);
730                 if (event && event->note()) {
731                         if (event->note()->note() < _current_range_min
732                                         || event->note()->note() > _current_range_max) {
733                                 if (canvas_item_visible(item)) {
734                                         item->hide();
735                                 }
736                         } else {
737                                 if (!canvas_item_visible(item)) {
738                                         item->show();
739                                 }
740
741                                 if (CanvasNote* note = dynamic_cast<CanvasNote*>(event)) {
742                                         const double y1 = midi_stream_view()->note_to_y(event->note()->note());
743                                         const double y2 = y1 + floor(midi_stream_view()->note_height());
744
745                                         note->property_y1() = y1;
746                                         note->property_y2() = y2;
747                                 } else if (CanvasHit* hit = dynamic_cast<CanvasHit*>(event)) {
748                                         double x = trackview.editor().frame_to_pixel(
749                                                         beats_to_frames(event->note()->time()) - _region->start());
750                                         const double diamond_size = midi_stream_view()->note_height() / 2.0;
751                                         double y = midi_stream_view()->note_to_y(event->note()->note()) 
752                                                          + ((diamond_size-2.0) / 4.0);
753                                         
754                                         hit->set_height(diamond_size);
755                                         hit->move(x-hit->x1(), y-hit->y1());
756                                         hit->show();
757                                 }
758                         }
759                 }
760         }
761         
762 }
763
764 GhostRegion*
765 MidiRegionView::add_ghost (TimeAxisView& tv)
766 {
767         CanvasNote* note;
768
769         double unit_position = _region->position () / samples_per_unit;
770         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(&tv);
771         MidiGhostRegion* ghost;
772
773         if (mtv && mtv->midi_view()) {
774                 /* if ghost is inserted into midi track, use a dedicated midi ghost canvas group
775                    to allow having midi notes on top of note lines and waveforms.
776                  */
777                 ghost = new MidiGhostRegion (*mtv->midi_view(), trackview, unit_position);
778         } else {
779                 ghost = new MidiGhostRegion (tv, trackview, unit_position);
780         }
781
782         ghost->set_height ();
783         ghost->set_duration (_region->length() / samples_per_unit);
784         ghosts.push_back (ghost);
785
786         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
787                 if ((note = dynamic_cast<CanvasNote*>(*i)) != 0) {
788                         ghost->add_note(note);
789                 }
790         }
791
792         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
793
794         return ghost;
795 }
796
797
798 /** Begin tracking note state for successive calls to add_event
799  */
800 void
801 MidiRegionView::begin_write()
802 {
803         assert(!_active_notes);
804         _active_notes = new CanvasNote*[128];
805         for (unsigned i=0; i < 128; ++i) {
806                 _active_notes[i] = NULL;
807         }
808 }
809
810
811 /** Destroy note state for add_event
812  */
813 void
814 MidiRegionView::end_write()
815 {
816         delete[] _active_notes;
817         _active_notes = NULL;
818         _marked_for_selection.clear();
819         _marked_for_velocity.clear();
820 }
821
822
823 /** Resolve an active MIDI note (while recording).
824  */
825 void
826 MidiRegionView::resolve_note(uint8_t note, double end_time)
827 {
828         if (midi_view()->note_mode() != Sustained) {
829                 return;
830         }
831
832         if (_active_notes && _active_notes[note]) {
833                 const nframes64_t end_time_frames = beats_to_frames(end_time);
834                 _active_notes[note]->property_x2() = trackview.editor().frame_to_pixel(end_time_frames);
835                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
836                 _active_notes[note] = NULL;
837         }
838 }
839
840
841 /** Extend active notes to rightmost edge of region (if length is changed)
842  */
843 void
844 MidiRegionView::extend_active_notes()
845 {
846         if (!_active_notes) {
847                 return;
848         }
849
850         for (unsigned i=0; i < 128; ++i) {
851                 if (_active_notes[i]) {
852                         _active_notes[i]->property_x2() = trackview.editor().frame_to_pixel(_region->length());
853                 }
854         }
855 }
856
857 void 
858 MidiRegionView::play_midi_note(boost::shared_ptr<NoteType> note)
859 {
860         if (!trackview.editor().sound_notes()) {
861                 return;
862         }
863
864         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
865         assert(route_ui);
866         
867         route_ui->midi_track()->write_immediate_event(
868                         note->on_event().size(), note->on_event().buffer());
869         
870         const double note_length_beats = (note->off_event().time() - note->on_event().time());
871         nframes_t note_length_ms = beats_to_frames(note_length_beats)
872                         * (1000 / (double)route_ui->session().nominal_frame_rate());
873         Glib::signal_timeout().connect(bind(mem_fun(this, &MidiRegionView::play_midi_note_off), note),
874                         note_length_ms, G_PRIORITY_DEFAULT);
875 }
876
877 bool
878 MidiRegionView::play_midi_note_off(boost::shared_ptr<NoteType> note)
879 {
880         RouteUI* route_ui = dynamic_cast<RouteUI*> (&trackview);
881         assert(route_ui);
882         
883         route_ui->midi_track()->write_immediate_event(
884                         note->off_event().size(), note->off_event().buffer());
885
886         return false;
887 }
888
889 bool
890 MidiRegionView::note_in_visible_range(const boost::shared_ptr<NoteType> note) const
891 {
892         const nframes64_t note_start_frames = beats_to_frames(note->time());
893         bool outside = (note_start_frames - _region->start() >= _region->length())
894                         || (note_start_frames < _region->start())
895                         || (note->note() < midi_stream_view()->lowest_note())
896                         || (note->note() > midi_stream_view()->highest_note());
897         return !outside;
898 }
899
900 /** Add a MIDI note to the view (with length).
901  *
902  * If in sustained mode, notes with length 0 will be considered active
903  * notes, and resolve_note should be called when the corresponding note off
904  * event arrives, to properly display the note.
905  */
906 void
907 MidiRegionView::add_note(const boost::shared_ptr<NoteType> note)
908 {
909         assert(note->time() >= 0);
910         assert(midi_view()->note_mode() == Sustained || midi_view()->note_mode() == Percussive);
911         
912         const nframes64_t note_start_frames = beats_to_frames(note->time());
913         const nframes64_t note_end_frames   = beats_to_frames(note->end_time());
914
915         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
916
917         CanvasNoteEvent* event = 0;
918         
919         const double x = trackview.editor().frame_to_pixel(note_start_frames - _region->start());
920         
921         if (midi_view()->note_mode() == Sustained) {
922                 const double y1 = midi_stream_view()->note_to_y(note->note());
923                 const double note_endpixel = 
924                         trackview.editor().frame_to_pixel(note_end_frames - _region->start());
925                 
926                 CanvasNote* ev_rect = new CanvasNote(*this, *group, note);
927                 ev_rect->property_x1() = x;
928                 ev_rect->property_y1() = y1;
929                 if (note->length() > 0) {
930                         ev_rect->property_x2() = note_endpixel;
931                 } else {
932                         ev_rect->property_x2() = trackview.editor().frame_to_pixel(_region->length());
933                 }
934                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
935
936                 if (note->length() == 0) {
937                         if (_active_notes) {
938                                 assert(note->note() < 128);
939                                 // If this note is already active there's a stuck note,
940                                 // finish the old note rectangle
941                                 if (_active_notes[note->note()]) {
942                                         CanvasNote* const old_rect = _active_notes[note->note()];
943                                         boost::shared_ptr<NoteType> old_note = old_rect->note();
944                                         old_rect->property_x2() = x;
945                                         old_rect->property_outline_what() = (guint32) 0xF;
946                                 }
947                                 _active_notes[note->note()] = ev_rect;
948                         }
949                         /* outline all but right edge */
950                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
951                 } else {
952                         /* outline all edges */
953                         ev_rect->property_outline_what() = (guint32) 0xF;
954                 }
955
956                 event = ev_rect;
957
958                 MidiGhostRegion* gr;
959                 for (std::vector<GhostRegion*>::iterator g = ghosts.begin(); g != ghosts.end(); ++g) {
960                         if ((gr = dynamic_cast<MidiGhostRegion*>(*g)) != 0) {
961                                 gr->add_note(ev_rect);
962                         }
963                 }
964
965         } else if (midi_view()->note_mode() == Percussive) {
966                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
967                 const double y = midi_stream_view()->note_to_y(note->note()) + ((diamond_size-2) / 4.0);
968
969                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size, note);
970                 ev_diamond->move(x, y);
971                 event = ev_diamond;
972         } else {
973                 event = 0;
974         }
975
976         if (event) {
977                 if (_marked_for_selection.find(note) != _marked_for_selection.end()) {
978                         note_selected(event, true);
979                 }
980                 if (_marked_for_velocity.find(note) != _marked_for_velocity.end()) {
981                         event->show_velocity();
982                 }
983                 event->on_channel_selection_change(_last_channel_selection);
984                 _events.push_back(event);
985                 if (note_in_visible_range(note)) {
986                         event->show();
987                 } else {
988                         event->hide();
989                 }
990         }
991 }
992
993 void
994 MidiRegionView::add_pgm_change(PCEvent& program, const string& displaytext)
995 {
996         assert(program.time >= 0);
997         
998         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
999         const double x = trackview.editor().frame_to_pixel(beats_to_frames(program.time));
1000         
1001         double height = midi_stream_view()->contents_height();
1002         
1003         boost::shared_ptr<CanvasProgramChange> pgm_change = boost::shared_ptr<CanvasProgramChange>(
1004                         new CanvasProgramChange(*this, *group,
1005                                         displaytext, 
1006                                         height, 
1007                                         x, 1.0, 
1008                                         _model_name, 
1009                                         _custom_device_mode, 
1010                                         program.time, program.channel, program.value));
1011         
1012         // Show unless program change is beyond the region bounds
1013         if (program.time - _region->start() >= _region->length() || program.time < _region->start()) {
1014                 pgm_change->hide();
1015         } else {
1016                 pgm_change->show();
1017         }
1018         
1019         _pgm_changes.push_back(pgm_change);
1020 }
1021
1022 void
1023 MidiRegionView::get_patch_key_at(double time, uint8_t channel, MIDI::Name::PatchPrimaryKey& key)
1024 {
1025         cerr << "getting patch key at " << time << " for channel " << channel << endl;
1026         Evoral::Parameter bank_select_msb(MidiCCAutomation, channel, MIDI_CTL_MSB_BANK);
1027         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1028         float msb = -1.0;
1029         if (msb_control != 0) {
1030                 msb = int(msb_control->get_float(true, time));
1031                 cerr << "got msb " << msb;
1032         }
1033
1034         Evoral::Parameter bank_select_lsb(MidiCCAutomation, channel, MIDI_CTL_LSB_BANK);
1035         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1036         float lsb = -1.0;
1037         if (lsb_control != 0) {
1038                 lsb = lsb_control->get_float(true, time);
1039                 cerr << " got lsb " << lsb;
1040         }
1041         
1042         Evoral::Parameter program_change(MidiPgmChangeAutomation, channel, 0);
1043         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1044         float program_number = -1.0;
1045         if (program_control != 0) {
1046                 program_number = program_control->get_float(true, time);
1047                 cerr << " got program " << program_number << endl;
1048         }
1049         
1050         key.msb = (int) floor(msb + 0.5);
1051         key.lsb = (int) floor(lsb + 0.5);
1052         key.program_number = (int) floor(program_number + 0.5);
1053         assert(key.is_sane());
1054 }
1055
1056
1057 void 
1058 MidiRegionView::alter_program_change(PCEvent& old_program, const MIDI::Name::PatchPrimaryKey& new_patch)
1059 {
1060         // TODO: Get the real event here and alter them at the original times
1061         Evoral::Parameter bank_select_msb(MidiCCAutomation, old_program.channel, MIDI_CTL_MSB_BANK);
1062         boost::shared_ptr<Evoral::Control> msb_control = _model->control(bank_select_msb);
1063         if (msb_control != 0) {
1064                 msb_control->set_float(float(new_patch.msb), true, old_program.time);
1065         }
1066
1067         // TODO: Get the real event here and alter them at the original times
1068         Evoral::Parameter bank_select_lsb(MidiCCAutomation, old_program.channel, MIDI_CTL_LSB_BANK);
1069         boost::shared_ptr<Evoral::Control> lsb_control = _model->control(bank_select_lsb);
1070         if (lsb_control != 0) {
1071                 lsb_control->set_float(float(new_patch.lsb), true, old_program.time);
1072         }
1073         
1074         Evoral::Parameter program_change(MidiPgmChangeAutomation, old_program.channel, 0);
1075         boost::shared_ptr<Evoral::Control> program_control = _model->control(program_change);
1076         
1077         assert(program_control != 0);
1078         program_control->set_float(float(new_patch.program_number), true, old_program.time);
1079         
1080         redisplay_model();
1081 }
1082
1083 void
1084 MidiRegionView::program_selected(CanvasProgramChange& program, const MIDI::Name::PatchPrimaryKey& new_patch)
1085 {
1086         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1087         alter_program_change(program_change_event, new_patch);
1088 }
1089
1090 void 
1091 MidiRegionView::previous_program(CanvasProgramChange& program)
1092 {
1093         MIDI::Name::PatchPrimaryKey key;
1094         get_patch_key_at(program.event_time(), program.channel(), key);
1095         
1096         boost::shared_ptr<MIDI::Name::Patch> patch = 
1097                 MIDI::Name::MidiPatchManager::instance().previous_patch(
1098                                 _model_name,
1099                                 _custom_device_mode, 
1100                                 program.channel(), 
1101                                 key);
1102         
1103         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1104         if (patch) {
1105                 alter_program_change(program_change_event, patch->patch_primary_key());
1106         }
1107 }
1108
1109 void 
1110 MidiRegionView::next_program(CanvasProgramChange& program)
1111 {
1112         MIDI::Name::PatchPrimaryKey key;
1113         get_patch_key_at(program.event_time(), program.channel(), key);
1114         
1115         boost::shared_ptr<MIDI::Name::Patch> patch = 
1116                 MIDI::Name::MidiPatchManager::instance().next_patch(
1117                                 _model_name,
1118                                 _custom_device_mode, 
1119                                 program.channel(), 
1120                                 key);   
1121
1122         PCEvent program_change_event(program.event_time(), program.program(), program.channel());
1123         if (patch) {
1124                 alter_program_change(program_change_event, patch->patch_primary_key());
1125         }
1126 }
1127
1128 void
1129 MidiRegionView::delete_selection()
1130 {
1131         if (_selection.empty()) {
1132                 return;
1133         }
1134
1135         if (!_delta_command) {
1136                 _delta_command = _model->new_delta_command("delete selection");
1137         }
1138
1139         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1140                 if ((*i)->selected()) {
1141                         _delta_command->remove((*i)->note());
1142                 }
1143         }
1144
1145         _selection.clear();
1146 }
1147
1148 void
1149 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasNoteEvent* ev)
1150 {
1151         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1152                 if ((*i)->selected() && (*i) != ev) {
1153                         (*i)->selected(false);
1154                         (*i)->hide_velocity();
1155                 }
1156         }
1157
1158         _selection.clear();
1159 }
1160
1161 void
1162 MidiRegionView::unique_select(ArdourCanvas::CanvasNoteEvent* ev)
1163 {
1164         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1165                 if ((*i) != ev) {
1166                         (*i)->selected(false);
1167                         (*i)->hide_velocity();
1168                 }
1169         }
1170
1171         _selection.clear();
1172         _selection.insert(ev);
1173
1174         if ( ! ev->selected()) {
1175                 ev->selected(true);
1176         }
1177 }
1178
1179 void
1180 MidiRegionView::note_selected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1181 {
1182         if ( ! add) {
1183                 clear_selection_except(ev);
1184         }
1185
1186         if (_selection.insert(ev).second) {
1187                 play_midi_note(ev->note());
1188         }
1189
1190         if ( ! ev->selected()) {
1191                 ev->selected(true);
1192         }
1193 }
1194
1195
1196 void
1197 MidiRegionView::note_deselected(ArdourCanvas::CanvasNoteEvent* ev, bool add)
1198 {
1199         if ( ! add) {
1200                 clear_selection_except(ev);
1201         }
1202
1203         _selection.erase(ev);
1204
1205         if (ev->selected()) {
1206                 ev->selected(false);
1207         }
1208 }
1209
1210
1211 void
1212 MidiRegionView::update_drag_selection(double x1, double x2, double y1, double y2)
1213 {
1214         const double last_y = std::min(y1, y2);
1215         const double y      = std::max(y1, y2);
1216
1217         // TODO: Make this faster by storing the last updated selection rect, and only
1218         // adjusting things that are in the area that appears/disappeared.
1219         // We probably need a tree to be able to find events in O(log(n)) time.
1220
1221 #ifndef NDEBUG
1222         double last_x1 = 0.0;
1223 #endif
1224
1225         if (x1 < x2) {
1226                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1227 #ifndef NDEBUG
1228                         // Events should always be sorted by increasing x1() here
1229                         assert((*i)->x1() >= last_x1);
1230                         last_x1 = (*i)->x1();
1231 #endif
1232                         // Inside rectangle
1233                         if ((*i)->x1() >= x1 && (*i)->x1() <= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1234                                 if (!(*i)->selected()) {
1235                                         (*i)->selected(true);
1236                                         _selection.insert(*i);
1237                                         play_midi_note((*i)->note());
1238                                 }
1239                         // Not inside rectangle
1240                         } else if ((*i)->selected()) {
1241                                 (*i)->selected(false);
1242                                 _selection.erase(*i);
1243                         }
1244                 }
1245         } else {
1246                 for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1247 #ifndef NDEBUG
1248                         // Events should always be sorted by increasing x1() here
1249                         assert((*i)->x1() >= last_x1);
1250                         last_x1 = (*i)->x1();
1251 #endif
1252                         // Inside rectangle
1253                         if ((*i)->x2() <= x1 && (*i)->x2() >= x2 && (*i)->y1() >= last_y && (*i)->y1() <= y) {
1254                                 if (!(*i)->selected()) {
1255                                         (*i)->selected(true);
1256                                         _selection.insert(*i);
1257                                         play_midi_note((*i)->note());
1258                                 }
1259                         // Not inside rectangle
1260                         } else if ((*i)->selected()) {
1261                                 (*i)->selected(false);
1262                                 _selection.erase(*i);
1263                         }
1264                 }
1265         }
1266 }
1267
1268
1269 void
1270 MidiRegionView::move_selection(double dx, double dy)
1271 {
1272         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1273                 (*i)->move_event(dx, dy);
1274         }
1275 }
1276
1277
1278 void
1279 MidiRegionView::note_dropped(CanvasNoteEvent* ev, double dt, uint8_t dnote)
1280 {
1281         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
1282         if (_selection.find(ev) == _selection.end()) {
1283                 return;
1284         }
1285
1286         uint8_t lowest_note_in_selection  = midi_stream_view()->lowest_note();
1287         uint8_t highest_note_in_selection = midi_stream_view()->highest_note();
1288         uint8_t highest_note_difference = 0;
1289
1290         // find highest and lowest notes first
1291         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1292                 uint8_t pitch = (*i)->note()->note();
1293                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  pitch);
1294                 highest_note_in_selection = std::max(highest_note_in_selection, pitch);
1295         }
1296         
1297         /*
1298         cerr << "dnote: " << (int) dnote << endl;
1299         cerr << "lowest note (streamview): " << int(midi_stream_view()->lowest_note()) 
1300              << " highest note (streamview): " << int(midi_stream_view()->highest_note()) << endl;
1301         cerr << "lowest note (selection): " << int(lowest_note_in_selection) << " highest note(selection): " 
1302              << int(highest_note_in_selection) << endl;
1303         cerr << "selection size: " << _selection.size() << endl;
1304         cerr << "Highest note in selection: " << (int) highest_note_in_selection << endl;
1305         */
1306         
1307         // Make sure the note pitch does not exceed the MIDI standard range
1308         if (dnote <= 127 && (highest_note_in_selection + dnote > 127)) {
1309                 highest_note_difference = highest_note_in_selection - 127;
1310         }
1311         
1312         start_delta_command(_("move notes"));
1313
1314         for (Selection::iterator i = _selection.begin(); i != _selection.end() ; ) {
1315                 Selection::iterator next = i;
1316                 ++next;
1317
1318                 const boost::shared_ptr<NoteType> copy(new NoteType(*(*i)->note().get()));
1319
1320                 nframes64_t start_frames = beats_to_frames((*i)->note()->time());
1321                 if (dt >= 0) {
1322                         start_frames += snap_frame_to_frame(trackview.editor().pixel_to_frame(dt));
1323                 } else {
1324                         start_frames -= snap_frame_to_frame(trackview.editor().pixel_to_frame(-dt));
1325                 }
1326
1327                 copy->set_time(frames_to_beats(start_frames));
1328
1329                 uint8_t original_pitch = (*i)->note()->note();
1330                 uint8_t new_pitch      = original_pitch + dnote - highest_note_difference;
1331                 
1332                 // keep notes in standard midi range
1333                 clamp_to_0_127(new_pitch);
1334                 
1335                 // keep original pitch if note is dragged outside valid midi range
1336                 if ((original_pitch != 0 && new_pitch == 0)
1337                                 || (original_pitch != 127 && new_pitch == 127)) {
1338                         new_pitch = original_pitch;
1339                 }
1340
1341                 lowest_note_in_selection  = std::min(lowest_note_in_selection,  new_pitch);
1342                 highest_note_in_selection = std::max(highest_note_in_selection, new_pitch);
1343
1344                 copy->set_note(new_pitch);
1345                 
1346                 command_remove_note(*i);
1347                 command_add_note(copy, (*i)->selected());
1348
1349                 i = next;
1350         }
1351
1352         apply_command();
1353         
1354         // care about notes being moved beyond the upper/lower bounds on the canvas
1355         if (lowest_note_in_selection  < midi_stream_view()->lowest_note() ||
1356                         highest_note_in_selection > midi_stream_view()->highest_note()) {
1357                 midi_stream_view()->set_note_range(MidiStreamView::ContentsRange);
1358         }
1359 }
1360
1361 nframes64_t
1362 MidiRegionView::snap_pixel_to_frame(double x)
1363 {
1364         PublicEditor& editor = trackview.editor();
1365         // x is region relative, convert it to global absolute frames
1366         nframes64_t frame = editor.pixel_to_frame(x) + _region->position();
1367         editor.snap_to(frame);
1368         return frame - _region->position(); // convert back to region relative
1369 }
1370
1371 nframes64_t
1372 MidiRegionView::snap_frame_to_frame(nframes64_t x)
1373 {
1374         PublicEditor& editor = trackview.editor();
1375         // x is region relative, convert it to global absolute frames
1376         nframes64_t frame = x + _region->position();
1377         editor.snap_to(frame);
1378         return frame - _region->position(); // convert back to region relative
1379 }
1380
1381 double
1382 MidiRegionView::snap_to_pixel(double x)
1383 {
1384         return (double) trackview.editor().frame_to_pixel(snap_pixel_to_frame(x));
1385 }
1386
1387 double
1388 MidiRegionView::get_position_pixels()
1389 {
1390         nframes64_t region_frame = get_position();
1391         return trackview.editor().frame_to_pixel(region_frame);
1392 }
1393
1394 nframes64_t
1395 MidiRegionView::beats_to_frames(double beats) const
1396 {
1397         return _time_converter.to(beats);
1398 }
1399
1400 double
1401 MidiRegionView::frames_to_beats(nframes64_t frames) const
1402 {
1403         return _time_converter.from(frames);
1404 }
1405
1406 void
1407 MidiRegionView::begin_resizing(CanvasNote::NoteEnd note_end)
1408 {
1409         _resize_data.clear();
1410
1411         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
1412                 CanvasNote *note = dynamic_cast<CanvasNote *> (*i);
1413
1414                 // only insert CanvasNotes into the map
1415                 if (note) {
1416                         NoteResizeData *resize_data = new NoteResizeData();
1417                         resize_data->canvas_note = note;
1418
1419                         // create a new SimpleRect from the note which will be the resize preview
1420                         SimpleRect *resize_rect = new SimpleRect(
1421                                         *group, note->x1(), note->y1(), note->x2(), note->y2());
1422
1423                         // calculate the colors: get the color settings
1424                         uint32_t fill_color = UINT_RGBA_CHANGE_A(
1425                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get(),
1426                                         128);
1427
1428                         // make the resize preview notes more transparent and bright
1429                         fill_color = UINT_INTERPOLATE(fill_color, 0xFFFFFF40, 0.5);
1430
1431                         // calculate color based on note velocity
1432                         resize_rect->property_fill_color_rgba() = UINT_INTERPOLATE(
1433                                         CanvasNoteEvent::meter_style_fill_color(note->note()->velocity()),
1434                                         fill_color,
1435                                         0.85);
1436
1437                         resize_rect->property_outline_color_rgba() = CanvasNoteEvent::calculate_outline(
1438                                         ARDOUR_UI::config()->canvasvar_MidiNoteSelected.get());
1439
1440                         resize_data->resize_rect = resize_rect;
1441
1442                         if (note_end == CanvasNote::NOTE_ON) {
1443                                 resize_data->current_x = note->x1();
1444                         } else { // NOTE_OFF
1445                                 resize_data->current_x = note->x2();
1446                         }
1447
1448                         _resize_data.push_back(resize_data);
1449                 }
1450         }
1451 }
1452
1453 void
1454 MidiRegionView::update_resizing(CanvasNote::NoteEnd note_end, double x, bool relative)
1455 {
1456         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1457                 SimpleRect* resize_rect = (*i)->resize_rect;
1458                 CanvasNote* canvas_note = (*i)->canvas_note;
1459
1460                 const double region_start = get_position_pixels();
1461
1462                 if (relative) {
1463                         (*i)->current_x = (*i)->current_x + x;
1464                 } else {
1465                         // x is in track relative, transform it to region relative
1466                         (*i)->current_x = x - region_start;
1467                 }
1468
1469                 double current_x = (*i)->current_x;
1470
1471                 if (note_end == CanvasNote::NOTE_ON) {
1472                         resize_rect->property_x1() = snap_to_pixel(current_x);
1473                         resize_rect->property_x2() = canvas_note->x2();
1474                 } else {
1475                         resize_rect->property_x2() = snap_to_pixel(current_x);
1476                         resize_rect->property_x1() = canvas_note->x1();
1477                 }
1478         }
1479 }
1480
1481 void
1482 MidiRegionView::commit_resizing(CanvasNote::NoteEnd note_end, double event_x, bool relative)
1483 {
1484         start_delta_command(_("resize notes"));
1485
1486         for (std::vector<NoteResizeData *>::iterator i = _resize_data.begin(); i != _resize_data.end(); ++i) {
1487                 CanvasNote*  canvas_note = (*i)->canvas_note;
1488                 SimpleRect*  resize_rect = (*i)->resize_rect;
1489                 double       current_x   = (*i)->current_x;
1490                 const double position    = get_position_pixels();
1491
1492                 if (!relative) {
1493                         // event_x is in track relative, transform it to region relative
1494                         current_x = event_x - position;
1495                 }
1496
1497                 // because snapping works on world coordinates we have to transform current_x
1498                 // to world coordinates before snapping and transform it back afterwards
1499                 nframes64_t current_frame = snap_pixel_to_frame(current_x);
1500                 // transform to region start relative
1501                 current_frame += _region->start();
1502                 
1503                 const boost::shared_ptr<NoteType> copy(new NoteType(*(canvas_note->note().get())));
1504
1505                 // resize beginning of note
1506                 if (note_end == CanvasNote::NOTE_ON && current_frame < copy->end_time()) {
1507                         command_remove_note(canvas_note);
1508                         copy->on_event().time() = current_frame;
1509                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1510                 }
1511                 // resize end of note
1512                 if (note_end == CanvasNote::NOTE_OFF && current_frame > copy->time()) {
1513                         command_remove_note(canvas_note);
1514                         copy->off_event().time() = current_frame;
1515                         command_add_note(copy, _selection.find(canvas_note) != _selection.end());
1516                 }
1517
1518                 delete resize_rect;
1519                 delete (*i);
1520         }
1521
1522         _resize_data.clear();
1523         apply_command();
1524 }
1525
1526 void
1527 MidiRegionView::change_note_velocity(CanvasNoteEvent* event, int8_t velocity, bool relative)
1528 {
1529         const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1530
1531         if (relative) {
1532                 uint8_t new_velocity = copy->velocity() + velocity;
1533                 clamp_to_0_127(new_velocity);
1534                 copy->set_velocity(new_velocity);
1535         } else {
1536                 copy->set_velocity(velocity);                   
1537         }
1538
1539         command_remove_note(event);
1540         command_add_note(copy, event->selected(), true);
1541 }
1542
1543 void
1544 MidiRegionView::change_velocity(CanvasNoteEvent* ev, int8_t velocity, bool relative)
1545 {
1546         start_delta_command(_("change velocity"));
1547         
1548         change_note_velocity(ev, velocity, relative);
1549
1550         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1551                 Selection::iterator next = i;
1552                 ++next;
1553                 if ( !(*((*i)->note()) == *(ev->note())) ) {
1554                         change_note_velocity(*i, velocity, relative);
1555                 }
1556                 i = next;
1557         }
1558         
1559         apply_command();
1560 }
1561
1562 void
1563 MidiRegionView::change_channel(uint8_t channel)
1564 {
1565         start_delta_command(_("change channel"));
1566         for (Selection::iterator i = _selection.begin(); i != _selection.end();) {
1567                 Selection::iterator next = i;
1568                 ++next;
1569
1570                 CanvasNoteEvent* event = *i;
1571                 const boost::shared_ptr<NoteType> copy(new NoteType(*(event->note().get())));
1572
1573                 copy->set_channel(channel);
1574                 
1575                 command_remove_note(event);
1576                 command_add_note(copy, event->selected());
1577                 
1578                 i = next;
1579         }
1580         
1581         apply_command();
1582 }
1583
1584
1585 void
1586 MidiRegionView::note_entered(ArdourCanvas::CanvasNoteEvent* ev)
1587 {
1588         if (_mouse_state == SelectTouchDragging) {
1589                 note_selected(ev, true);
1590         }
1591 }
1592
1593
1594 void
1595 MidiRegionView::switch_source(boost::shared_ptr<Source> src)
1596 {
1597         boost::shared_ptr<MidiSource> msrc = boost::dynamic_pointer_cast<MidiSource>(src);
1598         if (msrc)
1599                 display_model(msrc->model());
1600 }
1601
1602 void
1603 MidiRegionView::set_frame_color()
1604 {
1605         if (frame) {
1606                 if (_selected && should_show_selection) {
1607                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_SelectedFrameBase.get();
1608                 } else {
1609                         frame->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_MidiFrameBase.get();
1610                 }
1611         }
1612 }
1613
1614 void 
1615 MidiRegionView::midi_channel_mode_changed(ChannelMode mode, uint16_t mask)
1616 {
1617         switch (mode) {
1618         case AllChannels:
1619         case FilterChannels:
1620                 _force_channel = -1;
1621                 break;
1622         case ForceChannel:
1623                 _force_channel = mask;
1624                 mask = 0xFFFF; // Show all notes as active (below)
1625         };
1626
1627         // Update notes for selection
1628         for (Events::iterator i = _events.begin(); i != _events.end(); ++i) {
1629                 (*i)->on_channel_selection_change(mask);
1630         }
1631
1632         _last_channel_selection = mask;
1633 }
1634
1635 void 
1636 MidiRegionView::midi_patch_settings_changed(std::string model, std::string custom_device_mode)
1637 {
1638         _model_name         = model;
1639         _custom_device_mode = custom_device_mode;
1640         redisplay_model();
1641 }
1642