Snap note dragging vertically to note values (rows).
[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 "rgb_macros.h"
50 #include "gui_thread.h"
51
52 #include "i18n.h"
53
54 using namespace sigc;
55 using namespace ARDOUR;
56 using namespace PBD;
57 using namespace Editing;
58 using namespace ArdourCanvas;
59
60 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu,
61                                   Gdk::Color& basic_color)
62         : RegionView (parent, tv, r, spu, basic_color)
63         , _active_notes(0)
64         , _delta_command(NULL)
65         , _command_mode(None)
66 {
67 }
68
69 MidiRegionView::MidiRegionView (ArdourCanvas::Group *parent, RouteTimeAxisView &tv, boost::shared_ptr<MidiRegion> r, double spu, 
70                                   Gdk::Color& basic_color, TimeAxisViewItem::Visibility visibility)
71         : RegionView (parent, tv, r, spu, basic_color, visibility)
72         , _active_notes(0)
73         , _delta_command(NULL)
74         , _command_mode(None)
75 {
76 }
77
78 void
79 MidiRegionView::init (Gdk::Color& basic_color, bool wfd)
80 {
81         if (wfd)
82                 midi_region()->midi_source(0)->load_model();
83
84         _model = midi_region()->midi_source(0)->model();
85         _enable_display = false;
86         
87         RegionView::init(basic_color, false);
88
89         compute_colors (basic_color);
90
91         reset_width_dependent_items ((double) _region->length() / samples_per_unit);
92
93         set_y_position_and_height (0, trackview.height);
94
95         region_muted ();
96         region_resized (BoundsChanged);
97         region_locked ();
98
99         _region->StateChanged.connect (mem_fun(*this, &MidiRegionView::region_changed));
100
101         set_colors ();
102
103         _enable_display = true;
104
105         if (_model) {
106                 if (wfd) {
107                         redisplay_model();
108                 }
109                 _model->ContentsChanged.connect(sigc::mem_fun(this, &MidiRegionView::redisplay_model));
110         }
111         
112         group->signal_event().connect (mem_fun (this, &MidiRegionView::canvas_event), false);
113
114 }
115
116 bool
117 MidiRegionView::canvas_event(GdkEvent* ev)
118 {
119         enum State { None, Pressed, Dragging };
120         static int press_button = 0;
121         static State _state;
122
123         static double last_x, last_y;
124         double event_x, event_y;
125
126         static ArdourCanvas::SimpleRect* select_rect = NULL;
127         
128         if (trackview.editor.current_mouse_mode() != MouseNote)
129                 return false;
130
131         switch (ev->type) {
132         case GDK_KEY_PRESS:
133                 if (ev->key.keyval == GDK_Delete)
134                         start_remove_command();
135                 break;
136         
137         case GDK_KEY_RELEASE:
138                 if (_command_mode == Remove && ev->key.keyval == GDK_Delete)
139                         apply_command();
140                 break;
141
142         case GDK_BUTTON_PRESS:
143                 //group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK, ev->button.time);
144                 _state = Pressed;
145                 press_button = ev->button.button;
146                 //cerr << "PRESSED: " << press_button << endl;
147                 return true;
148         
149         case GDK_MOTION_NOTIFY:
150                 event_x = ev->motion.x;
151                 event_y = ev->motion.y;
152                 group->w2i(event_x, event_y);
153
154                 switch (_state) {
155                 case Pressed: // Drag start
156                         cerr << "PRESSED MOTION: " << press_button << endl;
157                         if (press_button == 1) { // Select rect start
158                                 group->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK,
159                                                 Gdk::Cursor(Gdk::FLEUR), ev->motion.time);
160                                 _state = Dragging;
161                                 last_x = event_x;
162                                 last_y = event_y;
163
164                                 select_rect = new ArdourCanvas::SimpleRect(*group);
165                                 select_rect->property_x1() = event_x;
166                                 select_rect->property_y1() = event_y;
167                                 select_rect->property_x2() = event_x;
168                                 select_rect->property_y2() = event_y;
169                                 select_rect->property_outline_color_rgba() = 0xFF000099;
170                                 select_rect->property_fill_color_rgba() = 0xFFDDDD33;
171
172                                 return true;
173                         }
174                         _state = Dragging;
175                         break;
176
177                 case Dragging: // Select rect motion
178                         if (ev->motion.is_hint) {
179                                 int t_x;
180                                 int t_y;
181                                 GdkModifierType state;
182                                 gdk_window_get_pointer(ev->motion.window, &t_x, &t_y, &state);
183                                 event_x = t_x;
184                                 event_y = t_y;
185                         }
186
187                         if (select_rect) {
188                                 select_rect->property_x2() = event_x;
189                                 select_rect->property_y2() = event_y;
190                         }
191
192                         last_x = event_x;
193                         last_y = event_y;
194
195                         return true;
196                 default:
197                         _state = None;
198                         break;
199                 }
200                 break;
201         
202         case GDK_BUTTON_RELEASE:
203                 group->ungrab(ev->button.time);
204                 switch (_state) {
205                 case Pressed: // Clicked
206                         if (ev->button.button == 1)
207                                 create_note_at(ev->button.x, ev->button.y);
208                         _state = None;
209                         return true;
210                 case Dragging: // Select rect done
211                         _state = None;
212                         delete select_rect;
213                         select_rect = NULL;
214                         return true;
215                 default:
216                         break;
217                 }
218         
219         default:
220                 break;
221         }
222
223         return false;
224 }
225
226
227 /** Add a note to the model, and the view, at a canvas (click) coordinate */
228 void
229 MidiRegionView::create_note_at(double x, double y)
230 {
231         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
232         MidiStreamView* const view = mtv->midi_view();
233
234         const uint8_t note_range = view->highest_note() - view->lowest_note() + 1;
235         const double footer_height = name_highlight->property_y2() - name_highlight->property_y1();
236         const double roll_height = trackview.height - footer_height;
237
238         get_canvas_group()->w2i(x, y);
239
240         double note = floor((roll_height - y) / roll_height * (double)note_range) + view->lowest_note();
241         assert(note >= 0.0);
242         assert(note <= 127.0);
243
244         const nframes_t stamp = trackview.editor.pixel_to_frame (x);
245         assert(stamp >= 0);
246         //assert(stamp <= _region->length());
247
248         const Meter& m = trackview.session().tempo_map().meter_at(stamp);
249         const Tempo& t = trackview.session().tempo_map().tempo_at(stamp);
250         double dur = m.frames_per_bar(t, trackview.session().frame_rate()) / m.beats_per_bar();
251
252         // Add a 1 beat long note (for now)
253         const MidiModel::Note new_note(stamp, dur, (uint8_t)note, 0x40);
254         
255         view->update_bounds(new_note.note());
256
257         MidiModel::DeltaCommand* cmd = _model->new_delta_command("add note");
258         cmd->add(new_note);
259         _model->apply_command(cmd);
260         
261         //add_note(new_note);
262 }
263
264
265 void
266 MidiRegionView::clear_events()
267 {
268         for (std::vector<ArdourCanvas::Item*>::iterator i = _events.begin(); i != _events.end(); ++i)
269                 delete *i;
270         
271         _events.clear();
272 }
273
274
275 void
276 MidiRegionView::display_model(boost::shared_ptr<MidiModel> model)
277 {
278         _model = model;
279
280         if (_enable_display)
281                 redisplay_model();
282 }
283
284
285 void
286 MidiRegionView::redisplay_model()
287 {
288         clear_events();
289         
290         if (_model) {
291                 begin_write();
292
293                 for (size_t i=0; i < _model->n_notes(); ++i)
294                         add_note(_model->note_at(i));
295
296                 end_write();
297         } else {
298                 warning << "MidiRegionView::redisplay_model called without a model" << endmsg;
299         }
300 }
301
302
303 MidiRegionView::~MidiRegionView ()
304 {
305         in_destructor = true;
306         end_write();
307
308         RegionViewGoingAway (this); /* EMIT_SIGNAL */
309 }
310
311
312 void
313 MidiRegionView::region_resized (Change what_changed)
314 {
315         RegionView::region_resized(what_changed);
316
317         if (what_changed & ARDOUR::PositionChanged) {
318         
319                 if (_enable_display)
320                         redisplay_model();
321         
322         } else if (what_changed & Change (StartChanged)) {
323
324                 //cerr << "MIDI RV START CHANGED" << endl;
325
326         } else if (what_changed & Change (LengthChanged)) {
327                 
328                 //cerr << "MIDI RV LENGTH CHANGED" << endl;
329         
330         }
331 }
332
333 void
334 MidiRegionView::reset_width_dependent_items (double pixel_width)
335 {
336         RegionView::reset_width_dependent_items(pixel_width);
337         assert(_pixel_width == pixel_width);
338                 
339         if (_enable_display)
340                 redisplay_model();
341 }
342
343 void
344 MidiRegionView::set_y_position_and_height (double y, double h)
345 {
346         RegionView::set_y_position_and_height(y, h - 1);
347
348         if (_enable_display)
349                 redisplay_model();
350
351         if (name_text) {
352                 name_text->raise_to_top();
353         }
354 }
355
356 void
357 MidiRegionView::show_region_editor ()
358 {
359         cerr << "No MIDI region editor." << endl;
360 }
361
362 GhostRegion*
363 MidiRegionView::add_ghost (AutomationTimeAxisView& atv)
364 {
365         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
366         assert(rtv);
367
368         double unit_position = _region->position () / samples_per_unit;
369         GhostRegion* ghost = new GhostRegion (atv, unit_position);
370
371         ghost->set_height ();
372         ghost->set_duration (_region->length() / samples_per_unit);
373         ghosts.push_back (ghost);
374
375         ghost->GoingAway.connect (mem_fun(*this, &MidiRegionView::remove_ghost));
376
377         return ghost;
378 }
379
380
381 /** Begin tracking note state for successive calls to add_event
382  */
383 void
384 MidiRegionView::begin_write()
385 {
386         _active_notes = new CanvasNote*[128];
387         for (unsigned i=0; i < 128; ++i)
388                 _active_notes[i] = NULL;
389 }
390
391
392 /** Destroy note state for add_event
393  */
394 void
395 MidiRegionView::end_write()
396 {
397         delete[] _active_notes;
398         _active_notes = NULL;
399 }
400
401
402 /** Add a MIDI event.
403  *
404  * This is used while recording, and handles displaying still-unresolved notes.
405  * Displaying an existing model is simpler, and done with add_note.
406  */
407 void
408 MidiRegionView::add_event (const MidiEvent& ev)
409 {
410         /*printf("Event, time = %f, size = %zu, data = ", ev.time, ev.size);
411         for (size_t i=0; i < ev.size; ++i) {
412                 printf("%X ", ev.buffer[i]);
413         }
414         printf("\n\n");*/
415
416         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
417         
418         if (midi_view()->note_mode() == Sustained) {
419                 if ((ev.buffer()[0] & 0xF0) == MIDI_CMD_NOTE_ON) {
420                         const Byte& note = ev.buffer()[1];
421                         const double y1 = note_y(note);
422
423                         CanvasNote* ev_rect = new CanvasNote(*this, *group);
424                         ev_rect->property_x1() = trackview.editor.frame_to_pixel (
425                                         (nframes_t)ev.time());
426                         ev_rect->property_y1() = y1;
427                         ev_rect->property_x2() = trackview.editor.frame_to_pixel (
428                                         _region->length());
429                         ev_rect->property_y2() = y1 + note_height();
430                         ev_rect->property_outline_color_rgba() = 0xFFFFFFAA;
431                         /* outline all but right edge */
432                         ev_rect->property_outline_what() = (guint32) (0x1 & 0x4 & 0x8);
433                         ev_rect->property_fill_color_rgba() = 0xFFFFFF66;
434
435                         ev_rect->raise_to_top();
436
437                         _events.push_back(ev_rect);
438                         if (_active_notes)
439                                 _active_notes[note] = ev_rect;
440
441                 } else if ((ev.buffer()[0] & 0xF0) == MIDI_CMD_NOTE_OFF) {
442                         const Byte& note = ev.buffer()[1];
443                         if (_active_notes && _active_notes[note]) {
444                                 _active_notes[note]->property_x2() = trackview.editor.frame_to_pixel((nframes_t)ev.time());
445                                 _active_notes[note]->property_outline_what() = (guint32) 0xF; // all edges
446                                 _active_notes[note] = NULL;
447                         }
448                 }
449         
450         } else if (midi_view()->note_mode() == Percussive) {
451                 const Byte& note = ev.buffer()[1];
452                 const double diamond_size = std::min(note_height(), 5.0);
453                 const double x = trackview.editor.frame_to_pixel((nframes_t)ev.time());
454                 const double y = note_y(note) + (diamond_size / 2.0);
455
456                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, diamond_size);
457                 ev_diamond->move(x, y);
458                 ev_diamond->show();
459                 ev_diamond->property_outline_color_rgba() = 0xFFFFFFDD;
460                 ev_diamond->property_fill_color_rgba() = 0xFFFFFF66;
461                         
462                 _events.push_back(ev_diamond);
463         }
464 }
465
466
467 /** Extend active notes to rightmost edge of region (if length is changed)
468  */
469 void
470 MidiRegionView::extend_active_notes()
471 {
472         if (!_active_notes)
473                 return;
474
475         for (unsigned i=0; i < 128; ++i)
476                 if (_active_notes[i])
477                         _active_notes[i]->property_x2() = trackview.editor.frame_to_pixel(_region->length());
478 }
479
480
481 /** Add a MIDI note to the view (with duration).
482  *
483  * This does no 'realtime' note resolution, notes from a MidiModel have a
484  * duration so they can be drawn in full immediately.
485  */
486 void
487 MidiRegionView::add_note (const MidiModel::Note& note)
488 {
489         assert(note.time() >= 0);
490         assert(note.time() < _region->length());
491         //assert(note.time() + note.duration < _region->length());
492
493         MidiTimeAxisView* const mtv = dynamic_cast<MidiTimeAxisView*>(&trackview);
494         MidiStreamView* const view = mtv->midi_view();
495         ArdourCanvas::Group* const group = (ArdourCanvas::Group*)get_canvas_group();
496         
497         const uint8_t note_range = view->highest_note() - view->lowest_note() + 1;
498         const double footer_height = name_highlight->property_y2() - name_highlight->property_y1();
499         const double pixel_range = (trackview.height - footer_height - 5.0) / (double)note_range;
500         const uint8_t fill_alpha = 0x20 + (uint8_t)(note.velocity() * 1.5); 
501         const uint32_t fill = RGBA_TO_UINT(0xE0 + note.velocity()/127.0 * 0x10, 0xE0, 0xE0, fill_alpha);
502         const uint8_t outline_alpha = 0x80 + (uint8_t)(note.velocity()); 
503         const uint32_t outline = RGBA_TO_UINT(0xE0 + note.velocity()/127.0 * 0x10, 0xE0, 0xE0, outline_alpha);
504         
505         //printf("Range: %d\n", note_range);
506         //printf("Event, time = %f, note = %d\n", note.time(), note.note());
507
508
509         if (mtv->note_mode() == Sustained) {
510                 const double y1 = trackview.height - (pixel_range * (note.note() - view->lowest_note() + 1))
511                         - footer_height - 3.0;
512
513                 ArdourCanvas::SimpleRect * ev_rect = new CanvasNote(*this, *group, &note);
514                 ev_rect->property_x1() = trackview.editor.frame_to_pixel((nframes_t)note.time());
515                 ev_rect->property_y1() = y1;
516                 ev_rect->property_x2() = trackview.editor.frame_to_pixel((nframes_t)(note.end_time()));
517                 ev_rect->property_y2() = y1 + ceil(pixel_range);
518
519                 ev_rect->property_fill_color_rgba() = fill;
520                 ev_rect->property_outline_color_rgba() = outline;
521                 ev_rect->property_outline_what() = (guint32) 0xF; // all edges
522
523                 ev_rect->show();
524                 _events.push_back(ev_rect);
525
526         } else if (mtv->note_mode() == Percussive) {
527                 const double x = trackview.editor.frame_to_pixel((nframes_t)note.time());
528                 const double y = trackview.height - (pixel_range * (note.note() - view->lowest_note() + 1))
529                         - footer_height - 3.0;
530
531                 CanvasHit* ev_diamond = new CanvasHit(*this, *group, std::min(pixel_range, 5.0), &note);
532                 ev_diamond->move(x, y);
533                 ev_diamond->show();
534                 ev_diamond->property_fill_color_rgba() = fill;
535                 ev_diamond->property_outline_color_rgba() = outline;
536                 _events.push_back(ev_diamond);
537         }
538 }
539
540