183481cf68091b3573fbdf2729a870c1fa5e2ae1
1 /** \file
2 * SPIcon: Generic icon widget
3 */
4 /*
5 * Author:
6 * Lauris Kaplinski <lauris@kaplinski.com>
7 * Jon A. Cruz <jon@joncruz.org>
8 *
9 * Copyright (C) 2002 Lauris Kaplinski
10 *
11 * Released under GNU GPL, read the file 'COPYING' for more information
12 */
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
18 #include <cstring>
19 #include <glib/gmem.h>
20 #include <gtk/gtkiconfactory.h>
21 #include <gtk/gtkstock.h>
22 #include <gtk/gtkimage.h>
23 #include <gtkmm/iconfactory.h>
24 #include <gtkmm/iconset.h>
25 #include <gtkmm/iconsource.h>
26 #include <gtkmm/icontheme.h>
27 #include <gtkmm/image.h>
29 #include "path-prefix.h"
30 #include "prefs-utils.h"
31 #include "inkscape.h"
32 #include "document.h"
33 #include "sp-item.h"
34 #include "display/nr-arena.h"
35 #include "display/nr-arena-item.h"
36 #include "io/sys.h"
38 #include "icon.h"
40 static gboolean icon_prerender_task(gpointer data);
42 static void addPreRender( GtkIconSize lsize, gchar const *name );
44 static void sp_icon_class_init(SPIconClass *klass);
45 static void sp_icon_init(SPIcon *icon);
46 static void sp_icon_destroy(GtkObject *object);
48 static void sp_icon_reset(SPIcon *icon);
49 static void sp_icon_clear(SPIcon *icon);
51 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
52 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
53 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
55 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
57 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
58 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
59 static void sp_icon_theme_changed( SPIcon *icon );
61 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
62 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
64 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
65 unsigned r, unsigned g, unsigned b );
67 static void injectCustomSize();
69 static GtkWidgetClass *parent_class;
71 static bool sizeDirty = true;
73 static bool sizeMapDone = false;
74 static GtkIconSize iconSizeLookup[] = {
75 GTK_ICON_SIZE_INVALID,
76 GTK_ICON_SIZE_MENU,
77 GTK_ICON_SIZE_SMALL_TOOLBAR,
78 GTK_ICON_SIZE_LARGE_TOOLBAR,
79 GTK_ICON_SIZE_BUTTON,
80 GTK_ICON_SIZE_DND,
81 GTK_ICON_SIZE_DIALOG,
82 GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
83 };
85 class IconCacheItem
86 {
87 public:
88 IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
89 _lsize( lsize ),
90 _pb( pb )
91 {}
92 GtkIconSize _lsize;
93 GdkPixbuf* _pb;
94 };
96 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
97 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
99 GtkType
100 sp_icon_get_type()
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 static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
285 GtkWidget *widget = 0;
286 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
287 if ( !sizeMapDone ) {
288 injectCustomSize();
289 }
290 GtkIconSize mappedSize = iconSizeLookup[trySize];
292 GtkStockItem stock;
293 gboolean stockFound = gtk_stock_lookup( name, &stock );
295 GtkWidget *img = 0;
296 if ( legacyNames.empty() ) {
297 setupLegacyNaming();
298 }
300 bool flagMe = false;
301 if ( legacyNames.find(name) != legacyNames.end() ) {
302 img = gtk_image_new_from_icon_name( name, mappedSize );
303 flagMe = true;
304 if ( dump ) {
305 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
306 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
307 g_message(" Type is %d %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
308 }
309 } else {
310 img = gtk_image_new_from_stock( name, mappedSize );
311 }
313 if ( img ) {
314 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
315 if ( type == GTK_IMAGE_STOCK ) {
316 if ( !stockFound ) {
317 // It's not showing as a stock ID, so assume it will be present internally
318 populate_placeholder_icon( name, mappedSize );
319 addPreRender( mappedSize, name );
321 // Add a hook to render if set visible before prerender is done.
322 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
323 if ( dump ) {
324 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
325 }
326 }
327 widget = GTK_WIDGET(img);
328 img = 0;
329 if ( dump ) {
330 g_message( "loaded gtk '%s' %d (GTK_IMAGE_STOCK) %s on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
331 }
332 } else if ( type == GTK_IMAGE_ICON_NAME ) {
333 widget = GTK_WIDGET(img);
334 img = 0;
336 // Add a hook to render if set visible before prerender is done.
337 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
339 if ( prefs_get_int_attribute_limited( "options.iconrender", "named_nodelay", 0, 0, 1 ) ) {
340 int psize = sp_icon_get_phys_size(lsize);
341 prerender_icon(name, mappedSize, psize);
342 } else {
343 addPreRender( mappedSize, name );
344 }
345 } else {
346 if ( dump ) {
347 g_message( "skipped gtk '%s' %d (not GTK_IMAGE_STOCK)", name, lsize );
348 }
349 //g_object_unref( (GObject *)img );
350 img = 0;
351 }
352 }
354 if ( !widget ) {
355 //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
356 SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
357 icon->lsize = lsize;
358 icon->name = g_strdup(name);
359 icon->psize = sp_icon_get_phys_size(lsize);
361 widget = GTK_WIDGET(icon);
362 }
364 return widget;
365 }
367 GtkWidget *
368 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
369 {
370 return sp_icon_new_full( lsize, name );
371 }
373 // PUBLIC CALL:
374 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
375 {
376 Gtk::Widget *result = 0;
377 GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
379 if ( widget ) {
380 if ( GTK_IS_IMAGE(widget) ) {
381 GtkImage *img = GTK_IMAGE(widget);
382 result = Glib::wrap( img );
383 } else {
384 result = Glib::wrap( widget );
385 }
386 }
388 return result;
389 }
391 GtkIconSize
392 sp_icon_get_gtk_size(int size)
393 {
394 static GtkIconSize sizemap[64] = {(GtkIconSize)0};
395 size = CLAMP(size, 4, 63);
396 if (!sizemap[size]) {
397 static int count = 0;
398 char c[64];
399 g_snprintf(c, 64, "InkscapeIcon%d", count++);
400 sizemap[size] = gtk_icon_size_register(c, size, size);
401 }
402 return sizemap[size];
403 }
406 static void injectCustomSize()
407 {
408 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
409 if ( !sizeMapDone )
410 {
411 gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
412 gint width = 0;
413 gint height = 0;
414 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
415 gint newWidth = ((width * 3) / 4);
416 gint newHeight = ((height * 3) / 4);
417 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
418 if ( newSizeEnum ) {
419 if ( dump ) {
420 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
421 }
422 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
423 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
424 iconSizeLookup[index] = newSizeEnum;
425 } else if ( dump ) {
426 g_message("size lookup array too small to store entry");
427 }
428 }
429 }
430 sizeMapDone = true;
431 }
433 static bool hit = false;
434 if ( !hit ) {
435 hit = true;
436 inkyIcons = Gtk::IconFactory::create();
437 inkyIcons->add_default();
438 }
439 }
441 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
442 {
443 GtkIconSize other = GTK_ICON_SIZE_MENU;
444 injectCustomSize();
445 size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
446 if ( size == Inkscape::ICON_SIZE_DECORATION ) {
447 other = gtk_icon_size_from_name("inkscape-decoration");
448 } else {
449 other = static_cast<GtkIconSize>(size);
450 }
452 return other;
453 }
456 // PUBLIC CALL:
457 int sp_icon_get_phys_size(int size)
458 {
459 static bool init = false;
460 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
461 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
463 size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
465 if ( !sizeMapDone ) {
466 injectCustomSize();
467 }
469 if ( sizeDirty && init ) {
470 GtkIconSize const gtkSizes[] = {
471 GTK_ICON_SIZE_MENU,
472 GTK_ICON_SIZE_SMALL_TOOLBAR,
473 GTK_ICON_SIZE_LARGE_TOOLBAR,
474 GTK_ICON_SIZE_BUTTON,
475 GTK_ICON_SIZE_DND,
476 GTK_ICON_SIZE_DIALOG,
477 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
478 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
479 GTK_ICON_SIZE_MENU
480 };
481 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
482 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
484 g_assert( val_ix < G_N_ELEMENTS(vals) );
486 gint width = 0;
487 gint height = 0;
488 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
489 init &= (lastSys[val_ix] == std::max(width, height));
490 }
491 }
492 }
494 if ( !init ) {
495 sizeDirty = false;
496 gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
498 if ( dump ) {
499 g_message( "Default icon sizes:" );
500 }
501 memset( vals, 0, sizeof(vals) );
502 memset( lastSys, 0, sizeof(lastSys) );
503 GtkIconSize const gtkSizes[] = {
504 GTK_ICON_SIZE_MENU,
505 GTK_ICON_SIZE_SMALL_TOOLBAR,
506 GTK_ICON_SIZE_LARGE_TOOLBAR,
507 GTK_ICON_SIZE_BUTTON,
508 GTK_ICON_SIZE_DND,
509 GTK_ICON_SIZE_DIALOG,
510 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
511 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
512 GTK_ICON_SIZE_MENU
513 };
514 gchar const *const names[] = {
515 "GTK_ICON_SIZE_MENU",
516 "GTK_ICON_SIZE_SMALL_TOOLBAR",
517 "GTK_ICON_SIZE_LARGE_TOOLBAR",
518 "GTK_ICON_SIZE_BUTTON",
519 "GTK_ICON_SIZE_DND",
520 "GTK_ICON_SIZE_DIALOG",
521 "inkscape-decoration"
522 };
524 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
526 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
527 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
529 g_assert( val_ix < G_N_ELEMENTS(vals) );
531 gint width = 0;
532 gint height = 0;
533 bool used = false;
534 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
535 vals[val_ix] = std::max(width, height);
536 lastSys[val_ix] = vals[val_ix];
537 used = true;
538 }
539 if (dump) {
540 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
541 i, gtkSizes[i],
542 ( used ? ' ' : 'X' ), width, height, names[i]);
543 }
544 gchar const *id = GTK_STOCK_OPEN;
545 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
546 if (pb) {
547 width = gdk_pixbuf_get_width(pb);
548 height = gdk_pixbuf_get_height(pb);
549 int newSize = std::max( width, height );
550 // TODO perhaps check a few more stock icons to get a range on sizes.
551 if ( newSize > 0 ) {
552 vals[val_ix] = newSize;
553 }
554 if (dump) {
555 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
556 }
558 g_object_unref(G_OBJECT(pb));
559 }
560 }
561 //g_object_unref(icon);
562 init = true;
563 }
565 return vals[size];
566 }
568 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
569 {
570 GtkWidget &widget = *GTK_WIDGET(icon);
572 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
574 if (image) {
575 int const padx = ( ( widget.allocation.width > icon->psize )
576 ? ( widget.allocation.width - icon->psize ) / 2
577 : 0 );
578 int const pady = ( ( widget.allocation.height > icon->psize )
579 ? ( widget.allocation.height - icon->psize ) / 2
580 : 0 );
582 int const x0 = std::max(area->x, widget.allocation.x + padx);
583 int const y0 = std::max(area->y, widget.allocation.y + pady);
584 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
585 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
587 int width = x1 - x0;
588 int height = y1 - y0;
589 // Limit drawing to when we actually have something. Avoids some crashes.
590 if ( (width > 0) && (height > 0) ) {
591 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
592 x0 - widget.allocation.x - padx,
593 y0 - widget.allocation.y - pady,
594 x0, y0,
595 width, height,
596 GDK_RGB_DITHER_NORMAL, x0, y0);
597 }
598 }
599 }
601 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
602 {
603 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
604 // TODO: bulia, please look over
605 gsize bytesRead = 0;
606 gsize bytesWritten = 0;
607 GError *error = NULL;
608 gchar *localFilename = g_filename_from_utf8( path,
609 -1,
610 &bytesRead,
611 &bytesWritten,
612 &error);
613 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
614 g_free(localFilename);
615 g_free(path);
616 if (!pb) {
617 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
618 // TODO: bulia, please look over
619 gsize bytesRead = 0;
620 gsize bytesWritten = 0;
621 GError *error = NULL;
622 gchar *localFilename = g_filename_from_utf8( path,
623 -1,
624 &bytesRead,
625 &bytesWritten,
626 &error);
627 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
628 g_free(localFilename);
629 g_free(path);
630 }
632 if (pb) {
633 if (!gdk_pixbuf_get_has_alpha(pb)) {
634 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
635 }
637 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
638 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
639 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
640 g_object_unref(G_OBJECT(pb));
641 pb = spb;
642 }
643 }
645 return pb;
646 }
648 // takes doc, root, icon, and icon name to produce pixels
649 extern "C" guchar *
650 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
651 gchar const *name, unsigned psize )
652 {
653 gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
654 guchar *px = NULL;
656 if (doc) {
657 SPObject *object = doc->getObjectById(name);
658 if (object && SP_IS_ITEM(object)) {
659 /* Find bbox in document */
660 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
661 boost::optional<NR::Rect> nrdbox = SP_ITEM(object)->getBounds(i2doc);
662 boost::optional<Geom::Rect> dbox;
663 if (nrdbox) {
664 dbox = to_2geom(*nrdbox);
665 }
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 && !dbox->isEmpty() ) {
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.set_identity();
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.set_identity();
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 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
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 static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
898 GtkStockItem stock;
899 gboolean stockFound = gtk_stock_lookup( name, &stock );
900 if ( !stockFound ) {
901 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
902 if (dump) {
903 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
904 }
905 }
907 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
908 if ( it->_lsize == lsize ) {
909 iconSetCache[name].erase(it);
910 break;
911 }
912 }
913 iconSetCache[name].push_back(IconCacheItem(lsize, pb));
915 Gtk::IconSet icnset;
916 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
917 Gtk::IconSource src;
918 g_object_ref( G_OBJECT(it->_pb) );
919 src.set_pixbuf( Glib::wrap(it->_pb) );
920 src.set_size( Gtk::IconSize(it->_lsize) );
921 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
922 src.set_state_wildcarded( true );
923 icnset.add_source(src);
924 }
925 inkyIcons->add(Gtk::StockID(name), icnset);
926 }
928 // returns true if icon needed preloading, false if nothing was done
929 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
930 {
931 static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
932 Glib::ustring key = icon_cache_key(name, lsize, psize);
933 GdkPixbuf *pb = get_cached_pixbuf(key);
934 if (pb) {
935 return false;
936 } else {
937 guchar* px = load_svg_pixels(name, lsize, psize);
938 if ( !px ) {
939 // check for a fallback name
940 if ( legacyNames.find(name) != legacyNames.end() ) {
941 if ( dump ) {
942 g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
943 }
944 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
945 }
946 }
948 if (px) {
949 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
950 psize, psize, psize * 4,
951 (GdkPixbufDestroyNotify)g_free, NULL);
952 pb_cache[key] = pb;
953 addToIconSet(pb, name, lsize, psize);
954 } else if (dump) {
955 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
956 }
957 return true;
958 }
959 }
961 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
962 {
963 Glib::ustring key = icon_cache_key(name, lsize, psize);
965 // did we already load this icon at this scale/size?
966 GdkPixbuf* pb = get_cached_pixbuf(key);
967 if (!pb) {
968 guchar *px = load_svg_pixels(name, lsize, psize);
969 if (px) {
970 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
971 psize, psize, psize * 4,
972 (GdkPixbufDestroyNotify)g_free, NULL);
973 pb_cache[key] = pb;
974 addToIconSet(pb, name, lsize, psize);
975 }
976 }
978 if ( pb ) {
979 // increase refcount since we're handing out ownership
980 g_object_ref(G_OBJECT(pb));
981 }
982 return pb;
983 }
985 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
986 unsigned r, unsigned g, unsigned b)
987 {
988 for ( int y = 0; y < height; y += 4 ) {
989 guchar *ptr = px + y * stride;
990 for ( int x = 0; x < width; x += 4 ) {
991 *(ptr++) = r;
992 *(ptr++) = g;
993 *(ptr++) = b;
994 *(ptr++) = 0xff;
996 ptr += 4 * 3;
997 }
998 }
1000 if ( width > 1 && height > 1 ) {
1001 // point at the last pixel
1002 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
1004 if ( width > 2 ) {
1005 px[4] = r;
1006 px[5] = g;
1007 px[6] = b;
1008 px[7] = 0xff;
1010 ptr[-12] = r;
1011 ptr[-11] = g;
1012 ptr[-10] = b;
1013 ptr[-9] = 0xff;
1014 }
1016 ptr[-4] = r;
1017 ptr[-3] = g;
1018 ptr[-2] = b;
1019 ptr[-1] = 0xff;
1021 px[0 + stride] = r;
1022 px[1 + stride] = g;
1023 px[2 + stride] = b;
1024 px[3 + stride] = 0xff;
1026 ptr[0 - stride] = r;
1027 ptr[1 - stride] = g;
1028 ptr[2 - stride] = b;
1029 ptr[3 - stride] = 0xff;
1031 if ( height > 2 ) {
1032 ptr[0 - stride * 3] = r;
1033 ptr[1 - stride * 3] = g;
1034 ptr[2 - stride * 3] = b;
1035 ptr[3 - stride * 3] = 0xff;
1036 }
1037 }
1038 }
1040 class preRenderItem
1041 {
1042 public:
1043 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1044 _lsize( lsize ),
1045 _name( name )
1046 {}
1047 GtkIconSize _lsize;
1048 Glib::ustring _name;
1049 };
1052 static std::vector<preRenderItem> pendingRenders;
1053 static bool callbackHooked = false;
1055 static void addPreRender( GtkIconSize lsize, gchar const *name )
1056 {
1057 if ( !callbackHooked )
1058 {
1059 callbackHooked = true;
1060 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1061 }
1063 pendingRenders.push_back(preRenderItem(lsize, name));
1064 }
1066 gboolean icon_prerender_task(gpointer /*data*/) {
1067 if (!pendingRenders.empty()) {
1068 bool workDone = false;
1069 do {
1070 preRenderItem single = pendingRenders.front();
1071 pendingRenders.erase(pendingRenders.begin());
1072 int psize = sp_icon_get_phys_size(single._lsize);
1073 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1074 } while (!pendingRenders.empty() && !workDone);
1075 }
1077 if (!pendingRenders.empty()) {
1078 return TRUE;
1079 } else {
1080 callbackHooked = false;
1081 return FALSE;
1082 }
1083 }
1086 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1087 gchar* id = 0;
1088 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1089 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1090 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1091 if ( id ) {
1092 int psize = sp_icon_get_phys_size(lsize);
1093 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1094 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1095 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1096 prerender_icon(id, lsize, psize);
1097 pendingRenders.erase(it);
1098 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1099 if (lsize != size) {
1100 int psize = sp_icon_get_phys_size(size);
1101 prerender_icon(id, size, psize);
1102 }
1103 break;
1104 }
1105 }
1106 }
1108 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1109 }
1111 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1112 GtkImage* img = GTK_IMAGE(widget);
1113 gchar const* iconName = 0;
1114 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1115 gtk_image_get_icon_name(img, &iconName, &size);
1116 if ( iconName ) {
1117 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1118 if ( type == GTK_IMAGE_ICON_NAME ) {
1119 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1120 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1121 int psize = sp_icon_get_phys_size(size);
1122 prerender_icon(iconName, size, psize);
1123 pendingRenders.erase(it);
1124 break;
1125 }
1126 }
1128 } else {
1129 g_warning("UNEXPECTED TYPE of %d", (int)type);
1130 }
1131 }
1133 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1134 }
1137 /*
1138 Local Variables:
1139 mode:c++
1140 c-file-style:"stroustrup"
1141 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1142 indent-tabs-mode:nil
1143 fill-column:99
1144 End:
1145 */
1146 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :