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 // Fixup workaround
570 if ((size == GTK_ICON_SIZE_MENU) || (size == GTK_ICON_SIZE_SMALL_TOOLBAR) || (size == GTK_ICON_SIZE_LARGE_TOOLBAR)) {
571 gint width = 0;
572 gint height = 0;
573 if ( gtk_icon_size_lookup( static_cast<GtkIconSize>(size), &width, &height ) ) {
574 int newSize = std::max( width, height );
575 if (newSize != vals[size]) {
576 vals[size] = newSize;
577 }
578 }
579 }
581 return vals[size];
582 }
584 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
585 {
586 GtkWidget &widget = *GTK_WIDGET(icon);
588 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
590 if (image) {
591 int const padx = ( ( widget.allocation.width > icon->psize )
592 ? ( widget.allocation.width - icon->psize ) / 2
593 : 0 );
594 int const pady = ( ( widget.allocation.height > icon->psize )
595 ? ( widget.allocation.height - icon->psize ) / 2
596 : 0 );
598 int const x0 = std::max(area->x, widget.allocation.x + padx);
599 int const y0 = std::max(area->y, widget.allocation.y + pady);
600 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
601 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
603 int width = x1 - x0;
604 int height = y1 - y0;
605 // Limit drawing to when we actually have something. Avoids some crashes.
606 if ( (width > 0) && (height > 0) ) {
607 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
608 x0 - widget.allocation.x - padx,
609 y0 - widget.allocation.y - pady,
610 x0, y0,
611 width, height,
612 GDK_RGB_DITHER_NORMAL, x0, y0);
613 }
614 }
615 }
617 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
618 {
619 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
620 // TODO: bulia, please look over
621 gsize bytesRead = 0;
622 gsize bytesWritten = 0;
623 GError *error = NULL;
624 gchar *localFilename = g_filename_from_utf8( path,
625 -1,
626 &bytesRead,
627 &bytesWritten,
628 &error);
629 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
630 g_free(localFilename);
631 g_free(path);
632 if (!pb) {
633 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
634 // TODO: bulia, please look over
635 gsize bytesRead = 0;
636 gsize bytesWritten = 0;
637 GError *error = NULL;
638 gchar *localFilename = g_filename_from_utf8( path,
639 -1,
640 &bytesRead,
641 &bytesWritten,
642 &error);
643 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
644 g_free(localFilename);
645 g_free(path);
646 }
648 if (pb) {
649 if (!gdk_pixbuf_get_has_alpha(pb)) {
650 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
651 }
653 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
654 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
655 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
656 g_object_unref(G_OBJECT(pb));
657 pb = spb;
658 }
659 }
661 return pb;
662 }
664 // takes doc, root, icon, and icon name to produce pixels
665 extern "C" guchar *
666 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
667 gchar const *name, unsigned psize )
668 {
669 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
670 bool const dump = prefs->getBool("/debug/icons/dumpSvg");
671 guchar *px = NULL;
673 if (doc) {
674 SPObject *object = doc->getObjectById(name);
675 if (object && SP_IS_ITEM(object)) {
676 /* Find bbox in document */
677 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
678 Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
680 if ( SP_OBJECT_PARENT(object) == NULL )
681 {
682 dbox = Geom::Rect(Geom::Point(0, 0),
683 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
684 }
686 /* This is in document coordinates, i.e. pixels */
687 if ( dbox ) {
688 NRGC gc(NULL);
689 /* Update to renderable state */
690 double sf = 1.0;
691 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
692 gc.transform.setIdentity();
693 nr_arena_item_invoke_update( root, NULL, &gc,
694 NR_ARENA_ITEM_STATE_ALL,
695 NR_ARENA_ITEM_STATE_NONE );
696 /* Item integer bbox in points */
697 NRRectL ibox;
698 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
699 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
700 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
701 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
703 if ( dump ) {
704 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
705 }
707 /* Find button visible area */
708 int width = ibox.x1 - ibox.x0;
709 int height = ibox.y1 - ibox.y0;
711 if ( dump ) {
712 g_message( " vis --'%s' (%d,%d)", name, width, height );
713 }
715 {
716 int block = std::max(width, height);
717 if (block != static_cast<int>(psize) ) {
718 if ( dump ) {
719 g_message(" resizing" );
720 }
721 sf = (double)psize / (double)block;
723 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
724 gc.transform.setIdentity();
725 nr_arena_item_invoke_update( root, NULL, &gc,
726 NR_ARENA_ITEM_STATE_ALL,
727 NR_ARENA_ITEM_STATE_NONE );
728 /* Item integer bbox in points */
729 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
730 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
731 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
732 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
734 if ( dump ) {
735 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
736 }
738 /* Find button visible area */
739 width = ibox.x1 - ibox.x0;
740 height = ibox.y1 - ibox.y0;
741 if ( dump ) {
742 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
743 }
744 }
745 }
747 int dx, dy;
748 //dx = (psize - width) / 2;
749 //dy = (psize - height) / 2;
750 dx=dy=psize;
751 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
752 dy=(dy-height)/2;
753 NRRectL area;
754 area.x0 = ibox.x0 - dx;
755 area.y0 = ibox.y0 - dy;
756 area.x1 = area.x0 + psize;
757 area.y1 = area.y0 + psize;
758 /* Actual renderable area */
759 NRRectL ua;
760 ua.x0 = MAX(ibox.x0, area.x0);
761 ua.y0 = MAX(ibox.y0, area.y0);
762 ua.x1 = MIN(ibox.x1, area.x1);
763 ua.y1 = MIN(ibox.y1, area.y1);
765 if ( dump ) {
766 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
767 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
768 }
769 /* Set up pixblock */
770 px = g_new(guchar, 4 * psize * psize);
771 memset(px, 0x00, 4 * psize * psize);
772 /* Render */
773 NRPixBlock B;
774 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
775 ua.x0, ua.y0, ua.x1, ua.y1,
776 px + 4 * psize * (ua.y0 - area.y0) +
777 4 * (ua.x0 - area.x0),
778 4 * psize, FALSE, FALSE );
779 nr_arena_item_invoke_render(NULL, root, &ua, &B,
780 NR_ARENA_ITEM_RENDER_NO_CACHE );
781 nr_pixblock_release(&B);
783 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
784 if ( useOverlay ) {
785 sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
786 }
787 }
788 }
789 }
791 return px;
792 } // end of sp_icon_doc_icon()
796 struct svg_doc_cache_t
797 {
798 SPDocument *doc;
799 NRArenaItem *root;
800 };
802 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
803 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
805 Glib::ustring icon_cache_key(gchar const *name,
806 unsigned lsize, unsigned psize)
807 {
808 Glib::ustring key=name;
809 key += ":";
810 key += lsize;
811 key += ":";
812 key += psize;
813 return key;
814 }
816 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
817 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
818 if ( found != pb_cache.end() ) {
819 return found->second;
820 }
821 return NULL;
822 }
824 static guchar *load_svg_pixels(gchar const *name,
825 unsigned /*lsize*/, unsigned psize)
826 {
827 SPDocument *doc = NULL;
828 NRArenaItem *root = NULL;
829 svg_doc_cache_t *info = NULL;
831 // Fall back from user prefs dir into system locations.
832 Glib::ustring iconsvg = name;
833 iconsvg += ".svg";
834 std::list<gchar *> sources;
835 sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
836 sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
837 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
838 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
840 // Try each document in turn until we successfully load the icon from one
841 guchar *px=NULL;
842 while ( !sources.empty() && !px ) {
843 gchar *doc_filename = sources.front();
845 // Did we already load this doc?
846 Glib::ustring key(doc_filename);
847 info = 0;
848 {
849 std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
850 if ( i != doc_cache.end() ) {
851 info = i->second;
852 }
853 }
855 /* Try to load from document. */
856 if (!info &&
857 Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
858 (doc = sp_document_new( doc_filename, FALSE )) ) {
860 // prep the document
861 sp_document_ensure_up_to_date(doc);
862 /* Create new arena */
863 NRArena *arena = NRArena::create();
864 /* Create ArenaItem and set transform */
865 unsigned visionkey = sp_item_display_key_new(1);
866 /* fixme: Memory manage root if needed (Lauris) */
867 root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
868 arena, visionkey, SP_ITEM_SHOW_DISPLAY );
870 // store into the cache
871 info = new svg_doc_cache_t;
872 g_assert(info);
874 info->doc=doc;
875 info->root=root;
876 doc_cache[key]=info;
877 }
878 if (info) {
879 doc=info->doc;
880 root=info->root;
881 }
883 // toss the filename
884 g_free(doc_filename);
885 sources.pop_front();
887 // move on to the next document if we couldn't get anything
888 if (!info && !doc) continue;
890 px = sp_icon_doc_icon( doc, root, name, psize );
891 }
893 return px;
894 }
896 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
897 {
898 if ( iconSetCache.find(name) == iconSetCache.end() ) {
899 // only add a placeholder if nothing is already set
900 Gtk::IconSet icnset;
901 Gtk::IconSource src;
902 src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
903 src.set_size( Gtk::IconSize(size) );
904 icnset.add_source(src);
905 inkyIcons->add(Gtk::StockID(name), icnset);
906 }
907 }
909 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
910 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
911 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
912 GtkStockItem stock;
913 gboolean stockFound = gtk_stock_lookup( name, &stock );
914 if ( !stockFound ) {
915 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
916 if (dump) {
917 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
918 }
919 }
921 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
922 if ( it->_lsize == lsize ) {
923 if (dump) {
924 g_message(" erasing %s:%d %p", name, it->_lsize, it->_pb);
925 }
926 iconSetCache[name].erase(it);
927 break;
928 }
929 }
930 iconSetCache[name].push_back(IconCacheItem(lsize, pb));
932 Gtk::IconSet icnset;
933 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
934 Gtk::IconSource src;
935 g_object_ref( G_OBJECT(it->_pb) );
936 src.set_pixbuf( Glib::wrap(it->_pb) );
937 src.set_size( Gtk::IconSize(it->_lsize) );
938 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
939 src.set_state_wildcarded( true );
940 icnset.add_source(src);
941 }
942 inkyIcons->add(Gtk::StockID(name), icnset);
943 }
945 // returns true if icon needed preloading, false if nothing was done
946 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
947 {
948 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
949 static bool dump = prefs->getBool("/debug/icons/dumpGtk");
950 Glib::ustring key = icon_cache_key(name, lsize, psize);
951 GdkPixbuf *pb = get_cached_pixbuf(key);
952 if (pb) {
953 return false;
954 } else {
955 GtkIconTheme* theme = gtk_icon_theme_get_default();
956 if ( gtk_icon_theme_has_icon(theme, name) ) {
957 gint *sizeArray = gtk_icon_theme_get_icon_sizes( theme, name );
958 for (gint* cur = sizeArray; *cur; cur++) {
959 if (static_cast<gint>(psize) == *cur) {
960 pb = gtk_icon_theme_load_icon( theme, name, psize,
961 (GtkIconLookupFlags) 0, NULL );
962 break;
963 }
964 }
965 g_free(sizeArray);
966 sizeArray = 0;
967 }
968 if (!pb) {
969 if (dump) {
970 g_message("prerender_icon [%s] %d:%d", name, lsize, psize);
971 }
972 guchar* px = load_svg_pixels(name, lsize, psize);
973 if ( !px ) {
974 // check for a fallback name
975 if ( legacyNames.find(name) != legacyNames.end() ) {
976 if ( dump ) {
977 g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
978 }
979 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
980 }
981 }
982 if (px) {
983 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
984 psize, psize, psize * 4,
985 (GdkPixbufDestroyNotify)g_free, NULL);
986 } else if (dump) {
987 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
988 }
989 }
990 else if (dump) {
991 g_message("prerender_icon [%s] %d NOT!!!!!!", name, psize);
992 }
994 if (pb) {
995 pb_cache[key] = pb;
996 addToIconSet(pb, name, lsize, psize);
997 }
998 return true;
999 }
1000 }
1002 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1003 {
1004 Glib::ustring key = icon_cache_key(name, lsize, psize);
1006 // did we already load this icon at this scale/size?
1007 GdkPixbuf* pb = get_cached_pixbuf(key);
1008 if (!pb) {
1009 guchar *px = load_svg_pixels(name, lsize, psize);
1010 if (px) {
1011 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1012 psize, psize, psize * 4,
1013 (GdkPixbufDestroyNotify)g_free, NULL);
1014 pb_cache[key] = pb;
1015 addToIconSet(pb, name, lsize, psize);
1016 }
1017 }
1019 if ( pb ) {
1020 // increase refcount since we're handing out ownership
1021 g_object_ref(G_OBJECT(pb));
1022 }
1023 return pb;
1024 }
1026 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1027 unsigned r, unsigned g, unsigned b)
1028 {
1029 int bytesPerPixel = 4;
1030 int spacing = 4;
1031 for ( int y = 0; y < height; y += spacing ) {
1032 guchar *ptr = px + y * stride;
1033 for ( int x = 0; x < width; x += spacing ) {
1034 *(ptr++) = r;
1035 *(ptr++) = g;
1036 *(ptr++) = b;
1037 *(ptr++) = 0xff;
1039 ptr += bytesPerPixel * (spacing - 1);
1040 }
1041 }
1043 if ( width > 1 && height > 1 ) {
1044 // point at the last pixel
1045 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1047 if ( width > 2 ) {
1048 px[4] = r;
1049 px[5] = g;
1050 px[6] = b;
1051 px[7] = 0xff;
1053 ptr[-12] = r;
1054 ptr[-11] = g;
1055 ptr[-10] = b;
1056 ptr[-9] = 0xff;
1057 }
1059 ptr[-4] = r;
1060 ptr[-3] = g;
1061 ptr[-2] = b;
1062 ptr[-1] = 0xff;
1064 px[0 + stride] = r;
1065 px[1 + stride] = g;
1066 px[2 + stride] = b;
1067 px[3 + stride] = 0xff;
1069 ptr[0 - stride] = r;
1070 ptr[1 - stride] = g;
1071 ptr[2 - stride] = b;
1072 ptr[3 - stride] = 0xff;
1074 if ( height > 2 ) {
1075 ptr[0 - stride * 3] = r;
1076 ptr[1 - stride * 3] = g;
1077 ptr[2 - stride * 3] = b;
1078 ptr[3 - stride * 3] = 0xff;
1079 }
1080 }
1081 }
1083 class preRenderItem
1084 {
1085 public:
1086 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1087 _lsize( lsize ),
1088 _name( name )
1089 {}
1090 GtkIconSize _lsize;
1091 Glib::ustring _name;
1092 };
1095 static std::vector<preRenderItem> pendingRenders;
1096 static bool callbackHooked = false;
1098 static void addPreRender( GtkIconSize lsize, gchar const *name )
1099 {
1100 if ( !callbackHooked )
1101 {
1102 callbackHooked = true;
1103 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1104 }
1106 pendingRenders.push_back(preRenderItem(lsize, name));
1107 }
1109 gboolean icon_prerender_task(gpointer /*data*/) {
1110 if (!pendingRenders.empty()) {
1111 bool workDone = false;
1112 do {
1113 preRenderItem single = pendingRenders.front();
1114 pendingRenders.erase(pendingRenders.begin());
1115 int psize = sp_icon_get_phys_size(single._lsize);
1116 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1117 } while (!pendingRenders.empty() && !workDone);
1118 }
1120 if (!pendingRenders.empty()) {
1121 return TRUE;
1122 } else {
1123 callbackHooked = false;
1124 return FALSE;
1125 }
1126 }
1129 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1130 gchar* id = 0;
1131 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1132 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1133 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1134 if ( id ) {
1135 int psize = sp_icon_get_phys_size(lsize);
1136 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1137 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1138 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1139 prerender_icon(id, lsize, psize);
1140 pendingRenders.erase(it);
1141 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1142 if (lsize != size) {
1143 int psize = sp_icon_get_phys_size(size);
1144 prerender_icon(id, size, psize);
1145 }
1146 break;
1147 }
1148 }
1149 }
1151 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1152 }
1154 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1155 GtkImage* img = GTK_IMAGE(widget);
1156 gchar const* iconName = 0;
1157 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1158 gtk_image_get_icon_name(img, &iconName, &size);
1159 if ( iconName ) {
1160 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1161 if ( type == GTK_IMAGE_ICON_NAME ) {
1162 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1163 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1164 int psize = sp_icon_get_phys_size(size);
1165 prerender_icon(iconName, size, psize);
1166 pendingRenders.erase(it);
1167 break;
1168 }
1169 }
1171 } else {
1172 g_warning("UNEXPECTED TYPE of %d", (int)type);
1173 }
1174 }
1176 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1177 }
1180 /*
1181 Local Variables:
1182 mode:c++
1183 c-file-style:"stroustrup"
1184 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1185 indent-tabs-mode:nil
1186 fill-column:99
1187 End:
1188 */
1189 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :