Code

70dee457c961b7e03a786c4563902b18ad73bdae
[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 struct svg_doc_cache_t
1042     SPDocument *doc;
1043     NRArenaItem *root;
1044 };
1046 static std::map<Glib::ustring, svg_doc_cache_t *> doc_cache;
1047 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
1049 Glib::ustring icon_cache_key(gchar const *name, unsigned psize)
1051     Glib::ustring key=name;
1052     key += ":";
1053     key += psize;
1054     return key;
1057 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
1058     GdkPixbuf* pb = 0;
1059     std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
1060     if ( found != pb_cache.end() ) {
1061         pb = found->second;
1062     }
1063     return pb;
1066 static std::list<gchar*> &icons_svg_paths()
1068     static std::list<gchar *> sources;
1069     static bool initialized = false;
1070     if (!initialized) {
1071         // Fall back from user prefs dir into system locations.
1072         gchar *userdir = profile_path("icons");
1073         sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
1074         sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
1075         g_free(userdir);
1076         initialized = true;
1077     }
1078     return sources;
1081 // this function renders icons from icons.svg and returns the pixels.
1082 static guchar *load_svg_pixels(gchar const *name,
1083                                unsigned /*lsize*/, unsigned psize)
1085     SPDocument *doc = NULL;
1086     NRArenaItem *root = NULL;
1087     svg_doc_cache_t *info = NULL;
1089     std::list<gchar *> &sources = icons_svg_paths();
1091     // Try each document in turn until we successfully load the icon from one
1092     guchar *px=NULL;
1093     for (std::list<gchar*>::iterator i = sources.begin(); i != sources.end() && !px; ++i) {
1094         gchar *doc_filename = *i;
1096         // Did we already load this doc?
1097         Glib::ustring key(doc_filename);
1098         info = 0;
1099         {
1100             std::map<Glib::ustring, svg_doc_cache_t *>::iterator i = doc_cache.find(key);
1101             if ( i != doc_cache.end() ) {
1102                 info = i->second;
1103             }
1104         }
1106         /* Try to load from document. */
1107         if (!info &&
1108             Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) &&
1109             (doc = SPDocument::createNewDoc( doc_filename, FALSE )) ) {
1111             //g_message("Loaded icon file %s", doc_filename);
1112             // prep the document
1113             doc->ensureUpToDate();
1114             /* Create new arena */
1115             NRArena *arena = NRArena::create();
1116             /* Create ArenaItem and set transform */
1117             unsigned visionkey = SPItem::display_key_new(1);
1118             /* fixme: Memory manage root if needed (Lauris) */
1119             // This needs to be fixed indeed; this leads to a memory leak of a few megabytes these days
1120             // because shapes are being rendered which are not being freed
1121             // Valgrind output:
1122             /*==7014== 1,548,344 bytes in 599 blocks are possibly lost in loss record 20,361 of 20,362
1123             ==7014==    at 0x4A05974: operator new(unsigned long) (vg_replace_malloc.c:220)
1124             ==7014==    by 0x4F1015: __gnu_cxx::new_allocator<Shape::point_data>::allocate(unsigned long, void const*) (new_allocator.h:89)
1125             ==7014==    by 0x4F02AC: std::_Vector_base<Shape::point_data, std::allocator<Shape::point_data> >::_M_allocate(unsigned long) (stl_vector.h:140)
1126             ==7014==    by 0xCF62D7: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::_M_fill_insert(__gnu_cxx::__normal_iterator<Shape::point_data*, std::vector<Shape::point_data, std::allocator<Shape::point_data> > >, unsigned long, Shape::point_data const&) (vector.tcc:414)
1127             ==7014==    by 0xCF4D45: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::insert(__gnu_cxx::__normal_iterator<Shape::point_data*, std::vector<Shape::point_data, std::allocator<Shape::point_data> > >, unsigned long, Shape::point_data const&) (stl_vector.h:851)
1128             ==7014==    by 0xCF3DCD: std::vector<Shape::point_data, std::allocator<Shape::point_data> >::resize(unsigned long, Shape::point_data) (stl_vector.h:557)
1129             ==7014==    by 0xCEA771: Shape::AddPoint(Geom::Point) (Shape.cpp:326)
1130             ==7014==    by 0xD0F413: Shape::ConvertToShape(Shape*, fill_typ, bool) (ShapeSweep.cpp:257)
1131             ==7014==    by 0x5ECD4F: nr_arena_shape_update_stroke(NRArenaShape*, NRGC*, NRRectL*) (nr-arena-shape.cpp:651)
1132             ==7014==    by 0x5EE0DA: nr_arena_shape_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-shape.cpp:862)
1133             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1134             ==7014==    by 0x5E9DDE: nr_arena_group_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-group.cpp:228)
1135             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1136             ==7014==    by 0x5E9DDE: nr_arena_group_render(_cairo*, NRArenaItem*, NRRectL*, NRPixBlock*, unsigned int) (nr-arena-group.cpp:228)
1137             ==7014==    by 0x5E72FB: nr_arena_item_invoke_render(_cairo*, NRArenaItem*, NRRectL const*, NRPixBlock*, unsigned int) (nr-arena-item.cpp:578)
1138             */
1139             root = SP_ITEM(doc->getRoot())->invoke_show(arena, visionkey, SP_ITEM_SHOW_DISPLAY );
1141             // store into the cache
1142             info = new svg_doc_cache_t;
1143             g_assert(info);
1145             info->doc=doc;
1146             info->root=root;
1147             doc_cache[key]=info;
1148         }
1149         if (info) {
1150             doc=info->doc;
1151             root=info->root;
1152         }
1154         // move on to the next document if we couldn't get anything
1155         if (!info && !doc) {
1156             continue;
1157         }
1159         px = sp_icon_doc_icon( doc, root, name, psize );
1160 //         if (px) {
1161 //             g_message("Found icon %s in %s", name, doc_filename);
1162 //         }
1163     }
1165 //     if (!px) {
1166 //         g_message("Not found icon %s", name);
1167 //     }
1168     return px;
1171 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
1172     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1173     GtkStockItem stock;
1174     gboolean stockFound = gtk_stock_lookup( name, &stock );
1175    if ( !stockFound ) {
1176         Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
1177         if (dump) {
1178             g_message("    set in a builtin for %s:%d:%d", name, lsize, psize);
1179         }
1180     }
1183 void Inkscape::queueIconPrerender( Glib::ustring const &name, Inkscape::IconSize lsize )
1185     GtkStockItem stock;
1186     gboolean stockFound = gtk_stock_lookup( name.c_str(), &stock );
1187     gboolean themedFound = gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name.c_str());
1188     if (!stockFound && !themedFound ) {
1189         gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
1190         if ( !sizeMapDone ) {
1191             injectCustomSize();
1192         }
1193         GtkIconSize mappedSize = iconSizeLookup[trySize];
1195         int psize = sp_icon_get_phys_size(lsize);
1196         // TODO place in a queue that is triggered by other map events
1197         prerender_icon(name.c_str(), mappedSize, psize);
1198     }
1201 static std::map<unsigned, Glib::ustring> sizePaths;
1203 static std::string getDestDir( unsigned psize )
1205     if ( sizePaths.find(psize) == sizePaths.end() ) {
1206         gchar *tmp = g_strdup_printf("%dx%d", psize, psize);
1207         sizePaths[psize] = tmp;
1208         g_free(tmp);
1209     }
1211     return sizePaths[psize];
1214 // returns true if icon needed preloading, false if nothing was done
1215 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
1217     bool loadNeeded = false;
1218     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1219     static bool useCache = Inkscape::Preferences::get()->getBool("/debug/icons/useCache");
1221     Glib::ustring key = icon_cache_key(name, psize);
1222     if ( !get_cached_pixbuf(key) ) {
1223         if ((internalNames.find(name) != internalNames.end())
1224             || (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name))) {
1225             if (dump) {
1226                 g_message("prerender_icon  [%s] %d:%d", name, lsize, psize);
1227             }
1229             std::string potentialFile;
1230             bool dataLoaded = false;
1231             if ( useCache ) {
1232                 // In file encoding:
1233                 std::string iconCacheDir = Glib::build_filename(Glib::build_filename(Glib::get_user_cache_dir(), "inkscape"), "icons");
1234                 std::string subpart = getDestDir(psize);
1235                 if (subpart.empty()) {
1236                     g_message("Is empty");
1237                 }
1238                 std::string subdir = Glib::build_filename( iconCacheDir, subpart );
1239                 if ( !Glib::file_test(subdir, Glib::FILE_TEST_EXISTS) ) {
1240                     g_message("NEED SUB OF   [%s]", subdir.c_str());
1241                     g_mkdir_with_parents( subdir.c_str(), 0x1ED );
1242                 }
1243                 potentialFile = Glib::build_filename( subdir, name );
1244                 potentialFile += ".png";
1246                 if ( Glib::file_test(potentialFile, Glib::FILE_TEST_EXISTS) && Glib::file_test(potentialFile, Glib::FILE_TEST_IS_REGULAR) ) {
1247                     Glib::RefPtr<Gdk::Pixbuf> pb = Gdk::Pixbuf::create_from_file(potentialFile);
1248                     if (pb) {
1249                         dataLoaded = true;
1250                         GdkPixbuf *obj = pb->gobj();
1251                         g_object_ref(obj);
1252                         pb_cache[key] = obj;
1253                         addToIconSet(obj, name, lsize, psize);
1254                         loadNeeded = true;
1255                         if (internalNames.find(name) == internalNames.end()) {
1256                             internalNames.insert(name);
1257                         }
1258                     }
1259                 }
1260             }
1262             if (!dataLoaded) {
1263                 guchar* px = load_svg_pixels(name, lsize, psize);
1264                 if ( !px ) {
1265                     // check for a fallback name
1266                     if ( legacyNames.find(name) != legacyNames.end() ) {
1267                         if ( dump ) {
1268                             g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1269                         }
1270                         px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
1271                     }
1272                 }
1273                 if (px) {
1274                     GdkPixbuf* pb = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, TRUE, 8,
1275                                                               psize, psize, psize * 4,
1276                                                               reinterpret_cast<GdkPixbufDestroyNotify>(g_free), NULL );
1277                     pb_cache[key] = pb;
1278                     addToIconSet(pb, name, lsize, psize);
1279                     loadNeeded = true;
1280                     if (internalNames.find(name) == internalNames.end()) {
1281                         internalNames.insert(name);
1282                     }
1283                     if (useCache) {
1284                         g_object_ref(pb);
1285                         Glib::RefPtr<Gdk::Pixbuf> ppp = Glib::wrap(pb);
1286                         try {
1287                             ppp->save( potentialFile, "png" );
1288                         } catch ( Glib::FileError &ex ) {
1289                             g_warning("FileError    [%s]", ex.what().c_str());
1290                         } catch ( Gdk::PixbufError &ex ) {
1291                             g_warning("PixbufError  [%s]", ex.what().c_str());
1292                         }
1293                     }
1294                 } else if (dump) {
1295                     g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
1296                 }
1297             }
1298         }
1299         else if (dump) {
1300             g_message("prerender_icon  [%s] %d NOT!!!!!!", name, psize);
1301         }
1302     }
1303     return loadNeeded;
1306 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1308     Glib::ustring key = icon_cache_key(name, psize);
1310     // did we already load this icon at this scale/size?
1311     GdkPixbuf* pb = get_cached_pixbuf(key);
1312     if (!pb) {
1313         guchar *px = load_svg_pixels(name, lsize, psize);
1314         if (px) {
1315             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1316                                           psize, psize, psize * 4,
1317                                           (GdkPixbufDestroyNotify)g_free, NULL);
1318             pb_cache[key] = pb;
1319             addToIconSet(pb, name, lsize, psize);
1320         }
1321     }
1323     if ( pb ) {
1324         // increase refcount since we're handing out ownership
1325         g_object_ref(G_OBJECT(pb));
1326     }
1327     return pb;
1330 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1331                             unsigned r, unsigned g, unsigned b)
1333     int bytesPerPixel = 4;
1334     int spacing = 4;
1335     for ( int y = 0; y < height; y += spacing ) {
1336         guchar *ptr = px + y * stride;
1337         for ( int x = 0; x < width; x += spacing ) {
1338             *(ptr++) = r;
1339             *(ptr++) = g;
1340             *(ptr++) = b;
1341             *(ptr++) = 0xff;
1343             ptr += bytesPerPixel * (spacing - 1);
1344         }
1345     }
1347     if ( width > 1 && height > 1 ) {
1348         // point at the last pixel
1349         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1351         if ( width > 2 ) {
1352             px[4] = r;
1353             px[5] = g;
1354             px[6] = b;
1355             px[7] = 0xff;
1357             ptr[-12] = r;
1358             ptr[-11] = g;
1359             ptr[-10] = b;
1360             ptr[-9] = 0xff;
1361         }
1363         ptr[-4] = r;
1364         ptr[-3] = g;
1365         ptr[-2] = b;
1366         ptr[-1] = 0xff;
1368         px[0 + stride] = r;
1369         px[1 + stride] = g;
1370         px[2 + stride] = b;
1371         px[3 + stride] = 0xff;
1373         ptr[0 - stride] = r;
1374         ptr[1 - stride] = g;
1375         ptr[2 - stride] = b;
1376         ptr[3 - stride] = 0xff;
1378         if ( height > 2 ) {
1379             ptr[0 - stride * 3] = r;
1380             ptr[1 - stride * 3] = g;
1381             ptr[2 - stride * 3] = b;
1382             ptr[3 - stride * 3] = 0xff;
1383         }
1384     }
1387 class preRenderItem
1389 public:
1390     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1391         _lsize( lsize ),
1392         _name( name )
1393     {}
1394     GtkIconSize _lsize;
1395     Glib::ustring _name;
1396 };
1399 static std::vector<preRenderItem> pendingRenders;
1400 static bool callbackHooked = false;
1402 static void addPreRender( GtkIconSize lsize, gchar const *name )
1404     if ( !callbackHooked )
1405     {
1406         callbackHooked = true;
1407         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1408     }
1410     pendingRenders.push_back(preRenderItem(lsize, name));
1413 gboolean icon_prerender_task(gpointer /*data*/) {
1414     if ( inkscapeIsCrashing() ) {
1415         // stop
1416     } else if (!pendingRenders.empty()) {
1417         bool workDone = false;
1418         do {
1419             preRenderItem single = pendingRenders.front();
1420             pendingRenders.erase(pendingRenders.begin());
1421             int psize = sp_icon_get_phys_size(single._lsize);
1422             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1423         } while (!pendingRenders.empty() && !workDone);
1424     }
1426     if (!inkscapeIsCrashing() && !pendingRenders.empty()) {
1427         return TRUE;
1428     } else {
1429         callbackHooked = false;
1430         return FALSE;
1431     }
1435 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1436     gchar* id = 0;
1437     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1438     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1439     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1440     if ( id ) {
1441         int psize = sp_icon_get_phys_size(lsize);
1442         g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1443         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1444             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1445                 prerender_icon(id, lsize, psize);
1446                 pendingRenders.erase(it);
1447                 g_message("    prerender for %s:%d:%d", id, lsize, psize);
1448                 if (lsize != size) {
1449                     int psize = sp_icon_get_phys_size(size);
1450                     prerender_icon(id, size, psize);
1451                 }
1452                 break;
1453             }
1454         }
1455     }
1457     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1460 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1461     GtkImage* img = GTK_IMAGE(widget);
1462     gchar const* iconName = 0;
1463     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1464     gtk_image_get_icon_name(img, &iconName, &size);
1465     if ( iconName ) {
1466         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1467         if ( type == GTK_IMAGE_ICON_NAME ) {
1469             gint iconSize = 0;
1470             gchar* iconName = 0;
1471             {
1472                 g_object_get(G_OBJECT(widget),
1473                              "icon-name", &iconName,
1474                              "icon-size", &iconSize,
1475                              NULL);
1476             }
1478             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1479                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1480                     int psize = sp_icon_get_phys_size(size);
1481                     prerender_icon(iconName, size, psize);
1482                     pendingRenders.erase(it);
1483                     break;
1484                 }
1485             }
1487             gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1488             gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1489         } else {
1490             g_warning("UNEXPECTED TYPE of %d", (int)type);
1491         }
1492     }
1494     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1498 /*
1499   Local Variables:
1500   mode:c++
1501   c-file-style:"stroustrup"
1502   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1503   indent-tabs-mode:nil
1504   fill-column:99
1505   End:
1506 */
1507 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :