First appearance of MIDI edit tool bar. Toggles when delete held, but otherwise...
[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_events.h>
36 #include <ardour/midi_model.h>
37
38 #include "streamview.h"
39 #include "midi_region_view.h"
40 #include "midi_streamview.h"
41 #include "midi_time_axis.h"
42 #include "simplerect.h"
43 #include "simpleline.h"
44 #include "canvas-hit.h"
45 #include "public_editor.h"
46 #include "ghostregion.h"
47 #include "midi_time_axis.h"
48 #include "utils.h"
49 #include "midi_util.h"
50 #include "gui_thread.h"
51 #include "keyboard.h"
52
53 #include "i18n.h"
54
55 using namespace sigc;
56 using namespace ARDOUR;
57 using namespace PBD;
58 using namespace Editing;
59 using namespace ArdourCanvas;
60
61 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu,
62                                   Gdk::Color& basic_color)
63         : RegionView (parent, tv, r, spu, basic_color)
64         , _default_note_length(0.0)
65         , _active_notes(0)
66         , _delta_command(NULL)
67         , _command_mode(None)
68 {
69 }
70
71 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu, 
72                                   Gdk::Color& basic_color, TimeAxisViewItem::Visibility visibility)
73         : RegionView (parent, tv, r, spu, basic_color, visibility)
74         , _default_note_length(0.0)
75         , _active_notes(0)
76         , _delta_command(NULL)
77         , _command_mode(None)
78 {
79 }
80
81 void
82 MidiRegionView::init (Gdk::Color& basic_color, bool wfd)
83 {
84         if (wfd)
85                 midi_region()->midi_source(0)->load_model();
86         
87         const Meter& m = trackview.session().tempo_map().meter_at(_region->start());
88         const Tempo& t = trackview.session().tempo_map().tempo_at(_region->start());
89         _default_note_length = m.frames_per_bar(t, trackview.session().frame_rate())
90                         / m.beats_per_bar();
91
92         _model = midi_region()->midi_source(0)->model();
93         _enable_display = false;
94         
95         RegionView::init(basic_color, false);
96
97         compute_colors (basic_color);
98
99         reset_width_dependent_items ((double) _region->length() / samples_per_unit);
100
101         set_y_position_and_height (0, trackview.height);
102
103         region_muted ();
104         region_resized (BoundsChanged);
105         region_locked ();
106
107         _region->StateChanged.connect (mem_fun(*this, &MidiRegionView::region_changed));
108
109         set_colors ();
110
111         _enable_display = true;
112
113         if (_model) {
114                 if (wfd) {
115                         redisplay_model();
116                 }
117                 _model->ContentsChanged.connect(sigc::mem_fun(this, &MidiRegionView::redisplay_model));
118         }
119         
120         group->signal_event().connect (mem_fun (this, &MidiRegionView::canvas_event), false);
121
122 }
123
124 bool
125 MidiRegionView::canvas_event(GdkEvent* ev)
126 {
127         enum State { None, Pressed, SelectDragging, AddDragging };
128         static int press_button = 0;
129         static State _state;
130
131         static double drag_start_x, drag_start_y;
132         static double last_x, last_y;
133         double event_x, event_y;
134
135         static ArdourCanvas::SimpleRect* drag_rect = NULL;
136         
137         if (trackview.editor.current_mouse_mode() != MouseNote)
138                 return false;
139
140         switch (ev->type) {
141         case GDK_KEY_PRESS:
142                 if (ev->key.keyval == GDK_Delete) {
143                         trackview.editor.set_midi_edit_mode(MidiEditErase);
144                         start_remove_command();
145                 }
146                 break;
147         
148         case GDK_KEY_RELEASE:
149                 if (_command_mode == Remove && ev->key.keyval == GDK_Delete) {
150                         delete_selection();
151                         apply_command();
152                         trackview.editor.set_midi_edit_mode(MidiEditSelect);
153                 }
154                 break;
155
156         case GDK_BUTTON_PRESS:
157                 //group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK, ev->button.time);
158                 _state = Pressed;
159                 press_button = ev->button.button;
160                 //cerr << "PRESSED: " << press_button << endl;
161                 return true;
162         
163         case GDK_ENTER_NOTIFY:
164                 /* FIXME: do this on switch to note tool, too, if the pointer is already in */
165                 Keyboard::magic_widget_grab_focus();
166                 group->grab_focus();
167                 break;
168         
169         case GDK_MOTION_NOTIFY:
170                 event_x = ev->motion.x;
171                 event_y = ev->motion.y;
172                 group->w2i(event_x, event_y);
173
174                 switch (_state) {
175                 case Pressed: // Drag start
176
177                         if (press_button == 1 && _command_mode != Remove) { // Select rect start
178                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
179                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
180                                 last_x = event_x;
181                                 last_y = event_y;
182                                 drag_start_x = event_x;
183                                 drag_start_y = event_y;
184
185                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
186                                 drag_rect->property_x1() = event_x;
187                                 drag_rect->property_y1() = event_y;
188                                 drag_rect->property_x2() = event_x;
189                                 drag_rect->property_y2() = event_y;
190                                 drag_rect->property_outline_what() = 0xFF;
191                                 drag_rect->property_outline_color_rgba()
192                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectOutline.get();
193                                 drag_rect->property_fill_color_rgba()
194                                         = ARDOUR_UI::config()->canvasvar_MidiSelectRectFill.get();
195
196                                 _state = SelectDragging;
197                                 return true;
198
199                         } else if (press_button == 3) { // Add note drag start
200                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
201                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
202                                 last_x = event_x;
203                                 last_y = event_y;
204                                 drag_start_x = event_x;
205                                 drag_start_y = event_y;
206                                 
207                                 nframes_t event_frame = midi_view()->editor.pixel_to_frame(event_x);
208                                 midi_view()->editor.snap_to(event_frame);
209
210                                 drag_rect = new ArdourCanvas::SimpleRect(*group);
211                                 drag_rect->property_x1() = midi_view()->editor.frame_to_pixel(event_frame);
212                                 
213                                 drag_rect->property_y1() = midi_stream_view()->note_to_y(midi_stream_view()->y_to_note(event_y));
214                                 drag_rect->property_x2() = event_x;
215                                 drag_rect->property_y2() = drag_rect->property_y1() + floor(midi_stream_view()->note_height());
216                                 drag_rect->property_outline_what() = 0xFF;
217                                 drag_rect->property_outline_color_rgba() = 0xFFFFFF99;
218
219                                 drag_rect->property_fill_color_rgba() = 0xFFFFFF66;
220
221                                 _state = AddDragging;
222                                 return true;
223                         }
224
225                         break;
226
227                 case SelectDragging: // Select rect motion
228                 case AddDragging: // Add note rect motion
229                         if (ev->motion.is_hint) {
230                                 int t_x;
231                                 int t_y;
232                                 GdkModifierType state;
233                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
234                                 event_x = t_x;
235                                 event_y = t_y;
236                         }
237
238                         if (_state == AddDragging) {
239                                 nframes_t event_frame = midi_view()->editor.pixel_to_frame(event_x);
240                                 midi_view()->editor.snap_to(event_frame);
241                                 event_x = midi_view()->editor.frame_to_pixel(event_frame);
242                         }
243
244                         if (drag_rect)
245                                 drag_rect->property_x2() = event_x;
246
247                         if (drag_rect && _state == SelectDragging) {
248                                 drag_rect->property_y2() = event_y;
249
250                                 update_drag_selection(drag_start_x, event_x, drag_start_y, event_y);
251                         }
252
253                         last_x = event_x;
254                         last_y = event_y;
255
256                         return true;
257                 default:
258                         _state = None;
259                         break;
260                 }
261                 break;
262         
263         case GDK_BUTTON_RELEASE:
264                 event_x = ev->motion.x;
265                 event_y = ev->motion.y;
266                 group->w2i(event_x, event_y);
267                 group->ungrab(ev->button.time);
268                 switch (_state) {
269                 case Pressed: // Clicked
270                         if (ev->button.button == 1) {
271                                 clear_selection();
272                         } else if (ev->button.button == 3) {
273                                 nframes_t event_frame = midi_view()->editor.pixel_to_frame(event_x);
274                                 midi_view()->editor.snap_to(event_frame);
275                                 event_x = midi_view()->editor.frame_to_pixel(event_frame);
276                                 create_note_at(event_x, event_y, _default_note_length);
277                         }
278                         _state = None;
279                         return true;
280                 case SelectDragging: // Select drag done
281                         _state = None;
282                         delete drag_rect;
283                         drag_rect = NULL;
284                         return true;
285                 case AddDragging: // Add drag done
286                         _state = None;
287                         if (drag_rect->property_x2() > drag_rect->property_x1() + 2) {
288                                 create_note_at(drag_rect->property_x1(), drag_rect->property_y1(),
289                                                 trackview.editor.pixel_to_frame(
290                                                 drag_rect->property_x2() - drag_rect->property_x1()));
291                         }
292
293                         delete drag_rect;
294                         drag_rect = NULL;
295                         return true;
296                 default:
297                         break;
298                 }
299         
300         default:
301                 break;
302         }
303
304         return false;
305 }
306
307
308 /** Add a note to the model, and the view, at a canvas (click) coordinate */
309 void
310 MidiRegionView::create_note_at(double x, double y, double dur)
311 {
312         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
313         MidiStreamView* const view = mtv->midi_view();
314
315         double note = midi_stream_view()->y_to_note(y);
316
317         assert(note >= 0.0);
318         assert(note <= 127.0);
319
320         const nframes_t stamp = trackview.editor.pixel_to_frame (x);
321         assert(stamp >= 0);
322         //assert(stamp <= _region->length());
323
324         //const Meter& m = trackview.session().tempo_map().meter_at(stamp);
325         //const Tempo& t = trackview.session().tempo_map().tempo_at(stamp);
326         //double dur = m.frames_per_bar(t, trackview.session().frame_rate()) / m.beats_per_bar();
327
328         // Add a 1 beat long note (for now)
329         const MidiModel::Note new_note(stamp, dur, (uint8_t)note, 0x40);
330         
331         view->update_bounds(new_note.note());
332
333         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
334         cmd->add(new_note);
335         _model->apply_command(cmd);
336         
337         //add_note(new_note);
338 }
339
340
341 void
342 MidiRegionView::clear_events()
343 {
344         for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i)
345                 delete *i;
346         
347         _events.clear();
348 }
349
350
351 void
352 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
353 {
354         _model = model;
355
356         if (_enable_display)
357                 redisplay_model();
358 }
359
360
361 void
362 MidiRegionView::redisplay_model()
363 {
364         clear_events();
365         
366         if (_model) {
367                 begin_write();
368
369                 for (size_t i=0; i < _model->n_notes(); ++i)
370                         add_note(_model->note_at(i));
371
372                 end_write();
373         } else {
374                 warning << "MidiRegionView::redisplay_model called without a model" << endmsg;
375         }
376 }
377
378
379 MidiRegionView::~MidiRegionView ()
380 {
381         in_destructor = true;
382         end_write();
383
384         RegionViewGoingAway (this); /* EMIT_SIGNAL */
385 }
386
387
388 void
389 MidiRegionView::region_resized (Change what_changed)
390 {
391         RegionView::region_resized(what_changed);
392
393         if (what_changed & ARDOUR::PositionChanged) {
394         
395                 if (_enable_display)
396                         redisplay_model();
397         
398         } else if (what_changed & Change (StartChanged)) {
399
400                 //cerr << "MIDI RV START CHANGED" << endl;
401
402         } else if (what_changed & Change (LengthChanged)) {
403                 
404                 //cerr << "MIDI RV LENGTH CHANGED" << endl;
405         
406         }
407 }
408
409 void
410 MidiRegionView::reset_width_dependent_items (double pixel_width)
411 {
412         RegionView::reset_width_dependent_items(pixel_width);
413         assert(_pixel_width == pixel_width);
414                 
415         if (_enable_display)
416                 redisplay_model();
417 }
418
419 void
420 MidiRegionView::set_y_position_and_height (double y, double h)
421 {
422         RegionView::set_y_position_and_height(y, h - 1);
423
424         if (_enable_display)
425                 redisplay_model();
426
427         if (name_text) {
428                 name_text->raise_to_top();
429         }
430 }
431
432 GhostRegion*
433 MidiRegionView::add_ghost (AutomationTimeAxisView& atv)
434 {
435         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
436         assert(rtv);
437
438         double unit_position = _region->position () / samples_per_unit;
439         GhostRegion* ghost = new GhostRegion (atv, unit_position);
440
441         ghost->set_height ();
442         ghost->set_duration (_region->length() / samples_per_unit);
443         ghosts.push_back (ghost);
444
445         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
446
447         return ghost;
448 }
449
450
451 /** Begin tracking note state for successive calls to add_event
452  */
453 void
454 MidiRegionView::begin_write()
455 {
456         _active_notes = new CanvasNote*[128];
457         for (unsigned i=0; i < 128; ++i)
458                 _active_notes[i] = NULL;
459 }
460
461
462 /** Destroy note state for add_event
463  */
464 void
465 MidiRegionView::end_write()
466 {
467         delete[] _active_notes;
468         _active_notes = NULL;
469 }
470
471
472 /** Add a MIDI event.
473  *
474  * This is used while recording, and handles displaying still-unresolved notes.
475  * Displaying an existing model is simpler, and done with add_note.
476  */
477 void
478 MidiRegionView::add_event (const MidiEvent& ev)
479 {
480         /*printf("Event, time = %f, size = %zu, data = ", ev.time, ev.size);
481         for (size_t i=0; i < ev.size; ++i) {
482                 printf("%X ", ev.buffer[i]);
483         }
484         printf("\n\n");*/
485
486         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
487         
488         if (midi_view()->note_mode() == Sustained) {
489                 if ((ev.buffer()[0] & 0xF0) == MIDI_CMD_NOTE_ON) {
490                         const Byte& note = ev.buffer()[1];
491                         const double y1 = midi_stream_view()->note_to_y(note);
492
493                         CanvasNote* ev_rect = new CanvasNote(*this, *group);
494                         ev_rect->property_x1() = trackview.editor.frame_to_pixel (
495                                         (nframes_t)ev.time());
496                         ev_rect->property_y1() = y1;
497                         ev_rect->property_x2() = trackview.editor.frame_to_pixel (
498                                         _region->length());
499                         ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
500                         ev_rect->property_fill_color_rgba() = note_fill_color(ev.velocity());
501                         ev_rect->property_outline_color_rgba() = note_outline_color(ev.velocity());
502                         /* outline all but right edge */
503                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
504
505                         ev_rect->raise_to_top();
506
507                         _events.push_back(ev_rect);
508                         if (_active_notes)
509                                 _active_notes[note] = ev_rect;
510
511                 } else if ((ev.buffer()[0] & 0xF0) == MIDI_CMD_NOTE_OFF) {
512                         const Byte& note = ev.buffer()[1];
513                         if (_active_notes && _active_notes[note]) {
514                                 _active_notes[note]->property_x2() = trackview.editor.frame_to_pixel((nframes_t)ev.time());
515                                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
516                                 _active_notes[note] = NULL;
517                         }
518                 }
519         
520         } else if (midi_view()->note_mode() == Percussive) {
521                 const Byte& note = ev.buffer()[1];
522                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
523                 const double x = trackview.editor.frame_to_pixel((nframes_t)ev.time());
524                 const double y = midi_stream_view()->note_to_y(note) + ((diamond_size-2) / 4.0);
525
526                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size);
527                 ev_diamond->move(x, y);
528                 ev_diamond->show();
529                 ev_diamond->property_fill_color_rgba() = note_fill_color(ev.velocity());
530                 ev_diamond->property_outline_color_rgba() = note_outline_color(ev.velocity());
531                 
532                 _events.push_back(ev_diamond);
533         }
534 }
535
536
537 /** Extend active notes to rightmost edge of region (if length is changed)
538  */
539 void
540 MidiRegionView::extend_active_notes()
541 {
542         if (!_active_notes)
543                 return;
544
545         for (unsigned i=0; i < 128; ++i)
546                 if (_active_notes[i])
547                         _active_notes[i]->property_x2() = trackview.editor.frame_to_pixel(_region->length());
548 }
549
550
551 /** Add a MIDI note to the view (with duration).
552  *
553  * This does no 'realtime' note resolution, notes from a MidiModel have a
554  * duration so they can be drawn in full immediately.
555  */
556 void
557 MidiRegionView::add_note (const MidiModel::Note& note)
558 {
559         assert(note.time() >= 0);
560         //assert(note.time() < _region->length());
561
562         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
563         
564         if (midi_view()->note_mode() == Sustained) {
565                 const double y1 = midi_stream_view()->note_to_y(note.note());
566
567                 CanvasNote* ev_rect = new CanvasNote(*this, *group, &note);
568                 ev_rect->property_x1() = trackview.editor.frame_to_pixel((nframes_t)note.time());
569                 ev_rect->property_y1() = y1;
570                 ev_rect->property_x2() = trackview.editor.frame_to_pixel((nframes_t)(note.end_time()));
571                 ev_rect->property_y2() = y1 + floor(midi_stream_view()->note_height());
572
573                 ev_rect->property_fill_color_rgba() = note_fill_color(note.velocity());
574                 ev_rect->property_outline_color_rgba() = note_outline_color(note.velocity());
575                 ev_rect->property_outline_what() = (guint32) 0xF; // all edges
576
577                 ev_rect->show();
578                 _events.push_back(ev_rect);
579
580         } else if (midi_view()->note_mode() == Percussive) {
581                 const double diamond_size = midi_stream_view()->note_height() / 2.0;
582                 const double x = trackview.editor.frame_to_pixel((nframes_t)note.time());
583                 const double y = midi_stream_view()->note_to_y(note.note()) + ((diamond_size-2) / 4.0);
584
585                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size);
586                 ev_diamond->move(x, y);
587                 ev_diamond->show();
588                 ev_diamond->property_fill_color_rgba() = note_fill_color(note.velocity());
589                 ev_diamond->property_outline_color_rgba() = note_outline_color(note.velocity());
590                 _events.push_back(ev_diamond);
591         }
592 }
593
594 void
595 MidiRegionView::delete_selection()
596 {
597         assert(_delta_command);
598
599         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
600                 if ((*i)->selected())
601                         _delta_command->remove(*(*i)->note());
602
603         _selection.clear();
604 }
605
606 void
607 MidiRegionView::clear_selection_except(ArdourCanvas::CanvasMidiEvent* ev)
608 {
609         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
610                 if ((*i)->selected() && (*i) != ev)
611                         (*i)->selected(false);
612
613         _selection.clear();
614 }
615
616 void
617 MidiRegionView::unique_select(ArdourCanvas::CanvasMidiEvent* ev)
618 {
619         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
620                 if ((*i) != ev)
621                         (*i)->selected(false);
622
623         _selection.clear();
624         _selection.insert(ev);
625         ev->selected(true);
626 }
627         
628 void
629 MidiRegionView::note_selected(ArdourCanvas::CanvasMidiEvent* ev, bool add)
630 {
631         if ( ! add)
632                 clear_selection_except(ev);
633         
634         _selection.insert(ev);
635         ev->selected(true);
636 }
637
638
639 void
640 MidiRegionView::note_deselected(ArdourCanvas::CanvasMidiEvent* ev, bool add)
641 {
642         if ( ! add)
643                 clear_selection_except(ev);
644         
645         _selection.erase(ev);
646         ev->selected(false);
647 }
648
649
650 void
651 MidiRegionView::update_drag_selection(double last_x, double x, double last_y, double y)
652 {
653         // FIXME: so, so, so much slower than this should be
654         for (std::vector<CanvasMidiEvent*>::iterator i = _events.begin(); i != _events.end(); ++i) {
655                 if ((*i)->x1() >= last_x && (*i)->x1() <= x && (*i)->y1() >= last_y && (*i)->y1() <= y) {
656                         (*i)->selected(true);
657                         _selection.insert(*i);
658                 } else {
659                         (*i)->selected(false);
660                         _selection.erase(*i);
661                 }
662         }
663 }
664
665         
666 void
667 MidiRegionView::move_selection(double dx, double dy)
668 {
669         for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i)
670                 (*i)->item()->move(dx, dy);
671 }
672
673 void
674 MidiRegionView::note_dropped(CanvasMidiEvent* ev, double dt, uint8_t dnote)
675 {
676         // TODO: This would be faster/nicer with a MoveCommand that doesn't need to copy...
677         if (_selection.find(ev) != _selection.end()) {
678                 start_delta_command();
679
680                 for (Selection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
681                         command_remove_note(*i);
682                         MidiModel::Note copy(*(*i)->note()); 
683
684                         copy.set_time((*i)->note()->time() + dt);
685                         copy.set_note((*i)->note()->note() + dnote);
686
687                         command_add_note(copy);
688                 }
689                 apply_command();
690         }
691 }
692