Code

Fix fallback icon loading order for icons with legacy names.
[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  *   Abhishek Sharma
9  *
10  * Copyright (C) 2002 Lauris Kaplinski
11  *
12  * Released under GNU GPL, read the file 'COPYING' for more information
13  */
15 #ifdef HAVE_CONFIG_H
16 # include "config.h"
17 #endif
19 #include <cstring>
20 #include <glib/gmem.h>
21 #include <gtk/gtk.h>
22 #include <gtkmm.h>
23 #include <gdkmm/pixbuf.h>
25 #include "path-prefix.h"
26 #include "preferences.h"
27 #include "inkscape.h"
28 #include "document.h"
29 #include "sp-item.h"
30 #include "display/nr-arena.h"
31 #include "display/nr-arena-item.h"
32 #include "io/sys.h"
34 #include "icon.h"
36 static gboolean icon_prerender_task(gpointer data);
38 static void addPreRender( GtkIconSize lsize, gchar const *name );
40 static void sp_icon_class_init(SPIconClass *klass);
41 static void sp_icon_init(SPIcon *icon);
42 static void sp_icon_dispose(GObject *object);
44 static void sp_icon_reset(SPIcon *icon);
45 static void sp_icon_clear(SPIcon *icon);
47 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
48 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
49 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
51 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
53 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
54 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
55 static void sp_icon_theme_changed( SPIcon *icon );
57 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
58 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
60 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
61                                     unsigned r, unsigned g, unsigned b );
63 static void injectCustomSize();
65 static GtkWidgetClass *parent_class;
67 static bool sizeDirty = true;
69 static bool sizeMapDone = false;
70 static GtkIconSize iconSizeLookup[] = {
71     GTK_ICON_SIZE_INVALID,
72     GTK_ICON_SIZE_MENU,
73     GTK_ICON_SIZE_SMALL_TOOLBAR,
74     GTK_ICON_SIZE_LARGE_TOOLBAR,
75     GTK_ICON_SIZE_BUTTON,
76     GTK_ICON_SIZE_DND,
77     GTK_ICON_SIZE_DIALOG,
78     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
79 };
81 static std::map<Glib::ustring, Glib::ustring> legacyNames;
83 class IconCacheItem
84 {
85 public:
86     IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
87         _lsize( lsize ),
88         _pb( pb )
89     {}
90     GtkIconSize _lsize;
91     GdkPixbuf* _pb;
92 };
94 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
95 static std::set<Glib::ustring> internalNames;
97 GType
98 sp_icon_get_type()
99 {
100     static GType type = 0;
101     if (!type) {
102         GTypeInfo info = {
103             sizeof(SPIconClass),
104             NULL,
105             NULL,
106             (GClassInitFunc) sp_icon_class_init,
107             NULL,
108             NULL,
109             sizeof(SPIcon),
110             0,
111             (GInstanceInitFunc) sp_icon_init,
112             NULL
113         };
114         type = g_type_register_static(GTK_TYPE_WIDGET, "SPIcon", &info, (GTypeFlags)0);
115     }
116     return type;
119 static void
120 sp_icon_class_init(SPIconClass *klass)
122     GObjectClass *object_class;
123     GtkWidgetClass *widget_class;
125     object_class = (GObjectClass *) klass;
126     widget_class = (GtkWidgetClass *) klass;
128     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
130     object_class->dispose = sp_icon_dispose;
132     widget_class->size_request = sp_icon_size_request;
133     widget_class->size_allocate = sp_icon_size_allocate;
134     widget_class->expose_event = sp_icon_expose;
135     widget_class->screen_changed = sp_icon_screen_changed;
136     widget_class->style_set = sp_icon_style_set;
140 static void
141 sp_icon_init(SPIcon *icon)
143     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
144     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
145     icon->psize = 0;
146     icon->name = 0;
147     icon->pb = 0;
150 static void
151 sp_icon_dispose(GObject *object)
153     SPIcon *icon = SP_ICON(object);
154     sp_icon_clear(icon);
155     if ( icon->name ) {
156         g_free( icon->name );
157         icon->name = 0;
158     }
160     ((GObjectClass *) (parent_class))->dispose(object);
163 static void sp_icon_reset( SPIcon *icon ) {
164     icon->psize = 0;
165     sp_icon_clear(icon);
168 static void sp_icon_clear( SPIcon *icon ) {
169     if (icon->pb) {
170         g_object_unref(G_OBJECT(icon->pb));
171         icon->pb = NULL;
172     }
175 static void
176 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
178     SPIcon const *icon = SP_ICON(widget);
180     int const size = ( icon->psize
181                        ? icon->psize
182                        : sp_icon_get_phys_size(icon->lsize) );
183     requisition->width = size;
184     requisition->height = size;
187 static void
188 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
190     widget->allocation = *allocation;
192     if (GTK_WIDGET_DRAWABLE(widget)) {
193         gtk_widget_queue_draw(widget);
194     }
197 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
199     if ( GTK_WIDGET_DRAWABLE(widget) ) {
200         SPIcon *icon = SP_ICON(widget);
201         if ( !icon->pb ) {
202             sp_icon_fetch_pixbuf( icon );
203         }
205         sp_icon_paint(SP_ICON(widget), &event->area);
206     }
208     return TRUE;
211 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize );
213 // PUBLIC CALL:
214 void sp_icon_fetch_pixbuf( SPIcon *icon )
216     if ( icon ) {
217         if ( !icon->pb ) {
218             icon->psize = sp_icon_get_phys_size(icon->lsize);
219             icon->pb = renderup(icon->name, icon->lsize, icon->psize);
220         }
221     }
224 GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize ) {
225     GtkIconTheme *theme = gtk_icon_theme_get_default();
227     GdkPixbuf *pb = 0;
228     if (gtk_icon_theme_has_icon(theme, name)) {
229         pb = gtk_icon_theme_load_icon(theme, name, psize, (GtkIconLookupFlags) 0, NULL);
230     }
231     if (!pb) {
232         pb = sp_icon_image_load_svg( name, Inkscape::getRegisteredIconSize(lsize), psize );
233         if (!pb && (legacyNames.find(name) != legacyNames.end())) {
234             if ( Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg") ) {
235                 g_message("Checking fallback [%s]->[%s]", name, legacyNames[name].c_str());
236             }
237             pb = sp_icon_image_load_svg( legacyNames[name].c_str(), Inkscape::getRegisteredIconSize(lsize), psize );
238         }
240         // if this was loaded from SVG, add it as a builtin icon
241         if (pb) {
242             gtk_icon_theme_add_builtin_icon(name, psize, pb);
243         }
244     }
245     if (!pb) {
246         pb = sp_icon_image_load_pixmap( name, lsize, psize );
247     }
248     if ( !pb ) {
249         // TODO: We should do something more useful if we can't load the image.
250         g_warning ("failed to load icon '%s'", name);
251     }
252     return pb;
255 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
257     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
258         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
259     }
260     SPIcon *icon = SP_ICON(widget);
261     sp_icon_theme_changed(icon);
264 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
266     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
267         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
268     }
269     SPIcon *icon = SP_ICON(widget);
270     sp_icon_theme_changed(icon);
273 static void sp_icon_theme_changed( SPIcon *icon )
275     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
276     if ( dump ) {
277         g_message("Got a change bump for this icon");
278     }
279     sizeDirty = true;
280     sp_icon_reset(icon);
281     gtk_widget_queue_draw( GTK_WIDGET(icon) );
285 static void imageMapCB(GtkWidget* widget, gpointer user_data);
286 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
287 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
288 static Glib::ustring icon_cache_key(gchar const *name, unsigned psize);
289 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
291 static void setupLegacyNaming() {
292     legacyNames["document-import"] ="file_import";
293     legacyNames["document-export"] ="file_export";
294     legacyNames["document-import-ocal"] ="ocal_import";
295     legacyNames["document-export-ocal"] ="ocal_export";
296     legacyNames["document-metadata"] ="document_metadata";
297     legacyNames["dialog-input-devices"] ="input_devices";
298     legacyNames["edit-duplicate"] ="edit_duplicate";
299     legacyNames["edit-clone"] ="edit_clone";
300     legacyNames["edit-clone-unlink"] ="edit_unlink_clone";
301     legacyNames["edit-select-original"] ="edit_select_original";
302     legacyNames["edit-undo-history"] ="edit_undo_history";
303     legacyNames["edit-paste-in-place"] ="selection_paste_in_place";
304     legacyNames["edit-paste-style"] ="selection_paste_style";
305     legacyNames["selection-make-bitmap-copy"] ="selection_bitmap";
306     legacyNames["edit-select-all"] ="selection_select_all";
307     legacyNames["edit-select-all-layers"] ="selection_select_all_in_all_layers";
308     legacyNames["edit-select-invert"] ="selection_invert";
309     legacyNames["edit-select-none"] ="selection_deselect";
310     legacyNames["dialog-xml-editor"] ="xml_editor";
311     legacyNames["zoom-original"] ="zoom_1_to_1";
312     legacyNames["zoom-half-size"] ="zoom_1_to_2";
313     legacyNames["zoom-double-size"] ="zoom_2_to_1";
314     legacyNames["zoom-fit-selection"] ="zoom_select";
315     legacyNames["zoom-fit-drawing"] ="zoom_draw";
316     legacyNames["zoom-fit-page"] ="zoom_page";
317     legacyNames["zoom-fit-width"] ="zoom_pagewidth";
318     legacyNames["zoom-previous"] ="zoom_previous";
319     legacyNames["zoom-next"] ="zoom_next";
320     legacyNames["zoom-in"] ="zoom_in";
321     legacyNames["zoom-out"] ="zoom_out";
322     legacyNames["show-grid"] ="grid";
323     legacyNames["show-guides"] ="guides";
324     legacyNames["color-management"] ="color_management";
325     legacyNames["show-dialogs"] ="dialog_toggle";
326     legacyNames["dialog-messages"] ="messages";
327     legacyNames["dialog-scripts"] ="scripts";
328     legacyNames["window-previous"] ="window_previous";
329     legacyNames["window-next"] ="window_next";
330     legacyNames["dialog-icon-preview"] ="view_icon_preview";
331     legacyNames["window-new"] ="view_new";
332     legacyNames["view-fullscreen"] ="fullscreen";
333     legacyNames["layer-new"] ="new_layer";
334     legacyNames["layer-rename"] ="rename_layer";
335     legacyNames["layer-previous"] ="switch_to_layer_above";
336     legacyNames["layer-next"] ="switch_to_layer_below";
337     legacyNames["selection-move-to-layer-above"] ="move_selection_above";
338     legacyNames["selection-move-to-layer-below"] ="move_selection_below";
339     legacyNames["layer-raise"] ="raise_layer";
340     legacyNames["layer-lower"] ="lower_layer";
341     legacyNames["layer-top"] ="layer_to_top";
342     legacyNames["layer-bottom"] ="layer_to_bottom";
343     legacyNames["layer-delete"] ="delete_layer";
344     legacyNames["dialog-layers"] ="layers";
345     legacyNames["dialog-fill-and-stroke"] ="fill_and_stroke";
346     legacyNames["dialog-object-properties"] ="dialog_item_properties";
347     legacyNames["object-group"] ="selection_group";
348     legacyNames["object-ungroup"] ="selection_ungroup";
349     legacyNames["selection-raise"] ="selection_up";
350     legacyNames["selection-lower"] ="selection_down";
351     legacyNames["selection-top"] ="selection_top";
352     legacyNames["selection-bottom"] ="selection_bot";
353     legacyNames["object-rotate-left"] ="object_rotate_90_CCW";
354     legacyNames["object-rotate-right"] ="object_rotate_90_CW";
355     legacyNames["object-flip-horizontal"] ="object_flip_hor";
356     legacyNames["object-flip-vertical"] ="object_flip_ver";
357     legacyNames["dialog-transform"] ="object_trans";
358     legacyNames["dialog-align-and-distribute"] ="object_align";
359     legacyNames["dialog-rows-and-columns"] ="grid_arrange";
360     legacyNames["object-to-path"] ="object_tocurve";
361     legacyNames["stroke-to-path"] ="stroke_tocurve";
362     legacyNames["bitmap-trace"] ="selection_trace";
363     legacyNames["path-union"] ="union";
364     legacyNames["path-difference"] ="difference";
365     legacyNames["path-intersection"] ="intersection";
366     legacyNames["path-exclusion"] ="exclusion";
367     legacyNames["path-division"] ="division";
368     legacyNames["path-cut"] ="cut_path";
369     legacyNames["path-combine"] ="selection_combine";
370     legacyNames["path-break-apart"] ="selection_break";
371     legacyNames["path-outset"] ="outset_path";
372     legacyNames["path-inset"] ="inset_path";
373     legacyNames["path-offset-dynamic"] ="dynamic_offset";
374     legacyNames["path-offset-linked"] ="linked_offset";
375     legacyNames["path-simplify"] ="simplify";
376     legacyNames["path-reverse"] ="selection_reverse";
377     legacyNames["dialog-text-and-font"] ="object_font";
378     legacyNames["text-put-on-path"] ="put_on_path";
379     legacyNames["text-remove-from-path"] ="remove_from_path";
380     legacyNames["text-flow-into-frame"] ="flow_into_frame";
381     legacyNames["text-unflow"] ="unflow";
382     legacyNames["text-convert-to-regular"] ="convert_to_text";
383     legacyNames["text-unkern"] ="remove_manual_kerns";
384     legacyNames["help-keyboard-shortcuts"] ="help_keys";
385     legacyNames["help-contents"] ="help_tutorials";
386     legacyNames["inkscape-logo"] ="inkscape_options";
387     legacyNames["dialog-memory"] ="about_memory";
388     legacyNames["tool-pointer"] ="draw_select";
389     legacyNames["tool-node-editor"] ="draw_node";
390     legacyNames["tool-tweak"] ="draw_tweak";
391     legacyNames["zoom"] ="draw_zoom";
392     legacyNames["draw-rectangle"] ="draw_rect";
393     legacyNames["draw-cuboid"] ="draw_3dbox";
394     legacyNames["draw-ellipse"] ="draw_arc";
395     legacyNames["draw-polygon-star"] ="draw_star";
396     legacyNames["draw-spiral"] ="draw_spiral";
397     legacyNames["draw-freehand"] ="draw_freehand";
398     legacyNames["draw-path"] ="draw_pen";
399     legacyNames["draw-calligraphic"] ="draw_calligraphic";
400     legacyNames["draw-eraser"] ="draw_erase";
401     legacyNames["color-fill"] ="draw_paintbucket";
402     legacyNames["draw-text"] ="draw_text";
403     legacyNames["draw-connector"] ="draw_connector";
404     legacyNames["color-gradient"] ="draw_gradient";
405     legacyNames["color-picker"] ="draw_dropper";
406     legacyNames["transform-affect-stroke"] ="transform_stroke";
407     legacyNames["transform-affect-rounded-corners"] ="transform_corners";
408     legacyNames["transform-affect-gradient"] ="transform_gradient";
409     legacyNames["transform-affect-pattern"] ="transform_pattern";
410     legacyNames["node-add"] ="node_insert";
411     legacyNames["node-delete"] ="node_delete";
412     legacyNames["node-join"] ="node_join";
413     legacyNames["node-break"] ="node_break";
414     legacyNames["node-join-segment"] ="node_join_segment";
415     legacyNames["node-delete-segment"] ="node_delete_segment";
416     legacyNames["node-type-cusp"] ="node_cusp";
417     legacyNames["node-type-smooth"] ="node_smooth";
418     legacyNames["node-type-symmetric"] ="node_symmetric";
419     legacyNames["node-type-auto-smooth"] ="node_auto";
420     legacyNames["node-segment-curve"] ="node_curve";
421     legacyNames["node-segment-line"] ="node_line";
422     legacyNames["show-node-handles"] ="nodes_show_handles";
423     legacyNames["path-effect-parameter-next"] ="edit_next_parameter";
424     legacyNames["show-path-outline"] ="nodes_show_helperpath";
425     legacyNames["path-clip-edit"] ="nodeedit-clippath";
426     legacyNames["path-mask-edit"] ="nodeedit-mask";
427     legacyNames["node-type-cusp"] ="node_cusp";
428     legacyNames["object-tweak-push"] ="tweak_move_mode";
429     legacyNames["object-tweak-attract"] ="tweak_move_mode_inout";
430     legacyNames["object-tweak-randomize"] ="tweak_move_mode_jitter";
431     legacyNames["object-tweak-shrink"] ="tweak_scale_mode";
432     legacyNames["object-tweak-rotate"] ="tweak_rotate_mode";
433     legacyNames["object-tweak-duplicate"] ="tweak_moreless_mode";
434     legacyNames["object-tweak-push"] ="tweak_move_mode";
435     legacyNames["path-tweak-push"] ="tweak_push_mode";
436     legacyNames["path-tweak-shrink"] ="tweak_shrink_mode";
437     legacyNames["path-tweak-attract"] ="tweak_attract_mode";
438     legacyNames["path-tweak-roughen"] ="tweak_roughen_mode";
439     legacyNames["object-tweak-paint"] ="tweak_colorpaint_mode";
440     legacyNames["object-tweak-jitter-color"] ="tweak_colorjitter_mode";
441     legacyNames["object-tweak-blur"] ="tweak_blur_mode";
442     legacyNames["rectangle-make-corners-sharp"] ="squared_corner";
443     legacyNames["perspective-parallel"] ="toggle_vp_x";
444     legacyNames["draw-ellipse-whole"] ="reset_circle";
445     legacyNames["draw-ellipse-segment"] ="circle_closed_arc";
446     legacyNames["draw-ellipse-arc"] ="circle_open_arc";
447     legacyNames["draw-polygon"] ="star_flat";
448     legacyNames["draw-star"] ="star_angled";
449     legacyNames["path-mode-bezier"] ="bezier_mode";
450     legacyNames["path-mode-spiro"] ="spiro_splines_mode";
451     legacyNames["path-mode-polyline"] ="polylines_mode";
452     legacyNames["path-mode-polyline-paraxial"] ="paraxial_lines_mode";
453     legacyNames["draw-use-tilt"] ="guse_tilt";
454     legacyNames["draw-use-pressure"] ="guse_pressure";
455     legacyNames["draw-trace-background"] ="trace_background";
456     legacyNames["draw-eraser-delete-objects"] ="delete_object";
457     legacyNames["format-text-direction-vertical"] ="writing_mode_tb";
458     legacyNames["format-text-direction-horizontal"] ="writing_mode_lr";
459     legacyNames["connector-avoid"] ="connector_avoid";
460     legacyNames["connector-ignore"] ="connector_ignore";
461     legacyNames["object-fill"] ="controls_fill";
462     legacyNames["object-stroke"] ="controls_stroke";
463     legacyNames["snap"] ="toggle_snap_global";
464     legacyNames["snap-bounding-box"] ="toggle_snap_bbox";
465     legacyNames["snap-bounding-box-edges"] ="toggle_snap_to_bbox_path";
466     legacyNames["snap-bounding-box-corners"] ="toggle_snap_to_bbox_node";
467     legacyNames["snap-bounding-box-midpoints"] ="toggle_snap_to_bbox_edge_midpoints";
468     legacyNames["snap-bounding-box-center"] ="toggle_snap_to_bbox_midpoints";
469     legacyNames["snap-nodes"] ="toggle_snap_nodes";
470     legacyNames["snap-nodes-path"] ="toggle_snap_to_paths";
471     legacyNames["snap-nodes-cusp"] ="toggle_snap_to_nodes";
472     legacyNames["snap-nodes-smooth"] ="toggle_snap_to_smooth_nodes";
473     legacyNames["snap-nodes-midpoint"] ="toggle_snap_to_midpoints";
474     legacyNames["snap-nodes-intersection"] ="toggle_snap_to_path_intersections";
475     legacyNames["snap-nodes-center"] ="toggle_snap_to_bbox_midpoints-3";
476     legacyNames["snap-nodes-rotation-center"] ="toggle_snap_center";
477     legacyNames["snap-page"] ="toggle_snap_page_border";
478     legacyNames["snap-grid-guide-intersections"] ="toggle_snap_grid_guide_intersections";
479     legacyNames["align-horizontal-right-to-anchor"] ="al_left_out";
480     legacyNames["align-horizontal-left"] ="al_left_in";
481     legacyNames["align-horizontal-center"] ="al_center_hor";
482     legacyNames["align-horizontal-right"] ="al_right_in";
483     legacyNames["align-horizontal-left-to-anchor"] ="al_right_out";
484     legacyNames["align-horizontal-baseline"] ="al_baselines_vert";
485     legacyNames["align-vertical-bottom-to-anchor"] ="al_top_out";
486     legacyNames["align-vertical-top"] ="al_top_in";
487     legacyNames["align-vertical-center"] ="al_center_ver";
488     legacyNames["align-vertical-bottom"] ="al_bottom_in";
489     legacyNames["align-vertical-top-to-anchor"] ="al_bottom_out";
490     legacyNames["align-vertical-baseline"] ="al_baselines_hor";
491     legacyNames["distribute-horizontal-left"] ="distribute_left";
492     legacyNames["distribute-horizontal-center"] ="distribute_hcentre";
493     legacyNames["distribute-horizontal-right"] ="distribute_right";
494     legacyNames["distribute-horizontal-baseline"] ="distribute_baselines_hor";
495     legacyNames["distribute-vertical-bottom"] ="distribute_bottom";
496     legacyNames["distribute-vertical-center"] ="distribute_vcentre";
497     legacyNames["distribute-vertical-top"] ="distribute_top";
498     legacyNames["distribute-vertical-baseline"] ="distribute_baselines_vert";
499     legacyNames["distribute-randomize"] ="distribute_randomize";
500     legacyNames["distribute-unclump"] ="unclump";
501     legacyNames["distribute-graph"] ="graph_layout";
502     legacyNames["distribute-graph-directed"] ="directed_graph";
503     legacyNames["distribute-remove-overlaps"] ="remove_overlaps";
504     legacyNames["align-horizontal-node"] ="node_valign";
505     legacyNames["align-vertical-node"] ="node_halign";
506     legacyNames["distribute-vertical-node"] ="node_vdistribute";
507     legacyNames["distribute-horizontal-node"] ="node_hdistribute";
508     legacyNames["xml-element-new"] ="add_xml_element_node";
509     legacyNames["xml-text-new"] ="add_xml_text_node";
510     legacyNames["xml-node-delete"] ="delete_xml_node";
511     legacyNames["xml-node-duplicate"] ="duplicate_xml_node";
512     legacyNames["xml-attribute-delete"] ="delete_xml_attribute";
513     legacyNames["transform-move-horizontal"] ="arrows_hor";
514     legacyNames["transform-move-vertical"] ="arrows_ver";
515     legacyNames["transform-scale-horizontal"] ="transform_scale_hor";
516     legacyNames["transform-scale-vertical"] ="transform_scale_ver";
517     legacyNames["transform-skew-horizontal"] ="transform_scew_hor";
518     legacyNames["transform-skew-vertical"] ="transform_scew_ver";
519     legacyNames["object-fill"] ="properties_fill";
520     legacyNames["object-stroke"] ="properties_stroke_paint";
521     legacyNames["object-stroke-style"] ="properties_stroke";
522     legacyNames["paint-none"] ="fill_none";
523     legacyNames["paint-solid"] ="fill_solid";
524     legacyNames["paint-gradient-linear"] ="fill_gradient";
525     legacyNames["paint-gradient-radial"] ="fill_radial";
526     legacyNames["paint-pattern"] ="fill_pattern";
527     legacyNames["paint-unknown"] ="fill_unset";
528     legacyNames["fill-rule-even-odd"] ="fillrule_evenodd";
529     legacyNames["fill-rule-nonzero"] ="fillrule_nonzero";
530     legacyNames["stroke-join-miter"] ="join_miter";
531     legacyNames["stroke-join-bevel"] ="join_bevel";
532     legacyNames["stroke-join-round"] ="join_round";
533     legacyNames["stroke-cap-butt"] ="cap_butt";
534     legacyNames["stroke-cap-square"] ="cap_square";
535     legacyNames["stroke-cap-round"] ="cap_round";
536     legacyNames["guides"] ="guide";
537     legacyNames["grid-rectangular"] ="grid_xy";
538     legacyNames["grid-axonometric"] ="grid_axonom";
539     legacyNames["object-visible"] ="visible";
540     legacyNames["object-hidden"] ="hidden";
541     legacyNames["object-unlocked"] ="lock_unlocked";
542     legacyNames["object-locked"] ="width_height_lock";
543     legacyNames["zoom"] ="sticky_zoom";
546 static GtkWidget *sp_icon_new_full( Inkscape::IconSize lsize, gchar const *name )
548     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
550     GtkWidget *widget = 0;
551     gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
552     if ( !sizeMapDone ) {
553         injectCustomSize();
554     }
555     GtkIconSize mappedSize = iconSizeLookup[trySize];
557     GtkStockItem stock;
558     gboolean stockFound = gtk_stock_lookup( name, &stock );
560     GtkWidget *img = 0;
561     if ( legacyNames.empty() ) {
562         setupLegacyNaming();
563     }
565     if ( stockFound ) {
566         img = gtk_image_new_from_stock( name, mappedSize );
567     } else {
568         img = gtk_image_new_from_icon_name( name, mappedSize );
569         if ( dump ) {
570             g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
571             GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
572             g_message("      Type is %d  %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
573         }
574     }
576     if ( img ) {
577         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
578         if ( type == GTK_IMAGE_STOCK ) {
579             if ( !stockFound ) {
580                 // It's not showing as a stock ID, so assume it will be present internally
581                 addPreRender( mappedSize, name );
583                 // Add a hook to render if set visible before prerender is done.
584                 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
585                 if ( dump ) {
586                     g_message("      connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
587                 }
588             }
589             widget = GTK_WIDGET(img);
590             img = 0;
591             if ( dump ) {
592                 g_message( "loaded gtk  '%s' %d  (GTK_IMAGE_STOCK) %s  on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
593             }
594         } else if ( type == GTK_IMAGE_ICON_NAME ) {
595             widget = GTK_WIDGET(img);
596             img = 0;
598             // Add a hook to render if set visible before prerender is done.
599             g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
601             if ( Inkscape::Preferences::get()->getBool("/options/iconrender/named_nodelay") ) {
602                 int psize = sp_icon_get_phys_size(lsize);
603                 prerender_icon(name, mappedSize, psize);
604             } else {
605                 addPreRender( mappedSize, name );
606             }
607         } else {
608             if ( dump ) {
609                 g_message( "skipped gtk '%s' %d  (not GTK_IMAGE_STOCK)", name, lsize );
610             }
611             //g_object_unref( (GObject *)img );
612             img = 0;
613         }
614     }
616     if ( !widget ) {
617         //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
618         SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
619         icon->lsize = lsize;
620         icon->name = g_strdup(name);
621         icon->psize = sp_icon_get_phys_size(lsize);
623         widget = GTK_WIDGET(icon);
624     }
626     return widget;
629 GtkWidget *
630 sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
632     return sp_icon_new_full( lsize, name );
635 // PUBLIC CALL:
636 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
638     Gtk::Widget *result = 0;
639     GtkWidget *widget = sp_icon_new_full( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
641     if ( widget ) {
642         if ( GTK_IS_IMAGE(widget) ) {
643             GtkImage *img = GTK_IMAGE(widget);
644             result = Glib::wrap( img );
645         } else {
646             result = Glib::wrap( widget );
647         }
648     }
650     return result;
653 GtkIconSize
654 sp_icon_get_gtk_size(int size)
656     static GtkIconSize sizemap[64] = {(GtkIconSize)0};
657     size = CLAMP(size, 4, 63);
658     if (!sizemap[size]) {
659         static int count = 0;
660         char c[64];
661         g_snprintf(c, 64, "InkscapeIcon%d", count++);
662         sizemap[size] = gtk_icon_size_register(c, size, size);
663     }
664     return sizemap[size];
668 static void injectCustomSize()
670     // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
671     if ( !sizeMapDone )
672     {
673         bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
674         gint width = 0;
675         gint height = 0;
676         if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
677             gint newWidth = ((width * 3) / 4);
678             gint newHeight = ((height * 3) / 4);
679             GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
680             if ( newSizeEnum ) {
681                 if ( dump ) {
682                     g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
683                 }
684                 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
685                 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
686                     iconSizeLookup[index] = newSizeEnum;
687                 } else if ( dump ) {
688                     g_message("size lookup array too small to store entry");
689                 }
690             }
691         }
692         sizeMapDone = true;
693     }
696 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
698     GtkIconSize other = GTK_ICON_SIZE_MENU;
699     injectCustomSize();
700     size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
701     if ( size == Inkscape::ICON_SIZE_DECORATION ) {
702         other = gtk_icon_size_from_name("inkscape-decoration");
703     } else {
704         other = static_cast<GtkIconSize>(size);
705     }
707     return other;
711 // PUBLIC CALL:
712 int sp_icon_get_phys_size(int size)
714     static bool init = false;
715     static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
716     static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
718     size = CLAMP( size, static_cast<int>(GTK_ICON_SIZE_MENU), static_cast<int>(Inkscape::ICON_SIZE_DECORATION) );
720     if ( !sizeMapDone ) {
721         injectCustomSize();
722     }
724     if ( sizeDirty && init ) {
725         GtkIconSize const gtkSizes[] = {
726             GTK_ICON_SIZE_MENU,
727             GTK_ICON_SIZE_SMALL_TOOLBAR,
728             GTK_ICON_SIZE_LARGE_TOOLBAR,
729             GTK_ICON_SIZE_BUTTON,
730             GTK_ICON_SIZE_DND,
731             GTK_ICON_SIZE_DIALOG,
732             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
733                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
734                 GTK_ICON_SIZE_MENU
735         };
736         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
737             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
739             g_assert( val_ix < G_N_ELEMENTS(vals) );
741             gint width = 0;
742             gint height = 0;
743             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
744                 init &= (lastSys[val_ix] == std::max(width, height));
745             }
746         }
747     }
749     if ( !init ) {
750         sizeDirty = false;
751         bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
752         if ( dump ) {
753             g_message( "Default icon sizes:" );
754         }
755         memset( vals, 0, sizeof(vals) );
756         memset( lastSys, 0, sizeof(lastSys) );
757         GtkIconSize const gtkSizes[] = {
758             GTK_ICON_SIZE_MENU,
759             GTK_ICON_SIZE_SMALL_TOOLBAR,
760             GTK_ICON_SIZE_LARGE_TOOLBAR,
761             GTK_ICON_SIZE_BUTTON,
762             GTK_ICON_SIZE_DND,
763             GTK_ICON_SIZE_DIALOG,
764             static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
765                 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
766                 GTK_ICON_SIZE_MENU
767         };
768         gchar const *const names[] = {
769             "GTK_ICON_SIZE_MENU",
770             "GTK_ICON_SIZE_SMALL_TOOLBAR",
771             "GTK_ICON_SIZE_LARGE_TOOLBAR",
772             "GTK_ICON_SIZE_BUTTON",
773             "GTK_ICON_SIZE_DND",
774             "GTK_ICON_SIZE_DIALOG",
775             "inkscape-decoration"
776         };
778         GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
780         for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
781             guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
783             g_assert( val_ix < G_N_ELEMENTS(vals) );
785             gint width = 0;
786             gint height = 0;
787             bool used = false;
788             if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
789                 vals[val_ix] = std::max(width, height);
790                 lastSys[val_ix] = vals[val_ix];
791                 used = true;
792             }
793             if (dump) {
794                 g_message(" =--  %u  size:%d  %c(%d, %d)   '%s'",
795                           i, gtkSizes[i],
796                           ( used ? ' ' : 'X' ), width, height, names[i]);
797             }
799             // The following is needed due to this documented behavior of gtk_icon_size_lookup:
800             //   "The rendered pixbuf may not even correspond to the width/height returned by
801             //   gtk_icon_size_lookup(), because themes are free to render the pixbuf however
802             //   they like, including changing the usual size."
803             gchar const *id = GTK_STOCK_OPEN;
804             GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
805             if (pb) {
806                 width = gdk_pixbuf_get_width(pb);
807                 height = gdk_pixbuf_get_height(pb);
808                 int newSize = std::max( width, height );
809                 // TODO perhaps check a few more stock icons to get a range on sizes.
810                 if ( newSize > 0 ) {
811                     vals[val_ix] = newSize;
812                 }
813                 if (dump) {
814                     g_message("      %u  size:%d   (%d, %d)", i, gtkSizes[i], width, height);
815                 }
817                 g_object_unref(G_OBJECT(pb));
818             }
819         }
820         //g_object_unref(icon);
821         init = true;
822     }
824     return vals[size];
827 static void sp_icon_paint(SPIcon *icon, GdkRectangle const */*area*/)
829     GtkWidget &widget = *GTK_WIDGET(icon);
830     GdkPixbuf *image = icon->pb;
831     bool unref_image = false;
833     /* copied from the expose function of GtkImage */
834     if (GTK_WIDGET_STATE (icon) != GTK_STATE_NORMAL && image) {
835         GtkIconSource *source = gtk_icon_source_new();
836         gtk_icon_source_set_pixbuf(source, icon->pb);
837         gtk_icon_source_set_size(source, GTK_ICON_SIZE_SMALL_TOOLBAR); // note: this is boilerplate and not used
838         gtk_icon_source_set_size_wildcarded(source, FALSE);
839         image = gtk_style_render_icon (widget.style, source, gtk_widget_get_direction(&widget),
840             (GtkStateType) GTK_WIDGET_STATE(&widget), (GtkIconSize)-1, &widget, "gtk-image");
841         gtk_icon_source_free(source);
842         unref_image = true;
843     }
845     if (image) {
846         int x = floor(widget.allocation.x + ((widget.allocation.width - widget.requisition.width) * 0.5));
847         int y = floor(widget.allocation.y + ((widget.allocation.height - widget.requisition.height) * 0.5));
848         int width = gdk_pixbuf_get_width(image);
849         int height = gdk_pixbuf_get_height(image);
850         // Limit drawing to when we actually have something. Avoids some crashes.
851         if ( (width > 0) && (height > 0) ) {
852             gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), widget.style->black_gc, image,
853                             0, 0, x, y, width, height,
854                             GDK_RGB_DITHER_NORMAL, x, y);
855         }
856     }
858     if (unref_image) {
859         g_object_unref(G_OBJECT(image));
860     }
863 GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
865     gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
866     // TODO: bulia, please look over
867     gsize bytesRead = 0;
868     gsize bytesWritten = 0;
869     GError *error = NULL;
870     gchar *localFilename = g_filename_from_utf8( path,
871                                                  -1,
872                                                  &bytesRead,
873                                                  &bytesWritten,
874                                                  &error);
875     GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
876     g_free(localFilename);
877     g_free(path);
878     if (!pb) {
879         path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
880         // TODO: bulia, please look over
881         gsize bytesRead = 0;
882         gsize bytesWritten = 0;
883         GError *error = NULL;
884         gchar *localFilename = g_filename_from_utf8( path,
885                                                      -1,
886                                                      &bytesRead,
887                                                      &bytesWritten,
888                                                      &error);
889         pb = gdk_pixbuf_new_from_file(localFilename, NULL);
890         g_free(localFilename);
891         g_free(path);
892     }
894     if (pb) {
895         if (!gdk_pixbuf_get_has_alpha(pb)) {
896             gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
897         }
899         if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
900              || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
901             GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
902             g_object_unref(G_OBJECT(pb));
903             pb = spb;
904         }
905     }
907     return pb;
910 // takes doc, root, icon, and icon name to produce pixels
911 extern "C" guchar *
912 sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
913                   gchar const *name, unsigned psize )
915     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
916     guchar *px = NULL;
918     if (doc) {
919         SPObject *object = doc->getObjectById(name);
920         if (object && SP_IS_ITEM(object)) {
921             /* Find bbox in document */
922             Geom::Matrix const i2doc(SP_ITEM(object)->i2doc_affine());
923             Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
925             if ( SP_OBJECT_PARENT(object) == NULL )
926             {
927                 dbox = Geom::Rect(Geom::Point(0, 0),
928                                 Geom::Point(doc->getWidth(), doc->getHeight()));
929             }
931             /* This is in document coordinates, i.e. pixels */
932             if ( dbox ) {
933                 NRGC gc(NULL);
934                 /* Update to renderable state */
935                 double sf = 1.0;
936                 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
937                 gc.transform.setIdentity();
938                 nr_arena_item_invoke_update( root, NULL, &gc,
939                                              NR_ARENA_ITEM_STATE_ALL,
940                                              NR_ARENA_ITEM_STATE_NONE );
941                 /* Item integer bbox in points */
942                 NRRectL ibox;
943                 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
944                 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
945                 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
946                 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
948                 if ( dump ) {
949                     g_message( "   box    --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
950                 }
952                 /* Find button visible area */
953                 int width = ibox.x1 - ibox.x0;
954                 int height = ibox.y1 - ibox.y0;
956                 if ( dump ) {
957                     g_message( "   vis    --'%s'  (%d,%d)", name, width, height );
958                 }
960                 {
961                     int block = std::max(width, height);
962                     if (block != static_cast<int>(psize) ) {
963                         if ( dump ) {
964                             g_message("      resizing" );
965                         }
966                         sf = (double)psize / (double)block;
968                         nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
969                         gc.transform.setIdentity();
970                         nr_arena_item_invoke_update( root, NULL, &gc,
971                                                      NR_ARENA_ITEM_STATE_ALL,
972                                                      NR_ARENA_ITEM_STATE_NONE );
973                         /* Item integer bbox in points */
974                         ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
975                         ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
976                         ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
977                         ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
979                         if ( dump ) {
980                             g_message( "   box2   --'%s'  (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
981                         }
983                         /* Find button visible area */
984                         width = ibox.x1 - ibox.x0;
985                         height = ibox.y1 - ibox.y0;
986                         if ( dump ) {
987                             g_message( "   vis2   --'%s'  (%d,%d)", name, width, height );
988                         }
989                     }
990                 }
992                 int dx, dy;
993                 //dx = (psize - width) / 2;
994                 //dy = (psize - height) / 2;
995                 dx=dy=psize;
996                 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
997                 dy=(dy-height)/2;
998                 NRRectL area;
999                 area.x0 = ibox.x0 - dx;
1000                 area.y0 = ibox.y0 - dy;
1001                 area.x1 = area.x0 + psize;
1002                 area.y1 = area.y0 + psize;
1003                 /* Actual renderable area */
1004                 NRRectL ua;
1005                 ua.x0 = MAX(ibox.x0, area.x0);
1006                 ua.y0 = MAX(ibox.y0, area.y0);
1007                 ua.x1 = MIN(ibox.x1, area.x1);
1008                 ua.y1 = MIN(ibox.y1, area.y1);
1010                 if ( dump ) {
1011                     g_message( "   area   --'%s'  (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
1012                     g_message( "   ua     --'%s'  (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
1013                 }
1014                 /* Set up pixblock */
1015                 px = g_new(guchar, 4 * psize * psize);
1016                 memset(px, 0x00, 4 * psize * psize);
1017                 /* Render */
1018                 NRPixBlock B;
1019                 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
1020                                           ua.x0, ua.y0, ua.x1, ua.y1,
1021                                           px + 4 * psize * (ua.y0 - area.y0) +
1022                                           4 * (ua.x0 - area.x0),
1023                                           4 * psize, FALSE, FALSE );
1024                 nr_arena_item_invoke_render(NULL, root, &ua, &B,
1025                                              NR_ARENA_ITEM_RENDER_NO_CACHE );
1026                 nr_pixblock_release(&B);
1028                 if ( Inkscape::Preferences::get()->getBool("/debug/icons/overlaySvg") ) {
1029                     sp_icon_overlay_pixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
1030                 }
1031             }
1032         }
1033     }
1035     return px;
1036 } // end of sp_icon_doc_icon()
1040 class SVGDocCache
1042 public:
1043     SVGDocCache( SPDocument *doc, NRArenaItem *root ) : doc(doc), root(root) {}
1044     SPDocument *doc;
1045     NRArenaItem *root;
1046 };
1048 static std::map<Glib::ustring, SVGDocCache *> doc_cache;
1049 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
1051 Glib::ustring icon_cache_key(gchar const *name, unsigned psize)
1053     Glib::ustring key=name;
1054     key += ":";
1055     key += psize;
1056     return key;
1059 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
1060     GdkPixbuf* pb = 0;
1061     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
1062     if ( found != pb_cache.end() ) {
1063         pb = found->second;
1064     }
1065     return pb;
1068 static std::list<gchar*> &icons_svg_paths()
1070     static std::list<gchar *> sources;
1071     static bool initialized = false;
1072     if (!initialized) {
1073         // Fall back from user prefs dir into system locations.
1074         gchar *userdir = profile_path("icons");
1075         sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
1076         sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
1077         g_free(userdir);
1078         initialized = true;
1079     }
1080     return sources;
1083 // this function renders icons from icons.svg and returns the pixels.
1084 static guchar *load_svg_pixels(std::list<Glib::ustring> const &names,
1085                                unsigned /*lsize*/, unsigned psize)
1087     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
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;
1094         SVGDocCache *info = 0;
1096         // Did we already load this doc?
1097         Glib::ustring key(doc_filename);
1098         {
1099             std::map<Glib::ustring, SVGDocCache *>::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 && Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) ) {
1107             SPDocument *doc = SPDocument::createNewDoc( doc_filename, FALSE );
1108             if ( doc ) {
1109                 if ( dump ) {
1110                     g_message("Loaded icon file %s", doc_filename);
1111                 }
1112                 // prep the document
1113                 doc->ensureUpToDate();
1115                 // Create new arena
1116                 NRArena *arena = NRArena::create();
1118                 // Create ArenaItem and set transform
1119                 unsigned visionkey = SPItem::display_key_new(1);
1120                 // fixme: Memory manage root if needed (Lauris)
1121                 // This needs to be fixed indeed; this leads to a memory leak of a few megabytes these days
1122                 // because shapes are being rendered which are not being freed
1123                 NRArenaItem *root = SP_ITEM(doc->getRoot())->invoke_show( arena, visionkey, SP_ITEM_SHOW_DISPLAY );
1125                 // store into the cache
1126                 info = new SVGDocCache(doc, root);
1127                 doc_cache[key] = info;
1128             }
1129         }
1130         if (info) {
1131             for (std::list<Glib::ustring>::const_iterator it = names.begin(); !px && (it != names.end()); ++it ) {
1132                 px = sp_icon_doc_icon( info->doc, info->root, it->c_str(), psize );
1133             }
1134         }
1135     }
1137     return px;
1140 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
1141     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1142     GtkStockItem stock;
1143     gboolean stockFound = gtk_stock_lookup( name, &stock );
1144    if ( !stockFound ) {
1145         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
1146         if (dump) {
1147             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
1148         }
1149     }
1152 void Inkscape::queueIconPrerender( Glib::ustring const &name, Inkscape::IconSize lsize )
1154     GtkStockItem stock;
1155     gboolean stockFound = gtk_stock_lookup( name.c_str(), &stock );
1156     gboolean themedFound = gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name.c_str());
1157     if (!stockFound && !themedFound ) {
1158         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
1159         if ( !sizeMapDone ) {
1160             injectCustomSize();
1161         }
1162         GtkIconSize mappedSize = iconSizeLookup[trySize];
1164         int psize = sp_icon_get_phys_size(lsize);
1165         // TODO place in a queue that is triggered by other map events
1166         prerender_icon(name.c_str(), mappedSize, psize);
1167     }
1170 static std::map<unsigned, Glib::ustring> sizePaths;
1172 static std::string getDestDir( unsigned psize )
1174     if ( sizePaths.find(psize) == sizePaths.end() ) {
1175         gchar *tmp = g_strdup_printf("%dx%d", psize, psize);
1176         sizePaths[psize] = tmp;
1177         g_free(tmp);
1178     }
1180     return sizePaths[psize];
1183 // returns true if icon needed preloading, false if nothing was done
1184 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
1186     bool loadNeeded = false;
1187     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1188     static bool useCache = Inkscape::Preferences::get()->getBool("/debug/icons/useCache");
1190     Glib::ustring key = icon_cache_key(name, psize);
1191     if ( !get_cached_pixbuf(key) ) {
1192         if ((internalNames.find(name) != internalNames.end())
1193             || (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name))) {
1194             if (dump) {
1195                 g_message("prerender_icon  [%s] %d:%d", name, lsize, psize);
1196             }
1198             std::string potentialFile;
1199             bool dataLoaded = false;
1200             if ( useCache ) {
1201                 // In file encoding:
1202                 std::string iconCacheDir = Glib::build_filename(Glib::build_filename(Glib::get_user_cache_dir(), "inkscape"), "icons");
1203                 std::string subpart = getDestDir(psize);
1204                 std::string subdir = Glib::build_filename( iconCacheDir, subpart );
1205                 if ( !Glib::file_test(subdir, Glib::FILE_TEST_EXISTS) ) {
1206                     g_mkdir_with_parents( subdir.c_str(), 0x1ED );
1207                 }
1208                 potentialFile = Glib::build_filename( subdir, name );
1209                 potentialFile += ".png";
1211                 if ( Glib::file_test(potentialFile, Glib::FILE_TEST_EXISTS) && Glib::file_test(potentialFile, Glib::FILE_TEST_IS_REGULAR) ) {
1212                     bool badFile = false;
1213                     try {
1214                         Glib::RefPtr<Gdk::Pixbuf> pb = Gdk::Pixbuf::create_from_file(potentialFile);
1215                         if (pb) {
1216                             dataLoaded = true;
1217                             GdkPixbuf *obj = pb->gobj();
1218                             g_object_ref(obj);
1219                             pb_cache[key] = obj;
1220                             addToIconSet(obj, name, lsize, psize);
1221                             loadNeeded = true;
1222                             if (internalNames.find(name) == internalNames.end()) {
1223                                 internalNames.insert(name);
1224                             }
1225                         }
1226                     } catch ( Glib::FileError &ex ) {
1227                         g_warning("FileError    [%s]", ex.what().c_str());
1228                         badFile = true;
1229                     } catch ( Gdk::PixbufError &ex ) {
1230                         g_warning("PixbufError  [%s]", ex.what().c_str());
1231                         // Invalid contents. Remove cached item
1232                         badFile = true;
1233                     }
1234                     if ( badFile ) {
1235                         g_remove(potentialFile.c_str());
1236                     }
1237                 }
1238             }
1240             if (!dataLoaded) {
1241                 std::list<Glib::ustring> names;
1242                 names.push_back(name);
1243                 if ( legacyNames.find(name) != legacyNames.end() ) {
1244                     names.push_back(legacyNames[name]);
1245                     if ( dump ) {
1246                         g_message("load_svg_pixels([%s] = %s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1247                     }
1248                 }
1249                 guchar* px = load_svg_pixels(names, lsize, psize);
1250                 if (px) {
1251                     GdkPixbuf* pb = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, TRUE, 8,
1252                                                               psize, psize, psize * 4,
1253                                                               reinterpret_cast<GdkPixbufDestroyNotify>(g_free), NULL );
1254                     pb_cache[key] = pb;
1255                     addToIconSet(pb, name, lsize, psize);
1256                     loadNeeded = true;
1257                     if (internalNames.find(name) == internalNames.end()) {
1258                         internalNames.insert(name);
1259                     }
1260                     if (useCache) {
1261                         g_object_ref(pb);
1262                         Glib::RefPtr<Gdk::Pixbuf> ppp = Glib::wrap(pb);
1263                         try {
1264                             ppp->save( potentialFile, "png" );
1265                         } catch ( Glib::FileError &ex ) {
1266                             g_warning("FileError    [%s]", ex.what().c_str());
1267                         } catch ( Gdk::PixbufError &ex ) {
1268                             g_warning("PixbufError  [%s]", ex.what().c_str());
1269                         }
1270                     }
1271                 } else if (dump) {
1272                     g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
1273                 }
1274             }
1275         }
1276         else if (dump) {
1277             g_message("prerender_icon  [%s] %d NOT!!!!!!", name, psize);
1278         }
1279     }
1280     return loadNeeded;
1283 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1285     Glib::ustring key = icon_cache_key(name, psize);
1287     // did we already load this icon at this scale/size?
1288     GdkPixbuf* pb = get_cached_pixbuf(key);
1289     if (!pb) {
1290         std::list<Glib::ustring> names;
1291         names.push_back(name);
1292         guchar *px = load_svg_pixels(names, lsize, psize);
1293         if (px) {
1294             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1295                                           psize, psize, psize * 4,
1296                                           (GdkPixbufDestroyNotify)g_free, NULL);
1297             pb_cache[key] = pb;
1298             addToIconSet(pb, name, lsize, psize);
1299         }
1300     }
1302     if ( pb ) {
1303         // increase refcount since we're handing out ownership
1304         g_object_ref(G_OBJECT(pb));
1305     }
1306     return pb;
1309 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1310                             unsigned r, unsigned g, unsigned b)
1312     int bytesPerPixel = 4;
1313     int spacing = 4;
1314     for ( int y = 0; y < height; y += spacing ) {
1315         guchar *ptr = px + y * stride;
1316         for ( int x = 0; x < width; x += spacing ) {
1317             *(ptr++) = r;
1318             *(ptr++) = g;
1319             *(ptr++) = b;
1320             *(ptr++) = 0xff;
1322             ptr += bytesPerPixel * (spacing - 1);
1323         }
1324     }
1326     if ( width > 1 && height > 1 ) {
1327         // point at the last pixel
1328         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1330         if ( width > 2 ) {
1331             px[4] = r;
1332             px[5] = g;
1333             px[6] = b;
1334             px[7] = 0xff;
1336             ptr[-12] = r;
1337             ptr[-11] = g;
1338             ptr[-10] = b;
1339             ptr[-9] = 0xff;
1340         }
1342         ptr[-4] = r;
1343         ptr[-3] = g;
1344         ptr[-2] = b;
1345         ptr[-1] = 0xff;
1347         px[0 + stride] = r;
1348         px[1 + stride] = g;
1349         px[2 + stride] = b;
1350         px[3 + stride] = 0xff;
1352         ptr[0 - stride] = r;
1353         ptr[1 - stride] = g;
1354         ptr[2 - stride] = b;
1355         ptr[3 - stride] = 0xff;
1357         if ( height > 2 ) {
1358             ptr[0 - stride * 3] = r;
1359             ptr[1 - stride * 3] = g;
1360             ptr[2 - stride * 3] = b;
1361             ptr[3 - stride * 3] = 0xff;
1362         }
1363     }
1366 class preRenderItem
1368 public:
1369     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1370         _lsize( lsize ),
1371         _name( name )
1372     {}
1373     GtkIconSize _lsize;
1374     Glib::ustring _name;
1375 };
1378 static std::vector<preRenderItem> pendingRenders;
1379 static bool callbackHooked = false;
1381 static void addPreRender( GtkIconSize lsize, gchar const *name )
1383     if ( !callbackHooked )
1384     {
1385         callbackHooked = true;
1386         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1387     }
1389     pendingRenders.push_back(preRenderItem(lsize, name));
1392 gboolean icon_prerender_task(gpointer /*data*/) {
1393     if ( inkscapeIsCrashing() ) {
1394         // stop
1395     } else if (!pendingRenders.empty()) {
1396         bool workDone = false;
1397         do {
1398             preRenderItem single = pendingRenders.front();
1399             pendingRenders.erase(pendingRenders.begin());
1400             int psize = sp_icon_get_phys_size(single._lsize);
1401             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1402         } while (!pendingRenders.empty() && !workDone);
1403     }
1405     if (!inkscapeIsCrashing() && !pendingRenders.empty()) {
1406         return TRUE;
1407     } else {
1408         callbackHooked = false;
1409         return FALSE;
1410     }
1414 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1415     gchar* id = 0;
1416     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1417     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1418     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1419     if ( id ) {
1420         int psize = sp_icon_get_phys_size(lsize);
1421         g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1422         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1423             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1424                 prerender_icon(id, lsize, psize);
1425                 pendingRenders.erase(it);
1426                 g_message("    prerender for %s:%d:%d", id, lsize, psize);
1427                 if (lsize != size) {
1428                     int psize = sp_icon_get_phys_size(size);
1429                     prerender_icon(id, size, psize);
1430                 }
1431                 break;
1432             }
1433         }
1434     }
1436     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1439 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1440     GtkImage* img = GTK_IMAGE(widget);
1441     gchar const* iconName = 0;
1442     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1443     gtk_image_get_icon_name(img, &iconName, &size);
1444     if ( iconName ) {
1445         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1446         if ( type == GTK_IMAGE_ICON_NAME ) {
1448             gint iconSize = 0;
1449             gchar* iconName = 0;
1450             {
1451                 g_object_get(G_OBJECT(widget),
1452                              "icon-name", &iconName,
1453                              "icon-size", &iconSize,
1454                              NULL);
1455             }
1457             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1458                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1459                     int psize = sp_icon_get_phys_size(size);
1460                     prerender_icon(iconName, size, psize);
1461                     pendingRenders.erase(it);
1462                     break;
1463                 }
1464             }
1466             gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1467             gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1468         } else {
1469             g_warning("UNEXPECTED TYPE of %d", (int)type);
1470         }
1471     }
1473     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1477 /*
1478   Local Variables:
1479   mode:c++
1480   c-file-style:"stroustrup"
1481   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1482   indent-tabs-mode:nil
1483   fill-column:99
1484   End:
1485 */
1486 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :