Code

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