Code

smooth panning: suppress painting for so long as scrolling events come one after...
[inkscape.git] / src / display / sp-canvas.cpp
1 #define __SP_CANVAS_C__
3 /** \file
4  * Port of GnomeCanvas for Inkscape needs
5  *
6  * Authors:
7  *   Federico Mena <federico@nuclecu.unam.mx>
8  *   Raph Levien <raph@gimp.org>
9  *   Lauris Kaplinski <lauris@kaplinski.com>
10  *   fred
11  *   bbyak
12  *
13  * Copyright (C) 1998 The Free Software Foundation
14  * Copyright (C) 2002-2006 authors
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <libnr/nr-pixblock.h>
25 #include <gtk/gtkmain.h>
26 #include <gtk/gtksignal.h>
28 #include <gtkmm.h>
30 #include <helper/sp-marshal.h>
31 #include <display/sp-canvas.h>
32 #include "display-forward.h"
33 #include <libnr/nr-matrix-fns.h>
34 #include <libnr/nr-matrix-ops.h>
35 #include <libnr/nr-convex-hull.h>
36 #include "prefs-utils.h"
38 // Tiles are a way to minimize the number of redraws, eliminating too small redraws. 
39 // The canvas stores a 2D array of ints, each representing a TILE_SIZExTILE_SIZE pixels tile.
40 // If any part of it is dirtied, the entire tile is dirtied (its int is nonzero) and repainted.
41 #define TILE_SIZE 32
43 enum {
44         RENDERMODE_NORMAL,
45         RENDERMODE_NOAA,
46         RENDERMODE_OUTLINE
47 };
49 const gint sp_canvas_update_priority = G_PRIORITY_HIGH_IDLE;
51 #define SP_CANVAS_WINDOW(c) (((GtkWidget *) (c))->window)
53 enum {
54     SP_CANVAS_ITEM_VISIBLE = 1 << 7,
55     SP_CANVAS_ITEM_NEED_UPDATE = 1 << 8,
56     SP_CANVAS_ITEM_NEED_AFFINE = 1 << 9
57 };
59 /**
60  * A group of Items.
61  */
62 struct SPCanvasGroup {
63     SPCanvasItem item;
65     GList *items, *last;
66 };
68 /**
69  * The SPCanvasGroup vtable.
70  */
71 struct SPCanvasGroupClass {
72     SPCanvasItemClass parent_class;
73 };
75 /**
76  * The SPCanvas vtable.
77  */
78 struct SPCanvasClass {
79     GtkWidgetClass parent_class;
80 };
82 static void group_add (SPCanvasGroup *group, SPCanvasItem *item);
83 static void group_remove (SPCanvasGroup *group, SPCanvasItem *item);
85 /* SPCanvasItem */
87 enum {ITEM_EVENT, ITEM_LAST_SIGNAL};
90 static void sp_canvas_request_update (SPCanvas *canvas);
92 static void sp_canvas_item_class_init (SPCanvasItemClass *klass);
93 static void sp_canvas_item_init (SPCanvasItem *item);
94 static void sp_canvas_item_dispose (GObject *object);
95 static void sp_canvas_item_construct (SPCanvasItem *item, SPCanvasGroup *parent, const gchar *first_arg_name, va_list args);
97 static int emit_event (SPCanvas *canvas, GdkEvent *event);
99 static guint item_signals[ITEM_LAST_SIGNAL] = { 0 };
101 static GtkObjectClass *item_parent_class;
103 /**
104  * Registers the SPCanvasItem class with Glib and returns its type number.
105  */
106 GType
107 sp_canvas_item_get_type (void)
109     static GType type = 0;
110     if (!type) {
111         static const GTypeInfo info = {
112             sizeof (SPCanvasItemClass),
113             NULL, NULL,
114             (GClassInitFunc) sp_canvas_item_class_init,
115             NULL, NULL,
116             sizeof (SPCanvasItem),
117             0,
118             (GInstanceInitFunc) sp_canvas_item_init,
119             NULL
120         };
121         type = g_type_register_static (GTK_TYPE_OBJECT, "SPCanvasItem", &info, (GTypeFlags)0);
122     }
124     return type;
127 /**
128  * Initializes the SPCanvasItem vtable and the "event" signal.
129  */
130 static void
131 sp_canvas_item_class_init (SPCanvasItemClass *klass)
133     GObjectClass *object_class = (GObjectClass *) klass;
135     /* fixme: Derive from GObject */
136     item_parent_class = (GtkObjectClass*)gtk_type_class (GTK_TYPE_OBJECT);
138     item_signals[ITEM_EVENT] = g_signal_new ("event",
139                                              G_TYPE_FROM_CLASS (klass),
140                                              G_SIGNAL_RUN_LAST,
141                                              G_STRUCT_OFFSET (SPCanvasItemClass, event),
142                                              NULL, NULL,
143                                              sp_marshal_BOOLEAN__POINTER,
144                                              G_TYPE_BOOLEAN, 1,
145                                              GDK_TYPE_EVENT);
147     object_class->dispose = sp_canvas_item_dispose;
150 /**
151  * Callback for initialization of SPCanvasItem.
152  */
153 static void
154 sp_canvas_item_init (SPCanvasItem *item)
156     item->flags |= SP_CANVAS_ITEM_VISIBLE;
157     item->xform = NR::Matrix(NR::identity());
160 /**
161  * Constructs new SPCanvasItem on SPCanvasGroup.
162  */
163 SPCanvasItem *
164 sp_canvas_item_new (SPCanvasGroup *parent, GtkType type, const gchar *first_arg_name, ...)
166     va_list args;
168     g_return_val_if_fail (parent != NULL, NULL);
169     g_return_val_if_fail (SP_IS_CANVAS_GROUP (parent), NULL);
170     g_return_val_if_fail (gtk_type_is_a (type, sp_canvas_item_get_type ()), NULL);
172     SPCanvasItem *item = SP_CANVAS_ITEM (gtk_type_new (type));
174     va_start (args, first_arg_name);
175     sp_canvas_item_construct (item, parent, first_arg_name, args);
176     va_end (args);
178     return item;
181 /**
182  * Sets up the newly created SPCanvasItem.
183  *
184  * We make it static for encapsulation reasons since it was nowhere used.
185  */
186 static void
187 sp_canvas_item_construct (SPCanvasItem *item, SPCanvasGroup *parent, const gchar *first_arg_name, va_list args)
189     g_return_if_fail (SP_IS_CANVAS_GROUP (parent));
190     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
192     item->parent = SP_CANVAS_ITEM (parent);
193     item->canvas = item->parent->canvas;
195     g_object_set_valist (G_OBJECT (item), first_arg_name, args);
197     group_add (SP_CANVAS_GROUP (item->parent), item);
199     sp_canvas_item_request_update (item);
200     sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
201     item->canvas->need_repick = TRUE;
204 /**
205  * Helper function that requests redraw only if item's visible flag is set.
206  */
207 static void
208 redraw_if_visible (SPCanvasItem *item)
210     if (item->flags & SP_CANVAS_ITEM_VISIBLE) {
211         sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
212     }
215 /**
216  * Callback that removes item from all referers and destroys it.
217  */
218 static void
219 sp_canvas_item_dispose (GObject *object)
221     SPCanvasItem *item = SP_CANVAS_ITEM (object);
223     redraw_if_visible (item);
224     item->flags &= ~SP_CANVAS_ITEM_VISIBLE;
226     if (item == item->canvas->current_item) {
227         item->canvas->current_item = NULL;
228         item->canvas->need_repick = TRUE;
229     }
231     if (item == item->canvas->new_current_item) {
232         item->canvas->new_current_item = NULL;
233         item->canvas->need_repick = TRUE;
234     }
236     if (item == item->canvas->grabbed_item) {
237         item->canvas->grabbed_item = NULL;
238         gdk_pointer_ungrab (GDK_CURRENT_TIME);
239     }
241     if (item == item->canvas->focused_item)
242         item->canvas->focused_item = NULL;
244     if (item->parent) {
245         group_remove (SP_CANVAS_GROUP (item->parent), item);
246     }
248     G_OBJECT_CLASS (item_parent_class)->dispose (object);
251 /**
252  * Helper function to update item and its children.
253  *
254  * NB! affine is parent2canvas.
255  */
256 static void
257 sp_canvas_item_invoke_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags)
259     /* Apply the child item's transform */
260     NR::Matrix child_affine = item->xform * affine;
262     /* apply object flags to child flags */
263     int child_flags = flags & ~SP_CANVAS_UPDATE_REQUESTED;
265     if (item->flags & SP_CANVAS_ITEM_NEED_UPDATE)
266         child_flags |= SP_CANVAS_UPDATE_REQUESTED;
268     if (item->flags & SP_CANVAS_ITEM_NEED_AFFINE)
269         child_flags |= SP_CANVAS_UPDATE_AFFINE;
271     if (child_flags & (SP_CANVAS_UPDATE_REQUESTED | SP_CANVAS_UPDATE_AFFINE)) {
272         if (SP_CANVAS_ITEM_GET_CLASS (item)->update)
273             SP_CANVAS_ITEM_GET_CLASS (item)->update (item, child_affine, child_flags);
274     }
276     GTK_OBJECT_UNSET_FLAGS (item, SP_CANVAS_ITEM_NEED_UPDATE);
277     GTK_OBJECT_UNSET_FLAGS (item, SP_CANVAS_ITEM_NEED_AFFINE);
280 /** 
281  * Helper function to invoke the point method of the item.  
282  *
283  * The argument x, y should be in the parent's item-relative coordinate 
284  * system.  This routine applies the inverse of the item's transform, 
285  * maintaining the affine invariant.
286  */
287 static double
288 sp_canvas_item_invoke_point (SPCanvasItem *item, NR::Point p, SPCanvasItem **actual_item)
290     if (SP_CANVAS_ITEM_GET_CLASS (item)->point)
291         return SP_CANVAS_ITEM_GET_CLASS (item)->point (item, p, actual_item);
293     return NR_HUGE;
296 /**
297  * Makes the item's affine transformation matrix be equal to the specified
298  * matrix.
299  * 
300  * @item: A canvas item.
301  * @affine: An affine transformation matrix.
302  */
303 void
304 sp_canvas_item_affine_absolute (SPCanvasItem *item, NR::Matrix const& affine)
306     item->xform = affine;
308     if (!(item->flags & SP_CANVAS_ITEM_NEED_AFFINE)) {
309         item->flags |= SP_CANVAS_ITEM_NEED_AFFINE;
310         if (item->parent != NULL) {
311             sp_canvas_item_request_update (item->parent);
312         } else {
313             sp_canvas_request_update (item->canvas);
314         }
315     }
317     item->canvas->need_repick = TRUE;
320 /**
321  * Convenience function to reorder items in a group's child list.  
322  *
323  * This puts the specified link after the "before" link.
324  */
325 static void
326 put_item_after (GList *link, GList *before)
328     if (link == before)
329         return;
331     SPCanvasGroup *parent = SP_CANVAS_GROUP (SP_CANVAS_ITEM (link->data)->parent);
333     if (before == NULL) {
334         if (link == parent->items) return;
336         link->prev->next = link->next;
338         if (link->next) {
339             link->next->prev = link->prev;
340         } else {
341             parent->last = link->prev;
342         }
344         link->prev = before;
345         link->next = parent->items;
346         link->next->prev = link;
347         parent->items = link;
348     } else {
349         if ((link == parent->last) && (before == parent->last->prev))
350             return;
352         if (link->next)
353             link->next->prev = link->prev;
355         if (link->prev)
356             link->prev->next = link->next;
357         else {
358             parent->items = link->next;
359             parent->items->prev = NULL;
360         }
362         link->prev = before;
363         link->next = before->next;
365         link->prev->next = link;
367         if (link->next)
368             link->next->prev = link;
369         else
370             parent->last = link;
371     }
375 /**
376  * Raises the item in its parent's stack by the specified number of positions.
377  * 
378  * \param item A canvas item.
379  * \param positions Number of steps to raise the item.
380  *
381  * If the number of positions is greater than the distance to the top of the
382  * stack, then the item is put at the top.
383  */
384 void
385 sp_canvas_item_raise (SPCanvasItem *item, int positions)
387     g_return_if_fail (item != NULL);
388     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
389     g_return_if_fail (positions >= 0);
391     if (!item->parent || positions == 0)
392         return;
394     SPCanvasGroup *parent = SP_CANVAS_GROUP (item->parent);
395     GList *link = g_list_find (parent->items, item);
396     g_assert (link != NULL);
398     GList *before;
399     for (before = link; positions && before; positions--)
400         before = before->next;
402     if (!before)
403         before = parent->last;
405     put_item_after (link, before);
407     redraw_if_visible (item);
408     item->canvas->need_repick = TRUE;
412 /**
413  * Lowers the item in its parent's stack by the specified number of positions.
414  *
415  * \param item A canvas item.
416  * \param positions Number of steps to lower the item.
417  *
418  * If the number of positions is greater than the distance to the bottom of the
419  * stack, then the item is put at the bottom.
420  **/
421 void
422 sp_canvas_item_lower (SPCanvasItem *item, int positions)
424     g_return_if_fail (item != NULL);
425     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
426     g_return_if_fail (positions >= 1);
428     if (!item->parent || positions == 0)
429         return;
431     SPCanvasGroup *parent = SP_CANVAS_GROUP (item->parent);
432     GList *link = g_list_find (parent->items, item);
433     g_assert (link != NULL);
435     GList *before;
436     if (link->prev)
437         for (before = link->prev; positions && before; positions--)
438             before = before->prev;
439     else
440         before = NULL;
442     put_item_after (link, before);
444     redraw_if_visible (item);
445     item->canvas->need_repick = TRUE;
448 /**
449  * Sets visible flag on item and requests a redraw.
450  */
451 void
452 sp_canvas_item_show (SPCanvasItem *item)
454     g_return_if_fail (item != NULL);
455     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
457     if (item->flags & SP_CANVAS_ITEM_VISIBLE)
458         return;
460     item->flags |= SP_CANVAS_ITEM_VISIBLE;
462     sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
463     item->canvas->need_repick = TRUE;
466 /**
467  * Clears visible flag on item and requests a redraw.
468  */
469 void
470 sp_canvas_item_hide (SPCanvasItem *item)
472     g_return_if_fail (item != NULL);
473     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
475     if (!(item->flags & SP_CANVAS_ITEM_VISIBLE))
476         return;
478     item->flags &= ~SP_CANVAS_ITEM_VISIBLE;
480     sp_canvas_request_redraw (item->canvas, (int)item->x1, (int)item->y1, (int)(item->x2 + 1), (int)(item->y2 + 1));
481     item->canvas->need_repick = TRUE;
484 /**
485  * Grab item under cursor.
486  * 
487  * \pre !canvas->grabbed_item && item->flags & SP_CANVAS_ITEM_VISIBLE
488  */
489 int
490 sp_canvas_item_grab (SPCanvasItem *item, guint event_mask, GdkCursor *cursor, guint32 etime)
492     g_return_val_if_fail (item != NULL, -1);
493     g_return_val_if_fail (SP_IS_CANVAS_ITEM (item), -1);
494     g_return_val_if_fail (GTK_WIDGET_MAPPED (item->canvas), -1);
496     if (item->canvas->grabbed_item)
497         return -1;
499     if (!(item->flags & SP_CANVAS_ITEM_VISIBLE))
500         return -1;
502     /* fixme: Top hack (Lauris) */
503     /* fixme: If we add key masks to event mask, Gdk will abort (Lauris) */
504     /* fixme: But Canvas actualle does get key events, so all we need is routing these here */
505     gdk_pointer_grab (SP_CANVAS_WINDOW (item->canvas), FALSE,
506                       (GdkEventMask)(event_mask & (~(GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK))),
507                       NULL, cursor, etime);
509     item->canvas->grabbed_item = item;
510     item->canvas->grabbed_event_mask = event_mask;
511     item->canvas->current_item = item; /* So that events go to the grabbed item */
513     return 0;
516 /**
517  * Ungrabs the item, which must have been grabbed in the canvas, and ungrabs the
518  * mouse.
519  * 
520  * \param item A canvas item that holds a grab.
521  * \param etime The timestamp for ungrabbing the mouse.
522  */
523 void
524 sp_canvas_item_ungrab (SPCanvasItem *item, guint32 etime)
526     g_return_if_fail (item != NULL);
527     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
529     if (item->canvas->grabbed_item != item)
530         return;
532     item->canvas->grabbed_item = NULL;
534     gdk_pointer_ungrab (etime);
537 /**
538  * Returns the product of all transformation matrices from the root item down
539  * to the item.
540  */
541 NR::Matrix sp_canvas_item_i2w_affine(SPCanvasItem const *item)
543     g_assert (SP_IS_CANVAS_ITEM (item)); // should we get this?
545     NR::Matrix affine = NR::identity();
547     while (item) {
548         affine *= item->xform;
549         item = item->parent;
550     }
551     return affine;
554 /**
555  * Helper that returns true iff item is descendant of parent.
556  */
557 static bool is_descendant(SPCanvasItem const *item, SPCanvasItem const *parent)
559     while (item) {
560         if (item == parent)
561             return true;
562         item = item->parent;
563     }
565     return false;
568 /**
569  * Focus canvas, and item under cursor if it is not already focussed.
570  */
571 void
572 sp_canvas_item_grab_focus (SPCanvasItem *item)
574     g_return_if_fail (item != NULL);
575     g_return_if_fail (SP_IS_CANVAS_ITEM (item));
576     g_return_if_fail (GTK_WIDGET_CAN_FOCUS (GTK_WIDGET (item->canvas)));
578     SPCanvasItem *focused_item = item->canvas->focused_item;
580     if (focused_item) {
581         GdkEvent ev;
582         ev.focus_change.type = GDK_FOCUS_CHANGE;
583         ev.focus_change.window = SP_CANVAS_WINDOW (item->canvas);
584         ev.focus_change.send_event = FALSE;
585         ev.focus_change.in = FALSE;
587         emit_event (item->canvas, &ev);
588     }
590     item->canvas->focused_item = item;
591     gtk_widget_grab_focus (GTK_WIDGET (item->canvas));
593     if (focused_item) {
594         GdkEvent ev;
595         ev.focus_change.type = GDK_FOCUS_CHANGE;
596         ev.focus_change.window = SP_CANVAS_WINDOW (item->canvas);
597         ev.focus_change.send_event = FALSE;
598         ev.focus_change.in = TRUE;
600         emit_event (item->canvas, &ev);
601     }
604 /**
605  * Requests that the canvas queue an update for the specified item.
606  * 
607  * To be used only by item implementations.
608  */
609 void
610 sp_canvas_item_request_update (SPCanvasItem *item)
612     if (item->flags & SP_CANVAS_ITEM_NEED_UPDATE)
613         return;
615     item->flags |= SP_CANVAS_ITEM_NEED_UPDATE;
617     if (item->parent != NULL) {
618         /* Recurse up the tree */
619         sp_canvas_item_request_update (item->parent);
620     } else {
621         /* Have reached the top of the tree, make sure the update call gets scheduled. */
622         sp_canvas_request_update (item->canvas);
623     }
626 /**
627  * Returns position of item in group.
628  */
629 gint sp_canvas_item_order (SPCanvasItem * item)
631     return g_list_index (SP_CANVAS_GROUP (item->parent)->items, item);
634 /* SPCanvasGroup */
636 static void sp_canvas_group_class_init (SPCanvasGroupClass *klass);
637 static void sp_canvas_group_init (SPCanvasGroup *group);
638 static void sp_canvas_group_destroy (GtkObject *object);
640 static void sp_canvas_group_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags);
641 static double sp_canvas_group_point (SPCanvasItem *item, NR::Point p, SPCanvasItem **actual_item);
642 static void sp_canvas_group_render (SPCanvasItem *item, SPCanvasBuf *buf);
644 static SPCanvasItemClass *group_parent_class;
646 /**
647  * Registers SPCanvasGroup class with Gtk and returns its type number.
648  */
649 GtkType
650 sp_canvas_group_get_type (void)
652     static GtkType group_type = 0;
654     if (!group_type) {
655         static const GtkTypeInfo group_info = {
656             "SPCanvasGroup",
657             sizeof (SPCanvasGroup),
658             sizeof (SPCanvasGroupClass),
659             (GtkClassInitFunc) sp_canvas_group_class_init,
660             (GtkObjectInitFunc) sp_canvas_group_init,
661             NULL, NULL, NULL
662         };
664         group_type = gtk_type_unique (sp_canvas_item_get_type (), &group_info);
665     }
667     return group_type;
670 /**
671  * Class initialization function for SPCanvasGroupClass
672  */
673 static void
674 sp_canvas_group_class_init (SPCanvasGroupClass *klass)
676     GtkObjectClass *object_class = (GtkObjectClass *) klass;
677     SPCanvasItemClass *item_class = (SPCanvasItemClass *) klass;
679     group_parent_class = (SPCanvasItemClass*)gtk_type_class (sp_canvas_item_get_type ());
681     object_class->destroy = sp_canvas_group_destroy;
683     item_class->update = sp_canvas_group_update;
684     item_class->render = sp_canvas_group_render;
685     item_class->point = sp_canvas_group_point;
688 /**
689  * Callback. Empty.
690  */
691 static void
692 sp_canvas_group_init (SPCanvasGroup */*group*/)
694     /* Nothing here */
697 /**
698  * Callback that destroys all items in group and calls group's virtual 
699  * destroy() function.
700  */
701 static void
702 sp_canvas_group_destroy (GtkObject *object)
704     g_return_if_fail (object != NULL);
705     g_return_if_fail (SP_IS_CANVAS_GROUP (object));
707     const SPCanvasGroup *group = SP_CANVAS_GROUP (object);
709     GList *list = group->items;
710     while (list) {
711         SPCanvasItem *child = (SPCanvasItem *)list->data;
712         list = list->next;
714         gtk_object_destroy (GTK_OBJECT (child));
715     }
717     if (GTK_OBJECT_CLASS (group_parent_class)->destroy)
718         (* GTK_OBJECT_CLASS (group_parent_class)->destroy) (object);
721 /**
722  * Update handler for canvas groups
723  */
724 static void
725 sp_canvas_group_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags)
727     const SPCanvasGroup *group = SP_CANVAS_GROUP (item);
728     NR::ConvexHull corners(NR::Point(0, 0));
729     bool empty=true;
731     for (GList *list = group->items; list; list = list->next) {
732         SPCanvasItem *i = (SPCanvasItem *)list->data;
734         sp_canvas_item_invoke_update (i, affine, flags);
736         if ( i->x2 > i->x1 && i->y2 > i->y1 ) {
737             if (empty) {
738                 corners = NR::ConvexHull(NR::Point(i->x1, i->y1));
739                 empty = false;
740             } else {
741                 corners.add(NR::Point(i->x1, i->y1));
742             }
743             corners.add(NR::Point(i->x2, i->y2));
744         }
745     }
747     NR::Rect const &bounds = corners.bounds();
748     item->x1 = bounds.min()[NR::X];
749     item->y1 = bounds.min()[NR::Y];
750     item->x2 = bounds.max()[NR::X];
751     item->y2 = bounds.max()[NR::Y];
754 /**
755  * Point handler for canvas groups.
756  */
757 static double
758 sp_canvas_group_point (SPCanvasItem *item, NR::Point p, SPCanvasItem **actual_item)
760     const SPCanvasGroup *group = SP_CANVAS_GROUP (item);
761     const double x = p[NR::X];
762     const double y = p[NR::Y];
763     int x1 = (int)(x - item->canvas->close_enough);
764     int y1 = (int)(y - item->canvas->close_enough);
765     int x2 = (int)(x + item->canvas->close_enough);
766     int y2 = (int)(y + item->canvas->close_enough);
768     double best = 0.0;
769     *actual_item = NULL;
771     double dist = 0.0;
773     for (GList *list = group->items; list; list = list->next) {
774         SPCanvasItem *child = (SPCanvasItem *)list->data;
776         if ((child->x1 <= x2) && (child->y1 <= y2) && (child->x2 >= x1) && (child->y2 >= y1)) {
777             SPCanvasItem *point_item = NULL; /* cater for incomplete item implementations */
779             int has_point;
780             if ((child->flags & SP_CANVAS_ITEM_VISIBLE) && SP_CANVAS_ITEM_GET_CLASS (child)->point) {
781                 dist = sp_canvas_item_invoke_point (child, p, &point_item);
782                 has_point = TRUE;
783             } else
784                 has_point = FALSE;
786             if (has_point && point_item && ((int) (dist + 0.5) <= item->canvas->close_enough)) {
787                 best = dist;
788                 *actual_item = point_item;
789             }
790         }
791     }
793     return best;
796 /**
797  * Renders all visible canvas group items in buf rectangle.
798  */
799 static void
800 sp_canvas_group_render (SPCanvasItem *item, SPCanvasBuf *buf)
802     const SPCanvasGroup *group = SP_CANVAS_GROUP (item);
804     for (GList *list = group->items; list; list = list->next) {
805         SPCanvasItem *child = (SPCanvasItem *)list->data;
806         if (child->flags & SP_CANVAS_ITEM_VISIBLE) {
807             if ((child->x1 < buf->rect.x1) &&
808                 (child->y1 < buf->rect.y1) &&
809                 (child->x2 > buf->rect.x0) &&
810                 (child->y2 > buf->rect.y0)) {
811                 if (SP_CANVAS_ITEM_GET_CLASS (child)->render)
812                     SP_CANVAS_ITEM_GET_CLASS (child)->render (child, buf);
813             }
814         }
815     }
818 /**
819  * Adds an item to a canvas group.
820  */
821 static void
822 group_add (SPCanvasGroup *group, SPCanvasItem *item)
824     gtk_object_ref (GTK_OBJECT (item));
825     gtk_object_sink (GTK_OBJECT (item));
827     if (!group->items) {
828         group->items = g_list_append (group->items, item);
829         group->last = group->items;
830     } else {
831         group->last = g_list_append (group->last, item)->next;
832     }
834     sp_canvas_item_request_update (item);
837 /** 
838  * Removes an item from a canvas group
839  */
840 static void
841 group_remove (SPCanvasGroup *group, SPCanvasItem *item)
843     g_return_if_fail (group != NULL);
844     g_return_if_fail (SP_IS_CANVAS_GROUP (group));
845     g_return_if_fail (item != NULL);
847     for (GList *children = group->items; children; children = children->next) {
848         if (children->data == item) {
850             /* Unparent the child */
852             item->parent = NULL;
853             gtk_object_unref (GTK_OBJECT (item));
855             /* Remove it from the list */
857             if (children == group->last) group->last = children->prev;
859             group->items = g_list_remove_link (group->items, children);
860             g_list_free (children);
861             break;
862         }
863     }
866 /* SPCanvas */
868 static void sp_canvas_class_init (SPCanvasClass *klass);
869 static void sp_canvas_init (SPCanvas *canvas);
870 static void sp_canvas_destroy (GtkObject *object);
872 static void sp_canvas_realize (GtkWidget *widget);
873 static void sp_canvas_unrealize (GtkWidget *widget);
875 static void sp_canvas_size_request (GtkWidget *widget, GtkRequisition *req);
876 static void sp_canvas_size_allocate (GtkWidget *widget, GtkAllocation *allocation);
878 static gint sp_canvas_button (GtkWidget *widget, GdkEventButton *event);
879 static gint sp_canvas_scroll (GtkWidget *widget, GdkEventScroll *event);
880 static gint sp_canvas_motion (GtkWidget *widget, GdkEventMotion *event);
881 static gint sp_canvas_expose (GtkWidget *widget, GdkEventExpose *event);
882 static gint sp_canvas_key (GtkWidget *widget, GdkEventKey *event);
883 static gint sp_canvas_crossing (GtkWidget *widget, GdkEventCrossing *event);
884 static gint sp_canvas_focus_in (GtkWidget *widget, GdkEventFocus *event);
885 static gint sp_canvas_focus_out (GtkWidget *widget, GdkEventFocus *event);
887 static GtkWidgetClass *canvas_parent_class;
889 void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb);
890 void sp_canvas_dirty_rect(SPCanvas* canvas,int nl,int nt,int nr,int nb);
891 static int do_update (SPCanvas *canvas);
893 /**
894  * Registers the SPCanvas class if necessary, and returns the type ID
895  * associated to it.
896  *
897  * \return The type ID of the SPCanvas class.
898  **/
899 GtkType
900 sp_canvas_get_type (void)
902     static GtkType canvas_type = 0;
904     if (!canvas_type) {
905         static const GtkTypeInfo canvas_info = {
906             "SPCanvas",
907             sizeof (SPCanvas),
908             sizeof (SPCanvasClass),
909             (GtkClassInitFunc) sp_canvas_class_init,
910             (GtkObjectInitFunc) sp_canvas_init,
911             NULL, NULL, NULL
912         };
914         canvas_type = gtk_type_unique (GTK_TYPE_WIDGET, &canvas_info);
915     }
917     return canvas_type;
920 /**
921  * Class initialization function for SPCanvasClass.
922  */
923 static void
924 sp_canvas_class_init (SPCanvasClass *klass)
926     GtkObjectClass *object_class = (GtkObjectClass *) klass;
927     GtkWidgetClass *widget_class = (GtkWidgetClass *) klass;
929     canvas_parent_class = (GtkWidgetClass *)gtk_type_class (GTK_TYPE_WIDGET);
931     object_class->destroy = sp_canvas_destroy;
933     widget_class->realize = sp_canvas_realize;
934     widget_class->unrealize = sp_canvas_unrealize;
935     widget_class->size_request = sp_canvas_size_request;
936     widget_class->size_allocate = sp_canvas_size_allocate;
937     widget_class->button_press_event = sp_canvas_button;
938     widget_class->button_release_event = sp_canvas_button;
939     widget_class->motion_notify_event = sp_canvas_motion;
940     widget_class->scroll_event = sp_canvas_scroll;
941     widget_class->expose_event = sp_canvas_expose;
942     widget_class->key_press_event = sp_canvas_key;
943     widget_class->key_release_event = sp_canvas_key;
944     widget_class->enter_notify_event = sp_canvas_crossing;
945     widget_class->leave_notify_event = sp_canvas_crossing;
946     widget_class->focus_in_event = sp_canvas_focus_in;
947     widget_class->focus_out_event = sp_canvas_focus_out;
950 /** 
951  * Callback: object initialization for SPCanvas.
952  */
953 static void
954 sp_canvas_init (SPCanvas *canvas)
956     GTK_WIDGET_UNSET_FLAGS (canvas, GTK_NO_WINDOW);
957     GTK_WIDGET_UNSET_FLAGS (canvas, GTK_DOUBLE_BUFFERED);
958     GTK_WIDGET_SET_FLAGS (canvas, GTK_CAN_FOCUS);
960     canvas->pick_event.type = GDK_LEAVE_NOTIFY;
961     canvas->pick_event.crossing.x = 0;
962     canvas->pick_event.crossing.y = 0;
964     /* Create the root item as a special case */
965     canvas->root = SP_CANVAS_ITEM (gtk_type_new (sp_canvas_group_get_type ()));
966     canvas->root->canvas = canvas;
968     gtk_object_ref (GTK_OBJECT (canvas->root));
969     gtk_object_sink (GTK_OBJECT (canvas->root));
971     canvas->need_repick = TRUE;
973     // See comment at in sp-canvas.h.
974     canvas->gen_all_enter_events = false;
976     canvas->tiles=NULL;
977     canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
978     canvas->tileH=canvas->tileV=0;
980     canvas->redraw_aborted.x0 = NR_HUGE_L;
981     canvas->redraw_aborted.x1 = -NR_HUGE_L;
982     canvas->redraw_aborted.y0 = NR_HUGE_L;
983     canvas->redraw_aborted.y1 = -NR_HUGE_L;
984     
985     canvas->redraw_count = 0;
986     
987     canvas->forced_redraw_count = 0;
988     canvas->forced_redraw_limit = -1;
990     canvas->slowest_buffer = 0;
993 /**
994  * Convenience function to remove the idle handler of a canvas.
995  */
996 static void
997 remove_idle (SPCanvas *canvas)
999     if (canvas->idle_id) {
1000         gtk_idle_remove (canvas->idle_id);
1001         canvas->idle_id = 0;
1002     }
1005 /*
1006  * Removes the transient state of the canvas (idle handler, grabs).
1007  */
1008 static void
1009 shutdown_transients (SPCanvas *canvas)
1011     /* We turn off the need_redraw flag, since if the canvas is mapped again
1012      * it will request a redraw anyways.  We do not turn off the need_update
1013      * flag, though, because updates are not queued when the canvas remaps
1014      * itself.
1015      */
1016     if (canvas->need_redraw) {
1017         canvas->need_redraw = FALSE;
1018     }
1019     if ( canvas->tiles ) g_free(canvas->tiles);
1020     canvas->tiles=NULL;
1021     canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
1022     canvas->tileH=canvas->tileV=0;
1024     if (canvas->grabbed_item) {
1025         canvas->grabbed_item = NULL;
1026         gdk_pointer_ungrab (GDK_CURRENT_TIME);
1027     }
1029     remove_idle (canvas);
1032 /**
1033  * Destroy handler for SPCanvas.
1034  */
1035 static void
1036 sp_canvas_destroy (GtkObject *object)
1038     SPCanvas *canvas = SP_CANVAS (object);
1040     if (canvas->root) {
1041         gtk_object_unref (GTK_OBJECT (canvas->root));
1042         canvas->root = NULL;
1043     }
1045     shutdown_transients (canvas);
1047     if (GTK_OBJECT_CLASS (canvas_parent_class)->destroy)
1048         (* GTK_OBJECT_CLASS (canvas_parent_class)->destroy) (object);
1051 /**
1052  * Returns new canvas as widget.
1053  */
1054 GtkWidget *
1055 sp_canvas_new_aa (void)
1057     SPCanvas *canvas = (SPCanvas *)gtk_type_new (sp_canvas_get_type ());
1059     return (GtkWidget *) canvas;
1062 /**
1063  * The canvas widget's realize callback.
1064  */
1065 static void
1066 sp_canvas_realize (GtkWidget *widget)
1068     SPCanvas *canvas = SP_CANVAS (widget);
1070     GdkWindowAttr attributes;
1071     attributes.window_type = GDK_WINDOW_CHILD;
1072     attributes.x = widget->allocation.x;
1073     attributes.y = widget->allocation.y;
1074     attributes.width = widget->allocation.width;
1075     attributes.height = widget->allocation.height;
1076     attributes.wclass = GDK_INPUT_OUTPUT;
1077     attributes.visual = gdk_rgb_get_visual ();
1078     attributes.colormap = gdk_rgb_get_cmap ();
1079     attributes.event_mask = (gtk_widget_get_events (widget) |
1080                              GDK_EXPOSURE_MASK |
1081                              GDK_BUTTON_PRESS_MASK |
1082                              GDK_BUTTON_RELEASE_MASK |
1083                              GDK_POINTER_MOTION_MASK |
1084                              GDK_PROXIMITY_IN_MASK |
1085                              GDK_PROXIMITY_OUT_MASK |
1086                              GDK_KEY_PRESS_MASK |
1087                              GDK_KEY_RELEASE_MASK |
1088                              GDK_ENTER_NOTIFY_MASK |
1089                              GDK_LEAVE_NOTIFY_MASK |
1090                              GDK_FOCUS_CHANGE_MASK);
1091     gint attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
1093     widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask);
1094     gdk_window_set_user_data (widget->window, widget);
1096     if ( prefs_get_int_attribute ("options.useextinput", "value", 1) )
1097         gtk_widget_set_events(widget, attributes.event_mask);
1099     widget->style = gtk_style_attach (widget->style, widget->window);
1101     GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
1103     canvas->pixmap_gc = gdk_gc_new (SP_CANVAS_WINDOW (canvas));
1106 /**
1107  * The canvas widget's unrealize callback.
1108  */
1109 static void
1110 sp_canvas_unrealize (GtkWidget *widget)
1112     SPCanvas *canvas = SP_CANVAS (widget);
1114     shutdown_transients (canvas);
1116     gdk_gc_destroy (canvas->pixmap_gc);
1117     canvas->pixmap_gc = NULL;
1119     if (GTK_WIDGET_CLASS (canvas_parent_class)->unrealize)
1120         (* GTK_WIDGET_CLASS (canvas_parent_class)->unrealize) (widget);
1123 /**
1124  * The canvas widget's size_request callback.
1125  */
1126 static void
1127 sp_canvas_size_request (GtkWidget *widget, GtkRequisition *req)
1129     static_cast<void>(SP_CANVAS (widget));
1131     req->width = 256;
1132     req->height = 256;
1135 /**
1136  * The canvas widget's size_allocate callback.
1137  */
1138 static void
1139 sp_canvas_size_allocate (GtkWidget *widget, GtkAllocation *allocation)
1141     SPCanvas *canvas = SP_CANVAS (widget);
1143     /* Schedule redraw of new region */
1144     sp_canvas_resize_tiles(canvas,canvas->x0,canvas->y0,canvas->x0+allocation->width,canvas->y0+allocation->height);
1145     if (allocation->width > widget->allocation.width) {
1146         sp_canvas_request_redraw (canvas,
1147                                   canvas->x0 + widget->allocation.width,
1148                                   0,
1149                                   canvas->x0 + allocation->width,
1150                                   canvas->y0 + allocation->height);
1151     }
1152     if (allocation->height > widget->allocation.height) {
1153         sp_canvas_request_redraw (canvas,
1154                                   0,
1155                                   canvas->y0 + widget->allocation.height,
1156                                   canvas->x0 + allocation->width,
1157                                   canvas->y0 + allocation->height);
1158     }
1160     widget->allocation = *allocation;
1162     if (GTK_WIDGET_REALIZED (widget)) {
1163         gdk_window_move_resize (widget->window,
1164                                 widget->allocation.x, widget->allocation.y,
1165                                 widget->allocation.width, widget->allocation.height);
1166     }
1169 /**
1170  * Helper that emits an event for an item in the canvas, be it the current 
1171  * item, grabbed item, or focused item, as appropriate.
1172  */
1173 static int
1174 emit_event (SPCanvas *canvas, GdkEvent *event)
1176     guint mask;
1178     if (canvas->grabbed_item) {
1179         switch (event->type) {
1180         case GDK_ENTER_NOTIFY:
1181             mask = GDK_ENTER_NOTIFY_MASK;
1182             break;
1183         case GDK_LEAVE_NOTIFY:
1184             mask = GDK_LEAVE_NOTIFY_MASK;
1185             break;
1186         case GDK_MOTION_NOTIFY:
1187             mask = GDK_POINTER_MOTION_MASK;
1188             break;
1189         case GDK_BUTTON_PRESS:
1190         case GDK_2BUTTON_PRESS:
1191         case GDK_3BUTTON_PRESS:
1192             mask = GDK_BUTTON_PRESS_MASK;
1193             break;
1194         case GDK_BUTTON_RELEASE:
1195             mask = GDK_BUTTON_RELEASE_MASK;
1196             break;
1197         case GDK_KEY_PRESS:
1198             mask = GDK_KEY_PRESS_MASK;
1199             break;
1200         case GDK_KEY_RELEASE:
1201             mask = GDK_KEY_RELEASE_MASK;
1202             break;
1203         case GDK_SCROLL:
1204             mask = GDK_SCROLL;
1205             break;
1206         default:
1207             mask = 0;
1208             break;
1209         }
1211         if (!(mask & canvas->grabbed_event_mask)) return FALSE;
1212     }
1214     /* Convert to world coordinates -- we have two cases because of diferent
1215      * offsets of the fields in the event structures.
1216      */
1218     GdkEvent ev = *event;
1220     switch (ev.type) {
1221     case GDK_ENTER_NOTIFY:
1222     case GDK_LEAVE_NOTIFY:
1223         ev.crossing.x += canvas->x0;
1224         ev.crossing.y += canvas->y0;
1225         break;
1226     case GDK_MOTION_NOTIFY:
1227     case GDK_BUTTON_PRESS:
1228     case GDK_2BUTTON_PRESS:
1229     case GDK_3BUTTON_PRESS:
1230     case GDK_BUTTON_RELEASE:
1231         ev.motion.x += canvas->x0;
1232         ev.motion.y += canvas->y0;
1233         break;
1234     default:
1235         break;
1236     }
1238     /* Choose where we send the event */
1240     /* canvas->current_item becomes NULL in some cases under Win32
1241     ** (e.g. if the pointer leaves the window).  So this is a hack that
1242     ** Lauris applied to SP to get around the problem.
1243     */
1244     SPCanvasItem* item = NULL;
1245     if (canvas->grabbed_item && !is_descendant (canvas->current_item, canvas->grabbed_item)) {
1246         item = canvas->grabbed_item;
1247     } else {
1248         item = canvas->current_item;
1249     }
1251     if (canvas->focused_item &&
1252         ((event->type == GDK_KEY_PRESS) ||
1253          (event->type == GDK_KEY_RELEASE) ||
1254          (event->type == GDK_FOCUS_CHANGE))) {
1255         item = canvas->focused_item;
1256     }
1258     /* The event is propagated up the hierarchy (for if someone connected to
1259      * a group instead of a leaf event), and emission is stopped if a
1260      * handler returns TRUE, just like for GtkWidget events.
1261      */
1263     gint finished = FALSE;
1265     while (item && !finished) {
1266         gtk_object_ref (GTK_OBJECT (item));
1267         gtk_signal_emit (GTK_OBJECT (item), item_signals[ITEM_EVENT], &ev, &finished);
1268         SPCanvasItem *parent = item->parent;
1269         gtk_object_unref (GTK_OBJECT (item));
1270         item = parent;
1271     }
1273     return finished;
1276 /**
1277  * Helper that re-picks the current item in the canvas, based on the event's 
1278  * coordinates and emits enter/leave events for items as appropriate.
1279  */
1280 static int
1281 pick_current_item (SPCanvas *canvas, GdkEvent *event)
1283     int button_down = 0;
1284     double x, y;
1286     if (!canvas->root) // canvas may have already be destroyed by closing desktop durring interrupted display!
1287         return FALSE;
1289     int retval = FALSE;
1291     if (canvas->gen_all_enter_events == false) {
1292         // If a button is down, we'll perform enter and leave events on the
1293         // current item, but not enter on any other item.  This is more or
1294         // less like X pointer grabbing for canvas items.
1295         //
1296         button_down = canvas->state & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK |
1297                 GDK_BUTTON3_MASK | GDK_BUTTON4_MASK | GDK_BUTTON5_MASK);
1299         if (!button_down) canvas->left_grabbed_item = FALSE;
1300     }
1302     /* Save the event in the canvas.  This is used to synthesize enter and
1303      * leave events in case the current item changes.  It is also used to
1304      * re-pick the current item if the current one gets deleted.  Also,
1305      * synthesize an enter event.
1306      */
1307     if (event != &canvas->pick_event) {
1308         if ((event->type == GDK_MOTION_NOTIFY) || (event->type == GDK_BUTTON_RELEASE)) {
1309             /* these fields have the same offsets in both types of events */
1311             canvas->pick_event.crossing.type       = GDK_ENTER_NOTIFY;
1312             canvas->pick_event.crossing.window     = event->motion.window;
1313             canvas->pick_event.crossing.send_event = event->motion.send_event;
1314             canvas->pick_event.crossing.subwindow  = NULL;
1315             canvas->pick_event.crossing.x          = event->motion.x;
1316             canvas->pick_event.crossing.y          = event->motion.y;
1317             canvas->pick_event.crossing.mode       = GDK_CROSSING_NORMAL;
1318             canvas->pick_event.crossing.detail     = GDK_NOTIFY_NONLINEAR;
1319             canvas->pick_event.crossing.focus      = FALSE;
1320             canvas->pick_event.crossing.state      = event->motion.state;
1322             /* these fields don't have the same offsets in both types of events */
1324             if (event->type == GDK_MOTION_NOTIFY) {
1325                 canvas->pick_event.crossing.x_root = event->motion.x_root;
1326                 canvas->pick_event.crossing.y_root = event->motion.y_root;
1327             } else {
1328                 canvas->pick_event.crossing.x_root = event->button.x_root;
1329                 canvas->pick_event.crossing.y_root = event->button.y_root;
1330             }
1331         } else {
1332             canvas->pick_event = *event;
1333         }
1334     }
1336     /* Don't do anything else if this is a recursive call */
1337     if (canvas->in_repick) return retval;
1339     /* LeaveNotify means that there is no current item, so we don't look for one */
1340     if (canvas->pick_event.type != GDK_LEAVE_NOTIFY) {
1341         /* these fields don't have the same offsets in both types of events */
1343         if (canvas->pick_event.type == GDK_ENTER_NOTIFY) {
1344             x = canvas->pick_event.crossing.x;
1345             y = canvas->pick_event.crossing.y;
1346         } else {
1347             x = canvas->pick_event.motion.x;
1348             y = canvas->pick_event.motion.y;
1349         }
1351         /* world coords */
1352         x += canvas->x0;
1353         y += canvas->y0;
1355         /* find the closest item */
1356         if (canvas->root->flags & SP_CANVAS_ITEM_VISIBLE) {
1357             sp_canvas_item_invoke_point (canvas->root, NR::Point(x, y), &canvas->new_current_item);
1358         } else {
1359             canvas->new_current_item = NULL;
1360         }
1361     } else {
1362         canvas->new_current_item = NULL;
1363     }
1365     if ((canvas->new_current_item == canvas->current_item) && !canvas->left_grabbed_item) {
1366         return retval; /* current item did not change */
1367     }
1369     /* Synthesize events for old and new current items */
1371     if ((canvas->new_current_item != canvas->current_item)
1372         && (canvas->current_item != NULL)
1373         && !canvas->left_grabbed_item) {
1374         GdkEvent new_event;
1375         SPCanvasItem *item;
1377         item = canvas->current_item;
1379         new_event = canvas->pick_event;
1380         new_event.type = GDK_LEAVE_NOTIFY;
1382         new_event.crossing.detail = GDK_NOTIFY_ANCESTOR;
1383         new_event.crossing.subwindow = NULL;
1384         canvas->in_repick = TRUE;
1385         retval = emit_event (canvas, &new_event);
1386         canvas->in_repick = FALSE;
1387     }
1389     if (canvas->gen_all_enter_events == false) {
1390         // new_current_item may have been set to NULL during the call to
1391         // emit_event() above
1392         if ((canvas->new_current_item != canvas->current_item) && button_down) {
1393             canvas->left_grabbed_item = TRUE;
1394             return retval;
1395         }
1396     }
1398     /* Handle the rest of cases */
1400     canvas->left_grabbed_item = FALSE;
1401     canvas->current_item = canvas->new_current_item;
1403     if (canvas->current_item != NULL) {
1404         GdkEvent new_event;
1406         new_event = canvas->pick_event;
1407         new_event.type = GDK_ENTER_NOTIFY;
1408         new_event.crossing.detail = GDK_NOTIFY_ANCESTOR;
1409         new_event.crossing.subwindow = NULL;
1410         retval = emit_event (canvas, &new_event);
1411     }
1413     return retval;
1416 /**
1417  * Button event handler for the canvas.
1418  */
1419 static gint
1420 sp_canvas_button (GtkWidget *widget, GdkEventButton *event)
1422     SPCanvas *canvas = SP_CANVAS (widget);
1424     int retval = FALSE;
1426     /* dispatch normally regardless of the event's window if an item has
1427        has a pointer grab in effect */
1428     if (!canvas->grabbed_item && 
1429         event->window != SP_CANVAS_WINDOW (canvas))
1430         return retval;
1432     int mask;
1433     switch (event->button) {
1434     case 1:
1435         mask = GDK_BUTTON1_MASK;
1436         break;
1437     case 2:
1438         mask = GDK_BUTTON2_MASK;
1439         break;
1440     case 3:
1441         mask = GDK_BUTTON3_MASK;
1442         break;
1443     case 4:
1444         mask = GDK_BUTTON4_MASK;
1445         break;
1446     case 5:
1447         mask = GDK_BUTTON5_MASK;
1448         break;
1449     default:
1450         mask = 0;
1451     }
1453     switch (event->type) {
1454     case GDK_BUTTON_PRESS:
1455     case GDK_2BUTTON_PRESS:
1456     case GDK_3BUTTON_PRESS:
1457         /* Pick the current item as if the button were not pressed, and
1458          * then process the event.
1459          */
1460         canvas->state = event->state;
1461         pick_current_item (canvas, (GdkEvent *) event);
1462         canvas->state ^= mask;
1463         retval = emit_event (canvas, (GdkEvent *) event);
1464         break;
1466     case GDK_BUTTON_RELEASE:
1467         /* Process the event as if the button were pressed, then repick
1468          * after the button has been released
1469          */
1470         canvas->state = event->state;
1471         retval = emit_event (canvas, (GdkEvent *) event);
1472         event->state ^= mask;
1473         canvas->state = event->state;
1474         pick_current_item (canvas, (GdkEvent *) event);
1475         event->state ^= mask;
1476         break;
1478     default:
1479         g_assert_not_reached ();
1480     }
1482     return retval;
1485 /**
1486  * Scroll event handler for the canvas.
1487  *
1488  * \todo FIXME: generate motion events to re-select items.
1489  */
1490 static gint
1491 sp_canvas_scroll (GtkWidget *widget, GdkEventScroll *event)
1493     return emit_event (SP_CANVAS (widget), (GdkEvent *) event);
1496 /**
1497  * Motion event handler for the canvas.
1498  */
1499 static int
1500 sp_canvas_motion (GtkWidget *widget, GdkEventMotion *event)
1502     SPCanvas *canvas = SP_CANVAS (widget);
1504     if (event->window != SP_CANVAS_WINDOW (canvas))
1505         return FALSE;
1507     if (canvas->grabbed_event_mask & GDK_POINTER_MOTION_HINT_MASK) {
1508         gint x, y;
1509         gdk_window_get_pointer (widget->window, &x, &y, NULL);
1510         event->x = x;
1511         event->y = y;
1512     }
1514     canvas->state = event->state;
1515     pick_current_item (canvas, (GdkEvent *) event);
1517     return emit_event (canvas, (GdkEvent *) event);
1520 static void
1521 sp_canvas_paint_single_buffer (SPCanvas *canvas, int x0, int y0, int x1, int y1, int draw_x1, int draw_y1, int draw_x2, int draw_y2, int sw)
1523     GtkWidget *widget = GTK_WIDGET (canvas);
1525     SPCanvasBuf buf;
1526     if (canvas->rendermode != RENDERMODE_OUTLINE) {
1527         buf.buf = nr_pixelstore_256K_new (FALSE, 0);
1528     } else {
1529         buf.buf = nr_pixelstore_1M_new (FALSE, 0);
1530     }
1532     buf.buf_rowstride = sw * 3; // CAIRO FIXME: for cairo output, the buffer must be RGB unpacked, i.e. sw * 4
1533     buf.rect.x0 = x0;
1534     buf.rect.y0 = y0;
1535     buf.rect.x1 = x1;
1536     buf.rect.y1 = y1;
1537     buf.visible_rect.x0 = draw_x1;
1538     buf.visible_rect.y0 = draw_y1;
1539     buf.visible_rect.x1 = draw_x2;
1540     buf.visible_rect.y1 = draw_y2;
1541     GdkColor *color = &widget->style->bg[GTK_STATE_NORMAL];
1542     buf.bg_color = (((color->red & 0xff00) << 8)
1543                     | (color->green & 0xff00)
1544                     | (color->blue >> 8));
1545     buf.is_empty = true;
1546       
1547     if (canvas->root->flags & SP_CANVAS_ITEM_VISIBLE) {
1548         SP_CANVAS_ITEM_GET_CLASS (canvas->root)->render (canvas->root, &buf);
1549     }
1550       
1551     if (buf.is_empty) {
1552         gdk_rgb_gc_set_foreground (canvas->pixmap_gc, buf.bg_color);
1553         gdk_draw_rectangle (SP_CANVAS_WINDOW (canvas),
1554                             canvas->pixmap_gc,
1555                             TRUE,
1556                             x0 - canvas->x0, y0 - canvas->y0,
1557                             x1 - x0, y1 - y0);
1558     } else {
1559 /*
1560  CAIRO FIXME: after SPCanvasBuf is made 32bpp throughout, this rgb_draw below can be replaced with:
1561     cairo_surface_t* cst = cairo_image_surface_create_for_data (
1562         buf.buf,
1563         CAIRO_FORMAT_RGB24,  // unpacked, i.e. 32 bits! one byte is unused
1564         x1 - x0, y1 - y0,
1565         buf.buf_rowstride
1566         );
1567         cairo_t *ct = gdk_cairo_create(SP_CANVAS_WINDOW (canvas));
1568         cairo_set_source_surface (ct, cst, x0 - canvas->x0, y0 - canvas->y0);
1569         cairo_paint (ct);
1571     cairo_destroy (ct);
1572     cairo_surface_finish (cst);
1573     cairo_surface_destroy (cst);
1574 */
1576         gdk_draw_rgb_image_dithalign (SP_CANVAS_WINDOW (canvas),
1577                                       canvas->pixmap_gc,
1578                                       x0 - canvas->x0, y0 - canvas->y0,
1579                                       x1 - x0, y1 - y0,
1580                                       GDK_RGB_DITHER_MAX,
1581                                       buf.buf,
1582                                       sw * 3,
1583                                       x0 - canvas->x0, y0 - canvas->y0);
1584     }
1586     if (canvas->rendermode != RENDERMODE_OUTLINE) {
1587         nr_pixelstore_256K_free (buf.buf);
1588     } else {
1589         nr_pixelstore_1M_free (buf.buf);
1590     }
1593 static int is_scrolling = 0;
1595 /* Paint the given rect, while updating canvas->redraw_aborted and running iterations after each
1596  * buffer; make sure canvas->redraw_aborted never goes past aborted_limit (used for 2-rect
1597  * optimized repaint)
1598  */
1599 static int
1600 sp_canvas_paint_rect_internal (SPCanvas *canvas, NRRectL *rect, NR::ICoord *x_aborted_limit, NR::ICoord *y_aborted_limit)
1602     int draw_x1 = rect->x0;
1603     int draw_x2 = rect->x1;
1604     int draw_y1 = rect->y0;
1605     int draw_y2 = rect->y1;
1607     // Here we'll store the time it took to draw the slowest buffer of this paint. 
1608     glong slowest_buffer = 0;
1610     // Find the optimal buffer dimensions
1611     int bw = draw_x2 - draw_x1;
1612     int bh = draw_y2 - draw_y1;
1613     if ((bw < 1) || (bh < 1))
1614         return 0;
1616     int sw, sh;  // CAIRO FIXME: the sw/sh calculations below all assume 24bpp, need fixing for 32bpp
1617     if (canvas->rendermode != RENDERMODE_OUTLINE) { // use 256K as a compromise to not slow down gradients
1618         /* 256K is the cached buffer and we need 3 channels */
1619         if (bw * bh <  87381) { // 256K/3
1620             // We can go with single buffer 
1621             sw = bw;
1622             sh = bh;
1623         } else if (bw <= (16 * 341)) {
1624             // Go with row buffer 
1625             sw = bw;
1626             sh =  87381 / bw;
1627         } else if (bh <= (16 * 256)) {
1628             // Go with column buffer 
1629             sw = 87381 / bh;
1630             sh = bh;
1631         } else {
1632             sw = 341;
1633             sh = 256;
1634         }
1635     } else {  // paths only, so 1M works faster
1636         /* 1M is the cached buffer and we need 3 channels */
1637         if (bw * bh <  349525) { // 1M/3
1638             // We can go with single buffer 
1639             sw = bw;
1640             sh = bh;
1641         } else if (bw <= (16 * 682)) {
1642             // Go with row buffer 
1643             sw = bw;
1644             sh =  349525 / bw;
1645         } else if (bh <= (16 * 512)) {
1646             // Go with column buffer 
1647             sw = 349525 / bh;
1648             sh = bh;
1649         } else {
1650             sw = 682;
1651             sh = 512;
1652         }
1653     }
1654     
1655     // Will this paint require more than one buffer?
1656     bool multiple_buffers = (((draw_y2 - draw_y1) > sh) || ((draw_x2 - draw_x1) > sw)); // or two_rects
1658     // remember the counter during this paint
1659     long this_count = canvas->redraw_count;
1661     // Time values to measure each buffer's paint time
1662     GTimeVal tstart, tfinish;
1664     // paint from the corner nearest the mouse pointer
1666     gint x, y;
1667     gdk_window_get_pointer (GTK_WIDGET(canvas)->window, &x, &y, NULL);
1668     NR::Point pw = sp_canvas_window_to_world (canvas, NR::Point(x,y));
1670     bool reverse_x = (pw[NR::X] > ((draw_x2 + draw_x1) / 2));
1671     bool reverse_y = (pw[NR::Y] > ((draw_y2 + draw_y1) / 2));
1673     if ((bw > bh) && (sh > sw)) {
1674       int t = sw; sw = sh; sh = t;
1675     }
1677     // This is the main loop which corresponds to the visible left-to-right, top-to-bottom drawing
1678     // of screen blocks (buffers).
1679     for (int y0 = draw_y1; y0 < draw_y2; y0 += sh) {
1680         int y1 = MIN (y0 + sh, draw_y2);
1681         for (int x0 = draw_x1; x0 < draw_x2; x0 += sw) {
1682             int x1 = MIN (x0 + sw, draw_x2);
1684             int dx0 = x0;
1685             int dx1 = x1;
1686             int dy0 = y0;
1687             int dy1 = y1;
1689             if (reverse_x) { 
1690               dx0 = (draw_x2 - (x0 + sw)) + draw_x1;
1691               dx0 = MAX (dx0, draw_x1);
1692               dx1 = (draw_x2 - x0) + draw_x1;
1693               dx1 = MIN (dx1, draw_x2);
1694             }
1695             if (reverse_y) { 
1696               dy0 = (draw_y2 - (y0 + sh)) + draw_y1;
1697               dy0 = MAX (dy0, draw_y1);
1698               dy1 = (draw_y2 - y0) + draw_y1;
1699               dy1 = MIN (dy1, draw_y2);
1700             }
1702             // SMOOTH SCROLLING: if we are scrolling, process pending events even before doing any rendering. 
1703             // This allows for scrolling smoothly without hiccups. Any accumulated redraws will be made 
1704             // when scrolling stops. The scrolling flag is set by sp_canvas_scroll_to for each scroll and zeroed
1705             // here for each redraw, to ensure it never gets stuck. 
1707             // OPTIMIZATION IDEA: if drawing is really slow (as measured by canvas->slowest
1708             // buffer), do the same - process some events even before we paint any buffers
1710             if (is_scrolling) {
1711                 is_scrolling = 0;
1712                 while (Gtk::Main::events_pending()) { // process any events
1713                     Gtk::Main::iteration(false);
1714                 }
1715                 if (this_count != canvas->redraw_count) { // if there was redraw,
1716                     return 1; // interrupt this one
1717                 }
1718             }
1719             
1720             // Paint one buffer; measure how long it takes.
1721             g_get_current_time (&tstart);
1722             sp_canvas_paint_single_buffer (canvas, dx0, dy0, dx1, dy1, draw_x1, draw_y1, draw_x2, draw_y2, sw);
1723             g_get_current_time (&tfinish);
1725             // Remember the slowest_buffer of this paint.
1726             glong this_buffer = (tfinish.tv_sec - tstart.tv_sec) * 1000000 + (tfinish.tv_usec - tstart.tv_usec);
1727             if (this_buffer > slowest_buffer) 
1728                 slowest_buffer = this_buffer;
1730             // After each successful buffer, reduce the rect remaining to redraw by what is already redrawn
1731             if (x1 >= draw_x2) {
1732               if (reverse_y) {
1733                 if (canvas->redraw_aborted.y1 > dy0) { canvas->redraw_aborted.y1 = dy0; }
1734               } else {
1735                 if (canvas->redraw_aborted.y0 < y1)  { canvas->redraw_aborted.y0 = y1; }
1736               }
1737             }
1739             if (y1 >= draw_y2) {
1740               if (reverse_x) {
1741                 if (canvas->redraw_aborted.x1 > dx0) { canvas->redraw_aborted.x1 = dx0; }
1742               } else {
1743                 if (canvas->redraw_aborted.x0 < x1)  { canvas->redraw_aborted.x0 = x1; }
1744               }
1745             }
1747             // INTERRUPTIBLE DISPLAY:
1748             // Process events that may have arrived while we were busy drawing;
1749             // only if we're drawing multiple buffers, and only if this one was not very fast,
1750             // and only if we're allowed to interrupt this redraw
1751             bool ok_to_interrupt = (multiple_buffers && this_buffer > 25000);
1752             if (ok_to_interrupt && (canvas->forced_redraw_limit != -1)) {
1753                 ok_to_interrupt = (canvas->forced_redraw_count < canvas->forced_redraw_limit);
1754             }
1756             if (ok_to_interrupt) {
1757                 // Run at most max_iterations of the main loop; we cannot process ALL events
1758                 // here because some things (e.g. rubberband) flood with dirtying events but will
1759                 // not redraw themselves
1760                 int max_iterations = 10;
1761                 int iterations = 0;
1762                 while (Gtk::Main::events_pending() && iterations++ < max_iterations) {
1763                     Gtk::Main::iteration(false);
1764                     // If one of the iterations has redrawn by itself, abort
1765                     if (this_count != canvas->redraw_count) {
1766                         canvas->slowest_buffer = slowest_buffer;
1767                         if (canvas->forced_redraw_limit != -1) {
1768                             canvas->forced_redraw_count++;
1769                         }
1770                         return 1; // interrupted
1771                     }
1772                 }
1773    
1774                 // If not aborted so far, check if the events set redraw or update flags; 
1775                 // if so, force update and abort
1776                 if (canvas->need_redraw || canvas->need_update) {
1777                     canvas->slowest_buffer = slowest_buffer;
1778                     if (canvas->forced_redraw_limit != -1) {
1779                         canvas->forced_redraw_count++;
1780                     }
1781                     do_update (canvas);
1782                     return 1; // interrupted
1783                 }
1784             }
1785         }
1786     }
1788     // Remember the slowest buffer of this paint in canvas
1789     canvas->slowest_buffer = slowest_buffer;
1791     return 0; // finished
1795 /**
1796  * Helper that draws a specific rectangular part of the canvas.
1797  */
1798 static void
1799 sp_canvas_paint_rect (SPCanvas *canvas, int xx0, int yy0, int xx1, int yy1)
1801     g_return_if_fail (!canvas->need_update);
1802  
1803     // Monotonously increment the canvas-global counter on each paint. This will let us find out
1804     // when a new paint happened in event processing during this paint, so we can abort it.
1805     canvas->redraw_count++;
1807     NRRectL rect;
1808     rect.x0 = xx0;
1809     rect.x1 = xx1;
1810     rect.y0 = yy0;
1811     rect.y1 = yy1;
1813     // Clip rect-to-draw by the current visible area
1814     rect.x0 = MAX (rect.x0, canvas->x0);
1815     rect.y0 = MAX (rect.y0, canvas->y0);
1816     rect.x1 = MIN (rect.x1, canvas->x0/*draw_x1*/ + GTK_WIDGET (canvas)->allocation.width);
1817     rect.y1 = MIN (rect.y1, canvas->y0/*draw_y1*/ + GTK_WIDGET (canvas)->allocation.height);
1819     // Clip rect-aborted-last-time by the current visible area
1820     canvas->redraw_aborted.x0 = MAX (canvas->redraw_aborted.x0, canvas->x0);
1821     canvas->redraw_aborted.y0 = MAX (canvas->redraw_aborted.y0, canvas->y0);
1822     canvas->redraw_aborted.x1 = MIN (canvas->redraw_aborted.x1, canvas->x0/*draw_x1*/ + GTK_WIDGET (canvas)->allocation.width);
1823     canvas->redraw_aborted.y1 = MIN (canvas->redraw_aborted.y1, canvas->y0/*draw_y1*/ + GTK_WIDGET (canvas)->allocation.height);
1825     if (canvas->redraw_aborted.x0 < canvas->redraw_aborted.x1 && canvas->redraw_aborted.y0 < canvas->redraw_aborted.y1) {
1826         // There was an aborted redraw last time, now we need to redraw BOTH it and the new rect.
1828         // save the old aborted rect in case we decide to paint it separately (see below)
1829         NRRectL aborted = canvas->redraw_aborted;
1831         // calculate the rectangle union of the both rects (the smallest rectangle which covers both) 
1832         NRRectL nion;
1833         nr_rect_l_union (&nion, &rect, &aborted);
1835         // subtract one of the rects-to-draw from the other (the smallest rectangle which covers
1836         // all of the first not covered by the second)
1837         NRRectL rect_minus_aborted;
1838         nr_rect_l_subtract (&rect_minus_aborted, &rect, &aborted);
1840         // Initially, the rect to redraw later (in case we're aborted) is the same as the union of both rects
1841         canvas->redraw_aborted = nion;
1843         // calculate areas of the three rects
1844         if ((nr_rect_l_area(&rect_minus_aborted) + nr_rect_l_area(&aborted)) * 1.2 < nr_rect_l_area(&nion)) {
1845             // If the summary area of the two rects is significantly (at least by 20%) less than
1846             // the area of their rectangular union, it makes sense to paint the two rects
1847             // separately instead of painting their union. This gives a significant speedup when,
1848             // for example, your current canvas is almost painted, with only a strip at bottom
1849             // left, and at that moment you abort it by scrolling down which reveals a new strip at
1850             // the top. Straightforward painting of the union of the aborted rect and the new rect
1851             // will have to repaint the entire canvas! By contrast, the optimized approach below
1852             // paints the two narrow strips in order which is much faster.
1854             // find out which rect to draw first - compare them first by y then by x of the top left corners
1855             NRRectL *first;
1856             NRRectL *second;
1857             if (rect.y0 == aborted.y0) {
1858                 if (rect.x0 < aborted.x0) {
1859                     first = &rect;
1860                     second = &aborted;
1861                 } else {
1862                     second = &rect;
1863                     first = &aborted;
1864                 }
1865             } else if (rect.y0 < aborted.y0) {
1866                 first = &rect;
1867                 second = &aborted;
1868             } else {
1869                 second = &rect;
1870                 first = &aborted;
1871             }
1873             NRRectL second_minus_first;
1874             nr_rect_l_subtract (&second_minus_first, second, first);
1876             // paint the first rect;
1877             if (sp_canvas_paint_rect_internal (canvas, first, &(second_minus_first.x0), &(second_minus_first.y0))) {
1878                 // aborted!
1879                 return;
1880             }
1882             // if not aborted, assign (second rect minus first) as the new redraw_aborted and paint the same
1883             canvas->redraw_aborted = second_minus_first;
1884             if (sp_canvas_paint_rect_internal (canvas, &second_minus_first, NULL, NULL)) {
1885                 return; // aborted
1886             }
1888         } else {
1889             // no need for separate drawing, just draw the union as one rect
1890             if (sp_canvas_paint_rect_internal (canvas, &nion, NULL, NULL)) {
1891                 return; // aborted
1892             }
1893         }
1894     } else {
1895         // Nothing was aborted last time, just draw the rect we're given
1897         // Initially, the rect to redraw later (in case we're aborted) is the same as the one we're going to draw now.
1898         canvas->redraw_aborted = rect;
1900         if (sp_canvas_paint_rect_internal (canvas, &rect, NULL, NULL)) {
1901             return; // aborted
1902         }
1903     }
1905     // we've had a full unaborted redraw, reset the full redraw counter
1906     if (canvas->forced_redraw_limit != -1) {
1907         canvas->forced_redraw_count = 0;
1908     }
1911 /**
1912  * Force a full redraw after a specified number of interrupted redraws
1913  */
1914 void
1915 sp_canvas_force_full_redraw_after_interruptions(SPCanvas *canvas, unsigned int count) {
1916   g_return_if_fail(canvas != NULL);
1917   
1918   canvas->forced_redraw_limit = count;
1919   canvas->forced_redraw_count = 0;
1922 /**
1923  * End forced full redraw requests
1924  */
1925 void
1926 sp_canvas_end_forced_full_redraws(SPCanvas *canvas) {
1927   g_return_if_fail(canvas != NULL);
1929   canvas->forced_redraw_limit = -1;
1932 /**
1933  * The canvas widget's expose callback.
1934  */
1935 static gint
1936 sp_canvas_expose (GtkWidget *widget, GdkEventExpose *event)
1938     SPCanvas *canvas = SP_CANVAS (widget);
1940     if (!GTK_WIDGET_DRAWABLE (widget) || 
1941         (event->window != SP_CANVAS_WINDOW (canvas)))
1942         return FALSE;
1944     int n_rects;
1945     GdkRectangle *rects;
1946     gdk_region_get_rectangles (event->region, &rects, &n_rects);
1948     for (int i = 0; i < n_rects; i++) {
1949         NRRectL rect;
1950                 
1951         rect.x0 = rects[i].x + canvas->x0;
1952         rect.y0 = rects[i].y + canvas->y0;
1953         rect.x1 = rect.x0 + rects[i].width;
1954         rect.y1 = rect.y0 + rects[i].height;
1956         sp_canvas_request_redraw (canvas, rect.x0, rect.y0, rect.x1, rect.y1);
1957     }
1959     if (n_rects > 0)
1960         g_free (rects);
1962     return FALSE;
1965 /**
1966  * The canvas widget's keypress callback.
1967  */
1968 static gint
1969 sp_canvas_key (GtkWidget *widget, GdkEventKey *event)
1971     return emit_event (SP_CANVAS (widget), (GdkEvent *) event);
1974 /**
1975  * Crossing event handler for the canvas.
1976  */
1977 static gint
1978 sp_canvas_crossing (GtkWidget *widget, GdkEventCrossing *event)
1980     SPCanvas *canvas = SP_CANVAS (widget);
1982     if (event->window != SP_CANVAS_WINDOW (canvas))
1983         return FALSE;
1985     canvas->state = event->state;
1986     return pick_current_item (canvas, (GdkEvent *) event);
1989 /**
1990  * Focus in handler for the canvas.
1991  */
1992 static gint
1993 sp_canvas_focus_in (GtkWidget *widget, GdkEventFocus *event)
1995     GTK_WIDGET_SET_FLAGS (widget, GTK_HAS_FOCUS);
1997     SPCanvas *canvas = SP_CANVAS (widget);
1999     if (canvas->focused_item) {
2000         return emit_event (canvas, (GdkEvent *) event);
2001     } else {
2002         return FALSE;
2003     }
2006 /**
2007  * Focus out handler for the canvas.
2008  */
2009 static gint
2010 sp_canvas_focus_out (GtkWidget *widget, GdkEventFocus *event)
2012     GTK_WIDGET_UNSET_FLAGS (widget, GTK_HAS_FOCUS);
2014     SPCanvas *canvas = SP_CANVAS (widget);
2016     if (canvas->focused_item)
2017         return emit_event (canvas, (GdkEvent *) event);
2018     else
2019         return FALSE;
2022 /**
2023  * Helper that repaints the areas in the canvas that need it.
2024  */
2025 static int
2026 paint (SPCanvas *canvas)
2028     if (canvas->need_update) {
2029         sp_canvas_item_invoke_update (canvas->root, NR::identity(), 0);
2030         canvas->need_update = FALSE;
2031     }
2033     if (!canvas->need_redraw)
2034         return TRUE;
2036     GtkWidget const *widget = GTK_WIDGET(canvas);
2037     int const canvas_x1 = canvas->x0 + widget->allocation.width;
2038     int const canvas_y1 = canvas->y0 + widget->allocation.height;
2040     bool dirty = false;
2042     int pl = canvas->tRight, pr = canvas->tLeft, pt = canvas->tBottom, pb = canvas->tTop; // start with "inverted" tile rect
2044     for (int j=canvas->tTop; j<canvas->tBottom; j++) { 
2045         for (int i=canvas->tLeft; i<canvas->tRight; i++) { 
2047             int tile_index = (i - canvas->tLeft) + (j - canvas->tTop)*canvas->tileH;
2049             if ( canvas->tiles[tile_index] ) { // if this tile is dirtied (nonzero)
2050                 dirty = true;
2051                 // make (pl..pr)x(pt..pb) the minimal rect covering all dirtied tiles
2052                 if ( i < pl ) pl = i;
2053                 if ( i+1 > pr ) pr = i+1;
2054                 if ( j < pt ) pt = j;
2055                 if ( j+1 > pb ) pb = j+1;
2056             }
2058             canvas->tiles[tile_index] = 0; // undirty this tile
2059         }
2060     }
2062     canvas->need_redraw = FALSE;
2063       
2064     if ( dirty ) {
2065         NRRectL topaint;
2066         topaint.x0 = MAX (pl*TILE_SIZE, canvas->x0);
2067         topaint.y0 = MAX (pt*TILE_SIZE, canvas->y0);
2068         topaint.x1 = MIN (pr*TILE_SIZE, canvas_x1);
2069         topaint.y1 = MIN (pb*TILE_SIZE, canvas_y1);
2070         if ((topaint.x0 < topaint.x1) && (topaint.y0 < topaint.y1)) {
2071             sp_canvas_paint_rect (canvas, topaint.x0, topaint.y0, topaint.x1, topaint.y1);
2072         }
2073     }
2075     return TRUE;
2078 /**
2079  * Helper that invokes update, paint, and repick on canvas.
2080  */
2081 static int
2082 do_update (SPCanvas *canvas)
2084     if (!canvas->root) // canvas may have already be destroyed by closing desktop durring interrupted display!
2085         return TRUE;
2087     /* Cause the update if necessary */
2088     if (canvas->need_update) {
2089         sp_canvas_item_invoke_update (canvas->root, NR::identity(), 0);
2090         canvas->need_update = FALSE;
2091     }
2093     /* Paint if able to */
2094     if (GTK_WIDGET_DRAWABLE (canvas)) {
2095             return paint (canvas);
2096     }
2098     /* Pick new current item */
2099     while (canvas->need_repick) {
2100         canvas->need_repick = FALSE;
2101         pick_current_item (canvas, &canvas->pick_event);
2102     }
2104     return TRUE;
2107 /**
2108  * Idle handler for the canvas that deals with pending updates and redraws.
2109  */
2110 static gint
2111 idle_handler (gpointer data)
2113     GDK_THREADS_ENTER ();
2115     SPCanvas *canvas = SP_CANVAS (data);
2117     const int ret = do_update (canvas);
2119     if (ret) {
2120         /* Reset idle id */
2121         canvas->idle_id = 0;
2122     }
2124     GDK_THREADS_LEAVE ();
2126     return !ret;
2129 /**
2130  * Convenience function to add an idle handler to a canvas.
2131  */
2132 static void
2133 add_idle (SPCanvas *canvas)
2135     if (canvas->idle_id != 0)
2136         return;
2138     canvas->idle_id = gtk_idle_add_priority (sp_canvas_update_priority, idle_handler, canvas);
2141 /**
2142  * Returns the root group of the specified canvas.
2143  */
2144 SPCanvasGroup *
2145 sp_canvas_root (SPCanvas *canvas)
2147     g_return_val_if_fail (canvas != NULL, NULL);
2148     g_return_val_if_fail (SP_IS_CANVAS (canvas), NULL);
2150     return SP_CANVAS_GROUP (canvas->root);
2153 /**
2154  * Scrolls canvas to specific position.
2155  */
2156 void
2157 sp_canvas_scroll_to (SPCanvas *canvas, double cx, double cy, unsigned int clear)
2159     g_return_if_fail (canvas != NULL);
2160     g_return_if_fail (SP_IS_CANVAS (canvas));
2162     int ix = (int) (cx + 0.5);
2163     int iy = (int) (cy + 0.5);
2164     int dx = ix - canvas->x0;
2165     int dy = iy - canvas->y0;
2167     canvas->dx0 = cx;
2168     canvas->dy0 = cy;
2169     canvas->x0 = ix;
2170     canvas->y0 = iy;
2172     sp_canvas_resize_tiles (canvas, canvas->x0, canvas->y0, canvas->x0+canvas->widget.allocation.width, canvas->y0+canvas->widget.allocation.height);
2174     if (!clear) {
2175         // scrolling without zoom; redraw only the newly exposed areas
2176         if ((dx != 0) || (dy != 0)) {
2177             is_scrolling = 1;
2178             if (GTK_WIDGET_REALIZED (canvas)) {
2179                 gdk_window_scroll (SP_CANVAS_WINDOW (canvas), -dx, -dy);
2180             }
2181         }
2182     } else {
2183         // scrolling as part of zoom; do nothing here - the next do_update will perform full redraw
2184     }
2187 /** 
2188  * Updates canvas if necessary.
2189  */
2190 void
2191 sp_canvas_update_now (SPCanvas *canvas)
2193     g_return_if_fail (canvas != NULL);
2194     g_return_if_fail (SP_IS_CANVAS (canvas));
2196     if (!(canvas->need_update ||
2197           canvas->need_redraw))
2198         return;
2200     remove_idle (canvas);
2201     do_update (canvas);
2204 /**
2205  * Update callback for canvas widget.
2206  */
2207 static void
2208 sp_canvas_request_update (SPCanvas *canvas)
2210     canvas->need_update = TRUE;
2211     add_idle (canvas);
2214 /**
2215  * Forces redraw of rectangular canvas area.
2216  */
2217 void
2218 sp_canvas_request_redraw (SPCanvas *canvas, int x0, int y0, int x1, int y1)
2220     NRRectL bbox;
2221     NRRectL visible;
2222     NRRectL clip;
2224     g_return_if_fail (canvas != NULL);
2225     g_return_if_fail (SP_IS_CANVAS (canvas));
2227     if (!GTK_WIDGET_DRAWABLE (canvas)) return;
2228     if ((x0 >= x1) || (y0 >= y1)) return;
2230     bbox.x0 = x0;
2231     bbox.y0 = y0;
2232     bbox.x1 = x1;
2233     bbox.y1 = y1;
2235     visible.x0 = canvas->x0;
2236     visible.y0 = canvas->y0;
2237     visible.x1 = visible.x0 + GTK_WIDGET (canvas)->allocation.width;
2238     visible.y1 = visible.y0 + GTK_WIDGET (canvas)->allocation.height;
2240     nr_rect_l_intersect (&clip, &bbox, &visible);
2242     sp_canvas_dirty_rect(canvas, clip.x0, clip.y0, clip.x1, clip.y1);
2243     add_idle (canvas);
2246 /**
2247  * Sets world coordinates from win and canvas.
2248  */
2249 void sp_canvas_window_to_world(SPCanvas const *canvas, double winx, double winy, double *worldx, double *worldy)
2251     g_return_if_fail (canvas != NULL);
2252     g_return_if_fail (SP_IS_CANVAS (canvas));
2254     if (worldx) *worldx = canvas->x0 + winx;
2255     if (worldy) *worldy = canvas->y0 + winy;
2258 /**
2259  * Sets win coordinates from world and canvas.
2260  */
2261 void sp_canvas_world_to_window(SPCanvas const *canvas, double worldx, double worldy, double *winx, double *winy)
2263     g_return_if_fail (canvas != NULL);
2264     g_return_if_fail (SP_IS_CANVAS (canvas));
2266     if (winx) *winx = worldx - canvas->x0;
2267     if (winy) *winy = worldy - canvas->y0;
2270 /**
2271  * Converts point from win to world coordinates.
2272  */
2273 NR::Point sp_canvas_window_to_world(SPCanvas const *canvas, NR::Point const win)
2275     g_assert (canvas != NULL);
2276     g_assert (SP_IS_CANVAS (canvas));
2278     return NR::Point(canvas->x0 + win[0], canvas->y0 + win[1]);
2281 /**
2282  * Converts point from world to win coordinates.
2283  */
2284 NR::Point sp_canvas_world_to_window(SPCanvas const *canvas, NR::Point const world)
2286     g_assert (canvas != NULL);
2287     g_assert (SP_IS_CANVAS (canvas));
2289     return NR::Point(world[0] - canvas->x0, world[1] - canvas->y0);
2292 /**
2293  * Returns true if point given in world coordinates is inside window.
2294  */
2295 bool sp_canvas_world_pt_inside_window(SPCanvas const *canvas, NR::Point const &world)
2297     g_assert( canvas != NULL );
2298     g_assert(SP_IS_CANVAS(canvas));
2300     using NR::X;
2301     using NR::Y;
2302     GtkWidget const &w = *GTK_WIDGET(canvas);
2303     return ( ( canvas->x0 <= world[X] )  &&
2304              ( canvas->y0 <= world[Y] )  &&
2305              ( world[X] < canvas->x0 + w.allocation.width )  &&
2306              ( world[Y] < canvas->y0 + w.allocation.height ) );
2309 /**
2310  * Return canvas window coordinates as NRRect.
2311  */
2312 NR::Rect SPCanvas::getViewbox() const
2314     GtkWidget const *w = GTK_WIDGET(this);
2316     return NR::Rect(NR::Point(dx0, dy0),
2317                     NR::Point(dx0 + w->allocation.width, dy0 + w->allocation.height));
2320 inline int sp_canvas_tile_floor(int x)
2322     return (x & (~(TILE_SIZE - 1))) / TILE_SIZE;
2325 inline int sp_canvas_tile_ceil(int x)
2327     return ((x + (TILE_SIZE - 1)) & (~(TILE_SIZE - 1))) / TILE_SIZE;
2330 /**
2331  * Helper that allocates a new tile array for the canvas, copying overlapping tiles from the old array
2332  */
2333 void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb)
2335     if ( nl >= nr || nt >= nb ) {
2336         if ( canvas->tiles ) g_free(canvas->tiles);
2337         canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
2338         canvas->tileH=canvas->tileV=0;
2339         canvas->tiles=NULL;
2340         return;
2341     }
2342     int tl=sp_canvas_tile_floor(nl);
2343     int tt=sp_canvas_tile_floor(nt);
2344     int tr=sp_canvas_tile_ceil(nr);
2345     int tb=sp_canvas_tile_ceil(nb);
2347     int nh = tr-tl, nv = tb-tt;
2348     uint8_t* ntiles = (uint8_t*)g_malloc(nh*nv*sizeof(uint8_t));
2349     for (int i=tl; i<tr; i++) {
2350         for (int j=tt; j<tb; j++) {
2351             int ind = (i-tl) + (j-tt)*nh;
2352             if ( i >= canvas->tLeft && i < canvas->tRight && j >= canvas->tTop && j < canvas->tBottom ) {
2353                 ntiles[ind]=canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH]; // copy from the old tile
2354             } else {
2355                 ntiles[ind]=0; // newly exposed areas get 0
2356             }
2357         }
2358     }
2359     if ( canvas->tiles ) g_free(canvas->tiles);
2360     canvas->tiles=ntiles;
2361     canvas->tLeft=tl;
2362     canvas->tTop=tt;
2363     canvas->tRight=tr;
2364     canvas->tBottom=tb;
2365     canvas->tileH=nh;
2366     canvas->tileV=nv;
2369 /**
2370  * Helper that marks specific canvas rectangle for redraw by dirtying its tiles
2371  */
2372 void sp_canvas_dirty_rect(SPCanvas* canvas,int nl,int nt,int nr,int nb)
2374     if ( nl >= nr || nt >= nb ) {
2375         return;
2376     }
2377     int tl=sp_canvas_tile_floor(nl);
2378     int tt=sp_canvas_tile_floor(nt);
2379     int tr=sp_canvas_tile_ceil(nr);
2380     int tb=sp_canvas_tile_ceil(nb);
2381     if ( tl >= canvas->tRight || tr <= canvas->tLeft || tt >= canvas->tBottom || tb <= canvas->tTop ) return;
2382     if ( tl < canvas->tLeft ) tl=canvas->tLeft;
2383     if ( tr > canvas->tRight ) tr=canvas->tRight;
2384     if ( tt < canvas->tTop ) tt=canvas->tTop;
2385     if ( tb > canvas->tBottom ) tb=canvas->tBottom;
2387     canvas->need_redraw = TRUE;
2389     for (int i=tl; i<tr; i++) {
2390         for (int j=tt; j<tb; j++) {
2391             canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH] = 1;
2392         }
2393     }
2397 /*
2398   Local Variables:
2399   mode:c++
2400   c-file-style:"stroustrup"
2401   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2402   indent-tabs-mode:nil
2403   fill-column:99
2404   End:
2405 */
2406 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :