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