Code

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