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 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;
115 }
117 static void
118 sp_icon_class_init(SPIconClass *klass)
119 {
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;
135 }
138 static void
139 sp_icon_init(SPIcon *icon)
140 {
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;
147 }
149 static void
150 sp_icon_destroy(GtkObject *object)
151 {
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);
160 }
162 static void sp_icon_reset( SPIcon *icon ) {
163 icon->psize = 0;
164 sp_icon_clear(icon);
165 }
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 }
176 }
178 static void
179 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
180 {
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;
188 }
190 static void
191 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
192 {
193 widget->allocation = *allocation;
195 if (GTK_WIDGET_DRAWABLE(widget)) {
196 gtk_widget_queue_draw(widget);
197 }
198 }
200 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
201 {
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;
212 }
214 // PUBLIC CALL:
215 void sp_icon_fetch_pixbuf( SPIcon *icon )
216 {
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 }
236 }
238 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
239 {
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);
245 }
247 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
248 {
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);
254 }
256 static void sp_icon_theme_changed( SPIcon *icon )
257 {
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) );
262 }
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";
278 }
280 static GtkWidget *
281 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
282 {
283 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
284 static bool dump = prefs->getBool( "/debug/icons/dumpGtk");
286 GtkWidget *widget = 0;
287 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
288 if ( !sizeMapDone ) {
289 injectCustomSize();
290 }
291 GtkIconSize mappedSize = iconSizeLookup[trySize];
293 GtkStockItem stock;
294 gboolean stockFound = gtk_stock_lookup( name, &stock );
296 GtkWidget *img = 0;
297 if ( legacyNames.empty() ) {
298 setupLegacyNaming();
299 }
301 bool flagMe = false;
302 if ( legacyNames.find(name) != legacyNames.end() ) {
303 img = gtk_image_new_from_icon_name( name, mappedSize );
304 flagMe = true;
305 if ( dump ) {
306 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
307 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
308 g_message(" Type is %d %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
309 }
310 } else {
311 img = gtk_image_new_from_stock( name, mappedSize );
312 }
314 if ( img ) {
315 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
316 if ( type == GTK_IMAGE_STOCK ) {
317 if ( !stockFound ) {
318 // It's not showing as a stock ID, so assume it will be present internally
319 populate_placeholder_icon( name, mappedSize );
320 addPreRender( mappedSize, name );
322 // Add a hook to render if set visible before prerender is done.
323 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
324 if ( dump ) {
325 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
326 }
327 }
328 widget = GTK_WIDGET(img);
329 img = 0;
330 if ( dump ) {
331 g_message( "loaded gtk '%s' %d (GTK_IMAGE_STOCK) %s on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
332 }
333 } else if ( type == GTK_IMAGE_ICON_NAME ) {
334 widget = GTK_WIDGET(img);
335 img = 0;
337 // Add a hook to render if set visible before prerender is done.
338 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
340 if ( prefs->getBool("/options/iconrender/named_nodelay") ) {
341 int psize = sp_icon_get_phys_size(lsize);
342 prerender_icon(name, mappedSize, psize);
343 } else {
344 addPreRender( mappedSize, name );
345 }
346 } else {
347 if ( dump ) {
348 g_message( "skipped gtk '%s' %d (not GTK_IMAGE_STOCK)", name, lsize );
349 }
350 //g_object_unref( (GObject *)img );
351 img = 0;
352 }
353 }
355 if ( !widget ) {
356 //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
357 SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
358 icon->lsize = lsize;
359 icon->name = g_strdup(name);
360 icon->psize = sp_icon_get_phys_size(lsize);
362 widget = GTK_WIDGET(icon);
363 }
365 return widget;
366 }
368 GtkWidget *
369 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
370 {
371 return sp_icon_new_full( lsize, name );
372 }
374 // PUBLIC CALL:
375 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
376 {
377 Gtk::Widget *result = 0;
378 GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
380 if ( widget ) {
381 if ( GTK_IS_IMAGE(widget) ) {
382 GtkImage *img = GTK_IMAGE(widget);
383 result = Glib::wrap( img );
384 } else {
385 result = Glib::wrap( widget );
386 }
387 }
389 return result;
390 }
392 GtkIconSize
393 sp_icon_get_gtk_size(int size)
394 {
395 static GtkIconSize sizemap[64] = {(GtkIconSize)0};
396 size = CLAMP(size, 4, 63);
397 if (!sizemap[size]) {
398 static int count = 0;
399 char c[64];
400 g_snprintf(c, 64, "InkscapeIcon%d", count++);
401 sizemap[size] = gtk_icon_size_register(c, size, size);
402 }
403 return sizemap[size];
404 }
407 static void injectCustomSize()
408 {
409 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
410 if ( !sizeMapDone )
411 {
412 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
413 bool dump = prefs->getBool( "/debug/icons/dumpDefault");
414 gint width = 0;
415 gint height = 0;
416 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
417 gint newWidth = ((width * 3) / 4);
418 gint newHeight = ((height * 3) / 4);
419 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
420 if ( newSizeEnum ) {
421 if ( dump ) {
422 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
423 }
424 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
425 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
426 iconSizeLookup[index] = newSizeEnum;
427 } else if ( dump ) {
428 g_message("size lookup array too small to store entry");
429 }
430 }
431 }
432 sizeMapDone = true;
433 }
435 static bool hit = false;
436 if ( !hit ) {
437 hit = true;
438 inkyIcons = Gtk::IconFactory::create();
439 inkyIcons->add_default();
440 }
441 }
443 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
444 {
445 GtkIconSize other = GTK_ICON_SIZE_MENU;
446 injectCustomSize();
447 size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
448 if ( size == Inkscape::ICON_SIZE_DECORATION ) {
449 other = gtk_icon_size_from_name("inkscape-decoration");
450 } else {
451 other = static_cast<GtkIconSize>(size);
452 }
454 return other;
455 }
458 // PUBLIC CALL:
459 int sp_icon_get_phys_size(int size)
460 {
461 static bool init = false;
462 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
463 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
465 size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
467 if ( !sizeMapDone ) {
468 injectCustomSize();
469 }
471 if ( sizeDirty && init ) {
472 GtkIconSize const gtkSizes[] = {
473 GTK_ICON_SIZE_MENU,
474 GTK_ICON_SIZE_SMALL_TOOLBAR,
475 GTK_ICON_SIZE_LARGE_TOOLBAR,
476 GTK_ICON_SIZE_BUTTON,
477 GTK_ICON_SIZE_DND,
478 GTK_ICON_SIZE_DIALOG,
479 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
480 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
481 GTK_ICON_SIZE_MENU
482 };
483 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
484 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
486 g_assert( val_ix < G_N_ELEMENTS(vals) );
488 gint width = 0;
489 gint height = 0;
490 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
491 init &= (lastSys[val_ix] == std::max(width, height));
492 }
493 }
494 }
496 if ( !init ) {
497 sizeDirty = false;
498 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
499 bool dump = prefs->getBool("/debug/icons/dumpDefault");
501 if ( dump ) {
502 g_message( "Default icon sizes:" );
503 }
504 memset( vals, 0, sizeof(vals) );
505 memset( lastSys, 0, sizeof(lastSys) );
506 GtkIconSize const gtkSizes[] = {
507 GTK_ICON_SIZE_MENU,
508 GTK_ICON_SIZE_SMALL_TOOLBAR,
509 GTK_ICON_SIZE_LARGE_TOOLBAR,
510 GTK_ICON_SIZE_BUTTON,
511 GTK_ICON_SIZE_DND,
512 GTK_ICON_SIZE_DIALOG,
513 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
514 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
515 GTK_ICON_SIZE_MENU
516 };
517 gchar const *const names[] = {
518 "GTK_ICON_SIZE_MENU",
519 "GTK_ICON_SIZE_SMALL_TOOLBAR",
520 "GTK_ICON_SIZE_LARGE_TOOLBAR",
521 "GTK_ICON_SIZE_BUTTON",
522 "GTK_ICON_SIZE_DND",
523 "GTK_ICON_SIZE_DIALOG",
524 "inkscape-decoration"
525 };
527 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
529 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
530 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
532 g_assert( val_ix < G_N_ELEMENTS(vals) );
534 gint width = 0;
535 gint height = 0;
536 bool used = false;
537 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
538 vals[val_ix] = std::max(width, height);
539 lastSys[val_ix] = vals[val_ix];
540 used = true;
541 }
542 if (dump) {
543 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
544 i, gtkSizes[i],
545 ( used ? ' ' : 'X' ), width, height, names[i]);
546 }
547 gchar const *id = GTK_STOCK_OPEN;
548 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
549 if (pb) {
550 width = gdk_pixbuf_get_width(pb);
551 height = gdk_pixbuf_get_height(pb);
552 int newSize = std::max( width, height );
553 // TODO perhaps check a few more stock icons to get a range on sizes.
554 if ( newSize > 0 ) {
555 vals[val_ix] = newSize;
556 }
557 if (dump) {
558 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
559 }
561 g_object_unref(G_OBJECT(pb));
562 }
563 }
564 //g_object_unref(icon);
565 init = true;
566 }
568 return vals[size];
569 }
571 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
572 {
573 GtkWidget &widget = *GTK_WIDGET(icon);
575 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
577 if (image) {
578 int const padx = ( ( widget.allocation.width > icon->psize )
579 ? ( widget.allocation.width - icon->psize ) / 2
580 : 0 );
581 int const pady = ( ( widget.allocation.height > icon->psize )
582 ? ( widget.allocation.height - icon->psize ) / 2
583 : 0 );
585 int const x0 = std::max(area->x, widget.allocation.x + padx);
586 int const y0 = std::max(area->y, widget.allocation.y + pady);
587 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
588 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
590 int width = x1 - x0;
591 int height = y1 - y0;
592 // Limit drawing to when we actually have something. Avoids some crashes.
593 if ( (width > 0) && (height > 0) ) {
594 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
595 x0 - widget.allocation.x - padx,
596 y0 - widget.allocation.y - pady,
597 x0, y0,
598 width, height,
599 GDK_RGB_DITHER_NORMAL, x0, y0);
600 }
601 }
602 }
604 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
605 {
606 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
607 // TODO: bulia, please look over
608 gsize bytesRead = 0;
609 gsize bytesWritten = 0;
610 GError *error = NULL;
611 gchar *localFilename = g_filename_from_utf8( path,
612 -1,
613 &bytesRead,
614 &bytesWritten,
615 &error);
616 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
617 g_free(localFilename);
618 g_free(path);
619 if (!pb) {
620 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
621 // TODO: bulia, please look over
622 gsize bytesRead = 0;
623 gsize bytesWritten = 0;
624 GError *error = NULL;
625 gchar *localFilename = g_filename_from_utf8( path,
626 -1,
627 &bytesRead,
628 &bytesWritten,
629 &error);
630 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
631 g_free(localFilename);
632 g_free(path);
633 }
635 if (pb) {
636 if (!gdk_pixbuf_get_has_alpha(pb)) {
637 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
638 }
640 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
641 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
642 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
643 g_object_unref(G_OBJECT(pb));
644 pb = spb;
645 }
646 }
648 return pb;
649 }
651 // takes doc, root, icon, and icon name to produce pixels
652 extern "C" guchar *
653 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
654 gchar const *name, unsigned psize )
655 {
656 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
657 bool const dump = prefs->getBool("/debug/icons/dumpSvg");
658 guchar *px = NULL;
660 if (doc) {
661 SPObject *object = doc->getObjectById(name);
662 if (object && SP_IS_ITEM(object)) {
663 /* Find bbox in document */
664 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
665 Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
667 if ( SP_OBJECT_PARENT(object) == NULL )
668 {
669 dbox = Geom::Rect(Geom::Point(0, 0),
670 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
671 }
673 /* This is in document coordinates, i.e. pixels */
674 if ( dbox ) {
675 NRGC gc(NULL);
676 /* Update to renderable state */
677 double sf = 1.0;
678 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
679 gc.transform.setIdentity();
680 nr_arena_item_invoke_update( root, NULL, &gc,
681 NR_ARENA_ITEM_STATE_ALL,
682 NR_ARENA_ITEM_STATE_NONE );
683 /* Item integer bbox in points */
684 NRRectL ibox;
685 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
686 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
687 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
688 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
690 if ( dump ) {
691 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
692 }
694 /* Find button visible area */
695 int width = ibox.x1 - ibox.x0;
696 int height = ibox.y1 - ibox.y0;
698 if ( dump ) {
699 g_message( " vis --'%s' (%d,%d)", name, width, height );
700 }
702 {
703 int block = std::max(width, height);
704 if (block != static_cast<int>(psize) ) {
705 if ( dump ) {
706 g_message(" resizing" );
707 }
708 sf = (double)psize / (double)block;
710 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
711 gc.transform.setIdentity();
712 nr_arena_item_invoke_update( root, NULL, &gc,
713 NR_ARENA_ITEM_STATE_ALL,
714 NR_ARENA_ITEM_STATE_NONE );
715 /* Item integer bbox in points */
716 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
717 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
718 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
719 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
721 if ( dump ) {
722 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
723 }
725 /* Find button visible area */
726 width = ibox.x1 - ibox.x0;
727 height = ibox.y1 - ibox.y0;
728 if ( dump ) {
729 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
730 }
731 }
732 }
734 int dx, dy;
735 //dx = (psize - width) / 2;
736 //dy = (psize - height) / 2;
737 dx=dy=psize;
738 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
739 dy=(dy-height)/2;
740 NRRectL area;
741 area.x0 = ibox.x0 - dx;
742 area.y0 = ibox.y0 - dy;
743 area.x1 = area.x0 + psize;
744 area.y1 = area.y0 + psize;
745 /* Actual renderable area */
746 NRRectL ua;
747 ua.x0 = MAX(ibox.x0, area.x0);
748 ua.y0 = MAX(ibox.y0, area.y0);
749 ua.x1 = MIN(ibox.x1, area.x1);
750 ua.y1 = MIN(ibox.y1, area.y1);
752 if ( dump ) {
753 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
754 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
755 }
756 /* Set up pixblock */
757 px = g_new(guchar, 4 * psize * psize);
758 memset(px, 0x00, 4 * psize * psize);
759 /* Render */
760 NRPixBlock B;
761 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
762 ua.x0, ua.y0, ua.x1, ua.y1,
763 px + 4 * psize * (ua.y0 - area.y0) +
764 4 * (ua.x0 - area.x0),
765 4 * psize, FALSE, FALSE );
766 nr_arena_item_invoke_render(NULL, root, &ua, &B,
767 NR_ARENA_ITEM_RENDER_NO_CACHE );
768 nr_pixblock_release(&B);
770 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
771 if ( useOverlay ) {
772 sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
773 }
774 }
775 }
776 }
778 return px;
779 } // end of sp_icon_doc_icon()
783 struct svg_doc_cache_t
784 {
785 SPDocument *doc;
786 NRArenaItem *root;
787 };
789 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
790 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
792 Glib::ustring icon_cache_key(gchar const *name,
793 unsigned lsize, unsigned psize)
794 {
795 Glib::ustring key=name;
796 key += ":";
797 key += lsize;
798 key += ":";
799 key += psize;
800 return key;
801 }
803 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
804 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
805 if ( found != pb_cache.end() ) {
806 return found->second;
807 }
808 return NULL;
809 }
811 static guchar *load_svg_pixels(gchar const *name,
812 unsigned /*lsize*/, unsigned psize)
813 {
814 SPDocument *doc = NULL;
815 NRArenaItem *root = NULL;
816 svg_doc_cache_t *info = NULL;
818 // Fall back from user prefs dir into system locations.
819 Glib::ustring iconsvg = name;
820 iconsvg += ".svg";
821 std::list<gchar *> sources;
822 sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
823 sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
824 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
825 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
827 // Try each document in turn until we successfully load the icon from one
828 guchar *px=NULL;
829 while ( !sources.empty() && !px ) {
830 gchar *doc_filename = sources.front();
832 // Did we already load this doc?
833 Glib::ustring key(doc_filename);
834 info = 0;
835 {
836 std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
837 if ( i != doc_cache.end() ) {
838 info = i->second;
839 }
840 }
842 /* Try to load from document. */
843 if (!info &&
844 Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
845 (doc = sp_document_new( doc_filename, FALSE )) ) {
847 // prep the document
848 sp_document_ensure_up_to_date(doc);
849 /* Create new arena */
850 NRArena *arena = NRArena::create();
851 /* Create ArenaItem and set transform */
852 unsigned visionkey = sp_item_display_key_new(1);
853 /* fixme: Memory manage root if needed (Lauris) */
854 root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
855 arena, visionkey, SP_ITEM_SHOW_DISPLAY );
857 // store into the cache
858 info = new svg_doc_cache_t;
859 g_assert(info);
861 info->doc=doc;
862 info->root=root;
863 doc_cache[key]=info;
864 }
865 if (info) {
866 doc=info->doc;
867 root=info->root;
868 }
870 // toss the filename
871 g_free(doc_filename);
872 sources.pop_front();
874 // move on to the next document if we couldn't get anything
875 if (!info && !doc) continue;
877 px = sp_icon_doc_icon( doc, root, name, psize );
878 }
880 return px;
881 }
883 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
884 {
885 if ( iconSetCache.find(name) == iconSetCache.end() ) {
886 // only add a placeholder if nothing is already set
887 Gtk::IconSet icnset;
888 Gtk::IconSource src;
889 src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
890 src.set_size( Gtk::IconSize(size) );
891 icnset.add_source(src);
892 inkyIcons->add(Gtk::StockID(name), icnset);
893 }
894 }
896 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
897 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
898 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
899 GtkStockItem stock;
900 gboolean stockFound = gtk_stock_lookup( name, &stock );
901 if ( !stockFound ) {
902 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
903 if (dump) {
904 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
905 }
906 }
908 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
909 if ( it->_lsize == lsize ) {
910 iconSetCache[name].erase(it);
911 break;
912 }
913 }
914 iconSetCache[name].push_back(IconCacheItem(lsize, pb));
916 Gtk::IconSet icnset;
917 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
918 Gtk::IconSource src;
919 g_object_ref( G_OBJECT(it->_pb) );
920 src.set_pixbuf( Glib::wrap(it->_pb) );
921 src.set_size( Gtk::IconSize(it->_lsize) );
922 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
923 src.set_state_wildcarded( true );
924 icnset.add_source(src);
925 }
926 inkyIcons->add(Gtk::StockID(name), icnset);
927 }
929 // returns true if icon needed preloading, false if nothing was done
930 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
931 {
932 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
933 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
934 Glib::ustring key = icon_cache_key(name, lsize, psize);
935 GdkPixbuf *pb = get_cached_pixbuf(key);
936 if (pb) {
937 return false;
938 } else {
939 guchar* px = load_svg_pixels(name, lsize, psize);
940 if ( !px ) {
941 // check for a fallback name
942 if ( legacyNames.find(name) != legacyNames.end() ) {
943 if ( dump ) {
944 g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
945 }
946 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
947 }
948 }
950 if (px) {
951 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
952 psize, psize, psize * 4,
953 (GdkPixbufDestroyNotify)g_free, NULL);
954 pb_cache[key] = pb;
955 addToIconSet(pb, name, lsize, psize);
956 } else if (dump) {
957 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
958 }
959 return true;
960 }
961 }
963 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
964 {
965 Glib::ustring key = icon_cache_key(name, lsize, psize);
967 // did we already load this icon at this scale/size?
968 GdkPixbuf* pb = get_cached_pixbuf(key);
969 if (!pb) {
970 guchar *px = load_svg_pixels(name, lsize, psize);
971 if (px) {
972 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
973 psize, psize, psize * 4,
974 (GdkPixbufDestroyNotify)g_free, NULL);
975 pb_cache[key] = pb;
976 addToIconSet(pb, name, lsize, psize);
977 }
978 }
980 if ( pb ) {
981 // increase refcount since we're handing out ownership
982 g_object_ref(G_OBJECT(pb));
983 }
984 return pb;
985 }
987 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
988 unsigned r, unsigned g, unsigned b)
989 {
990 for ( int y = 0; y < height; y += 4 ) {
991 guchar *ptr = px + y * stride;
992 for ( int x = 0; x < width; x += 4 ) {
993 *(ptr++) = r;
994 *(ptr++) = g;
995 *(ptr++) = b;
996 *(ptr++) = 0xff;
998 ptr += 4 * 3;
999 }
1000 }
1002 if ( width > 1 && height > 1 ) {
1003 // point at the last pixel
1004 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
1006 if ( width > 2 ) {
1007 px[4] = r;
1008 px[5] = g;
1009 px[6] = b;
1010 px[7] = 0xff;
1012 ptr[-12] = r;
1013 ptr[-11] = g;
1014 ptr[-10] = b;
1015 ptr[-9] = 0xff;
1016 }
1018 ptr[-4] = r;
1019 ptr[-3] = g;
1020 ptr[-2] = b;
1021 ptr[-1] = 0xff;
1023 px[0 + stride] = r;
1024 px[1 + stride] = g;
1025 px[2 + stride] = b;
1026 px[3 + stride] = 0xff;
1028 ptr[0 - stride] = r;
1029 ptr[1 - stride] = g;
1030 ptr[2 - stride] = b;
1031 ptr[3 - stride] = 0xff;
1033 if ( height > 2 ) {
1034 ptr[0 - stride * 3] = r;
1035 ptr[1 - stride * 3] = g;
1036 ptr[2 - stride * 3] = b;
1037 ptr[3 - stride * 3] = 0xff;
1038 }
1039 }
1040 }
1042 class preRenderItem
1043 {
1044 public:
1045 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1046 _lsize( lsize ),
1047 _name( name )
1048 {}
1049 GtkIconSize _lsize;
1050 Glib::ustring _name;
1051 };
1054 static std::vector<preRenderItem> pendingRenders;
1055 static bool callbackHooked = false;
1057 static void addPreRender( GtkIconSize lsize, gchar const *name )
1058 {
1059 if ( !callbackHooked )
1060 {
1061 callbackHooked = true;
1062 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1063 }
1065 pendingRenders.push_back(preRenderItem(lsize, name));
1066 }
1068 gboolean icon_prerender_task(gpointer /*data*/) {
1069 if (!pendingRenders.empty()) {
1070 bool workDone = false;
1071 do {
1072 preRenderItem single = pendingRenders.front();
1073 pendingRenders.erase(pendingRenders.begin());
1074 int psize = sp_icon_get_phys_size(single._lsize);
1075 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1076 } while (!pendingRenders.empty() && !workDone);
1077 }
1079 if (!pendingRenders.empty()) {
1080 return TRUE;
1081 } else {
1082 callbackHooked = false;
1083 return FALSE;
1084 }
1085 }
1088 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1089 gchar* id = 0;
1090 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1091 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1092 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1093 if ( id ) {
1094 int psize = sp_icon_get_phys_size(lsize);
1095 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1096 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1097 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1098 prerender_icon(id, lsize, psize);
1099 pendingRenders.erase(it);
1100 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1101 if (lsize != size) {
1102 int psize = sp_icon_get_phys_size(size);
1103 prerender_icon(id, size, psize);
1104 }
1105 break;
1106 }
1107 }
1108 }
1110 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1111 }
1113 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1114 GtkImage* img = GTK_IMAGE(widget);
1115 gchar const* iconName = 0;
1116 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1117 gtk_image_get_icon_name(img, &iconName, &size);
1118 if ( iconName ) {
1119 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1120 if ( type == GTK_IMAGE_ICON_NAME ) {
1121 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1122 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1123 int psize = sp_icon_get_phys_size(size);
1124 prerender_icon(iconName, size, psize);
1125 pendingRenders.erase(it);
1126 break;
1127 }
1128 }
1130 } else {
1131 g_warning("UNEXPECTED TYPE of %d", (int)type);
1132 }
1133 }
1135 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1136 }
1139 /*
1140 Local Variables:
1141 mode:c++
1142 c-file-style:"stroustrup"
1143 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1144 indent-tabs-mode:nil
1145 fill-column:99
1146 End:
1147 */
1148 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :