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 "preferences.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()
101 {
102 //TODO: switch to GObject
103 // GtkType and such calls were deprecated a while back with the
104 // introduction of GObject as a separate layer, with GType instead. --JonCruz
106 static GtkType type = 0;
107 if (!type) {
108 GtkTypeInfo info = {
109 (gchar*) "SPIcon",
110 sizeof(SPIcon),
111 sizeof(SPIconClass),
112 (GtkClassInitFunc) sp_icon_class_init,
113 (GtkObjectInitFunc) sp_icon_init,
114 NULL, NULL, NULL
115 };
116 type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
117 }
118 return type;
119 }
121 static void
122 sp_icon_class_init(SPIconClass *klass)
123 {
124 GtkObjectClass *object_class;
125 GtkWidgetClass *widget_class;
127 object_class = (GtkObjectClass *) klass;
128 widget_class = (GtkWidgetClass *) klass;
130 parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
132 object_class->destroy = sp_icon_destroy;
134 widget_class->size_request = sp_icon_size_request;
135 widget_class->size_allocate = sp_icon_size_allocate;
136 widget_class->expose_event = sp_icon_expose;
137 widget_class->screen_changed = sp_icon_screen_changed;
138 widget_class->style_set = sp_icon_style_set;
139 }
142 static void
143 sp_icon_init(SPIcon *icon)
144 {
145 GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
146 icon->lsize = Inkscape::ICON_SIZE_BUTTON;
147 icon->psize = 0;
148 icon->name = 0;
149 icon->pb = 0;
150 icon->pb_faded = 0;
151 }
153 static void
154 sp_icon_destroy(GtkObject *object)
155 {
156 SPIcon *icon = SP_ICON(object);
157 sp_icon_clear(icon);
158 if ( icon->name ) {
159 g_free( icon->name );
160 icon->name = 0;
161 }
163 ((GtkObjectClass *) (parent_class))->destroy(object);
164 }
166 static void sp_icon_reset( SPIcon *icon ) {
167 icon->psize = 0;
168 sp_icon_clear(icon);
169 }
171 static void sp_icon_clear( SPIcon *icon ) {
172 if (icon->pb) {
173 g_object_unref(G_OBJECT(icon->pb));
174 icon->pb = NULL;
175 }
176 if (icon->pb_faded) {
177 g_object_unref(G_OBJECT(icon->pb_faded));
178 icon->pb_faded = NULL;
179 }
180 }
182 static void
183 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
184 {
185 SPIcon const *icon = SP_ICON(widget);
187 int const size = ( icon->psize
188 ? icon->psize
189 : sp_icon_get_phys_size(icon->lsize) );
190 requisition->width = size;
191 requisition->height = size;
192 }
194 static void
195 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
196 {
197 widget->allocation = *allocation;
199 if (GTK_WIDGET_DRAWABLE(widget)) {
200 gtk_widget_queue_draw(widget);
201 }
202 }
204 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
205 {
206 if ( GTK_WIDGET_DRAWABLE(widget) ) {
207 SPIcon *icon = SP_ICON(widget);
208 if ( !icon->pb ) {
209 sp_icon_fetch_pixbuf( icon );
210 }
212 sp_icon_paint(SP_ICON(widget), &event->area);
213 }
215 return TRUE;
216 }
218 // PUBLIC CALL:
219 void sp_icon_fetch_pixbuf( SPIcon *icon )
220 {
221 if ( icon ) {
222 if ( !icon->pb ) {
223 icon->psize = sp_icon_get_phys_size(icon->lsize);
225 GdkPixbuf *pb = sp_icon_image_load_svg( icon->name, Inkscape::getRegisteredIconSize(icon->lsize), icon->psize );
226 if (!pb) {
227 pb = sp_icon_image_load_pixmap( icon->name, icon->lsize, icon->psize );
228 }
230 if ( pb ) {
231 icon->pb = pb;
232 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
233 gdk_pixbuf_saturate_and_pixelate(icon->pb, icon->pb_faded, 0.5, TRUE);
234 } else {
235 /* TODO: We should do something more useful if we can't load the image. */
236 g_warning ("failed to load icon '%s'", icon->name);
237 }
238 }
239 }
240 }
242 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
243 {
244 if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
245 GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
246 }
247 SPIcon *icon = SP_ICON(widget);
248 sp_icon_theme_changed(icon);
249 }
251 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
252 {
253 if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
254 GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
255 }
256 SPIcon *icon = SP_ICON(widget);
257 sp_icon_theme_changed(icon);
258 }
260 static void sp_icon_theme_changed( SPIcon *icon )
261 {
262 //g_message("Got a change bump for this icon");
263 sizeDirty = true;
264 sp_icon_reset(icon);
265 gtk_widget_queue_draw( GTK_WIDGET(icon) );
266 }
269 static void imageMapCB(GtkWidget* widget, gpointer user_data);
270 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
271 static void populate_placeholder_icon(gchar const* name, GtkIconSize size);
272 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
273 static Glib::ustring icon_cache_key(gchar const *name, unsigned lsize, unsigned psize);
274 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
276 std::map<Glib::ustring, Glib::ustring> legacyNames;
278 static void setupLegacyNaming() {
279 legacyNames["view-fullscreen"] = "fullscreen";
280 legacyNames["edit-select-all"] = "selection_select_all";
281 legacyNames["window-new"] = "view_new";
282 }
284 static GtkWidget *
285 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
286 {
287 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
288 static bool dump = prefs->getBool( "/debug/icons/dumpGtk");
290 GtkWidget *widget = 0;
291 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
292 if ( !sizeMapDone ) {
293 injectCustomSize();
294 }
295 GtkIconSize mappedSize = iconSizeLookup[trySize];
297 GtkStockItem stock;
298 gboolean stockFound = gtk_stock_lookup( name, &stock );
300 GtkWidget *img = 0;
301 if ( legacyNames.empty() ) {
302 setupLegacyNaming();
303 }
305 bool flagMe = false;
306 if ( legacyNames.find(name) != legacyNames.end() ) {
307 img = gtk_image_new_from_icon_name( name, mappedSize );
308 flagMe = true;
309 if ( dump ) {
310 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
311 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
312 g_message(" Type is %d %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
313 }
314 } else {
315 img = gtk_image_new_from_stock( name, mappedSize );
316 }
318 if ( img ) {
319 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
320 if ( type == GTK_IMAGE_STOCK ) {
321 if ( !stockFound ) {
322 // It's not showing as a stock ID, so assume it will be present internally
323 populate_placeholder_icon( name, mappedSize );
324 addPreRender( mappedSize, name );
326 // Add a hook to render if set visible before prerender is done.
327 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
328 if ( dump ) {
329 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
330 }
331 }
332 widget = GTK_WIDGET(img);
333 img = 0;
334 if ( dump ) {
335 g_message( "loaded gtk '%s' %d (GTK_IMAGE_STOCK) %s on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
336 }
337 } else if ( type == GTK_IMAGE_ICON_NAME ) {
338 widget = GTK_WIDGET(img);
339 img = 0;
341 // Add a hook to render if set visible before prerender is done.
342 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
344 if ( prefs->getBool("/options/iconrender/named_nodelay") ) {
345 int psize = sp_icon_get_phys_size(lsize);
346 prerender_icon(name, mappedSize, psize);
347 } else {
348 addPreRender( mappedSize, name );
349 }
350 } else {
351 if ( dump ) {
352 g_message( "skipped gtk '%s' %d (not GTK_IMAGE_STOCK)", name, lsize );
353 }
354 //g_object_unref( (GObject *)img );
355 img = 0;
356 }
357 }
359 if ( !widget ) {
360 //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
361 SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
362 icon->lsize = lsize;
363 icon->name = g_strdup(name);
364 icon->psize = sp_icon_get_phys_size(lsize);
366 widget = GTK_WIDGET(icon);
367 }
369 return widget;
370 }
372 GtkWidget *
373 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
374 {
375 return sp_icon_new_full( lsize, name );
376 }
378 // PUBLIC CALL:
379 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
380 {
381 Gtk::Widget *result = 0;
382 GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
384 if ( widget ) {
385 if ( GTK_IS_IMAGE(widget) ) {
386 GtkImage *img = GTK_IMAGE(widget);
387 result = Glib::wrap( img );
388 } else {
389 result = Glib::wrap( widget );
390 }
391 }
393 return result;
394 }
396 GtkIconSize
397 sp_icon_get_gtk_size(int size)
398 {
399 static GtkIconSize sizemap[64] = {(GtkIconSize)0};
400 size = CLAMP(size, 4, 63);
401 if (!sizemap[size]) {
402 static int count = 0;
403 char c[64];
404 g_snprintf(c, 64, "InkscapeIcon%d", count++);
405 sizemap[size] = gtk_icon_size_register(c, size, size);
406 }
407 return sizemap[size];
408 }
411 static void injectCustomSize()
412 {
413 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
414 if ( !sizeMapDone )
415 {
416 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
417 bool dump = prefs->getBool( "/debug/icons/dumpDefault");
418 gint width = 0;
419 gint height = 0;
420 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
421 gint newWidth = ((width * 3) / 4);
422 gint newHeight = ((height * 3) / 4);
423 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
424 if ( newSizeEnum ) {
425 if ( dump ) {
426 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
427 }
428 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
429 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
430 iconSizeLookup[index] = newSizeEnum;
431 } else if ( dump ) {
432 g_message("size lookup array too small to store entry");
433 }
434 }
435 }
436 sizeMapDone = true;
437 }
439 static bool hit = false;
440 if ( !hit ) {
441 hit = true;
442 inkyIcons = Gtk::IconFactory::create();
443 inkyIcons->add_default();
444 }
445 }
447 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
448 {
449 GtkIconSize other = GTK_ICON_SIZE_MENU;
450 injectCustomSize();
451 size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
452 if ( size == Inkscape::ICON_SIZE_DECORATION ) {
453 other = gtk_icon_size_from_name("inkscape-decoration");
454 } else {
455 other = static_cast<GtkIconSize>(size);
456 }
458 return other;
459 }
462 // PUBLIC CALL:
463 int sp_icon_get_phys_size(int size)
464 {
465 static bool init = false;
466 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
467 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
469 size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
471 if ( !sizeMapDone ) {
472 injectCustomSize();
473 }
475 if ( sizeDirty && init ) {
476 GtkIconSize const gtkSizes[] = {
477 GTK_ICON_SIZE_MENU,
478 GTK_ICON_SIZE_SMALL_TOOLBAR,
479 GTK_ICON_SIZE_LARGE_TOOLBAR,
480 GTK_ICON_SIZE_BUTTON,
481 GTK_ICON_SIZE_DND,
482 GTK_ICON_SIZE_DIALOG,
483 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
484 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
485 GTK_ICON_SIZE_MENU
486 };
487 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
488 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
490 g_assert( val_ix < G_N_ELEMENTS(vals) );
492 gint width = 0;
493 gint height = 0;
494 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
495 init &= (lastSys[val_ix] == std::max(width, height));
496 }
497 }
498 }
500 if ( !init ) {
501 sizeDirty = false;
502 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
503 bool dump = prefs->getBool("/debug/icons/dumpDefault");
505 if ( dump ) {
506 g_message( "Default icon sizes:" );
507 }
508 memset( vals, 0, sizeof(vals) );
509 memset( lastSys, 0, sizeof(lastSys) );
510 GtkIconSize const gtkSizes[] = {
511 GTK_ICON_SIZE_MENU,
512 GTK_ICON_SIZE_SMALL_TOOLBAR,
513 GTK_ICON_SIZE_LARGE_TOOLBAR,
514 GTK_ICON_SIZE_BUTTON,
515 GTK_ICON_SIZE_DND,
516 GTK_ICON_SIZE_DIALOG,
517 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
518 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
519 GTK_ICON_SIZE_MENU
520 };
521 gchar const *const names[] = {
522 "GTK_ICON_SIZE_MENU",
523 "GTK_ICON_SIZE_SMALL_TOOLBAR",
524 "GTK_ICON_SIZE_LARGE_TOOLBAR",
525 "GTK_ICON_SIZE_BUTTON",
526 "GTK_ICON_SIZE_DND",
527 "GTK_ICON_SIZE_DIALOG",
528 "inkscape-decoration"
529 };
531 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
533 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
534 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
536 g_assert( val_ix < G_N_ELEMENTS(vals) );
538 gint width = 0;
539 gint height = 0;
540 bool used = false;
541 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
542 vals[val_ix] = std::max(width, height);
543 lastSys[val_ix] = vals[val_ix];
544 used = true;
545 }
546 if (dump) {
547 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
548 i, gtkSizes[i],
549 ( used ? ' ' : 'X' ), width, height, names[i]);
550 }
551 gchar const *id = GTK_STOCK_OPEN;
552 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
553 if (pb) {
554 width = gdk_pixbuf_get_width(pb);
555 height = gdk_pixbuf_get_height(pb);
556 int newSize = std::max( width, height );
557 // TODO perhaps check a few more stock icons to get a range on sizes.
558 if ( newSize > 0 ) {
559 vals[val_ix] = newSize;
560 }
561 if (dump) {
562 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
563 }
565 g_object_unref(G_OBJECT(pb));
566 }
567 }
568 //g_object_unref(icon);
569 init = true;
570 }
572 return vals[size];
573 }
575 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
576 {
577 GtkWidget &widget = *GTK_WIDGET(icon);
579 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
581 if (image) {
582 int const padx = ( ( widget.allocation.width > icon->psize )
583 ? ( widget.allocation.width - icon->psize ) / 2
584 : 0 );
585 int const pady = ( ( widget.allocation.height > icon->psize )
586 ? ( widget.allocation.height - icon->psize ) / 2
587 : 0 );
589 int const x0 = std::max(area->x, widget.allocation.x + padx);
590 int const y0 = std::max(area->y, widget.allocation.y + pady);
591 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
592 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
594 int width = x1 - x0;
595 int height = y1 - y0;
596 // Limit drawing to when we actually have something. Avoids some crashes.
597 if ( (width > 0) && (height > 0) ) {
598 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
599 x0 - widget.allocation.x - padx,
600 y0 - widget.allocation.y - pady,
601 x0, y0,
602 width, height,
603 GDK_RGB_DITHER_NORMAL, x0, y0);
604 }
605 }
606 }
608 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
609 {
610 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
611 // TODO: bulia, please look over
612 gsize bytesRead = 0;
613 gsize bytesWritten = 0;
614 GError *error = NULL;
615 gchar *localFilename = g_filename_from_utf8( path,
616 -1,
617 &bytesRead,
618 &bytesWritten,
619 &error);
620 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
621 g_free(localFilename);
622 g_free(path);
623 if (!pb) {
624 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
625 // TODO: bulia, please look over
626 gsize bytesRead = 0;
627 gsize bytesWritten = 0;
628 GError *error = NULL;
629 gchar *localFilename = g_filename_from_utf8( path,
630 -1,
631 &bytesRead,
632 &bytesWritten,
633 &error);
634 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
635 g_free(localFilename);
636 g_free(path);
637 }
639 if (pb) {
640 if (!gdk_pixbuf_get_has_alpha(pb)) {
641 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
642 }
644 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
645 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
646 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
647 g_object_unref(G_OBJECT(pb));
648 pb = spb;
649 }
650 }
652 return pb;
653 }
655 // takes doc, root, icon, and icon name to produce pixels
656 extern "C" guchar *
657 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
658 gchar const *name, unsigned psize )
659 {
660 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
661 bool const dump = prefs->getBool("/debug/icons/dumpSvg");
662 guchar *px = NULL;
664 if (doc) {
665 SPObject *object = doc->getObjectById(name);
666 if (object && SP_IS_ITEM(object)) {
667 /* Find bbox in document */
668 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
669 Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
671 if ( SP_OBJECT_PARENT(object) == NULL )
672 {
673 dbox = Geom::Rect(Geom::Point(0, 0),
674 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
675 }
677 /* This is in document coordinates, i.e. pixels */
678 if ( dbox ) {
679 NRGC gc(NULL);
680 /* Update to renderable state */
681 double sf = 1.0;
682 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
683 gc.transform.setIdentity();
684 nr_arena_item_invoke_update( root, NULL, &gc,
685 NR_ARENA_ITEM_STATE_ALL,
686 NR_ARENA_ITEM_STATE_NONE );
687 /* Item integer bbox in points */
688 NRRectL ibox;
689 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
690 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
691 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
692 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
694 if ( dump ) {
695 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
696 }
698 /* Find button visible area */
699 int width = ibox.x1 - ibox.x0;
700 int height = ibox.y1 - ibox.y0;
702 if ( dump ) {
703 g_message( " vis --'%s' (%d,%d)", name, width, height );
704 }
706 {
707 int block = std::max(width, height);
708 if (block != static_cast<int>(psize) ) {
709 if ( dump ) {
710 g_message(" resizing" );
711 }
712 sf = (double)psize / (double)block;
714 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
715 gc.transform.setIdentity();
716 nr_arena_item_invoke_update( root, NULL, &gc,
717 NR_ARENA_ITEM_STATE_ALL,
718 NR_ARENA_ITEM_STATE_NONE );
719 /* Item integer bbox in points */
720 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
721 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
722 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
723 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
725 if ( dump ) {
726 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
727 }
729 /* Find button visible area */
730 width = ibox.x1 - ibox.x0;
731 height = ibox.y1 - ibox.y0;
732 if ( dump ) {
733 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
734 }
735 }
736 }
738 int dx, dy;
739 //dx = (psize - width) / 2;
740 //dy = (psize - height) / 2;
741 dx=dy=psize;
742 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
743 dy=(dy-height)/2;
744 NRRectL area;
745 area.x0 = ibox.x0 - dx;
746 area.y0 = ibox.y0 - dy;
747 area.x1 = area.x0 + psize;
748 area.y1 = area.y0 + psize;
749 /* Actual renderable area */
750 NRRectL ua;
751 ua.x0 = MAX(ibox.x0, area.x0);
752 ua.y0 = MAX(ibox.y0, area.y0);
753 ua.x1 = MIN(ibox.x1, area.x1);
754 ua.y1 = MIN(ibox.y1, area.y1);
756 if ( dump ) {
757 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
758 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
759 }
760 /* Set up pixblock */
761 px = g_new(guchar, 4 * psize * psize);
762 memset(px, 0x00, 4 * psize * psize);
763 /* Render */
764 NRPixBlock B;
765 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
766 ua.x0, ua.y0, ua.x1, ua.y1,
767 px + 4 * psize * (ua.y0 - area.y0) +
768 4 * (ua.x0 - area.x0),
769 4 * psize, FALSE, FALSE );
770 nr_arena_item_invoke_render(NULL, root, &ua, &B,
771 NR_ARENA_ITEM_RENDER_NO_CACHE );
772 nr_pixblock_release(&B);
774 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
775 if ( useOverlay ) {
776 sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
777 }
778 }
779 }
780 }
782 return px;
783 } // end of sp_icon_doc_icon()
787 struct svg_doc_cache_t
788 {
789 SPDocument *doc;
790 NRArenaItem *root;
791 };
793 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
794 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
796 Glib::ustring icon_cache_key(gchar const *name,
797 unsigned lsize, unsigned psize)
798 {
799 Glib::ustring key=name;
800 key += ":";
801 key += lsize;
802 key += ":";
803 key += psize;
804 return key;
805 }
807 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
808 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
809 if ( found != pb_cache.end() ) {
810 return found->second;
811 }
812 return NULL;
813 }
815 static guchar *load_svg_pixels(gchar const *name,
816 unsigned /*lsize*/, unsigned psize)
817 {
818 SPDocument *doc = NULL;
819 NRArenaItem *root = NULL;
820 svg_doc_cache_t *info = NULL;
822 // Fall back from user prefs dir into system locations.
823 Glib::ustring iconsvg = name;
824 iconsvg += ".svg";
825 std::list<gchar *> sources;
826 sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
827 sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
828 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
829 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
831 // Try each document in turn until we successfully load the icon from one
832 guchar *px=NULL;
833 while ( !sources.empty() && !px ) {
834 gchar *doc_filename = sources.front();
836 // Did we already load this doc?
837 Glib::ustring key(doc_filename);
838 info = 0;
839 {
840 std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
841 if ( i != doc_cache.end() ) {
842 info = i->second;
843 }
844 }
846 /* Try to load from document. */
847 if (!info &&
848 Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
849 (doc = sp_document_new( doc_filename, FALSE )) ) {
851 // prep the document
852 sp_document_ensure_up_to_date(doc);
853 /* Create new arena */
854 NRArena *arena = NRArena::create();
855 /* Create ArenaItem and set transform */
856 unsigned visionkey = sp_item_display_key_new(1);
857 /* fixme: Memory manage root if needed (Lauris) */
858 root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
859 arena, visionkey, SP_ITEM_SHOW_DISPLAY );
861 // store into the cache
862 info = new svg_doc_cache_t;
863 g_assert(info);
865 info->doc=doc;
866 info->root=root;
867 doc_cache[key]=info;
868 }
869 if (info) {
870 doc=info->doc;
871 root=info->root;
872 }
874 // toss the filename
875 g_free(doc_filename);
876 sources.pop_front();
878 // move on to the next document if we couldn't get anything
879 if (!info && !doc) continue;
881 px = sp_icon_doc_icon( doc, root, name, psize );
882 }
884 return px;
885 }
887 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
888 {
889 if ( iconSetCache.find(name) == iconSetCache.end() ) {
890 // only add a placeholder if nothing is already set
891 Gtk::IconSet icnset;
892 Gtk::IconSource src;
893 src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
894 src.set_size( Gtk::IconSize(size) );
895 icnset.add_source(src);
896 inkyIcons->add(Gtk::StockID(name), icnset);
897 }
898 }
900 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
901 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
902 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
903 GtkStockItem stock;
904 gboolean stockFound = gtk_stock_lookup( name, &stock );
905 if ( !stockFound ) {
906 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
907 if (dump) {
908 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
909 }
910 }
912 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
913 if ( it->_lsize == lsize ) {
914 iconSetCache[name].erase(it);
915 break;
916 }
917 }
918 iconSetCache[name].push_back(IconCacheItem(lsize, pb));
920 Gtk::IconSet icnset;
921 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
922 Gtk::IconSource src;
923 g_object_ref( G_OBJECT(it->_pb) );
924 src.set_pixbuf( Glib::wrap(it->_pb) );
925 src.set_size( Gtk::IconSize(it->_lsize) );
926 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
927 src.set_state_wildcarded( true );
928 icnset.add_source(src);
929 }
930 inkyIcons->add(Gtk::StockID(name), icnset);
931 }
933 // returns true if icon needed preloading, false if nothing was done
934 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
935 {
936 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
937 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
938 Glib::ustring key = icon_cache_key(name, lsize, psize);
939 GdkPixbuf *pb = get_cached_pixbuf(key);
940 if (pb) {
941 return false;
942 } else {
943 guchar* px = load_svg_pixels(name, lsize, psize);
944 if ( !px ) {
945 // check for a fallback name
946 if ( legacyNames.find(name) != legacyNames.end() ) {
947 if ( dump ) {
948 g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
949 }
950 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
951 }
952 }
954 if (px) {
955 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
956 psize, psize, psize * 4,
957 (GdkPixbufDestroyNotify)g_free, NULL);
958 pb_cache[key] = pb;
959 addToIconSet(pb, name, lsize, psize);
960 } else if (dump) {
961 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
962 }
963 return true;
964 }
965 }
967 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
968 {
969 Glib::ustring key = icon_cache_key(name, lsize, psize);
971 // did we already load this icon at this scale/size?
972 GdkPixbuf* pb = get_cached_pixbuf(key);
973 if (!pb) {
974 guchar *px = load_svg_pixels(name, lsize, psize);
975 if (px) {
976 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
977 psize, psize, psize * 4,
978 (GdkPixbufDestroyNotify)g_free, NULL);
979 pb_cache[key] = pb;
980 addToIconSet(pb, name, lsize, psize);
981 }
982 }
984 if ( pb ) {
985 // increase refcount since we're handing out ownership
986 g_object_ref(G_OBJECT(pb));
987 }
988 return pb;
989 }
991 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
992 unsigned r, unsigned g, unsigned b)
993 {
994 for ( int y = 0; y < height; y += 4 ) {
995 guchar *ptr = px + y * stride;
996 for ( int x = 0; x < width; x += 4 ) {
997 *(ptr++) = r;
998 *(ptr++) = g;
999 *(ptr++) = b;
1000 *(ptr++) = 0xff;
1002 ptr += 4 * 3;
1003 }
1004 }
1006 if ( width > 1 && height > 1 ) {
1007 // point at the last pixel
1008 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
1010 if ( width > 2 ) {
1011 px[4] = r;
1012 px[5] = g;
1013 px[6] = b;
1014 px[7] = 0xff;
1016 ptr[-12] = r;
1017 ptr[-11] = g;
1018 ptr[-10] = b;
1019 ptr[-9] = 0xff;
1020 }
1022 ptr[-4] = r;
1023 ptr[-3] = g;
1024 ptr[-2] = b;
1025 ptr[-1] = 0xff;
1027 px[0 + stride] = r;
1028 px[1 + stride] = g;
1029 px[2 + stride] = b;
1030 px[3 + stride] = 0xff;
1032 ptr[0 - stride] = r;
1033 ptr[1 - stride] = g;
1034 ptr[2 - stride] = b;
1035 ptr[3 - stride] = 0xff;
1037 if ( height > 2 ) {
1038 ptr[0 - stride * 3] = r;
1039 ptr[1 - stride * 3] = g;
1040 ptr[2 - stride * 3] = b;
1041 ptr[3 - stride * 3] = 0xff;
1042 }
1043 }
1044 }
1046 class preRenderItem
1047 {
1048 public:
1049 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1050 _lsize( lsize ),
1051 _name( name )
1052 {}
1053 GtkIconSize _lsize;
1054 Glib::ustring _name;
1055 };
1058 static std::vector<preRenderItem> pendingRenders;
1059 static bool callbackHooked = false;
1061 static void addPreRender( GtkIconSize lsize, gchar const *name )
1062 {
1063 if ( !callbackHooked )
1064 {
1065 callbackHooked = true;
1066 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1067 }
1069 pendingRenders.push_back(preRenderItem(lsize, name));
1070 }
1072 gboolean icon_prerender_task(gpointer /*data*/) {
1073 if (!pendingRenders.empty()) {
1074 bool workDone = false;
1075 do {
1076 preRenderItem single = pendingRenders.front();
1077 pendingRenders.erase(pendingRenders.begin());
1078 int psize = sp_icon_get_phys_size(single._lsize);
1079 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1080 } while (!pendingRenders.empty() && !workDone);
1081 }
1083 if (!pendingRenders.empty()) {
1084 return TRUE;
1085 } else {
1086 callbackHooked = false;
1087 return FALSE;
1088 }
1089 }
1092 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1093 gchar* id = 0;
1094 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1095 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1096 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1097 if ( id ) {
1098 int psize = sp_icon_get_phys_size(lsize);
1099 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1100 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1101 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1102 prerender_icon(id, lsize, psize);
1103 pendingRenders.erase(it);
1104 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1105 if (lsize != size) {
1106 int psize = sp_icon_get_phys_size(size);
1107 prerender_icon(id, size, psize);
1108 }
1109 break;
1110 }
1111 }
1112 }
1114 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1115 }
1117 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1118 GtkImage* img = GTK_IMAGE(widget);
1119 gchar const* iconName = 0;
1120 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1121 gtk_image_get_icon_name(img, &iconName, &size);
1122 if ( iconName ) {
1123 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1124 if ( type == GTK_IMAGE_ICON_NAME ) {
1125 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1126 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1127 int psize = sp_icon_get_phys_size(size);
1128 prerender_icon(iconName, size, psize);
1129 pendingRenders.erase(it);
1130 break;
1131 }
1132 }
1134 } else {
1135 g_warning("UNEXPECTED TYPE of %d", (int)type);
1136 }
1137 }
1139 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1140 }
1143 /*
1144 Local Variables:
1145 mode:c++
1146 c-file-style:"stroustrup"
1147 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1148 indent-tabs-mode:nil
1149 fill-column:99
1150 End:
1151 */
1152 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :