Code

Fixed array index calculation
[inkscape.git] / src / widgets / icon.cpp
1 /** \file
2  * SPIcon: Generic icon widget
3  */
4 /*
5  * Author:
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *   Jon A. Cruz <jon@joncruz.org>
8  *
9  * Copyright (C) 2002 Lauris Kaplinski
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17 #include "path-prefix.h"
21 #include <gtk/gtkiconfactory.h>
22 #include <gtk/gtkstock.h>
23 #include <gtk/gtkimage.h>
25 #include <gtkmm/image.h>
27 #include "prefs-utils.h"
28 #include "inkscape.h"
29 #include "document.h"
30 #include "sp-item.h"
31 #include "display/nr-arena.h"
32 #include "display/nr-arena-item.h"
33 #include "io/sys.h"
35 #include "icon.h"
37 static gboolean icon_prerender_task(gpointer data);
39 static void addPreRender( Inkscape::IconSize lsize, gchar const *name );
41 static void sp_icon_class_init(SPIconClass *klass);
42 static void sp_icon_init(SPIcon *icon);
43 static void sp_icon_destroy(GtkObject *object);
45 static void sp_icon_reset(SPIcon *icon);
46 static void sp_icon_clear(SPIcon *icon);
48 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
49 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
50 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
52 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
54 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
55 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
56 static void sp_icon_theme_changed( SPIcon *icon );
58 static guchar *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
59 static guchar *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize);
61 static guchar *sp_icon_image_load(SPIcon *icon, gchar const *name);
63 static int sp_icon_get_phys_size(int size);
65 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
66                                     unsigned r, unsigned g, unsigned b );
68 static void injectCustomSize();
70 static GtkWidgetClass *parent_class;
72 static bool sizeDirty = true;
74 static bool sizeMapDone = false;
75 static GtkIconSize iconSizeLookup[] = {
76     GTK_ICON_SIZE_INVALID,
77     GTK_ICON_SIZE_MENU,
78     GTK_ICON_SIZE_SMALL_TOOLBAR,
79     GTK_ICON_SIZE_LARGE_TOOLBAR,
80     GTK_ICON_SIZE_BUTTON,
81     GTK_ICON_SIZE_DND,
82     GTK_ICON_SIZE_DIALOG,
83     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
84 };
86 GtkType
87 sp_icon_get_type()
88 {
89     static GtkType type = 0;
90     if (!type) {
91         GtkTypeInfo info = {
92             "SPIcon",
93             sizeof(SPIcon),
94             sizeof(SPIconClass),
95             (GtkClassInitFunc) sp_icon_class_init,
96             (GtkObjectInitFunc) sp_icon_init,
97             NULL, NULL, NULL
98         };
99         type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
100     }
101     return type;
104 static void
105 sp_icon_class_init(SPIconClass *klass)
107     GtkObjectClass *object_class;
108     GtkWidgetClass *widget_class;
110     object_class = (GtkObjectClass *) klass;
111     widget_class = (GtkWidgetClass *) klass;
113     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
115     object_class->destroy = sp_icon_destroy;
117     widget_class->size_request = sp_icon_size_request;
118     widget_class->size_allocate = sp_icon_size_allocate;
119     widget_class->expose_event = sp_icon_expose;
120     widget_class->screen_changed = sp_icon_screen_changed;
121     widget_class->style_set = sp_icon_style_set;
125 static void
126 sp_icon_init(SPIcon *icon)
128     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
129     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
130     icon->psize = 0;
131     icon->name = 0;
132     icon->pb = 0;
133     icon->pb_faded = 0;
136 static void
137 sp_icon_destroy(GtkObject *object)
139     SPIcon *icon = SP_ICON(object);
140     sp_icon_clear(icon);
141     if ( icon->name ) {
142         g_free( icon->name );
143         icon->name = 0;
144     }
146     ((GtkObjectClass *) (parent_class))->destroy(object);
149 static void sp_icon_reset( SPIcon *icon ) {
150     icon->psize = 0;
151     sp_icon_clear(icon);
154 static void sp_icon_clear( SPIcon *icon ) {
155     if (icon->pb) {
156         g_object_unref(G_OBJECT(icon->pb));
157         icon->pb = NULL;
158     }
159     if (icon->pb_faded) {
160         g_object_unref(G_OBJECT(icon->pb_faded));
161         icon->pb_faded = NULL;
162     }
165 static void
166 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
168     SPIcon const *icon = SP_ICON(widget);
170     int const size = ( icon->psize
171                        ? icon->psize
172                        : sp_icon_get_phys_size(icon->lsize) );
173     requisition->width = size;
174     requisition->height = size;
177 static void
178 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
180     widget->allocation = *allocation;
182     if (GTK_WIDGET_DRAWABLE(widget)) {
183         gtk_widget_queue_draw(widget);
184     }
187 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
189     if ( GTK_WIDGET_DRAWABLE(widget) ) {
190         SPIcon *icon = SP_ICON(widget);
191         if ( !icon->pb ) {
192             guchar *pixels = 0;
194             icon->psize = sp_icon_get_phys_size(icon->lsize);
196             pixels = sp_icon_image_load( icon, icon->name );
198             if (pixels) {
199                 // don't pass the nr_free because we're caching the pixel
200                 // space loaded through ...
201                 // I just changed this. make sure sp_icon_image_load still does the right thing.
202                 icon->pb = gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, TRUE, 8,
203                                                     icon->psize, icon->psize, icon->psize * 4,
204                                                     /*(GdkPixbufDestroyNotify)nr_free*/NULL, NULL);
205                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
207                 pixels = gdk_pixbuf_get_pixels(icon->pb_faded);
208                 size_t stride = gdk_pixbuf_get_rowstride(icon->pb_faded);
209                 pixels += 3; // alpha
210                 for ( int row = 0 ; row < icon->psize ; row++ ) {
211                     guchar *row_pixels = pixels;
212                     for ( int column = 0 ; column < icon->psize ; column++ ) {
213                         *row_pixels = *row_pixels >> 1;
214                         row_pixels += 4;
215                     }
216                     pixels += stride;
217                 }
218             } else {
219                 /* TODO: We should do something more useful if we can't load the image. */
220                 g_warning ("failed to load icon '%s'", icon->name);
221             }
222         }
224         sp_icon_paint(SP_ICON(widget), &event->area);
225     }
227     return TRUE;
231 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
233     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
234         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
235     }
236     SPIcon *icon = SP_ICON(widget);
237     sp_icon_theme_changed(icon);
240 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
242     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
243         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
244     }
245     SPIcon *icon = SP_ICON(widget);
246     sp_icon_theme_changed(icon);
249 static void sp_icon_theme_changed( SPIcon *icon )
251     //g_message("Got a change bump for this icon");
252     sizeDirty = true;
253     sp_icon_reset(icon);
254     gtk_widget_queue_draw( GTK_WIDGET(icon) );
258 static GtkWidget *
259 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
261     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
262     static gint fallback = prefs_get_int_attribute_limited( "debug.icons", "checkNames", 0, 0, 1 );
264     addPreRender( lsize, name );
266     GtkStockItem stock;
267     gboolean tryLoad = gtk_stock_lookup( name, &stock );
268     if ( !tryLoad && fallback ) {
269         tryLoad |= strncmp("gtk-", name, 4 ) == 0;
270     }
271     if ( !tryLoad && fallback ) {
272         tryLoad |= strncmp("gnome-", name, 6 ) == 0;
273     }
275     GtkWidget *widget = 0;
276     if ( tryLoad ) {
277         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
279         if ( !sizeMapDone ) {
280             injectCustomSize();
281         }
283         GtkWidget *img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
284         if ( img ) {
285             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
286             if ( type == GTK_IMAGE_STOCK ) {
287                 widget = GTK_WIDGET(img);
288                 img = 0;
290                 if ( dump ) {
291                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK)", name, lsize );
292                 }
293             } else {
294                 if ( dump ) {
295                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
296                 }
297                 g_object_unref( (GObject *)img );
298                 img = 0;
299             }
300         }
301     }
303     if ( !widget ) {
304         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
305         icon->lsize = lsize;
306         icon->name = g_strdup(name);
307         icon->psize = sp_icon_get_phys_size(lsize);
309         widget = GTK_WIDGET(icon);
310     }
312     return widget;
315 GtkWidget *
316 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
318     return sp_icon_new_full( lsize, name );
321 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
323     Gtk::Widget *result = 0;
324     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
326     if ( widget ) {
327         if ( GTK_IS_IMAGE(widget) ) {
328             GtkImage *img = GTK_IMAGE(widget);
329             result = Glib::wrap( img );
330         } else {
331             result = Glib::wrap( widget );
332         }
333     }
335     return result;
338 // Try to load the named svg, falling back to pixmaps
339 guchar *
340 sp_icon_image_load( SPIcon *icon, gchar const *name )
342     guchar *px = sp_icon_image_load_svg( name, icon->lsize, icon->psize );
343     if (!px) {
344         px = sp_icon_image_load_pixmap(name, icon->lsize, icon->psize);
345     }
347     return px;
350 GtkIconSize
351 sp_icon_get_gtk_size(int size)
353     static GtkIconSize map[64] = {(GtkIconSize)0};
354     size = CLAMP(size, 4, 63);
355     if (!map[size]) {
356         static int count = 0;
357         char c[64];
358         g_snprintf(c, 64, "InkscapeIcon%d", count++);
359         map[size] = gtk_icon_size_register(c, size, size);
360     }
361     return map[size];
364 static void injectCustomSize()
366     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
367     if ( !sizeMapDone )
368     {
369         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
370         gint width = 0;
371         gint height = 0;
372         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
373             gint newWidth = (width > 18) ? (width / 2) : ((width * 2) / 3);
374             gint newHeight = (height > 18) ? (height / 2) : ((height * 2) / 3);
375             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
376             if ( newSizeEnum ) {
377                 if ( dump ) {
378                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
379                 }
380                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
381                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
382                     iconSizeLookup[index] = newSizeEnum;
383                 } else if ( dump ) {
384                     g_message("size lookup array too small to store entry");
385                 }
386             }
387         }
388         sizeMapDone = true;
389     }
393 static int sp_icon_get_phys_size(int size)
395     static bool init = false;
396     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
397     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
399     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
401     if ( !sizeMapDone ) {
402         injectCustomSize();
403     }
405     if ( sizeDirty && init ) {
406         GtkIconSize const gtkSizes[] = {
407             GTK_ICON_SIZE_MENU,
408             GTK_ICON_SIZE_SMALL_TOOLBAR,
409             GTK_ICON_SIZE_LARGE_TOOLBAR,
410             GTK_ICON_SIZE_BUTTON,
411             GTK_ICON_SIZE_DND,
412             GTK_ICON_SIZE_DIALOG,
413             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
414                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
415                 GTK_ICON_SIZE_MENU
416         };
417         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
418             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
420             g_assert( val_ix < G_N_ELEMENTS(vals) );
422             gint width = 0;
423             gint height = 0;
424             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
425                 init &= (lastSys[val_ix] == std::max(width, height));
426             }
427         }
428     }
430     if ( !init ) {
431         sizeDirty = false;
432         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
434         if ( dump ) {
435             g_message( "Default icon sizes:" );
436         }
437         memset( vals, 0, sizeof(vals) );
438         memset( lastSys, 0, sizeof(lastSys) );
439         GtkIconSize const gtkSizes[] = {
440             GTK_ICON_SIZE_MENU,
441             GTK_ICON_SIZE_SMALL_TOOLBAR,
442             GTK_ICON_SIZE_LARGE_TOOLBAR,
443             GTK_ICON_SIZE_BUTTON,
444             GTK_ICON_SIZE_DND,
445             GTK_ICON_SIZE_DIALOG,
446             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
447                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
448                 GTK_ICON_SIZE_MENU
449         };
450         gchar const *const names[] = {
451             "GTK_ICON_SIZE_MENU",
452             "GTK_ICON_SIZE_SMALL_TOOLBAR",
453             "GTK_ICON_SIZE_LARGE_TOOLBAR",
454             "GTK_ICON_SIZE_BUTTON",
455             "GTK_ICON_SIZE_DND",
456             "GTK_ICON_SIZE_DIALOG",
457             "inkscape-decoration"
458         };
460         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
462         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
463             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
465             g_assert( val_ix < G_N_ELEMENTS(vals) );
467             gint width = 0;
468             gint height = 0;
469             bool used = false;
470             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
471                 vals[val_ix] = std::max(width, height);
472                 lastSys[val_ix] = vals[val_ix];
473                 used = true;
474             }
475             if (dump) {
476                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
477                           i, gtkSizes[i],
478                           ( used ? ' ' : 'X' ), width, height, names[i]);
479             }
480             gchar const *id = GTK_STOCK_OPEN;
481             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
482             if (pb) {
483                 width = gdk_pixbuf_get_width(pb);
484                 height = gdk_pixbuf_get_height(pb);
485                 int newSize = std::max( width, height );
486                 // TODO perhaps check a few more stock icons to get a range on sizes.
487                 if ( newSize > 0 ) {
488                     vals[val_ix] = newSize;
489                 }
490                 if (dump) {
491                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
492                 }
494                 g_object_unref(G_OBJECT(pb));
495             }
496         }
497         //g_object_unref(icon);
498         init = true;
499     }
501     return vals[size];
504 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
506     GtkWidget &widget = *GTK_WIDGET(icon);
508     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
510     if (image) {
511         int const padx = ( ( widget.allocation.width > icon->psize )
512                            ? ( widget.allocation.width - icon->psize ) / 2
513                            : 0 );
514         int const pady = ( ( widget.allocation.height > icon->psize )
515                            ? ( widget.allocation.height - icon->psize ) / 2
516                            : 0 );
518         int const x0 = std::max(area->x, widget.allocation.x + padx);
519         int const y0 = std::max(area->y, widget.allocation.y + pady);
520         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
521         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
523         gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
524                         x0 - widget.allocation.x - padx,
525                         y0 - widget.allocation.y - pady,
526                         x0, y0,
527                         x1 - x0, y1 - y0,
528                         GDK_RGB_DITHER_NORMAL, x0, y0);
529     }
532 static guchar *
533 sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize)
535     gchar *path;
536     guchar *px;
537     GdkPixbuf *pb;
539     path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
540     // TODO: bulia, please look over
541     gsize bytesRead = 0;
542     gsize bytesWritten = 0;
543     GError *error = NULL;
544     gchar *localFilename = g_filename_from_utf8( path,
545                                                  -1,
546                                                  &bytesRead,
547                                                  &bytesWritten,
548                                                  &error);
549     pb = gdk_pixbuf_new_from_file(localFilename, NULL);
550     g_free(localFilename);
551     g_free(path);
552     if (!pb) {
553         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
554         // TODO: bulia, please look over
555         gsize bytesRead = 0;
556         gsize bytesWritten = 0;
557         GError *error = NULL;
558         gchar *localFilename = g_filename_from_utf8( path,
559                                                      -1,
560                                                      &bytesRead,
561                                                      &bytesWritten,
562                                                      &error);
563         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
564         g_free(localFilename);
565         g_free(path);
566     }
567     if (pb) {
568         if (!gdk_pixbuf_get_has_alpha(pb))
569             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
570         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
571              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
572             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
573             g_object_unref(G_OBJECT(pb));
574             pb = spb;
575         }
576         guchar *spx = gdk_pixbuf_get_pixels(pb);
577         int srs = gdk_pixbuf_get_rowstride(pb);
578         px = nr_new(guchar, 4 * psize * psize);
579         for (unsigned y = 0; y < psize; y++) {
580             memcpy(px + 4 * y * psize, spx + y * srs, 4 * psize);
581         }
582         g_object_unref(G_OBJECT(pb));
584         return px;
585     }
587     return NULL;
590 // takes doc, root, icon, and icon name to produce pixels
591 extern "C" guchar *
592 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
593                   gchar const *name, unsigned psize )
595     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
596     guchar *px = NULL;
598     if (doc) {
599         SPObject *object = doc->getObjectById(name);
600         if (object && SP_IS_ITEM(object)) {
601             /* Find bbox in document */
602             NR::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
603             NR::Rect dbox = SP_ITEM(object)->invokeBbox(i2doc);
605             if ( SP_OBJECT_PARENT(object) == NULL )
606             {
607                 dbox = NR::Rect(NR::Point(0, 0),
608                                 NR::Point(sp_document_width(doc), sp_document_height(doc)));
609             }
611             /* This is in document coordinates, i.e. pixels */
612             if (dbox.isEmpty() == false) {
613                 NRGC gc(NULL);
614                 /* Update to renderable state */
615                 double sf = 1.0;
616                 NRMatrix t;
617                 nr_matrix_set_scale(&t, sf, sf);
618                 nr_arena_item_set_transform(root, &t);
619                 nr_matrix_set_identity(&gc.transform);
620                 nr_arena_item_invoke_update( root, NULL, &gc,
621                                              NR_ARENA_ITEM_STATE_ALL,
622                                              NR_ARENA_ITEM_STATE_NONE );
623                 /* Item integer bbox in points */
624                 NRRectL ibox;
625                 ibox.x0 = (int) floor(sf * dbox.min()[NR::X] + 0.5);
626                 ibox.y0 = (int) floor(sf * dbox.min()[NR::Y] + 0.5);
627                 ibox.x1 = (int) floor(sf * dbox.max()[NR::X] + 0.5);
628                 ibox.y1 = (int) floor(sf * dbox.max()[NR::Y] + 0.5);
630                 if ( dump ) {
631                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
632                 }
634                 /* Find button visible area */
635                 int width = ibox.x1 - ibox.x0;
636                 int height = ibox.y1 - ibox.y0;
638                 if ( dump ) {
639                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
640                 }
642                 {
643                     int block = std::max(width, height);
644                     if (block != static_cast<int>(psize) ) {
645                         if ( dump ) {
646                             g_message("      resizing" );
647                         }
648                         sf = (double)psize / (double)block;
650                         nr_matrix_set_scale(&t, sf, sf);
651                         nr_arena_item_set_transform(root, &t);
652                         nr_matrix_set_identity(&gc.transform);
653                         nr_arena_item_invoke_update( root, NULL, &gc,
654                                                      NR_ARENA_ITEM_STATE_ALL,
655                                                      NR_ARENA_ITEM_STATE_NONE );
656                         /* Item integer bbox in points */
657                         ibox.x0 = (int) floor(sf * dbox.min()[NR::X] + 0.5);
658                         ibox.y0 = (int) floor(sf * dbox.min()[NR::Y] + 0.5);
659                         ibox.x1 = (int) floor(sf * dbox.max()[NR::X] + 0.5);
660                         ibox.y1 = (int) floor(sf * dbox.max()[NR::Y] + 0.5);
662                         if ( dump ) {
663                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
664                         }
666                         /* Find button visible area */
667                         width = ibox.x1 - ibox.x0;
668                         height = ibox.y1 - ibox.y0;
669                         if ( dump ) {
670                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
671                         }
672                     }
673                 }
675                 int dx, dy;
676                 //dx = (psize - width) / 2;
677                 //dy = (psize - height) / 2;
678                 dx=dy=psize;
679                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
680                 dy=(dy-height)/2;
681                 NRRectL area;
682                 area.x0 = ibox.x0 - dx;
683                 area.y0 = ibox.y0 - dy;
684                 area.x1 = area.x0 + psize;
685                 area.y1 = area.y0 + psize;
686                 /* Actual renderable area */
687                 NRRectL ua;
688                 ua.x0 = MAX(ibox.x0, area.x0);
689                 ua.y0 = MAX(ibox.y0, area.y0);
690                 ua.x1 = MIN(ibox.x1, area.x1);
691                 ua.y1 = MIN(ibox.y1, area.y1);
693                 if ( dump ) {
694                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
695                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
696                 }
697                 /* Set up pixblock */
698                 px = nr_new(guchar, 4 * psize * psize);
699                 memset(px, 0x00, 4 * psize * psize);
700                 /* Render */
701                 NRPixBlock B;
702                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
703                                           ua.x0, ua.y0, ua.x1, ua.y1,
704                                           px + 4 * psize * (ua.y0 - area.y0) +
705                                           4 * (ua.x0 - area.x0),
706                                           4 * psize, FALSE, FALSE );
707                 nr_arena_item_invoke_render( root, &ua, &B,
708                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
709                 nr_pixblock_release(&B);
711                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
712                 if ( useOverlay ) {
713                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
714                 }
715             }
716         }
717     }
719     return px;
720 } // end of sp_icon_doc_icon()
724 struct svg_doc_cache_t
726     SPDocument *doc;
727     NRArenaItem *root;
728 };
730 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
731 static std::map<Glib::ustring, guchar *> px_cache;
733 static Glib::ustring icon_cache_key(gchar const *name,
734                                     unsigned lsize, unsigned psize)
736     Glib::ustring key=name;
737     key += ":";
738     key += lsize;
739     key += ":";
740     key += psize;
741     return key;
744 static guchar *get_cached_pixels(Glib::ustring const &key) {
745     std::map<Glib::ustring, guchar *>::iterator found=px_cache.find(key);
746     if ( found != px_cache.end() ) {
747         return found->second;
748     }
749     return NULL;
752 static guchar *load_svg_pixels(gchar const *name,
753                                unsigned lsize, unsigned psize)
755     SPDocument *doc = NULL;
756     NRArenaItem *root = NULL;
757     svg_doc_cache_t *info = NULL;
759     // Fall back from user prefs dir into system locations.
760     Glib::ustring iconsvg = name;
761     iconsvg += ".svg";
762     std::list<gchar *> sources;
763     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
764     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
765     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
766     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
768     // Try each document in turn until we successfully load the icon from one
769     guchar *px=NULL;
770     while ( !sources.empty() && !px ) {
771         gchar *doc_filename = sources.front();
773         // Did we already load this doc?
774         Glib::ustring key(doc_filename);
775         info = 0;
776         {
777             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
778             if ( i != doc_cache.end() ) {
779                 info = i->second;
780             }
781         }
783         /* Try to load from document. */
784         if (!info &&
785             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
786             (doc = sp_document_new( doc_filename, FALSE )) ) {
788             // prep the document
789             sp_document_ensure_up_to_date(doc);
790             /* Create new arena */
791             NRArena *arena = NRArena::create();
792             /* Create ArenaItem and set transform */
793             unsigned visionkey = sp_item_display_key_new(1);
794             /* fixme: Memory manage root if needed (Lauris) */
795             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
796                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
798             // store into the cache
799             info = new svg_doc_cache_t;
800             g_assert(info);
802             info->doc=doc;
803             info->root=root;
804             doc_cache[key]=info;
805         }
806         if (info) {
807             doc=info->doc;
808             root=info->root;
809         }
811         // toss the filename
812         g_free(doc_filename);
813         sources.pop_front();
815         // move on to the next document if we couldn't get anything
816         if (!info && !doc) continue;
818         px = sp_icon_doc_icon( doc, root, name, psize );
819     }
821     return px;
824 // returns true if icon needed preloading, false if nothing was done
825 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
827     Glib::ustring key=icon_cache_key(name, lsize, psize);
828     guchar *px=get_cached_pixels(key);
829     if (px) {
830         return false;
831     } else {
832         px = load_svg_pixels(name, lsize, psize);
833         if (px) {
834             px_cache[key] = px;
835         }
836         return true;
837     }
840 static guchar *
841 sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
843     Glib::ustring key=icon_cache_key(name, lsize, psize);
845     // did we already load this icon at this scale/size?
846     guchar *px=get_cached_pixels(key);
847     if (!px) {
848         px = load_svg_pixels(name, lsize, psize);
849         if (px) {
850             px_cache[key] = px;
851         }
852     }
853     return px;
856 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
857                             unsigned r, unsigned g, unsigned b)
859     for ( int y = 0; y < height; y += 4 ) {
860         guchar *ptr = px + y * stride;
861         for ( int x = 0; x < width; x += 4 ) {
862             *(ptr++) = r;
863             *(ptr++) = g;
864             *(ptr++) = b;
865             *(ptr++) = 0xff;
867             ptr += 4 * 3;
868         }
869     }
871     if ( width > 1 && height > 1 ) {
872         // point at the last pixel
873         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
875         if ( width > 2 ) {
876             px[4] = r;
877             px[5] = g;
878             px[6] = b;
879             px[7] = 0xff;
881             ptr[-12] = r;
882             ptr[-11] = g;
883             ptr[-10] = b;
884             ptr[-9] = 0xff;
885         }
887         ptr[-4] = r;
888         ptr[-3] = g;
889         ptr[-2] = b;
890         ptr[-1] = 0xff;
892         px[0 + stride] = r;
893         px[1 + stride] = g;
894         px[2 + stride] = b;
895         px[3 + stride] = 0xff;
897         ptr[0 - stride] = r;
898         ptr[1 - stride] = g;
899         ptr[2 - stride] = b;
900         ptr[3 - stride] = 0xff;
902         if ( height > 2 ) {
903             ptr[0 - stride * 3] = r;
904             ptr[1 - stride * 3] = g;
905             ptr[2 - stride * 3] = b;
906             ptr[3 - stride * 3] = 0xff;
907         }
908     }
911 class preRenderItem
913 public:
914     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
915         _lsize( lsize ),
916         _name( name )
917     {}
918     Inkscape::IconSize _lsize;
919     Glib::ustring _name;
920 };
923 #include <queue>
925 static std::queue<preRenderItem> pendingRenders;
926 static bool callbackHooked = false;
928 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
931     if ( !callbackHooked )
932     {
933         callbackHooked = true;
934         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
935     }
937     pendingRenders.push(preRenderItem(lsize, name));
940 gboolean icon_prerender_task(gpointer data) {
941     if (!pendingRenders.empty()) {
942         preRenderItem single=pendingRenders.front();
943         pendingRenders.pop();
944         int psize = sp_icon_get_phys_size(single._lsize);
945         prerender_icon(single._name.c_str(), single._lsize, psize);
946     }
948     if (!pendingRenders.empty()) {
949         return TRUE;
950     } else {
951         callbackHooked = false;
952         return FALSE;
953     }
956 /*
957   Local Variables:
958   mode:c++
959   c-file-style:"stroustrup"
960   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
961   indent-tabs-mode:nil
962   fill-column:99
963   End:
964 */
965 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :