Code

ad0646e5a2d821b8922153eadf62c0057aa9ebf9
[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
18 #include <cstring>
19 #include <glib/gmem.h>
20 #include <gtk/gtk.h>
21 #include <gtkmm.h>
23 #include "path-prefix.h"
24 #include "preferences.h"
25 #include "inkscape.h"
26 #include "document.h"
27 #include "sp-item.h"
28 #include "display/nr-arena.h"
29 #include "display/nr-arena-item.h"
30 #include "io/sys.h"
32 #include "icon.h"
34 static void sp_icon_class_init(SPIconClass *klass);
35 static void sp_icon_init(SPIcon *icon);
36 static void sp_icon_dispose(GObject *object);
38 static void sp_icon_reset(SPIcon *icon);
39 static void sp_icon_clear(SPIcon *icon);
41 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
42 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
43 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
45 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
47 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
48 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
49 static void sp_icon_theme_changed( SPIcon *icon );
51 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
52 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
54 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
55                                     unsigned r, unsigned g, unsigned b );
57 static void injectCustomSize();
59 static GtkWidgetClass *parent_class;
61 static bool sizeDirty = true;
63 static bool sizeMapDone = false;
64 static GtkIconSize iconSizeLookup[] = {
65     GTK_ICON_SIZE_INVALID,
66     GTK_ICON_SIZE_MENU,
67     GTK_ICON_SIZE_SMALL_TOOLBAR,
68     GTK_ICON_SIZE_LARGE_TOOLBAR,
69     GTK_ICON_SIZE_BUTTON,
70     GTK_ICON_SIZE_DND,
71     GTK_ICON_SIZE_DIALOG,
72     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
73 };
75 class IconCacheItem
76 {
77 public:
78     IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
79         _lsize( lsize ),
80         _pb( pb )
81     {}
82     GtkIconSize _lsize;
83     GdkPixbuf* _pb;
84 };
86 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
88 GType
89 sp_icon_get_type()
90 {
91     //TODO: switch to GObject
92     // GtkType and such calls were deprecated a while back with the
93     // introduction of GObject as a separate layer, with GType instead. --JonCruz
95     static GType type = 0;
96     if (!type) {
97         GTypeInfo info = {
98             sizeof(SPIconClass),
99             NULL,
100             NULL,
101             (GClassInitFunc) sp_icon_class_init,
102             NULL,
103             NULL,
104             sizeof(SPIcon),
105             0,
106             (GInstanceInitFunc) sp_icon_init,
107             NULL
108         };
109         type = g_type_register_static(GTK_TYPE_WIDGET, "SPIcon", &info, (GTypeFlags)0);
110     }
111     return type;
114 static void
115 sp_icon_class_init(SPIconClass *klass)
117     GObjectClass *object_class;
118     GtkWidgetClass *widget_class;
120     object_class = (GObjectClass *) klass;
121     widget_class = (GtkWidgetClass *) klass;
123     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
125     object_class->dispose = sp_icon_dispose;
127     widget_class->size_request = sp_icon_size_request;
128     widget_class->size_allocate = sp_icon_size_allocate;
129     widget_class->expose_event = sp_icon_expose;
130     widget_class->screen_changed = sp_icon_screen_changed;
131     widget_class->style_set = sp_icon_style_set;
135 static void
136 sp_icon_init(SPIcon *icon)
138     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
139     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
140     icon->psize = 0;
141     icon->name = 0;
142     icon->pb = 0;
145 static void
146 sp_icon_dispose(GObject *object)
148     SPIcon *icon = SP_ICON(object);
149     sp_icon_clear(icon);
150     if ( icon->name ) {
151         g_free( icon->name );
152         icon->name = 0;
153     }
155     ((GObjectClass *) (parent_class))->dispose(object);
158 static void sp_icon_reset( SPIcon *icon ) {
159     icon->psize = 0;
160     sp_icon_clear(icon);
163 static void sp_icon_clear( SPIcon *icon ) {
164     if (icon->pb) {
165         g_object_unref(G_OBJECT(icon->pb));
166         icon->pb = NULL;
167     }
170 static void
171 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
173     SPIcon const *icon = SP_ICON(widget);
175     int const size = ( icon->psize
176                        ? icon->psize
177                        : sp_icon_get_phys_size(icon->lsize) );
178     requisition->width = size;
179     requisition->height = size;
182 static void
183 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
185     widget->allocation = *allocation;
187     if (GTK_WIDGET_DRAWABLE(widget)) {
188         gtk_widget_queue_draw(widget);
189     }
192 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
194     if ( GTK_WIDGET_DRAWABLE(widget) ) {
195         SPIcon *icon = SP_ICON(widget);
196         if ( !icon->pb ) {
197             sp_icon_fetch_pixbuf( icon );
198         }
200         sp_icon_paint(SP_ICON(widget), &event->area);
201     }
203     return TRUE;
206 // PUBLIC CALL:
207 void sp_icon_fetch_pixbuf( SPIcon *icon )
209     if ( icon ) {
210         if ( !icon->pb ) {
211             icon->psize = sp_icon_get_phys_size(icon->lsize);
212             GtkIconTheme *theme = gtk_icon_theme_get_default();
214             GdkPixbuf *pb = NULL;
215             if (gtk_icon_theme_has_icon(theme, icon->name)) {
216                 pb = gtk_icon_theme_load_icon(theme, icon->name, icon->psize, (GtkIconLookupFlags) 0, NULL);
217             }
218             if (!pb) {
219                 pb = sp_icon_image_load_svg( icon->name, Inkscape::getRegisteredIconSize(icon->lsize), icon->psize );
220                 // if this was loaded from SVG, add it as a builtin icon
221                 if (pb) gtk_icon_theme_add_builtin_icon(icon->name, icon->psize, pb);
222             }
223             if (!pb) {
224                 pb = sp_icon_image_load_pixmap( icon->name, icon->lsize, icon->psize );
225             }
226             if ( pb ) {
227                 icon->pb = pb;
228             } else {
229                 /* TODO: We should do something more useful if we can't load the image. */
230                 g_warning ("failed to load icon '%s'", icon->name);
231             }
232         }
233     }
236 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
238     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
239         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
240     }
241     SPIcon *icon = SP_ICON(widget);
242     sp_icon_theme_changed(icon);
245 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
247     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
248         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
249     }
250     SPIcon *icon = SP_ICON(widget);
251     sp_icon_theme_changed(icon);
254 static void sp_icon_theme_changed( SPIcon *icon )
256     //g_message("Got a change bump for this icon");
257     sizeDirty = true;
258     sp_icon_reset(icon);
259     gtk_widget_queue_draw( GTK_WIDGET(icon) );
263 static Glib::ustring icon_cache_key(gchar const *name, unsigned psize);
264 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
266 static GtkWidget *
267 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
269     GtkWidget *widget = 0;
270     gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
271     if ( !sizeMapDone ) {
272         injectCustomSize();
273     }
274     GtkIconSize mappedSize = iconSizeLookup[trySize];
276     GtkStockItem stock;
277     gboolean stockFound = gtk_stock_lookup( name, &stock );
279     if ( stockFound ) {
280         GtkWidget *img = gtk_image_new_from_stock( name, mappedSize );
281         widget = GTK_WIDGET(img);
282     }
284     if ( !widget ) {
285         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
286         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
287         icon->lsize = lsize;
288         icon->name = g_strdup(name);
289         icon->psize = sp_icon_get_phys_size(lsize);
291         widget = GTK_WIDGET(icon);
292     }
294     return widget;
297 GtkWidget *
298 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
300     return sp_icon_new_full( lsize, name );
303 // PUBLIC CALL:
304 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
306     Gtk::Widget *result = 0;
307     GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
309     if ( widget ) {
310         if ( GTK_IS_IMAGE(widget) ) {
311             GtkImage *img = GTK_IMAGE(widget);
312             result = Glib::wrap( img );
313         } else {
314             result = Glib::wrap( widget );
315         }
316     }
318     return result;
321 GtkIconSize
322 sp_icon_get_gtk_size(int size)
324     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
325     size = CLAMP(size, 4, 63);
326     if (!sizemap[size]) {
327         static int count = 0;
328         char c[64];
329         g_snprintf(c, 64, "InkscapeIcon%d", count++);
330         sizemap[size] = gtk_icon_size_register(c, size, size);
331     }
332     return sizemap[size];
336 static void injectCustomSize()
338     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
339     if ( !sizeMapDone )
340     {
341         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
342         bool dump = prefs->getBool( "/debug/icons/dumpDefault");
343         gint width = 0;
344         gint height = 0;
345         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
346             gint newWidth = ((width * 3) / 4);
347             gint newHeight = ((height * 3) / 4);
348             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
349             if ( newSizeEnum ) {
350                 if ( dump ) {
351                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
352                 }
353                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
354                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
355                     iconSizeLookup[index] = newSizeEnum;
356                 } else if ( dump ) {
357                     g_message("size lookup array too small to store entry");
358                 }
359             }
360         }
361         sizeMapDone = true;
362     }
364     static bool hit = false;
365     if ( !hit ) {
366         hit = true;
367         inkyIcons = Gtk::IconFactory::create();
368         inkyIcons->add_default();
369     }
372 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
374     GtkIconSize other = GTK_ICON_SIZE_MENU;
375     injectCustomSize();
376     size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
377     if ( size == Inkscape::ICON_SIZE_DECORATION ) {
378         other = gtk_icon_size_from_name("inkscape-decoration");
379     } else {
380         other = static_cast<GtkIconSize>(size);
381     }
383     return other;
387 // PUBLIC CALL:
388 int sp_icon_get_phys_size(int size)
390     static bool init = false;
391     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
392     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
394     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
396     if ( !sizeMapDone ) {
397         injectCustomSize();
398     }
400     if ( sizeDirty && init ) {
401         GtkIconSize const gtkSizes[] = {
402             GTK_ICON_SIZE_MENU,
403             GTK_ICON_SIZE_SMALL_TOOLBAR,
404             GTK_ICON_SIZE_LARGE_TOOLBAR,
405             GTK_ICON_SIZE_BUTTON,
406             GTK_ICON_SIZE_DND,
407             GTK_ICON_SIZE_DIALOG,
408             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
409                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
410                 GTK_ICON_SIZE_MENU
411         };
412         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
413             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
415             g_assert( val_ix < G_N_ELEMENTS(vals) );
417             gint width = 0;
418             gint height = 0;
419             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
420                 init &= (lastSys[val_ix] == std::max(width, height));
421             }
422         }
423     }
425     if ( !init ) {
426         sizeDirty = false;
427         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
428         bool dump = prefs->getBool("/debug/icons/dumpDefault");
430         if ( dump ) {
431             g_message( "Default icon sizes:" );
432         }
433         memset( vals, 0, sizeof(vals) );
434         memset( lastSys, 0, sizeof(lastSys) );
435         GtkIconSize const gtkSizes[] = {
436             GTK_ICON_SIZE_MENU,
437             GTK_ICON_SIZE_SMALL_TOOLBAR,
438             GTK_ICON_SIZE_LARGE_TOOLBAR,
439             GTK_ICON_SIZE_BUTTON,
440             GTK_ICON_SIZE_DND,
441             GTK_ICON_SIZE_DIALOG,
442             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
443                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
444                 GTK_ICON_SIZE_MENU
445         };
446         gchar const *const names[] = {
447             "GTK_ICON_SIZE_MENU",
448             "GTK_ICON_SIZE_SMALL_TOOLBAR",
449             "GTK_ICON_SIZE_LARGE_TOOLBAR",
450             "GTK_ICON_SIZE_BUTTON",
451             "GTK_ICON_SIZE_DND",
452             "GTK_ICON_SIZE_DIALOG",
453             "inkscape-decoration"
454         };
456         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
458         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
459             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
461             g_assert( val_ix < G_N_ELEMENTS(vals) );
463             gint width = 0;
464             gint height = 0;
465             bool used = false;
466             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
467                 vals[val_ix] = std::max(width, height);
468                 lastSys[val_ix] = vals[val_ix];
469                 used = true;
470             }
471             if (dump) {
472                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
473                           i, gtkSizes[i],
474                           ( used ? ' ' : 'X' ), width, height, names[i]);
475             }
476             gchar const *id = GTK_STOCK_OPEN;
477             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
478             if (pb) {
479                 width = gdk_pixbuf_get_width(pb);
480                 height = gdk_pixbuf_get_height(pb);
481                 int newSize = std::max( width, height );
482                 // TODO perhaps check a few more stock icons to get a range on sizes.
483                 if ( newSize > 0 ) {
484                     vals[val_ix] = newSize;
485                 }
486                 if (dump) {
487                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
488                 }
490                 g_object_unref(G_OBJECT(pb));
491             }
492         }
493         //g_object_unref(icon);
494         init = true;
495     }
497     // Fixup workaround
498     if ((size == GTK_ICON_SIZE_MENU) || (size == GTK_ICON_SIZE_SMALL_TOOLBAR) || (size == GTK_ICON_SIZE_LARGE_TOOLBAR)) {
499         gint width = 0;
500         gint height = 0;
501         if ( gtk_icon_size_lookup( static_cast<GtkIconSize>(size), &width, &height ) ) {
502             vals[size] = std::max( width, height );
503         }
504     }
506     return vals[size];
509 static void sp_icon_paint(SPIcon *icon, GdkRectangle const */*area*/)
511     GtkWidget &widget = *GTK_WIDGET(icon);
512     GdkPixbuf *image = icon->pb;
513     bool unref_image = false;
515     /* copied from the expose function of GtkImage */
516     if (GTK_WIDGET_STATE (icon) != GTK_STATE_NORMAL && image) {
517         GtkIconSource *source = gtk_icon_source_new();
518         gtk_icon_source_set_pixbuf(source, icon->pb);
519         gtk_icon_source_set_size(source, GTK_ICON_SIZE_SMALL_TOOLBAR); // note: this is boilerplate and not used
520         gtk_icon_source_set_size_wildcarded(source, FALSE);
521         image = gtk_style_render_icon (widget.style, source, gtk_widget_get_direction(&widget),
522             (GtkStateType) GTK_WIDGET_STATE(&widget), (GtkIconSize)-1, &widget, "gtk-image");
523         gtk_icon_source_free(source);
524         unref_image = true;
525     }
527     if (image) {
528         int x = floor(widget.allocation.x + ((widget.allocation.width - widget.requisition.width) * 0.5));
529         int y = floor(widget.allocation.y + ((widget.allocation.height - widget.requisition.height) * 0.5));
530         int width = gdk_pixbuf_get_width(image);
531         int height = gdk_pixbuf_get_height(image);
532         // Limit drawing to when we actually have something. Avoids some crashes.
533         if ( (width > 0) && (height > 0) ) {
534             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), widget.style->black_gc, image,
535                             0, 0, x, y, width, height,
536                             GDK_RGB_DITHER_NORMAL, x, y);
537         }
538     }
540     if (unref_image) g_object_unref(G_OBJECT(image));
543 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
545     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
546     // TODO: bulia, please look over
547     gsize bytesRead = 0;
548     gsize bytesWritten = 0;
549     GError *error = NULL;
550     gchar *localFilename = g_filename_from_utf8( path,
551                                                  -1,
552                                                  &bytesRead,
553                                                  &bytesWritten,
554                                                  &error);
555     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
556     g_free(localFilename);
557     g_free(path);
558     if (!pb) {
559         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
560         // TODO: bulia, please look over
561         gsize bytesRead = 0;
562         gsize bytesWritten = 0;
563         GError *error = NULL;
564         gchar *localFilename = g_filename_from_utf8( path,
565                                                      -1,
566                                                      &bytesRead,
567                                                      &bytesWritten,
568                                                      &error);
569         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
570         g_free(localFilename);
571         g_free(path);
572     }
574     if (pb) {
575         if (!gdk_pixbuf_get_has_alpha(pb)) {
576             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
577         }
579         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
580              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
581             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
582             g_object_unref(G_OBJECT(pb));
583             pb = spb;
584         }
585     }
587     return pb;
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     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
596     bool const dump = prefs->getBool("/debug/icons/dumpSvg");
597     guchar *px = NULL;
599     if (doc) {
600         SPObject *object = doc->getObjectById(name);
601         if (object && SP_IS_ITEM(object)) {
602             /* Find bbox in document */
603             Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
604             Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
606             if ( SP_OBJECT_PARENT(object) == NULL )
607             {
608                 dbox = Geom::Rect(Geom::Point(0, 0),
609                                 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
610             }
612             /* This is in document coordinates, i.e. pixels */
613             if ( dbox ) {
614                 NRGC gc(NULL);
615                 /* Update to renderable state */
616                 double sf = 1.0;
617                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
618                 gc.transform.setIdentity();
619                 nr_arena_item_invoke_update( root, NULL, &gc,
620                                              NR_ARENA_ITEM_STATE_ALL,
621                                              NR_ARENA_ITEM_STATE_NONE );
622                 /* Item integer bbox in points */
623                 NRRectL ibox;
624                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
625                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
626                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
627                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
629                 if ( dump ) {
630                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
631                 }
633                 /* Find button visible area */
634                 int width = ibox.x1 - ibox.x0;
635                 int height = ibox.y1 - ibox.y0;
637                 if ( dump ) {
638                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
639                 }
641                 {
642                     int block = std::max(width, height);
643                     if (block != static_cast<int>(psize) ) {
644                         if ( dump ) {
645                             g_message("      resizing" );
646                         }
647                         sf = (double)psize / (double)block;
649                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
650                         gc.transform.setIdentity();
651                         nr_arena_item_invoke_update( root, NULL, &gc,
652                                                      NR_ARENA_ITEM_STATE_ALL,
653                                                      NR_ARENA_ITEM_STATE_NONE );
654                         /* Item integer bbox in points */
655                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
656                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
657                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
658                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
660                         if ( dump ) {
661                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
662                         }
664                         /* Find button visible area */
665                         width = ibox.x1 - ibox.x0;
666                         height = ibox.y1 - ibox.y0;
667                         if ( dump ) {
668                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
669                         }
670                     }
671                 }
673                 int dx, dy;
674                 //dx = (psize - width) / 2;
675                 //dy = (psize - height) / 2;
676                 dx=dy=psize;
677                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
678                 dy=(dy-height)/2;
679                 NRRectL area;
680                 area.x0 = ibox.x0 - dx;
681                 area.y0 = ibox.y0 - dy;
682                 area.x1 = area.x0 + psize;
683                 area.y1 = area.y0 + psize;
684                 /* Actual renderable area */
685                 NRRectL ua;
686                 ua.x0 = MAX(ibox.x0, area.x0);
687                 ua.y0 = MAX(ibox.y0, area.y0);
688                 ua.x1 = MIN(ibox.x1, area.x1);
689                 ua.y1 = MIN(ibox.y1, area.y1);
691                 if ( dump ) {
692                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
693                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
694                 }
695                 /* Set up pixblock */
696                 px = g_new(guchar, 4 * psize * psize);
697                 memset(px, 0x00, 4 * psize * psize);
698                 /* Render */
699                 NRPixBlock B;
700                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
701                                           ua.x0, ua.y0, ua.x1, ua.y1,
702                                           px + 4 * psize * (ua.y0 - area.y0) +
703                                           4 * (ua.x0 - area.x0),
704                                           4 * psize, FALSE, FALSE );
705                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
706                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
707                 nr_pixblock_release(&B);
709                 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
710                 if ( useOverlay ) {
711                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
712                 }
713             }
714         }
715     }
717     return px;
718 } // end of sp_icon_doc_icon()
722 struct svg_doc_cache_t
724     SPDocument *doc;
725     NRArenaItem *root;
726 };
728 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
729 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
731 Glib::ustring icon_cache_key(gchar const *name, unsigned psize)
733     Glib::ustring key=name;
734     key += ":";
735     key += psize;
736     return key;
739 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
740     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
741     if ( found != pb_cache.end() ) {
742         return found->second;
743     }
744     return NULL;
747 static std::list<gchar*> &icons_svg_paths()
749     static std::list<gchar *> sources;
750     static bool initialized = false;
751     if (!initialized) {
752         // Fall back from user prefs dir into system locations.
753         gchar *userdir = profile_path("icons");
754         sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
755         sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
756         g_free(userdir);
757         initialized = true;
758     }
759     return sources;
762 // this function renders icons from icons.svg and returns the pixels.
763 static guchar *load_svg_pixels(gchar const *name,
764                                unsigned /*lsize*/, unsigned psize)
766     SPDocument *doc = NULL;
767     NRArenaItem *root = NULL;
768     svg_doc_cache_t *info = NULL;
770     std::list<gchar *> &sources = icons_svg_paths();
772     // Try each document in turn until we successfully load the icon from one
773     guchar *px=NULL;
774     for (std::list<gchar*>::iterator i = sources.begin(); i != sources.end() && !px; ++i) {
775         gchar *doc_filename = *i;
777         // Did we already load this doc?
778         Glib::ustring key(doc_filename);
779         info = 0;
780         {
781             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
782             if ( i != doc_cache.end() ) {
783                 info = i->second;
784             }
785         }
787         /* Try to load from document. */
788         if (!info &&
789             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
790             (doc = sp_document_new( doc_filename, FALSE )) ) {
792             //g_message("Loaded icon file %s", doc_filename);
793             // prep the document
794             sp_document_ensure_up_to_date(doc);
795             /* Create new arena */
796             NRArena *arena = NRArena::create();
797             /* Create ArenaItem and set transform */
798             unsigned visionkey = sp_item_display_key_new(1);
799             /* fixme: Memory manage root if needed (Lauris) */
800             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
801                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
803             // store into the cache
804             info = new svg_doc_cache_t;
805             g_assert(info);
807             info->doc=doc;
808             info->root=root;
809             doc_cache[key]=info;
810         }
811         if (info) {
812             doc=info->doc;
813             root=info->root;
814         }
816         // move on to the next document if we couldn't get anything
817         if (!info && !doc) continue;
819         px = sp_icon_doc_icon( doc, root, name, psize );
820         //if (px) g_message("Found icon %s in %s", name, doc_filename);
821     }
823     //if (!px) g_message("Not found icon %s", name);
824     return px;
827 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
829     Glib::ustring key = icon_cache_key(name, psize);
831     // did we already load this icon at this scale/size?
832     GdkPixbuf* pb = get_cached_pixbuf(key);
833     if (!pb) {
834         guchar *px = load_svg_pixels(name, lsize, psize);
835         if (px) {
836             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
837                                           psize, psize, psize * 4,
838                                           (GdkPixbufDestroyNotify)g_free, NULL);
839             pb_cache[key] = pb;
840         }
841     }
843     if ( pb ) {
844         // increase refcount since we're handing out ownership
845         g_object_ref(G_OBJECT(pb));
846     }
847     return pb;
850 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
851                             unsigned r, unsigned g, unsigned b)
853     int bytesPerPixel = 4;
854     int spacing = 4;
855     for ( int y = 0; y < height; y += spacing ) {
856         guchar *ptr = px + y * stride;
857         for ( int x = 0; x < width; x += spacing ) {
858             *(ptr++) = r;
859             *(ptr++) = g;
860             *(ptr++) = b;
861             *(ptr++) = 0xff;
863             ptr += bytesPerPixel * (spacing - 1);
864         }
865     }
867     if ( width > 1 && height > 1 ) {
868         // point at the last pixel
869         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
871         if ( width > 2 ) {
872             px[4] = r;
873             px[5] = g;
874             px[6] = b;
875             px[7] = 0xff;
877             ptr[-12] = r;
878             ptr[-11] = g;
879             ptr[-10] = b;
880             ptr[-9] = 0xff;
881         }
883         ptr[-4] = r;
884         ptr[-3] = g;
885         ptr[-2] = b;
886         ptr[-1] = 0xff;
888         px[0 + stride] = r;
889         px[1 + stride] = g;
890         px[2 + stride] = b;
891         px[3 + stride] = 0xff;
893         ptr[0 - stride] = r;
894         ptr[1 - stride] = g;
895         ptr[2 - stride] = b;
896         ptr[3 - stride] = 0xff;
898         if ( height > 2 ) {
899             ptr[0 - stride * 3] = r;
900             ptr[1 - stride * 3] = g;
901             ptr[2 - stride * 3] = b;
902             ptr[3 - stride * 3] = 0xff;
903         }
904     }
908 /*
909   Local Variables:
910   mode:c++
911   c-file-style:"stroustrup"
912   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
913   indent-tabs-mode:nil
914   fill-column:99
915   End:
916 */
917 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :