Code

prevent freeze when window is too wide; reduce tile size to 16 for now
[inkscape.git] / src / display / sp-canvas.cpp
index b1ed7d3d23fd81537decc9e9656e17bd03b97116..57a6ac269b4e84a089ff6cf5a70002c7e37bd6d6 100644 (file)
@@ -8,9 +8,10 @@
  *   Raph Levien <raph@gimp.org>
  *   Lauris Kaplinski <lauris@kaplinski.com>
  *   fred
+ *   bbyak
  *
  * Copyright (C) 1998 The Free Software Foundation
- * Copyright (C) 2002 Lauris Kaplinski
+ * Copyright (C) 2002-2006 authors
  *
  * Released under GNU GPL, read the file 'COPYING' for more information
  */
 #include <gtk/gtkmain.h>
 #include <gtk/gtksignal.h>
 
+#include <gtkmm.h>
+
 #include <helper/sp-marshal.h>
 #include <display/sp-canvas.h>
 #include "display-forward.h"
 #include <libnr/nr-matrix-fns.h>
 #include <libnr/nr-matrix-ops.h>
 #include <libnr/nr-convex-hull.h>
+#include "prefs-utils.h"
+#include "box3d-context.h"
+#include "inkscape.h"
+#include "sodipodi-ctrlrect.h"
+
+// Define this to visualize the regions to be redrawn
+//#define DEBUG_REDRAW 1;
+
+// Tiles are a way to minimize the number of redraws, eliminating too small redraws. 
+// The canvas stores a 2D array of ints, each representing a TILE_SIZExTILE_SIZE pixels tile.
+// If any part of it is dirtied, the entire tile is dirtied (its int is nonzero) and repainted.
+#define TILE_SIZE 16
 
 enum {
        RENDERMODE_NORMAL,
@@ -188,8 +203,6 @@ sp_canvas_item_construct (SPCanvasItem *item, SPCanvasGroup *parent, const gchar
     group_add (SP_CANVAS_GROUP (item->parent), item);
 
     sp_canvas_item_request_update (item);
-    sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
-    item->canvas->need_repick = TRUE;
 }
 
 /**
@@ -199,7 +212,14 @@ static void
 redraw_if_visible (SPCanvasItem *item)
 {
     if (item->flags & SP_CANVAS_ITEM_VISIBLE) {
-        sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
+        int x0 = (int)(item->x1);
+        int x1 = (int)(item->x2);
+        int y0 = (int)(item->y1);
+        int y1 = (int)(item->y2);
+
+        if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) {
+            sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
+        }
     }
 }
 
@@ -211,7 +231,15 @@ sp_canvas_item_dispose (GObject *object)
 {
     SPCanvasItem *item = SP_CANVAS_ITEM (object);
 
-    redraw_if_visible (item);
+    // Hack: if this is a ctrlrect, move it to 0,0;
+    // this redraws only the stroke of the rect to be deleted,
+    // avoiding redraw of the entire area
+    if (SP_IS_CTRLRECT(item)) {
+        SP_CTRLRECT(object)->setRectangle(NR::Rect(NR::Point(0,0),NR::Point(0,0)));
+        SP_CTRLRECT(object)->update(item->xform, 0);
+    } else {
+        redraw_if_visible (item);
+    }
     item->flags &= ~SP_CANVAS_ITEM_VISIBLE;
 
     if (item == item->canvas->current_item) {
@@ -450,8 +478,15 @@ sp_canvas_item_show (SPCanvasItem *item)
 
     item->flags |= SP_CANVAS_ITEM_VISIBLE;
 
-    sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
-    item->canvas->need_repick = TRUE;
+    int x0 = (int)(item->x1);
+    int x1 = (int)(item->x2);
+    int y0 = (int)(item->y1);
+    int y1 = (int)(item->y2);
+
+    if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) {
+        sp_canvas_request_redraw (item->canvas, (int)(item->x1), (int)(item->y1), (int)(item->x2 + 1), (int)(item->y2 + 1));
+        item->canvas->need_repick = TRUE;
+    }
 }
 
 /**
@@ -468,8 +503,15 @@ sp_canvas_item_hide (SPCanvasItem *item)
 
     item->flags &= ~SP_CANVAS_ITEM_VISIBLE;
 
-    sp_canvas_request_redraw (item->canvas, (int)item->x1, (int)item->y1, (int)(item->x2 + 1), (int)(item->y2 + 1));
-    item->canvas->need_repick = TRUE;
+    int x0 = (int)(item->x1);
+    int x1 = (int)(item->x2);
+    int y0 = (int)(item->y1);
+    int y1 = (int)(item->y2);
+
+    if (x0 !=0 || x1 !=0 || y0 !=0 || y1 !=0) {
+        sp_canvas_request_redraw (item->canvas, (int)item->x1, (int)item->y1, (int)(item->x2 + 1), (int)(item->y2 + 1));
+        item->canvas->need_repick = TRUE;
+    }
 }
 
 /**
@@ -735,11 +777,16 @@ sp_canvas_group_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned i
         }
     }
 
-    NR::Rect const &bounds = corners.bounds();
-    item->x1 = bounds.min()[NR::X];
-    item->y1 = bounds.min()[NR::Y];
-    item->x2 = bounds.max()[NR::X];
-    item->y2 = bounds.max()[NR::Y];
+    NR::Maybe<NR::Rect> const bounds = corners.bounds();
+    if (bounds) {
+        item->x1 = bounds->min()[NR::X];
+        item->y1 = bounds->min()[NR::Y];
+        item->x2 = bounds->max()[NR::X];
+        item->y2 = bounds->max()[NR::Y];
+    } else {
+        // FIXME ?
+        item->x1 = item->x2 = item->y1 = item->y2 = 0;
+    }
 }
 
 /**
@@ -877,8 +924,10 @@ static gint sp_canvas_focus_out (GtkWidget *widget, GdkEventFocus *event);
 
 static GtkWidgetClass *canvas_parent_class;
 
-void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb);
-void sp_canvas_dirty_rect(SPCanvas* canvas,int nl,int nt,int nr,int nb);
+static void sp_canvas_resize_tiles(SPCanvas* canvas, int nl, int nt, int nr, int nb);
+static void sp_canvas_dirty_rect(SPCanvas* canvas, int nl, int nt, int nr, int nb);
+static void sp_canvas_mark_rect(SPCanvas* canvas, int nl, int nt, int nr, int nb, uint8_t val);
+static int do_update (SPCanvas *canvas);
 
 /**
  * Registers the SPCanvas class if necessary, and returns the type ID
@@ -966,6 +1015,12 @@ sp_canvas_init (SPCanvas *canvas)
     canvas->tiles=NULL;
     canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
     canvas->tileH=canvas->tileV=0;
+
+    canvas->forced_redraw_count = 0;
+    canvas->forced_redraw_limit = -1;
+
+    canvas->is_scrolling = false;
+
 }
 
 /**
@@ -994,7 +1049,7 @@ shutdown_transients (SPCanvas *canvas)
     if (canvas->need_redraw) {
         canvas->need_redraw = FALSE;
     }
-    if ( canvas->tiles ) free(canvas->tiles);
+    if ( canvas->tiles ) g_free(canvas->tiles);
     canvas->tiles=NULL;
     canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
     canvas->tileH=canvas->tileV=0;
@@ -1070,7 +1125,11 @@ sp_canvas_realize (GtkWidget *widget)
 
     widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask);
     gdk_window_set_user_data (widget->window, widget);
-    gtk_widget_set_events(widget, attributes.event_mask);
+
+    if ( prefs_get_int_attribute ("options.useextinput", "value", 1) )
+        gtk_widget_set_events(widget, attributes.event_mask);
+
+    widget->style = gtk_style_attach (widget->style, widget->window);
 
     GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
 
@@ -1254,9 +1313,12 @@ emit_event (SPCanvas *canvas, GdkEvent *event)
 static int
 pick_current_item (SPCanvas *canvas, GdkEvent *event)
 {
-    int button_down;
+    int button_down = 0;
     double x, y;
 
+    if (!canvas->root) // canvas may have already be destroyed by closing desktop durring interrupted display!
+        return FALSE;
+
     int retval = FALSE;
 
     if (canvas->gen_all_enter_events == false) {
@@ -1488,119 +1550,285 @@ sp_canvas_motion (GtkWidget *widget, GdkEventMotion *event)
     return emit_event (canvas, (GdkEvent *) event);
 }
 
-/**
- * Helper that draws a specific rectangular part of the canvas.
- */
 static void
-sp_canvas_paint_rect (SPCanvas *canvas, int xx0, int yy0, int xx1, int yy1)
+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)
 {
-    g_return_if_fail (!canvas->need_update);
-
     GtkWidget *widget = GTK_WIDGET (canvas);
 
-    int draw_x1 = MAX (xx0, canvas->x0);
-    int draw_y1 = MAX (yy0, canvas->y0);
-    int draw_x2 = MIN (xx1, canvas->x0/*draw_x1*/ + GTK_WIDGET (canvas)->allocation.width);
-    int draw_y2 = MIN (yy1, canvas->y0/*draw_y1*/ + GTK_WIDGET (canvas)->allocation.height);
+    SPCanvasBuf buf;
+    if (canvas->rendermode != RENDERMODE_OUTLINE) {
+        buf.buf = nr_pixelstore_256K_new (FALSE, 0);
+    } else {
+        buf.buf = nr_pixelstore_1M_new (FALSE, 0);
+    }
+
+    // Mark the region clean
+    sp_canvas_mark_rect(canvas, x0, y0, x1, y1, 0);
+
+    buf.buf_rowstride = sw * 3; // CAIRO FIXME: for cairo output, the buffer must be RGB unpacked, i.e. sw * 4
+    buf.rect.x0 = x0;
+    buf.rect.y0 = y0;
+    buf.rect.x1 = x1;
+    buf.rect.y1 = y1;
+    buf.visible_rect.x0 = draw_x1;
+    buf.visible_rect.y0 = draw_y1;
+    buf.visible_rect.x1 = draw_x2;
+    buf.visible_rect.y1 = draw_y2;
+    GdkColor *color = &widget->style->bg[GTK_STATE_NORMAL];
+    buf.bg_color = (((color->red & 0xff00) << 8)
+                    | (color->green & 0xff00)
+                    | (color->blue >> 8));
+    buf.is_empty = true;
+      
+    if (canvas->root->flags & SP_CANVAS_ITEM_VISIBLE) {
+        SP_CANVAS_ITEM_GET_CLASS (canvas->root)->render (canvas->root, &buf);
+    }
+      
+    if (buf.is_empty) {
+        gdk_rgb_gc_set_foreground (canvas->pixmap_gc, buf.bg_color);
+        gdk_draw_rectangle (SP_CANVAS_WINDOW (canvas),
+                            canvas->pixmap_gc,
+                            TRUE,
+                            x0 - canvas->x0, y0 - canvas->y0,
+                            x1 - x0, y1 - y0);
+    } else {
+/*
+// CAIRO FIXME: after SPCanvasBuf is made 32bpp throughout, this rgb_draw below can be replaced with the below.
+// Why this must not be done currently:
+// - all canvas items (handles, nodes etc) paint themselves assuming 24bpp
+// - cairo assumes bgra, but we have rgba, so r and b get swapped (until we paint all with cairo too)  
+// - it does not seem to be any faster; in fact since with 32bpp, buf contains less pixels, 
+// we need more bufs to paint a given area and as a result it's even a bit slower
+
+    cairo_surface_t* cst = cairo_image_surface_create_for_data (
+        buf.buf,
+        CAIRO_FORMAT_RGB24,  // unpacked, i.e. 32 bits! one byte is unused
+        x1 - x0, y1 - y0,
+        buf.buf_rowstride
+        );
+        cairo_t *ct = gdk_cairo_create(SP_CANVAS_WINDOW (canvas));
+        cairo_set_source_surface (ct, cst, x0 - canvas->x0, y0 - canvas->y0);
+        cairo_paint (ct);
+    cairo_destroy (ct);
+    cairo_surface_finish (cst);
+    cairo_surface_destroy (cst);
+*/
+
+        gdk_draw_rgb_image_dithalign (SP_CANVAS_WINDOW (canvas),
+                                      canvas->pixmap_gc,
+                                      x0 - canvas->x0, y0 - canvas->y0,
+                                      x1 - x0, y1 - y0,
+                                      GDK_RGB_DITHER_MAX,
+                                      buf.buf,
+                                      sw * 3,
+                                      x0 - canvas->x0, y0 - canvas->y0);
+    }
 
-    int bw = draw_x2 - draw_x1;
-    int bh = draw_y2 - draw_y1;
+    if (canvas->rendermode != RENDERMODE_OUTLINE) {
+        nr_pixelstore_256K_free (buf.buf);
+    } else {
+        nr_pixelstore_1M_free (buf.buf);
+    }
+}
+
+struct PaintRectSetup {
+    SPCanvas* canvas;
+    NRRectL big_rect;
+    GTimeVal start_time;
+    int max_pixels;
+    NR::Point mouse_loc;
+};
+
+/**
+ * Paint the given rect, recursively subdividing the region until it is the size of a single
+ * buffer.
+ *
+ * @return true if the drawing completes
+ */
+static int
+sp_canvas_paint_rect_internal (PaintRectSetup const *setup, NRRectL this_rect)
+{
+    GTimeVal now;
+    g_get_current_time (&now);
+
+    glong elapsed = (now.tv_sec - setup->start_time.tv_sec) * 1000000
+        + (now.tv_usec - setup->start_time.tv_usec);
+
+    // Allow only very fast buffers to be run together;
+    // as soon as the total redraw time exceeds 1ms, cancel;
+    // this returns control to the idle loop and allows Inkscape to process user input
+    // (potentially interrupting the redraw); as soon as Inkscape has some more idle time,
+    // it will get back and finish painting what remains to paint.
+    if (elapsed > 1000) {
+
+        // Interrupting redraw isn't always good.
+        // For example, when you drag one node of a big path, only the buffer containing
+        // the mouse cursor will be redrawn again and again, and the rest of the path
+        // will remain stale because Inkscape never has enough idle time to redraw all 
+        // of the screen. To work around this, such operations set a forced_redraw_limit > 0. 
+        // If this limit is set, and if we have aborted redraw more times than is allowed,
+        // interrupting is blocked and we're forced to redraw full screen once 
+        // (after which we can again interrupt forced_redraw_limit times).
+        if (setup->canvas->forced_redraw_limit < 0 || 
+            setup->canvas->forced_redraw_count < setup->canvas->forced_redraw_limit) {
+
+            if (setup->canvas->forced_redraw_limit != -1) {
+                setup->canvas->forced_redraw_count++;
+            }
+
+            return false;
+        }
+    }
+
+    // Find the optimal buffer dimensions
+    int bw = this_rect.x1 - this_rect.x0;
+    int bh = this_rect.y1 - this_rect.y0;
     if ((bw < 1) || (bh < 1))
-        return;
+        return 0;
+
+    if (bw * bh < setup->max_pixels) {
+        // We are small enough
+        sp_canvas_paint_single_buffer (setup->canvas,
+                                       this_rect.x0, this_rect.y0,
+                                       this_rect.x1, this_rect.y1,
+                                       setup->big_rect.x0, setup->big_rect.y0,
+                                       setup->big_rect.x1, setup->big_rect.y1, bw);
+        return 1;
+    }
+
+    NRRectL lo = this_rect;
+    NRRectL hi = this_rect;
 
-    int sw, sh;
-    if (canvas->rendermode != RENDERMODE_OUTLINE) { // use 256K as a compromise to not slow down gradients
-        /* 256K is the cached buffer and we need 3 channels */
-        if (bw * bh <  87381) { // 256K/3
-            // We can go with single buffer 
-            sw = bw;
-            sh = bh;
-        } else if (bw <= (16 * 341)) {
-            // Go with row buffer 
-            sw = bw;
-            sh =  87381 / bw;
-        } else if (bh <= (16 * 256)) {
-            // Go with column buffer 
-            sw = 87381 / bh;
-            sh = bh;
+/* 
+This test determines the redraw strategy: 
+
+bw < bh (strips mode) splits across the smaller dimension of the rect and therefore (on
+horizontally-stretched windows) results in redrawing in horizontal strips (from cursor point, in
+both directions if the cursor is in the middle). This is traditional for Inkscape since old days,
+and seems to be faster for drawings with many smaller objects at zoom-out.
+
+bw > bh (chunks mode) splits across the larger dimension of the rect and therefore paints in
+almost-square chunks, again from the cursor point. It's sometimes faster for drawings with few slow
+(e.g. blurred) objects crossing the entire screen. It also appears to be somewhat psychologically
+faster.
+
+The default for now is the strips mode.
+*/
+    if (bw < bh || bh < 2 * TILE_SIZE) { 
+        int mid = (this_rect.x0 + this_rect.x1) / 2;
+        // Make sure that mid lies on a tile boundary
+        mid = (mid / TILE_SIZE) * TILE_SIZE;
+
+        lo.x1 = mid;
+        hi.x0 = mid;
+
+        if (setup->mouse_loc[NR::X] < mid) {
+            // Always paint towards the mouse first
+            return sp_canvas_paint_rect_internal(setup, lo)
+                && sp_canvas_paint_rect_internal(setup, hi);
         } else {
-            sw = 341;
-            sh = 256;
+            return sp_canvas_paint_rect_internal(setup, hi)
+                && sp_canvas_paint_rect_internal(setup, lo);
         }
-    } else {  // paths only, so 1M works faster
-        /* 1M is the cached buffer and we need 3 channels */
-        if (bw * bh <  349525) { // 1M/3
-            // We can go with single buffer 
-            sw = bw;
-            sh = bh;
-        } else if (bw <= (16 * 682)) {
-            // Go with row buffer 
-            sw = bw;
-            sh =  349525 / bw;
-        } else if (bh <= (16 * 512)) {
-            // Go with column buffer 
-            sw = 349525 / bh;
-            sh = bh;
+    } else {
+        int mid = (this_rect.y0 + this_rect.y1) / 2;
+        // Make sure that mid lies on a tile boundary
+        mid = (mid / TILE_SIZE) * TILE_SIZE;
+
+        lo.y1 = mid;
+        hi.y0 = mid;
+
+        if (setup->mouse_loc[NR::Y] < mid) {
+            // Always paint towards the mouse first
+            return sp_canvas_paint_rect_internal(setup, lo)
+                && sp_canvas_paint_rect_internal(setup, hi);
         } else {
-            sw = 682;
-            sh = 512;
+            return sp_canvas_paint_rect_internal(setup, hi)
+                && sp_canvas_paint_rect_internal(setup, lo);
         }
     }
+}
 
-    // As we can come from expose, we have to tile here 
-    for (int y0 = draw_y1; y0 < draw_y2; y0 += sh) {
-        int y1 = MIN (y0 + sh, draw_y2);
-        for (int x0 = draw_x1; x0 < draw_x2; x0 += sw) {
-            int x1 = MIN (x0 + sw, draw_x2);
-
-            SPCanvasBuf buf;
-       if (canvas->rendermode != RENDERMODE_OUTLINE) {
-            buf.buf = nr_pixelstore_256K_new (FALSE, 0);
-  } else {
-            buf.buf = nr_pixelstore_1M_new (FALSE, 0);
-  }
-
-            buf.buf_rowstride = sw * 3;
-            buf.rect.x0 = x0;
-            buf.rect.y0 = y0;
-            buf.rect.x1 = x1;
-            buf.rect.y1 = y1;
-            GdkColor *color = &widget->style->bg[GTK_STATE_NORMAL];
-            buf.bg_color = (((color->red & 0xff00) << 8)
-                            | (color->green & 0xff00)
-                            | (color->blue >> 8));
-            buf.is_empty = true;
-      
-            if (canvas->root->flags & SP_CANVAS_ITEM_VISIBLE) {
-                SP_CANVAS_ITEM_GET_CLASS (canvas->root)->render (canvas->root, &buf);
-            }
-      
-            if (buf.is_empty) {
-                gdk_rgb_gc_set_foreground (canvas->pixmap_gc, buf.bg_color);
-                gdk_draw_rectangle (SP_CANVAS_WINDOW (canvas),
-                                    canvas->pixmap_gc,
-                                    TRUE,
-                                    x0 - canvas->x0, y0 - canvas->y0,
-                                    x1 - x0, y1 - y0);
-            } else {
-                gdk_draw_rgb_image_dithalign (SP_CANVAS_WINDOW (canvas),
-                                              canvas->pixmap_gc,
-                                              x0 - canvas->x0, y0 - canvas->y0,
-                                              x1 - x0, y1 - y0,
-                                              GDK_RGB_DITHER_MAX,
-                                              buf.buf,
-                                              sw * 3,
-                                              x0 - canvas->x0, y0 - canvas->y0);
-            }
-
-       if (canvas->rendermode != RENDERMODE_OUTLINE) {
-            nr_pixelstore_256K_free (buf.buf);
-  } else {
-            nr_pixelstore_1M_free (buf.buf);
-  }
 
-        }
+/**
+ * Helper that draws a specific rectangular part of the canvas.
+ *
+ * @return true if the rectangle painting succeeds.
+ */
+static bool
+sp_canvas_paint_rect (SPCanvas *canvas, int xx0, int yy0, int xx1, int yy1)
+{
+    g_return_val_if_fail (!canvas->need_update, false);
+    NRRectL rect;
+    rect.x0 = xx0;
+    rect.x1 = xx1;
+    rect.y0 = yy0;
+    rect.y1 = yy1;
+
+    // Clip rect-to-draw by the current visible area
+    rect.x0 = MAX (rect.x0, canvas->x0);
+    rect.y0 = MAX (rect.y0, canvas->y0);
+    rect.x1 = MIN (rect.x1, canvas->x0/*draw_x1*/ + GTK_WIDGET (canvas)->allocation.width);
+    rect.y1 = MIN (rect.y1, canvas->y0/*draw_y1*/ + GTK_WIDGET (canvas)->allocation.height);
+
+#ifdef DEBUG_REDRAW
+    // paint the area to redraw yellow
+    gdk_rgb_gc_set_foreground (canvas->pixmap_gc, 0xFFFF00);
+    gdk_draw_rectangle (SP_CANVAS_WINDOW (canvas),
+                            canvas->pixmap_gc,
+                            TRUE,
+                            rect.x0 - canvas->x0, rect.y0 - canvas->y0,
+                                             rect.x1 - rect.x0, rect.y1 - rect.y0);
+#endif                     
+
+    PaintRectSetup setup;
+
+    setup.canvas = canvas;
+    setup.big_rect = rect;
+
+    // Save the mouse location
+    gint x, y;
+    gdk_window_get_pointer (GTK_WIDGET(canvas)->window, &x, &y, NULL);
+    setup.mouse_loc = sp_canvas_window_to_world (canvas, NR::Point(x,y));
+
+    // CAIRO FIXME: the sw/sh calculations below all assume 24bpp, need fixing for 32bpp
+    if (canvas->rendermode != RENDERMODE_OUTLINE) {
+        // use 256K as a compromise to not slow down gradients
+        // 256K is the cached buffer and we need 3 channels
+        setup.max_pixels = 87381; // 256K/3
+    } else {
+        // paths only, so 1M works faster
+        // 1M is the cached buffer and we need 3 channels
+        setup.max_pixels = 349525;
     }
+
+    // Start the clock
+    g_get_current_time(&(setup.start_time));
+
+    // Go
+    return sp_canvas_paint_rect_internal(&setup, rect);
+}
+
+/**
+ * Force a full redraw after a specified number of interrupted redraws
+ */
+void
+sp_canvas_force_full_redraw_after_interruptions(SPCanvas *canvas, unsigned int count) {
+  g_return_if_fail(canvas != NULL);
+  
+  canvas->forced_redraw_limit = count;
+  canvas->forced_redraw_count = 0;
+}
+
+/**
+ * End forced full redraw requests
+ */
+void
+sp_canvas_end_forced_full_redraws(SPCanvas *canvas) {
+  g_return_if_fail(canvas != NULL);
+
+  canvas->forced_redraw_limit = -1;
 }
 
 /**
@@ -1627,12 +1855,7 @@ sp_canvas_expose (GtkWidget *widget, GdkEventExpose *event)
         rect.x1 = rect.x0 + rects[i].width;
         rect.y1 = rect.y0 + rects[i].height;
 
-        if (canvas->need_update || canvas->need_redraw) {
-            sp_canvas_request_redraw (canvas, rect.x0, rect.y0, rect.x1, rect.y1);
-        } else {
-            /* No pending updates, draw exposed area immediately */
-            sp_canvas_paint_rect (canvas, rect.x0, rect.y0, rect.x1, rect.y1);
-        }
+        sp_canvas_request_redraw (canvas, rect.x0, rect.y0, rect.x1, rect.y1);
     }
 
     if (n_rects > 0)
@@ -1700,6 +1923,8 @@ sp_canvas_focus_out (GtkWidget *widget, GdkEventFocus *event)
 
 /**
  * Helper that repaints the areas in the canvas that need it.
+ *
+ * @return true if all the dirty parts have been redrawn
  */
 static int
 paint (SPCanvas *canvas)
@@ -1712,48 +1937,42 @@ paint (SPCanvas *canvas)
     if (!canvas->need_redraw)
         return TRUE;
 
-    GtkWidget const *widget = GTK_WIDGET(canvas);
-    int const canvas_x1 = canvas->x0 + widget->allocation.width;
-    int const canvas_y1 = canvas->y0 + widget->allocation.height;
+    Gdk::Region to_paint;
 
-    NRRectL topaint;
-    topaint.x0 = topaint.y0 = topaint.x1 = topaint.y1 = 0;
+    for (int j=canvas->tTop; j<canvas->tBottom; j++) { 
+        for (int i=canvas->tLeft; i<canvas->tRight; i++) { 
+            int tile_index = (i - canvas->tLeft) + (j - canvas->tTop)*canvas->tileH;
 
-    for (int j=canvas->tTop&(~3);j<canvas->tBottom;j+=4) {
-        for (int i=canvas->tLeft&(~3);i<canvas->tRight;i+=4) {
-            int  mode=0;
-      
-            int pl=i+1,pr=i,pt=j+4,pb=j;
-            for (int l=MAX(j,canvas->tTop);l<MIN(j+4,canvas->tBottom);l++) {
-                for (int k=MAX(i,canvas->tLeft);k<MIN(i+4,canvas->tRight);k++) {
-                    if ( canvas->tiles[(k-canvas->tLeft)+(l-canvas->tTop)*canvas->tileH] ) {
-                        mode|=1<<((k-i)+(l-j)*4);
-                        if ( k < pl ) pl=k;
-                        if ( k+1 > pr ) pr=k+1;
-                        if ( l < pt ) pt=l;
-                        if ( l+1 > pb ) pb=l+1;
-                    }
-                    canvas->tiles[(k-canvas->tLeft)+(l-canvas->tTop)*canvas->tileH]=0;
-                }
+            if ( canvas->tiles[tile_index] ) { // if this tile is dirtied (nonzero)
+                to_paint.union_with_rect(Gdk::Rectangle(i*TILE_SIZE, j*TILE_SIZE,
+                                   TILE_SIZE, TILE_SIZE));
             }
-      
-            if ( mode ) {
-                NRRectL tile;
-                tile.x0 = MAX (pl*32, canvas->x0);
-                tile.y0 = MAX (pt*32, canvas->y0);
-                tile.x1 = MIN (pr*32, canvas_x1);
-                tile.y1 = MIN (pb*32, canvas_y1);
-                if ((tile.x0 < tile.x1) && (tile.y0 < tile.y1)) {
-                    nr_rect_l_union (&topaint, &topaint, &tile);
-                }
 
-            }
         }
     }
 
-    sp_canvas_paint_rect (canvas, topaint.x0, topaint.y0, topaint.x1, topaint.y1);
+    if (!to_paint.empty()) {
+        Glib::ArrayHandle<Gdk::Rectangle> rect = to_paint.get_rectangles();
+        typedef Glib::ArrayHandle<Gdk::Rectangle>::const_iterator Iter;
+        for (Iter i=rect.begin(); i != rect.end(); ++i) {
+            int x0 = (*i).get_x();
+            int y0 = (*i).get_y();
+            int x1 = x0 + (*i).get_width();
+            int y1 = y0 + (*i).get_height();
+            if (!sp_canvas_paint_rect(canvas, x0, y0, x1, y1)) {
+                // Aborted
+                return FALSE;
+            };
+        }
+    }
 
     canvas->need_redraw = FALSE;
+
+    // we've had a full unaborted redraw, reset the full redraw counter
+    if (canvas->forced_redraw_limit != -1) {
+        canvas->forced_redraw_count = 0;
+    }
+
     return TRUE;
 }
 
@@ -1763,6 +1982,9 @@ paint (SPCanvas *canvas)
 static int
 do_update (SPCanvas *canvas)
 {
+    if (!canvas->root) // canvas may have already be destroyed by closing desktop durring interrupted display!
+        return TRUE;
+
     /* Cause the update if necessary */
     if (canvas->need_update) {
         sp_canvas_item_invoke_update (canvas->root, NR::identity(), 0);
@@ -1833,7 +2055,7 @@ sp_canvas_root (SPCanvas *canvas)
  * Scrolls canvas to specific position.
  */
 void
-sp_canvas_scroll_to (SPCanvas *canvas, double cx, double cy, unsigned int clear)
+sp_canvas_scroll_to (SPCanvas *canvas, double cx, double cy, unsigned int clear, bool is_scrolling)
 {
     g_return_if_fail (canvas != NULL);
     g_return_if_fail (SP_IS_CANVAS (canvas));
@@ -1848,32 +2070,28 @@ sp_canvas_scroll_to (SPCanvas *canvas, double cx, double cy, unsigned int clear)
     canvas->x0 = ix;
     canvas->y0 = iy;
 
-    sp_canvas_resize_tiles(canvas,canvas->x0,canvas->y0,canvas->x0+canvas->widget.allocation.width,canvas->y0+canvas->widget.allocation.height);
+    sp_canvas_resize_tiles (canvas, canvas->x0, canvas->y0, canvas->x0+canvas->widget.allocation.width, canvas->y0+canvas->widget.allocation.height);
 
     if (!clear) {
         // scrolling without zoom; redraw only the newly exposed areas
         if ((dx != 0) || (dy != 0)) {
-            int width, height;
-            width = canvas->widget.allocation.width;
-            height = canvas->widget.allocation.height;
+            canvas->is_scrolling = is_scrolling;
             if (GTK_WIDGET_REALIZED (canvas)) {
                 gdk_window_scroll (SP_CANVAS_WINDOW (canvas), -dx, -dy);
-                gdk_window_process_updates (SP_CANVAS_WINDOW (canvas), TRUE);
-            }
-            if (dx < 0) {
-                sp_canvas_request_redraw (canvas, ix + 0, iy + 0, ix - dx, iy + height);
-            } else if (dx > 0) {
-                sp_canvas_request_redraw (canvas, ix + width - dx, iy + 0, ix + width, iy + height);
-            }
-            if (dy < 0) {
-                sp_canvas_request_redraw (canvas, ix + 0, iy + 0, ix + width, iy - dy);
-            } else if (dy > 0) {
-                sp_canvas_request_redraw (canvas, ix + 0, iy + height - dy, ix + width, iy + height);
             }
         }
     } else {
         // scrolling as part of zoom; do nothing here - the next do_update will perform full redraw
     }
+
+    /*  update perspective lines if we are in the 3D box tool (so that infinite ones are shown correctly) */
+    SPEventContext *ec = inkscape_active_event_context();
+    if (SP_IS_3DBOX_CONTEXT (ec)) {
+        // We could avoid redraw during panning by checking the status of is_scrolling, but this is
+        // neither faster nor does it get rid of artefacts, so we update PLs unconditionally
+        SP3DBoxContext *bc = SP_3DBOX_CONTEXT (ec);
+        bc->_vpdrag->updateLines();
+    }
 }
 
 /** 
@@ -1889,7 +2107,6 @@ sp_canvas_update_now (SPCanvas *canvas)
           canvas->need_redraw))
         return;
 
-    remove_idle (canvas);
     do_update (canvas);
 }
 
@@ -1931,7 +2148,7 @@ sp_canvas_request_redraw (SPCanvas *canvas, int x0, int y0, int x1, int y1)
 
     nr_rect_l_intersect (&clip, &bbox, &visible);
 
-    sp_canvas_dirty_rect(canvas,x0,y0,x1,y1);
+    sp_canvas_dirty_rect(canvas, clip.x0, clip.y0, clip.x1, clip.y1);
     add_idle (canvas);
 }
 
@@ -1999,7 +2216,7 @@ bool sp_canvas_world_pt_inside_window(SPCanvas const *canvas, NR::Point const &w
 }
 
 /**
- * Return canvas window coordinates as NRRect.
+ * Return canvas window coordinates as NR::Rect.
  */
 NR::Rect SPCanvas::getViewbox() const
 {
@@ -2011,21 +2228,21 @@ NR::Rect SPCanvas::getViewbox() const
 
 inline int sp_canvas_tile_floor(int x)
 {
-    return (x&(~31))/32;
+    return (x & (~(TILE_SIZE - 1))) / TILE_SIZE;
 }
 
 inline int sp_canvas_tile_ceil(int x)
 {
-    return ((x+31)&(~31))/32;
+    return ((x + (TILE_SIZE - 1)) & (~(TILE_SIZE - 1))) / TILE_SIZE;
 }
 
 /**
- * Helper that changes tile size for canvas redraw.
+ * Helper that allocates a new tile array for the canvas, copying overlapping tiles from the old array
  */
-void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb)
+static void sp_canvas_resize_tiles(SPCanvas* canvas, int nl, int nt, int nr, int nb)
 {
     if ( nl >= nr || nt >= nb ) {
-        if ( canvas->tiles ) free(canvas->tiles);
+        if ( canvas->tiles ) g_free(canvas->tiles);
         canvas->tLeft=canvas->tTop=canvas->tRight=canvas->tBottom=0;
         canvas->tileH=canvas->tileV=0;
         canvas->tiles=NULL;
@@ -2036,19 +2253,19 @@ void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb)
     int tr=sp_canvas_tile_ceil(nr);
     int tb=sp_canvas_tile_ceil(nb);
 
-    int nh=tr-tl,nv=tb-tt;
-    uint8_t* ntiles=(uint8_t*)malloc(nh*nv*sizeof(uint8_t));
-    for (int i=tl;i<tr;i++) {
-        for (int j=tt;j<tb;j++) {
-            int ind=(i-tl)+(j-tt)*nh;
+    int nh = tr-tl, nv = tb-tt;
+    uint8_t* ntiles = (uint8_t*)g_malloc(nh*nv*sizeof(uint8_t));
+    for (int i=tl; i<tr; i++) {
+        for (int j=tt; j<tb; j++) {
+            int ind = (i-tl) + (j-tt)*nh;
             if ( i >= canvas->tLeft && i < canvas->tRight && j >= canvas->tTop && j < canvas->tBottom ) {
-                ntiles[ind]=canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH];
+                ntiles[ind]=canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH]; // copy from the old tile
             } else {
-                ntiles[ind]=0;
+                ntiles[ind]=0; // newly exposed areas get 0
             }
         }
     }
-    if ( canvas->tiles ) free(canvas->tiles);
+    if ( canvas->tiles ) g_free(canvas->tiles);
     canvas->tiles=ntiles;
     canvas->tLeft=tl;
     canvas->tTop=tt;
@@ -2058,10 +2275,19 @@ void sp_canvas_resize_tiles(SPCanvas* canvas,int nl,int nt,int nr,int nb)
     canvas->tileV=nv;
 }
 
+/*
+ * Helper that queues a canvas rectangle for redraw
+ */
+static void sp_canvas_dirty_rect(SPCanvas* canvas, int nl, int nt, int nr, int nb) {
+    canvas->need_redraw = TRUE;
+
+    sp_canvas_mark_rect(canvas, nl, nt, nr, nb, 1);
+}
+
 /**
- * Helper that marks specific canvas rectangle for redraw.
+ * Helper that marks specific canvas rectangle as clean (val == 0) or dirty (otherwise)
  */
-void sp_canvas_dirty_rect(SPCanvas* canvas,int nl,int nt,int nr,int nb)
+void sp_canvas_mark_rect(SPCanvas* canvas, int nl, int nt, int nr, int nb, uint8_t val)
 {
     if ( nl >= nr || nt >= nb ) {
         return;
@@ -2076,11 +2302,9 @@ void sp_canvas_dirty_rect(SPCanvas* canvas,int nl,int nt,int nr,int nb)
     if ( tt < canvas->tTop ) tt=canvas->tTop;
     if ( tb > canvas->tBottom ) tb=canvas->tBottom;
 
-    canvas->need_redraw = TRUE;
-
-    for (int i=tl;i<tr;i++) {
-        for (int j=tt;j<tb;j++) {
-            canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH]=1;
+    for (int i=tl; i<tr; i++) {
+        for (int j=tt; j<tb; j++) {
+            canvas->tiles[(i-canvas->tLeft)+(j-canvas->tTop)*canvas->tileH] = val;
         }
     }
 }