f9e4bf94172ba58acddd7824ae02d98b37d43292
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( Inkscape::IconSize 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, unsigned 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( Inkscape::IconSize lsize, GdkPixbuf* pb ) :
89 _lsize( lsize ),
90 _pb( pb )
91 {}
92 Inkscape::IconSize _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, 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, unsigned lsize);
268 static bool prerender_icon(gchar const *name, unsigned 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) );
288 if ( !sizeMapDone ) {
289 injectCustomSize();
290 }
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, iconSizeLookup[trySize] );
303 flagMe = true;
304 if ( dump ) {
305 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, iconSizeLookup[trySize], 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, iconSizeLookup[trySize] );
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, lsize );
319 addPreRender( lsize, 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>(lsize)) );
323 if ( dump ) {
324 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)lsize);
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, lsize, (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, lsize, psize);
342 } else {
343 addPreRender( lsize, 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( 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 }
405 static void injectCustomSize()
406 {
407 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
408 if ( !sizeMapDone )
409 {
410 gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
411 gint width = 0;
412 gint height = 0;
413 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
414 gint newWidth = ((width * 3) / 4);
415 gint newHeight = ((height * 3) / 4);
416 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
417 if ( newSizeEnum ) {
418 if ( dump ) {
419 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
420 }
421 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
422 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
423 iconSizeLookup[index] = newSizeEnum;
424 } else if ( dump ) {
425 g_message("size lookup array too small to store entry");
426 }
427 }
428 }
429 sizeMapDone = true;
430 }
432 static bool hit = false;
433 if ( !hit ) {
434 hit = true;
435 inkyIcons = Gtk::IconFactory::create();
436 inkyIcons->add_default();
437 }
438 }
440 // PUBLIC CALL:
441 int sp_icon_get_phys_size(int size)
442 {
443 static bool init = false;
444 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
445 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
447 size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
449 if ( !sizeMapDone ) {
450 injectCustomSize();
451 }
453 if ( sizeDirty && init ) {
454 GtkIconSize const gtkSizes[] = {
455 GTK_ICON_SIZE_MENU,
456 GTK_ICON_SIZE_SMALL_TOOLBAR,
457 GTK_ICON_SIZE_LARGE_TOOLBAR,
458 GTK_ICON_SIZE_BUTTON,
459 GTK_ICON_SIZE_DND,
460 GTK_ICON_SIZE_DIALOG,
461 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
462 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
463 GTK_ICON_SIZE_MENU
464 };
465 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
466 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
468 g_assert( val_ix < G_N_ELEMENTS(vals) );
470 gint width = 0;
471 gint height = 0;
472 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
473 init &= (lastSys[val_ix] == std::max(width, height));
474 }
475 }
476 }
478 if ( !init ) {
479 sizeDirty = false;
480 gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
482 if ( dump ) {
483 g_message( "Default icon sizes:" );
484 }
485 memset( vals, 0, sizeof(vals) );
486 memset( lastSys, 0, sizeof(lastSys) );
487 GtkIconSize const gtkSizes[] = {
488 GTK_ICON_SIZE_MENU,
489 GTK_ICON_SIZE_SMALL_TOOLBAR,
490 GTK_ICON_SIZE_LARGE_TOOLBAR,
491 GTK_ICON_SIZE_BUTTON,
492 GTK_ICON_SIZE_DND,
493 GTK_ICON_SIZE_DIALOG,
494 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
495 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
496 GTK_ICON_SIZE_MENU
497 };
498 gchar const *const names[] = {
499 "GTK_ICON_SIZE_MENU",
500 "GTK_ICON_SIZE_SMALL_TOOLBAR",
501 "GTK_ICON_SIZE_LARGE_TOOLBAR",
502 "GTK_ICON_SIZE_BUTTON",
503 "GTK_ICON_SIZE_DND",
504 "GTK_ICON_SIZE_DIALOG",
505 "inkscape-decoration"
506 };
508 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
510 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
511 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
513 g_assert( val_ix < G_N_ELEMENTS(vals) );
515 gint width = 0;
516 gint height = 0;
517 bool used = false;
518 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
519 vals[val_ix] = std::max(width, height);
520 lastSys[val_ix] = vals[val_ix];
521 used = true;
522 }
523 if (dump) {
524 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
525 i, gtkSizes[i],
526 ( used ? ' ' : 'X' ), width, height, names[i]);
527 }
528 gchar const *id = GTK_STOCK_OPEN;
529 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
530 if (pb) {
531 width = gdk_pixbuf_get_width(pb);
532 height = gdk_pixbuf_get_height(pb);
533 int newSize = std::max( width, height );
534 // TODO perhaps check a few more stock icons to get a range on sizes.
535 if ( newSize > 0 ) {
536 vals[val_ix] = newSize;
537 }
538 if (dump) {
539 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
540 }
542 g_object_unref(G_OBJECT(pb));
543 }
544 }
545 //g_object_unref(icon);
546 init = true;
547 }
549 return vals[size];
550 }
552 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
553 {
554 GtkWidget &widget = *GTK_WIDGET(icon);
556 GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
558 if (image) {
559 int const padx = ( ( widget.allocation.width > icon->psize )
560 ? ( widget.allocation.width - icon->psize ) / 2
561 : 0 );
562 int const pady = ( ( widget.allocation.height > icon->psize )
563 ? ( widget.allocation.height - icon->psize ) / 2
564 : 0 );
566 int const x0 = std::max(area->x, widget.allocation.x + padx);
567 int const y0 = std::max(area->y, widget.allocation.y + pady);
568 int const x1 = std::min(area->x + area->width, widget.allocation.x + padx + static_cast<int>(icon->psize) );
569 int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
571 int width = x1 - x0;
572 int height = y1 - y0;
573 // Limit drawing to when we actually have something. Avoids some crashes.
574 if ( (width > 0) && (height > 0) ) {
575 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
576 x0 - widget.allocation.x - padx,
577 y0 - widget.allocation.y - pady,
578 x0, y0,
579 width, height,
580 GDK_RGB_DITHER_NORMAL, x0, y0);
581 }
582 }
583 }
585 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
586 {
587 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
588 // TODO: bulia, please look over
589 gsize bytesRead = 0;
590 gsize bytesWritten = 0;
591 GError *error = NULL;
592 gchar *localFilename = g_filename_from_utf8( path,
593 -1,
594 &bytesRead,
595 &bytesWritten,
596 &error);
597 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
598 g_free(localFilename);
599 g_free(path);
600 if (!pb) {
601 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
602 // TODO: bulia, please look over
603 gsize bytesRead = 0;
604 gsize bytesWritten = 0;
605 GError *error = NULL;
606 gchar *localFilename = g_filename_from_utf8( path,
607 -1,
608 &bytesRead,
609 &bytesWritten,
610 &error);
611 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
612 g_free(localFilename);
613 g_free(path);
614 }
616 if (pb) {
617 if (!gdk_pixbuf_get_has_alpha(pb)) {
618 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
619 }
621 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
622 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
623 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
624 g_object_unref(G_OBJECT(pb));
625 pb = spb;
626 }
627 }
629 return pb;
630 }
632 // takes doc, root, icon, and icon name to produce pixels
633 extern "C" guchar *
634 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
635 gchar const *name, unsigned psize )
636 {
637 gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
638 guchar *px = NULL;
640 if (doc) {
641 SPObject *object = doc->getObjectById(name);
642 if (object && SP_IS_ITEM(object)) {
643 /* Find bbox in document */
644 Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
645 boost::optional<NR::Rect> nrdbox = SP_ITEM(object)->getBounds(i2doc);
646 boost::optional<Geom::Rect> dbox;
647 if (nrdbox) {
648 dbox = to_2geom(*nrdbox);
649 }
651 if ( SP_OBJECT_PARENT(object) == NULL )
652 {
653 dbox = Geom::Rect(Geom::Point(0, 0),
654 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
655 }
657 /* This is in document coordinates, i.e. pixels */
658 if ( dbox && !dbox->isEmpty() ) {
659 NRGC gc(NULL);
660 /* Update to renderable state */
661 double sf = 1.0;
662 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
663 gc.transform.set_identity();
664 nr_arena_item_invoke_update( root, NULL, &gc,
665 NR_ARENA_ITEM_STATE_ALL,
666 NR_ARENA_ITEM_STATE_NONE );
667 /* Item integer bbox in points */
668 NRRectL ibox;
669 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
670 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
671 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
672 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
674 if ( dump ) {
675 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
676 }
678 /* Find button visible area */
679 int width = ibox.x1 - ibox.x0;
680 int height = ibox.y1 - ibox.y0;
682 if ( dump ) {
683 g_message( " vis --'%s' (%d,%d)", name, width, height );
684 }
686 {
687 int block = std::max(width, height);
688 if (block != static_cast<int>(psize) ) {
689 if ( dump ) {
690 g_message(" resizing" );
691 }
692 sf = (double)psize / (double)block;
694 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
695 gc.transform.set_identity();
696 nr_arena_item_invoke_update( root, NULL, &gc,
697 NR_ARENA_ITEM_STATE_ALL,
698 NR_ARENA_ITEM_STATE_NONE );
699 /* Item integer bbox in points */
700 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
701 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
702 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
703 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
705 if ( dump ) {
706 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
707 }
709 /* Find button visible area */
710 width = ibox.x1 - ibox.x0;
711 height = ibox.y1 - ibox.y0;
712 if ( dump ) {
713 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
714 }
715 }
716 }
718 int dx, dy;
719 //dx = (psize - width) / 2;
720 //dy = (psize - height) / 2;
721 dx=dy=psize;
722 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
723 dy=(dy-height)/2;
724 NRRectL area;
725 area.x0 = ibox.x0 - dx;
726 area.y0 = ibox.y0 - dy;
727 area.x1 = area.x0 + psize;
728 area.y1 = area.y0 + psize;
729 /* Actual renderable area */
730 NRRectL ua;
731 ua.x0 = MAX(ibox.x0, area.x0);
732 ua.y0 = MAX(ibox.y0, area.y0);
733 ua.x1 = MIN(ibox.x1, area.x1);
734 ua.y1 = MIN(ibox.y1, area.y1);
736 if ( dump ) {
737 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
738 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
739 }
740 /* Set up pixblock */
741 px = g_new(guchar, 4 * psize * psize);
742 memset(px, 0x00, 4 * psize * psize);
743 /* Render */
744 NRPixBlock B;
745 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
746 ua.x0, ua.y0, ua.x1, ua.y1,
747 px + 4 * psize * (ua.y0 - area.y0) +
748 4 * (ua.x0 - area.x0),
749 4 * psize, FALSE, FALSE );
750 nr_arena_item_invoke_render(NULL, root, &ua, &B,
751 NR_ARENA_ITEM_RENDER_NO_CACHE );
752 nr_pixblock_release(&B);
754 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
755 if ( useOverlay ) {
756 sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
757 }
758 }
759 }
760 }
762 return px;
763 } // end of sp_icon_doc_icon()
767 struct svg_doc_cache_t
768 {
769 SPDocument *doc;
770 NRArenaItem *root;
771 };
773 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
774 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
776 Glib::ustring icon_cache_key(gchar const *name,
777 unsigned lsize, unsigned psize)
778 {
779 Glib::ustring key=name;
780 key += ":";
781 key += lsize;
782 key += ":";
783 key += psize;
784 return key;
785 }
787 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
788 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
789 if ( found != pb_cache.end() ) {
790 return found->second;
791 }
792 return NULL;
793 }
795 static guchar *load_svg_pixels(gchar const *name,
796 unsigned /*lsize*/, unsigned psize)
797 {
798 SPDocument *doc = NULL;
799 NRArenaItem *root = NULL;
800 svg_doc_cache_t *info = NULL;
802 // Fall back from user prefs dir into system locations.
803 Glib::ustring iconsvg = name;
804 iconsvg += ".svg";
805 std::list<gchar *> sources;
806 sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
807 sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
808 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
809 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
811 // Try each document in turn until we successfully load the icon from one
812 guchar *px=NULL;
813 while ( !sources.empty() && !px ) {
814 gchar *doc_filename = sources.front();
816 // Did we already load this doc?
817 Glib::ustring key(doc_filename);
818 info = 0;
819 {
820 std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
821 if ( i != doc_cache.end() ) {
822 info = i->second;
823 }
824 }
826 /* Try to load from document. */
827 if (!info &&
828 Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
829 (doc = sp_document_new( doc_filename, FALSE )) ) {
831 // prep the document
832 sp_document_ensure_up_to_date(doc);
833 /* Create new arena */
834 NRArena *arena = NRArena::create();
835 /* Create ArenaItem and set transform */
836 unsigned visionkey = sp_item_display_key_new(1);
837 /* fixme: Memory manage root if needed (Lauris) */
838 root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
839 arena, visionkey, SP_ITEM_SHOW_DISPLAY );
841 // store into the cache
842 info = new svg_doc_cache_t;
843 g_assert(info);
845 info->doc=doc;
846 info->root=root;
847 doc_cache[key]=info;
848 }
849 if (info) {
850 doc=info->doc;
851 root=info->root;
852 }
854 // toss the filename
855 g_free(doc_filename);
856 sources.pop_front();
858 // move on to the next document if we couldn't get anything
859 if (!info && !doc) continue;
861 px = sp_icon_doc_icon( doc, root, name, psize );
862 }
864 return px;
865 }
867 static void populate_placeholder_icon(gchar const* name, unsigned lsize)
868 {
869 if ( iconSetCache.find(name) == iconSetCache.end() ) {
870 // only add a placeholder if nothing is already set
871 Gtk::IconSet icnset;
872 Gtk::IconSource src;
873 src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
874 src.set_size( Gtk::IconSize(lsize) );
875 icnset.add_source(src);
876 inkyIcons->add(Gtk::StockID(name), icnset);
877 }
878 }
880 static void addToIconSet(GdkPixbuf* pb, gchar const* name, unsigned lsize, unsigned psize) {
881 static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
882 GtkStockItem stock;
883 gboolean stockFound = gtk_stock_lookup( name, &stock );
884 if ( !stockFound ) {
885 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
886 if (dump) {
887 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
888 }
889 }
891 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
892 if ( it->_lsize == Inkscape::IconSize(lsize) ) {
893 iconSetCache[name].erase(it);
894 break;
895 }
896 }
897 iconSetCache[name].push_back(IconCacheItem(Inkscape::IconSize(lsize), pb));
899 Gtk::IconSet icnset;
900 for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
901 Gtk::IconSource src;
902 g_object_ref( G_OBJECT(it->_pb) );
903 src.set_pixbuf( Glib::wrap(it->_pb) );
904 src.set_size( Gtk::IconSize(it->_lsize) );
905 src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
906 src.set_state_wildcarded( true );
907 icnset.add_source(src);
908 }
909 inkyIcons->add(Gtk::StockID(name), icnset);
910 }
912 // returns true if icon needed preloading, false if nothing was done
913 bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
914 {
915 static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
916 Glib::ustring key = icon_cache_key(name, lsize, psize);
917 GdkPixbuf *pb = get_cached_pixbuf(key);
918 if (pb) {
919 return false;
920 } else {
921 guchar* px = load_svg_pixels(name, lsize, psize);
922 if ( !px ) {
923 // check for a fallback name
924 if ( legacyNames.find(name) != legacyNames.end() ) {
925 if ( dump ) {
926 g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
927 }
928 px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
929 }
930 }
932 if (px) {
933 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
934 psize, psize, psize * 4,
935 (GdkPixbufDestroyNotify)g_free, NULL);
936 pb_cache[key] = pb;
937 addToIconSet(pb, name, lsize, psize);
938 } else if (dump) {
939 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
940 }
941 return true;
942 }
943 }
945 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
946 {
947 Glib::ustring key = icon_cache_key(name, lsize, psize);
949 // did we already load this icon at this scale/size?
950 GdkPixbuf* pb = get_cached_pixbuf(key);
951 if (!pb) {
952 guchar *px = load_svg_pixels(name, lsize, psize);
953 if (px) {
954 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
955 psize, psize, psize * 4,
956 (GdkPixbufDestroyNotify)g_free, NULL);
957 pb_cache[key] = pb;
958 addToIconSet(pb, name, lsize, psize);
959 }
960 }
962 if ( pb ) {
963 // increase refcount since we're handing out ownership
964 g_object_ref(G_OBJECT(pb));
965 }
966 return pb;
967 }
969 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
970 unsigned r, unsigned g, unsigned b)
971 {
972 for ( int y = 0; y < height; y += 4 ) {
973 guchar *ptr = px + y * stride;
974 for ( int x = 0; x < width; x += 4 ) {
975 *(ptr++) = r;
976 *(ptr++) = g;
977 *(ptr++) = b;
978 *(ptr++) = 0xff;
980 ptr += 4 * 3;
981 }
982 }
984 if ( width > 1 && height > 1 ) {
985 // point at the last pixel
986 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
988 if ( width > 2 ) {
989 px[4] = r;
990 px[5] = g;
991 px[6] = b;
992 px[7] = 0xff;
994 ptr[-12] = r;
995 ptr[-11] = g;
996 ptr[-10] = b;
997 ptr[-9] = 0xff;
998 }
1000 ptr[-4] = r;
1001 ptr[-3] = g;
1002 ptr[-2] = b;
1003 ptr[-1] = 0xff;
1005 px[0 + stride] = r;
1006 px[1 + stride] = g;
1007 px[2 + stride] = b;
1008 px[3 + stride] = 0xff;
1010 ptr[0 - stride] = r;
1011 ptr[1 - stride] = g;
1012 ptr[2 - stride] = b;
1013 ptr[3 - stride] = 0xff;
1015 if ( height > 2 ) {
1016 ptr[0 - stride * 3] = r;
1017 ptr[1 - stride * 3] = g;
1018 ptr[2 - stride * 3] = b;
1019 ptr[3 - stride * 3] = 0xff;
1020 }
1021 }
1022 }
1024 class preRenderItem
1025 {
1026 public:
1027 preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
1028 _lsize( lsize ),
1029 _name( name )
1030 {}
1031 Inkscape::IconSize _lsize;
1032 Glib::ustring _name;
1033 };
1036 static std::vector<preRenderItem> pendingRenders;
1037 static bool callbackHooked = false;
1039 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
1040 {
1041 if ( !callbackHooked )
1042 {
1043 callbackHooked = true;
1044 g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1045 }
1047 pendingRenders.push_back(preRenderItem(lsize, name));
1048 }
1050 gboolean icon_prerender_task(gpointer /*data*/) {
1051 if (!pendingRenders.empty()) {
1052 bool workDone = false;
1053 do {
1054 preRenderItem single = pendingRenders.front();
1055 pendingRenders.erase(pendingRenders.begin());
1056 int psize = sp_icon_get_phys_size(single._lsize);
1057 workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1058 } while (!pendingRenders.empty() && !workDone);
1059 }
1061 if (!pendingRenders.empty()) {
1062 return TRUE;
1063 } else {
1064 callbackHooked = false;
1065 return FALSE;
1066 }
1067 }
1070 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1071 gchar* id = 0;
1072 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1073 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1074 int lsize = GPOINTER_TO_INT(user_data);
1075 if ( id ) {
1076 int psize = sp_icon_get_phys_size(lsize);
1077 //g_message("imageMapCB(%p) for %s:%d:%d", widget, id, lsize, psize);
1078 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1079 if ( (it->_name == id) && (it->_lsize == static_cast<Inkscape::IconSize>(lsize)) ) {
1080 prerender_icon(id, lsize, psize);
1081 pendingRenders.erase(it);
1082 //g_message(" prerender for %s:%d:%d", id, lsize, psize);
1083 break;
1084 }
1085 }
1086 }
1088 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1089 }
1091 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1092 GtkImage* img = GTK_IMAGE(widget);
1093 gchar const* iconName = 0;
1094 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1095 gtk_image_get_icon_name(img, &iconName, &size);
1096 if ( iconName ) {
1097 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1098 if ( type == GTK_IMAGE_ICON_NAME ) {
1099 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1100 if ( (it->_name == iconName) && (it->_lsize == static_cast<Inkscape::IconSize>(size)) ) {
1101 int psize = sp_icon_get_phys_size(size);
1102 prerender_icon(iconName, size, psize);
1103 pendingRenders.erase(it);
1104 break;
1105 }
1106 }
1108 } else {
1109 g_warning("UNEXPECTED TYPE of %d", (int)type);
1110 }
1111 }
1113 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1114 }
1117 /*
1118 Local Variables:
1119 mode:c++
1120 c-file-style:"stroustrup"
1121 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1122 indent-tabs-mode:nil
1123 fill-column:99
1124 End:
1125 */
1126 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :