Code

Cleanup of named icon background rendering and added pref for workaround
[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/gtkiconfactory.h>
21 #include <gtk/gtkstock.h>
22 #include <gtk/gtkimage.h>
23 #include <gtkmm/iconfactory.h>
24 #include <gtkmm/iconset.h>
25 #include <gtkmm/iconsource.h>
26 #include <gtkmm/icontheme.h>
27 #include <gtkmm/image.h>
29 #include "path-prefix.h"
30 #include "prefs-utils.h"
31 #include "inkscape.h"
32 #include "document.h"
33 #include "sp-item.h"
34 #include "display/nr-arena.h"
35 #include "display/nr-arena-item.h"
36 #include "io/sys.h"
38 #include "icon.h"
40 static gboolean icon_prerender_task(gpointer data);
42 static void addPreRender( Inkscape::IconSize lsize, gchar const *name );
44 static void sp_icon_class_init(SPIconClass *klass);
45 static void sp_icon_init(SPIcon *icon);
46 static void sp_icon_destroy(GtkObject *object);
48 static void sp_icon_reset(SPIcon *icon);
49 static void sp_icon_clear(SPIcon *icon);
51 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
52 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
53 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
55 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
57 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
58 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
59 static void sp_icon_theme_changed( SPIcon *icon );
61 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
62 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize);
64 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
65                                     unsigned r, unsigned g, unsigned b );
67 static void injectCustomSize();
69 static GtkWidgetClass *parent_class;
71 static bool sizeDirty = true;
73 static bool sizeMapDone = false;
74 static GtkIconSize iconSizeLookup[] = {
75     GTK_ICON_SIZE_INVALID,
76     GTK_ICON_SIZE_MENU,
77     GTK_ICON_SIZE_SMALL_TOOLBAR,
78     GTK_ICON_SIZE_LARGE_TOOLBAR,
79     GTK_ICON_SIZE_BUTTON,
80     GTK_ICON_SIZE_DND,
81     GTK_ICON_SIZE_DIALOG,
82     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
83 };
85 class IconCacheItem
86 {
87 public:
88     IconCacheItem( Inkscape::IconSize lsize, GdkPixbuf* pb ) :
89         _lsize( lsize ),
90         _pb( pb )
91     {}
92     Inkscape::IconSize _lsize;
93     GdkPixbuf* _pb;
94 };
96 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
97 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
99 GtkType
100 sp_icon_get_type()
102     static GtkType type = 0;
103     if (!type) {
104         GtkTypeInfo info = {
105             "SPIcon",
106             sizeof(SPIcon),
107             sizeof(SPIconClass),
108             (GtkClassInitFunc) sp_icon_class_init,
109             (GtkObjectInitFunc) sp_icon_init,
110             NULL, NULL, NULL
111         };
112         type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
113     }
114     return type;
117 static void
118 sp_icon_class_init(SPIconClass *klass)
120     GtkObjectClass *object_class;
121     GtkWidgetClass *widget_class;
123     object_class = (GtkObjectClass *) klass;
124     widget_class = (GtkWidgetClass *) klass;
126     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
128     object_class->destroy = sp_icon_destroy;
130     widget_class->size_request = sp_icon_size_request;
131     widget_class->size_allocate = sp_icon_size_allocate;
132     widget_class->expose_event = sp_icon_expose;
133     widget_class->screen_changed = sp_icon_screen_changed;
134     widget_class->style_set = sp_icon_style_set;
138 static void
139 sp_icon_init(SPIcon *icon)
141     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
142     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
143     icon->psize = 0;
144     icon->name = 0;
145     icon->pb = 0;
146     icon->pb_faded = 0;
149 static void
150 sp_icon_destroy(GtkObject *object)
152     SPIcon *icon = SP_ICON(object);
153     sp_icon_clear(icon);
154     if ( icon->name ) {
155         g_free( icon->name );
156         icon->name = 0;
157     }
159     ((GtkObjectClass *) (parent_class))->destroy(object);
162 static void sp_icon_reset( SPIcon *icon ) {
163     icon->psize = 0;
164     sp_icon_clear(icon);
167 static void sp_icon_clear( SPIcon *icon ) {
168     if (icon->pb) {
169         g_object_unref(G_OBJECT(icon->pb));
170         icon->pb = NULL;
171     }
172     if (icon->pb_faded) {
173         g_object_unref(G_OBJECT(icon->pb_faded));
174         icon->pb_faded = NULL;
175     }
178 static void
179 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
181     SPIcon const *icon = SP_ICON(widget);
183     int const size = ( icon->psize
184                        ? icon->psize
185                        : sp_icon_get_phys_size(icon->lsize) );
186     requisition->width = size;
187     requisition->height = size;
190 static void
191 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
193     widget->allocation = *allocation;
195     if (GTK_WIDGET_DRAWABLE(widget)) {
196         gtk_widget_queue_draw(widget);
197     }
200 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
202     if ( GTK_WIDGET_DRAWABLE(widget) ) {
203         SPIcon *icon = SP_ICON(widget);
204         if ( !icon->pb ) {
205             sp_icon_fetch_pixbuf( icon );
206         }
208         sp_icon_paint(SP_ICON(widget), &event->area);
209     }
211     return TRUE;
214 // PUBLIC CALL:
215 void sp_icon_fetch_pixbuf( SPIcon *icon )
217     if ( icon ) {
218         if ( !icon->pb ) {
219             icon->psize = sp_icon_get_phys_size(icon->lsize);
221             GdkPixbuf *pb = sp_icon_image_load_svg( icon->name, icon->lsize, icon->psize );
222             if (!pb) {
223                 pb = sp_icon_image_load_pixmap( icon->name, icon->lsize, icon->psize );
224             }
226             if ( pb ) {
227                 icon->pb = pb;
228                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
229                 gdk_pixbuf_saturate_and_pixelate(icon->pb, icon->pb_faded, 0.5, TRUE);
230             } else {
231                 /* TODO: We should do something more useful if we can't load the image. */
232                 g_warning ("failed to load icon '%s'", icon->name);
233             }
234         }
235     }
238 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
240     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
241         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
242     }
243     SPIcon *icon = SP_ICON(widget);
244     sp_icon_theme_changed(icon);
247 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
249     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
250         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
251     }
252     SPIcon *icon = SP_ICON(widget);
253     sp_icon_theme_changed(icon);
256 static void sp_icon_theme_changed( SPIcon *icon )
258     //g_message("Got a change bump for this icon");
259     sizeDirty = true;
260     sp_icon_reset(icon);
261     gtk_widget_queue_draw( GTK_WIDGET(icon) );
265 static void imageMapCB(GtkWidget* widget, gpointer user_data);
266 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
267 static void populate_placeholder_icon(gchar const* name, unsigned lsize);
268 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize);
269 static Glib::ustring icon_cache_key(gchar const *name, unsigned lsize, unsigned psize);
270 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
272 std::map<Glib::ustring, Glib::ustring> legacyNames;
274 static void setupLegacyNaming() {
275     legacyNames["view-fullscreen"] = "fullscreen";
276     legacyNames["edit-select-all"] = "selection_select_all";
277     legacyNames["window-new"] = "view_new";
280 static GtkWidget *
281 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
283     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
285     GtkWidget *widget = 0;
286         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
288         if ( !sizeMapDone ) {
289             injectCustomSize();
290         }
292         GtkStockItem stock;
293         gboolean stockFound = gtk_stock_lookup( name, &stock );
295         GtkWidget *img = 0;
296         if ( legacyNames.empty() ) {
297             setupLegacyNaming();
298         }
300         bool flagMe = false;
301         if ( legacyNames.find(name) != legacyNames.end() ) {
302             img = gtk_image_new_from_icon_name( name, iconSizeLookup[trySize] );
303             flagMe = true;
304             if ( dump ) {
305                 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, iconSizeLookup[trySize], img);
306                 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
307                 g_message("      Type is %d  %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
308             }
309         } else {
310             img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
311         }
313         if ( img ) {
314             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
315             if ( type == GTK_IMAGE_STOCK ) {
316                 if ( !stockFound ) {
317                     // It's not showing as a stock ID, so assume it will be present internally
318                     populate_placeholder_icon( name, lsize );
319                     addPreRender( lsize, name );
321                     // Add a hook to render if set visible before prerender is done.
322                     g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(0) );
323                 }
324                 widget = GTK_WIDGET(img);
325                 img = 0;
326                 if ( dump ) {
327                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK) %s", name, lsize, (stockFound ? "STOCK" : "local") );
328                 }
329             } else if ( type == GTK_IMAGE_ICON_NAME ) {
330                 widget = GTK_WIDGET(img);
331                 img = 0;
333                 // Add a hook to render if set visible before prerender is done.
334                 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
336                 if ( prefs_get_int_attribute_limited( "options.iconrender", "named_nodelay", 0, 0, 1 ) ) {
337                     int psize = sp_icon_get_phys_size(lsize);
338                     prerender_icon(name, lsize, psize);
339                 } else {
340                     addPreRender( lsize, name );
341                 }
342             } else {
343                 if ( dump ) {
344                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
345                 }
346                 //g_object_unref( (GObject *)img );
347                 img = 0;
348             }
349         }
351     if ( !widget ) {
352         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
353         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
354         icon->lsize = lsize;
355         icon->name = g_strdup(name);
356         icon->psize = sp_icon_get_phys_size(lsize);
358         widget = GTK_WIDGET(icon);
359     }
361     return widget;
364 GtkWidget *
365 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
367     return sp_icon_new_full( lsize, name );
370 // PUBLIC CALL:
371 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
373     Gtk::Widget *result = 0;
374     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
376     if ( widget ) {
377         if ( GTK_IS_IMAGE(widget) ) {
378             GtkImage *img = GTK_IMAGE(widget);
379             result = Glib::wrap( img );
380         } else {
381             result = Glib::wrap( widget );
382         }
383     }
385     return result;
388 GtkIconSize
389 sp_icon_get_gtk_size(int size)
391     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
392     size = CLAMP(size, 4, 63);
393     if (!sizemap[size]) {
394         static int count = 0;
395         char c[64];
396         g_snprintf(c, 64, "InkscapeIcon%d", count++);
397         sizemap[size] = gtk_icon_size_register(c, size, size);
398     }
399     return sizemap[size];
402 static void injectCustomSize()
404     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
405     if ( !sizeMapDone )
406     {
407         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
408         gint width = 0;
409         gint height = 0;
410         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
411             gint newWidth = ((width * 3) / 4);
412             gint newHeight = ((height * 3) / 4);
413             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
414             if ( newSizeEnum ) {
415                 if ( dump ) {
416                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
417                 }
418                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
419                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
420                     iconSizeLookup[index] = newSizeEnum;
421                 } else if ( dump ) {
422                     g_message("size lookup array too small to store entry");
423                 }
424             }
425         }
426         sizeMapDone = true;
427     }
429     static bool hit = false;
430     if ( !hit ) {
431         hit = true;
432         inkyIcons = Gtk::IconFactory::create();
433         inkyIcons->add_default();
434     }
437 // PUBLIC CALL:
438 int sp_icon_get_phys_size(int size)
440     static bool init = false;
441     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
442     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
444     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
446     if ( !sizeMapDone ) {
447         injectCustomSize();
448     }
450     if ( sizeDirty && init ) {
451         GtkIconSize const gtkSizes[] = {
452             GTK_ICON_SIZE_MENU,
453             GTK_ICON_SIZE_SMALL_TOOLBAR,
454             GTK_ICON_SIZE_LARGE_TOOLBAR,
455             GTK_ICON_SIZE_BUTTON,
456             GTK_ICON_SIZE_DND,
457             GTK_ICON_SIZE_DIALOG,
458             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
459                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
460                 GTK_ICON_SIZE_MENU
461         };
462         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++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             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
470                 init &= (lastSys[val_ix] == std::max(width, height));
471             }
472         }
473     }
475     if ( !init ) {
476         sizeDirty = false;
477         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
479         if ( dump ) {
480             g_message( "Default icon sizes:" );
481         }
482         memset( vals, 0, sizeof(vals) );
483         memset( lastSys, 0, sizeof(lastSys) );
484         GtkIconSize const gtkSizes[] = {
485             GTK_ICON_SIZE_MENU,
486             GTK_ICON_SIZE_SMALL_TOOLBAR,
487             GTK_ICON_SIZE_LARGE_TOOLBAR,
488             GTK_ICON_SIZE_BUTTON,
489             GTK_ICON_SIZE_DND,
490             GTK_ICON_SIZE_DIALOG,
491             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
492                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
493                 GTK_ICON_SIZE_MENU
494         };
495         gchar const *const names[] = {
496             "GTK_ICON_SIZE_MENU",
497             "GTK_ICON_SIZE_SMALL_TOOLBAR",
498             "GTK_ICON_SIZE_LARGE_TOOLBAR",
499             "GTK_ICON_SIZE_BUTTON",
500             "GTK_ICON_SIZE_DND",
501             "GTK_ICON_SIZE_DIALOG",
502             "inkscape-decoration"
503         };
505         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
507         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
508             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
510             g_assert( val_ix < G_N_ELEMENTS(vals) );
512             gint width = 0;
513             gint height = 0;
514             bool used = false;
515             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
516                 vals[val_ix] = std::max(width, height);
517                 lastSys[val_ix] = vals[val_ix];
518                 used = true;
519             }
520             if (dump) {
521                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
522                           i, gtkSizes[i],
523                           ( used ? ' ' : 'X' ), width, height, names[i]);
524             }
525             gchar const *id = GTK_STOCK_OPEN;
526             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
527             if (pb) {
528                 width = gdk_pixbuf_get_width(pb);
529                 height = gdk_pixbuf_get_height(pb);
530                 int newSize = std::max( width, height );
531                 // TODO perhaps check a few more stock icons to get a range on sizes.
532                 if ( newSize > 0 ) {
533                     vals[val_ix] = newSize;
534                 }
535                 if (dump) {
536                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
537                 }
539                 g_object_unref(G_OBJECT(pb));
540             }
541         }
542         //g_object_unref(icon);
543         init = true;
544     }
546     return vals[size];
549 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
551     GtkWidget &widget = *GTK_WIDGET(icon);
553     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
555     if (image) {
556         int const padx = ( ( widget.allocation.width > icon->psize )
557                            ? ( widget.allocation.width - icon->psize ) / 2
558                            : 0 );
559         int const pady = ( ( widget.allocation.height > icon->psize )
560                            ? ( widget.allocation.height - icon->psize ) / 2
561                            : 0 );
563         int const x0 = std::max(area->x, widget.allocation.x + padx);
564         int const y0 = std::max(area->y, widget.allocation.y + pady);
565         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
566         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
568         int width = x1 - x0;
569         int height = y1 - y0;
570         // Limit drawing to when we actually have something. Avoids some crashes.
571         if ( (width > 0) && (height > 0) ) {
572             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
573                             x0 - widget.allocation.x - padx,
574                             y0 - widget.allocation.y - pady,
575                             x0, y0,
576                             width, height,
577                             GDK_RGB_DITHER_NORMAL, x0, y0);
578         }
579     }
582 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
584     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
585     // TODO: bulia, please look over
586     gsize bytesRead = 0;
587     gsize bytesWritten = 0;
588     GError *error = NULL;
589     gchar *localFilename = g_filename_from_utf8( path,
590                                                  -1,
591                                                  &bytesRead,
592                                                  &bytesWritten,
593                                                  &error);
594     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
595     g_free(localFilename);
596     g_free(path);
597     if (!pb) {
598         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
599         // TODO: bulia, please look over
600         gsize bytesRead = 0;
601         gsize bytesWritten = 0;
602         GError *error = NULL;
603         gchar *localFilename = g_filename_from_utf8( path,
604                                                      -1,
605                                                      &bytesRead,
606                                                      &bytesWritten,
607                                                      &error);
608         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
609         g_free(localFilename);
610         g_free(path);
611     }
613     if (pb) {
614         if (!gdk_pixbuf_get_has_alpha(pb)) {
615             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
616         }
618         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
619              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
620             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
621             g_object_unref(G_OBJECT(pb));
622             pb = spb;
623         }
624     }
626     return pb;
629 // takes doc, root, icon, and icon name to produce pixels
630 extern "C" guchar *
631 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
632                   gchar const *name, unsigned psize )
634     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
635     guchar *px = NULL;
637     if (doc) {
638         SPObject *object = doc->getObjectById(name);
639         if (object && SP_IS_ITEM(object)) {
640             /* Find bbox in document */
641             Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
642             boost::optional<NR::Rect> nrdbox = SP_ITEM(object)->getBounds(i2doc);
643             boost::optional<Geom::Rect> dbox;
644             if (nrdbox) {
645                 dbox = to_2geom(*nrdbox);
646             }
648             if ( SP_OBJECT_PARENT(object) == NULL )
649             {
650                 dbox = Geom::Rect(Geom::Point(0, 0),
651                                 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
652             }
654             /* This is in document coordinates, i.e. pixels */
655             if ( dbox && !dbox->isEmpty() ) {
656                 NRGC gc(NULL);
657                 /* Update to renderable state */
658                 double sf = 1.0;
659                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
660                 gc.transform.set_identity();
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                 NRRectL ibox;
666                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
667                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
668                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
669                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
671                 if ( dump ) {
672                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
673                 }
675                 /* Find button visible area */
676                 int width = ibox.x1 - ibox.x0;
677                 int height = ibox.y1 - ibox.y0;
679                 if ( dump ) {
680                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
681                 }
683                 {
684                     int block = std::max(width, height);
685                     if (block != static_cast<int>(psize) ) {
686                         if ( dump ) {
687                             g_message("      resizing" );
688                         }
689                         sf = (double)psize / (double)block;
691                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
692                         gc.transform.set_identity();
693                         nr_arena_item_invoke_update( root, NULL, &gc,
694                                                      NR_ARENA_ITEM_STATE_ALL,
695                                                      NR_ARENA_ITEM_STATE_NONE );
696                         /* Item integer bbox in points */
697                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
698                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
699                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
700                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
702                         if ( dump ) {
703                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
704                         }
706                         /* Find button visible area */
707                         width = ibox.x1 - ibox.x0;
708                         height = ibox.y1 - ibox.y0;
709                         if ( dump ) {
710                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
711                         }
712                     }
713                 }
715                 int dx, dy;
716                 //dx = (psize - width) / 2;
717                 //dy = (psize - height) / 2;
718                 dx=dy=psize;
719                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
720                 dy=(dy-height)/2;
721                 NRRectL area;
722                 area.x0 = ibox.x0 - dx;
723                 area.y0 = ibox.y0 - dy;
724                 area.x1 = area.x0 + psize;
725                 area.y1 = area.y0 + psize;
726                 /* Actual renderable area */
727                 NRRectL ua;
728                 ua.x0 = MAX(ibox.x0, area.x0);
729                 ua.y0 = MAX(ibox.y0, area.y0);
730                 ua.x1 = MIN(ibox.x1, area.x1);
731                 ua.y1 = MIN(ibox.y1, area.y1);
733                 if ( dump ) {
734                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
735                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
736                 }
737                 /* Set up pixblock */
738                 px = g_new(guchar, 4 * psize * psize);
739                 memset(px, 0x00, 4 * psize * psize);
740                 /* Render */
741                 NRPixBlock B;
742                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
743                                           ua.x0, ua.y0, ua.x1, ua.y1,
744                                           px + 4 * psize * (ua.y0 - area.y0) +
745                                           4 * (ua.x0 - area.x0),
746                                           4 * psize, FALSE, FALSE );
747                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
748                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
749                 nr_pixblock_release(&B);
751                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
752                 if ( useOverlay ) {
753                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
754                 }
755             }
756         }
757     }
759     return px;
760 } // end of sp_icon_doc_icon()
764 struct svg_doc_cache_t
766     SPDocument *doc;
767     NRArenaItem *root;
768 };
770 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
771 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
773 Glib::ustring icon_cache_key(gchar const *name,
774                              unsigned lsize, unsigned psize)
776     Glib::ustring key=name;
777     key += ":";
778     key += lsize;
779     key += ":";
780     key += psize;
781     return key;
784 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
785     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
786     if ( found != pb_cache.end() ) {
787         return found->second;
788     }
789     return NULL;
792 static guchar *load_svg_pixels(gchar const *name,
793                                unsigned /*lsize*/, unsigned psize)
795     SPDocument *doc = NULL;
796     NRArenaItem *root = NULL;
797     svg_doc_cache_t *info = NULL;
799     // Fall back from user prefs dir into system locations.
800     Glib::ustring iconsvg = name;
801     iconsvg += ".svg";
802     std::list<gchar *> sources;
803     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
804     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
805     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
806     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
808     // Try each document in turn until we successfully load the icon from one
809     guchar *px=NULL;
810     while ( !sources.empty() && !px ) {
811         gchar *doc_filename = sources.front();
813         // Did we already load this doc?
814         Glib::ustring key(doc_filename);
815         info = 0;
816         {
817             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
818             if ( i != doc_cache.end() ) {
819                 info = i->second;
820             }
821         }
823         /* Try to load from document. */
824         if (!info &&
825             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
826             (doc = sp_document_new( doc_filename, FALSE )) ) {
828             // prep the document
829             sp_document_ensure_up_to_date(doc);
830             /* Create new arena */
831             NRArena *arena = NRArena::create();
832             /* Create ArenaItem and set transform */
833             unsigned visionkey = sp_item_display_key_new(1);
834             /* fixme: Memory manage root if needed (Lauris) */
835             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
836                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
838             // store into the cache
839             info = new svg_doc_cache_t;
840             g_assert(info);
842             info->doc=doc;
843             info->root=root;
844             doc_cache[key]=info;
845         }
846         if (info) {
847             doc=info->doc;
848             root=info->root;
849         }
851         // toss the filename
852         g_free(doc_filename);
853         sources.pop_front();
855         // move on to the next document if we couldn't get anything
856         if (!info && !doc) continue;
858         px = sp_icon_doc_icon( doc, root, name, psize );
859     }
861     return px;
864 static void populate_placeholder_icon(gchar const* name, unsigned lsize)
866     if ( iconSetCache.find(name) == iconSetCache.end() ) {
867         // only add a placeholder if nothing is already set
868         Gtk::IconSet icnset;
869         Gtk::IconSource src;
870         src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
871         src.set_size( Gtk::IconSize(lsize) );
872         icnset.add_source(src);
873         inkyIcons->add(Gtk::StockID(name), icnset);
874     }
877 static void addToIconSet(GdkPixbuf* pb, gchar const* name, unsigned lsize, unsigned psize) {
878     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
879     GtkStockItem stock;
880     gboolean stockFound = gtk_stock_lookup( name, &stock );
881     if ( !stockFound ) {
882         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
883         if (dump) {
884             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
885         }
886     }
888     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
889         if ( it->_lsize == Inkscape::IconSize(lsize) ) {
890             iconSetCache[name].erase(it);
891             break;
892         }
893     }
894     iconSetCache[name].push_back(IconCacheItem(Inkscape::IconSize(lsize), pb));
896     Gtk::IconSet icnset;
897     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
898         Gtk::IconSource src;
899         g_object_ref( G_OBJECT(it->_pb) );
900         src.set_pixbuf( Glib::wrap(it->_pb) );
901         src.set_size( Gtk::IconSize(it->_lsize) );
902         src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
903         src.set_state_wildcarded( true );
904         icnset.add_source(src);
905     }
906     inkyIcons->add(Gtk::StockID(name), icnset);
909 // returns true if icon needed preloading, false if nothing was done
910 bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
912     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
913     Glib::ustring key = icon_cache_key(name, lsize, psize);
914     GdkPixbuf *pb = get_cached_pixbuf(key);
915     if (pb) {
916         return false;
917     } else {
918         guchar* px = load_svg_pixels(name, lsize, psize);
919         if ( !px ) {
920             // check for a fallback name
921             if ( legacyNames.find(name) != legacyNames.end() ) {
922                 if ( dump ) {
923                     g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
924                 }
925                 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
926             }
927         }
929         if (px) {
930             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
931                                           psize, psize, psize * 4,
932                                           (GdkPixbufDestroyNotify)g_free, NULL);
933             pb_cache[key] = pb;
934             addToIconSet(pb, name, lsize, psize);
935         } else if (dump) {
936             g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
937         }
938         return true;
939     }
942 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
944     Glib::ustring key = icon_cache_key(name, lsize, psize);
946     // did we already load this icon at this scale/size?
947     GdkPixbuf* pb = get_cached_pixbuf(key);
948     if (!pb) {
949         guchar *px = load_svg_pixels(name, lsize, psize);
950         if (px) {
951             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
952                                           psize, psize, psize * 4,
953                                           (GdkPixbufDestroyNotify)g_free, NULL);
954             pb_cache[key] = pb;
955             addToIconSet(pb, name, lsize, psize);
956         }
957     }
959     if ( pb ) {
960         // increase refcount since we're handing out ownership
961         g_object_ref(G_OBJECT(pb));
962     }
963     return pb;
966 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
967                             unsigned r, unsigned g, unsigned b)
969     for ( int y = 0; y < height; y += 4 ) {
970         guchar *ptr = px + y * stride;
971         for ( int x = 0; x < width; x += 4 ) {
972             *(ptr++) = r;
973             *(ptr++) = g;
974             *(ptr++) = b;
975             *(ptr++) = 0xff;
977             ptr += 4 * 3;
978         }
979     }
981     if ( width > 1 && height > 1 ) {
982         // point at the last pixel
983         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
985         if ( width > 2 ) {
986             px[4] = r;
987             px[5] = g;
988             px[6] = b;
989             px[7] = 0xff;
991             ptr[-12] = r;
992             ptr[-11] = g;
993             ptr[-10] = b;
994             ptr[-9] = 0xff;
995         }
997         ptr[-4] = r;
998         ptr[-3] = g;
999         ptr[-2] = b;
1000         ptr[-1] = 0xff;
1002         px[0 + stride] = r;
1003         px[1 + stride] = g;
1004         px[2 + stride] = b;
1005         px[3 + stride] = 0xff;
1007         ptr[0 - stride] = r;
1008         ptr[1 - stride] = g;
1009         ptr[2 - stride] = b;
1010         ptr[3 - stride] = 0xff;
1012         if ( height > 2 ) {
1013             ptr[0 - stride * 3] = r;
1014             ptr[1 - stride * 3] = g;
1015             ptr[2 - stride * 3] = b;
1016             ptr[3 - stride * 3] = 0xff;
1017         }
1018     }
1021 class preRenderItem
1023 public:
1024     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
1025         _lsize( lsize ),
1026         _name( name )
1027     {}
1028     Inkscape::IconSize _lsize;
1029     Glib::ustring _name;
1030 };
1033 static std::vector<preRenderItem> pendingRenders;
1034 static bool callbackHooked = false;
1036 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
1038     if ( !callbackHooked )
1039     {
1040         callbackHooked = true;
1041         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1042     }
1044     pendingRenders.push_back(preRenderItem(lsize, name));
1047 gboolean icon_prerender_task(gpointer /*data*/) {
1048     if (!pendingRenders.empty()) {
1049         bool workDone = false;
1050         do {
1051             preRenderItem single = pendingRenders.front();
1052             pendingRenders.erase(pendingRenders.begin());
1053             int psize = sp_icon_get_phys_size(single._lsize);
1054             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1055         } while (!pendingRenders.empty() && !workDone);
1056     }
1058     if (!pendingRenders.empty()) {
1059         return TRUE;
1060     } else {
1061         callbackHooked = false;
1062         return FALSE;
1063     }
1067 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1068     gchar* id = 0;
1069     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1070     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1071     if ( id ) {
1072         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1073             if ( (it->_name == id) && (it->_lsize == static_cast<Inkscape::IconSize>(size)) ) {
1074                 int psize = sp_icon_get_phys_size(size);
1075                 prerender_icon(id, size, psize);
1076                 pendingRenders.erase(it);
1077                 break;
1078             }
1079         }
1080     }
1082     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1085 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1086     GtkImage* img = GTK_IMAGE(widget);
1087     gchar const* iconName = 0;
1088     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1089     gtk_image_get_icon_name(img, &iconName, &size);
1090     if ( iconName ) {
1091         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1092         if ( type == GTK_IMAGE_ICON_NAME ) {
1093             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1094                 if ( (it->_name == iconName) && (it->_lsize == static_cast<Inkscape::IconSize>(size)) ) {
1095                     int psize = sp_icon_get_phys_size(size);
1096                     prerender_icon(iconName, size, psize);
1097                     pendingRenders.erase(it);
1098                     break;
1099                 }
1100             }
1102         } else {
1103             g_warning("UNEXPECTED TYPE of %d", (int)type);
1104         }
1105     }
1107     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1111 /*
1112   Local Variables:
1113   mode:c++
1114   c-file-style:"stroustrup"
1115   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1116   indent-tabs-mode:nil
1117   fill-column:99
1118   End:
1119 */
1120 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :