Code

Refactoring to be able to use standard themeable icons
[inkscape.git] / src / widgets / icon.cpp
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/image.h>
28 #include "path-prefix.h"
29 #include "prefs-utils.h"
30 #include "inkscape.h"
31 #include "document.h"
32 #include "sp-item.h"
33 #include "display/nr-arena.h"
34 #include "display/nr-arena-item.h"
35 #include "io/sys.h"
37 #include "icon.h"
39 static gboolean icon_prerender_task(gpointer data);
41 static void addPreRender( Inkscape::IconSize lsize, gchar const *name );
43 static void sp_icon_class_init(SPIconClass *klass);
44 static void sp_icon_init(SPIcon *icon);
45 static void sp_icon_destroy(GtkObject *object);
47 static void sp_icon_reset(SPIcon *icon);
48 static void sp_icon_clear(SPIcon *icon);
50 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
51 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
52 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
54 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
56 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
57 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
58 static void sp_icon_theme_changed( SPIcon *icon );
60 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
61 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize);
63 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
64                                     unsigned r, unsigned g, unsigned b );
66 static void injectCustomSize();
68 static GtkWidgetClass *parent_class;
70 static bool sizeDirty = true;
72 static bool sizeMapDone = false;
73 static GtkIconSize iconSizeLookup[] = {
74     GTK_ICON_SIZE_INVALID,
75     GTK_ICON_SIZE_MENU,
76     GTK_ICON_SIZE_SMALL_TOOLBAR,
77     GTK_ICON_SIZE_LARGE_TOOLBAR,
78     GTK_ICON_SIZE_BUTTON,
79     GTK_ICON_SIZE_DND,
80     GTK_ICON_SIZE_DIALOG,
81     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
82 };
84 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
85 static std::map<Glib::ustring, Gtk::IconSet *> iconSetCache;
88 GtkType
89 sp_icon_get_type()
90 {
91     static GtkType type = 0;
92     if (!type) {
93         GtkTypeInfo info = {
94             "SPIcon",
95             sizeof(SPIcon),
96             sizeof(SPIconClass),
97             (GtkClassInitFunc) sp_icon_class_init,
98             (GtkObjectInitFunc) sp_icon_init,
99             NULL, NULL, NULL
100         };
101         type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
102     }
103     return type;
106 static void
107 sp_icon_class_init(SPIconClass *klass)
109     GtkObjectClass *object_class;
110     GtkWidgetClass *widget_class;
112     object_class = (GtkObjectClass *) klass;
113     widget_class = (GtkWidgetClass *) klass;
115     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
117     object_class->destroy = sp_icon_destroy;
119     widget_class->size_request = sp_icon_size_request;
120     widget_class->size_allocate = sp_icon_size_allocate;
121     widget_class->expose_event = sp_icon_expose;
122     widget_class->screen_changed = sp_icon_screen_changed;
123     widget_class->style_set = sp_icon_style_set;
127 static void
128 sp_icon_init(SPIcon *icon)
130     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
131     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
132     icon->psize = 0;
133     icon->name = 0;
134     icon->pb = 0;
135     icon->pb_faded = 0;
138 static void
139 sp_icon_destroy(GtkObject *object)
141     SPIcon *icon = SP_ICON(object);
142     sp_icon_clear(icon);
143     if ( icon->name ) {
144         g_free( icon->name );
145         icon->name = 0;
146     }
148     ((GtkObjectClass *) (parent_class))->destroy(object);
151 static void sp_icon_reset( SPIcon *icon ) {
152     icon->psize = 0;
153     sp_icon_clear(icon);
156 static void sp_icon_clear( SPIcon *icon ) {
157     if (icon->pb) {
158         g_object_unref(G_OBJECT(icon->pb));
159         icon->pb = NULL;
160     }
161     if (icon->pb_faded) {
162         g_object_unref(G_OBJECT(icon->pb_faded));
163         icon->pb_faded = NULL;
164     }
167 static void
168 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
170     SPIcon const *icon = SP_ICON(widget);
172     int const size = ( icon->psize
173                        ? icon->psize
174                        : sp_icon_get_phys_size(icon->lsize) );
175     requisition->width = size;
176     requisition->height = size;
179 static void
180 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
182     widget->allocation = *allocation;
184     if (GTK_WIDGET_DRAWABLE(widget)) {
185         gtk_widget_queue_draw(widget);
186     }
189 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
191     if ( GTK_WIDGET_DRAWABLE(widget) ) {
192         SPIcon *icon = SP_ICON(widget);
193         if ( !icon->pb ) {
194             sp_icon_fetch_pixbuf( icon );
195         }
197         sp_icon_paint(SP_ICON(widget), &event->area);
198     }
200     return TRUE;
203 // PUBLIC CALL:
204 void sp_icon_fetch_pixbuf( SPIcon *icon )
206     if ( icon ) {
207         if ( !icon->pb ) {
208             icon->psize = sp_icon_get_phys_size(icon->lsize);
210             GdkPixbuf *pb = sp_icon_image_load_svg( icon->name, icon->lsize, icon->psize );
211             if (!pb) {
212                 pb = sp_icon_image_load_pixmap( icon->name, icon->lsize, icon->psize );
213             }
215             if ( pb ) {
216                 icon->pb = pb;
217                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
218                 gdk_pixbuf_saturate_and_pixelate(icon->pb, icon->pb_faded, 0.5, TRUE);
219             } else {
220                 /* TODO: We should do something more useful if we can't load the image. */
221                 g_warning ("failed to load icon '%s'", icon->name);
222             }
223         }
224     }
227 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
229     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
230         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
231     }
232     SPIcon *icon = SP_ICON(widget);
233     sp_icon_theme_changed(icon);
236 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
238     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
239         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
240     }
241     SPIcon *icon = SP_ICON(widget);
242     sp_icon_theme_changed(icon);
245 static void sp_icon_theme_changed( SPIcon *icon )
247     //g_message("Got a change bump for this icon");
248     sizeDirty = true;
249     sp_icon_reset(icon);
250     gtk_widget_queue_draw( GTK_WIDGET(icon) );
254 static GtkWidget *
255 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
257     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
258     static gint fallback = prefs_get_int_attribute_limited( "debug.icons", "checkNames", 0, 0, 1 );
260     addPreRender( lsize, name );
262     GtkStockItem stock;
263     gboolean tryLoad = gtk_stock_lookup( name, &stock );
264     if ( !tryLoad && fallback ) {
265         tryLoad |= strncmp("gtk-", name, 4 ) == 0;
266     }
267     if ( !tryLoad && fallback ) {
268         tryLoad |= strncmp("gnome-", name, 6 ) == 0;
269     }
271     GtkWidget *widget = 0;
272     if ( tryLoad ) {
273         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
275         if ( !sizeMapDone ) {
276             injectCustomSize();
277         }
279         GtkWidget *img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
280         if ( img ) {
281             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
282             if ( type == GTK_IMAGE_STOCK ) {
283                 widget = GTK_WIDGET(img);
284                 img = 0;
286                 if ( dump ) {
287                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK)", name, lsize );
288                 }
289             } else {
290                 if ( dump ) {
291                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
292                 }
293                 g_object_unref( (GObject *)img );
294                 img = 0;
295             }
296         }
297     }
299     if ( !widget ) {
300         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
301         icon->lsize = lsize;
302         icon->name = g_strdup(name);
303         icon->psize = sp_icon_get_phys_size(lsize);
305         widget = GTK_WIDGET(icon);
306     }
308     return widget;
311 GtkWidget *
312 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
314     return sp_icon_new_full( lsize, name );
317 // PUBLIC CALL:
318 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
320     Gtk::Widget *result = 0;
321     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
323     if ( widget ) {
324         if ( GTK_IS_IMAGE(widget) ) {
325             GtkImage *img = GTK_IMAGE(widget);
326             result = Glib::wrap( img );
327         } else {
328             result = Glib::wrap( widget );
329         }
330     }
332     return result;
335 GtkIconSize
336 sp_icon_get_gtk_size(int size)
338     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
339     size = CLAMP(size, 4, 63);
340     if (!sizemap[size]) {
341         static int count = 0;
342         char c[64];
343         g_snprintf(c, 64, "InkscapeIcon%d", count++);
344         sizemap[size] = gtk_icon_size_register(c, size, size);
345     }
346     return sizemap[size];
349 static void injectCustomSize()
351     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
352     if ( !sizeMapDone )
353     {
354         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
355         gint width = 0;
356         gint height = 0;
357         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
358             gint newWidth = ((width * 3) / 4);
359             gint newHeight = ((height * 3) / 4);
360             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
361             if ( newSizeEnum ) {
362                 if ( dump ) {
363                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
364                 }
365                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
366                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
367                     iconSizeLookup[index] = newSizeEnum;
368                 } else if ( dump ) {
369                     g_message("size lookup array too small to store entry");
370                 }
371             }
372         }
373         sizeMapDone = true;
374     }
376     static bool hit = false;
377     if ( !hit ) {
378         hit = true;
379         inkyIcons = Gtk::IconFactory::create();
380         inkyIcons->add_default();
381     }
384 // PUBLIC CALL:
385 int sp_icon_get_phys_size(int size)
387     static bool init = false;
388     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
389     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
391     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
393     if ( !sizeMapDone ) {
394         injectCustomSize();
395     }
397     if ( sizeDirty && init ) {
398         GtkIconSize const gtkSizes[] = {
399             GTK_ICON_SIZE_MENU,
400             GTK_ICON_SIZE_SMALL_TOOLBAR,
401             GTK_ICON_SIZE_LARGE_TOOLBAR,
402             GTK_ICON_SIZE_BUTTON,
403             GTK_ICON_SIZE_DND,
404             GTK_ICON_SIZE_DIALOG,
405             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
406                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
407                 GTK_ICON_SIZE_MENU
408         };
409         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
410             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
412             g_assert( val_ix < G_N_ELEMENTS(vals) );
414             gint width = 0;
415             gint height = 0;
416             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
417                 init &= (lastSys[val_ix] == std::max(width, height));
418             }
419         }
420     }
422     if ( !init ) {
423         sizeDirty = false;
424         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
426         if ( dump ) {
427             g_message( "Default icon sizes:" );
428         }
429         memset( vals, 0, sizeof(vals) );
430         memset( lastSys, 0, sizeof(lastSys) );
431         GtkIconSize const gtkSizes[] = {
432             GTK_ICON_SIZE_MENU,
433             GTK_ICON_SIZE_SMALL_TOOLBAR,
434             GTK_ICON_SIZE_LARGE_TOOLBAR,
435             GTK_ICON_SIZE_BUTTON,
436             GTK_ICON_SIZE_DND,
437             GTK_ICON_SIZE_DIALOG,
438             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
439                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
440                 GTK_ICON_SIZE_MENU
441         };
442         gchar const *const names[] = {
443             "GTK_ICON_SIZE_MENU",
444             "GTK_ICON_SIZE_SMALL_TOOLBAR",
445             "GTK_ICON_SIZE_LARGE_TOOLBAR",
446             "GTK_ICON_SIZE_BUTTON",
447             "GTK_ICON_SIZE_DND",
448             "GTK_ICON_SIZE_DIALOG",
449             "inkscape-decoration"
450         };
452         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
454         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
455             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
457             g_assert( val_ix < G_N_ELEMENTS(vals) );
459             gint width = 0;
460             gint height = 0;
461             bool used = false;
462             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
463                 vals[val_ix] = std::max(width, height);
464                 lastSys[val_ix] = vals[val_ix];
465                 used = true;
466             }
467             if (dump) {
468                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
469                           i, gtkSizes[i],
470                           ( used ? ' ' : 'X' ), width, height, names[i]);
471             }
472             gchar const *id = GTK_STOCK_OPEN;
473             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
474             if (pb) {
475                 width = gdk_pixbuf_get_width(pb);
476                 height = gdk_pixbuf_get_height(pb);
477                 int newSize = std::max( width, height );
478                 // TODO perhaps check a few more stock icons to get a range on sizes.
479                 if ( newSize > 0 ) {
480                     vals[val_ix] = newSize;
481                 }
482                 if (dump) {
483                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
484                 }
486                 g_object_unref(G_OBJECT(pb));
487             }
488         }
489         //g_object_unref(icon);
490         init = true;
491     }
493     return vals[size];
496 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
498     GtkWidget &widget = *GTK_WIDGET(icon);
500     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
502     if (image) {
503         int const padx = ( ( widget.allocation.width > icon->psize )
504                            ? ( widget.allocation.width - icon->psize ) / 2
505                            : 0 );
506         int const pady = ( ( widget.allocation.height > icon->psize )
507                            ? ( widget.allocation.height - icon->psize ) / 2
508                            : 0 );
510         int const x0 = std::max(area->x, widget.allocation.x + padx);
511         int const y0 = std::max(area->y, widget.allocation.y + pady);
512         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
513         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
515         int width = x1 - x0;
516         int height = y1 - y0;
517         // Limit drawing to when we actually have something. Avoids some crashes.
518         if ( (width > 0) && (height > 0) ) {
519             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
520                             x0 - widget.allocation.x - padx,
521                             y0 - widget.allocation.y - pady,
522                             x0, y0,
523                             width, height,
524                             GDK_RGB_DITHER_NORMAL, x0, y0);
525         }
526     }
529 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
531     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
532     // TODO: bulia, please look over
533     gsize bytesRead = 0;
534     gsize bytesWritten = 0;
535     GError *error = NULL;
536     gchar *localFilename = g_filename_from_utf8( path,
537                                                  -1,
538                                                  &bytesRead,
539                                                  &bytesWritten,
540                                                  &error);
541     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
542     g_free(localFilename);
543     g_free(path);
544     if (!pb) {
545         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
546         // TODO: bulia, please look over
547         gsize bytesRead = 0;
548         gsize bytesWritten = 0;
549         GError *error = NULL;
550         gchar *localFilename = g_filename_from_utf8( path,
551                                                      -1,
552                                                      &bytesRead,
553                                                      &bytesWritten,
554                                                      &error);
555         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
556         g_free(localFilename);
557         g_free(path);
558     }
560     if (pb) {
561         if (!gdk_pixbuf_get_has_alpha(pb)) {
562             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
563         }
565         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
566              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
567             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
568             g_object_unref(G_OBJECT(pb));
569             pb = spb;
570         }
571     }
573     return pb;
576 // takes doc, root, icon, and icon name to produce pixels
577 extern "C" guchar *
578 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
579                   gchar const *name, unsigned psize )
581     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
582     guchar *px = NULL;
584     if (doc) {
585         SPObject *object = doc->getObjectById(name);
586         if (object && SP_IS_ITEM(object)) {
587             /* Find bbox in document */
588             NR::Matrix const i2doc(from_2geom(sp_item_i2doc_affine(SP_ITEM(object))));
589             NR::Maybe<NR::Rect> dbox = SP_ITEM(object)->getBounds(i2doc);
591             if ( SP_OBJECT_PARENT(object) == NULL )
592             {
593                 dbox = NR::Rect(NR::Point(0, 0),
594                                 NR::Point(sp_document_width(doc), sp_document_height(doc)));
595             }
597             /* This is in document coordinates, i.e. pixels */
598             if ( dbox && !dbox->isEmpty() ) {
599                 NRGC gc(NULL);
600                 /* Update to renderable state */
601                 double sf = 1.0;
602                 nr_arena_item_set_transform(root, NR::Matrix(NR::scale(sf, sf)));
603                 gc.transform.set_identity();
604                 nr_arena_item_invoke_update( root, NULL, &gc,
605                                              NR_ARENA_ITEM_STATE_ALL,
606                                              NR_ARENA_ITEM_STATE_NONE );
607                 /* Item integer bbox in points */
608                 NRRectL ibox;
609                 ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
610                 ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
611                 ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
612                 ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
614                 if ( dump ) {
615                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
616                 }
618                 /* Find button visible area */
619                 int width = ibox.x1 - ibox.x0;
620                 int height = ibox.y1 - ibox.y0;
622                 if ( dump ) {
623                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
624                 }
626                 {
627                     int block = std::max(width, height);
628                     if (block != static_cast<int>(psize) ) {
629                         if ( dump ) {
630                             g_message("      resizing" );
631                         }
632                         sf = (double)psize / (double)block;
634                         nr_arena_item_set_transform(root, NR::Matrix(NR::scale(sf, sf)));
635                         gc.transform.set_identity();
636                         nr_arena_item_invoke_update( root, NULL, &gc,
637                                                      NR_ARENA_ITEM_STATE_ALL,
638                                                      NR_ARENA_ITEM_STATE_NONE );
639                         /* Item integer bbox in points */
640                         ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
641                         ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
642                         ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
643                         ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
645                         if ( dump ) {
646                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
647                         }
649                         /* Find button visible area */
650                         width = ibox.x1 - ibox.x0;
651                         height = ibox.y1 - ibox.y0;
652                         if ( dump ) {
653                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
654                         }
655                     }
656                 }
658                 int dx, dy;
659                 //dx = (psize - width) / 2;
660                 //dy = (psize - height) / 2;
661                 dx=dy=psize;
662                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
663                 dy=(dy-height)/2;
664                 NRRectL area;
665                 area.x0 = ibox.x0 - dx;
666                 area.y0 = ibox.y0 - dy;
667                 area.x1 = area.x0 + psize;
668                 area.y1 = area.y0 + psize;
669                 /* Actual renderable area */
670                 NRRectL ua;
671                 ua.x0 = MAX(ibox.x0, area.x0);
672                 ua.y0 = MAX(ibox.y0, area.y0);
673                 ua.x1 = MIN(ibox.x1, area.x1);
674                 ua.y1 = MIN(ibox.y1, area.y1);
676                 if ( dump ) {
677                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
678                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
679                 }
680                 /* Set up pixblock */
681                 px = g_new(guchar, 4 * psize * psize);
682                 memset(px, 0x00, 4 * psize * psize);
683                 /* Render */
684                 NRPixBlock B;
685                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
686                                           ua.x0, ua.y0, ua.x1, ua.y1,
687                                           px + 4 * psize * (ua.y0 - area.y0) +
688                                           4 * (ua.x0 - area.x0),
689                                           4 * psize, FALSE, FALSE );
690                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
691                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
692                 nr_pixblock_release(&B);
694                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
695                 if ( useOverlay ) {
696                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
697                 }
698             }
699         }
700     }
702     return px;
703 } // end of sp_icon_doc_icon()
707 struct svg_doc_cache_t
709     SPDocument *doc;
710     NRArenaItem *root;
711 };
713 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
714 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
716 static Glib::ustring icon_cache_key(gchar const *name,
717                                     unsigned lsize, unsigned psize)
719     Glib::ustring key=name;
720     key += ":";
721     key += lsize;
722     key += ":";
723     key += psize;
724     return key;
727 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
728     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
729     if ( found != pb_cache.end() ) {
730         return found->second;
731     }
732     return NULL;
735 static guchar *load_svg_pixels(gchar const *name,
736                                unsigned /*lsize*/, unsigned psize)
738     SPDocument *doc = NULL;
739     NRArenaItem *root = NULL;
740     svg_doc_cache_t *info = NULL;
742     // Fall back from user prefs dir into system locations.
743     Glib::ustring iconsvg = name;
744     iconsvg += ".svg";
745     std::list<gchar *> sources;
746     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
747     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
748     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
749     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
751     // Try each document in turn until we successfully load the icon from one
752     guchar *px=NULL;
753     while ( !sources.empty() && !px ) {
754         gchar *doc_filename = sources.front();
756         // Did we already load this doc?
757         Glib::ustring key(doc_filename);
758         info = 0;
759         {
760             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
761             if ( i != doc_cache.end() ) {
762                 info = i->second;
763             }
764         }
766         /* Try to load from document. */
767         if (!info &&
768             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
769             (doc = sp_document_new( doc_filename, FALSE )) ) {
771             // prep the document
772             sp_document_ensure_up_to_date(doc);
773             /* Create new arena */
774             NRArena *arena = NRArena::create();
775             /* Create ArenaItem and set transform */
776             unsigned visionkey = sp_item_display_key_new(1);
777             /* fixme: Memory manage root if needed (Lauris) */
778             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
779                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
781             // store into the cache
782             info = new svg_doc_cache_t;
783             g_assert(info);
785             info->doc=doc;
786             info->root=root;
787             doc_cache[key]=info;
788         }
789         if (info) {
790             doc=info->doc;
791             root=info->root;
792         }
794         // toss the filename
795         g_free(doc_filename);
796         sources.pop_front();
798         // move on to the next document if we couldn't get anything
799         if (!info && !doc) continue;
801         px = sp_icon_doc_icon( doc, root, name, psize );
802     }
804     return px;
807 static void addToIconSet(GdkPixbuf* pb, gchar const* name, unsigned lsize, unsigned /*psize*/) {
808     Gtk::IconSet* icnset = 0;
809     if ( iconSetCache.find(name) == iconSetCache.end() ) {
810         icnset = new Gtk::IconSet();
811         iconSetCache[name] = icnset;
812         inkyIcons->add(Gtk::StockID(name), *icnset);
813     } else {
814         icnset = iconSetCache[name];
815     }
816     Gtk::IconSource src;
817     src.set_pixbuf( Glib::wrap(pb) );
818     src.set_size( Gtk::IconSize(lsize) );
819     //src.set_state_wildcarded();
820     icnset->add_source(src);
823 // returns true if icon needed preloading, false if nothing was done
824 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
826     Glib::ustring key = icon_cache_key(name, lsize, psize);
827     GdkPixbuf *pb = get_cached_pixbuf(key);
828     if (pb) {
829         return false;
830     } else {
831         guchar* px = load_svg_pixels(name, lsize, psize);
832         if (px) {
833             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
834                                           psize, psize, psize * 4,
835                                           /*(GdkPixbufDestroyNotify)g_free*/NULL, NULL);
837             pb_cache[key] = pb;
838             addToIconSet(pb, name, lsize, psize);
839         }
840         return true;
841     }
844 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
846     Glib::ustring key = icon_cache_key(name, lsize, psize);
848     // did we already load this icon at this scale/size?
849     GdkPixbuf* pb = get_cached_pixbuf(key);
850     if (!pb) {
851         guchar *px = load_svg_pixels(name, lsize, psize);
852         if (px) {
853             // don't pass the g_free because we're caching the pixel
854             // space loaded through ...
855             // I just changed this. make sure sp_icon_image_load still does the right thing.
856             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
857                                           psize, psize, psize * 4,
858                                           /*(GdkPixbufDestroyNotify)g_free*/NULL, NULL);
859             pb_cache[key] = pb;
860             addToIconSet(pb, name, lsize, psize);
861         }
862     }
864     // increase refcount since we're hading out ownership
865     g_object_ref(G_OBJECT(pb));
866     return pb;
869 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
870                             unsigned r, unsigned g, unsigned b)
872     for ( int y = 0; y < height; y += 4 ) {
873         guchar *ptr = px + y * stride;
874         for ( int x = 0; x < width; x += 4 ) {
875             *(ptr++) = r;
876             *(ptr++) = g;
877             *(ptr++) = b;
878             *(ptr++) = 0xff;
880             ptr += 4 * 3;
881         }
882     }
884     if ( width > 1 && height > 1 ) {
885         // point at the last pixel
886         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
888         if ( width > 2 ) {
889             px[4] = r;
890             px[5] = g;
891             px[6] = b;
892             px[7] = 0xff;
894             ptr[-12] = r;
895             ptr[-11] = g;
896             ptr[-10] = b;
897             ptr[-9] = 0xff;
898         }
900         ptr[-4] = r;
901         ptr[-3] = g;
902         ptr[-2] = b;
903         ptr[-1] = 0xff;
905         px[0 + stride] = r;
906         px[1 + stride] = g;
907         px[2 + stride] = b;
908         px[3 + stride] = 0xff;
910         ptr[0 - stride] = r;
911         ptr[1 - stride] = g;
912         ptr[2 - stride] = b;
913         ptr[3 - stride] = 0xff;
915         if ( height > 2 ) {
916             ptr[0 - stride * 3] = r;
917             ptr[1 - stride * 3] = g;
918             ptr[2 - stride * 3] = b;
919             ptr[3 - stride * 3] = 0xff;
920         }
921     }
924 class preRenderItem
926 public:
927     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
928         _lsize( lsize ),
929         _name( name )
930     {}
931     Inkscape::IconSize _lsize;
932     Glib::ustring _name;
933 };
936 #include <queue>
938 static std::queue<preRenderItem> pendingRenders;
939 static bool callbackHooked = false;
941 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
944     if ( !callbackHooked )
945     {
946         callbackHooked = true;
947         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
948     }
950     pendingRenders.push(preRenderItem(lsize, name));
953 gboolean icon_prerender_task(gpointer /*data*/) {
954     if (!pendingRenders.empty()) {
955         preRenderItem single=pendingRenders.front();
956         pendingRenders.pop();
957         int psize = sp_icon_get_phys_size(single._lsize);
958         prerender_icon(single._name.c_str(), single._lsize, psize);
959     }
961     if (!pendingRenders.empty()) {
962         return TRUE;
963     } else {
964         callbackHooked = false;
965         return FALSE;
966     }
969 /*
970   Local Variables:
971   mode:c++
972   c-file-style:"stroustrup"
973   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
974   indent-tabs-mode:nil
975   fill-column:99
976   End:
977 */
978 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :