Merge branch 'master' into cairocanvas
[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 void
268 GtkCanvas::enter_leave_items (int state)
269 {
270         int x;
271         int y;
272
273         /* this version of ::enter_leave_items() is called after an item is
274          * added or removed, so we have no coordinates to work from as is the
275          * case with a motion event. Find out where the mouse is and use that.
276          */
277              
278         Glib::RefPtr<const Gdk::Window> pointer_window = Gdk::Display::get_default()->get_window_at_pointer (x, y);
279
280         if (pointer_window != get_window()) {
281                 return;
282         }
283
284         enter_leave_items (window_to_canvas (Duple (x, y)), state);
285 }
286                 
287 void
288 GtkCanvas::enter_leave_items (Duple const & point, int state)
289 {
290         /* we do not enter/leave items during a drag/grab */
291
292         if (_grabbed_item) {
293                 return;
294         }
295
296         GdkEventCrossing enter_event;
297         enter_event.type = GDK_ENTER_NOTIFY;
298         enter_event.window = get_window()->gobj();
299         enter_event.send_event = 0;
300         enter_event.subwindow = 0;
301         enter_event.mode = GDK_CROSSING_NORMAL;
302         enter_event.detail = GDK_NOTIFY_NONLINEAR;
303         enter_event.focus = FALSE;
304         enter_event.state = state;
305         enter_event.x = point.x;
306         enter_event.y = point.y;
307         enter_event.detail = GDK_NOTIFY_UNKNOWN;
308
309         GdkEventCrossing leave_event = enter_event;
310         leave_event.type = GDK_LEAVE_NOTIFY;
311
312         /* find the items at the given position */
313
314         vector<Item const *> items;
315         _root.add_items_at_point (point, items);
316
317         /* put all items at point that are event-sensitive and visible into within_items, and if this
318            is a new addition, also put them into newly_entered for later deliver of enter events.
319         */
320         
321         vector<Item const *>::const_iterator i;
322         vector<Item const *> newly_entered;
323         Item const * new_item;
324
325         for (i = items.begin(); i != items.end(); ++i) {
326
327                 new_item = *i;
328
329                 if (new_item->ignore_events() || !new_item->visible()) {
330                         continue;
331                 }
332
333                 pair<set<Item const *>::iterator,bool> res = within_items.insert (new_item);
334
335                 if (res.second) {
336                         newly_entered.push_back (new_item);
337                 }
338         }
339
340         /* for every item in "within_items", check that we are still within them. if not,
341            send a leave event, and remove them from "within_items"
342         */
343
344         for (set<Item const *>::const_iterator i = within_items.begin(); i != within_items.end(); ) {
345
346                 set<Item const *>::const_iterator tmp = i;
347                 ++tmp;
348
349                 new_item = *i;
350
351                 boost::optional<Rect> bbox = new_item->bounding_box();
352
353                 if (bbox) {
354                         if (!new_item->item_to_canvas (bbox.get()).contains (point)) {
355                                 leave_event.detail = GDK_NOTIFY_UNKNOWN;
356                                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("Leave %1 %2\n", new_item->whatami(), new_item->name));
357                                 (*i)->Event (reinterpret_cast<GdkEvent*> (&leave_event));
358                                 within_items.erase (i);
359                         }
360                 }
361
362                 i = tmp;
363         }
364         
365         /* for every item in "newly_entered", send an enter event (and propagate it up the
366            item tree until it is handled 
367         */
368
369         for (vector<Item const*>::const_iterator i = newly_entered.begin(); i != newly_entered.end(); ++i) {
370                 new_item = *i;
371
372                 new_item->Event (reinterpret_cast<GdkEvent*> (&enter_event));
373                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("Enter %1 %2\n", new_item->whatami(), new_item->name));
374         }
375
376 #if 1
377         cerr << "Within:\n";
378         for (set<Item const *>::const_iterator i = within_items.begin(); i != within_items.end(); ++i) {
379                 cerr << '\t' << (*i)->whatami() << '/' << (*i)->name << endl;
380         }
381         cerr << "----\n";
382 #endif
383 }
384
385 /** Deliver an event to the appropriate item; either the grabbed item, or
386  *  one of the items underneath the event.
387  *  @param point Position that the event has occurred at, in canvas coordinates.
388  *  @param event The event.
389  */
390 bool
391 GtkCanvas::deliver_event (Duple point, GdkEvent* event)
392 {
393         /* Point in in canvas coordinate space */
394
395         if (_grabbed_item) {
396                 /* we have a grabbed item, so everything gets sent there */
397                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 %2 (%3) was grabbed, send event there\n",
398                                                                        _grabbed_item, _grabbed_item->whatami(), _grabbed_item->name));
399                 return _grabbed_item->Event (event);
400         }
401
402         /* find the items that exist at the event's position */
403         vector<Item const *> items;
404         _root.add_items_at_point (point, items);
405
406         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 possible items to deliver event to\n", items.size()));
407
408         /* run through the items under the event, from top to bottom, until one claims the event */
409         vector<Item const *>::const_reverse_iterator i = items.rbegin ();
410         while (i != items.rend()) {
411
412                 if ((*i)->ignore_events ()) {
413                         DEBUG_TRACE (
414                                 PBD::DEBUG::CanvasEvents,
415                                 string_compose ("canvas event ignored by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
416                                 );
417                         ++i;
418                         continue;
419                 }
420                 
421                 if ((*i)->Event (event)) {
422                         /* this item has just handled the event */
423                         DEBUG_TRACE (
424                                 PBD::DEBUG::CanvasEvents,
425                                 string_compose ("canvas event handled by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
426                                 );
427                         
428                         return true;
429                 }
430                 
431                 DEBUG_TRACE (
432                         PBD::DEBUG::CanvasEvents,
433                         string_compose ("canvas event left unhandled by %1 %2\n", (*i)->whatami(), (*i)->name.empty() ? "[unknown]" : (*i)->name)
434                         );
435                 
436                 ++i;
437         }
438
439         /* debugging */
440         if (PBD::debug_bits & PBD::DEBUG::CanvasEvents) {
441                 while (i != items.rend()) {
442                         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas event not seen by %1\n", (*i)->name.empty() ? "[unknown]" : (*i)->name));
443                         ++i;
444                 }
445         }
446         
447         return false;
448 }
449
450 /** Called when an item is being destroyed.
451  *  @param item Item being destroyed.
452  *  @param bounding_box Last known bounding box of the item.
453  */
454 void
455 GtkCanvas::item_going_away (Item* item, boost::optional<Rect> bounding_box)
456 {
457         if (bounding_box) {
458                 queue_draw_item_area (item, bounding_box.get ());
459         }
460         
461         /* no need to send a leave event to this item, since it is going away 
462          */
463
464         within_items.erase (item);
465
466         if (_grabbed_item == item) {
467                 _grabbed_item = 0;
468         }
469
470         if (_focused_item == item) {
471                 _focused_item = 0;
472         }
473
474         enter_leave_items (0); // no mouse state
475         
476 }
477
478 /** Handler for GDK expose events.
479  *  @param ev Event.
480  *  @return true if the event was handled.
481  */
482 bool
483 GtkCanvas::on_expose_event (GdkEventExpose* ev)
484 {
485         Cairo::RefPtr<Cairo::Context> c = get_window()->create_cairo_context ();
486
487         render (Rect (ev->area.x, ev->area.y, ev->area.x + ev->area.width, ev->area.y + ev->area.height), c);
488
489         return true;
490 }
491
492 /** @return Our Cairo context, or 0 if we don't have one */
493 Cairo::RefPtr<Cairo::Context>
494 GtkCanvas::context ()
495 {
496         Glib::RefPtr<Gdk::Window> w = get_window ();
497         if (!w) {
498                 return Cairo::RefPtr<Cairo::Context> ();
499         }
500
501         return w->create_cairo_context ();
502 }
503
504 /** Handler for GDK button press events.
505  *  @param ev Event.
506  *  @return true if the event was handled.
507  */
508 bool
509 GtkCanvas::on_button_press_event (GdkEventButton* ev)
510 {
511         /* translate event coordinates from window to canvas */
512
513         GdkEvent copy = *((GdkEvent*)ev);
514         Duple where = window_to_canvas (Duple (ev->x, ev->y));
515
516         copy.button.x = where.x;
517         copy.button.y = where.y;
518         
519         /* Coordinates in the event will be canvas coordinates, correctly adjusted
520            for scroll if this GtkCanvas is in a GtkCanvasViewport.
521         */
522
523         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas button press @ %1, %2 => %3\n", ev->x, ev->y, where));
524         return deliver_event (where, reinterpret_cast<GdkEvent*>(&copy));
525 }
526
527 /** Handler for GDK button release events.
528  *  @param ev Event.
529  *  @return true if the event was handled.
530  */
531 bool
532 GtkCanvas::on_button_release_event (GdkEventButton* ev)
533 {       
534         /* translate event coordinates from window to canvas */
535
536         GdkEvent copy = *((GdkEvent*)ev);
537         Duple where = window_to_canvas (Duple (ev->x, ev->y));
538         
539         enter_leave_items (where, ev->state);
540
541         copy.button.x = where.x;
542         copy.button.y = where.y;
543
544         /* Coordinates in the event will be canvas coordinates, correctly adjusted
545            for scroll if this GtkCanvas is in a GtkCanvasViewport.
546         */
547
548         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas button release @ %1, %2 => %3\n", ev->x, ev->y, where));
549         return deliver_event (where, reinterpret_cast<GdkEvent*>(&copy));
550 }
551
552 /** Handler for GDK motion events.
553  *  @param ev Event.
554  *  @return true if the event was handled.
555  */
556 bool
557 GtkCanvas::on_motion_notify_event (GdkEventMotion* ev)
558 {
559         /* translate event coordinates from window to canvas */
560
561         GdkEvent copy = *((GdkEvent*)ev);
562         Duple point (ev->x, ev->y);
563         Duple where = window_to_canvas (point);
564
565         copy.motion.x = where.x;
566         copy.motion.y = where.y;
567
568         /* Coordinates in "copy" will be canvas coordinates, 
569         */
570
571         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas motion @ %1, %2\n", ev->x, ev->y));
572
573         if (_grabbed_item) {
574                 /* if we have a grabbed item, it gets just the motion event,
575                    since no enter/leave events can have happened.
576                 */
577                 DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("%1 %2 (%3) was grabbed, send MOTION event there\n",
578                                                                        _grabbed_item, _grabbed_item->whatami(), _grabbed_item->name));
579                 return _grabbed_item->Event (reinterpret_cast<GdkEvent*> (&copy));
580         }
581
582         enter_leave_items (where, ev->state);
583
584         /* Now deliver the motion event.  It may seem a little inefficient
585            to recompute the items under the event, but the enter notify/leave
586            events may have deleted canvas items so it is important to
587            recompute the list in deliver_event.
588         */
589
590         return deliver_event (point, reinterpret_cast<GdkEvent*> (&copy));
591 }
592
593 bool
594 GtkCanvas::on_enter_notify_event (GdkEventCrossing* ev)
595 {
596         Duple where = window_to_canvas (Duple (ev->x, ev->y));
597         enter_leave_items (where, ev->state);
598         return true;
599 }
600
601 bool
602 GtkCanvas::on_leave_notify_event (GdkEventCrossing* /*ev*/)
603 {
604         within_items.clear ();
605         return true;
606 }
607
608 /** Called to request a redraw of our canvas.
609  *  @param area Area to redraw, in canvas coordinates.
610  */
611 void
612 GtkCanvas::request_redraw (Rect const & request)
613 {
614         Rect area = canvas_to_window (request);
615         queue_draw_area (floor (area.x0), floor (area.y0), ceil (area.width()), ceil (area.height()));
616 }
617
618 /** Called to request that we try to get a particular size for ourselves.
619  *  @param size Size to request, in pixels.
620  */
621 void
622 GtkCanvas::request_size (Duple size)
623 {
624         Duple req = size;
625
626         if (req.x > INT_MAX) {
627                 req.x = INT_MAX;
628         }
629
630         if (req.y > INT_MAX) {
631                 req.y = INT_MAX;
632         }
633
634         set_size_request (req.x, req.y);
635 }
636
637 /** `Grab' an item, so that all events are sent to that item until it is `ungrabbed'.
638  *  This is typically used for dragging items around, so that they are grabbed during
639  *  the drag.
640  *  @param item Item to grab.
641  */
642 void
643 GtkCanvas::grab (Item* item)
644 {
645         /* XXX: should this be doing gdk_pointer_grab? */
646         _grabbed_item = item;
647 }
648
649
650 /** `Ungrab' any item that was previously grabbed */
651 void
652 GtkCanvas::ungrab ()
653 {
654         /* XXX: should this be doing gdk_pointer_ungrab? */
655         _grabbed_item = 0;
656 }
657
658 /** Set keyboard focus on an item, so that all keyboard events are sent to that item until the focus
659  *  moves elsewhere.
660  *  @param item Item to grab.
661  */
662 void
663 GtkCanvas::focus (Item* item)
664 {
665         _focused_item = item;
666 }
667
668 void
669 GtkCanvas::unfocus (Item* item)
670 {
671         if (item == _focused_item) {
672                 _focused_item = 0;
673         }
674 }
675
676 /** @return The visible area of the canvas, in canvas coordinates */
677 Rect
678 GtkCanvas::visible_area () const
679 {
680         Distance const xo = _scroll_offset_x;
681         Distance const yo = _scroll_offset_y;
682         return Rect (xo, yo, xo + get_allocation().get_width (), yo + get_allocation().get_height ());
683 }
684
685 /** Create a GtkCanvaSViewport.
686  *  @param hadj Adjustment to use for horizontal scrolling.
687  *  @param vadj Adjustment to use for vertica scrolling.
688  */
689 GtkCanvasViewport::GtkCanvasViewport (Gtk::Adjustment& hadj, Gtk::Adjustment& vadj)
690         : Alignment (0, 0, 1.0, 1.0)
691         , hadjustment (hadj)
692         , vadjustment (vadj)
693 {
694         add (_canvas);
695
696         hadj.signal_value_changed().connect (sigc::mem_fun (*this, &GtkCanvasViewport::scrolled));
697         vadj.signal_value_changed().connect (sigc::mem_fun (*this, &GtkCanvasViewport::scrolled));
698 }
699
700 void
701 GtkCanvasViewport::scrolled ()
702 {
703         _canvas.scroll_to (hadjustment.get_value(), vadjustment.get_value());
704         queue_draw ();
705 }
706
707 /** Handler for when GTK asks us what minimum size we want.
708  *  @param req Requsition to fill in.
709  */
710 void
711 GtkCanvasViewport::on_size_request (Gtk::Requisition* req)
712 {
713         /* force the canvas to size itself */
714         // _canvas.root()->bounding_box(); 
715
716         req->width = 16;
717         req->height = 16;
718 }
719