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