Code

Restoring needed icon rendering code. Addresses bug #363781.
[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/gtk.h>
21 #include <gtkmm.h>
23 #include "path-prefix.h"
24 #include "preferences.h"
25 #include "inkscape.h"
26 #include "document.h"
27 #include "sp-item.h"
28 #include "display/nr-arena.h"
29 #include "display/nr-arena-item.h"
30 #include "io/sys.h"
32 #include "icon.h"
34 static gboolean icon_prerender_task(gpointer data);
36 static void addPreRender( GtkIconSize lsize, gchar const *name );
38 static void sp_icon_class_init(SPIconClass *klass);
39 static void sp_icon_init(SPIcon *icon);
40 static void sp_icon_dispose(GObject *object);
42 static void sp_icon_reset(SPIcon *icon);
43 static void sp_icon_clear(SPIcon *icon);
45 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
46 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
47 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
49 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
51 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
52 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
53 static void sp_icon_theme_changed( SPIcon *icon );
55 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
56 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
58 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
59                                     unsigned r, unsigned g, unsigned b );
61 static void injectCustomSize();
63 static GtkWidgetClass *parent_class;
65 static bool sizeDirty = true;
67 static bool sizeMapDone = false;
68 static GtkIconSize iconSizeLookup[] = {
69     GTK_ICON_SIZE_INVALID,
70     GTK_ICON_SIZE_MENU,
71     GTK_ICON_SIZE_SMALL_TOOLBAR,
72     GTK_ICON_SIZE_LARGE_TOOLBAR,
73     GTK_ICON_SIZE_BUTTON,
74     GTK_ICON_SIZE_DND,
75     GTK_ICON_SIZE_DIALOG,
76     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
77 };
79 static std::map<Glib::ustring, Glib::ustring> legacyNames;
81 class IconCacheItem
82 {
83 public:
84     IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
85         _lsize( lsize ),
86         _pb( pb )
87     {}
88     GtkIconSize _lsize;
89     GdkPixbuf* _pb;
90 };
92 static Glib::RefPtr<Gtk::IconFactory> inkyIcons;
93 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
95 GType
96 sp_icon_get_type()
97 {
98     //TODO: switch to GObject
99     // GtkType and such calls were deprecated a while back with the
100     // introduction of GObject as a separate layer, with GType instead. --JonCruz
102     static GType type = 0;
103     if (!type) {
104         GTypeInfo info = {
105             sizeof(SPIconClass),
106             NULL,
107             NULL,
108             (GClassInitFunc) sp_icon_class_init,
109             NULL,
110             NULL,
111             sizeof(SPIcon),
112             0,
113             (GInstanceInitFunc) sp_icon_init,
114             NULL
115         };
116         type = g_type_register_static(GTK_TYPE_WIDGET, "SPIcon", &info, (GTypeFlags)0);
117     }
118     return type;
121 static void
122 sp_icon_class_init(SPIconClass *klass)
124     GObjectClass *object_class;
125     GtkWidgetClass *widget_class;
127     object_class = (GObjectClass *) klass;
128     widget_class = (GtkWidgetClass *) klass;
130     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
132     object_class->dispose = sp_icon_dispose;
134     widget_class->size_request = sp_icon_size_request;
135     widget_class->size_allocate = sp_icon_size_allocate;
136     widget_class->expose_event = sp_icon_expose;
137     widget_class->screen_changed = sp_icon_screen_changed;
138     widget_class->style_set = sp_icon_style_set;
142 static void
143 sp_icon_init(SPIcon *icon)
145     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
146     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
147     icon->psize = 0;
148     icon->name = 0;
149     icon->pb = 0;
152 static void
153 sp_icon_dispose(GObject *object)
155     SPIcon *icon = SP_ICON(object);
156     sp_icon_clear(icon);
157     if ( icon->name ) {
158         g_free( icon->name );
159         icon->name = 0;
160     }
162     ((GObjectClass *) (parent_class))->dispose(object);
165 static void sp_icon_reset( SPIcon *icon ) {
166     icon->psize = 0;
167     sp_icon_clear(icon);
170 static void sp_icon_clear( SPIcon *icon ) {
171     if (icon->pb) {
172         g_object_unref(G_OBJECT(icon->pb));
173         icon->pb = NULL;
174     }
177 static void
178 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
180     SPIcon const *icon = SP_ICON(widget);
182     int const size = ( icon->psize
183                        ? icon->psize
184                        : sp_icon_get_phys_size(icon->lsize) );
185     requisition->width = size;
186     requisition->height = size;
189 static void
190 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
192     widget->allocation = *allocation;
194     if (GTK_WIDGET_DRAWABLE(widget)) {
195         gtk_widget_queue_draw(widget);
196     }
199 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
201     if ( GTK_WIDGET_DRAWABLE(widget) ) {
202         SPIcon *icon = SP_ICON(widget);
203         if ( !icon->pb ) {
204             sp_icon_fetch_pixbuf( icon );
205         }
207         sp_icon_paint(SP_ICON(widget), &event->area);
208     }
210     return TRUE;
213 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize );
215 // PUBLIC CALL:
216 void sp_icon_fetch_pixbuf( SPIcon *icon )
218     if ( icon ) {
219         if ( !icon->pb ) {
220             icon->psize = sp_icon_get_phys_size(icon->lsize);
221             icon->pb = renderup(icon->name, icon->lsize, icon->psize);
222         }
223     }
226 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize ) {
227     GtkIconTheme *theme = gtk_icon_theme_get_default();
229     GdkPixbuf *pb = 0;
230     if (gtk_icon_theme_has_icon(theme, name)) {
231         pb = gtk_icon_theme_load_icon(theme, name, psize, (GtkIconLookupFlags) 0, NULL);
232     }
233     if (!pb) {
234         pb = sp_icon_image_load_svg( name, Inkscape::getRegisteredIconSize(lsize), psize );
235         if (!pb && (legacyNames.find(name) != legacyNames.end())) {
236             if ( Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg") ) {
237                 g_message("Checking fallback [%s]->[%s]", name, legacyNames[name].c_str());
238             }
239             pb = sp_icon_image_load_svg( legacyNames[name].c_str(), Inkscape::getRegisteredIconSize(lsize), psize );
240         }
242         // if this was loaded from SVG, add it as a builtin icon
243         if (pb) {
244             gtk_icon_theme_add_builtin_icon(name, psize, pb);
245         }
246     }
247     if (!pb) {
248         pb = sp_icon_image_load_pixmap( name, lsize, psize );
249     }
250     if ( !pb ) {
251         // TODO: We should do something more useful if we can't load the image.
252         g_warning ("failed to load icon '%s'", name);
253     }
254     return pb;
257 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
259     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
260         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
261     }
262     SPIcon *icon = SP_ICON(widget);
263     sp_icon_theme_changed(icon);
266 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
268     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
269         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
270     }
271     SPIcon *icon = SP_ICON(widget);
272     sp_icon_theme_changed(icon);
275 static void sp_icon_theme_changed( SPIcon *icon )
277     //g_message("Got a change bump for this icon");
278     sizeDirty = true;
279     sp_icon_reset(icon);
280     gtk_widget_queue_draw( GTK_WIDGET(icon) );
284 static void imageMapCB(GtkWidget* widget, gpointer user_data);
285 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
286 static void populate_placeholder_icon(gchar const* name, GtkIconSize size);
287 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
288 static Glib::ustring icon_cache_key(gchar const *name, unsigned lsize, unsigned psize);
289 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
291 static void setupLegacyNaming() {
292     legacyNames["document-import"] ="file_import";
293     legacyNames["document-export"] ="file_export";
294     legacyNames["document-import-ocal"] ="ocal_import";
295     legacyNames["document-export-ocal"] ="ocal_export";
296     legacyNames["document-metadata"] ="document_metadata";
297     legacyNames["dialog-input-devices"] ="input_devices";
298     legacyNames["edit-duplicate"] ="edit_duplicate";
299     legacyNames["edit-clone"] ="edit_clone";
300     legacyNames["edit-clone-unlink"] ="edit_unlink_clone";
301     legacyNames["edit-select-original"] ="edit_select_original";
302     legacyNames["edit-undo-history"] ="edit_undo_history";
303     legacyNames["edit-paste-in-place"] ="selection_paste_in_place";
304     legacyNames["edit-paste-style"] ="selection_paste_style";
305     legacyNames["selection-make-bitmap-copy"] ="selection_bitmap";
306     legacyNames["edit-select-all"] ="selection_select_all";
307     legacyNames["edit-select-all-layers"] ="selection_select_all_in_all_layers";
308     legacyNames["edit-select-invert"] ="selection_invert";
309     legacyNames["edit-select-none"] ="selection_deselect";
310     legacyNames["dialog-xml-editor"] ="xml_editor";
311     legacyNames["zoom-original"] ="zoom_1_to_1";
312     legacyNames["zoom-half-size"] ="zoom_1_to_2";
313     legacyNames["zoom-double-size"] ="zoom_2_to_1";
314     legacyNames["zoom-fit-selection"] ="zoom_select";
315     legacyNames["zoom-fit-drawing"] ="zoom_draw";
316     legacyNames["zoom-fit-page"] ="zoom_page";
317     legacyNames["zoom-fit-width"] ="zoom_pagewidth";
318     legacyNames["zoom-previous"] ="zoom_previous";
319     legacyNames["zoom-next"] ="zoom_next";
320     legacyNames["zoom-in"] ="zoom_in";
321     legacyNames["zoom-out"] ="zoom_out";
322     legacyNames["show-grid"] ="grid";
323     legacyNames["show-guides"] ="guides";
324     legacyNames["color-management"] ="color_management";
325     legacyNames["show-dialogs"] ="dialog_toggle";
326     legacyNames["dialog-messages"] ="messages";
327     legacyNames["dialog-scripts"] ="scripts";
328     legacyNames["window-previous"] ="window_previous";
329     legacyNames["window-next"] ="window_next";
330     legacyNames["dialog-icon-preview"] ="view_icon_preview";
331     legacyNames["window-new"] ="view_new";
332     legacyNames["view-fullscreen"] ="fullscreen";
333     legacyNames["layer-new"] ="new_layer";
334     legacyNames["layer-rename"] ="rename_layer";
335     legacyNames["layer-previous"] ="switch_to_layer_above";
336     legacyNames["layer-next"] ="switch_to_layer_below";
337     legacyNames["selection-move-to-layer-above"] ="move_selection_above";
338     legacyNames["selection-move-to-layer-below"] ="move_selection_below";
339     legacyNames["layer-raise"] ="raise_layer";
340     legacyNames["layer-lower"] ="lower_layer";
341     legacyNames["layer-top"] ="layer_to_top";
342     legacyNames["layer-bottom"] ="layer_to_bottom";
343     legacyNames["layer-delete"] ="delete_layer";
344     legacyNames["dialog-layers"] ="layers";
345     legacyNames["dialog-fill-and-stroke"] ="fill_and_stroke";
346     legacyNames["dialog-object-properties"] ="dialog_item_properties";
347     legacyNames["object-group"] ="selection_group";
348     legacyNames["object-ungroup"] ="selection_ungroup";
349     legacyNames["selection-raise"] ="selection_up";
350     legacyNames["selection-lower"] ="selection_down";
351     legacyNames["selection-top"] ="selection_top";
352     legacyNames["selection-bottom"] ="selection_bot";
353     legacyNames["object-rotate-left"] ="object_rotate_90_CCW";
354     legacyNames["object-rotate-right"] ="object_rotate_90_CW";
355     legacyNames["object-flip-horizontal"] ="object_flip_hor";
356     legacyNames["object-flip-vertical"] ="object_flip_ver";
357     legacyNames["dialog-transform"] ="object_trans";
358     legacyNames["dialog-align-and-distribute"] ="object_align";
359     legacyNames["dialog-rows-and-columns"] ="grid_arrange";
360     legacyNames["object-to-path"] ="object_tocurve";
361     legacyNames["stroke-to-path"] ="stroke_tocurve";
362     legacyNames["bitmap-trace"] ="selection_trace";
363     legacyNames["path-union"] ="union";
364     legacyNames["path-difference"] ="difference";
365     legacyNames["path-intersection"] ="intersection";
366     legacyNames["path-exclusion"] ="exclusion";
367     legacyNames["path-division"] ="division";
368     legacyNames["path-cut"] ="cut_path";
369     legacyNames["path-combine"] ="selection_combine";
370     legacyNames["path-break-apart"] ="selection_break";
371     legacyNames["path-outset"] ="outset_path";
372     legacyNames["path-inset"] ="inset_path";
373     legacyNames["path-offset-dynamic"] ="dynamic_offset";
374     legacyNames["path-offset-linked"] ="linked_offset";
375     legacyNames["path-simplify"] ="simplify";
376     legacyNames["path-reverse"] ="selection_reverse";
377     legacyNames["dialog-text-and-font"] ="object_font";
378     legacyNames["text-put-on-path"] ="put_on_path";
379     legacyNames["text-remove-from-path"] ="remove_from_path";
380     legacyNames["text-flow-into-frame"] ="flow_into_frame";
381     legacyNames["text-unflow"] ="unflow";
382     legacyNames["text-convert-to-regular"] ="convert_to_text";
383     legacyNames["text-unkern"] ="remove_manual_kerns";
384     legacyNames["help-keyboard-shortcuts"] ="help_keys";
385     legacyNames["help-contents"] ="help_tutorials";
386     legacyNames["inkscape"] ="inkscape_options";
387     legacyNames["dialog-memory"] ="about_memory";
388     legacyNames["tool-pointer"] ="draw_select";
389     legacyNames["tool-node-editor"] ="draw_node";
390     legacyNames["tool-tweak"] ="draw_tweak";
391     legacyNames["zoom"] ="draw_zoom";
392     legacyNames["draw-rectangle"] ="draw_rect";
393     legacyNames["draw-cuboid"] ="draw_3dbox";
394     legacyNames["draw-ellipse"] ="draw_arc";
395     legacyNames["draw-polygon-star"] ="draw_star";
396     legacyNames["draw-spiral"] ="draw_spiral";
397     legacyNames["draw-freehand"] ="draw_freehand";
398     legacyNames["draw-path"] ="draw_pen";
399     legacyNames["draw-calligraphic"] ="draw_calligraphic";
400     legacyNames["draw-eraser"] ="draw_erase";
401     legacyNames["color-fill"] ="draw_paintbucket";
402     legacyNames["draw-text"] ="draw_text";
403     legacyNames["draw-connector"] ="draw_connector";
404     legacyNames["color-gradient"] ="draw_gradient";
405     legacyNames["color-picker"] ="draw_dropper";
406     legacyNames["transform-affect-stroke"] ="transform_stroke";
407     legacyNames["transform-affect-rounded-corners"] ="transform_corners";
408     legacyNames["transform-affect-gradient"] ="transform_gradient";
409     legacyNames["transform-affect-pattern"] ="transform_pattern";
410     legacyNames["node-add"] ="node_insert";
411     legacyNames["node-delete"] ="node_delete";
412     legacyNames["node-join"] ="node_join";
413     legacyNames["node-break"] ="node_break";
414     legacyNames["node-join-segment"] ="node_join_segment";
415     legacyNames["node-delete-segment"] ="node_delete_segment";
416     legacyNames["node-type-cusp"] ="node_cusp";
417     legacyNames["node-type-smooth"] ="node_smooth";
418     legacyNames["node-type-symmetric"] ="node_symmetric";
419     legacyNames["node-type-auto-smooth"] ="node_auto";
420     legacyNames["node-segment-curve"] ="node_curve";
421     legacyNames["node-segment-line"] ="node_line";
422     legacyNames["show-node-handles"] ="nodes_show_handles";
423     legacyNames["path-effect-parameter-next"] ="edit_next_parameter";
424     legacyNames["show-path-outline"] ="nodes_show_helperpath";
425     legacyNames["path-clip-edit"] ="nodeedit-clippath";
426     legacyNames["path-mask-edit"] ="nodeedit-mask";
427     legacyNames["node-type-cusp"] ="node_cusp";
428     legacyNames["object-tweak-push"] ="tweak_move_mode";
429     legacyNames["object-tweak-attract"] ="tweak_move_mode_inout";
430     legacyNames["object-tweak-randomize"] ="tweak_move_mode_jitter";
431     legacyNames["object-tweak-shrink"] ="tweak_scale_mode";
432     legacyNames["object-tweak-rotate"] ="tweak_rotate_mode";
433     legacyNames["object-tweak-duplicate"] ="tweak_moreless_mode";
434     legacyNames["object-tweak-push"] ="tweak_move_mode";
435     legacyNames["path-tweak-push"] ="tweak_push_mode";
436     legacyNames["path-tweak-shrink"] ="tweak_shrink_mode";
437     legacyNames["path-tweak-attract"] ="tweak_attract_mode";
438     legacyNames["path-tweak-roughen"] ="tweak_roughen_mode";
439     legacyNames["object-tweak-paint"] ="tweak_colorpaint_mode";
440     legacyNames["object-tweak-jitter-color"] ="tweak_colorjitter_mode";
441     legacyNames["object-tweak-blur"] ="tweak_blur_mode";
442     legacyNames["rectangle-make-corners-sharp"] ="squared_corner";
443     legacyNames["perspective-parallel"] ="toggle_vp_x";
444     legacyNames["draw-ellipse-whole"] ="reset_circle";
445     legacyNames["draw-ellipse-segment"] ="circle_closed_arc";
446     legacyNames["draw-ellipse-arc"] ="circle_open_arc";
447     legacyNames["draw-polygon"] ="star_flat";
448     legacyNames["draw-star"] ="star_angled";
449     legacyNames["path-mode-bezier"] ="bezier_mode";
450     legacyNames["path-mode-spiro"] ="spiro_splines_mode";
451     legacyNames["path-mode-polyline"] ="polylines_mode";
452     legacyNames["path-mode-polyline-paraxial"] ="paraxial_lines_mode";
453     legacyNames["draw-use-tilt"] ="guse_tilt";
454     legacyNames["draw-use-pressure"] ="guse_pressure";
455     legacyNames["draw-trace-background"] ="trace_background";
456     legacyNames["draw-eraser-delete-objects"] ="delete_object";
457     legacyNames["format-text-direction-vertical"] ="writing_mode_tb";
458     legacyNames["format-text-direction-horizontal"] ="writing_mode_lr";
459     legacyNames["connector-avoid"] ="connector_avoid";
460     legacyNames["connector-ignore"] ="connector_ignore";
461     legacyNames["object-fill"] ="controls_fill";
462     legacyNames["object-stroke"] ="controls_stroke";
463     legacyNames["snap"] ="toggle_snap_global";
464     legacyNames["snap-bounding-box"] ="toggle_snap_bbox";
465     legacyNames["snap-bounding-box-edges"] ="toggle_snap_to_bbox_path";
466     legacyNames["snap-bounding-box-corners"] ="toggle_snap_to_bbox_node";
467     legacyNames["snap-bounding-box-midpoints"] ="toggle_snap_to_bbox_edge_midpoints";
468     legacyNames["snap-bounding-box-center"] ="toggle_snap_to_bbox_midpoints";
469     legacyNames["snap-nodes"] ="toggle_snap_nodes";
470     legacyNames["snap-nodes-path"] ="toggle_snap_to_paths";
471     legacyNames["snap-nodes-cusp"] ="toggle_snap_to_nodes";
472     legacyNames["snap-nodes-smooth"] ="toggle_snap_to_smooth_nodes";
473     legacyNames["snap-nodes-midpoint"] ="toggle_snap_to_midpoints";
474     legacyNames["snap-nodes-intersection"] ="toggle_snap_to_path_intersections";
475     legacyNames["snap-nodes-center"] ="toggle_snap_to_bbox_midpoints-3";
476     legacyNames["snap-nodes-rotation-center"] ="toggle_snap_center";
477     legacyNames["snap-page"] ="toggle_snap_page_border";
478     legacyNames["snap-grid-guide-intersections"] ="toggle_snap_grid_guide_intersections";
479     legacyNames["align-horizontal-right-to-anchor"] ="al_left_out";
480     legacyNames["align-horizontal-left"] ="al_left_in";
481     legacyNames["align-horizontal-center"] ="al_center_hor";
482     legacyNames["align-horizontal-right"] ="al_right_in";
483     legacyNames["align-horizontal-left-to-anchor"] ="al_right_out";
484     legacyNames["align-horizontal-baseline"] ="al_baselines_vert";
485     legacyNames["align-vertical-bottom-to-anchor"] ="al_top_out";
486     legacyNames["align-vertical-top"] ="al_top_in";
487     legacyNames["align-vertical-center"] ="al_center_ver";
488     legacyNames["align-vertical-bottom"] ="al_bottom_in";
489     legacyNames["align-vertical-top-to-anchor"] ="al_bottom_out";
490     legacyNames["align-vertical-baseline"] ="al_baselines_hor";
491     legacyNames["distribute-horizontal-left"] ="distribute_left";
492     legacyNames["distribute-horizontal-center"] ="distribute_hcentre";
493     legacyNames["distribute-horizontal-right"] ="distribute_right";
494     legacyNames["distribute-horizontal-baseline"] ="distribute_baselines_hor";
495     legacyNames["distribute-vertical-bottom"] ="distribute_bottom";
496     legacyNames["distribute-vertical-center"] ="distribute_vcentre";
497     legacyNames["distribute-vertical-top"] ="distribute_top";
498     legacyNames["distribute-vertical-baseline"] ="distribute_baselines_vert";
499     legacyNames["distribute-randomize"] ="distribute_randomize";
500     legacyNames["distribute-unclump"] ="unclump";
501     legacyNames["distribute-graph"] ="graph_layout";
502     legacyNames["distribute-graph-directed"] ="directed_graph";
503     legacyNames["distribute-remove-overlaps"] ="remove_overlaps";
504     legacyNames["align-horizontal-node"] ="node_valign";
505     legacyNames["align-vertical-node"] ="node_halign";
506     legacyNames["distribute-vertical-node"] ="node_vdistribute";
507     legacyNames["distribute-horizontal-node"] ="node_hdistribute";
508     legacyNames["xml-element-new"] ="add_xml_element_node";
509     legacyNames["xml-text-new"] ="add_xml_text_node";
510     legacyNames["xml-node-delete"] ="delete_xml_node";
511     legacyNames["xml-node-duplicate"] ="duplicate_xml_node";
512     legacyNames["xml-attribute-delete"] ="delete_xml_attribute";
513     legacyNames["transform-move-horizontal"] ="arrows_hor";
514     legacyNames["transform-move-vertical"] ="arrows_ver";
515     legacyNames["transform-scale-horizontal"] ="transform_scale_hor";
516     legacyNames["transform-scale-vertical"] ="transform_scale_ver";
517     legacyNames["transform-skew-horizontal"] ="transform_scew_hor";
518     legacyNames["transform-skew-vertical"] ="transform_scew_ver";
519     legacyNames["object-fill"] ="properties_fill";
520     legacyNames["object-stroke"] ="properties_stroke_paint";
521     legacyNames["object-stroke-style"] ="properties_stroke";
522     legacyNames["paint-none"] ="fill_none";
523     legacyNames["paint-solid"] ="fill_solid";
524     legacyNames["paint-gradient-linear"] ="fill_gradient";
525     legacyNames["paint-gradient-radial"] ="fill_radial";
526     legacyNames["paint-pattern"] ="fill_pattern";
527     legacyNames["paint-unknown"] ="fill_unset";
528     legacyNames["fill-rule-even-odd"] ="fillrule_evenodd";
529     legacyNames["fill-rule-nonzero"] ="fillrule_nonzero";
530     legacyNames["stroke-join-miter"] ="join_miter";
531     legacyNames["stroke-join-bevel"] ="join_bevel";
532     legacyNames["stroke-join-round"] ="join_round";
533     legacyNames["stroke-cap-butt"] ="cap_butt";
534     legacyNames["stroke-cap-square"] ="cap_square";
535     legacyNames["stroke-cap-round"] ="cap_round";
536     legacyNames["guides"] ="guide";
537     legacyNames["grid-rectangular"] ="grid_xy";
538     legacyNames["grid-axonometric"] ="grid_axonom";
539     legacyNames["object-visible"] ="visible";
540     legacyNames["object-hidden"] ="hidden";
541     legacyNames["object-unlocked"] ="lock_unlocked";
542     legacyNames["object-locked"] ="width_height_lock";
543     legacyNames["zoom"] ="sticky_zoom";
546 static GtkWidget *
547 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
549     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
550     static bool dump = prefs->getBool( "/debug/icons/dumpGtk");
552     GtkWidget *widget = 0;
553     gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
554     if ( !sizeMapDone ) {
555         injectCustomSize();
556     }
557     GtkIconSize mappedSize = iconSizeLookup[trySize];
559     GtkStockItem stock;
560     gboolean stockFound = gtk_stock_lookup( name, &stock );
562     GtkWidget *img = 0;
563     if ( legacyNames.empty() ) {
564         setupLegacyNaming();
565     }
567     if ( stockFound ) {
568         img = gtk_image_new_from_stock( name, mappedSize );
569     } else {
570         img = gtk_image_new_from_icon_name( name, mappedSize );
571         if ( dump ) {
572             g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
573             GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
574             g_message("      Type is %d  %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
575         }
576     }
578     if ( img ) {
579         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
580         if ( type == GTK_IMAGE_STOCK ) {
581             if ( !stockFound ) {
582                 // It's not showing as a stock ID, so assume it will be present internally
583                 populate_placeholder_icon( name, mappedSize );
584                 addPreRender( mappedSize, name );
586                 // Add a hook to render if set visible before prerender is done.
587                 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
588                 if ( dump ) {
589                     g_message("      connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
590                 }
591             }
592             widget = GTK_WIDGET(img);
593             img = 0;
594             if ( dump ) {
595                 g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK) %s  on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
596             }
597         } else if ( type == GTK_IMAGE_ICON_NAME ) {
598             widget = GTK_WIDGET(img);
599             img = 0;
601 //             if (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name)) {
602 //                 // TODO temporary work-around. until background rendering is restored.
603 //                 int psize = sp_icon_get_phys_size(lsize);
604 //                 renderup(name, lsize, psize);
605 //             }
607             // Add a hook to render if set visible before prerender is done.
608             g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
610             if ( prefs->getBool("/options/iconrender/named_nodelay") ) {
611                 int psize = sp_icon_get_phys_size(lsize);
612                 prerender_icon(name, mappedSize, psize);
613             } else {
614                 addPreRender( mappedSize, name );
615             }
616         } else {
617             if ( dump ) {
618                 g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
619             }
620             //g_object_unref( (GObject *)img );
621             img = 0;
622         }
623     }
625     if ( !widget ) {
626         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
627         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
628         icon->lsize = lsize;
629         icon->name = g_strdup(name);
630         icon->psize = sp_icon_get_phys_size(lsize);
632         widget = GTK_WIDGET(icon);
633     }
635     return widget;
638 GtkWidget *
639 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
641     return sp_icon_new_full( lsize, name );
644 // PUBLIC CALL:
645 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
647     Gtk::Widget *result = 0;
648     GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
650     if ( widget ) {
651         if ( GTK_IS_IMAGE(widget) ) {
652             GtkImage *img = GTK_IMAGE(widget);
653             result = Glib::wrap( img );
654         } else {
655             result = Glib::wrap( widget );
656         }
657     }
659     return result;
662 GtkIconSize
663 sp_icon_get_gtk_size(int size)
665     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
666     size = CLAMP(size, 4, 63);
667     if (!sizemap[size]) {
668         static int count = 0;
669         char c[64];
670         g_snprintf(c, 64, "InkscapeIcon%d", count++);
671         sizemap[size] = gtk_icon_size_register(c, size, size);
672     }
673     return sizemap[size];
677 static void injectCustomSize()
679     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
680     if ( !sizeMapDone )
681     {
682         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
683         bool dump = prefs->getBool( "/debug/icons/dumpDefault");
684         gint width = 0;
685         gint height = 0;
686         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
687             gint newWidth = ((width * 3) / 4);
688             gint newHeight = ((height * 3) / 4);
689             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
690             if ( newSizeEnum ) {
691                 if ( dump ) {
692                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
693                 }
694                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
695                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
696                     iconSizeLookup[index] = newSizeEnum;
697                 } else if ( dump ) {
698                     g_message("size lookup array too small to store entry");
699                 }
700             }
701         }
702         sizeMapDone = true;
703     }
705     static bool hit = false;
706     if ( !hit ) {
707         hit = true;
708         inkyIcons = Gtk::IconFactory::create();
709         inkyIcons->add_default();
710     }
713 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
715     GtkIconSize other = GTK_ICON_SIZE_MENU;
716     injectCustomSize();
717     size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
718     if ( size == Inkscape::ICON_SIZE_DECORATION ) {
719         other = gtk_icon_size_from_name("inkscape-decoration");
720     } else {
721         other = static_cast<GtkIconSize>(size);
722     }
724     return other;
728 // PUBLIC CALL:
729 int sp_icon_get_phys_size(int size)
731     static bool init = false;
732     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
733     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
735     size = CLAMP( size, GTK_ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
737     if ( !sizeMapDone ) {
738         injectCustomSize();
739     }
741     if ( sizeDirty && init ) {
742         GtkIconSize const gtkSizes[] = {
743             GTK_ICON_SIZE_MENU,
744             GTK_ICON_SIZE_SMALL_TOOLBAR,
745             GTK_ICON_SIZE_LARGE_TOOLBAR,
746             GTK_ICON_SIZE_BUTTON,
747             GTK_ICON_SIZE_DND,
748             GTK_ICON_SIZE_DIALOG,
749             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
750                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
751                 GTK_ICON_SIZE_MENU
752         };
753         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
754             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
756             g_assert( val_ix < G_N_ELEMENTS(vals) );
758             gint width = 0;
759             gint height = 0;
760             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
761                 init &= (lastSys[val_ix] == std::max(width, height));
762             }
763         }
764     }
766     if ( !init ) {
767         sizeDirty = false;
768         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
769         bool dump = prefs->getBool("/debug/icons/dumpDefault");
771         if ( dump ) {
772             g_message( "Default icon sizes:" );
773         }
774         memset( vals, 0, sizeof(vals) );
775         memset( lastSys, 0, sizeof(lastSys) );
776         GtkIconSize const gtkSizes[] = {
777             GTK_ICON_SIZE_MENU,
778             GTK_ICON_SIZE_SMALL_TOOLBAR,
779             GTK_ICON_SIZE_LARGE_TOOLBAR,
780             GTK_ICON_SIZE_BUTTON,
781             GTK_ICON_SIZE_DND,
782             GTK_ICON_SIZE_DIALOG,
783             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
784                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
785                 GTK_ICON_SIZE_MENU
786         };
787         gchar const *const names[] = {
788             "GTK_ICON_SIZE_MENU",
789             "GTK_ICON_SIZE_SMALL_TOOLBAR",
790             "GTK_ICON_SIZE_LARGE_TOOLBAR",
791             "GTK_ICON_SIZE_BUTTON",
792             "GTK_ICON_SIZE_DND",
793             "GTK_ICON_SIZE_DIALOG",
794             "inkscape-decoration"
795         };
797         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
799         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
800             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
802             g_assert( val_ix < G_N_ELEMENTS(vals) );
804             gint width = 0;
805             gint height = 0;
806             bool used = false;
807             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
808                 vals[val_ix] = std::max(width, height);
809                 lastSys[val_ix] = vals[val_ix];
810                 used = true;
811             }
812             if (dump) {
813                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
814                           i, gtkSizes[i],
815                           ( used ? ' ' : 'X' ), width, height, names[i]);
816             }
817             gchar const *id = GTK_STOCK_OPEN;
818             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
819             if (pb) {
820                 width = gdk_pixbuf_get_width(pb);
821                 height = gdk_pixbuf_get_height(pb);
822                 int newSize = std::max( width, height );
823                 // TODO perhaps check a few more stock icons to get a range on sizes.
824                 if ( newSize > 0 ) {
825                     vals[val_ix] = newSize;
826                 }
827                 if (dump) {
828                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
829                 }
831                 g_object_unref(G_OBJECT(pb));
832             }
833         }
834         //g_object_unref(icon);
835         init = true;
836     }
838     // Fixup workaround
839     if ((size == GTK_ICON_SIZE_MENU) || (size == GTK_ICON_SIZE_SMALL_TOOLBAR) || (size == GTK_ICON_SIZE_LARGE_TOOLBAR)) {
840         gint width = 0;
841         gint height = 0;
842         if ( gtk_icon_size_lookup( static_cast<GtkIconSize>(size), &width, &height ) ) {
843             vals[size] = std::max( width, height );
844         }
845     }
847     return vals[size];
850 static void sp_icon_paint(SPIcon *icon, GdkRectangle const */*area*/)
852     GtkWidget &widget = *GTK_WIDGET(icon);
853     GdkPixbuf *image = icon->pb;
854     bool unref_image = false;
856     /* copied from the expose function of GtkImage */
857     if (GTK_WIDGET_STATE (icon) != GTK_STATE_NORMAL && image) {
858         GtkIconSource *source = gtk_icon_source_new();
859         gtk_icon_source_set_pixbuf(source, icon->pb);
860         gtk_icon_source_set_size(source, GTK_ICON_SIZE_SMALL_TOOLBAR); // note: this is boilerplate and not used
861         gtk_icon_source_set_size_wildcarded(source, FALSE);
862         image = gtk_style_render_icon (widget.style, source, gtk_widget_get_direction(&widget),
863             (GtkStateType) GTK_WIDGET_STATE(&widget), (GtkIconSize)-1, &widget, "gtk-image");
864         gtk_icon_source_free(source);
865         unref_image = true;
866     }
868     if (image) {
869         int x = floor(widget.allocation.x + ((widget.allocation.width - widget.requisition.width) * 0.5));
870         int y = floor(widget.allocation.y + ((widget.allocation.height - widget.requisition.height) * 0.5));
871         int width = gdk_pixbuf_get_width(image);
872         int height = gdk_pixbuf_get_height(image);
873         // Limit drawing to when we actually have something. Avoids some crashes.
874         if ( (width > 0) && (height > 0) ) {
875             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), widget.style->black_gc, image,
876                             0, 0, x, y, width, height,
877                             GDK_RGB_DITHER_NORMAL, x, y);
878         }
879     }
881     if (unref_image) {
882         g_object_unref(G_OBJECT(image));
883     }
886 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
888     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
889     // TODO: bulia, please look over
890     gsize bytesRead = 0;
891     gsize bytesWritten = 0;
892     GError *error = NULL;
893     gchar *localFilename = g_filename_from_utf8( path,
894                                                  -1,
895                                                  &bytesRead,
896                                                  &bytesWritten,
897                                                  &error);
898     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
899     g_free(localFilename);
900     g_free(path);
901     if (!pb) {
902         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
903         // TODO: bulia, please look over
904         gsize bytesRead = 0;
905         gsize bytesWritten = 0;
906         GError *error = NULL;
907         gchar *localFilename = g_filename_from_utf8( path,
908                                                      -1,
909                                                      &bytesRead,
910                                                      &bytesWritten,
911                                                      &error);
912         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
913         g_free(localFilename);
914         g_free(path);
915     }
917     if (pb) {
918         if (!gdk_pixbuf_get_has_alpha(pb)) {
919             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
920         }
922         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
923              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
924             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
925             g_object_unref(G_OBJECT(pb));
926             pb = spb;
927         }
928     }
930     return pb;
933 // takes doc, root, icon, and icon name to produce pixels
934 extern "C" guchar *
935 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
936                   gchar const *name, unsigned psize )
938     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
939     bool const dump = prefs->getBool("/debug/icons/dumpSvg");
940     guchar *px = NULL;
942     if (doc) {
943         SPObject *object = doc->getObjectById(name);
944         if (object && SP_IS_ITEM(object)) {
945             /* Find bbox in document */
946             Geom::Matrix const i2doc(sp_item_i2doc_affine(SP_ITEM(object)));
947             Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
949             if ( SP_OBJECT_PARENT(object) == NULL )
950             {
951                 dbox = Geom::Rect(Geom::Point(0, 0),
952                                 Geom::Point(sp_document_width(doc), sp_document_height(doc)));
953             }
955             /* This is in document coordinates, i.e. pixels */
956             if ( dbox ) {
957                 NRGC gc(NULL);
958                 /* Update to renderable state */
959                 double sf = 1.0;
960                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
961                 gc.transform.setIdentity();
962                 nr_arena_item_invoke_update( root, NULL, &gc,
963                                              NR_ARENA_ITEM_STATE_ALL,
964                                              NR_ARENA_ITEM_STATE_NONE );
965                 /* Item integer bbox in points */
966                 NRRectL ibox;
967                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
968                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
969                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
970                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
972                 if ( dump ) {
973                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
974                 }
976                 /* Find button visible area */
977                 int width = ibox.x1 - ibox.x0;
978                 int height = ibox.y1 - ibox.y0;
980                 if ( dump ) {
981                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
982                 }
984                 {
985                     int block = std::max(width, height);
986                     if (block != static_cast<int>(psize) ) {
987                         if ( dump ) {
988                             g_message("      resizing" );
989                         }
990                         sf = (double)psize / (double)block;
992                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
993                         gc.transform.setIdentity();
994                         nr_arena_item_invoke_update( root, NULL, &gc,
995                                                      NR_ARENA_ITEM_STATE_ALL,
996                                                      NR_ARENA_ITEM_STATE_NONE );
997                         /* Item integer bbox in points */
998                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
999                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
1000                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
1001                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
1003                         if ( dump ) {
1004                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
1005                         }
1007                         /* Find button visible area */
1008                         width = ibox.x1 - ibox.x0;
1009                         height = ibox.y1 - ibox.y0;
1010                         if ( dump ) {
1011                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
1012                         }
1013                     }
1014                 }
1016                 int dx, dy;
1017                 //dx = (psize - width) / 2;
1018                 //dy = (psize - height) / 2;
1019                 dx=dy=psize;
1020                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
1021                 dy=(dy-height)/2;
1022                 NRRectL area;
1023                 area.x0 = ibox.x0 - dx;
1024                 area.y0 = ibox.y0 - dy;
1025                 area.x1 = area.x0 + psize;
1026                 area.y1 = area.y0 + psize;
1027                 /* Actual renderable area */
1028                 NRRectL ua;
1029                 ua.x0 = MAX(ibox.x0, area.x0);
1030                 ua.y0 = MAX(ibox.y0, area.y0);
1031                 ua.x1 = MIN(ibox.x1, area.x1);
1032                 ua.y1 = MIN(ibox.y1, area.y1);
1034                 if ( dump ) {
1035                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
1036                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
1037                 }
1038                 /* Set up pixblock */
1039                 px = g_new(guchar, 4 * psize * psize);
1040                 memset(px, 0x00, 4 * psize * psize);
1041                 /* Render */
1042                 NRPixBlock B;
1043                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
1044                                           ua.x0, ua.y0, ua.x1, ua.y1,
1045                                           px + 4 * psize * (ua.y0 - area.y0) +
1046                                           4 * (ua.x0 - area.x0),
1047                                           4 * psize, FALSE, FALSE );
1048                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
1049                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
1050                 nr_pixblock_release(&B);
1052                 bool useOverlay = prefs->getBool("/debug/icons/overlaySvg");
1053                 if ( useOverlay ) {
1054                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
1055                 }
1056             }
1057         }
1058     }
1060     return px;
1061 } // end of sp_icon_doc_icon()
1065 struct svg_doc_cache_t
1067     SPDocument *doc;
1068     NRArenaItem *root;
1069 };
1071 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
1072 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
1074 Glib::ustring icon_cache_key(gchar const *name,
1075                              unsigned lsize, unsigned psize)
1077     Glib::ustring key=name;
1078     key += ":";
1079     key += lsize;
1080     key += ":";
1081     key += psize;
1082     return key;
1085 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
1086     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
1087     if ( found != pb_cache.end() ) {
1088         return found->second;
1089     }
1090     return NULL;
1093 static std::list<gchar*> &icons_svg_paths()
1095     static std::list<gchar *> sources;
1096     static bool initialized = false;
1097     if (!initialized) {
1098         // Fall back from user prefs dir into system locations.
1099         gchar *userdir = profile_path("icons");
1100         sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
1101         sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
1102         g_free(userdir);
1103         initialized = true;
1104     }
1105     return sources;
1108 // this function renders icons from icons.svg and returns the pixels.
1109 static guchar *load_svg_pixels(gchar const *name,
1110                                unsigned /*lsize*/, unsigned psize)
1112     SPDocument *doc = NULL;
1113     NRArenaItem *root = NULL;
1114     svg_doc_cache_t *info = NULL;
1116     std::list<gchar *> &sources = icons_svg_paths();
1118     // Try each document in turn until we successfully load the icon from one
1119     guchar *px=NULL;
1120     for (std::list<gchar*>::iterator i = sources.begin(); i != sources.end() && !px; ++i) {
1121         gchar *doc_filename = *i;
1123         // Did we already load this doc?
1124         Glib::ustring key(doc_filename);
1125         info = 0;
1126         {
1127             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
1128             if ( i != doc_cache.end() ) {
1129                 info = i->second;
1130             }
1131         }
1133         /* Try to load from document. */
1134         if (!info &&
1135             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
1136             (doc = sp_document_new( doc_filename, FALSE )) ) {
1138             //g_message("Loaded icon file %s", doc_filename);
1139             // prep the document
1140             sp_document_ensure_up_to_date(doc);
1141             /* Create new arena */
1142             NRArena *arena = NRArena::create();
1143             /* Create ArenaItem and set transform */
1144             unsigned visionkey = sp_item_display_key_new(1);
1145             /* fixme: Memory manage root if needed (Lauris) */
1146             root = sp_item_invoke_show( SP_ITEM(SP_DOCUMENT_ROOT(doc)),
1147                                         arena, visionkey, SP_ITEM_SHOW_DISPLAY );
1149             // store into the cache
1150             info = new svg_doc_cache_t;
1151             g_assert(info);
1153             info->doc=doc;
1154             info->root=root;
1155             doc_cache[key]=info;
1156         }
1157         if (info) {
1158             doc=info->doc;
1159             root=info->root;
1160         }
1162         // move on to the next document if we couldn't get anything
1163         if (!info && !doc) {
1164             continue;
1165         }
1167         px = sp_icon_doc_icon( doc, root, name, psize );
1168 //         if (px) {
1169 //             g_message("Found icon %s in %s", name, doc_filename);
1170 //         }
1171     }
1173 //     if (!px) {
1174 //         g_message("Not found icon %s", name);
1175 //     }
1176     return px;
1179 static void populate_placeholder_icon(gchar const* name, GtkIconSize size)
1181     if ( iconSetCache.find(name) == iconSetCache.end() ) {
1182         // only add a placeholder if nothing is already set
1183         Gtk::IconSet icnset;
1184         Gtk::IconSource src;
1185         src.set_icon_name( GTK_STOCK_MISSING_IMAGE );
1186         src.set_size( Gtk::IconSize(size) );
1187         icnset.add_source(src);
1188         inkyIcons->add(Gtk::StockID(name), icnset);
1189     }
1192 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
1193     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1194     static bool dump = prefs->getBool("/debug/icons/dumpGtk");
1195     GtkStockItem stock;
1196     gboolean stockFound = gtk_stock_lookup( name, &stock );
1197     if ( !stockFound ) {
1198         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
1199         if (dump) {
1200             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
1201         }
1202     }
1204     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
1205         if ( it->_lsize == lsize ) {
1206             if (dump) {
1207                 g_message("         erasing %s:%d   %p", name, it->_lsize, it->_pb);
1208             }
1209             iconSetCache[name].erase(it);
1210             break;
1211         }
1212     }
1213     iconSetCache[name].push_back(IconCacheItem(lsize, pb));
1215     Gtk::IconSet icnset;
1216     for ( std::vector<IconCacheItem>::iterator it = iconSetCache[name].begin(); it != iconSetCache[name].end(); ++it ) {
1217         Gtk::IconSource src;
1218         g_object_ref( G_OBJECT(it->_pb) );
1219         src.set_pixbuf( Glib::wrap(it->_pb) );
1220         src.set_size( Gtk::IconSize(it->_lsize) );
1221         src.set_size_wildcarded( (it->_lsize != 1) || (iconSetCache[name].size() == 1) );
1222         src.set_state_wildcarded( true );
1223         icnset.add_source(src);
1224     }
1225     inkyIcons->add(Gtk::StockID(name), icnset);
1228 // returns true if icon needed preloading, false if nothing was done
1229 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
1231     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1232     static bool dump = prefs->getBool("/debug/icons/dumpGtk");
1234     Glib::ustring key = icon_cache_key(name, lsize, psize);
1235     GdkPixbuf *pb = get_cached_pixbuf(key);
1236     if (pb) {
1237         return false;
1238     } else {
1239         GtkIconTheme* theme = gtk_icon_theme_get_default();
1240         if ( gtk_icon_theme_has_icon(theme, name) ) {
1241             gint *sizeArray = gtk_icon_theme_get_icon_sizes( theme, name );
1242             for (gint* cur = sizeArray; *cur; cur++) {
1243                 if (static_cast<gint>(psize) == *cur) {
1244                     pb = gtk_icon_theme_load_icon( theme, name, psize,
1245                                                    (GtkIconLookupFlags) 0, NULL );
1246                     break;
1247                 }
1248             }
1249             g_free(sizeArray);
1250             sizeArray = 0;
1251         }
1252         if (!pb) {
1253             if (dump) {
1254                 g_message("prerender_icon  [%s] %d:%d", name, lsize, psize);
1255             }
1256             guchar* px = load_svg_pixels(name, lsize, psize);
1257             if ( !px ) {
1258                 // check for a fallback name
1259                 if ( legacyNames.find(name) != legacyNames.end() ) {
1260                     if ( dump ) {
1261                         g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1262                     }
1263                     px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
1264                 }
1265             }
1266             if (px) {
1267                 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1268                                               psize, psize, psize * 4,
1269                                               (GdkPixbufDestroyNotify)g_free, NULL);
1270             } else if (dump) {
1271                 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
1272             }
1273         }
1274         else if (dump) {
1275             g_message("prerender_icon  [%s] %d NOT!!!!!!", name, psize);
1276         }
1278         if (pb) {
1279             pb_cache[key] = pb;
1280             addToIconSet(pb, name, lsize, psize);
1281         }
1282         return true;
1283     }
1286 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1288     Glib::ustring key = icon_cache_key(name, lsize, psize);
1290     // did we already load this icon at this scale/size?
1291     GdkPixbuf* pb = get_cached_pixbuf(key);
1292     if (!pb) {
1293         guchar *px = load_svg_pixels(name, lsize, psize);
1294         if (px) {
1295             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1296                                           psize, psize, psize * 4,
1297                                           (GdkPixbufDestroyNotify)g_free, NULL);
1298             pb_cache[key] = pb;
1299             addToIconSet(pb, name, lsize, psize);
1300         }
1301     }
1303     if ( pb ) {
1304         // increase refcount since we're handing out ownership
1305         g_object_ref(G_OBJECT(pb));
1306     }
1307     return pb;
1310 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1311                             unsigned r, unsigned g, unsigned b)
1313     int bytesPerPixel = 4;
1314     int spacing = 4;
1315     for ( int y = 0; y < height; y += spacing ) {
1316         guchar *ptr = px + y * stride;
1317         for ( int x = 0; x < width; x += spacing ) {
1318             *(ptr++) = r;
1319             *(ptr++) = g;
1320             *(ptr++) = b;
1321             *(ptr++) = 0xff;
1323             ptr += bytesPerPixel * (spacing - 1);
1324         }
1325     }
1327     if ( width > 1 && height > 1 ) {
1328         // point at the last pixel
1329         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1331         if ( width > 2 ) {
1332             px[4] = r;
1333             px[5] = g;
1334             px[6] = b;
1335             px[7] = 0xff;
1337             ptr[-12] = r;
1338             ptr[-11] = g;
1339             ptr[-10] = b;
1340             ptr[-9] = 0xff;
1341         }
1343         ptr[-4] = r;
1344         ptr[-3] = g;
1345         ptr[-2] = b;
1346         ptr[-1] = 0xff;
1348         px[0 + stride] = r;
1349         px[1 + stride] = g;
1350         px[2 + stride] = b;
1351         px[3 + stride] = 0xff;
1353         ptr[0 - stride] = r;
1354         ptr[1 - stride] = g;
1355         ptr[2 - stride] = b;
1356         ptr[3 - stride] = 0xff;
1358         if ( height > 2 ) {
1359             ptr[0 - stride * 3] = r;
1360             ptr[1 - stride * 3] = g;
1361             ptr[2 - stride * 3] = b;
1362             ptr[3 - stride * 3] = 0xff;
1363         }
1364     }
1367 class preRenderItem
1369 public:
1370     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1371         _lsize( lsize ),
1372         _name( name )
1373     {}
1374     GtkIconSize _lsize;
1375     Glib::ustring _name;
1376 };
1379 static std::vector<preRenderItem> pendingRenders;
1380 static bool callbackHooked = false;
1382 static void addPreRender( GtkIconSize lsize, gchar const *name )
1384     if ( !callbackHooked )
1385     {
1386         callbackHooked = true;
1387         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1388     }
1390     pendingRenders.push_back(preRenderItem(lsize, name));
1393 gboolean icon_prerender_task(gpointer /*data*/) {
1394     if (!pendingRenders.empty()) {
1395         bool workDone = false;
1396         do {
1397             preRenderItem single = pendingRenders.front();
1398             pendingRenders.erase(pendingRenders.begin());
1399             int psize = sp_icon_get_phys_size(single._lsize);
1400             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1401         } while (!pendingRenders.empty() && !workDone);
1402     }
1404     if (!pendingRenders.empty()) {
1405         return TRUE;
1406     } else {
1407         callbackHooked = false;
1408         return FALSE;
1409     }
1413 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1414     gchar* id = 0;
1415     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1416     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1417     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1418     if ( id ) {
1419         int psize = sp_icon_get_phys_size(lsize);
1420         g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1421         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1422             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1423                 prerender_icon(id, lsize, psize);
1424                 pendingRenders.erase(it);
1425                 g_message("    prerender for %s:%d:%d", id, lsize, psize);
1426                 if (lsize != size) {
1427                     int psize = sp_icon_get_phys_size(size);
1428                     prerender_icon(id, size, psize);
1429                 }
1430                 break;
1431             }
1432         }
1433     }
1435     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1438 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1439     GtkImage* img = GTK_IMAGE(widget);
1440     gchar const* iconName = 0;
1441     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1442     gtk_image_get_icon_name(img, &iconName, &size);
1443     if ( iconName ) {
1444         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1445         if ( type == GTK_IMAGE_ICON_NAME ) {
1447             gint iconSize = 0;
1448             gchar* iconName = 0;
1449             {
1450                 GIcon* gicon = 0;
1451                 GtkIconSet* iconSet = 0;
1452                 GdkImage* iii = 0;
1453                 GdkPixbuf* pixbuf = 0;
1454                 gint pixelSize = 0;
1455                 gchar* stock = 0;
1456                 g_object_get(G_OBJECT(widget),
1457                              "gicon", &gicon,
1458                              "icon-set", &iconSet,
1459                              "icon-name", &iconName,
1460                              "icon-size", &iconSize,
1461                              "image", &iii,
1462                              "pixbuf", &pixbuf,
1463                              "pixel-size", &pixelSize,
1464                              "stock", &stock,
1465                              NULL);
1466             }
1468             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1469                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1470                     int psize = sp_icon_get_phys_size(size);
1471                     prerender_icon(iconName, size, psize);
1472                     pendingRenders.erase(it);
1473                     break;
1474                 }
1475             }
1477             gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1478             gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1479         } else {
1480             g_warning("UNEXPECTED TYPE of %d", (int)type);
1481         }
1482     }
1484     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1488 /*
1489   Local Variables:
1490   mode:c++
1491   c-file-style:"stroustrup"
1492   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1493   indent-tabs-mode:nil
1494   fill-column:99
1495   End:
1496 */
1497 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :