tweak event/leave event delivery so that it applies to items being deleted as well...
[ardour.git] / libs / canvas / canvas.cc
1 /*
2     Copyright (C) 2011 Paul Davis
3     Author: Carl Hetherington <cth@carlh.net>
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
21 /** @file  canvas/canvas.cc
22  *  @brief Implementation of the main canvas classes.
23  */
24
25 #include <cassert>
26 #include <gtkmm/adjustment.h>
27 #include <gtkmm/label.h>
28
29 #include "pbd/compose.h"
30 #include "pbd/stacktrace.h"
31
32 #include "canvas/canvas.h"
33 #include "canvas/debug.h"
34
35 using namespace std;
36 using namespace ArdourCanvas;
37
38 /** Construct a new Canvas */
39 Canvas::Canvas ()
40         : _root (this)
41         , _log_renders (true)
42         , _scroll_offset_x (0)
43         , _scroll_offset_y (0)
44 {
45         set_epoch ();
46 }
47
48 void
49 Canvas::scroll_to (Coord x, Coord y)
50 {
51         _scroll_offset_x = x;
52         _scroll_offset_y = y;
53 }
54
55 /** Render an area of the canvas.
56  *  @param area Area in canvas coordinates.
57  *  @param context Cairo context to render to.
58  */
59 void
60 Canvas::render (Rect const & area, Cairo::RefPtr<Cairo::Context> const & context) const
61 {
62 #ifdef CANVAS_DEBUG
63         if (DEBUG_ENABLED(PBD::DEBUG::CanvasRender)) {
64                 cerr << "CANVAS @ " << this << endl;
65                 dump (cerr);
66                 cerr << "-------------------------\n";
67         }
68 #endif
69
70         // checkpoint ("render", "-> render");
71         render_count = 0;
72         
73         context->save ();
74
75 #ifdef CANVAS_DEBUG
76         if (getenv ("ARDOUR_REDRAW_CANVAS")) {
77                 /* light up the canvas to show redraws */
78                 context->set_source_rgba (random()%255 / 255.0,
79                                           random()%255 / 255.0,
80                                           random()%255 / 255.0,
81                                           255);
82                 context->rectangle (area.x0, area.y0, area.width(), area.height());
83                 context->stroke ();
84         }
85 #endif
86
87         /* clip to the requested area */
88         context->rectangle (area.x0, area.y0, area.width(), area.height());
89         context->clip ();
90
91         boost::optional<Rect> root_bbox = _root.bounding_box();
92         if (!root_bbox) {
93                 /* the root has no bounding box, so there's nothing to render */
94                 // checkpoint ("render", "no root bbox");
95                 context->restore ();
96                 return;
97         }
98
99         boost::optional<Rect> draw = root_bbox.get().intersection (area);
100         if (draw) {
101                 /* there's a common area between the root and the requested
102                    area, so render it.
103                 */
104                 // checkpoint ("render", "... root");
105                 context->stroke ();
106
107                 _root.render (*draw, context);
108         }
109
110         if (_log_renders) {
111                 _renders.push_back (area);
112         }
113
114         context->restore ();
115
116 #ifdef CANVAS_DEBUG
117         if (getenv ("ARDOUR_HARLEQUIN_CANVAS")) {
118                 /* light up the canvas to show redraws */
119                 context->set_source_rgba (random()%255 / 255.0,
120                                           random()%255 / 255.0,
121                                           random()%255 / 255.0,
122                                           255);
123                 context->rectangle (area.x0, area.y0, area.width(), area.height());
124                 context->fill ();
125         }
126 #endif
127         // checkpoint ("render", "<- render");
128 }
129
130 ostream&
131 operator<< (ostream& o, Canvas& c)
132 {
133         c.dump (o);
134         return o;
135 }
136
137 std::string
138 Canvas::indent() const
139
140         string s;
141
142         for (int n = 0; n < ArdourCanvas::dump_depth; ++n) {
143                 s += '\t';
144         }
145
146         return s;
147 }
148
149 std::string
150 Canvas::render_indent() const
151
152         string s;
153
154         for (int n = 0; n < ArdourCanvas::render_depth; ++n) {
155                 s += ' ';
156         }
157
158         return s;
159 }
160
161 void
162 Canvas::dump (ostream& o) const
163 {
164         dump_depth = 0;
165         _root.dump (o);
166 }       
167
168 /** Called when an item has been shown or hidden.
169  *  @param item Item that has been shown or hidden.
170  */
171 void
172 Canvas::item_shown_or_hidden (Item* item)
173 {
174         boost::optional<Rect> bbox = item->bounding_box ();
175         if (bbox) {
176                 queue_draw_item_area (item, bbox.get ());
177         }
178 }
179
180 /** Called when an item has a change to its visual properties
181  *  that do NOT affect its bounding box.
182  *  @param item Item that has been modified.
183  */
184 void
185 Canvas::item_visual_property_changed (Item* item)
186 {
187         boost::optional<Rect> bbox = item->bounding_box ();
188         if (bbox) {
189                 queue_draw_item_area (item, bbox.get ());
190         }
191 }
192
193 /** Called when an item has changed, but not moved.
194  *  @param item Item that has changed.
195  *  @param pre_change_bounding_box The bounding box of item before the change,
196  *  in the item's coordinates.
197  */
198 void
199 Canvas::item_changed (Item* item, boost::optional<Rect> pre_change_bounding_box)
200 {
201         if (pre_change_bounding_box) {
202                 /* request a redraw of the item's old bounding box */
203                 queue_draw_item_area (item, pre_change_bounding_box.get ());
204         }
205
206         boost::optional<Rect> post_change_bounding_box = item->bounding_box ();
207         if (post_change_bounding_box) {
208                 /* request a redraw of the item's new bounding box */
209                 queue_draw_item_area (item, post_change_bounding_box.get ());
210         }
211 }
212
213 Duple
214 Canvas::window_to_canvas (Duple const & d) const
215 {
216         return d.translate (Duple (_scroll_offset_x, _scroll_offset_y));
217 }
218
219 Duple
220 Canvas::canvas_to_window (Duple const & d) const
221 {
222         return d.translate (Duple (-_scroll_offset_x, -_scroll_offset_y));
223 }       
224
225 Rect
226 Canvas::window_to_canvas (Rect const & r) const
227 {
228         return r.translate (Duple (_scroll_offset_x, _scroll_offset_y));
229 }
230
231 Rect
232 Canvas::canvas_to_window (Rect const & r) const
233 {
234         return r.translate (Duple (-_scroll_offset_x, -_scroll_offset_y));
235 }       
236
237 /** Called when an item has moved.
238  *  @param item Item that has moved.
239  *  @param pre_change_parent_bounding_box The bounding box of the item before
240  *  the move, in its parent's coordinates.
241  */
242 void
243 Canvas::item_moved (Item* item, boost::optional<Rect> pre_change_parent_bounding_box)
244 {
245         if (pre_change_parent_bounding_box) {
246                 /* request a redraw of where the item used to be. The box has
247                  * to be in parent coordinate space since the bounding box of
248                  * an item does not change when moved. If we use
249                  * item->item_to_canvas() on the old bounding box, we will be
250                  * using the item's new position, and so will compute the wrong
251                  * invalidation area. If we use the parent (which has not
252                  * moved, then this will work.
253                  */
254
255                 queue_draw_item_area (item->parent(), pre_change_parent_bounding_box.get ());
256         }
257
258         boost::optional<Rect> post_change_bounding_box = item->bounding_box ();
259         if (post_change_bounding_box) {
260                 /* request a redraw of where the item now is */
261                 queue_draw_item_area (item, post_change_bounding_box.get ());
262         }
263 }
264
265 /** Request a redraw of a particular area in an item's coordinates.
266  *  @param item Item.
267  *  @param area Area to redraw in the item's coordinates.
268  */
269 void
270 Canvas::queue_draw_item_area (Item* item, Rect area)
271 {
272         ArdourCanvas::Rect canvas_area = item->item_to_canvas (area);
273         // cerr << "CANVAS Invalidate " << area << " TRANSLATE AS " << canvas_area << endl;
274         request_redraw (canvas_area);
275 }
276
277 /** Construct a GtkCanvas */
278 GtkCanvas::GtkCanvas ()
279         : _current_item (0)
280         , _grabbed_item (0)
281 {
282         /* these are the events we want to know about */
283         add_events (Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::POINTER_MOTION_MASK);
284 }
285
286 /** Handler for button presses on the canvas.
287  *  @param ev GDK event.
288  */
289 bool
290 GtkCanvas::button_handler (GdkEventButton* ev)
291 {
292         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas button %3 %1 %1\n", ev->x, ev->y, (ev->type == GDK_BUTTON_PRESS ? "press" : "release")));
293         /* The Duple that we are passing in here is in canvas coordinates */
294         return deliver_event (Duple (ev->x, ev->y), reinterpret_cast<GdkEvent*> (ev));
295 }
296
297 /** Handler for pointer motion events on the canvas.
298  *  @param ev GDK event.
299  *  @return true if the motion event was handled, otherwise false.
300  */
301 bool
302 GtkCanvas::motion_notify_handler (GdkEventMotion* ev)
303 {
304         if (_grabbed_item) {
305                 /* if we have a grabbed item, it gets just the motion event,
306                    since no enter/leave events can have happened.
307                 */
308                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 %2 (%3) was grabbed, send MOTION event there\n",
309                                                                        _grabbed_item, _grabbed_item->whatami(), _grabbed_item->name));
310                 return _grabbed_item->Event (reinterpret_cast<GdkEvent*> (ev));
311         }
312
313         Duple point (ev->x, ev->y);
314         
315         enter_leave_items (point);
316
317         /* Now deliver the motion event.  It may seem a little inefficient
318            to recompute the items under the event, but the enter notify/leave
319            events may have deleted canvas items so it is important to
320            recompute the list in deliver_event.
321         */
322         return deliver_event (point, reinterpret_cast<GdkEvent*> (ev));
323 }
324
325 void
326 GtkCanvas::enter_leave_items ()
327 {
328         int x;
329         int y;
330              
331         Glib::RefPtr<const Gdk::Window> pointer_window = Gdk::Display::get_default()->get_window_at_pointer (x, y);
332
333         if (pointer_window != get_window()) {
334                 return;
335         }
336
337         enter_leave_items (window_to_canvas (Duple (x, y)));
338 }
339                 
340 void
341 GtkCanvas::enter_leave_items (Duple const & point)
342 {
343         /* find the items at the new mouse position */
344         vector<Item const *> items;
345         _root.add_items_at_point (point, items);
346
347         Item const * new_item = items.empty() ? 0 : items.back ();
348
349         if (_current_item && _current_item != new_item) {
350                 /* leave event */
351                 GdkEventCrossing leave_event;
352                 leave_event.type = GDK_LEAVE_NOTIFY;
353                 leave_event.x = point.x;
354                 leave_event.y = point.y;
355                 _current_item->Event (reinterpret_cast<GdkEvent*> (&leave_event));
356         }
357
358         if (new_item && _current_item != new_item) {
359                 /* enter event */
360                 GdkEventCrossing enter_event;
361                 enter_event.type = GDK_ENTER_NOTIFY;
362                 enter_event.x = point.x;
363                 enter_event.y = point.y;
364                 new_item->Event (reinterpret_cast<GdkEvent*> (&enter_event));
365         }
366
367         _current_item = new_item;
368 }
369
370 /** Deliver an event to the appropriate item; either the grabbed item, or
371  *  one of the items underneath the event.
372  *  @param point Position that the event has occurred at, in canvas coordinates.
373  *  @param event The event.
374  */
375 bool
376 GtkCanvas::deliver_event (Duple point, GdkEvent* event)
377 {
378         if (_grabbed_item) {
379                 /* we have a grabbed item, so everything gets sent there */
380                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 %2 (%3) was grabbed, send event there\n",
381                                                                        _grabbed_item, _grabbed_item->whatami(), _grabbed_item->name));
382                 return _grabbed_item->Event (event);
383         }
384
385         /* find the items that exist at the event's position */
386         vector<Item const *> items;
387         _root.add_items_at_point (point, items);
388
389         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 possible items to deliver event to\n", items.size()));
390
391         /* run through the items under the event, from top to bottom, until one claims the event */
392         vector<Item const *>::const_reverse_iterator i = items.rbegin ();
393         while (i != items.rend()) {
394
395                 if ((*i)->ignore_events ()) {
396                         DEBUG_TRACE (
397                                 PBD::DEBUG::CanvasEvents,
398                                 string_compose ("canvas event ignored by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
399                                 );
400                         ++i;
401                         continue;
402                 }
403                 
404                 if ((*i)->Event (event)) {
405                         /* this item has just handled the event */
406                         DEBUG_TRACE (
407                                 PBD::DEBUG::CanvasEvents,
408                                 string_compose ("canvas event handled by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
409                                 );
410                         
411                         return true;
412                 }
413                 
414                 DEBUG_TRACE (
415                         PBD::DEBUG::CanvasEvents,
416                         string_compose ("canvas event left unhandled by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
417                         );
418                 
419                 ++i;
420         }
421
422         /* debugging */
423         if (PBD::debug_bits & PBD::DEBUG::CanvasEvents) {
424                 while (i != items.rend()) {
425                         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas event not seen by %1\n", (*i)->name.empty() ? "[unknown]" : (*i)->name));
426                         ++i;
427                 }
428         }
429         
430         return false;
431 }
432
433 /** Called when an item is being destroyed.
434  *  @param item Item being destroyed.
435  *  @param bounding_box Last known bounding box of the item.
436  */
437 void
438 GtkCanvas::item_going_away (Item* item, boost::optional<Rect> bounding_box)
439 {
440         if (bounding_box) {
441                 queue_draw_item_area (item, bounding_box.get ());
442         }
443         
444         if (_current_item == item) {
445                 _current_item = 0;
446         }
447
448         if (_grabbed_item == item) {
449                 _grabbed_item = 0;
450         }
451
452         enter_leave_items ();
453         
454 }
455
456 /** Handler for GDK expose events.
457  *  @param ev Event.
458  *  @return true if the event was handled.
459  */
460 bool
461 GtkCanvas::on_expose_event (GdkEventExpose* ev)
462 {
463
464         Cairo::RefPtr<Cairo::Context> c = get_window()->create_cairo_context ();
465         
466         /* WINDOW  CANVAS
467          * 0,0     _scroll_offset_x, _scroll_offset_y
468          */
469
470         /* render using canvas coordinates */
471
472         Rect canvas_area (ev->area.x, ev->area.y, ev->area.x + ev->area.width, ev->area.y + ev->area.height);
473         canvas_area  = canvas_area.translate (Duple (_scroll_offset_x, _scroll_offset_y));
474
475         /* things are going to render to the cairo surface with canvas
476          * coordinates:
477          *
478          *  an item at window/cairo 0,0 will have canvas_coords _scroll_offset_x,_scroll_offset_y
479          *
480          * let them render at their natural coordinates by using cairo_translate()
481          */
482
483         c->translate (-_scroll_offset_x, -_scroll_offset_y);
484
485         render (canvas_area, c);
486
487         return true;
488 }
489
490 /** @return Our Cairo context, or 0 if we don't have one */
491 Cairo::RefPtr<Cairo::Context>
492 GtkCanvas::context ()
493 {
494         Glib::RefPtr<Gdk::Window> w = get_window ();
495         if (!w) {
496                 return Cairo::RefPtr<Cairo::Context> ();
497         }
498
499         return w->create_cairo_context ();
500 }
501
502 /** Handler for GDK button press events.
503  *  @param ev Event.
504  *  @return true if the event was handled.
505  */
506 bool
507 GtkCanvas::on_button_press_event (GdkEventButton* ev)
508 {
509         /* translate event coordinates from window to canvas */
510
511         GdkEvent copy = *((GdkEvent*)ev);
512         Duple where = window_to_canvas (Duple (ev->x, ev->y));
513
514         copy.button.x = where.x;
515         copy.button.y = where.y;
516                                  
517         /* Coordinates in the event will be canvas coordinates, correctly adjusted
518            for scroll if this GtkCanvas is in a GtkCanvasViewport.
519         */
520         return button_handler ((GdkEventButton*) &copy);
521 }
522
523 /** Handler for GDK button release events.
524  *  @param ev Event.
525  *  @return true if the event was handled.
526  */
527 bool
528 GtkCanvas::on_button_release_event (GdkEventButton* ev)
529 {       
530         /* translate event coordinates from window to canvas */
531
532         GdkEvent copy = *((GdkEvent*)ev);
533         Duple where = window_to_canvas (Duple (ev->x, ev->y));
534
535         copy.button.x = where.x;
536         copy.button.y = where.y;
537
538         /* Coordinates in the event will be canvas coordinates, correctly adjusted
539            for scroll if this GtkCanvas is in a GtkCanvasViewport.
540         */
541         return button_handler ((GdkEventButton*) &copy);
542 }
543
544 /** Handler for GDK motion events.
545  *  @param ev Event.
546  *  @return true if the event was handled.
547  */
548 bool
549 GtkCanvas::on_motion_notify_event (GdkEventMotion* ev)
550 {
551         /* translate event coordinates from window to canvas */
552
553         GdkEvent copy = *((GdkEvent*)ev);
554         Duple where = window_to_canvas (Duple (ev->x, ev->y));
555
556         copy.motion.x = where.x;
557         copy.motion.y = where.y;
558
559         /* Coordinates in the event will be canvas coordinates, correctly adjusted
560            for scroll if this GtkCanvas is in a GtkCanvasViewport.
561         */
562         return motion_notify_handler ((GdkEventMotion*) &copy);
563 }
564
565 /** Called to request a redraw of our canvas.
566  *  @param area Area to redraw, in canvas coordinates.
567  */
568 void
569 GtkCanvas::request_redraw (Rect const & request)
570 {
571         Rect area = canvas_to_window (request);
572         // cerr << "Invalidate " << request << " TRANSLATE AS " << area << endl;
573         queue_draw_area (floor (area.x0), floor (area.y0), ceil (area.x1) - floor (area.x0), ceil (area.y1) - floor (area.y0));
574 }
575
576 /** Called to request that we try to get a particular size for ourselves.
577  *  @param size Size to request, in pixels.
578  */
579 void
580 GtkCanvas::request_size (Duple size)
581 {
582         Duple req = size;
583
584         if (req.x > INT_MAX) {
585                 req.x = INT_MAX;
586         }
587
588         if (req.y > INT_MAX) {
589                 req.y = INT_MAX;
590         }
591
592         set_size_request (req.x, req.y);
593 }
594
595 /** `Grab' an item, so that all events are sent to that item until it is `ungrabbed'.
596  *  This is typically used for dragging items around, so that they are grabbed during
597  *  the drag.
598  *  @param item Item to grab.
599  */
600 void
601 GtkCanvas::grab (Item* item)
602 {
603         /* XXX: should this be doing gdk_pointer_grab? */
604         _grabbed_item = item;
605 }
606
607 /** `Ungrab' any item that was previously grabbed */
608 void
609 GtkCanvas::ungrab ()
610 {
611         /* XXX: should this be doing gdk_pointer_ungrab? */
612         _grabbed_item = 0;
613 }
614
615 /** @return The visible area of the canvas, in canvas coordinates */
616 Rect
617 GtkCanvas::visible_area () const
618 {
619         Distance const xo = _scroll_offset_x;
620         Distance const yo = _scroll_offset_y;
621         return Rect (xo, yo, xo + get_allocation().get_width (), yo + get_allocation().get_height ());
622 }
623
624 /** Create a GtkCanvaSViewport.
625  *  @param hadj Adjustment to use for horizontal scrolling.
626  *  @param vadj Adjustment to use for vertica scrolling.
627  */
628 GtkCanvasViewport::GtkCanvasViewport (Gtk::Adjustment& hadj, Gtk::Adjustment& vadj)
629         : Alignment (0, 0, 1.0, 1.0)
630         , hadjustment (hadj)
631         , vadjustment (vadj)
632 {
633         add (_canvas);
634
635         hadj.signal_value_changed().connect (sigc::mem_fun (*this, &GtkCanvasViewport::scrolled));
636         vadj.signal_value_changed().connect (sigc::mem_fun (*this, &GtkCanvasViewport::scrolled));
637 }
638
639 void
640 GtkCanvasViewport::scrolled ()
641 {
642         _canvas.scroll_to (hadjustment.get_value(), vadjustment.get_value());
643         queue_draw ();
644 }
645
646 /** Handler for when GTK asks us what minimum size we want.
647  *  @param req Requsition to fill in.
648  */
649 void
650 GtkCanvasViewport::on_size_request (Gtk::Requisition* req)
651 {
652         /* force the canvas to size itself */
653         // _canvas.root()->bounding_box(); 
654
655         req->width = 16;
656         req->height = 16;
657 }
658