828d277b2fe16d3200f78078100d29749336228f
[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 "pbd/xml++.h"
28 #include "pbd/compose.h"
29 #include "canvas/canvas.h"
30 #include "canvas/debug.h"
31
32 using namespace std;
33 using namespace ArdourCanvas;
34
35 /** Construct a new Canvas */
36 Canvas::Canvas ()
37         : _root (this)
38         , _log_renders (true)
39 {
40         set_epoch ();
41 }
42
43 /** Construct a new Canvas from an XML tree
44  *  @param tree XML Tree.
45  */
46 Canvas::Canvas (XMLTree const * tree)
47         : _root (this)
48         , _log_renders (true)
49 {
50         set_epoch ();
51         
52         /* XXX: little bit hacky */
53         _root.set_state (tree->root()->child ("Group"));
54
55         XMLNodeList const & children = tree->root()->children ();
56         for (XMLNodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
57                 if ((*i)->name() == ("Render")) {
58                         _renders.push_back (
59                                 Rect (
60                                         atof ((*i)->property ("x0")->value().c_str()),
61                                         atof ((*i)->property ("y0")->value().c_str()),
62                                         atof ((*i)->property ("x1")->value().c_str()),
63                                         atof ((*i)->property ("x1")->value().c_str())
64                                         )
65                                 );
66                 }
67         }
68 }
69
70 /** Render an area of the canvas.
71  *  @param area Area in canvas coordinates.
72  *  @param context Cairo context to render to.
73  */
74 void
75 Canvas::render (Rect const & area, Cairo::RefPtr<Cairo::Context> const & context) const
76 {
77         checkpoint ("render", "-> render");
78         render_count = 0;
79         
80         context->save ();
81
82         /* clip to the requested area */
83         context->rectangle (area.x0, area.y0, area.width(), area.height());
84         context->clip ();
85
86         boost::optional<Rect> root_bbox = _root.bounding_box();
87         if (!root_bbox) {
88                 /* the root has no bounding box, so there's nothing to render */
89                 context->restore ();
90                 return;
91         }
92
93         boost::optional<Rect> draw = root_bbox.get().intersection (area);
94         if (draw) {
95                 /* there's a common area between the root and the requested
96                    area, so render it.
97                 */
98                 _root.render (*draw, context);
99         }
100
101         if (_log_renders) {
102                 _renders.push_back (area);
103         }
104
105         context->restore ();
106
107         cout << "Rendered " << render_count << "\n";
108         checkpoint ("render", "<- render");
109 }
110
111 /** Called when an item has been shown or hidden.
112  *  @param item Item that has been shown or hidden.
113  */
114 void
115 Canvas::item_shown_or_hidden (Item* item)
116 {
117         boost::optional<Rect> bbox = item->bounding_box ();
118         if (bbox) {
119                 queue_draw_item_area (item, bbox.get ());
120         }
121 }
122
123 /** Called when an item has changed, but not moved.
124  *  @param item Item that has changed.
125  *  @param pre_change_bounding_box The bounding box of item before the change,
126  *  in the item's coordinates.
127  */
128 void
129 Canvas::item_changed (Item* item, boost::optional<Rect> pre_change_bounding_box)
130 {
131         if (pre_change_bounding_box) {
132                 /* request a redraw of the item's old bounding box */
133                 queue_draw_item_area (item, pre_change_bounding_box.get ());
134         }
135
136         boost::optional<Rect> post_change_bounding_box = item->bounding_box ();
137         if (post_change_bounding_box) {
138                 /* request a redraw of the item's new bounding box */
139                 queue_draw_item_area (item, post_change_bounding_box.get ());
140         }
141 }
142
143 /** Called when an item has moved.
144  *  @param item Item that has moved.
145  *  @param pre_change_parent_bounding_box The bounding box of the item before
146  *  the move, in its parent's coordinates.
147  */
148 void
149 Canvas::item_moved (Item* item, boost::optional<Rect> pre_change_parent_bounding_box)
150 {
151         if (pre_change_parent_bounding_box) {
152                 /* request a redraw of where the item used to be; we have to use the
153                    parent's coordinates here as item bounding boxes do not change
154                    when the item moves.
155                 */
156                 queue_draw_item_area (item->parent(), pre_change_parent_bounding_box.get ());
157         }
158
159         boost::optional<Rect> post_change_bounding_box = item->bounding_box ();
160         if (post_change_bounding_box) {
161                 /* request a redraw of where the item now is */
162                 queue_draw_item_area (item, post_change_bounding_box.get ());
163         }
164 }
165
166 /** Request a redraw of a particular area in an item's coordinates.
167  *  @param item Item.
168  *  @param area Area to redraw in the item's coordinates.
169  */
170 void
171 Canvas::queue_draw_item_area (Item* item, Rect area)
172 {
173         request_redraw (item->item_to_canvas (area));
174 }
175
176 /** @return An XML description of the canvas and its objects */
177 XMLTree *
178 Canvas::get_state () const
179 {
180         XMLTree* tree = new XMLTree ();
181         XMLNode* node = new XMLNode ("Canvas");
182         node->add_child_nocopy (*_root.get_state ());
183
184         for (list<Rect>::const_iterator i = _renders.begin(); i != _renders.end(); ++i) {
185                 XMLNode* render = new XMLNode ("Render");
186                 render->add_property ("x0", string_compose ("%1", i->x0));
187                 render->add_property ("y0", string_compose ("%1", i->y0));
188                 render->add_property ("x1", string_compose ("%1", i->x1));
189                 render->add_property ("y1", string_compose ("%1", i->y1));
190                 node->add_child_nocopy (*render);
191         }
192
193         tree->set_root (node);
194         return tree;
195 }
196
197 /** Construct a GtkCanvas */
198 GtkCanvas::GtkCanvas ()
199         : _current_item (0)
200         , _grabbed_item (0)
201 {
202         /* these are the events we want to know about */
203         add_events (Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::POINTER_MOTION_MASK);
204 }
205
206 /** Construct a GtkCanvas from an XML tree.
207  *  @param tree XML Tree.
208  */
209 GtkCanvas::GtkCanvas (XMLTree const * tree)
210         : Canvas (tree)
211         , _current_item (0)
212         , _grabbed_item (0)
213 {
214         /* these are the events we want to know about */
215         add_events (Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK | Gdk::POINTER_MOTION_MASK);
216 }
217
218 /** Handler for button presses on the canvas.
219  *  @param ev GDK event.
220  */
221 bool
222 GtkCanvas::button_handler (GdkEventButton* ev)
223 {
224         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas button press %1 %1\n", ev->x, ev->y));
225         /* The Duple that we are passing in here is in canvas coordinates */
226         return deliver_event (Duple (ev->x, ev->y), reinterpret_cast<GdkEvent*> (ev));
227 }
228
229 /** Handler for pointer motion events on the canvas.
230  *  @param ev GDK event.
231  *  @return true if the motion event was handled, otherwise false.
232  */
233 bool
234 GtkCanvas::motion_notify_handler (GdkEventMotion* ev)
235 {
236         if (_grabbed_item) {
237                 /* if we have a grabbed item, it gets just the motion event,
238                    since no enter/leave events can have happened.
239                 */
240                 return _grabbed_item->Event (reinterpret_cast<GdkEvent*> (ev));
241         }
242
243         /* This is in canvas coordinates */
244         Duple point (ev->x, ev->y);
245
246         /* find the items at the new mouse position */
247         vector<Item const *> items;
248         _root.add_items_at_point (point, items);
249
250         Item const * new_item = items.empty() ? 0 : items.back ();
251
252         if (_current_item && _current_item != new_item) {
253                 /* leave event */
254                 GdkEventCrossing leave_event;
255                 leave_event.type = GDK_LEAVE_NOTIFY;
256                 leave_event.x = ev->x;
257                 leave_event.y = ev->y;
258                 _current_item->Event (reinterpret_cast<GdkEvent*> (&leave_event));
259         }
260
261         if (new_item && _current_item != new_item) {
262                 /* enter event */
263                 GdkEventCrossing enter_event;
264                 enter_event.type = GDK_ENTER_NOTIFY;
265                 enter_event.x = ev->x;
266                 enter_event.y = ev->y;
267                 new_item->Event (reinterpret_cast<GdkEvent*> (&enter_event));
268         }
269
270         _current_item = new_item;
271
272         /* Now deliver the motion event.  It may seem a little inefficient
273            to recompute the items under the event, but the enter notify/leave
274            events may have deleted canvas items so it is important to
275            recompute the list in deliver_event.
276         */
277         return deliver_event (point, reinterpret_cast<GdkEvent*> (ev));
278 }
279
280 /** Deliver an event to the appropriate item; either the grabbed item, or
281  *  one of the items underneath the event.
282  *  @param point Position that the event has occurred at, in canvas coordinates.
283  *  @param event The event.
284  */
285 bool
286 GtkCanvas::deliver_event (Duple point, GdkEvent* event)
287 {
288         if (_grabbed_item) {
289                 /* we have a grabbed item, so everything gets sent there */
290                 return _grabbed_item->Event (event);
291         }
292
293         /* find the items that exist at the event's position */
294         vector<Item const *> items;
295         _root.add_items_at_point (point, items);
296
297         /* run through the items under the event, from top to bottom, until one claims the event */
298         vector<Item const *>::const_reverse_iterator i = items.rbegin ();
299         while (i != items.rend()) {
300
301                 if ((*i)->ignore_events ()) {
302                         ++i;
303                         continue;
304                 }
305                 
306                 if ((*i)->Event (event)) {
307                         /* this item has just handled the event */
308                         DEBUG_TRACE (
309                                 PBD::DEBUG::CanvasEvents,
310                                 string_compose ("canvas event handled by %1\n", (*i)->name.empty() ? "[unknown]" : (*i)->name)
311                                 );
312                         
313                         return true;
314                 }
315                 
316                 DEBUG_TRACE (
317                         PBD::DEBUG::CanvasEvents,
318                         string_compose ("canvas event ignored by %1\n", (*i)->name.empty() ? "[unknown]" : (*i)->name)
319                         );
320                 
321                 ++i;
322         }
323
324         /* debugging */
325         if (PBD::debug_bits & PBD::DEBUG::CanvasEvents) {
326                 while (i != items.rend()) {
327                         DEBUG_TRACE (PBD::DEBUG::CanvasEvents, string_compose ("canvas event not seen by %1\n", (*i)->name.empty() ? "[unknown]" : (*i)->name));
328                         ++i;
329                 }
330         }
331         
332         return false;
333 }
334
335 /** Called when an item is being destroyed.
336  *  @param item Item being destroyed.
337  *  @param bounding_box Last known bounding box of the item.
338  */
339 void
340 GtkCanvas::item_going_away (Item* item, boost::optional<Rect> bounding_box)
341 {
342         if (bounding_box) {
343                 queue_draw_item_area (item, bounding_box.get ());
344         }
345         
346         if (_current_item == item) {
347                 _current_item = 0;
348         }
349
350         if (_grabbed_item == item) {
351                 _grabbed_item = 0;
352         }
353 }
354
355 /** Construct an ImageCanvas.
356  *  @param size Size in pixels.
357  */
358 ImageCanvas::ImageCanvas (Duple size)
359         : _surface (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, size.x, size.y))
360 {
361         _context = Cairo::Context::create (_surface);
362 }
363
364 /** Construct an ImageCanvas from an XML tree.
365  *  @param tree XML Tree.
366  *  @param size Size in pixels.
367  */
368 ImageCanvas::ImageCanvas (XMLTree const * tree, Duple size)
369         : Canvas (tree)
370         , _surface (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, size.x, size.y))
371 {
372         _context = Cairo::Context::create (_surface);
373 }
374
375 /** Render the canvas to our pixbuf.
376  *  @param area Area to render, in canvas coordinates.
377  */
378 void
379 ImageCanvas::render_to_image (Rect const & area) const
380 {
381         render (area, _context);
382 }
383
384 /** Write our pixbuf to a PNG file.
385  *  @param f PNG file name.
386  */
387 void
388 ImageCanvas::write_to_png (string const & f)
389 {
390         assert (_surface);
391         _surface->write_to_png (f);
392 }
393
394 /** @return Our Cairo context */
395 Cairo::RefPtr<Cairo::Context>
396 ImageCanvas::context ()
397 {
398         return _context;
399 }
400
401 /** Handler for GDK expose events.
402  *  @param ev Event.
403  *  @return true if the event was handled.
404  */
405 bool
406 GtkCanvas::on_expose_event (GdkEventExpose* ev)
407 {
408         Cairo::RefPtr<Cairo::Context> c = get_window()->create_cairo_context ();
409         render (Rect (ev->area.x, ev->area.y, ev->area.x + ev->area.width, ev->area.y + ev->area.height), c);
410         return true;
411 }
412
413 /** @return Our Cairo context, or 0 if we don't have one */
414 Cairo::RefPtr<Cairo::Context>
415 GtkCanvas::context ()
416 {
417         Glib::RefPtr<Gdk::Window> w = get_window ();
418         if (!w) {
419                 return Cairo::RefPtr<Cairo::Context> ();
420         }
421
422         return w->create_cairo_context ();
423 }
424
425 /** Handler for GDK button press events.
426  *  @param ev Event.
427  *  @return true if the event was handled.
428  */
429 bool
430 GtkCanvas::on_button_press_event (GdkEventButton* ev)
431 {
432         /* Coordinates in the event will be canvas coordinates, correctly adjusted
433            for scroll if this GtkCanvas is in a GtkCanvasViewport.
434         */
435         return button_handler (ev);
436 }
437
438 /** Handler for GDK button release events.
439  *  @param ev Event.
440  *  @return true if the event was handled.
441  */
442 bool
443 GtkCanvas::on_button_release_event (GdkEventButton* ev)
444 {
445         /* Coordinates in the event will be canvas coordinates, correctly adjusted
446            for scroll if this GtkCanvas is in a GtkCanvasViewport.
447         */
448         return button_handler (ev);
449 }
450
451 /** Handler for GDK motion events.
452  *  @param ev Event.
453  *  @return true if the event was handled.
454  */
455 bool
456 GtkCanvas::on_motion_notify_event (GdkEventMotion* ev)
457 {
458         /* Coordinates in the event will be canvas coordinates, correctly adjusted
459            for scroll if this GtkCanvas is in a GtkCanvasViewport.
460         */
461         return motion_notify_handler (ev);
462 }
463
464 /** Called to request a redraw of our canvas.
465  *  @param area Area to redraw, in canvas coordinates.
466  */
467 void
468 GtkCanvas::request_redraw (Rect const & area)
469 {
470         queue_draw_area (floor (area.x0), floor (area.y0), ceil (area.x1) - floor (area.x0), ceil (area.y1) - floor (area.y0));
471 }
472
473 /** Called to request that we try to get a particular size for ourselves.
474  *  @param size Size to request, in pixels.
475  */
476 void
477 GtkCanvas::request_size (Duple size)
478 {
479         Duple req = size;
480
481         if (req.x > INT_MAX) {
482                 req.x = INT_MAX;
483         }
484
485         if (req.y > INT_MAX) {
486                 req.y = INT_MAX;
487         }
488         
489         set_size_request (req.x, req.y);
490 }
491
492 /** `Grab' an item, so that all events are sent to that item until it is `ungrabbed'.
493  *  This is typically used for dragging items around, so that they are grabbed during
494  *  the drag.
495  *  @param item Item to grab.
496  */
497 void
498 GtkCanvas::grab (Item* item)
499 {
500         /* XXX: should this be doing gdk_pointer_grab? */
501         _grabbed_item = item;
502 }
503
504 /** `Ungrab' any item that was previously grabbed */
505 void
506 GtkCanvas::ungrab ()
507 {
508         /* XXX: should this be doing gdk_pointer_ungrab? */
509         _grabbed_item = 0;
510 }
511
512 /** Create a GtkCanvaSViewport.
513  *  @param hadj Adjustment to use for horizontal scrolling.
514  *  @param vadj Adjustment to use for vertica scrolling.
515  */
516 GtkCanvasViewport::GtkCanvasViewport (Gtk::Adjustment& hadj, Gtk::Adjustment& vadj)
517         : Viewport (hadj, vadj)
518 {
519         add (_canvas);
520 }
521
522 /** Handler for when GTK asks us what minimum size we want.
523  *  @param req Requsition to fill in.
524  */
525 void
526 GtkCanvasViewport::on_size_request (Gtk::Requisition* req)
527 {
528         req->width = 16;
529         req->height = 16;
530 }
531
532 /** Convert window coordinates to canvas coordinates by taking into account
533  *  where we are scrolled to.
534  *  @param wx Window x.
535  *  @param wy Window y.
536  *  @param cx Filled in with canvas x.
537  *  @param cy Filled in with canvas y.
538  */
539 void
540 GtkCanvasViewport::window_to_canvas (int wx, int wy, Coord& cx, Coord& cy) const
541 {
542         cx = wx + get_hadjustment()->get_value ();
543         cy = wy + get_vadjustment()->get_value ();
544 }
545
546 /** @return The visible area of the canvas, in canvas coordinates */
547 Rect
548 GtkCanvasViewport::visible_area () const
549 {
550         Distance const xo = get_hadjustment()->get_value ();
551         Distance const yo = get_vadjustment()->get_value ();
552         return Rect (xo, yo, xo + get_allocation().get_width (), yo + get_allocation().get_height ());
553 }