Code

03a39acb62a9d58681355b55fb9fefa30e539e24
[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/image.h>
25 #include "path-prefix.h"
26 #include "prefs-utils.h"
27 #include "inkscape.h"
28 #include "document.h"
29 #include "sp-item.h"
30 #include "display/nr-arena.h"
31 #include "display/nr-arena-item.h"
32 #include "io/sys.h"
34 #include "icon.h"
36 static gboolean icon_prerender_task(gpointer data);
38 static void addPreRender( Inkscape::IconSize lsize, gchar const *name );
40 static void sp_icon_class_init(SPIconClass *klass);
41 static void sp_icon_init(SPIcon *icon);
42 static void sp_icon_destroy(GtkObject *object);
44 static void sp_icon_reset(SPIcon *icon);
45 static void sp_icon_clear(SPIcon *icon);
47 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
48 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
49 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
51 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
53 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
54 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
55 static void sp_icon_theme_changed( SPIcon *icon );
57 static guchar *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
58 static guchar *sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize);
60 static guchar *sp_icon_image_load(SPIcon *icon, gchar const *name);
62 static int sp_icon_get_phys_size(int size);
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 GtkType
86 sp_icon_get_type()
87 {
88     static GtkType type = 0;
89     if (!type) {
90         GtkTypeInfo info = {
91             "SPIcon",
92             sizeof(SPIcon),
93             sizeof(SPIconClass),
94             (GtkClassInitFunc) sp_icon_class_init,
95             (GtkObjectInitFunc) sp_icon_init,
96             NULL, NULL, NULL
97         };
98         type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
99     }
100     return type;
103 static void
104 sp_icon_class_init(SPIconClass *klass)
106     GtkObjectClass *object_class;
107     GtkWidgetClass *widget_class;
109     object_class = (GtkObjectClass *) klass;
110     widget_class = (GtkWidgetClass *) klass;
112     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
114     object_class->destroy = sp_icon_destroy;
116     widget_class->size_request = sp_icon_size_request;
117     widget_class->size_allocate = sp_icon_size_allocate;
118     widget_class->expose_event = sp_icon_expose;
119     widget_class->screen_changed = sp_icon_screen_changed;
120     widget_class->style_set = sp_icon_style_set;
124 static void
125 sp_icon_init(SPIcon *icon)
127     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
128     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
129     icon->psize = 0;
130     icon->name = 0;
131     icon->pb = 0;
132     icon->pb_faded = 0;
135 static void
136 sp_icon_destroy(GtkObject *object)
138     SPIcon *icon = SP_ICON(object);
139     sp_icon_clear(icon);
140     if ( icon->name ) {
141         g_free( icon->name );
142         icon->name = 0;
143     }
145     ((GtkObjectClass *) (parent_class))->destroy(object);
148 static void sp_icon_reset( SPIcon *icon ) {
149     icon->psize = 0;
150     sp_icon_clear(icon);
153 static void sp_icon_clear( SPIcon *icon ) {
154     if (icon->pb) {
155         g_object_unref(G_OBJECT(icon->pb));
156         icon->pb = NULL;
157     }
158     if (icon->pb_faded) {
159         g_object_unref(G_OBJECT(icon->pb_faded));
160         icon->pb_faded = NULL;
161     }
164 static void
165 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
167     SPIcon const *icon = SP_ICON(widget);
169     int const size = ( icon->psize
170                        ? icon->psize
171                        : sp_icon_get_phys_size(icon->lsize) );
172     requisition->width = size;
173     requisition->height = size;
176 static void
177 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
179     widget->allocation = *allocation;
181     if (GTK_WIDGET_DRAWABLE(widget)) {
182         gtk_widget_queue_draw(widget);
183     }
186 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
188     if ( GTK_WIDGET_DRAWABLE(widget) ) {
189         SPIcon *icon = SP_ICON(widget);
190         if ( !icon->pb ) {
191             sp_icon_fetch_pixbuf( icon );
192         }
194         sp_icon_paint(SP_ICON(widget), &event->area);
195     }
197     return TRUE;
200 void sp_icon_fetch_pixbuf( SPIcon *icon )
202     if ( icon ) {
203         if ( !icon->pb ) {
204             guchar *pixels = 0;
206             icon->psize = sp_icon_get_phys_size(icon->lsize);
208             pixels = sp_icon_image_load( icon, icon->name );
210             if (pixels) {
211                 // don't pass the g_free because we're caching the pixel
212                 // space loaded through ...
213                 // I just changed this. make sure sp_icon_image_load still does the right thing.
214                 icon->pb = gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, TRUE, 8,
215                                                     icon->psize, icon->psize, icon->psize * 4,
216                                                     /*(GdkPixbufDestroyNotify)g_free*/NULL, NULL);
217                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
219                 pixels = gdk_pixbuf_get_pixels(icon->pb_faded);
220                 size_t stride = gdk_pixbuf_get_rowstride(icon->pb_faded);
221                 pixels += 3; // alpha
222                 for ( int row = 0 ; row < icon->psize ; row++ ) {
223                     guchar *row_pixels = pixels;
224                     for ( int column = 0 ; column < icon->psize ; column++ ) {
225                         *row_pixels = *row_pixels >> 1;
226                         row_pixels += 4;
227                     }
228                     pixels += stride;
229                 }
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     }
238 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
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);
247 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
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);
256 static void sp_icon_theme_changed( SPIcon *icon )
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) );
265 static GtkWidget *
266 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
268     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
269     static gint fallback = prefs_get_int_attribute_limited( "debug.icons", "checkNames", 0, 0, 1 );
271     addPreRender( lsize, name );
273     GtkStockItem stock;
274     gboolean tryLoad = gtk_stock_lookup( name, &stock );
275     if ( !tryLoad && fallback ) {
276         tryLoad |= strncmp("gtk-", name, 4 ) == 0;
277     }
278     if ( !tryLoad && fallback ) {
279         tryLoad |= strncmp("gnome-", name, 6 ) == 0;
280     }
282     GtkWidget *widget = 0;
283     if ( tryLoad ) {
284         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
286         if ( !sizeMapDone ) {
287             injectCustomSize();
288         }
290         GtkWidget *img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
291         if ( img ) {
292             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
293             if ( type == GTK_IMAGE_STOCK ) {
294                 widget = GTK_WIDGET(img);
295                 img = 0;
297                 if ( dump ) {
298                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK)", name, lsize );
299                 }
300             } else {
301                 if ( dump ) {
302                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
303                 }
304                 g_object_unref( (GObject *)img );
305                 img = 0;
306             }
307         }
308     }
310     if ( !widget ) {
311         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
312         icon->lsize = lsize;
313         icon->name = g_strdup(name);
314         icon->psize = sp_icon_get_phys_size(lsize);
316         widget = GTK_WIDGET(icon);
317     }
319     return widget;
322 GtkWidget *
323 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
325     return sp_icon_new_full( lsize, name );
328 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
330     Gtk::Widget *result = 0;
331     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
333     if ( widget ) {
334         if ( GTK_IS_IMAGE(widget) ) {
335             GtkImage *img = GTK_IMAGE(widget);
336             result = Glib::wrap( img );
337         } else {
338             result = Glib::wrap( widget );
339         }
340     }
342     return result;
345 // Try to load the named svg, falling back to pixmaps
346 guchar *
347 sp_icon_image_load( SPIcon *icon, gchar const *name )
349     guchar *px = sp_icon_image_load_svg( name, icon->lsize, icon->psize );
350     if (!px) {
351         px = sp_icon_image_load_pixmap(name, icon->lsize, icon->psize);
352     }
354     return px;
357 GtkIconSize
358 sp_icon_get_gtk_size(int size)
360     static GtkIconSize map[64] = {(GtkIconSize)0};
361     size = CLAMP(size, 4, 63);
362     if (!map[size]) {
363         static int count = 0;
364         char c[64];
365         g_snprintf(c, 64, "InkscapeIcon%d", count++);
366         map[size] = gtk_icon_size_register(c, size, size);
367     }
368     return map[size];
371 static void injectCustomSize()
373     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
374     if ( !sizeMapDone )
375     {
376         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
377         gint width = 0;
378         gint height = 0;
379         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
380             gint newWidth = ((width * 3) / 4);
381             gint newHeight = ((height * 3) / 4);
382             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
383             if ( newSizeEnum ) {
384                 if ( dump ) {
385                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
386                 }
387                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
388                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
389                     iconSizeLookup[index] = newSizeEnum;
390                 } else if ( dump ) {
391                     g_message("size lookup array too small to store entry");
392                 }
393             }
394         }
395         sizeMapDone = true;
396     }
400 static int sp_icon_get_phys_size(int size)
402     static bool init = false;
403     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
404     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
406     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
408     if ( !sizeMapDone ) {
409         injectCustomSize();
410     }
412     if ( sizeDirty && init ) {
413         GtkIconSize const gtkSizes[] = {
414             GTK_ICON_SIZE_MENU,
415             GTK_ICON_SIZE_SMALL_TOOLBAR,
416             GTK_ICON_SIZE_LARGE_TOOLBAR,
417             GTK_ICON_SIZE_BUTTON,
418             GTK_ICON_SIZE_DND,
419             GTK_ICON_SIZE_DIALOG,
420             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
421                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
422                 GTK_ICON_SIZE_MENU
423         };
424         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
425             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
427             g_assert( val_ix < G_N_ELEMENTS(vals) );
429             gint width = 0;
430             gint height = 0;
431             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
432                 init &= (lastSys[val_ix] == std::max(width, height));
433             }
434         }
435     }
437     if ( !init ) {
438         sizeDirty = false;
439         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
441         if ( dump ) {
442             g_message( "Default icon sizes:" );
443         }
444         memset( vals, 0, sizeof(vals) );
445         memset( lastSys, 0, sizeof(lastSys) );
446         GtkIconSize const gtkSizes[] = {
447             GTK_ICON_SIZE_MENU,
448             GTK_ICON_SIZE_SMALL_TOOLBAR,
449             GTK_ICON_SIZE_LARGE_TOOLBAR,
450             GTK_ICON_SIZE_BUTTON,
451             GTK_ICON_SIZE_DND,
452             GTK_ICON_SIZE_DIALOG,
453             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
454                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
455                 GTK_ICON_SIZE_MENU
456         };
457         gchar const *const names[] = {
458             "GTK_ICON_SIZE_MENU",
459             "GTK_ICON_SIZE_SMALL_TOOLBAR",
460             "GTK_ICON_SIZE_LARGE_TOOLBAR",
461             "GTK_ICON_SIZE_BUTTON",
462             "GTK_ICON_SIZE_DND",
463             "GTK_ICON_SIZE_DIALOG",
464             "inkscape-decoration"
465         };
467         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
469         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
470             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
472             g_assert( val_ix < G_N_ELEMENTS(vals) );
474             gint width = 0;
475             gint height = 0;
476             bool used = false;
477             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
478                 vals[val_ix] = std::max(width, height);
479                 lastSys[val_ix] = vals[val_ix];
480                 used = true;
481             }
482             if (dump) {
483                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
484                           i, gtkSizes[i],
485                           ( used ? ' ' : 'X' ), width, height, names[i]);
486             }
487             gchar const *id = GTK_STOCK_OPEN;
488             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
489             if (pb) {
490                 width = gdk_pixbuf_get_width(pb);
491                 height = gdk_pixbuf_get_height(pb);
492                 int newSize = std::max( width, height );
493                 // TODO perhaps check a few more stock icons to get a range on sizes.
494                 if ( newSize > 0 ) {
495                     vals[val_ix] = newSize;
496                 }
497                 if (dump) {
498                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
499                 }
501                 g_object_unref(G_OBJECT(pb));
502             }
503         }
504         //g_object_unref(icon);
505         init = true;
506     }
508     return vals[size];
511 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
513     GtkWidget &widget = *GTK_WIDGET(icon);
515     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
517     if (image) {
518         int const padx = ( ( widget.allocation.width > icon->psize )
519                            ? ( widget.allocation.width - icon->psize ) / 2
520                            : 0 );
521         int const pady = ( ( widget.allocation.height > icon->psize )
522                            ? ( widget.allocation.height - icon->psize ) / 2
523                            : 0 );
525         int const x0 = std::max(area->x, widget.allocation.x + padx);
526         int const y0 = std::max(area->y, widget.allocation.y + pady);
527         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
528         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
530         int width = x1 - x0;
531         int height = y1 - y0;
532         // Limit drawing to when we actually have something. Avoids some crashes.
533         if ( (width > 0) && (height > 0) ) {
534             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
535                             x0 - widget.allocation.x - padx,
536                             y0 - widget.allocation.y - pady,
537                             x0, y0,
538                             width, height,
539                             GDK_RGB_DITHER_NORMAL, x0, y0);
540         }
541     }
544 static guchar *
545 sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize)
547     gchar *path;
548     guchar *px;
549     GdkPixbuf *pb;
551     path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
552     // TODO: bulia, please look over
553     gsize bytesRead = 0;
554     gsize bytesWritten = 0;
555     GError *error = NULL;
556     gchar *localFilename = g_filename_from_utf8( path,
557                                                  -1,
558                                                  &bytesRead,
559                                                  &bytesWritten,
560                                                  &error);
561     pb = gdk_pixbuf_new_from_file(localFilename, NULL);
562     g_free(localFilename);
563     g_free(path);
564     if (!pb) {
565         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
566         // TODO: bulia, please look over
567         gsize bytesRead = 0;
568         gsize bytesWritten = 0;
569         GError *error = NULL;
570         gchar *localFilename = g_filename_from_utf8( path,
571                                                      -1,
572                                                      &bytesRead,
573                                                      &bytesWritten,
574                                                      &error);
575         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
576         g_free(localFilename);
577         g_free(path);
578     }
579     if (pb) {
580         if (!gdk_pixbuf_get_has_alpha(pb))
581             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
582         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
583              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
584             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
585             g_object_unref(G_OBJECT(pb));
586             pb = spb;
587         }
588         guchar *spx = gdk_pixbuf_get_pixels(pb);
589         int srs = gdk_pixbuf_get_rowstride(pb);
590         px = g_new(guchar, 4 * psize * psize);
591         for (unsigned y = 0; y < psize; y++) {
592             memcpy(px + 4 * y * psize, spx + y * srs, 4 * psize);
593         }
594         g_object_unref(G_OBJECT(pb));
596         return px;
597     }
599     return NULL;
602 // takes doc, root, icon, and icon name to produce pixels
603 extern "C" guchar *
604 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
605                   gchar const *name, unsigned psize )
607     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
608     guchar *px = NULL;
610     if (doc) {
611         SPObject *object = doc->getObjectById(name);
612         if (object && SP_IS_ITEM(object)) {
613             /* Find bbox in document */
614             NR::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
615             NR::Maybe<NR::Rect> dbox = SP_ITEM(object)->getBounds(i2doc);
617             if ( SP_OBJECT_PARENT(object) == NULL )
618             {
619                 dbox = NR::Rect(NR::Point(0, 0),
620                                 NR::Point(sp_document_width(doc), sp_document_height(doc)));
621             }
623             /* This is in document coordinates, i.e. pixels */
624             if ( dbox && !dbox->isEmpty() ) {
625                 NRGC gc(NULL);
626                 /* Update to renderable state */
627                 double sf = 1.0;
628                 NRMatrix t;
629                 nr_matrix_set_scale(&t, sf, sf);
630                 nr_arena_item_set_transform(root, &t);
631                 nr_matrix_set_identity(&gc.transform);
632                 nr_arena_item_invoke_update( root, NULL, &gc,
633                                              NR_ARENA_ITEM_STATE_ALL,
634                                              NR_ARENA_ITEM_STATE_NONE );
635                 /* Item integer bbox in points */
636                 NRRectL ibox;
637                 ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
638                 ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
639                 ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
640                 ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
642                 if ( dump ) {
643                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
644                 }
646                 /* Find button visible area */
647                 int width = ibox.x1 - ibox.x0;
648                 int height = ibox.y1 - ibox.y0;
650                 if ( dump ) {
651                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
652                 }
654                 {
655                     int block = std::max(width, height);
656                     if (block != static_cast<int>(psize) ) {
657                         if ( dump ) {
658                             g_message("      resizing" );
659                         }
660                         sf = (double)psize / (double)block;
662                         nr_matrix_set_scale(&t, sf, sf);
663                         nr_arena_item_set_transform(root, &t);
664                         nr_matrix_set_identity(&gc.transform);
665                         nr_arena_item_invoke_update( root, NULL, &gc,
666                                                      NR_ARENA_ITEM_STATE_ALL,
667                                                      NR_ARENA_ITEM_STATE_NONE );
668                         /* Item integer bbox in points */
669                         ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
670                         ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
671                         ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
672                         ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
674                         if ( dump ) {
675                             g_message( "   box2   --'%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                         width = ibox.x1 - ibox.x0;
680                         height = ibox.y1 - ibox.y0;
681                         if ( dump ) {
682                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
683                         }
684                     }
685                 }
687                 int dx, dy;
688                 //dx = (psize - width) / 2;
689                 //dy = (psize - height) / 2;
690                 dx=dy=psize;
691                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
692                 dy=(dy-height)/2;
693                 NRRectL area;
694                 area.x0 = ibox.x0 - dx;
695                 area.y0 = ibox.y0 - dy;
696                 area.x1 = area.x0 + psize;
697                 area.y1 = area.y0 + psize;
698                 /* Actual renderable area */
699                 NRRectL ua;
700                 ua.x0 = MAX(ibox.x0, area.x0);
701                 ua.y0 = MAX(ibox.y0, area.y0);
702                 ua.x1 = MIN(ibox.x1, area.x1);
703                 ua.y1 = MIN(ibox.y1, area.y1);
705                 if ( dump ) {
706                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
707                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
708                 }
709                 /* Set up pixblock */
710                 px = g_new(guchar, 4 * psize * psize);
711                 memset(px, 0x00, 4 * psize * psize);
712                 /* Render */
713                 NRPixBlock B;
714                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
715                                           ua.x0, ua.y0, ua.x1, ua.y1,
716                                           px + 4 * psize * (ua.y0 - area.y0) +
717                                           4 * (ua.x0 - area.x0),
718                                           4 * psize, FALSE, FALSE );
719                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
720                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
721                 nr_pixblock_release(&B);
723                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
724                 if ( useOverlay ) {
725                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
726                 }
727             }
728         }
729     }
731     return px;
732 } // end of sp_icon_doc_icon()
736 struct svg_doc_cache_t
738     SPDocument *doc;
739     NRArenaItem *root;
740 };
742 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
743 static std::map<Glib::ustring, guchar *> px_cache;
745 static Glib::ustring icon_cache_key(gchar const *name,
746                                     unsigned lsize, unsigned psize)
748     Glib::ustring key=name;
749     key += ":";
750     key += lsize;
751     key += ":";
752     key += psize;
753     return key;
756 static guchar *get_cached_pixels(Glib::ustring const &key) {
757     std::map<Glib::ustring, guchar *>::iterator found=px_cache.find(key);
758     if ( found != px_cache.end() ) {
759         return found->second;
760     }
761     return NULL;
764 static guchar *load_svg_pixels(gchar const *name,
765                                unsigned lsize, unsigned psize)
767     SPDocument *doc = NULL;
768     NRArenaItem *root = NULL;
769     svg_doc_cache_t *info = NULL;
771     // Fall back from user prefs dir into system locations.
772     Glib::ustring iconsvg = name;
773     iconsvg += ".svg";
774     std::list<gchar *> sources;
775     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
776     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
777     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
778     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
780     // Try each document in turn until we successfully load the icon from one
781     guchar *px=NULL;
782     while ( !sources.empty() && !px ) {
783         gchar *doc_filename = sources.front();
785         // Did we already load this doc?
786         Glib::ustring key(doc_filename);
787         info = 0;
788         {
789             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
790             if ( i != doc_cache.end() ) {
791                 info = i->second;
792             }
793         }
795         /* Try to load from document. */
796         if (!info &&
797             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
798             (doc = sp_document_new( doc_filename, FALSE )) ) {
800             // prep the document
801             sp_document_ensure_up_to_date(doc);
802             /* Create new arena */
803             NRArena *arena = NRArena::create();
804             /* Create ArenaItem and set transform */
805             unsigned visionkey = sp_item_display_key_new(1);
806             /* fixme: Memory manage root if needed (Lauris) */
807             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
808                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
810             // store into the cache
811             info = new svg_doc_cache_t;
812             g_assert(info);
814             info->doc=doc;
815             info->root=root;
816             doc_cache[key]=info;
817         }
818         if (info) {
819             doc=info->doc;
820             root=info->root;
821         }
823         // toss the filename
824         g_free(doc_filename);
825         sources.pop_front();
827         // move on to the next document if we couldn't get anything
828         if (!info && !doc) continue;
830         px = sp_icon_doc_icon( doc, root, name, psize );
831     }
833     return px;
836 // returns true if icon needed preloading, false if nothing was done
837 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
839     Glib::ustring key = icon_cache_key(name, lsize, psize);
840     guchar *px = get_cached_pixels(key);
841     if (px) {
842         return false;
843     } else {
844         px = load_svg_pixels(name, lsize, psize);
845         if (px) {
846             px_cache[key] = px;
847         }
848         return true;
849     }
852 static guchar *
853 sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
855     Glib::ustring key = icon_cache_key(name, lsize, psize);
857     // did we already load this icon at this scale/size?
858     guchar *px = get_cached_pixels(key);
859     if (!px) {
860         px = load_svg_pixels(name, lsize, psize);
861         if (px) {
862             px_cache[key] = px;
863         }
864     }
865     return px;
868 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
869                             unsigned r, unsigned g, unsigned b)
871     for ( int y = 0; y < height; y += 4 ) {
872         guchar *ptr = px + y * stride;
873         for ( int x = 0; x < width; x += 4 ) {
874             *(ptr++) = r;
875             *(ptr++) = g;
876             *(ptr++) = b;
877             *(ptr++) = 0xff;
879             ptr += 4 * 3;
880         }
881     }
883     if ( width > 1 && height > 1 ) {
884         // point at the last pixel
885         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
887         if ( width > 2 ) {
888             px[4] = r;
889             px[5] = g;
890             px[6] = b;
891             px[7] = 0xff;
893             ptr[-12] = r;
894             ptr[-11] = g;
895             ptr[-10] = b;
896             ptr[-9] = 0xff;
897         }
899         ptr[-4] = r;
900         ptr[-3] = g;
901         ptr[-2] = b;
902         ptr[-1] = 0xff;
904         px[0 + stride] = r;
905         px[1 + stride] = g;
906         px[2 + stride] = b;
907         px[3 + stride] = 0xff;
909         ptr[0 - stride] = r;
910         ptr[1 - stride] = g;
911         ptr[2 - stride] = b;
912         ptr[3 - stride] = 0xff;
914         if ( height > 2 ) {
915             ptr[0 - stride * 3] = r;
916             ptr[1 - stride * 3] = g;
917             ptr[2 - stride * 3] = b;
918             ptr[3 - stride * 3] = 0xff;
919         }
920     }
923 class preRenderItem
925 public:
926     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
927         _lsize( lsize ),
928         _name( name )
929     {}
930     Inkscape::IconSize _lsize;
931     Glib::ustring _name;
932 };
935 #include <queue>
937 static std::queue<preRenderItem> pendingRenders;
938 static bool callbackHooked = false;
940 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
943     if ( !callbackHooked )
944     {
945         callbackHooked = true;
946         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
947     }
949     pendingRenders.push(preRenderItem(lsize, name));
952 gboolean icon_prerender_task(gpointer data) {
953     if (!pendingRenders.empty()) {
954         preRenderItem single=pendingRenders.front();
955         pendingRenders.pop();
956         int psize = sp_icon_get_phys_size(single._lsize);
957         prerender_icon(single._name.c_str(), single._lsize, psize);
958     }
960     if (!pendingRenders.empty()) {
961         return TRUE;
962     } else {
963         callbackHooked = false;
964         return FALSE;
965     }
968 /*
969   Local Variables:
970   mode:c++
971   c-file-style:"stroustrup"
972   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
973   indent-tabs-mode:nil
974   fill-column:99
975   End:
976 */
977 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :