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