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