Code

0aa01a37e36daaea75d0a9d91f7ba9ed2ba58f59
[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             sp_icon_fetch_pixbuf( icon );
193         }
195         sp_icon_paint(SP_ICON(widget), &event->area);
196     }
198     return TRUE;
201 void sp_icon_fetch_pixbuf( SPIcon *icon )
203     if ( icon ) {
204         if ( !icon->pb ) {
205             guchar *pixels = 0;
207             icon->psize = sp_icon_get_phys_size(icon->lsize);
209             pixels = sp_icon_image_load( icon, icon->name );
211             if (pixels) {
212                 // don't pass the nr_free because we're caching the pixel
213                 // space loaded through ...
214                 // I just changed this. make sure sp_icon_image_load still does the right thing.
215                 icon->pb = gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, TRUE, 8,
216                                                     icon->psize, icon->psize, icon->psize * 4,
217                                                     /*(GdkPixbufDestroyNotify)nr_free*/NULL, NULL);
218                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
220                 pixels = gdk_pixbuf_get_pixels(icon->pb_faded);
221                 size_t stride = gdk_pixbuf_get_rowstride(icon->pb_faded);
222                 pixels += 3; // alpha
223                 for ( int row = 0 ; row < icon->psize ; row++ ) {
224                     guchar *row_pixels = pixels;
225                     for ( int column = 0 ; column < icon->psize ; column++ ) {
226                         *row_pixels = *row_pixels >> 1;
227                         row_pixels += 4;
228                     }
229                     pixels += stride;
230                 }
231             } else {
232                 /* TODO: We should do something more useful if we can't load the image. */
233                 g_warning ("failed to load icon '%s'", icon->name);
234             }
235         }
236     }
239 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
241     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
242         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
243     }
244     SPIcon *icon = SP_ICON(widget);
245     sp_icon_theme_changed(icon);
248 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
250     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
251         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
252     }
253     SPIcon *icon = SP_ICON(widget);
254     sp_icon_theme_changed(icon);
257 static void sp_icon_theme_changed( SPIcon *icon )
259     //g_message("Got a change bump for this icon");
260     sizeDirty = true;
261     sp_icon_reset(icon);
262     gtk_widget_queue_draw( GTK_WIDGET(icon) );
266 static GtkWidget *
267 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
269     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
270     static gint fallback = prefs_get_int_attribute_limited( "debug.icons", "checkNames", 0, 0, 1 );
272     addPreRender( lsize, name );
274     GtkStockItem stock;
275     gboolean tryLoad = gtk_stock_lookup( name, &stock );
276     if ( !tryLoad && fallback ) {
277         tryLoad |= strncmp("gtk-", name, 4 ) == 0;
278     }
279     if ( !tryLoad && fallback ) {
280         tryLoad |= strncmp("gnome-", name, 6 ) == 0;
281     }
283     GtkWidget *widget = 0;
284     if ( tryLoad ) {
285         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
287         if ( !sizeMapDone ) {
288             injectCustomSize();
289         }
291         GtkWidget *img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
292         if ( img ) {
293             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
294             if ( type == GTK_IMAGE_STOCK ) {
295                 widget = GTK_WIDGET(img);
296                 img = 0;
298                 if ( dump ) {
299                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK)", name, lsize );
300                 }
301             } else {
302                 if ( dump ) {
303                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
304                 }
305                 g_object_unref( (GObject *)img );
306                 img = 0;
307             }
308         }
309     }
311     if ( !widget ) {
312         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
313         icon->lsize = lsize;
314         icon->name = g_strdup(name);
315         icon->psize = sp_icon_get_phys_size(lsize);
317         widget = GTK_WIDGET(icon);
318     }
320     return widget;
323 GtkWidget *
324 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
326     return sp_icon_new_full( lsize, name );
329 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
331     Gtk::Widget *result = 0;
332     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
334     if ( widget ) {
335         if ( GTK_IS_IMAGE(widget) ) {
336             GtkImage *img = GTK_IMAGE(widget);
337             result = Glib::wrap( img );
338         } else {
339             result = Glib::wrap( widget );
340         }
341     }
343     return result;
346 // Try to load the named svg, falling back to pixmaps
347 guchar *
348 sp_icon_image_load( SPIcon *icon, gchar const *name )
350     guchar *px = sp_icon_image_load_svg( name, icon->lsize, icon->psize );
351     if (!px) {
352         px = sp_icon_image_load_pixmap(name, icon->lsize, icon->psize);
353     }
355     return px;
358 GtkIconSize
359 sp_icon_get_gtk_size(int size)
361     static GtkIconSize map[64] = {(GtkIconSize)0};
362     size = CLAMP(size, 4, 63);
363     if (!map[size]) {
364         static int count = 0;
365         char c[64];
366         g_snprintf(c, 64, "InkscapeIcon%d", count++);
367         map[size] = gtk_icon_size_register(c, size, size);
368     }
369     return map[size];
372 static void injectCustomSize()
374     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
375     if ( !sizeMapDone )
376     {
377         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
378         gint width = 0;
379         gint height = 0;
380         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
381             gint newWidth = ((width * 3) / 4);
382             gint newHeight = ((height * 3) / 4);
383             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
384             if ( newSizeEnum ) {
385                 if ( dump ) {
386                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
387                 }
388                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
389                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
390                     iconSizeLookup[index] = newSizeEnum;
391                 } else if ( dump ) {
392                     g_message("size lookup array too small to store entry");
393                 }
394             }
395         }
396         sizeMapDone = true;
397     }
401 static int sp_icon_get_phys_size(int size)
403     static bool init = false;
404     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
405     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
407     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
409     if ( !sizeMapDone ) {
410         injectCustomSize();
411     }
413     if ( sizeDirty && init ) {
414         GtkIconSize const gtkSizes[] = {
415             GTK_ICON_SIZE_MENU,
416             GTK_ICON_SIZE_SMALL_TOOLBAR,
417             GTK_ICON_SIZE_LARGE_TOOLBAR,
418             GTK_ICON_SIZE_BUTTON,
419             GTK_ICON_SIZE_DND,
420             GTK_ICON_SIZE_DIALOG,
421             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
422                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
423                 GTK_ICON_SIZE_MENU
424         };
425         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
426             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
428             g_assert( val_ix < G_N_ELEMENTS(vals) );
430             gint width = 0;
431             gint height = 0;
432             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
433                 init &= (lastSys[val_ix] == std::max(width, height));
434             }
435         }
436     }
438     if ( !init ) {
439         sizeDirty = false;
440         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
442         if ( dump ) {
443             g_message( "Default icon sizes:" );
444         }
445         memset( vals, 0, sizeof(vals) );
446         memset( lastSys, 0, sizeof(lastSys) );
447         GtkIconSize const gtkSizes[] = {
448             GTK_ICON_SIZE_MENU,
449             GTK_ICON_SIZE_SMALL_TOOLBAR,
450             GTK_ICON_SIZE_LARGE_TOOLBAR,
451             GTK_ICON_SIZE_BUTTON,
452             GTK_ICON_SIZE_DND,
453             GTK_ICON_SIZE_DIALOG,
454             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
455                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
456                 GTK_ICON_SIZE_MENU
457         };
458         gchar const *const names[] = {
459             "GTK_ICON_SIZE_MENU",
460             "GTK_ICON_SIZE_SMALL_TOOLBAR",
461             "GTK_ICON_SIZE_LARGE_TOOLBAR",
462             "GTK_ICON_SIZE_BUTTON",
463             "GTK_ICON_SIZE_DND",
464             "GTK_ICON_SIZE_DIALOG",
465             "inkscape-decoration"
466         };
468         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
470         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
471             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
473             g_assert( val_ix < G_N_ELEMENTS(vals) );
475             gint width = 0;
476             gint height = 0;
477             bool used = false;
478             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
479                 vals[val_ix] = std::max(width, height);
480                 lastSys[val_ix] = vals[val_ix];
481                 used = true;
482             }
483             if (dump) {
484                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
485                           i, gtkSizes[i],
486                           ( used ? ' ' : 'X' ), width, height, names[i]);
487             }
488             gchar const *id = GTK_STOCK_OPEN;
489             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
490             if (pb) {
491                 width = gdk_pixbuf_get_width(pb);
492                 height = gdk_pixbuf_get_height(pb);
493                 int newSize = std::max( width, height );
494                 // TODO perhaps check a few more stock icons to get a range on sizes.
495                 if ( newSize > 0 ) {
496                     vals[val_ix] = newSize;
497                 }
498                 if (dump) {
499                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
500                 }
502                 g_object_unref(G_OBJECT(pb));
503             }
504         }
505         //g_object_unref(icon);
506         init = true;
507     }
509     return vals[size];
512 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
514     GtkWidget &widget = *GTK_WIDGET(icon);
516     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
518     if (image) {
519         int const padx = ( ( widget.allocation.width > icon->psize )
520                            ? ( widget.allocation.width - icon->psize ) / 2
521                            : 0 );
522         int const pady = ( ( widget.allocation.height > icon->psize )
523                            ? ( widget.allocation.height - icon->psize ) / 2
524                            : 0 );
526         int const x0 = std::max(area->x, widget.allocation.x + padx);
527         int const y0 = std::max(area->y, widget.allocation.y + pady);
528         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
529         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
531         gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
532                         x0 - widget.allocation.x - padx,
533                         y0 - widget.allocation.y - pady,
534                         x0, y0,
535                         x1 - x0, y1 - y0,
536                         GDK_RGB_DITHER_NORMAL, x0, y0);
537     }
540 static guchar *
541 sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize)
543     gchar *path;
544     guchar *px;
545     GdkPixbuf *pb;
547     path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
548     // TODO: bulia, please look over
549     gsize bytesRead = 0;
550     gsize bytesWritten = 0;
551     GError *error = NULL;
552     gchar *localFilename = g_filename_from_utf8( path,
553                                                  -1,
554                                                  &bytesRead,
555                                                  &bytesWritten,
556                                                  &error);
557     pb = gdk_pixbuf_new_from_file(localFilename, NULL);
558     g_free(localFilename);
559     g_free(path);
560     if (!pb) {
561         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
562         // TODO: bulia, please look over
563         gsize bytesRead = 0;
564         gsize bytesWritten = 0;
565         GError *error = NULL;
566         gchar *localFilename = g_filename_from_utf8( path,
567                                                      -1,
568                                                      &bytesRead,
569                                                      &bytesWritten,
570                                                      &error);
571         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
572         g_free(localFilename);
573         g_free(path);
574     }
575     if (pb) {
576         if (!gdk_pixbuf_get_has_alpha(pb))
577             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
578         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
579              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
580             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
581             g_object_unref(G_OBJECT(pb));
582             pb = spb;
583         }
584         guchar *spx = gdk_pixbuf_get_pixels(pb);
585         int srs = gdk_pixbuf_get_rowstride(pb);
586         px = nr_new(guchar, 4 * psize * psize);
587         for (unsigned y = 0; y < psize; y++) {
588             memcpy(px + 4 * y * psize, spx + y * srs, 4 * psize);
589         }
590         g_object_unref(G_OBJECT(pb));
592         return px;
593     }
595     return NULL;
598 // takes doc, root, icon, and icon name to produce pixels
599 extern "C" guchar *
600 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
601                   gchar const *name, unsigned psize )
603     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
604     guchar *px = NULL;
606     if (doc) {
607         SPObject *object = doc->getObjectById(name);
608         if (object && SP_IS_ITEM(object)) {
609             /* Find bbox in document */
610             NR::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
611             NR::Rect dbox = SP_ITEM(object)->invokeBbox(i2doc);
613             if ( SP_OBJECT_PARENT(object) == NULL )
614             {
615                 dbox = NR::Rect(NR::Point(0, 0),
616                                 NR::Point(sp_document_width(doc), sp_document_height(doc)));
617             }
619             /* This is in document coordinates, i.e. pixels */
620             if (dbox.isEmpty() == false) {
621                 NRGC gc(NULL);
622                 /* Update to renderable state */
623                 double sf = 1.0;
624                 NRMatrix t;
625                 nr_matrix_set_scale(&t, sf, sf);
626                 nr_arena_item_set_transform(root, &t);
627                 nr_matrix_set_identity(&gc.transform);
628                 nr_arena_item_invoke_update( root, NULL, &gc,
629                                              NR_ARENA_ITEM_STATE_ALL,
630                                              NR_ARENA_ITEM_STATE_NONE );
631                 /* Item integer bbox in points */
632                 NRRectL ibox;
633                 ibox.x0 = (int) floor(sf * dbox.min()[NR::X] + 0.5);
634                 ibox.y0 = (int) floor(sf * dbox.min()[NR::Y] + 0.5);
635                 ibox.x1 = (int) floor(sf * dbox.max()[NR::X] + 0.5);
636                 ibox.y1 = (int) floor(sf * dbox.max()[NR::Y] + 0.5);
638                 if ( dump ) {
639                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
640                 }
642                 /* Find button visible area */
643                 int width = ibox.x1 - ibox.x0;
644                 int height = ibox.y1 - ibox.y0;
646                 if ( dump ) {
647                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
648                 }
650                 {
651                     int block = std::max(width, height);
652                     if (block != static_cast<int>(psize) ) {
653                         if ( dump ) {
654                             g_message("      resizing" );
655                         }
656                         sf = (double)psize / (double)block;
658                         nr_matrix_set_scale(&t, sf, sf);
659                         nr_arena_item_set_transform(root, &t);
660                         nr_matrix_set_identity(&gc.transform);
661                         nr_arena_item_invoke_update( root, NULL, &gc,
662                                                      NR_ARENA_ITEM_STATE_ALL,
663                                                      NR_ARENA_ITEM_STATE_NONE );
664                         /* Item integer bbox in points */
665                         ibox.x0 = (int) floor(sf * dbox.min()[NR::X] + 0.5);
666                         ibox.y0 = (int) floor(sf * dbox.min()[NR::Y] + 0.5);
667                         ibox.x1 = (int) floor(sf * dbox.max()[NR::X] + 0.5);
668                         ibox.y1 = (int) floor(sf * dbox.max()[NR::Y] + 0.5);
670                         if ( dump ) {
671                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
672                         }
674                         /* Find button visible area */
675                         width = ibox.x1 - ibox.x0;
676                         height = ibox.y1 - ibox.y0;
677                         if ( dump ) {
678                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
679                         }
680                     }
681                 }
683                 int dx, dy;
684                 //dx = (psize - width) / 2;
685                 //dy = (psize - height) / 2;
686                 dx=dy=psize;
687                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
688                 dy=(dy-height)/2;
689                 NRRectL area;
690                 area.x0 = ibox.x0 - dx;
691                 area.y0 = ibox.y0 - dy;
692                 area.x1 = area.x0 + psize;
693                 area.y1 = area.y0 + psize;
694                 /* Actual renderable area */
695                 NRRectL ua;
696                 ua.x0 = MAX(ibox.x0, area.x0);
697                 ua.y0 = MAX(ibox.y0, area.y0);
698                 ua.x1 = MIN(ibox.x1, area.x1);
699                 ua.y1 = MIN(ibox.y1, area.y1);
701                 if ( dump ) {
702                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
703                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
704                 }
705                 /* Set up pixblock */
706                 px = nr_new(guchar, 4 * psize * psize);
707                 memset(px, 0x00, 4 * psize * psize);
708                 /* Render */
709                 NRPixBlock B;
710                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
711                                           ua.x0, ua.y0, ua.x1, ua.y1,
712                                           px + 4 * psize * (ua.y0 - area.y0) +
713                                           4 * (ua.x0 - area.x0),
714                                           4 * psize, FALSE, FALSE );
715                 nr_arena_item_invoke_render( root, &ua, &B,
716                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
717                 nr_pixblock_release(&B);
719                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
720                 if ( useOverlay ) {
721                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
722                 }
723             }
724         }
725     }
727     return px;
728 } // end of sp_icon_doc_icon()
732 struct svg_doc_cache_t
734     SPDocument *doc;
735     NRArenaItem *root;
736 };
738 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
739 static std::map<Glib::ustring, guchar *> px_cache;
741 static Glib::ustring icon_cache_key(gchar const *name,
742                                     unsigned lsize, unsigned psize)
744     Glib::ustring key=name;
745     key += ":";
746     key += lsize;
747     key += ":";
748     key += psize;
749     return key;
752 static guchar *get_cached_pixels(Glib::ustring const &key) {
753     std::map<Glib::ustring, guchar *>::iterator found=px_cache.find(key);
754     if ( found != px_cache.end() ) {
755         return found->second;
756     }
757     return NULL;
760 static guchar *load_svg_pixels(gchar const *name,
761                                unsigned lsize, unsigned psize)
763     SPDocument *doc = NULL;
764     NRArenaItem *root = NULL;
765     svg_doc_cache_t *info = NULL;
767     // Fall back from user prefs dir into system locations.
768     Glib::ustring iconsvg = name;
769     iconsvg += ".svg";
770     std::list<gchar *> sources;
771     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
772     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
773     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
774     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
776     // Try each document in turn until we successfully load the icon from one
777     guchar *px=NULL;
778     while ( !sources.empty() && !px ) {
779         gchar *doc_filename = sources.front();
781         // Did we already load this doc?
782         Glib::ustring key(doc_filename);
783         info = 0;
784         {
785             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
786             if ( i != doc_cache.end() ) {
787                 info = i->second;
788             }
789         }
791         /* Try to load from document. */
792         if (!info &&
793             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
794             (doc = sp_document_new( doc_filename, FALSE )) ) {
796             // prep the document
797             sp_document_ensure_up_to_date(doc);
798             /* Create new arena */
799             NRArena *arena = NRArena::create();
800             /* Create ArenaItem and set transform */
801             unsigned visionkey = sp_item_display_key_new(1);
802             /* fixme: Memory manage root if needed (Lauris) */
803             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
804                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
806             // store into the cache
807             info = new svg_doc_cache_t;
808             g_assert(info);
810             info->doc=doc;
811             info->root=root;
812             doc_cache[key]=info;
813         }
814         if (info) {
815             doc=info->doc;
816             root=info->root;
817         }
819         // toss the filename
820         g_free(doc_filename);
821         sources.pop_front();
823         // move on to the next document if we couldn't get anything
824         if (!info && !doc) continue;
826         px = sp_icon_doc_icon( doc, root, name, psize );
827     }
829     return px;
832 // returns true if icon needed preloading, false if nothing was done
833 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
835     Glib::ustring key=icon_cache_key(name, lsize, psize);
836     guchar *px=get_cached_pixels(key);
837     if (px) {
838         return false;
839     } else {
840         px = load_svg_pixels(name, lsize, psize);
841         if (px) {
842             px_cache[key] = px;
843         }
844         return true;
845     }
848 static guchar *
849 sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
851     Glib::ustring key=icon_cache_key(name, lsize, psize);
853     // did we already load this icon at this scale/size?
854     guchar *px=get_cached_pixels(key);
855     if (!px) {
856         px = load_svg_pixels(name, lsize, psize);
857         if (px) {
858             px_cache[key] = px;
859         }
860     }
861     return px;
864 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
865                             unsigned r, unsigned g, unsigned b)
867     for ( int y = 0; y < height; y += 4 ) {
868         guchar *ptr = px + y * stride;
869         for ( int x = 0; x < width; x += 4 ) {
870             *(ptr++) = r;
871             *(ptr++) = g;
872             *(ptr++) = b;
873             *(ptr++) = 0xff;
875             ptr += 4 * 3;
876         }
877     }
879     if ( width > 1 && height > 1 ) {
880         // point at the last pixel
881         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
883         if ( width > 2 ) {
884             px[4] = r;
885             px[5] = g;
886             px[6] = b;
887             px[7] = 0xff;
889             ptr[-12] = r;
890             ptr[-11] = g;
891             ptr[-10] = b;
892             ptr[-9] = 0xff;
893         }
895         ptr[-4] = r;
896         ptr[-3] = g;
897         ptr[-2] = b;
898         ptr[-1] = 0xff;
900         px[0 + stride] = r;
901         px[1 + stride] = g;
902         px[2 + stride] = b;
903         px[3 + stride] = 0xff;
905         ptr[0 - stride] = r;
906         ptr[1 - stride] = g;
907         ptr[2 - stride] = b;
908         ptr[3 - stride] = 0xff;
910         if ( height > 2 ) {
911             ptr[0 - stride * 3] = r;
912             ptr[1 - stride * 3] = g;
913             ptr[2 - stride * 3] = b;
914             ptr[3 - stride * 3] = 0xff;
915         }
916     }
919 class preRenderItem
921 public:
922     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
923         _lsize( lsize ),
924         _name( name )
925     {}
926     Inkscape::IconSize _lsize;
927     Glib::ustring _name;
928 };
931 #include <queue>
933 static std::queue<preRenderItem> pendingRenders;
934 static bool callbackHooked = false;
936 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
939     if ( !callbackHooked )
940     {
941         callbackHooked = true;
942         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
943     }
945     pendingRenders.push(preRenderItem(lsize, name));
948 gboolean icon_prerender_task(gpointer data) {
949     if (!pendingRenders.empty()) {
950         preRenderItem single=pendingRenders.front();
951         pendingRenders.pop();
952         int psize = sp_icon_get_phys_size(single._lsize);
953         prerender_icon(single._name.c_str(), single._lsize, psize);
954     }
956     if (!pendingRenders.empty()) {
957         return TRUE;
958     } else {
959         callbackHooked = false;
960         return FALSE;
961     }
964 /*
965   Local Variables:
966   mode:c++
967   c-file-style:"stroustrup"
968   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
969   indent-tabs-mode:nil
970   fill-column:99
971   End:
972 */
973 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :