Code

No more NRMatrix or NRPoint.
[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 void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
63                                     unsigned r, unsigned g, unsigned b );
65 static void injectCustomSize();
67 static GtkWidgetClass *parent_class;
69 static bool sizeDirty = true;
71 static bool sizeMapDone = false;
72 static GtkIconSize iconSizeLookup[] = {
73     GTK_ICON_SIZE_INVALID,
74     GTK_ICON_SIZE_MENU,
75     GTK_ICON_SIZE_SMALL_TOOLBAR,
76     GTK_ICON_SIZE_LARGE_TOOLBAR,
77     GTK_ICON_SIZE_BUTTON,
78     GTK_ICON_SIZE_DND,
79     GTK_ICON_SIZE_DIALOG,
80     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
81 };
83 GtkType
84 sp_icon_get_type()
85 {
86     static GtkType type = 0;
87     if (!type) {
88         GtkTypeInfo info = {
89             "SPIcon",
90             sizeof(SPIcon),
91             sizeof(SPIconClass),
92             (GtkClassInitFunc) sp_icon_class_init,
93             (GtkObjectInitFunc) sp_icon_init,
94             NULL, NULL, NULL
95         };
96         type = gtk_type_unique(GTK_TYPE_WIDGET, &info);
97     }
98     return type;
99 }
101 static void
102 sp_icon_class_init(SPIconClass *klass)
104     GtkObjectClass *object_class;
105     GtkWidgetClass *widget_class;
107     object_class = (GtkObjectClass *) klass;
108     widget_class = (GtkWidgetClass *) klass;
110     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
112     object_class->destroy = sp_icon_destroy;
114     widget_class->size_request = sp_icon_size_request;
115     widget_class->size_allocate = sp_icon_size_allocate;
116     widget_class->expose_event = sp_icon_expose;
117     widget_class->screen_changed = sp_icon_screen_changed;
118     widget_class->style_set = sp_icon_style_set;
122 static void
123 sp_icon_init(SPIcon *icon)
125     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
126     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
127     icon->psize = 0;
128     icon->name = 0;
129     icon->pb = 0;
130     icon->pb_faded = 0;
133 static void
134 sp_icon_destroy(GtkObject *object)
136     SPIcon *icon = SP_ICON(object);
137     sp_icon_clear(icon);
138     if ( icon->name ) {
139         g_free( icon->name );
140         icon->name = 0;
141     }
143     ((GtkObjectClass *) (parent_class))->destroy(object);
146 static void sp_icon_reset( SPIcon *icon ) {
147     icon->psize = 0;
148     sp_icon_clear(icon);
151 static void sp_icon_clear( SPIcon *icon ) {
152     if (icon->pb) {
153         g_object_unref(G_OBJECT(icon->pb));
154         icon->pb = NULL;
155     }
156     if (icon->pb_faded) {
157         g_object_unref(G_OBJECT(icon->pb_faded));
158         icon->pb_faded = NULL;
159     }
162 static void
163 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
165     SPIcon const *icon = SP_ICON(widget);
167     int const size = ( icon->psize
168                        ? icon->psize
169                        : sp_icon_get_phys_size(icon->lsize) );
170     requisition->width = size;
171     requisition->height = size;
174 static void
175 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
177     widget->allocation = *allocation;
179     if (GTK_WIDGET_DRAWABLE(widget)) {
180         gtk_widget_queue_draw(widget);
181     }
184 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
186     if ( GTK_WIDGET_DRAWABLE(widget) ) {
187         SPIcon *icon = SP_ICON(widget);
188         if ( !icon->pb ) {
189             sp_icon_fetch_pixbuf( icon );
190         }
192         sp_icon_paint(SP_ICON(widget), &event->area);
193     }
195     return TRUE;
198 void sp_icon_fetch_pixbuf( SPIcon *icon )
200     if ( icon ) {
201         if ( !icon->pb ) {
202             guchar *pixels = 0;
204             icon->psize = sp_icon_get_phys_size(icon->lsize);
206             pixels = sp_icon_image_load( icon, icon->name );
208             if (pixels) {
209                 // don't pass the g_free because we're caching the pixel
210                 // space loaded through ...
211                 // I just changed this. make sure sp_icon_image_load still does the right thing.
212                 icon->pb = gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, TRUE, 8,
213                                                     icon->psize, icon->psize, icon->psize * 4,
214                                                     /*(GdkPixbufDestroyNotify)g_free*/NULL, NULL);
215                 icon->pb_faded = gdk_pixbuf_copy(icon->pb);
217                 pixels = gdk_pixbuf_get_pixels(icon->pb_faded);
218                 size_t stride = gdk_pixbuf_get_rowstride(icon->pb_faded);
219                 pixels += 3; // alpha
220                 for ( int row = 0 ; row < icon->psize ; row++ ) {
221                     guchar *row_pixels = pixels;
222                     for ( int column = 0 ; column < icon->psize ; column++ ) {
223                         *row_pixels = *row_pixels >> 1;
224                         row_pixels += 4;
225                     }
226                     pixels += stride;
227                 }
228             } else {
229                 /* TODO: We should do something more useful if we can't load the image. */
230                 g_warning ("failed to load icon '%s'", icon->name);
231             }
232         }
233     }
236 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
238     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
239         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
240     }
241     SPIcon *icon = SP_ICON(widget);
242     sp_icon_theme_changed(icon);
245 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
247     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
248         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
249     }
250     SPIcon *icon = SP_ICON(widget);
251     sp_icon_theme_changed(icon);
254 static void sp_icon_theme_changed( SPIcon *icon )
256     //g_message("Got a change bump for this icon");
257     sizeDirty = true;
258     sp_icon_reset(icon);
259     gtk_widget_queue_draw( GTK_WIDGET(icon) );
263 static GtkWidget *
264 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
266     static gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpGtk", 0, 0, 1 );
267     static gint fallback = prefs_get_int_attribute_limited( "debug.icons", "checkNames", 0, 0, 1 );
269     addPreRender( lsize, name );
271     GtkStockItem stock;
272     gboolean tryLoad = gtk_stock_lookup( name, &stock );
273     if ( !tryLoad && fallback ) {
274         tryLoad |= strncmp("gtk-", name, 4 ) == 0;
275     }
276     if ( !tryLoad && fallback ) {
277         tryLoad |= strncmp("gnome-", name, 6 ) == 0;
278     }
280     GtkWidget *widget = 0;
281     if ( tryLoad ) {
282         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
284         if ( !sizeMapDone ) {
285             injectCustomSize();
286         }
288         GtkWidget *img = gtk_image_new_from_stock( name, iconSizeLookup[trySize] );
289         if ( img ) {
290             GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
291             if ( type == GTK_IMAGE_STOCK ) {
292                 widget = GTK_WIDGET(img);
293                 img = 0;
295                 if ( dump ) {
296                     g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK)", name, lsize );
297                 }
298             } else {
299                 if ( dump ) {
300                     g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
301                 }
302                 g_object_unref( (GObject *)img );
303                 img = 0;
304             }
305         }
306     }
308     if ( !widget ) {
309         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
310         icon->lsize = lsize;
311         icon->name = g_strdup(name);
312         icon->psize = sp_icon_get_phys_size(lsize);
314         widget = GTK_WIDGET(icon);
315     }
317     return widget;
320 GtkWidget *
321 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
323     return sp_icon_new_full( lsize, name );
326 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
328     Gtk::Widget *result = 0;
329     GtkWidget *widget = sp_icon_new_full( size, oid.c_str() );
331     if ( widget ) {
332         if ( GTK_IS_IMAGE(widget) ) {
333             GtkImage *img = GTK_IMAGE(widget);
334             result = Glib::wrap( img );
335         } else {
336             result = Glib::wrap( widget );
337         }
338     }
340     return result;
343 // Try to load the named svg, falling back to pixmaps
344 guchar *
345 sp_icon_image_load( SPIcon *icon, gchar const *name )
347     guchar *px = sp_icon_image_load_svg( name, icon->lsize, icon->psize );
348     if (!px) {
349         px = sp_icon_image_load_pixmap(name, icon->lsize, icon->psize);
350     }
352     return px;
355 GtkIconSize
356 sp_icon_get_gtk_size(int size)
358     static GtkIconSize map[64] = {(GtkIconSize)0};
359     size = CLAMP(size, 4, 63);
360     if (!map[size]) {
361         static int count = 0;
362         char c[64];
363         g_snprintf(c, 64, "InkscapeIcon%d", count++);
364         map[size] = gtk_icon_size_register(c, size, size);
365     }
366     return map[size];
369 static void injectCustomSize()
371     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
372     if ( !sizeMapDone )
373     {
374         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
375         gint width = 0;
376         gint height = 0;
377         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
378             gint newWidth = ((width * 3) / 4);
379             gint newHeight = ((height * 3) / 4);
380             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
381             if ( newSizeEnum ) {
382                 if ( dump ) {
383                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
384                 }
385                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
386                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
387                     iconSizeLookup[index] = newSizeEnum;
388                 } else if ( dump ) {
389                     g_message("size lookup array too small to store entry");
390                 }
391             }
392         }
393         sizeMapDone = true;
394     }
398 int sp_icon_get_phys_size(int size)
400     static bool init = false;
401     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
402     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
404     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
406     if ( !sizeMapDone ) {
407         injectCustomSize();
408     }
410     if ( sizeDirty && init ) {
411         GtkIconSize const gtkSizes[] = {
412             GTK_ICON_SIZE_MENU,
413             GTK_ICON_SIZE_SMALL_TOOLBAR,
414             GTK_ICON_SIZE_LARGE_TOOLBAR,
415             GTK_ICON_SIZE_BUTTON,
416             GTK_ICON_SIZE_DND,
417             GTK_ICON_SIZE_DIALOG,
418             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
419                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
420                 GTK_ICON_SIZE_MENU
421         };
422         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
423             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
425             g_assert( val_ix < G_N_ELEMENTS(vals) );
427             gint width = 0;
428             gint height = 0;
429             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
430                 init &= (lastSys[val_ix] == std::max(width, height));
431             }
432         }
433     }
435     if ( !init ) {
436         sizeDirty = false;
437         gint dump = prefs_get_int_attribute_limited( "debug.icons", "dumpDefault", 0, 0, 1 );
439         if ( dump ) {
440             g_message( "Default icon sizes:" );
441         }
442         memset( vals, 0, sizeof(vals) );
443         memset( lastSys, 0, sizeof(lastSys) );
444         GtkIconSize const gtkSizes[] = {
445             GTK_ICON_SIZE_MENU,
446             GTK_ICON_SIZE_SMALL_TOOLBAR,
447             GTK_ICON_SIZE_LARGE_TOOLBAR,
448             GTK_ICON_SIZE_BUTTON,
449             GTK_ICON_SIZE_DND,
450             GTK_ICON_SIZE_DIALOG,
451             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
452                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
453                 GTK_ICON_SIZE_MENU
454         };
455         gchar const *const names[] = {
456             "GTK_ICON_SIZE_MENU",
457             "GTK_ICON_SIZE_SMALL_TOOLBAR",
458             "GTK_ICON_SIZE_LARGE_TOOLBAR",
459             "GTK_ICON_SIZE_BUTTON",
460             "GTK_ICON_SIZE_DND",
461             "GTK_ICON_SIZE_DIALOG",
462             "inkscape-decoration"
463         };
465         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
467         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
468             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
470             g_assert( val_ix < G_N_ELEMENTS(vals) );
472             gint width = 0;
473             gint height = 0;
474             bool used = false;
475             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
476                 vals[val_ix] = std::max(width, height);
477                 lastSys[val_ix] = vals[val_ix];
478                 used = true;
479             }
480             if (dump) {
481                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
482                           i, gtkSizes[i],
483                           ( used ? ' ' : 'X' ), width, height, names[i]);
484             }
485             gchar const *id = GTK_STOCK_OPEN;
486             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
487             if (pb) {
488                 width = gdk_pixbuf_get_width(pb);
489                 height = gdk_pixbuf_get_height(pb);
490                 int newSize = std::max( width, height );
491                 // TODO perhaps check a few more stock icons to get a range on sizes.
492                 if ( newSize > 0 ) {
493                     vals[val_ix] = newSize;
494                 }
495                 if (dump) {
496                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
497                 }
499                 g_object_unref(G_OBJECT(pb));
500             }
501         }
502         //g_object_unref(icon);
503         init = true;
504     }
506     return vals[size];
509 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area)
511     GtkWidget &widget = *GTK_WIDGET(icon);
513     GdkPixbuf *image = GTK_WIDGET_IS_SENSITIVE(&widget) ? icon->pb : icon->pb_faded;
515     if (image) {
516         int const padx = ( ( widget.allocation.width > icon->psize )
517                            ? ( widget.allocation.width - icon->psize ) / 2
518                            : 0 );
519         int const pady = ( ( widget.allocation.height > icon->psize )
520                            ? ( widget.allocation.height - icon->psize ) / 2
521                            : 0 );
523         int const x0 = std::max(area->x, widget.allocation.x + padx);
524         int const y0 = std::max(area->y, widget.allocation.y + pady);
525         int const x1 = std::min(area->x + area->width,  widget.allocation.x + padx + static_cast<int>(icon->psize) );
526         int const y1 = std::min(area->y + area->height, widget.allocation.y + pady + static_cast<int>(icon->psize) );
528         int width = x1 - x0;
529         int height = y1 - y0;
530         // Limit drawing to when we actually have something. Avoids some crashes.
531         if ( (width > 0) && (height > 0) ) {
532             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), NULL, image,
533                             x0 - widget.allocation.x - padx,
534                             y0 - widget.allocation.y - pady,
535                             x0, y0,
536                             width, height,
537                             GDK_RGB_DITHER_NORMAL, x0, y0);
538         }
539     }
542 static guchar *
543 sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
545     gchar *path;
546     guchar *px;
547     GdkPixbuf *pb;
549     path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
550     // TODO: bulia, please look over
551     gsize bytesRead = 0;
552     gsize bytesWritten = 0;
553     GError *error = NULL;
554     gchar *localFilename = g_filename_from_utf8( path,
555                                                  -1,
556                                                  &bytesRead,
557                                                  &bytesWritten,
558                                                  &error);
559     pb = gdk_pixbuf_new_from_file(localFilename, NULL);
560     g_free(localFilename);
561     g_free(path);
562     if (!pb) {
563         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
564         // TODO: bulia, please look over
565         gsize bytesRead = 0;
566         gsize bytesWritten = 0;
567         GError *error = NULL;
568         gchar *localFilename = g_filename_from_utf8( path,
569                                                      -1,
570                                                      &bytesRead,
571                                                      &bytesWritten,
572                                                      &error);
573         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
574         g_free(localFilename);
575         g_free(path);
576     }
577     if (pb) {
578         if (!gdk_pixbuf_get_has_alpha(pb))
579             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
580         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
581              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
582             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
583             g_object_unref(G_OBJECT(pb));
584             pb = spb;
585         }
586         guchar *spx = gdk_pixbuf_get_pixels(pb);
587         int srs = gdk_pixbuf_get_rowstride(pb);
588         px = g_new(guchar, 4 * psize * psize);
589         for (unsigned y = 0; y < psize; y++) {
590             memcpy(px + 4 * y * psize, spx + y * srs, 4 * psize);
591         }
592         g_object_unref(G_OBJECT(pb));
594         return px;
595     }
597     return NULL;
600 // takes doc, root, icon, and icon name to produce pixels
601 extern "C" guchar *
602 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
603                   gchar const *name, unsigned psize )
605     gint const dump = prefs_get_int_attribute_limited( "debug.icons", "dumpSvg", 0, 0, 1 );
606     guchar *px = NULL;
608     if (doc) {
609         SPObject *object = doc->getObjectById(name);
610         if (object && SP_IS_ITEM(object)) {
611             /* Find bbox in document */
612             NR::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
613             NR::Maybe<NR::Rect> dbox = SP_ITEM(object)->getBounds(i2doc);
615             if ( SP_OBJECT_PARENT(object) == NULL )
616             {
617                 dbox = NR::Rect(NR::Point(0, 0),
618                                 NR::Point(sp_document_width(doc), sp_document_height(doc)));
619             }
621             /* This is in document coordinates, i.e. pixels */
622             if ( dbox && !dbox->isEmpty() ) {
623                 NRGC gc(NULL);
624                 /* Update to renderable state */
625                 double sf = 1.0;
626                 nr_arena_item_set_transform(root, NR::Matrix(NR::scale(sf, sf)));
627                 gc.transform.set_identity();
628                 nr_arena_item_invoke_update( root, NULL, &gc,
629                                              NR_ARENA_ITEM_STATE_ALL,
630                                              NR_ARENA_ITEM_STATE_NONE );
631                 /* Item integer bbox in points */
632                 NRRectL ibox;
633                 ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
634                 ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
635                 ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
636                 ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
638                 if ( dump ) {
639                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
640                 }
642                 /* Find button visible area */
643                 int width = ibox.x1 - ibox.x0;
644                 int height = ibox.y1 - ibox.y0;
646                 if ( dump ) {
647                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
648                 }
650                 {
651                     int block = std::max(width, height);
652                     if (block != static_cast<int>(psize) ) {
653                         if ( dump ) {
654                             g_message("      resizing" );
655                         }
656                         sf = (double)psize / (double)block;
658                         nr_arena_item_set_transform(root, NR::Matrix(NR::scale(sf, sf)));
659                         gc.transform.set_identity();
660                         nr_arena_item_invoke_update( root, NULL, &gc,
661                                                      NR_ARENA_ITEM_STATE_ALL,
662                                                      NR_ARENA_ITEM_STATE_NONE );
663                         /* Item integer bbox in points */
664                         ibox.x0 = (int) floor(sf * dbox->min()[NR::X] + 0.5);
665                         ibox.y0 = (int) floor(sf * dbox->min()[NR::Y] + 0.5);
666                         ibox.x1 = (int) floor(sf * dbox->max()[NR::X] + 0.5);
667                         ibox.y1 = (int) floor(sf * dbox->max()[NR::Y] + 0.5);
669                         if ( dump ) {
670                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
671                         }
673                         /* Find button visible area */
674                         width = ibox.x1 - ibox.x0;
675                         height = ibox.y1 - ibox.y0;
676                         if ( dump ) {
677                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
678                         }
679                     }
680                 }
682                 int dx, dy;
683                 //dx = (psize - width) / 2;
684                 //dy = (psize - height) / 2;
685                 dx=dy=psize;
686                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
687                 dy=(dy-height)/2;
688                 NRRectL area;
689                 area.x0 = ibox.x0 - dx;
690                 area.y0 = ibox.y0 - dy;
691                 area.x1 = area.x0 + psize;
692                 area.y1 = area.y0 + psize;
693                 /* Actual renderable area */
694                 NRRectL ua;
695                 ua.x0 = MAX(ibox.x0, area.x0);
696                 ua.y0 = MAX(ibox.y0, area.y0);
697                 ua.x1 = MIN(ibox.x1, area.x1);
698                 ua.y1 = MIN(ibox.y1, area.y1);
700                 if ( dump ) {
701                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
702                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
703                 }
704                 /* Set up pixblock */
705                 px = g_new(guchar, 4 * psize * psize);
706                 memset(px, 0x00, 4 * psize * psize);
707                 /* Render */
708                 NRPixBlock B;
709                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
710                                           ua.x0, ua.y0, ua.x1, ua.y1,
711                                           px + 4 * psize * (ua.y0 - area.y0) +
712                                           4 * (ua.x0 - area.x0),
713                                           4 * psize, FALSE, FALSE );
714                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
715                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
716                 nr_pixblock_release(&B);
718                 gint useOverlay = prefs_get_int_attribute_limited( "debug.icons", "overlaySvg", 0, 0, 1 );
719                 if ( useOverlay ) {
720                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
721                 }
722             }
723         }
724     }
726     return px;
727 } // end of sp_icon_doc_icon()
731 struct svg_doc_cache_t
733     SPDocument *doc;
734     NRArenaItem *root;
735 };
737 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
738 static std::map<Glib::ustring, guchar *> px_cache;
740 static Glib::ustring icon_cache_key(gchar const *name,
741                                     unsigned lsize, unsigned psize)
743     Glib::ustring key=name;
744     key += ":";
745     key += lsize;
746     key += ":";
747     key += psize;
748     return key;
751 static guchar *get_cached_pixels(Glib::ustring const &key) {
752     std::map<Glib::ustring, guchar *>::iterator found=px_cache.find(key);
753     if ( found != px_cache.end() ) {
754         return found->second;
755     }
756     return NULL;
759 static guchar *load_svg_pixels(gchar const *name,
760                                unsigned /*lsize*/, unsigned psize)
762     SPDocument *doc = NULL;
763     NRArenaItem *root = NULL;
764     svg_doc_cache_t *info = NULL;
766     // Fall back from user prefs dir into system locations.
767     Glib::ustring iconsvg = name;
768     iconsvg += ".svg";
769     std::list<gchar *> sources;
770     sources.push_back(g_build_filename(profile_path("icons"),iconsvg.c_str(), NULL));
771     sources.push_back(g_build_filename(profile_path("icons"),"icons.svg", NULL));
772     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, iconsvg.c_str(), NULL));
773     sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
775     // Try each document in turn until we successfully load the icon from one
776     guchar *px=NULL;
777     while ( !sources.empty() && !px ) {
778         gchar *doc_filename = sources.front();
780         // Did we already load this doc?
781         Glib::ustring key(doc_filename);
782         info = 0;
783         {
784             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
785             if ( i != doc_cache.end() ) {
786                 info = i->second;
787             }
788         }
790         /* Try to load from document. */
791         if (!info &&
792             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
793             (doc = sp_document_new( doc_filename, FALSE )) ) {
795             // prep the document
796             sp_document_ensure_up_to_date(doc);
797             /* Create new arena */
798             NRArena *arena = NRArena::create();
799             /* Create ArenaItem and set transform */
800             unsigned visionkey = sp_item_display_key_new(1);
801             /* fixme: Memory manage root if needed (Lauris) */
802             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
803                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
805             // store into the cache
806             info = new svg_doc_cache_t;
807             g_assert(info);
809             info->doc=doc;
810             info->root=root;
811             doc_cache[key]=info;
812         }
813         if (info) {
814             doc=info->doc;
815             root=info->root;
816         }
818         // toss the filename
819         g_free(doc_filename);
820         sources.pop_front();
822         // move on to the next document if we couldn't get anything
823         if (!info && !doc) continue;
825         px = sp_icon_doc_icon( doc, root, name, psize );
826     }
828     return px;
831 // returns true if icon needed preloading, false if nothing was done
832 static bool prerender_icon(gchar const *name, unsigned lsize, unsigned psize)
834     Glib::ustring key = icon_cache_key(name, lsize, psize);
835     guchar *px = get_cached_pixels(key);
836     if (px) {
837         return false;
838     } else {
839         px = load_svg_pixels(name, lsize, psize);
840         if (px) {
841             px_cache[key] = px;
842         }
843         return true;
844     }
847 static guchar *
848 sp_icon_image_load_svg(gchar const *name, unsigned lsize, unsigned psize)
850     Glib::ustring key = icon_cache_key(name, lsize, psize);
852     // did we already load this icon at this scale/size?
853     guchar *px = get_cached_pixels(key);
854     if (!px) {
855         px = load_svg_pixels(name, lsize, psize);
856         if (px) {
857             px_cache[key] = px;
858         }
859     }
860     return px;
863 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
864                             unsigned r, unsigned g, unsigned b)
866     for ( int y = 0; y < height; y += 4 ) {
867         guchar *ptr = px + y * stride;
868         for ( int x = 0; x < width; x += 4 ) {
869             *(ptr++) = r;
870             *(ptr++) = g;
871             *(ptr++) = b;
872             *(ptr++) = 0xff;
874             ptr += 4 * 3;
875         }
876     }
878     if ( width > 1 && height > 1 ) {
879         // point at the last pixel
880         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * 4);
882         if ( width > 2 ) {
883             px[4] = r;
884             px[5] = g;
885             px[6] = b;
886             px[7] = 0xff;
888             ptr[-12] = r;
889             ptr[-11] = g;
890             ptr[-10] = b;
891             ptr[-9] = 0xff;
892         }
894         ptr[-4] = r;
895         ptr[-3] = g;
896         ptr[-2] = b;
897         ptr[-1] = 0xff;
899         px[0 + stride] = r;
900         px[1 + stride] = g;
901         px[2 + stride] = b;
902         px[3 + stride] = 0xff;
904         ptr[0 - stride] = r;
905         ptr[1 - stride] = g;
906         ptr[2 - stride] = b;
907         ptr[3 - stride] = 0xff;
909         if ( height > 2 ) {
910             ptr[0 - stride * 3] = r;
911             ptr[1 - stride * 3] = g;
912             ptr[2 - stride * 3] = b;
913             ptr[3 - stride * 3] = 0xff;
914         }
915     }
918 class preRenderItem
920 public:
921     preRenderItem( Inkscape::IconSize lsize, gchar const *name ) :
922         _lsize( lsize ),
923         _name( name )
924     {}
925     Inkscape::IconSize _lsize;
926     Glib::ustring _name;
927 };
930 #include <queue>
932 static std::queue<preRenderItem> pendingRenders;
933 static bool callbackHooked = false;
935 static void addPreRender( Inkscape::IconSize lsize, gchar const *name )
938     if ( !callbackHooked )
939     {
940         callbackHooked = true;
941         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
942     }
944     pendingRenders.push(preRenderItem(lsize, name));
947 gboolean icon_prerender_task(gpointer /*data*/) {
948     if (!pendingRenders.empty()) {
949         preRenderItem single=pendingRenders.front();
950         pendingRenders.pop();
951         int psize = sp_icon_get_phys_size(single._lsize);
952         prerender_icon(single._name.c_str(), single._lsize, psize);
953     }
955     if (!pendingRenders.empty()) {
956         return TRUE;
957     } else {
958         callbackHooked = false;
959         return FALSE;
960     }
963 /*
964   Local Variables:
965   mode:c++
966   c-file-style:"stroustrup"
967   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
968   indent-tabs-mode:nil
969   fill-column:99
970   End:
971 */
972 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :