1 /** \file
2 * SPIcon: Generic icon widget
3 */
4 /*
5 * Author:
6 * Lauris Kaplinski <lauris@kaplinski.com>
7 * Jon A. Cruz <jon@joncruz.org>
8 *
9 * Copyright (C) 2002 Lauris Kaplinski
10 *
11 * Released under GNU GPL, read the file 'COPYING' for more information
12 */
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
18 #include <cstring>
19 #include <glib/gmem.h>
20 #include <gtk/gtk.h>
21 #include <gtkmm.h>
23 #include "path-prefix.h"
24 #include "preferences.h"
25 #include "inkscape.h"
26 #include "document.h"
27 #include "sp-item.h"
28 #include "display/nr-arena.h"
29 #include "display/nr-arena-item.h"
30 #include "io/sys.h"
32 #include "icon.h"
34 static gboolean icon_prerender_task(gpointer data);
36 static void addPreRender( GtkIconSize lsize, gchar const *name );
38 static void sp_icon_class_init(SPIconClass *klass);
39 static void sp_icon_init(SPIcon *icon);
40 static void sp_icon_destroy(GtkObject *object);
42 static void sp_icon_reset(SPIcon *icon);
43 static void sp_icon_clear(SPIcon *icon);
45 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
46 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
47 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
49 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
51 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
52 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
53 static void sp_icon_theme_changed( SPIcon *icon );
55 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
56 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
58 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
59 unsigned r, unsigned g, unsigned b );
61 static void injectCustomSize();
63 static GtkWidgetClass *parent_class;
65 static bool sizeDirty = true;
67 static bool sizeMapDone = false;
68 static GtkIconSize iconSizeLookup[] = {
69 GTK_ICON_SIZE_INVALID,
70 GTK_ICON_SIZE_MENU,
71 GTK_ICON_SIZE_SMALL_TOOLBAR,
72 GTK_ICON_SIZE_LARGE_TOOLBAR,
73 GTK_ICON_SIZE_BUTTON,
74 GTK_ICON_SIZE_DND,
75 GTK_ICON_SIZE_DIALOG,
76 GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
77 };
79 class IconCacheItem
80 {
81 public:
82 IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
83 _lsize( lsize ),
84 _pb( pb )
85 {}
86 GtkIconSize _lsize;
87 GdkPixbuf* _pb;
88 };
90 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
91 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
93 GtkType
94 sp_icon_get_type()
95 {
96 //TODO: switch to GObject
97 // GtkType and such calls were deprecated a while back with the
98 // introduction of GObject as a separate layer, with GType instead. --JonCruz
100 static GtkType type = 0;
101 if (!type) {
102 GtkTypeInfo info = {
103 (gchar*) "SPIcon",
104 sizeof(SPIcon),
105 sizeof(SPIconClass),
106 (GtkClassInitFunc) sp_icon_class_init,
107 (GtkObjectInitFunc) sp_icon_init,
108 NULL, NULL, NULL
109 };
110 type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
111 }
112 return type;
113 }
115 static void
116 sp_icon_class_init(SPIconClass *klass)
117 {
118 GtkObjectClass *object_class;
119 GtkWidgetClass *widget_class;
121 object_class = (GtkObjectClass *) klass;
122 widget_class = (GtkWidgetClass *) klass;
124 parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
126 object_class->destroy = sp_icon_destroy;
128 widget_class->size_request = sp_icon_size_request;
129 widget_class->size_allocate = sp_icon_size_allocate;
130 widget_class->expose_event = sp_icon_expose;
131 widget_class->screen_changed = sp_icon_screen_changed;
132 widget_class->style_set = sp_icon_style_set;
133 }
136 static void
137 sp_icon_init(SPIcon *icon)
138 {
139 GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
140 icon->lsize = Inkscape::ICON_SIZE_BUTTON;
141 icon->psize = 0;
142 icon->name = 0;
143 icon->pb = 0;
144 icon->pb_faded = 0;
145 }
147 static void
148 sp_icon_destroy(GtkObject *object)
149 {
150 SPIcon *icon = SP_ICON(object);
151 sp_icon_clear(icon);
152 if ( icon->name ) {
153 g_free( icon->name );
154 icon->name = 0;
155 }
157 ((GtkObjectClass *) (parent_class))->destroy(object);
158 }
160 static void sp_icon_reset( SPIcon *icon ) {
161 icon->psize = 0;
162 sp_icon_clear(icon);
163 }
165 static void sp_icon_clear( SPIcon *icon ) {
166 if (icon->pb) {
167 g_object_unref(G_OBJECT(icon->pb));
168 icon->pb = NULL;
169 }
170 if (icon->pb_faded) {
171 g_object_unref(G_OBJECT(icon->pb_faded));
172 icon->pb_faded = NULL;
173 }
174 }
176 static void
177 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
178 {
179 SPIcon const *icon = SP_ICON(widget);
181 int const size = ( icon->psize
182 ? icon->psize
183 : sp_icon_get_phys_size(icon->lsize) );
184 requisition->width = size;
185 requisition->height = size;
186 }
188 static void
189 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
190 {
191 widget->allocation = *allocation;
193 if (GTK_WIDGET_DRAWABLE(widget)) {
194 gtk_widget_queue_draw(widget);
195 }
196 }
198 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
199 {
200 if ( GTK_WIDGET_DRAWABLE(widget) ) {
201 SPIcon *icon = SP_ICON(widget);
202 if ( !icon->pb ) {
203 sp_icon_fetch_pixbuf( icon );
204 }
206 sp_icon_paint(SP_ICON(widget), &event->area);
207 }
209 return TRUE;
210 }
212 // PUBLIC CALL:
213 void sp_icon_fetch_pixbuf( SPIcon *icon )
214 {
215 if ( icon ) {
216 if ( !icon->pb ) {
217 icon->psize = sp_icon_get_phys_size(icon->lsize);
219 GdkPixbuf *pb;
221 pb = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), icon->name, icon->psize,
222 (GtkIconLookupFlags) 0, NULL);
223 if (!pb) {
224 pb = sp_icon_image_load_svg( icon->name, Inkscape::getRegisteredIconSize(icon->lsize), icon->psize );
225 }
226 if (!pb) {
227 pb = sp_icon_image_load_pixmap( icon->name, icon->lsize, icon->psize );
228 }
229 if ( pb ) {
230 icon->pb = pb;
231 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
232 gdk_pixbuf_saturate_and_pixelate(icon->pb, icon->pb_faded, 0.5, TRUE);
233 } else {
234 /* TODO: We should do something more useful if we can't load the image. */
235 g_warning ("failed to load icon '%s'", icon->name);
236 }
237 }
238 }
239 }
241 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
242 {
243 if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
244 GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
245 }
246 SPIcon *icon = SP_ICON(widget);
247 sp_icon_theme_changed(icon);
248 }
250 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
251 {
252 if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
253 GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
254 }
255 SPIcon *icon = SP_ICON(widget);
256 sp_icon_theme_changed(icon);
257 }
259 static void sp_icon_theme_changed( SPIcon *icon )
260 {
261 //g_message("Got a change bump for this icon");
262 sizeDirty = true;
263 sp_icon_reset(icon);
264 gtk_widget_queue_draw( GTK_WIDGET(icon) );
265 }
268 static void imageMapCB(GtkWidget* widget, gpointer user_data);
269 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
270 static void populate_placeholder_icon(gchar const* name, GtkIconSize size);
271 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
272 static Glib::ustring icon_cache_key(gchar const *name, unsigned lsize, unsigned psize);
273 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
275 std::map<Glib::ustring, Glib::ustring> legacyNames;
277 static void setupLegacyNaming() {
278 legacyNames["view-fullscreen"] = "fullscreen";
279 legacyNames["edit-select-all"] = "selection_select_all";
280 legacyNames["window-new"] = "view_new";
281 }
283 static GtkWidget *
284 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
285 {
286 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
287 static bool dump = prefs->getBool( "/debug/icons/dumpGtk");
289 GtkWidget *widget = 0;
290 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
291 if ( !sizeMapDone ) {
292 injectCustomSize();
293 }
294 GtkIconSize mappedSize = iconSizeLookup[trySize];
296 GtkStockItem stock;
297 gboolean stockFound = gtk_stock_lookup( name, &stock );
299 GtkWidget *img = 0;
300 if ( legacyNames.empty() ) {
301 setupLegacyNaming();
302 }
304 if ( legacyNames.find(name) != legacyNames.end() ) {
305 img = gtk_image_new_from_icon_name( name, mappedSize );
306 if ( dump ) {
307 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
308 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
309 g_message(" Type is %d %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
310 }
311 } else {
312 img = gtk_image_new_from_stock( name, mappedSize );
313 }
315 if ( img ) {
316 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
317 if ( type == GTK_IMAGE_STOCK ) {
318 if ( !stockFound ) {
319 // It's not showing as a stock ID, so assume it will be present internally
320 populate_placeholder_icon( name, mappedSize );
321 addPreRender( mappedSize, name );
323 // Add a hook to render if set visible before prerender is done.
324 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
325 if ( dump ) {
326 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
327 }
328 }
329 widget = GTK_WIDGET(img);
330 img = 0;
331 if ( dump ) {
332 g_message( "loaded gtk '%s' %d (GTK_IMAGE_STOCK) %s on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
333 }
334 } else if ( type == GTK_IMAGE_ICON_NAME ) {
335 widget = GTK_WIDGET(img);
336 img = 0;
338 // Add a hook to render if set visible before prerender is done.
339 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
341 if ( prefs->getBool("/options/iconrender/named_nodelay") ) {
342 int psize = sp_icon_get_phys_size(lsize);
343 prerender_icon(name, mappedSize, psize);
344 } else {
345 addPreRender( mappedSize, name );
346 }
347 } else {
348 if ( dump ) {
349 g_message( "skipped gtk '%s' %d (not GTK_IMAGE_STOCK)", name, lsize );
350 }
351 //g_object_unref( (GObject *)img );
352 img = 0;
353 }
354 }
356 if ( !widget ) {
357 //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
358 SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
359 icon->lsize = lsize;
360 icon->name = g_strdup(name);
361 icon->psize = sp_icon_get_phys_size(lsize);
363 widget = GTK_WIDGET(icon);
364 }
366 return widget;
367 }
369 GtkWidget *
370 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
371 {
372 return sp_icon_new_full( lsize, name );
373 }
375 // PUBLIC CALL:
376 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
377 {
378 Gtk::Widget *result = 0;
379 GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
381 if ( widget ) {
382 if ( GTK_IS_IMAGE(widget) ) {
383 GtkImage *img = GTK_IMAGE(widget);
384 result = Glib::wrap( img );
385 } else {
386 result = Glib::wrap( widget );
387 }
388 }
390 return result;
391 }
393 GtkIconSize
394 sp_icon_get_gtk_size(int size)
395 {
396 static GtkIconSize sizemap[64] = {(GtkIconSize)0};
397 size = CLAMP(size, 4, 63);
398 if (!sizemap[size]) {
399 static int count = 0;
400 char c[64];
401 g_snprintf(c, 64, "InkscapeIcon%d", count++);
402 sizemap[size] = gtk_icon_size_register(c, size, size);
403 }
404 return sizemap[size];
405 }
408 static void injectCustomSize()
409 {
410 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
411 if ( !sizeMapDone )
412 {
413 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
414 bool dump = prefs->getBool( "/debug/icons/dumpDefault");
415 gint width = 0;
416 gint height = 0;
417 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
418 gint newWidth = ((width * 3) / 4);
419 gint newHeight = ((height * 3) / 4);
420 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
421 if ( newSizeEnum ) {
422 if ( dump ) {
423 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
424 }
425 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
426 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
427 iconSizeLookup[index] = newSizeEnum;
428 } else if ( dump ) {
429 g_message("size lookup array too small to store entry");
430 }
431 }
432 }
433 sizeMapDone = true;
434 }
436 static bool hit = false;
437 if ( !hit ) {
438 hit = true;
439 inkyIcons = Gtk::IconFactory::create();
440 inkyIcons->add_default();
441 }
442 }
444 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
445 {
446 GtkIconSize other = GTK_ICON_SIZE_MENU;
447 injectCustomSize();
448 size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
449 if ( size == Inkscape::ICON_SIZE_DECORATION ) {
450 other = gtk_icon_size_from_name("inkscape-decoration");
451 } else {
452 other = static_cast<GtkIconSize>(size);
453 }
455 return other;
456 }
459 // PUBLIC CALL:
460 int sp_icon_get_phys_size(int size)
461 {
462 static bool init = false;
463 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
464 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
466 size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
468 if ( !sizeMapDone ) {
469 injectCustomSize();
470 }
472 if ( sizeDirty && init ) {
473 GtkIconSize const gtkSizes[] = {
474 GTK_ICON_SIZE_MENU,
475 GTK_ICON_SIZE_SMALL_TOOLBAR,
476 GTK_ICON_SIZE_LARGE_TOOLBAR,
477 GTK_ICON_SIZE_BUTTON,
478 GTK_ICON_SIZE_DND,
479 GTK_ICON_SIZE_DIALOG,
480 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
481 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
482 GTK_ICON_SIZE_MENU
483 };
484 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
485 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
487 g_assert( val_ix < G_N_ELEMENTS(vals) );
489 gint width = 0;
490 gint height = 0;
491 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
492 init &= (lastSys[val_ix] == std::max(width, height));
493 }
494 }
495 }
497 if ( !init ) {
498 sizeDirty = false;
499 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
500 bool dump = prefs->getBool("/debug/icons/dumpDefault");
502 if ( dump ) {
503 g_message( "Default icon sizes:" );
504 }
505 memset( vals, 0, sizeof(vals) );
506 memset( lastSys, 0, sizeof(lastSys) );
507 GtkIconSize const gtkSizes[] = {
508 GTK_ICON_SIZE_MENU,
509 GTK_ICON_SIZE_SMALL_TOOLBAR,
510 GTK_ICON_SIZE_LARGE_TOOLBAR,
511 GTK_ICON_SIZE_BUTTON,
512 GTK_ICON_SIZE_DND,
513 GTK_ICON_SIZE_DIALOG,
514 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
515 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
516 GTK_ICON_SIZE_MENU
517 };
518 gchar const *const names[] = {
519 "GTK_ICON_SIZE_MENU",
520 "GTK_ICON_SIZE_SMALL_TOOLBAR",
521 "GTK_ICON_SIZE_LARGE_TOOLBAR",
522 "GTK_ICON_SIZE_BUTTON",
523 "GTK_ICON_SIZE_DND",
524 "GTK_ICON_SIZE_DIALOG",
525 "inkscape-decoration"
526 };
528 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
530 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
531 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
533 g_assert( val_ix < G_N_ELEMENTS(vals) );
535 gint width = 0;
536 gint height = 0;
537 bool used = false;
538 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
539 vals[val_ix] = std::max(width, height);
540 lastSys[val_ix] = vals[val_ix];
541 used = true;
542 }
543 if (dump) {
544 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
545 i, gtkSizes[i],
546 ( used ? ' ' : 'X' ), width, height, names[i]);
547 }
548 gchar const *id = GTK_STOCK_OPEN;
549 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
550 if (pb) {
551 width = gdk_pixbuf_get_width(pb);
552 height = gdk_pixbuf_get_height(pb);
553 int newSize = std::max( width, height );
554 // TODO perhaps check a few more stock icons to get a range on sizes.
555 if ( newSize > 0 ) {
556 vals[val_ix] = newSize;
557 }
558 if (dump) {
559 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
560 }
562 g_object_unref(G_OBJECT(pb));
563 }
564 }
565 //g_object_unref(icon);
566 init = true;
567 }
569 return vals[size];
570 }
572 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
573 {
574 GtkWidget &widget = *GTK_WIDGET(icon);
576 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
578 if (image) {
579 int const padx = ( ( widget.allocation.width > icon->psize )
580 ? ( widget.allocation.width - icon->psize ) / 2
581 : 0 );
582 int const pady = ( ( widget.allocation.height > icon->psize )
583 ? ( widget.allocation.height - icon->psize ) / 2
584 : 0 );
586 int const x0 = std::max(area->x, widget.allocation.x + padx);
587 int const y0 = std::max(area->y, widget.allocation.y + pady);
588 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
589 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
591 int width = x1 - x0;
592 int height = y1 - y0;
593 // Limit drawing to when we actually have something. Avoids some crashes.
594 if ( (width > 0) && (height > 0) ) {
595 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
596 x0 - widget.allocation.x - padx,
597 y0 - widget.allocation.y - pady,
598 x0, y0,
599 width, height,
600 GDK_RGB_DITHER_NORMAL, x0, y0);
601 }
602 }
603 }
605 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
606 {
607 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
608 // TODO: bulia, please look over
609 gsize bytesRead = 0;
610 gsize bytesWritten = 0;
611 GError *error = NULL;
612 gchar *localFilename = g_filename_from_utf8( path,
613 -1,
614 &bytesRead,
615 &bytesWritten,
616 &error);
617 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
618 g_free(localFilename);
619 g_free(path);
620 if (!pb) {
621 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
622 // TODO: bulia, please look over
623 gsize bytesRead = 0;
624 gsize bytesWritten = 0;
625 GError *error = NULL;
626 gchar *localFilename = g_filename_from_utf8( path,
627 -1,
628 &bytesRead,
629 &bytesWritten,
630 &error);
631 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
632 g_free(localFilename);
633 g_free(path);
634 }
636 if (pb) {
637 if (!gdk_pixbuf_get_has_alpha(pb)) {
638 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
639 }
641 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
642 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
643 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
644 g_object_unref(G_OBJECT(pb));
645 pb = spb;
646 }
647 }
649 return pb;
650 }
652 // takes doc, root, icon, and icon name to produce pixels
653 extern "C" guchar *
654 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
655 gchar const *name, unsigned psize )
656 {
657 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
658 bool const dump = prefs->getBool("/debug/icons/dumpSvg");
659 guchar *px = NULL;
661 if (doc) {
662 SPObject *object = doc->getObjectById(name);
663 if (object && SP_IS_ITEM(object)) {
664 /* Find bbox in document */
665 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
666 Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
668 if ( SP_OBJECT_PARENT(object) == NULL )
669 {
670 dbox = Geom::Rect(Geom::Point(0, 0),
671 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
672 }
674 /* This is in document coordinates, i.e. pixels */
675 if ( dbox ) {
676 NRGC gc(NULL);
677 /* Update to renderable state */
678 double sf = 1.0;
679 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
680 gc.transform.setIdentity();
681 nr_arena_item_invoke_update( root, NULL, &gc,
682 NR_ARENA_ITEM_STATE_ALL,
683 NR_ARENA_ITEM_STATE_NONE );
684 /* Item integer bbox in points */
685 NRRectL ibox;
686 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
687 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
688 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
689 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
691 if ( dump ) {
692 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
693 }
695 /* Find button visible area */
696 int width = ibox.x1 - ibox.x0;
697 int height = ibox.y1 - ibox.y0;
699 if ( dump ) {
700 g_message( " vis --'%s' (%d,%d)", name, width, height );
701 }
703 {
704 int block = std::max(width, height);
705 if (block != static_cast<int>(psize) ) {
706 if ( dump ) {
707 g_message(" resizing" );
708 }
709 sf = (double)psize / (double)block;
711 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
712 gc.transform.setIdentity();
713 nr_arena_item_invoke_update( root, NULL, &gc,
714 NR_ARENA_ITEM_STATE_ALL,
715 NR_ARENA_ITEM_STATE_NONE );
716 /* Item integer bbox in points */
717 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
718 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
719 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
720 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
722 if ( dump ) {
723 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
724 }
726 /* Find button visible area */
727 width = ibox.x1 - ibox.x0;
728 height = ibox.y1 - ibox.y0;
729 if ( dump ) {
730 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
731 }
732 }
733 }
735 int dx, dy;
736 //dx = (psize - width) / 2;
737 //dy = (psize - height) / 2;
738 dx=dy=psize;
739 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
740 dy=(dy-height)/2;
741 NRRectL area;
742 area.x0 = ibox.x0 - dx;
743 area.y0 = ibox.y0 - dy;
744 area.x1 = area.x0 + psize;
745 area.y1 = area.y0 + psize;
746 /* Actual renderable area */
747 NRRectL ua;
748 ua.x0 = MAX(ibox.x0, area.x0);
749 ua.y0 = MAX(ibox.y0, area.y0);
750 ua.x1 = MIN(ibox.x1, area.x1);
751 ua.y1 = MIN(ibox.y1, area.y1);
753 if ( dump ) {
754 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
755 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
756 }
757 /* Set up pixblock */
758 px = g_new(guchar, 4 * psize * psize);
759 memset(px, 0x00, 4 * psize * psize);
760 /* Render */
761 NRPixBlock B;
762 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
763 ua.x0, ua.y0, ua.x1, ua.y1,
764 px + 4 * psize * (ua.y0 - area.y0) +
765 4 * (ua.x0 - area.x0),
766 4 * psize, FALSE, FALSE );
767 nr_arena_item_invoke_render(NULL, root, &ua, &B,
768 NR_ARENA_ITEM_RENDER_NO_CACHE );
769 nr_pixblock_release(&B);
771 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
772 if ( useOverlay ) {
773 sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
774 }
775 }
776 }
777 }
779 return px;
780 } // end of sp_icon_doc_icon()
784 struct svg_doc_cache_t
785 {
786 SPDocument *doc;
787 NRArenaItem *root;
788 };
790 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
791 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
793 Glib::ustring icon_cache_key(gchar const *name,
794 unsigned lsize, unsigned psize)
795 {
796 Glib::ustring key=name;
797 key += ":";
798 key += lsize;
799 key += ":";
800 key += psize;
801 return key;
802 }
804 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
805 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
806 if ( found != pb_cache.end() ) {
807 return found->second;
808 }
809 return NULL;
810 }
812 static guchar *load_svg_pixels(gchar const *name,
813 unsigned /*lsize*/, unsigned psize)
814 {
815 SPDocument *doc = NULL;
816 NRArenaItem *root = NULL;
817 svg_doc_cache_t *info = NULL;
819 // Fall back from user prefs dir into system locations.
820 Glib::ustring iconsvg = name;
821 iconsvg += ".svg";
822 std::list<gchar *> sources;
823 sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
824 sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
825 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
826 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
828 // Try each document in turn until we successfully load the icon from one
829 guchar *px=NULL;
830 while ( !sources.empty() && !px ) {
831 gchar *doc_filename = sources.front();
833 // Did we already load this doc?
834 Glib::ustring key(doc_filename);
835 info = 0;
836 {
837 std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
838 if ( i != doc_cache.end() ) {
839 info = i->second;
840 }
841 }
843 /* Try to load from document. */
844 if (!info &&
845 Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
846 (doc = sp_document_new( doc_filename, FALSE )) ) {
848 // prep the document
849 sp_document_ensure_up_to_date(doc);
850 /* Create new arena */
851 NRArena *arena = NRArena::create();
852 /* Create ArenaItem and set transform */
853 unsigned visionkey = sp_item_display_key_new(1);
854 /* fixme: Memory manage root if needed (Lauris) */
855 root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
856 arena, visionkey, SP_ITEM_SHOW_DISPLAY );
858 // store into the cache
859 info = new svg_doc_cache_t;
860 g_assert(info);
862 info->doc=doc;
863 info->root=root;
864 doc_cache[key]=info;
865 }
866 if (info) {
867 doc=info->doc;
868 root=info->root;
869 }
871 // toss the filename
872 g_free(doc_filename);
873 sources.pop_front();
875 // move on to the next document if we couldn't get anything
876 if (!info && !doc) continue;
878 px = sp_icon_doc_icon( doc, root, name, psize );
879 }
881 return px;
882 }
884 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
885 {
886 if ( iconSetCache.find(name) == iconSetCache.end() ) {
887 // only add a placeholder if nothing is already set
888 Gtk::IconSet icnset;
889 Gtk::IconSource src;
890 src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
891 src.set_size( Gtk::IconSize(size) );
892 icnset.add_source(src);
893 inkyIcons->add(Gtk::StockID(name), icnset);
894 }
895 }
897 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
898 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
899 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
900 GtkStockItem stock;
901 gboolean stockFound = gtk_stock_lookup( name, &stock );
902 if ( !stockFound ) {
903 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
904 if (dump) {
905 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
906 }
907 }
909 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
910 if ( it->_lsize == lsize ) {
911 iconSetCache[name].erase(it);
912 break;
913 }
914 }
915 iconSetCache[name].push_back(IconCacheItem(lsize, pb));
917 Gtk::IconSet icnset;
918 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
919 Gtk::IconSource src;
920 g_object_ref( G_OBJECT(it->_pb) );
921 src.set_pixbuf( Glib::wrap(it->_pb) );
922 src.set_size( Gtk::IconSize(it->_lsize) );
923 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
924 src.set_state_wildcarded( true );
925 icnset.add_source(src);
926 }
927 inkyIcons->add(Gtk::StockID(name), icnset);
928 }
930 // returns true if icon needed preloading, false if nothing was done
931 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
932 {
933 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
934 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
935 Glib::ustring key = icon_cache_key(name, lsize, psize);
936 GdkPixbuf *pb = get_cached_pixbuf(key);
937 if (pb) {
938 return false;
939 } else {
940 pb = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, psize,
941 (GtkIconLookupFlags) 0, NULL);
942 if (!pb) {
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 }
953 if (px) {
954 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
955 psize, psize, psize * 4,
956 (GdkPixbufDestroyNotify)g_free, NULL);
957 } else if (dump) {
958 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
959 }
960 }
962 if (pb) {
963 pb_cache[key] = pb;
964 addToIconSet(pb, name, lsize, psize);
965 }
966 return true;
967 }
968 }
970 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
971 {
972 Glib::ustring key = icon_cache_key(name, lsize, psize);
974 // did we already load this icon at this scale/size?
975 GdkPixbuf* pb = get_cached_pixbuf(key);
976 if (!pb) {
977 guchar *px = load_svg_pixels(name, lsize, psize);
978 if (px) {
979 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
980 psize, psize, psize * 4,
981 (GdkPixbufDestroyNotify)g_free, NULL);
982 pb_cache[key] = pb;
983 addToIconSet(pb, name, lsize, psize);
984 }
985 }
987 if ( pb ) {
988 // increase refcount since we're handing out ownership
989 g_object_ref(G_OBJECT(pb));
990 }
991 return pb;
992 }
994 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
995 unsigned r, unsigned g, unsigned b)
996 {
997 for ( int y = 0; y < height; y += 4 ) {
998 guchar *ptr = px + y * stride;
999 for ( int x = 0; x < width; x += 4 ) {
1000 *(ptr++) = r;
1001 *(ptr++) = g;
1002 *(ptr++) = b;
1003 *(ptr++) = 0xff;
1005 ptr += 4 * 3;
1006 }
1007 }
1009 if ( width > 1 && height > 1 ) {
1010 // point at the last pixel
1011 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
1013 if ( width > 2 ) {
1014 px[4] = r;
1015 px[5] = g;
1016 px[6] = b;
1017 px[7] = 0xff;
1019 ptr[-12] = r;
1020 ptr[-11] = g;
1021 ptr[-10] = b;
1022 ptr[-9] = 0xff;
1023 }
1025 ptr[-4] = r;
1026 ptr[-3] = g;
1027 ptr[-2] = b;
1028 ptr[-1] = 0xff;
1030 px[0 + stride] = r;
1031 px[1 + stride] = g;
1032 px[2 + stride] = b;
1033 px[3 + stride] = 0xff;
1035 ptr[0 - stride] = r;
1036 ptr[1 - stride] = g;
1037 ptr[2 - stride] = b;
1038 ptr[3 - stride] = 0xff;
1040 if ( height > 2 ) {
1041 ptr[0 - stride * 3] = r;
1042 ptr[1 - stride * 3] = g;
1043 ptr[2 - stride * 3] = b;
1044 ptr[3 - stride * 3] = 0xff;
1045 }
1046 }
1047 }
1049 class preRenderItem
1050 {
1051 public:
1052 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1053 _lsize( lsize ),
1054 _name( name )
1055 {}
1056 GtkIconSize _lsize;
1057 Glib::ustring _name;
1058 };
1061 static std::vector<preRenderItem> pendingRenders;
1062 static bool callbackHooked = false;
1064 static void addPreRender( GtkIconSize lsize, gchar const *name )
1065 {
1066 if ( !callbackHooked )
1067 {
1068 callbackHooked = true;
1069 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1070 }
1072 pendingRenders.push_back(preRenderItem(lsize, name));
1073 }
1075 gboolean icon_prerender_task(gpointer /*data*/) {
1076 if (!pendingRenders.empty()) {
1077 bool workDone = false;
1078 do {
1079 preRenderItem single = pendingRenders.front();
1080 pendingRenders.erase(pendingRenders.begin());
1081 int psize = sp_icon_get_phys_size(single._lsize);
1082 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1083 } while (!pendingRenders.empty() && !workDone);
1084 }
1086 if (!pendingRenders.empty()) {
1087 return TRUE;
1088 } else {
1089 callbackHooked = false;
1090 return FALSE;
1091 }
1092 }
1095 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1096 gchar* id = 0;
1097 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1098 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1099 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1100 if ( id ) {
1101 int psize = sp_icon_get_phys_size(lsize);
1102 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1103 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1104 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1105 prerender_icon(id, lsize, psize);
1106 pendingRenders.erase(it);
1107 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1108 if (lsize != size) {
1109 int psize = sp_icon_get_phys_size(size);
1110 prerender_icon(id, size, psize);
1111 }
1112 break;
1113 }
1114 }
1115 }
1117 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1118 }
1120 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1121 GtkImage* img = GTK_IMAGE(widget);
1122 gchar const* iconName = 0;
1123 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1124 gtk_image_get_icon_name(img, &iconName, &size);
1125 if ( iconName ) {
1126 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1127 if ( type == GTK_IMAGE_ICON_NAME ) {
1128 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1129 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1130 int psize = sp_icon_get_phys_size(size);
1131 prerender_icon(iconName, size, psize);
1132 pendingRenders.erase(it);
1133 break;
1134 }
1135 }
1137 } else {
1138 g_warning("UNEXPECTED TYPE of %d", (int)type);
1139 }
1140 }
1142 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1143 }
1146 /*
1147 Local Variables:
1148 mode:c++
1149 c-file-style:"stroustrup"
1150 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1151 indent-tabs-mode:nil
1152 fill-column:99
1153 End:
1154 */
1155 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :