Code

A simple layout document as to what, why and how is cppification.
[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 std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
93 static std::set<Glib::ustring> internalNames;
95 GType
96 sp_icon_get_type()
97 {
98     static GType type = 0;
99     if (!type) {
100         GTypeInfo info = {
101             sizeof(SPIconClass),
102             NULL,
103             NULL,
104             (GClassInitFunc) sp_icon_class_init,
105             NULL,
106             NULL,
107             sizeof(SPIcon),
108             0,
109             (GInstanceInitFunc) sp_icon_init,
110             NULL
111         };
112         type = g_type_register_static(GTK_TYPE_WIDGET, "SPIcon", &info, (GTypeFlags)0);
113     }
114     return type;
117 static void
118 sp_icon_class_init(SPIconClass *klass)
120     GObjectClass *object_class;
121     GtkWidgetClass *widget_class;
123     object_class = (GObjectClass *) klass;
124     widget_class = (GtkWidgetClass *) klass;
126     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
128     object_class->dispose = sp_icon_dispose;
130     widget_class->size_request = sp_icon_size_request;
131     widget_class->size_allocate = sp_icon_size_allocate;
132     widget_class->expose_event = sp_icon_expose;
133     widget_class->screen_changed = sp_icon_screen_changed;
134     widget_class->style_set = sp_icon_style_set;
138 static void
139 sp_icon_init(SPIcon *icon)
141     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
142     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
143     icon->psize = 0;
144     icon->name = 0;
145     icon->pb = 0;
148 static void
149 sp_icon_dispose(GObject *object)
151     SPIcon *icon = SP_ICON(object);
152     sp_icon_clear(icon);
153     if ( icon->name ) {
154         g_free( icon->name );
155         icon->name = 0;
156     }
158     ((GObjectClass *) (parent_class))->dispose(object);
161 static void sp_icon_reset( SPIcon *icon ) {
162     icon->psize = 0;
163     sp_icon_clear(icon);
166 static void sp_icon_clear( SPIcon *icon ) {
167     if (icon->pb) {
168         g_object_unref(G_OBJECT(icon->pb));
169         icon->pb = NULL;
170     }
173 static void
174 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
176     SPIcon const *icon = SP_ICON(widget);
178     int const size = ( icon->psize
179                        ? icon->psize
180                        : sp_icon_get_phys_size(icon->lsize) );
181     requisition->width = size;
182     requisition->height = size;
185 static void
186 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
188     widget->allocation = *allocation;
190     if (GTK_WIDGET_DRAWABLE(widget)) {
191         gtk_widget_queue_draw(widget);
192     }
195 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
197     if ( GTK_WIDGET_DRAWABLE(widget) ) {
198         SPIcon *icon = SP_ICON(widget);
199         if ( !icon->pb ) {
200             sp_icon_fetch_pixbuf( icon );
201         }
203         sp_icon_paint(SP_ICON(widget), &event->area);
204     }
206     return TRUE;
209 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize );
211 // PUBLIC CALL:
212 void sp_icon_fetch_pixbuf( SPIcon *icon )
214     if ( icon ) {
215         if ( !icon->pb ) {
216             icon->psize = sp_icon_get_phys_size(icon->lsize);
217             icon->pb = renderup(icon->name, icon->lsize, icon->psize);
218         }
219     }
222 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize ) {
223     GtkIconTheme *theme = gtk_icon_theme_get_default();
225     GdkPixbuf *pb = 0;
226     if (gtk_icon_theme_has_icon(theme, name)) {
227         pb = gtk_icon_theme_load_icon(theme, name, psize, (GtkIconLookupFlags) 0, NULL);
228     }
229     if (!pb) {
230         pb = sp_icon_image_load_svg( name, Inkscape::getRegisteredIconSize(lsize), psize );
231         if (!pb && (legacyNames.find(name) != legacyNames.end())) {
232             if ( Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg") ) {
233                 g_message("Checking fallback [%s]->[%s]", name, legacyNames[name].c_str());
234             }
235             pb = sp_icon_image_load_svg( legacyNames[name].c_str(), Inkscape::getRegisteredIconSize(lsize), psize );
236         }
238         // if this was loaded from SVG, add it as a builtin icon
239         if (pb) {
240             gtk_icon_theme_add_builtin_icon(name, psize, pb);
241         }
242     }
243     if (!pb) {
244         pb = sp_icon_image_load_pixmap( name, lsize, psize );
245     }
246     if ( !pb ) {
247         // TODO: We should do something more useful if we can't load the image.
248         g_warning ("failed to load icon '%s'", name);
249     }
250     return pb;
253 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
255     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
256         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
257     }
258     SPIcon *icon = SP_ICON(widget);
259     sp_icon_theme_changed(icon);
262 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
264     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
265         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
266     }
267     SPIcon *icon = SP_ICON(widget);
268     sp_icon_theme_changed(icon);
271 static void sp_icon_theme_changed( SPIcon *icon )
273     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
274     if ( dump ) {
275         g_message("Got a change bump for this icon");
276     }
277     sizeDirty = true;
278     sp_icon_reset(icon);
279     gtk_widget_queue_draw( GTK_WIDGET(icon) );
283 static void imageMapCB(GtkWidget* widget, gpointer user_data);
284 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
285 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
286 static Glib::ustring icon_cache_key(gchar const *name, unsigned psize);
287 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
289 static void setupLegacyNaming() {
290     legacyNames["document-import"] ="file_import";
291     legacyNames["document-export"] ="file_export";
292     legacyNames["document-import-ocal"] ="ocal_import";
293     legacyNames["document-export-ocal"] ="ocal_export";
294     legacyNames["document-metadata"] ="document_metadata";
295     legacyNames["dialog-input-devices"] ="input_devices";
296     legacyNames["edit-duplicate"] ="edit_duplicate";
297     legacyNames["edit-clone"] ="edit_clone";
298     legacyNames["edit-clone-unlink"] ="edit_unlink_clone";
299     legacyNames["edit-select-original"] ="edit_select_original";
300     legacyNames["edit-undo-history"] ="edit_undo_history";
301     legacyNames["edit-paste-in-place"] ="selection_paste_in_place";
302     legacyNames["edit-paste-style"] ="selection_paste_style";
303     legacyNames["selection-make-bitmap-copy"] ="selection_bitmap";
304     legacyNames["edit-select-all"] ="selection_select_all";
305     legacyNames["edit-select-all-layers"] ="selection_select_all_in_all_layers";
306     legacyNames["edit-select-invert"] ="selection_invert";
307     legacyNames["edit-select-none"] ="selection_deselect";
308     legacyNames["dialog-xml-editor"] ="xml_editor";
309     legacyNames["zoom-original"] ="zoom_1_to_1";
310     legacyNames["zoom-half-size"] ="zoom_1_to_2";
311     legacyNames["zoom-double-size"] ="zoom_2_to_1";
312     legacyNames["zoom-fit-selection"] ="zoom_select";
313     legacyNames["zoom-fit-drawing"] ="zoom_draw";
314     legacyNames["zoom-fit-page"] ="zoom_page";
315     legacyNames["zoom-fit-width"] ="zoom_pagewidth";
316     legacyNames["zoom-previous"] ="zoom_previous";
317     legacyNames["zoom-next"] ="zoom_next";
318     legacyNames["zoom-in"] ="zoom_in";
319     legacyNames["zoom-out"] ="zoom_out";
320     legacyNames["show-grid"] ="grid";
321     legacyNames["show-guides"] ="guides";
322     legacyNames["color-management"] ="color_management";
323     legacyNames["show-dialogs"] ="dialog_toggle";
324     legacyNames["dialog-messages"] ="messages";
325     legacyNames["dialog-scripts"] ="scripts";
326     legacyNames["window-previous"] ="window_previous";
327     legacyNames["window-next"] ="window_next";
328     legacyNames["dialog-icon-preview"] ="view_icon_preview";
329     legacyNames["window-new"] ="view_new";
330     legacyNames["view-fullscreen"] ="fullscreen";
331     legacyNames["layer-new"] ="new_layer";
332     legacyNames["layer-rename"] ="rename_layer";
333     legacyNames["layer-previous"] ="switch_to_layer_above";
334     legacyNames["layer-next"] ="switch_to_layer_below";
335     legacyNames["selection-move-to-layer-above"] ="move_selection_above";
336     legacyNames["selection-move-to-layer-below"] ="move_selection_below";
337     legacyNames["layer-raise"] ="raise_layer";
338     legacyNames["layer-lower"] ="lower_layer";
339     legacyNames["layer-top"] ="layer_to_top";
340     legacyNames["layer-bottom"] ="layer_to_bottom";
341     legacyNames["layer-delete"] ="delete_layer";
342     legacyNames["dialog-layers"] ="layers";
343     legacyNames["dialog-fill-and-stroke"] ="fill_and_stroke";
344     legacyNames["dialog-object-properties"] ="dialog_item_properties";
345     legacyNames["object-group"] ="selection_group";
346     legacyNames["object-ungroup"] ="selection_ungroup";
347     legacyNames["selection-raise"] ="selection_up";
348     legacyNames["selection-lower"] ="selection_down";
349     legacyNames["selection-top"] ="selection_top";
350     legacyNames["selection-bottom"] ="selection_bot";
351     legacyNames["object-rotate-left"] ="object_rotate_90_CCW";
352     legacyNames["object-rotate-right"] ="object_rotate_90_CW";
353     legacyNames["object-flip-horizontal"] ="object_flip_hor";
354     legacyNames["object-flip-vertical"] ="object_flip_ver";
355     legacyNames["dialog-transform"] ="object_trans";
356     legacyNames["dialog-align-and-distribute"] ="object_align";
357     legacyNames["dialog-rows-and-columns"] ="grid_arrange";
358     legacyNames["object-to-path"] ="object_tocurve";
359     legacyNames["stroke-to-path"] ="stroke_tocurve";
360     legacyNames["bitmap-trace"] ="selection_trace";
361     legacyNames["path-union"] ="union";
362     legacyNames["path-difference"] ="difference";
363     legacyNames["path-intersection"] ="intersection";
364     legacyNames["path-exclusion"] ="exclusion";
365     legacyNames["path-division"] ="division";
366     legacyNames["path-cut"] ="cut_path";
367     legacyNames["path-combine"] ="selection_combine";
368     legacyNames["path-break-apart"] ="selection_break";
369     legacyNames["path-outset"] ="outset_path";
370     legacyNames["path-inset"] ="inset_path";
371     legacyNames["path-offset-dynamic"] ="dynamic_offset";
372     legacyNames["path-offset-linked"] ="linked_offset";
373     legacyNames["path-simplify"] ="simplify";
374     legacyNames["path-reverse"] ="selection_reverse";
375     legacyNames["dialog-text-and-font"] ="object_font";
376     legacyNames["text-put-on-path"] ="put_on_path";
377     legacyNames["text-remove-from-path"] ="remove_from_path";
378     legacyNames["text-flow-into-frame"] ="flow_into_frame";
379     legacyNames["text-unflow"] ="unflow";
380     legacyNames["text-convert-to-regular"] ="convert_to_text";
381     legacyNames["text-unkern"] ="remove_manual_kerns";
382     legacyNames["help-keyboard-shortcuts"] ="help_keys";
383     legacyNames["help-contents"] ="help_tutorials";
384     legacyNames["inkscape-logo"] ="inkscape_options";
385     legacyNames["dialog-memory"] ="about_memory";
386     legacyNames["tool-pointer"] ="draw_select";
387     legacyNames["tool-node-editor"] ="draw_node";
388     legacyNames["tool-tweak"] ="draw_tweak";
389     legacyNames["zoom"] ="draw_zoom";
390     legacyNames["draw-rectangle"] ="draw_rect";
391     legacyNames["draw-cuboid"] ="draw_3dbox";
392     legacyNames["draw-ellipse"] ="draw_arc";
393     legacyNames["draw-polygon-star"] ="draw_star";
394     legacyNames["draw-spiral"] ="draw_spiral";
395     legacyNames["draw-freehand"] ="draw_freehand";
396     legacyNames["draw-path"] ="draw_pen";
397     legacyNames["draw-calligraphic"] ="draw_calligraphic";
398     legacyNames["draw-eraser"] ="draw_erase";
399     legacyNames["color-fill"] ="draw_paintbucket";
400     legacyNames["draw-text"] ="draw_text";
401     legacyNames["draw-connector"] ="draw_connector";
402     legacyNames["color-gradient"] ="draw_gradient";
403     legacyNames["color-picker"] ="draw_dropper";
404     legacyNames["transform-affect-stroke"] ="transform_stroke";
405     legacyNames["transform-affect-rounded-corners"] ="transform_corners";
406     legacyNames["transform-affect-gradient"] ="transform_gradient";
407     legacyNames["transform-affect-pattern"] ="transform_pattern";
408     legacyNames["node-add"] ="node_insert";
409     legacyNames["node-delete"] ="node_delete";
410     legacyNames["node-join"] ="node_join";
411     legacyNames["node-break"] ="node_break";
412     legacyNames["node-join-segment"] ="node_join_segment";
413     legacyNames["node-delete-segment"] ="node_delete_segment";
414     legacyNames["node-type-cusp"] ="node_cusp";
415     legacyNames["node-type-smooth"] ="node_smooth";
416     legacyNames["node-type-symmetric"] ="node_symmetric";
417     legacyNames["node-type-auto-smooth"] ="node_auto";
418     legacyNames["node-segment-curve"] ="node_curve";
419     legacyNames["node-segment-line"] ="node_line";
420     legacyNames["show-node-handles"] ="nodes_show_handles";
421     legacyNames["path-effect-parameter-next"] ="edit_next_parameter";
422     legacyNames["show-path-outline"] ="nodes_show_helperpath";
423     legacyNames["path-clip-edit"] ="nodeedit-clippath";
424     legacyNames["path-mask-edit"] ="nodeedit-mask";
425     legacyNames["node-type-cusp"] ="node_cusp";
426     legacyNames["object-tweak-push"] ="tweak_move_mode";
427     legacyNames["object-tweak-attract"] ="tweak_move_mode_inout";
428     legacyNames["object-tweak-randomize"] ="tweak_move_mode_jitter";
429     legacyNames["object-tweak-shrink"] ="tweak_scale_mode";
430     legacyNames["object-tweak-rotate"] ="tweak_rotate_mode";
431     legacyNames["object-tweak-duplicate"] ="tweak_moreless_mode";
432     legacyNames["object-tweak-push"] ="tweak_move_mode";
433     legacyNames["path-tweak-push"] ="tweak_push_mode";
434     legacyNames["path-tweak-shrink"] ="tweak_shrink_mode";
435     legacyNames["path-tweak-attract"] ="tweak_attract_mode";
436     legacyNames["path-tweak-roughen"] ="tweak_roughen_mode";
437     legacyNames["object-tweak-paint"] ="tweak_colorpaint_mode";
438     legacyNames["object-tweak-jitter-color"] ="tweak_colorjitter_mode";
439     legacyNames["object-tweak-blur"] ="tweak_blur_mode";
440     legacyNames["rectangle-make-corners-sharp"] ="squared_corner";
441     legacyNames["perspective-parallel"] ="toggle_vp_x";
442     legacyNames["draw-ellipse-whole"] ="reset_circle";
443     legacyNames["draw-ellipse-segment"] ="circle_closed_arc";
444     legacyNames["draw-ellipse-arc"] ="circle_open_arc";
445     legacyNames["draw-polygon"] ="star_flat";
446     legacyNames["draw-star"] ="star_angled";
447     legacyNames["path-mode-bezier"] ="bezier_mode";
448     legacyNames["path-mode-spiro"] ="spiro_splines_mode";
449     legacyNames["path-mode-polyline"] ="polylines_mode";
450     legacyNames["path-mode-polyline-paraxial"] ="paraxial_lines_mode";
451     legacyNames["draw-use-tilt"] ="guse_tilt";
452     legacyNames["draw-use-pressure"] ="guse_pressure";
453     legacyNames["draw-trace-background"] ="trace_background";
454     legacyNames["draw-eraser-delete-objects"] ="delete_object";
455     legacyNames["format-text-direction-vertical"] ="writing_mode_tb";
456     legacyNames["format-text-direction-horizontal"] ="writing_mode_lr";
457     legacyNames["connector-avoid"] ="connector_avoid";
458     legacyNames["connector-ignore"] ="connector_ignore";
459     legacyNames["object-fill"] ="controls_fill";
460     legacyNames["object-stroke"] ="controls_stroke";
461     legacyNames["snap"] ="toggle_snap_global";
462     legacyNames["snap-bounding-box"] ="toggle_snap_bbox";
463     legacyNames["snap-bounding-box-edges"] ="toggle_snap_to_bbox_path";
464     legacyNames["snap-bounding-box-corners"] ="toggle_snap_to_bbox_node";
465     legacyNames["snap-bounding-box-midpoints"] ="toggle_snap_to_bbox_edge_midpoints";
466     legacyNames["snap-bounding-box-center"] ="toggle_snap_to_bbox_midpoints";
467     legacyNames["snap-nodes"] ="toggle_snap_nodes";
468     legacyNames["snap-nodes-path"] ="toggle_snap_to_paths";
469     legacyNames["snap-nodes-cusp"] ="toggle_snap_to_nodes";
470     legacyNames["snap-nodes-smooth"] ="toggle_snap_to_smooth_nodes";
471     legacyNames["snap-nodes-midpoint"] ="toggle_snap_to_midpoints";
472     legacyNames["snap-nodes-intersection"] ="toggle_snap_to_path_intersections";
473     legacyNames["snap-nodes-center"] ="toggle_snap_to_bbox_midpoints-3";
474     legacyNames["snap-nodes-rotation-center"] ="toggle_snap_center";
475     legacyNames["snap-page"] ="toggle_snap_page_border";
476     legacyNames["snap-grid-guide-intersections"] ="toggle_snap_grid_guide_intersections";
477     legacyNames["align-horizontal-right-to-anchor"] ="al_left_out";
478     legacyNames["align-horizontal-left"] ="al_left_in";
479     legacyNames["align-horizontal-center"] ="al_center_hor";
480     legacyNames["align-horizontal-right"] ="al_right_in";
481     legacyNames["align-horizontal-left-to-anchor"] ="al_right_out";
482     legacyNames["align-horizontal-baseline"] ="al_baselines_vert";
483     legacyNames["align-vertical-bottom-to-anchor"] ="al_top_out";
484     legacyNames["align-vertical-top"] ="al_top_in";
485     legacyNames["align-vertical-center"] ="al_center_ver";
486     legacyNames["align-vertical-bottom"] ="al_bottom_in";
487     legacyNames["align-vertical-top-to-anchor"] ="al_bottom_out";
488     legacyNames["align-vertical-baseline"] ="al_baselines_hor";
489     legacyNames["distribute-horizontal-left"] ="distribute_left";
490     legacyNames["distribute-horizontal-center"] ="distribute_hcentre";
491     legacyNames["distribute-horizontal-right"] ="distribute_right";
492     legacyNames["distribute-horizontal-baseline"] ="distribute_baselines_hor";
493     legacyNames["distribute-vertical-bottom"] ="distribute_bottom";
494     legacyNames["distribute-vertical-center"] ="distribute_vcentre";
495     legacyNames["distribute-vertical-top"] ="distribute_top";
496     legacyNames["distribute-vertical-baseline"] ="distribute_baselines_vert";
497     legacyNames["distribute-randomize"] ="distribute_randomize";
498     legacyNames["distribute-unclump"] ="unclump";
499     legacyNames["distribute-graph"] ="graph_layout";
500     legacyNames["distribute-graph-directed"] ="directed_graph";
501     legacyNames["distribute-remove-overlaps"] ="remove_overlaps";
502     legacyNames["align-horizontal-node"] ="node_valign";
503     legacyNames["align-vertical-node"] ="node_halign";
504     legacyNames["distribute-vertical-node"] ="node_vdistribute";
505     legacyNames["distribute-horizontal-node"] ="node_hdistribute";
506     legacyNames["xml-element-new"] ="add_xml_element_node";
507     legacyNames["xml-text-new"] ="add_xml_text_node";
508     legacyNames["xml-node-delete"] ="delete_xml_node";
509     legacyNames["xml-node-duplicate"] ="duplicate_xml_node";
510     legacyNames["xml-attribute-delete"] ="delete_xml_attribute";
511     legacyNames["transform-move-horizontal"] ="arrows_hor";
512     legacyNames["transform-move-vertical"] ="arrows_ver";
513     legacyNames["transform-scale-horizontal"] ="transform_scale_hor";
514     legacyNames["transform-scale-vertical"] ="transform_scale_ver";
515     legacyNames["transform-skew-horizontal"] ="transform_scew_hor";
516     legacyNames["transform-skew-vertical"] ="transform_scew_ver";
517     legacyNames["object-fill"] ="properties_fill";
518     legacyNames["object-stroke"] ="properties_stroke_paint";
519     legacyNames["object-stroke-style"] ="properties_stroke";
520     legacyNames["paint-none"] ="fill_none";
521     legacyNames["paint-solid"] ="fill_solid";
522     legacyNames["paint-gradient-linear"] ="fill_gradient";
523     legacyNames["paint-gradient-radial"] ="fill_radial";
524     legacyNames["paint-pattern"] ="fill_pattern";
525     legacyNames["paint-unknown"] ="fill_unset";
526     legacyNames["fill-rule-even-odd"] ="fillrule_evenodd";
527     legacyNames["fill-rule-nonzero"] ="fillrule_nonzero";
528     legacyNames["stroke-join-miter"] ="join_miter";
529     legacyNames["stroke-join-bevel"] ="join_bevel";
530     legacyNames["stroke-join-round"] ="join_round";
531     legacyNames["stroke-cap-butt"] ="cap_butt";
532     legacyNames["stroke-cap-square"] ="cap_square";
533     legacyNames["stroke-cap-round"] ="cap_round";
534     legacyNames["guides"] ="guide";
535     legacyNames["grid-rectangular"] ="grid_xy";
536     legacyNames["grid-axonometric"] ="grid_axonom";
537     legacyNames["object-visible"] ="visible";
538     legacyNames["object-hidden"] ="hidden";
539     legacyNames["object-unlocked"] ="lock_unlocked";
540     legacyNames["object-locked"] ="width_height_lock";
541     legacyNames["zoom"] ="sticky_zoom";
544 static GtkWidget *
545 sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
547     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
549     GtkWidget *widget = 0;
550     gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
551     if ( !sizeMapDone ) {
552         injectCustomSize();
553     }
554     GtkIconSize mappedSize = iconSizeLookup[trySize];
556     GtkStockItem stock;
557     gboolean stockFound = gtk_stock_lookup( name, &stock );
559     GtkWidget *img = 0;
560     if ( legacyNames.empty() ) {
561         setupLegacyNaming();
562     }
564     if ( stockFound ) {
565         img = gtk_image_new_from_stock( name, mappedSize );
566     } else {
567         img = gtk_image_new_from_icon_name( name, mappedSize );
568         if ( dump ) {
569             g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
570             GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
571             g_message("      Type is %d  %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
572         }
573     }
575     if ( img ) {
576         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
577         if ( type == GTK_IMAGE_STOCK ) {
578             if ( !stockFound ) {
579                 // It's not showing as a stock ID, so assume it will be present internally
580                 addPreRender( mappedSize, name );
582                 // Add a hook to render if set visible before prerender is done.
583                 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
584                 if ( dump ) {
585                     g_message("      connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
586                 }
587             }
588             widget = GTK_WIDGET(img);
589             img = 0;
590             if ( dump ) {
591                 g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK) %s  on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
592             }
593         } else if ( type == GTK_IMAGE_ICON_NAME ) {
594             widget = GTK_WIDGET(img);
595             img = 0;
597             // Add a hook to render if set visible before prerender is done.
598             g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
600             if ( Inkscape::Preferences::get()->getBool("/options/iconrender/named_nodelay") ) {
601                 int psize = sp_icon_get_phys_size(lsize);
602                 prerender_icon(name, mappedSize, psize);
603             } else {
604                 addPreRender( mappedSize, name );
605             }
606         } else {
607             if ( dump ) {
608                 g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
609             }
610             //g_object_unref( (GObject *)img );
611             img = 0;
612         }
613     }
615     if ( !widget ) {
616         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
617         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
618         icon->lsize = lsize;
619         icon->name = g_strdup(name);
620         icon->psize = sp_icon_get_phys_size(lsize);
622         widget = GTK_WIDGET(icon);
623     }
625     return widget;
628 GtkWidget *
629 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
631     return sp_icon_new_full( lsize, name );
634 // PUBLIC CALL:
635 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
637     Gtk::Widget *result = 0;
638     GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
640     if ( widget ) {
641         if ( GTK_IS_IMAGE(widget) ) {
642             GtkImage *img = GTK_IMAGE(widget);
643             result = Glib::wrap( img );
644         } else {
645             result = Glib::wrap( widget );
646         }
647     }
649     return result;
652 GtkIconSize
653 sp_icon_get_gtk_size(int size)
655     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
656     size = CLAMP(size, 4, 63);
657     if (!sizemap[size]) {
658         static int count = 0;
659         char c[64];
660         g_snprintf(c, 64, "InkscapeIcon%d", count++);
661         sizemap[size] = gtk_icon_size_register(c, size, size);
662     }
663     return sizemap[size];
667 static void injectCustomSize()
669     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
670     if ( !sizeMapDone )
671     {
672         bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
673         gint width = 0;
674         gint height = 0;
675         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
676             gint newWidth = ((width * 3) / 4);
677             gint newHeight = ((height * 3) / 4);
678             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
679             if ( newSizeEnum ) {
680                 if ( dump ) {
681                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
682                 }
683                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
684                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
685                     iconSizeLookup[index] = newSizeEnum;
686                 } else if ( dump ) {
687                     g_message("size lookup array too small to store entry");
688                 }
689             }
690         }
691         sizeMapDone = true;
692     }
695 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
697     GtkIconSize other = GTK_ICON_SIZE_MENU;
698     injectCustomSize();
699     size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
700     if ( size == Inkscape::ICON_SIZE_DECORATION ) {
701         other = gtk_icon_size_from_name("inkscape-decoration");
702     } else {
703         other = static_cast<GtkIconSize>(size);
704     }
706     return other;
710 // PUBLIC CALL:
711 int sp_icon_get_phys_size(int size)
713     static bool init = false;
714     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
715     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
717     size = CLAMP( size, static_cast<int>(GTK_ICON_SIZE_MENU), static_cast<int>(Inkscape::ICON_SIZE_DECORATION) );
719     if ( !sizeMapDone ) {
720         injectCustomSize();
721     }
723     if ( sizeDirty && init ) {
724         GtkIconSize const gtkSizes[] = {
725             GTK_ICON_SIZE_MENU,
726             GTK_ICON_SIZE_SMALL_TOOLBAR,
727             GTK_ICON_SIZE_LARGE_TOOLBAR,
728             GTK_ICON_SIZE_BUTTON,
729             GTK_ICON_SIZE_DND,
730             GTK_ICON_SIZE_DIALOG,
731             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
732                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
733                 GTK_ICON_SIZE_MENU
734         };
735         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
736             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
738             g_assert( val_ix < G_N_ELEMENTS(vals) );
740             gint width = 0;
741             gint height = 0;
742             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
743                 init &= (lastSys[val_ix] == std::max(width, height));
744             }
745         }
746     }
748     if ( !init ) {
749         sizeDirty = false;
750         bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
751         if ( dump ) {
752             g_message( "Default icon sizes:" );
753         }
754         memset( vals, 0, sizeof(vals) );
755         memset( lastSys, 0, sizeof(lastSys) );
756         GtkIconSize const gtkSizes[] = {
757             GTK_ICON_SIZE_MENU,
758             GTK_ICON_SIZE_SMALL_TOOLBAR,
759             GTK_ICON_SIZE_LARGE_TOOLBAR,
760             GTK_ICON_SIZE_BUTTON,
761             GTK_ICON_SIZE_DND,
762             GTK_ICON_SIZE_DIALOG,
763             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
764                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
765                 GTK_ICON_SIZE_MENU
766         };
767         gchar const *const names[] = {
768             "GTK_ICON_SIZE_MENU",
769             "GTK_ICON_SIZE_SMALL_TOOLBAR",
770             "GTK_ICON_SIZE_LARGE_TOOLBAR",
771             "GTK_ICON_SIZE_BUTTON",
772             "GTK_ICON_SIZE_DND",
773             "GTK_ICON_SIZE_DIALOG",
774             "inkscape-decoration"
775         };
777         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
779         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
780             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
782             g_assert( val_ix < G_N_ELEMENTS(vals) );
784             gint width = 0;
785             gint height = 0;
786             bool used = false;
787             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
788                 vals[val_ix] = std::max(width, height);
789                 lastSys[val_ix] = vals[val_ix];
790                 used = true;
791             }
792             if (dump) {
793                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
794                           i, gtkSizes[i],
795                           ( used ? ' ' : 'X' ), width, height, names[i]);
796             }
798             // The following is needed due to this documented behavior of gtk_icon_size_lookup:
799             //   "The rendered pixbuf may not even correspond to the width/height returned by
800             //   gtk_icon_size_lookup(), because themes are free to render the pixbuf however
801             //   they like, including changing the usual size."
802             gchar const *id = GTK_STOCK_OPEN;
803             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
804             if (pb) {
805                 width = gdk_pixbuf_get_width(pb);
806                 height = gdk_pixbuf_get_height(pb);
807                 int newSize = std::max( width, height );
808                 // TODO perhaps check a few more stock icons to get a range on sizes.
809                 if ( newSize > 0 ) {
810                     vals[val_ix] = newSize;
811                 }
812                 if (dump) {
813                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
814                 }
816                 g_object_unref(G_OBJECT(pb));
817             }
818         }
819         //g_object_unref(icon);
820         init = true;
821     }
823     return vals[size];
826 static void sp_icon_paint(SPIcon *icon, GdkRectangle const */*area*/)
828     GtkWidget &widget = *GTK_WIDGET(icon);
829     GdkPixbuf *image = icon->pb;
830     bool unref_image = false;
832     /* copied from the expose function of GtkImage */
833     if (GTK_WIDGET_STATE (icon) != GTK_STATE_NORMAL && image) {
834         GtkIconSource *source = gtk_icon_source_new();
835         gtk_icon_source_set_pixbuf(source, icon->pb);
836         gtk_icon_source_set_size(source, GTK_ICON_SIZE_SMALL_TOOLBAR); // note: this is boilerplate and not used
837         gtk_icon_source_set_size_wildcarded(source, FALSE);
838         image = gtk_style_render_icon (widget.style, source, gtk_widget_get_direction(&widget),
839             (GtkStateType) GTK_WIDGET_STATE(&widget), (GtkIconSize)-1, &widget, "gtk-image");
840         gtk_icon_source_free(source);
841         unref_image = true;
842     }
844     if (image) {
845         int x = floor(widget.allocation.x + ((widget.allocation.width - widget.requisition.width) * 0.5));
846         int y = floor(widget.allocation.y + ((widget.allocation.height - widget.requisition.height) * 0.5));
847         int width = gdk_pixbuf_get_width(image);
848         int height = gdk_pixbuf_get_height(image);
849         // Limit drawing to when we actually have something. Avoids some crashes.
850         if ( (width > 0) && (height > 0) ) {
851             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), widget.style->black_gc, image,
852                             0, 0, x, y, width, height,
853                             GDK_RGB_DITHER_NORMAL, x, y);
854         }
855     }
857     if (unref_image) {
858         g_object_unref(G_OBJECT(image));
859     }
862 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
864     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
865     // TODO: bulia, please look over
866     gsize bytesRead = 0;
867     gsize bytesWritten = 0;
868     GError *error = NULL;
869     gchar *localFilename = g_filename_from_utf8( path,
870                                                  -1,
871                                                  &bytesRead,
872                                                  &bytesWritten,
873                                                  &error);
874     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
875     g_free(localFilename);
876     g_free(path);
877     if (!pb) {
878         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
879         // TODO: bulia, please look over
880         gsize bytesRead = 0;
881         gsize bytesWritten = 0;
882         GError *error = NULL;
883         gchar *localFilename = g_filename_from_utf8( path,
884                                                      -1,
885                                                      &bytesRead,
886                                                      &bytesWritten,
887                                                      &error);
888         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
889         g_free(localFilename);
890         g_free(path);
891     }
893     if (pb) {
894         if (!gdk_pixbuf_get_has_alpha(pb)) {
895             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
896         }
898         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
899              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
900             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
901             g_object_unref(G_OBJECT(pb));
902             pb = spb;
903         }
904     }
906     return pb;
909 // takes doc, root, icon, and icon name to produce pixels
910 extern "C" guchar *
911 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
912                   gchar const *name, unsigned psize )
914     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
915     guchar *px = NULL;
917     if (doc) {
918         SPObject *object = doc->getObjectById(name);
919         if (object && SP_IS_ITEM(object)) {
920             /* Find bbox in document */
921             Geom::Matrix const i2doc(SP_ITEM(object)->i2doc_affine());
922             Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
924             if ( SP_OBJECT_PARENT(object) == NULL )
925             {
926                 dbox = Geom::Rect(Geom::Point(0, 0),
927                                 Geom::Point(doc->getWidth(), doc->getHeight()));
928             }
930             /* This is in document coordinates, i.e. pixels */
931             if ( dbox ) {
932                 NRGC gc(NULL);
933                 /* Update to renderable state */
934                 double sf = 1.0;
935                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
936                 gc.transform.setIdentity();
937                 nr_arena_item_invoke_update( root, NULL, &gc,
938                                              NR_ARENA_ITEM_STATE_ALL,
939                                              NR_ARENA_ITEM_STATE_NONE );
940                 /* Item integer bbox in points */
941                 NRRectL ibox;
942                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
943                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
944                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
945                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
947                 if ( dump ) {
948                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
949                 }
951                 /* Find button visible area */
952                 int width = ibox.x1 - ibox.x0;
953                 int height = ibox.y1 - ibox.y0;
955                 if ( dump ) {
956                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
957                 }
959                 {
960                     int block = std::max(width, height);
961                     if (block != static_cast<int>(psize) ) {
962                         if ( dump ) {
963                             g_message("      resizing" );
964                         }
965                         sf = (double)psize / (double)block;
967                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
968                         gc.transform.setIdentity();
969                         nr_arena_item_invoke_update( root, NULL, &gc,
970                                                      NR_ARENA_ITEM_STATE_ALL,
971                                                      NR_ARENA_ITEM_STATE_NONE );
972                         /* Item integer bbox in points */
973                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
974                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
975                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
976                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
978                         if ( dump ) {
979                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
980                         }
982                         /* Find button visible area */
983                         width = ibox.x1 - ibox.x0;
984                         height = ibox.y1 - ibox.y0;
985                         if ( dump ) {
986                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
987                         }
988                     }
989                 }
991                 int dx, dy;
992                 //dx = (psize - width) / 2;
993                 //dy = (psize - height) / 2;
994                 dx=dy=psize;
995                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
996                 dy=(dy-height)/2;
997                 NRRectL area;
998                 area.x0 = ibox.x0 - dx;
999                 area.y0 = ibox.y0 - dy;
1000                 area.x1 = area.x0 + psize;
1001                 area.y1 = area.y0 + psize;
1002                 /* Actual renderable area */
1003                 NRRectL ua;
1004                 ua.x0 = MAX(ibox.x0, area.x0);
1005                 ua.y0 = MAX(ibox.y0, area.y0);
1006                 ua.x1 = MIN(ibox.x1, area.x1);
1007                 ua.y1 = MIN(ibox.y1, area.y1);
1009                 if ( dump ) {
1010                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
1011                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
1012                 }
1013                 /* Set up pixblock */
1014                 px = g_new(guchar, 4 * psize * psize);
1015                 memset(px, 0x00, 4 * psize * psize);
1016                 /* Render */
1017                 NRPixBlock B;
1018                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
1019                                           ua.x0, ua.y0, ua.x1, ua.y1,
1020                                           px + 4 * psize * (ua.y0 - area.y0) +
1021                                           4 * (ua.x0 - area.x0),
1022                                           4 * psize, FALSE, FALSE );
1023                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
1024                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
1025                 nr_pixblock_release(&B);
1027                 if ( Inkscape::Preferences::get()->getBool("/debug/icons/overlaySvg") ) {
1028                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
1029                 }
1030             }
1031         }
1032     }
1034     return px;
1035 } // end of sp_icon_doc_icon()
1039 struct svg_doc_cache_t
1041     SPDocument *doc;
1042     NRArenaItem *root;
1043 };
1045 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
1046 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
1048 Glib::ustring icon_cache_key(gchar const *name, unsigned psize)
1050     Glib::ustring key=name;
1051     key += ":";
1052     key += psize;
1053     return key;
1056 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
1057     GdkPixbuf* pb = 0;
1058     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
1059     if ( found != pb_cache.end() ) {
1060         pb = found->second;
1061     }
1062     return pb;
1065 static std::list<gchar*> &icons_svg_paths()
1067     static std::list<gchar *> sources;
1068     static bool initialized = false;
1069     if (!initialized) {
1070         // Fall back from user prefs dir into system locations.
1071         gchar *userdir = profile_path("icons");
1072         sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
1073         sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
1074         g_free(userdir);
1075         initialized = true;
1076     }
1077     return sources;
1080 // this function renders icons from icons.svg and returns the pixels.
1081 static guchar *load_svg_pixels(gchar const *name,
1082                                unsigned /*lsize*/, unsigned psize)
1084     SPDocument *doc = NULL;
1085     NRArenaItem *root = NULL;
1086     svg_doc_cache_t *info = NULL;
1088     std::list<gchar *> &sources = icons_svg_paths();
1090     // Try each document in turn until we successfully load the icon from one
1091     guchar *px=NULL;
1092     for (std::list<gchar*>::iterator i = sources.begin(); i != sources.end() && !px; ++i) {
1093         gchar *doc_filename = *i;
1095         // Did we already load this doc?
1096         Glib::ustring key(doc_filename);
1097         info = 0;
1098         {
1099             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
1100             if ( i != doc_cache.end() ) {
1101                 info = i->second;
1102             }
1103         }
1105         /* Try to load from document. */
1106         if (!info &&
1107             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
1108             (doc = SPDocument::createNewDoc( doc_filename, FALSE )) ) {
1110             //g_message("Loaded icon file %s", doc_filename);
1111             // prep the document
1112             doc->ensure_up_to_date();
1113             /* Create new arena */
1114             NRArena *arena = NRArena::create();
1115             /* Create ArenaItem and set transform */
1116             unsigned visionkey = SPItem::display_key_new(1);
1117             /* fixme: Memory manage root if needed (Lauris) */
1118             // This needs to be fixed indeed; this leads to a memory leak of a few megabytes these days
1119             // because shapes are being rendered which are not being freed
1120             // Valgrind output:
1121             /*==7014== 1,548,344 bytes in 599 blocks are possibly lost in loss record 20,361 of 20,362
1122             ==7014==    at 0x4A05974: operator new(unsigned long) (vg_replace_malloc.c:220)
1123             ==7014==    by 0x4F1015: __gnu_cxx::new_allocator<Shape::point_data>::allocate(unsigned long, void const*) (new_allocator.h:89)
1124             ==7014==    by 0x4F02AC: std::_Vector_base<Shape::point_data, std::allocator<Shape::point_data> >::_M_allocate(unsigned long) (stl_vector.h:140)
1125             ==7014==    by 0xCF62D7: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::_M_fill_insert(__gnu_cxx::__normal_iterator<Shape::point_data*, std::vector<Shape::point_data, std::allocator<Shape::point_data> > >, unsigned long, Shape::point_data const&) (vector.tcc:414)
1126             ==7014==    by 0xCF4D45: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::insert(__gnu_cxx::__normal_iterator<Shape::point_data*, std::vector<Shape::point_data, std::allocator<Shape::point_data> > >, unsigned long, Shape::point_data const&) (stl_vector.h:851)
1127             ==7014==    by 0xCF3DCD: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::resize(unsigned long, Shape::point_data) (stl_vector.h:557)
1128             ==7014==    by 0xCEA771: Shape::AddPoint(Geom::Point) (Shape.cpp:326)
1129             ==7014==    by 0xD0F413: Shape::ConvertToShape(Shape*, fill_typ, bool) (ShapeSweep.cpp:257)
1130             ==7014==    by 0x5ECD4F: nr_arena_shape_update_stroke(NRArenaShape*, NRGC*, NRRectL*) (nr-arena-shape.cpp:651)
1131             ==7014==    by 0x5EE0DA: nr_arena_shape_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-shape.cpp:862)
1132             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1133             ==7014==    by 0x5E9DDE: nr_arena_group_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-group.cpp:228)
1134             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1135             ==7014==    by 0x5E9DDE: nr_arena_group_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-group.cpp:228)
1136             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1137             */
1138             root = SP_ITEM(SP_DOCUMENT_ROOT(doc))->invoke_show(arena, visionkey, SP_ITEM_SHOW_DISPLAY );
1140             // store into the cache
1141             info = new svg_doc_cache_t;
1142             g_assert(info);
1144             info->doc=doc;
1145             info->root=root;
1146             doc_cache[key]=info;
1147         }
1148         if (info) {
1149             doc=info->doc;
1150             root=info->root;
1151         }
1153         // move on to the next document if we couldn't get anything
1154         if (!info && !doc) {
1155             continue;
1156         }
1158         px = sp_icon_doc_icon( doc, root, name, psize );
1159 //         if (px) {
1160 //             g_message("Found icon %s in %s", name, doc_filename);
1161 //         }
1162     }
1164 //     if (!px) {
1165 //         g_message("Not found icon %s", name);
1166 //     }
1167     return px;
1170 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
1171     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1172     GtkStockItem stock;
1173     gboolean stockFound = gtk_stock_lookup( name, &stock );
1174    if ( !stockFound ) {
1175         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
1176         if (dump) {
1177             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
1178         }
1179     }
1182 void Inkscape::queueIconPrerender( Glib::ustring const &name, Inkscape::IconSize lsize )
1184     GtkStockItem stock;
1185     gboolean stockFound = gtk_stock_lookup( name.c_str(), &stock );
1186     if (!stockFound && !gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name.c_str()) ) {
1187         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
1188         if ( !sizeMapDone ) {
1189             injectCustomSize();
1190         }
1191         GtkIconSize mappedSize = iconSizeLookup[trySize];
1193         int psize = sp_icon_get_phys_size(lsize);
1194         // TODO place in a queue that is triggered by other map events
1195         prerender_icon(name.c_str(), mappedSize, psize);
1196     }
1199 // returns true if icon needed preloading, false if nothing was done
1200 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
1202     bool loadNeeded = false;
1203     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1205     Glib::ustring key = icon_cache_key(name, psize);
1206     if ( !get_cached_pixbuf(key) ) {
1207         if ((internalNames.find(name) != internalNames.end())
1208             || (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name))) {
1209             if (dump) {
1210                 g_message("prerender_icon  [%s] %d:%d", name, lsize, psize);
1211             }
1212             guchar* px = load_svg_pixels(name, lsize, psize);
1213             if ( !px ) {
1214                 // check for a fallback name
1215                 if ( legacyNames.find(name) != legacyNames.end() ) {
1216                     if ( dump ) {
1217                         g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1218                     }
1219                     px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
1220                 }
1221             }
1222             if (px) {
1223                 GdkPixbuf* pb = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, TRUE, 8,
1224                                                           psize, psize, psize * 4,
1225                                                           reinterpret_cast<GdkPixbufDestroyNotify>(g_free), NULL );
1226                 pb_cache[key] = pb;
1227                 addToIconSet(pb, name, lsize, psize);
1228                 loadNeeded = true;
1229                 if (internalNames.find(name) == internalNames.end()) {
1230                     internalNames.insert(name);
1231                 }
1232             } else if (dump) {
1233                 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
1234             }
1235         }
1236         else if (dump) {
1237             g_message("prerender_icon  [%s] %d NOT!!!!!!", name, psize);
1238         }
1239     }
1240     return loadNeeded;
1243 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1245     Glib::ustring key = icon_cache_key(name, psize);
1247     // did we already load this icon at this scale/size?
1248     GdkPixbuf* pb = get_cached_pixbuf(key);
1249     if (!pb) {
1250         guchar *px = load_svg_pixels(name, lsize, psize);
1251         if (px) {
1252             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1253                                           psize, psize, psize * 4,
1254                                           (GdkPixbufDestroyNotify)g_free, NULL);
1255             pb_cache[key] = pb;
1256             addToIconSet(pb, name, lsize, psize);
1257         }
1258     }
1260     if ( pb ) {
1261         // increase refcount since we're handing out ownership
1262         g_object_ref(G_OBJECT(pb));
1263     }
1264     return pb;
1267 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1268                             unsigned r, unsigned g, unsigned b)
1270     int bytesPerPixel = 4;
1271     int spacing = 4;
1272     for ( int y = 0; y < height; y += spacing ) {
1273         guchar *ptr = px + y * stride;
1274         for ( int x = 0; x < width; x += spacing ) {
1275             *(ptr++) = r;
1276             *(ptr++) = g;
1277             *(ptr++) = b;
1278             *(ptr++) = 0xff;
1280             ptr += bytesPerPixel * (spacing - 1);
1281         }
1282     }
1284     if ( width > 1 && height > 1 ) {
1285         // point at the last pixel
1286         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1288         if ( width > 2 ) {
1289             px[4] = r;
1290             px[5] = g;
1291             px[6] = b;
1292             px[7] = 0xff;
1294             ptr[-12] = r;
1295             ptr[-11] = g;
1296             ptr[-10] = b;
1297             ptr[-9] = 0xff;
1298         }
1300         ptr[-4] = r;
1301         ptr[-3] = g;
1302         ptr[-2] = b;
1303         ptr[-1] = 0xff;
1305         px[0 + stride] = r;
1306         px[1 + stride] = g;
1307         px[2 + stride] = b;
1308         px[3 + stride] = 0xff;
1310         ptr[0 - stride] = r;
1311         ptr[1 - stride] = g;
1312         ptr[2 - stride] = b;
1313         ptr[3 - stride] = 0xff;
1315         if ( height > 2 ) {
1316             ptr[0 - stride * 3] = r;
1317             ptr[1 - stride * 3] = g;
1318             ptr[2 - stride * 3] = b;
1319             ptr[3 - stride * 3] = 0xff;
1320         }
1321     }
1324 class preRenderItem
1326 public:
1327     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1328         _lsize( lsize ),
1329         _name( name )
1330     {}
1331     GtkIconSize _lsize;
1332     Glib::ustring _name;
1333 };
1336 static std::vector<preRenderItem> pendingRenders;
1337 static bool callbackHooked = false;
1339 static void addPreRender( GtkIconSize lsize, gchar const *name )
1341     if ( !callbackHooked )
1342     {
1343         callbackHooked = true;
1344         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1345     }
1347     pendingRenders.push_back(preRenderItem(lsize, name));
1350 gboolean icon_prerender_task(gpointer /*data*/) {
1351     if (!pendingRenders.empty()) {
1352         bool workDone = false;
1353         do {
1354             preRenderItem single = pendingRenders.front();
1355             pendingRenders.erase(pendingRenders.begin());
1356             int psize = sp_icon_get_phys_size(single._lsize);
1357             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1358         } while (!pendingRenders.empty() && !workDone);
1359     }
1361     if (!pendingRenders.empty()) {
1362         return TRUE;
1363     } else {
1364         callbackHooked = false;
1365         return FALSE;
1366     }
1370 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1371     gchar* id = 0;
1372     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1373     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1374     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1375     if ( id ) {
1376         int psize = sp_icon_get_phys_size(lsize);
1377         g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1378         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1379             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1380                 prerender_icon(id, lsize, psize);
1381                 pendingRenders.erase(it);
1382                 g_message("    prerender for %s:%d:%d", id, lsize, psize);
1383                 if (lsize != size) {
1384                     int psize = sp_icon_get_phys_size(size);
1385                     prerender_icon(id, size, psize);
1386                 }
1387                 break;
1388             }
1389         }
1390     }
1392     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1395 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1396     GtkImage* img = GTK_IMAGE(widget);
1397     gchar const* iconName = 0;
1398     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1399     gtk_image_get_icon_name(img, &iconName, &size);
1400     if ( iconName ) {
1401         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1402         if ( type == GTK_IMAGE_ICON_NAME ) {
1404             gint iconSize = 0;
1405             gchar* iconName = 0;
1406             {
1407                 g_object_get(G_OBJECT(widget),
1408                              "icon-name", &iconName,
1409                              "icon-size", &iconSize,
1410                              NULL);
1411             }
1413             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1414                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1415                     int psize = sp_icon_get_phys_size(size);
1416                     prerender_icon(iconName, size, psize);
1417                     pendingRenders.erase(it);
1418                     break;
1419                 }
1420             }
1422             gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1423             gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1424         } else {
1425             g_warning("UNEXPECTED TYPE of %d", (int)type);
1426         }
1427     }
1429     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1433 /*
1434   Local Variables:
1435   mode:c++
1436   c-file-style:"stroustrup"
1437   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1438   indent-tabs-mode:nil
1439   fill-column:99
1440   End:
1441 */
1442 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :