Code

401d76474b88add712638a4934cefbf4d285e300
[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( GtkIconSize 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, GtkIconSize 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( GtkIconSize lsize, GdkPixbuf* pb ) :
89         _lsize( lsize ),
90         _pb( pb )
91     {}
92     GtkIconSize _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, Inkscape::getRegisteredIconSize(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, GtkIconSize size);
268 static bool prerender_icon(gchar const *name, GtkIconSize 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) );
287         if ( !sizeMapDone ) {
288             injectCustomSize();
289         }
290         GtkIconSize mappedSize = iconSizeLookup[trySize];
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, mappedSize );
303             flagMe = true;
304             if ( dump ) {
305                 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, 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, mappedSize );
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, mappedSize );
319                     addPreRender( mappedSize, 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(static_cast<int>(mappedSize)) );
323                     if ( dump ) {
324                         g_message("      connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
325                     }
326                 }
327                 widget = GTK_WIDGET(img);
328                 img = 0;
329                 if ( dump ) {
330                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK) %s  on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
331                 }
332             } else if ( type == GTK_IMAGE_ICON_NAME ) {
333                 widget = GTK_WIDGET(img);
334                 img = 0;
336                 // Add a hook to render if set visible before prerender is done.
337                 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
339                 if ( prefs_get_int_attribute_limited( "options.iconrender", "named_nodelay", 0, 0, 1 ) ) {
340                     int psize = sp_icon_get_phys_size(lsize);
341                     prerender_icon(name, mappedSize, psize);
342                 } else {
343                     addPreRender( mappedSize, name );
344                 }
345             } else {
346                 if ( dump ) {
347                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
348                 }
349                 //g_object_unref( (GObject *)img );
350                 img = 0;
351             }
352         }
354     if ( !widget ) {
355         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
356         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
357         icon->lsize = lsize;
358         icon->name = g_strdup(name);
359         icon->psize = sp_icon_get_phys_size(lsize);
361         widget = GTK_WIDGET(icon);
362     }
364     return widget;
367 GtkWidget *
368 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
370     return sp_icon_new_full( lsize, name );
373 // PUBLIC CALL:
374 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
376     Gtk::Widget *result = 0;
377     GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
379     if ( widget ) {
380         if ( GTK_IS_IMAGE(widget) ) {
381             GtkImage *img = GTK_IMAGE(widget);
382             result = Glib::wrap( img );
383         } else {
384             result = Glib::wrap( widget );
385         }
386     }
388     return result;
391 GtkIconSize
392 sp_icon_get_gtk_size(int size)
394     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
395     size = CLAMP(size, 4, 63);
396     if (!sizemap[size]) {
397         static int count = 0;
398         char c[64];
399         g_snprintf(c, 64, "InkscapeIcon%d", count++);
400         sizemap[size] = gtk_icon_size_register(c, size, size);
401     }
402     return sizemap[size];
406 static void injectCustomSize()
408     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
409     if ( !sizeMapDone )
410     {
411         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
412         gint width = 0;
413         gint height = 0;
414         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
415             gint newWidth = ((width * 3) / 4);
416             gint newHeight = ((height * 3) / 4);
417             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
418             if ( newSizeEnum ) {
419                 if ( dump ) {
420                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
421                 }
422                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
423                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
424                     iconSizeLookup[index] = newSizeEnum;
425                 } else if ( dump ) {
426                     g_message("size lookup array too small to store entry");
427                 }
428             }
429         }
430         sizeMapDone = true;
431     }
433     static bool hit = false;
434     if ( !hit ) {
435         hit = true;
436         inkyIcons = Gtk::IconFactory::create();
437         inkyIcons->add_default();
438     }
441 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
443     GtkIconSize other = GTK_ICON_SIZE_MENU;
444     injectCustomSize();
445     size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
446     if ( size == Inkscape::ICON_SIZE_DECORATION ) {
447         other = gtk_icon_size_from_name("inkscape-decoration");
448     } else {
449         other = static_cast<GtkIconSize>(size);
450     }
452     return other;
456 // PUBLIC CALL:
457 int sp_icon_get_phys_size(int size)
459     static bool init = false;
460     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
461     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
463     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
465     if ( !sizeMapDone ) {
466         injectCustomSize();
467     }
469     if ( sizeDirty && init ) {
470         GtkIconSize const gtkSizes[] = {
471             GTK_ICON_SIZE_MENU,
472             GTK_ICON_SIZE_SMALL_TOOLBAR,
473             GTK_ICON_SIZE_LARGE_TOOLBAR,
474             GTK_ICON_SIZE_BUTTON,
475             GTK_ICON_SIZE_DND,
476             GTK_ICON_SIZE_DIALOG,
477             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
478                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
479                 GTK_ICON_SIZE_MENU
480         };
481         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
482             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
484             g_assert( val_ix < G_N_ELEMENTS(vals) );
486             gint width = 0;
487             gint height = 0;
488             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
489                 init &= (lastSys[val_ix] == std::max(width, height));
490             }
491         }
492     }
494     if ( !init ) {
495         sizeDirty = false;
496         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
498         if ( dump ) {
499             g_message( "Default icon sizes:" );
500         }
501         memset( vals, 0, sizeof(vals) );
502         memset( lastSys, 0, sizeof(lastSys) );
503         GtkIconSize const gtkSizes[] = {
504             GTK_ICON_SIZE_MENU,
505             GTK_ICON_SIZE_SMALL_TOOLBAR,
506             GTK_ICON_SIZE_LARGE_TOOLBAR,
507             GTK_ICON_SIZE_BUTTON,
508             GTK_ICON_SIZE_DND,
509             GTK_ICON_SIZE_DIALOG,
510             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
511                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
512                 GTK_ICON_SIZE_MENU
513         };
514         gchar const *const names[] = {
515             "GTK_ICON_SIZE_MENU",
516             "GTK_ICON_SIZE_SMALL_TOOLBAR",
517             "GTK_ICON_SIZE_LARGE_TOOLBAR",
518             "GTK_ICON_SIZE_BUTTON",
519             "GTK_ICON_SIZE_DND",
520             "GTK_ICON_SIZE_DIALOG",
521             "inkscape-decoration"
522         };
524         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
526         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
527             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
529             g_assert( val_ix < G_N_ELEMENTS(vals) );
531             gint width = 0;
532             gint height = 0;
533             bool used = false;
534             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
535                 vals[val_ix] = std::max(width, height);
536                 lastSys[val_ix] = vals[val_ix];
537                 used = true;
538             }
539             if (dump) {
540                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
541                           i, gtkSizes[i],
542                           ( used ? ' ' : 'X' ), width, height, names[i]);
543             }
544             gchar const *id = GTK_STOCK_OPEN;
545             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
546             if (pb) {
547                 width = gdk_pixbuf_get_width(pb);
548                 height = gdk_pixbuf_get_height(pb);
549                 int newSize = std::max( width, height );
550                 // TODO perhaps check a few more stock icons to get a range on sizes.
551                 if ( newSize > 0 ) {
552                     vals[val_ix] = newSize;
553                 }
554                 if (dump) {
555                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
556                 }
558                 g_object_unref(G_OBJECT(pb));
559             }
560         }
561         //g_object_unref(icon);
562         init = true;
563     }
565     return vals[size];
568 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
570     GtkWidget &widget = *GTK_WIDGET(icon);
572     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
574     if (image) {
575         int const padx = ( ( widget.allocation.width > icon->psize )
576                            ? ( widget.allocation.width - icon->psize ) / 2
577                            : 0 );
578         int const pady = ( ( widget.allocation.height > icon->psize )
579                            ? ( widget.allocation.height - icon->psize ) / 2
580                            : 0 );
582         int const x0 = std::max(area->x, widget.allocation.x + padx);
583         int const y0 = std::max(area->y, widget.allocation.y + pady);
584         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
585         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
587         int width = x1 - x0;
588         int height = y1 - y0;
589         // Limit drawing to when we actually have something. Avoids some crashes.
590         if ( (width > 0) && (height > 0) ) {
591             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
592                             x0 - widget.allocation.x - padx,
593                             y0 - widget.allocation.y - pady,
594                             x0, y0,
595                             width, height,
596                             GDK_RGB_DITHER_NORMAL, x0, y0);
597         }
598     }
601 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
603     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
604     // TODO: bulia, please look over
605     gsize bytesRead = 0;
606     gsize bytesWritten = 0;
607     GError *error = NULL;
608     gchar *localFilename = g_filename_from_utf8( path,
609                                                  -1,
610                                                  &bytesRead,
611                                                  &bytesWritten,
612                                                  &error);
613     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
614     g_free(localFilename);
615     g_free(path);
616     if (!pb) {
617         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
618         // TODO: bulia, please look over
619         gsize bytesRead = 0;
620         gsize bytesWritten = 0;
621         GError *error = NULL;
622         gchar *localFilename = g_filename_from_utf8( path,
623                                                      -1,
624                                                      &bytesRead,
625                                                      &bytesWritten,
626                                                      &error);
627         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
628         g_free(localFilename);
629         g_free(path);
630     }
632     if (pb) {
633         if (!gdk_pixbuf_get_has_alpha(pb)) {
634             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
635         }
637         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
638              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
639             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
640             g_object_unref(G_OBJECT(pb));
641             pb = spb;
642         }
643     }
645     return pb;
648 // takes doc, root, icon, and icon name to produce pixels
649 extern "C" guchar *
650 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
651                   gchar const *name, unsigned psize )
653     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
654     guchar *px = NULL;
656     if (doc) {
657         SPObject *object = doc->getObjectById(name);
658         if (object && SP_IS_ITEM(object)) {
659             /* Find bbox in document */
660             Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
661             boost::optional<Geom::Rect> dbox = SP_ITEM(object)->getBounds(i2doc);
663             if ( SP_OBJECT_PARENT(object) == NULL )
664             {
665                 dbox = Geom::Rect(Geom::Point(0, 0),
666                                 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
667             }
669             /* This is in document coordinates, i.e. pixels */
670             if ( dbox && !dbox->isEmpty() ) {
671                 NRGC gc(NULL);
672                 /* Update to renderable state */
673                 double sf = 1.0;
674                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
675                 gc.transform.setIdentity();
676                 nr_arena_item_invoke_update( root, NULL, &gc,
677                                              NR_ARENA_ITEM_STATE_ALL,
678                                              NR_ARENA_ITEM_STATE_NONE );
679                 /* Item integer bbox in points */
680                 NRRectL ibox;
681                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
682                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
683                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
684                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
686                 if ( dump ) {
687                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
688                 }
690                 /* Find button visible area */
691                 int width = ibox.x1 - ibox.x0;
692                 int height = ibox.y1 - ibox.y0;
694                 if ( dump ) {
695                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
696                 }
698                 {
699                     int block = std::max(width, height);
700                     if (block != static_cast<int>(psize) ) {
701                         if ( dump ) {
702                             g_message("      resizing" );
703                         }
704                         sf = (double)psize / (double)block;
706                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
707                         gc.transform.setIdentity();
708                         nr_arena_item_invoke_update( root, NULL, &gc,
709                                                      NR_ARENA_ITEM_STATE_ALL,
710                                                      NR_ARENA_ITEM_STATE_NONE );
711                         /* Item integer bbox in points */
712                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
713                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
714                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
715                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
717                         if ( dump ) {
718                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
719                         }
721                         /* Find button visible area */
722                         width = ibox.x1 - ibox.x0;
723                         height = ibox.y1 - ibox.y0;
724                         if ( dump ) {
725                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
726                         }
727                     }
728                 }
730                 int dx, dy;
731                 //dx = (psize - width) / 2;
732                 //dy = (psize - height) / 2;
733                 dx=dy=psize;
734                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
735                 dy=(dy-height)/2;
736                 NRRectL area;
737                 area.x0 = ibox.x0 - dx;
738                 area.y0 = ibox.y0 - dy;
739                 area.x1 = area.x0 + psize;
740                 area.y1 = area.y0 + psize;
741                 /* Actual renderable area */
742                 NRRectL ua;
743                 ua.x0 = MAX(ibox.x0, area.x0);
744                 ua.y0 = MAX(ibox.y0, area.y0);
745                 ua.x1 = MIN(ibox.x1, area.x1);
746                 ua.y1 = MIN(ibox.y1, area.y1);
748                 if ( dump ) {
749                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
750                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
751                 }
752                 /* Set up pixblock */
753                 px = g_new(guchar, 4 * psize * psize);
754                 memset(px, 0x00, 4 * psize * psize);
755                 /* Render */
756                 NRPixBlock B;
757                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
758                                           ua.x0, ua.y0, ua.x1, ua.y1,
759                                           px + 4 * psize * (ua.y0 - area.y0) +
760                                           4 * (ua.x0 - area.x0),
761                                           4 * psize, FALSE, FALSE );
762                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
763                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
764                 nr_pixblock_release(&B);
766                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
767                 if ( useOverlay ) {
768                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
769                 }
770             }
771         }
772     }
774     return px;
775 } // end of sp_icon_doc_icon()
779 struct svg_doc_cache_t
781     SPDocument *doc;
782     NRArenaItem *root;
783 };
785 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
786 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
788 Glib::ustring icon_cache_key(gchar const *name,
789                              unsigned lsize, unsigned psize)
791     Glib::ustring key=name;
792     key += ":";
793     key += lsize;
794     key += ":";
795     key += psize;
796     return key;
799 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
800     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
801     if ( found != pb_cache.end() ) {
802         return found->second;
803     }
804     return NULL;
807 static guchar *load_svg_pixels(gchar const *name,
808                                unsigned /*lsize*/, unsigned psize)
810     SPDocument *doc = NULL;
811     NRArenaItem *root = NULL;
812     svg_doc_cache_t *info = NULL;
814     // Fall back from user prefs dir into system locations.
815     Glib::ustring iconsvg = name;
816     iconsvg += ".svg";
817     std::list<gchar *> sources;
818     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
819     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
820     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
821     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
823     // Try each document in turn until we successfully load the icon from one
824     guchar *px=NULL;
825     while ( !sources.empty() && !px ) {
826         gchar *doc_filename = sources.front();
828         // Did we already load this doc?
829         Glib::ustring key(doc_filename);
830         info = 0;
831         {
832             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
833             if ( i != doc_cache.end() ) {
834                 info = i->second;
835             }
836         }
838         /* Try to load from document. */
839         if (!info &&
840             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
841             (doc = sp_document_new( doc_filename, FALSE )) ) {
843             // prep the document
844             sp_document_ensure_up_to_date(doc);
845             /* Create new arena */
846             NRArena *arena = NRArena::create();
847             /* Create ArenaItem and set transform */
848             unsigned visionkey = sp_item_display_key_new(1);
849             /* fixme: Memory manage root if needed (Lauris) */
850             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
851                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
853             // store into the cache
854             info = new svg_doc_cache_t;
855             g_assert(info);
857             info->doc=doc;
858             info->root=root;
859             doc_cache[key]=info;
860         }
861         if (info) {
862             doc=info->doc;
863             root=info->root;
864         }
866         // toss the filename
867         g_free(doc_filename);
868         sources.pop_front();
870         // move on to the next document if we couldn't get anything
871         if (!info && !doc) continue;
873         px = sp_icon_doc_icon( doc, root, name, psize );
874     }
876     return px;
879 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
881     if ( iconSetCache.find(name) == iconSetCache.end() ) {
882         // only add a placeholder if nothing is already set
883         Gtk::IconSet icnset;
884         Gtk::IconSource src;
885         src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
886         src.set_size( Gtk::IconSize(size) );
887         icnset.add_source(src);
888         inkyIcons->add(Gtk::StockID(name), icnset);
889     }
892 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
893     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
894     GtkStockItem stock;
895     gboolean stockFound = gtk_stock_lookup( name, &stock );
896     if ( !stockFound ) {
897         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
898         if (dump) {
899             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
900         }
901     }
903     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
904         if ( it->_lsize == lsize ) {
905             iconSetCache[name].erase(it);
906             break;
907         }
908     }
909     iconSetCache[name].push_back(IconCacheItem(lsize, pb));
911     Gtk::IconSet icnset;
912     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
913         Gtk::IconSource src;
914         g_object_ref( G_OBJECT(it->_pb) );
915         src.set_pixbuf( Glib::wrap(it->_pb) );
916         src.set_size( Gtk::IconSize(it->_lsize) );
917         src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
918         src.set_state_wildcarded( true );
919         icnset.add_source(src);
920     }
921     inkyIcons->add(Gtk::StockID(name), icnset);
924 // returns true if icon needed preloading, false if nothing was done
925 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
927     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
928     Glib::ustring key = icon_cache_key(name, lsize, psize);
929     GdkPixbuf *pb = get_cached_pixbuf(key);
930     if (pb) {
931         return false;
932     } else {
933         guchar* px = load_svg_pixels(name, lsize, psize);
934         if ( !px ) {
935             // check for a fallback name
936             if ( legacyNames.find(name) != legacyNames.end() ) {
937                 if ( dump ) {
938                     g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
939                 }
940                 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
941             }
942         }
944         if (px) {
945             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
946                                           psize, psize, psize * 4,
947                                           (GdkPixbufDestroyNotify)g_free, NULL);
948             pb_cache[key] = pb;
949             addToIconSet(pb, name, lsize, psize);
950         } else if (dump) {
951             g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
952         }
953         return true;
954     }
957 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
959     Glib::ustring key = icon_cache_key(name, lsize, psize);
961     // did we already load this icon at this scale/size?
962     GdkPixbuf* pb = get_cached_pixbuf(key);
963     if (!pb) {
964         guchar *px = load_svg_pixels(name, lsize, psize);
965         if (px) {
966             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
967                                           psize, psize, psize * 4,
968                                           (GdkPixbufDestroyNotify)g_free, NULL);
969             pb_cache[key] = pb;
970             addToIconSet(pb, name, lsize, psize);
971         }
972     }
974     if ( pb ) {
975         // increase refcount since we're handing out ownership
976         g_object_ref(G_OBJECT(pb));
977     }
978     return pb;
981 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
982                             unsigned r, unsigned g, unsigned b)
984     for ( int y = 0; y < height; y += 4 ) {
985         guchar *ptr = px + y * stride;
986         for ( int x = 0; x < width; x += 4 ) {
987             *(ptr++) = r;
988             *(ptr++) = g;
989             *(ptr++) = b;
990             *(ptr++) = 0xff;
992             ptr += 4 * 3;
993         }
994     }
996     if ( width > 1 && height > 1 ) {
997         // point at the last pixel
998         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
1000         if ( width > 2 ) {
1001             px[4] = r;
1002             px[5] = g;
1003             px[6] = b;
1004             px[7] = 0xff;
1006             ptr[-12] = r;
1007             ptr[-11] = g;
1008             ptr[-10] = b;
1009             ptr[-9] = 0xff;
1010         }
1012         ptr[-4] = r;
1013         ptr[-3] = g;
1014         ptr[-2] = b;
1015         ptr[-1] = 0xff;
1017         px[0 + stride] = r;
1018         px[1 + stride] = g;
1019         px[2 + stride] = b;
1020         px[3 + stride] = 0xff;
1022         ptr[0 - stride] = r;
1023         ptr[1 - stride] = g;
1024         ptr[2 - stride] = b;
1025         ptr[3 - stride] = 0xff;
1027         if ( height > 2 ) {
1028             ptr[0 - stride * 3] = r;
1029             ptr[1 - stride * 3] = g;
1030             ptr[2 - stride * 3] = b;
1031             ptr[3 - stride * 3] = 0xff;
1032         }
1033     }
1036 class preRenderItem
1038 public:
1039     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1040         _lsize( lsize ),
1041         _name( name )
1042     {}
1043     GtkIconSize _lsize;
1044     Glib::ustring _name;
1045 };
1048 static std::vector<preRenderItem> pendingRenders;
1049 static bool callbackHooked = false;
1051 static void addPreRender( GtkIconSize lsize, gchar const *name )
1053     if ( !callbackHooked )
1054     {
1055         callbackHooked = true;
1056         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1057     }
1059     pendingRenders.push_back(preRenderItem(lsize, name));
1062 gboolean icon_prerender_task(gpointer /*data*/) {
1063     if (!pendingRenders.empty()) {
1064         bool workDone = false;
1065         do {
1066             preRenderItem single = pendingRenders.front();
1067             pendingRenders.erase(pendingRenders.begin());
1068             int psize = sp_icon_get_phys_size(single._lsize);
1069             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1070         } while (!pendingRenders.empty() && !workDone);
1071     }
1073     if (!pendingRenders.empty()) {
1074         return TRUE;
1075     } else {
1076         callbackHooked = false;
1077         return FALSE;
1078     }
1082 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1083     gchar* id = 0;
1084     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1085     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1086     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1087     if ( id ) {
1088         int psize = sp_icon_get_phys_size(lsize);
1089         //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1090         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1091             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1092                 prerender_icon(id, lsize, psize);
1093                 pendingRenders.erase(it);
1094                 //g_message("    prerender for %s:%d:%d", id, lsize, psize);
1095                 if (lsize != size) {
1096                     int psize = sp_icon_get_phys_size(size);
1097                     prerender_icon(id, size, psize);
1098                 }
1099                 break;
1100             }
1101         }
1102     }
1104     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1107 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1108     GtkImage* img = GTK_IMAGE(widget);
1109     gchar const* iconName = 0;
1110     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1111     gtk_image_get_icon_name(img, &iconName, &size);
1112     if ( iconName ) {
1113         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1114         if ( type == GTK_IMAGE_ICON_NAME ) {
1115             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1116                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1117                     int psize = sp_icon_get_phys_size(size);
1118                     prerender_icon(iconName, size, psize);
1119                     pendingRenders.erase(it);
1120                     break;
1121                 }
1122             }
1124         } else {
1125             g_warning("UNEXPECTED TYPE of %d", (int)type);
1126         }
1127     }
1129     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1133 /*
1134   Local Variables:
1135   mode:c++
1136   c-file-style:"stroustrup"
1137   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1138   indent-tabs-mode:nil
1139   fill-column:99
1140   End:
1141 */
1142 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :