Code

Merge and cleanup of GSoC C++-ification project.
[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>
24 #include "path-prefix.h"
25 #include "preferences.h"
26 #include "inkscape.h"
27 #include "document.h"
28 #include "sp-item.h"
29 #include "display/nr-arena.h"
30 #include "display/nr-arena-item.h"
31 #include "io/sys.h"
33 #include "icon.h"
35 static gboolean icon_prerender_task(gpointer data);
37 static void addPreRender( GtkIconSize lsize, gchar const *name );
39 static void sp_icon_class_init(SPIconClass *klass);
40 static void sp_icon_init(SPIcon *icon);
41 static void sp_icon_dispose(GObject *object);
43 static void sp_icon_reset(SPIcon *icon);
44 static void sp_icon_clear(SPIcon *icon);
46 static void sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition);
47 static void sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation);
48 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event);
50 static void sp_icon_paint(SPIcon *icon, GdkRectangle const *area);
52 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen );
53 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style );
54 static void sp_icon_theme_changed( SPIcon *icon );
56 static GdkPixbuf *sp_icon_image_load_pixmap(gchar const *name, unsigned lsize, unsigned psize);
57 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize);
59 static void sp_icon_overlay_pixels( guchar *px, int width, int height, int stride,
60                                     unsigned r, unsigned g, unsigned b );
62 static void injectCustomSize();
64 static GtkWidgetClass *parent_class;
66 static bool sizeDirty = true;
68 static bool sizeMapDone = false;
69 static GtkIconSize iconSizeLookup[] = {
70     GTK_ICON_SIZE_INVALID,
71     GTK_ICON_SIZE_MENU,
72     GTK_ICON_SIZE_SMALL_TOOLBAR,
73     GTK_ICON_SIZE_LARGE_TOOLBAR,
74     GTK_ICON_SIZE_BUTTON,
75     GTK_ICON_SIZE_DND,
76     GTK_ICON_SIZE_DIALOG,
77     GTK_ICON_SIZE_MENU, // for Inkscape::ICON_SIZE_DECORATION
78 };
80 static std::map<Glib::ustring, Glib::ustring> legacyNames;
82 class IconCacheItem
83 {
84 public:
85     IconCacheItem( GtkIconSize lsize, GdkPixbuf* pb ) :
86         _lsize( lsize ),
87         _pb( pb )
88     {}
89     GtkIconSize _lsize;
90     GdkPixbuf* _pb;
91 };
93 static std::map<Glib::ustring, std::vector<IconCacheItem> > iconSetCache;
94 static std::set<Glib::ustring> internalNames;
96 GType
97 sp_icon_get_type()
98 {
99     static GType type = 0;
100     if (!type) {
101         GTypeInfo info = {
102             sizeof(SPIconClass),
103             NULL,
104             NULL,
105             (GClassInitFunc) sp_icon_class_init,
106             NULL,
107             NULL,
108             sizeof(SPIcon),
109             0,
110             (GInstanceInitFunc) sp_icon_init,
111             NULL
112         };
113         type = g_type_register_static(GTK_TYPE_WIDGET, "SPIcon", &info, (GTypeFlags)0);
114     }
115     return type;
118 static void
119 sp_icon_class_init(SPIconClass *klass)
121     GObjectClass *object_class;
122     GtkWidgetClass *widget_class;
124     object_class = (GObjectClass *) klass;
125     widget_class = (GtkWidgetClass *) klass;
127     parent_class = (GtkWidgetClass*)g_type_class_peek_parent(klass);
129     object_class->dispose = sp_icon_dispose;
131     widget_class->size_request = sp_icon_size_request;
132     widget_class->size_allocate = sp_icon_size_allocate;
133     widget_class->expose_event = sp_icon_expose;
134     widget_class->screen_changed = sp_icon_screen_changed;
135     widget_class->style_set = sp_icon_style_set;
139 static void
140 sp_icon_init(SPIcon *icon)
142     GTK_WIDGET_FLAGS(icon) |= GTK_NO_WINDOW;
143     icon->lsize = Inkscape::ICON_SIZE_BUTTON;
144     icon->psize = 0;
145     icon->name = 0;
146     icon->pb = 0;
149 static void
150 sp_icon_dispose(GObject *object)
152     SPIcon *icon = SP_ICON(object);
153     sp_icon_clear(icon);
154     if ( icon->name ) {
155         g_free( icon->name );
156         icon->name = 0;
157     }
159     ((GObjectClass *) (parent_class))->dispose(object);
162 static void sp_icon_reset( SPIcon *icon ) {
163     icon->psize = 0;
164     sp_icon_clear(icon);
167 static void sp_icon_clear( SPIcon *icon ) {
168     if (icon->pb) {
169         g_object_unref(G_OBJECT(icon->pb));
170         icon->pb = NULL;
171     }
174 static void
175 sp_icon_size_request(GtkWidget *widget, GtkRequisition *requisition)
177     SPIcon const *icon = SP_ICON(widget);
179     int const size = ( icon->psize
180                        ? icon->psize
181                        : sp_icon_get_phys_size(icon->lsize) );
182     requisition->width = size;
183     requisition->height = size;
186 static void
187 sp_icon_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
189     widget->allocation = *allocation;
191     if (GTK_WIDGET_DRAWABLE(widget)) {
192         gtk_widget_queue_draw(widget);
193     }
196 static int sp_icon_expose(GtkWidget *widget, GdkEventExpose *event)
198     if ( GTK_WIDGET_DRAWABLE(widget) ) {
199         SPIcon *icon = SP_ICON(widget);
200         if ( !icon->pb ) {
201             sp_icon_fetch_pixbuf( icon );
202         }
204         sp_icon_paint(SP_ICON(widget), &event->area);
205     }
207     return TRUE;
210 static GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize );
212 // PUBLIC CALL:
213 void sp_icon_fetch_pixbuf( SPIcon *icon )
215     if ( icon ) {
216         if ( !icon->pb ) {
217             icon->psize = sp_icon_get_phys_size(icon->lsize);
218             icon->pb = renderup(icon->name, icon->lsize, icon->psize);
219         }
220     }
223 GdkPixbuf* renderup( gchar const* name, Inkscape::IconSize lsize, unsigned psize ) {
224     GtkIconTheme *theme = gtk_icon_theme_get_default();
226     GdkPixbuf *pb = 0;
227     if (gtk_icon_theme_has_icon(theme, name)) {
228         pb = gtk_icon_theme_load_icon(theme, name, psize, (GtkIconLookupFlags) 0, NULL);
229     }
230     if (!pb) {
231         pb = sp_icon_image_load_svg( name, Inkscape::getRegisteredIconSize(lsize), psize );
232         if (!pb && (legacyNames.find(name) != legacyNames.end())) {
233             if ( Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg") ) {
234                 g_message("Checking fallback [%s]->[%s]", name, legacyNames[name].c_str());
235             }
236             pb = sp_icon_image_load_svg( legacyNames[name].c_str(), Inkscape::getRegisteredIconSize(lsize), psize );
237         }
239         // if this was loaded from SVG, add it as a builtin icon
240         if (pb) {
241             gtk_icon_theme_add_builtin_icon(name, psize, pb);
242         }
243     }
244     if (!pb) {
245         pb = sp_icon_image_load_pixmap( name, lsize, psize );
246     }
247     if ( !pb ) {
248         // TODO: We should do something more useful if we can't load the image.
249         g_warning ("failed to load icon '%s'", name);
250     }
251     return pb;
254 static void sp_icon_screen_changed( GtkWidget *widget, GdkScreen *previous_screen )
256     if ( GTK_WIDGET_CLASS( parent_class )->screen_changed ) {
257         GTK_WIDGET_CLASS( parent_class )->screen_changed( widget, previous_screen );
258     }
259     SPIcon *icon = SP_ICON(widget);
260     sp_icon_theme_changed(icon);
263 static void sp_icon_style_set( GtkWidget *widget, GtkStyle *previous_style )
265     if ( GTK_WIDGET_CLASS( parent_class )->style_set ) {
266         GTK_WIDGET_CLASS( parent_class )->style_set( widget, previous_style );
267     }
268     SPIcon *icon = SP_ICON(widget);
269     sp_icon_theme_changed(icon);
272 static void sp_icon_theme_changed( SPIcon *icon )
274     bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
275     if ( dump ) {
276         g_message("Got a change bump for this icon");
277     }
278     sizeDirty = true;
279     sp_icon_reset(icon);
280     gtk_widget_queue_draw( GTK_WIDGET(icon) );
284 static void imageMapCB(GtkWidget* widget, gpointer user_data);
285 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data);
286 static bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize);
287 static Glib::ustring icon_cache_key(gchar const *name, unsigned psize);
288 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
290 static void setupLegacyNaming() {
291     legacyNames["document-import"] ="file_import";
292     legacyNames["document-export"] ="file_export";
293     legacyNames["document-import-ocal"] ="ocal_import";
294     legacyNames["document-export-ocal"] ="ocal_export";
295     legacyNames["document-metadata"] ="document_metadata";
296     legacyNames["dialog-input-devices"] ="input_devices";
297     legacyNames["edit-duplicate"] ="edit_duplicate";
298     legacyNames["edit-clone"] ="edit_clone";
299     legacyNames["edit-clone-unlink"] ="edit_unlink_clone";
300     legacyNames["edit-select-original"] ="edit_select_original";
301     legacyNames["edit-undo-history"] ="edit_undo_history";
302     legacyNames["edit-paste-in-place"] ="selection_paste_in_place";
303     legacyNames["edit-paste-style"] ="selection_paste_style";
304     legacyNames["selection-make-bitmap-copy"] ="selection_bitmap";
305     legacyNames["edit-select-all"] ="selection_select_all";
306     legacyNames["edit-select-all-layers"] ="selection_select_all_in_all_layers";
307     legacyNames["edit-select-invert"] ="selection_invert";
308     legacyNames["edit-select-none"] ="selection_deselect";
309     legacyNames["dialog-xml-editor"] ="xml_editor";
310     legacyNames["zoom-original"] ="zoom_1_to_1";
311     legacyNames["zoom-half-size"] ="zoom_1_to_2";
312     legacyNames["zoom-double-size"] ="zoom_2_to_1";
313     legacyNames["zoom-fit-selection"] ="zoom_select";
314     legacyNames["zoom-fit-drawing"] ="zoom_draw";
315     legacyNames["zoom-fit-page"] ="zoom_page";
316     legacyNames["zoom-fit-width"] ="zoom_pagewidth";
317     legacyNames["zoom-previous"] ="zoom_previous";
318     legacyNames["zoom-next"] ="zoom_next";
319     legacyNames["zoom-in"] ="zoom_in";
320     legacyNames["zoom-out"] ="zoom_out";
321     legacyNames["show-grid"] ="grid";
322     legacyNames["show-guides"] ="guides";
323     legacyNames["color-management"] ="color_management";
324     legacyNames["show-dialogs"] ="dialog_toggle";
325     legacyNames["dialog-messages"] ="messages";
326     legacyNames["dialog-scripts"] ="scripts";
327     legacyNames["window-previous"] ="window_previous";
328     legacyNames["window-next"] ="window_next";
329     legacyNames["dialog-icon-preview"] ="view_icon_preview";
330     legacyNames["window-new"] ="view_new";
331     legacyNames["view-fullscreen"] ="fullscreen";
332     legacyNames["layer-new"] ="new_layer";
333     legacyNames["layer-rename"] ="rename_layer";
334     legacyNames["layer-previous"] ="switch_to_layer_above";
335     legacyNames["layer-next"] ="switch_to_layer_below";
336     legacyNames["selection-move-to-layer-above"] ="move_selection_above";
337     legacyNames["selection-move-to-layer-below"] ="move_selection_below";
338     legacyNames["layer-raise"] ="raise_layer";
339     legacyNames["layer-lower"] ="lower_layer";
340     legacyNames["layer-top"] ="layer_to_top";
341     legacyNames["layer-bottom"] ="layer_to_bottom";
342     legacyNames["layer-delete"] ="delete_layer";
343     legacyNames["dialog-layers"] ="layers";
344     legacyNames["dialog-fill-and-stroke"] ="fill_and_stroke";
345     legacyNames["dialog-object-properties"] ="dialog_item_properties";
346     legacyNames["object-group"] ="selection_group";
347     legacyNames["object-ungroup"] ="selection_ungroup";
348     legacyNames["selection-raise"] ="selection_up";
349     legacyNames["selection-lower"] ="selection_down";
350     legacyNames["selection-top"] ="selection_top";
351     legacyNames["selection-bottom"] ="selection_bot";
352     legacyNames["object-rotate-left"] ="object_rotate_90_CCW";
353     legacyNames["object-rotate-right"] ="object_rotate_90_CW";
354     legacyNames["object-flip-horizontal"] ="object_flip_hor";
355     legacyNames["object-flip-vertical"] ="object_flip_ver";
356     legacyNames["dialog-transform"] ="object_trans";
357     legacyNames["dialog-align-and-distribute"] ="object_align";
358     legacyNames["dialog-rows-and-columns"] ="grid_arrange";
359     legacyNames["object-to-path"] ="object_tocurve";
360     legacyNames["stroke-to-path"] ="stroke_tocurve";
361     legacyNames["bitmap-trace"] ="selection_trace";
362     legacyNames["path-union"] ="union";
363     legacyNames["path-difference"] ="difference";
364     legacyNames["path-intersection"] ="intersection";
365     legacyNames["path-exclusion"] ="exclusion";
366     legacyNames["path-division"] ="division";
367     legacyNames["path-cut"] ="cut_path";
368     legacyNames["path-combine"] ="selection_combine";
369     legacyNames["path-break-apart"] ="selection_break";
370     legacyNames["path-outset"] ="outset_path";
371     legacyNames["path-inset"] ="inset_path";
372     legacyNames["path-offset-dynamic"] ="dynamic_offset";
373     legacyNames["path-offset-linked"] ="linked_offset";
374     legacyNames["path-simplify"] ="simplify";
375     legacyNames["path-reverse"] ="selection_reverse";
376     legacyNames["dialog-text-and-font"] ="object_font";
377     legacyNames["text-put-on-path"] ="put_on_path";
378     legacyNames["text-remove-from-path"] ="remove_from_path";
379     legacyNames["text-flow-into-frame"] ="flow_into_frame";
380     legacyNames["text-unflow"] ="unflow";
381     legacyNames["text-convert-to-regular"] ="convert_to_text";
382     legacyNames["text-unkern"] ="remove_manual_kerns";
383     legacyNames["help-keyboard-shortcuts"] ="help_keys";
384     legacyNames["help-contents"] ="help_tutorials";
385     legacyNames["inkscape-logo"] ="inkscape_options";
386     legacyNames["dialog-memory"] ="about_memory";
387     legacyNames["tool-pointer"] ="draw_select";
388     legacyNames["tool-node-editor"] ="draw_node";
389     legacyNames["tool-tweak"] ="draw_tweak";
390     legacyNames["zoom"] ="draw_zoom";
391     legacyNames["draw-rectangle"] ="draw_rect";
392     legacyNames["draw-cuboid"] ="draw_3dbox";
393     legacyNames["draw-ellipse"] ="draw_arc";
394     legacyNames["draw-polygon-star"] ="draw_star";
395     legacyNames["draw-spiral"] ="draw_spiral";
396     legacyNames["draw-freehand"] ="draw_freehand";
397     legacyNames["draw-path"] ="draw_pen";
398     legacyNames["draw-calligraphic"] ="draw_calligraphic";
399     legacyNames["draw-eraser"] ="draw_erase";
400     legacyNames["color-fill"] ="draw_paintbucket";
401     legacyNames["draw-text"] ="draw_text";
402     legacyNames["draw-connector"] ="draw_connector";
403     legacyNames["color-gradient"] ="draw_gradient";
404     legacyNames["color-picker"] ="draw_dropper";
405     legacyNames["transform-affect-stroke"] ="transform_stroke";
406     legacyNames["transform-affect-rounded-corners"] ="transform_corners";
407     legacyNames["transform-affect-gradient"] ="transform_gradient";
408     legacyNames["transform-affect-pattern"] ="transform_pattern";
409     legacyNames["node-add"] ="node_insert";
410     legacyNames["node-delete"] ="node_delete";
411     legacyNames["node-join"] ="node_join";
412     legacyNames["node-break"] ="node_break";
413     legacyNames["node-join-segment"] ="node_join_segment";
414     legacyNames["node-delete-segment"] ="node_delete_segment";
415     legacyNames["node-type-cusp"] ="node_cusp";
416     legacyNames["node-type-smooth"] ="node_smooth";
417     legacyNames["node-type-symmetric"] ="node_symmetric";
418     legacyNames["node-type-auto-smooth"] ="node_auto";
419     legacyNames["node-segment-curve"] ="node_curve";
420     legacyNames["node-segment-line"] ="node_line";
421     legacyNames["show-node-handles"] ="nodes_show_handles";
422     legacyNames["path-effect-parameter-next"] ="edit_next_parameter";
423     legacyNames["show-path-outline"] ="nodes_show_helperpath";
424     legacyNames["path-clip-edit"] ="nodeedit-clippath";
425     legacyNames["path-mask-edit"] ="nodeedit-mask";
426     legacyNames["node-type-cusp"] ="node_cusp";
427     legacyNames["object-tweak-push"] ="tweak_move_mode";
428     legacyNames["object-tweak-attract"] ="tweak_move_mode_inout";
429     legacyNames["object-tweak-randomize"] ="tweak_move_mode_jitter";
430     legacyNames["object-tweak-shrink"] ="tweak_scale_mode";
431     legacyNames["object-tweak-rotate"] ="tweak_rotate_mode";
432     legacyNames["object-tweak-duplicate"] ="tweak_moreless_mode";
433     legacyNames["object-tweak-push"] ="tweak_move_mode";
434     legacyNames["path-tweak-push"] ="tweak_push_mode";
435     legacyNames["path-tweak-shrink"] ="tweak_shrink_mode";
436     legacyNames["path-tweak-attract"] ="tweak_attract_mode";
437     legacyNames["path-tweak-roughen"] ="tweak_roughen_mode";
438     legacyNames["object-tweak-paint"] ="tweak_colorpaint_mode";
439     legacyNames["object-tweak-jitter-color"] ="tweak_colorjitter_mode";
440     legacyNames["object-tweak-blur"] ="tweak_blur_mode";
441     legacyNames["rectangle-make-corners-sharp"] ="squared_corner";
442     legacyNames["perspective-parallel"] ="toggle_vp_x";
443     legacyNames["draw-ellipse-whole"] ="reset_circle";
444     legacyNames["draw-ellipse-segment"] ="circle_closed_arc";
445     legacyNames["draw-ellipse-arc"] ="circle_open_arc";
446     legacyNames["draw-polygon"] ="star_flat";
447     legacyNames["draw-star"] ="star_angled";
448     legacyNames["path-mode-bezier"] ="bezier_mode";
449     legacyNames["path-mode-spiro"] ="spiro_splines_mode";
450     legacyNames["path-mode-polyline"] ="polylines_mode";
451     legacyNames["path-mode-polyline-paraxial"] ="paraxial_lines_mode";
452     legacyNames["draw-use-tilt"] ="guse_tilt";
453     legacyNames["draw-use-pressure"] ="guse_pressure";
454     legacyNames["draw-trace-background"] ="trace_background";
455     legacyNames["draw-eraser-delete-objects"] ="delete_object";
456     legacyNames["format-text-direction-vertical"] ="writing_mode_tb";
457     legacyNames["format-text-direction-horizontal"] ="writing_mode_lr";
458     legacyNames["connector-avoid"] ="connector_avoid";
459     legacyNames["connector-ignore"] ="connector_ignore";
460     legacyNames["object-fill"] ="controls_fill";
461     legacyNames["object-stroke"] ="controls_stroke";
462     legacyNames["snap"] ="toggle_snap_global";
463     legacyNames["snap-bounding-box"] ="toggle_snap_bbox";
464     legacyNames["snap-bounding-box-edges"] ="toggle_snap_to_bbox_path";
465     legacyNames["snap-bounding-box-corners"] ="toggle_snap_to_bbox_node";
466     legacyNames["snap-bounding-box-midpoints"] ="toggle_snap_to_bbox_edge_midpoints";
467     legacyNames["snap-bounding-box-center"] ="toggle_snap_to_bbox_midpoints";
468     legacyNames["snap-nodes"] ="toggle_snap_nodes";
469     legacyNames["snap-nodes-path"] ="toggle_snap_to_paths";
470     legacyNames["snap-nodes-cusp"] ="toggle_snap_to_nodes";
471     legacyNames["snap-nodes-smooth"] ="toggle_snap_to_smooth_nodes";
472     legacyNames["snap-nodes-midpoint"] ="toggle_snap_to_midpoints";
473     legacyNames["snap-nodes-intersection"] ="toggle_snap_to_path_intersections";
474     legacyNames["snap-nodes-center"] ="toggle_snap_to_bbox_midpoints-3";
475     legacyNames["snap-nodes-rotation-center"] ="toggle_snap_center";
476     legacyNames["snap-page"] ="toggle_snap_page_border";
477     legacyNames["snap-grid-guide-intersections"] ="toggle_snap_grid_guide_intersections";
478     legacyNames["align-horizontal-right-to-anchor"] ="al_left_out";
479     legacyNames["align-horizontal-left"] ="al_left_in";
480     legacyNames["align-horizontal-center"] ="al_center_hor";
481     legacyNames["align-horizontal-right"] ="al_right_in";
482     legacyNames["align-horizontal-left-to-anchor"] ="al_right_out";
483     legacyNames["align-horizontal-baseline"] ="al_baselines_vert";
484     legacyNames["align-vertical-bottom-to-anchor"] ="al_top_out";
485     legacyNames["align-vertical-top"] ="al_top_in";
486     legacyNames["align-vertical-center"] ="al_center_ver";
487     legacyNames["align-vertical-bottom"] ="al_bottom_in";
488     legacyNames["align-vertical-top-to-anchor"] ="al_bottom_out";
489     legacyNames["align-vertical-baseline"] ="al_baselines_hor";
490     legacyNames["distribute-horizontal-left"] ="distribute_left";
491     legacyNames["distribute-horizontal-center"] ="distribute_hcentre";
492     legacyNames["distribute-horizontal-right"] ="distribute_right";
493     legacyNames["distribute-horizontal-baseline"] ="distribute_baselines_hor";
494     legacyNames["distribute-vertical-bottom"] ="distribute_bottom";
495     legacyNames["distribute-vertical-center"] ="distribute_vcentre";
496     legacyNames["distribute-vertical-top"] ="distribute_top";
497     legacyNames["distribute-vertical-baseline"] ="distribute_baselines_vert";
498     legacyNames["distribute-randomize"] ="distribute_randomize";
499     legacyNames["distribute-unclump"] ="unclump";
500     legacyNames["distribute-graph"] ="graph_layout";
501     legacyNames["distribute-graph-directed"] ="directed_graph";
502     legacyNames["distribute-remove-overlaps"] ="remove_overlaps";
503     legacyNames["align-horizontal-node"] ="node_valign";
504     legacyNames["align-vertical-node"] ="node_halign";
505     legacyNames["distribute-vertical-node"] ="node_vdistribute";
506     legacyNames["distribute-horizontal-node"] ="node_hdistribute";
507     legacyNames["xml-element-new"] ="add_xml_element_node";
508     legacyNames["xml-text-new"] ="add_xml_text_node";
509     legacyNames["xml-node-delete"] ="delete_xml_node";
510     legacyNames["xml-node-duplicate"] ="duplicate_xml_node";
511     legacyNames["xml-attribute-delete"] ="delete_xml_attribute";
512     legacyNames["transform-move-horizontal"] ="arrows_hor";
513     legacyNames["transform-move-vertical"] ="arrows_ver";
514     legacyNames["transform-scale-horizontal"] ="transform_scale_hor";
515     legacyNames["transform-scale-vertical"] ="transform_scale_ver";
516     legacyNames["transform-skew-horizontal"] ="transform_scew_hor";
517     legacyNames["transform-skew-vertical"] ="transform_scew_ver";
518     legacyNames["object-fill"] ="properties_fill";
519     legacyNames["object-stroke"] ="properties_stroke_paint";
520     legacyNames["object-stroke-style"] ="properties_stroke";
521     legacyNames["paint-none"] ="fill_none";
522     legacyNames["paint-solid"] ="fill_solid";
523     legacyNames["paint-gradient-linear"] ="fill_gradient";
524     legacyNames["paint-gradient-radial"] ="fill_radial";
525     legacyNames["paint-pattern"] ="fill_pattern";
526     legacyNames["paint-unknown"] ="fill_unset";
527     legacyNames["fill-rule-even-odd"] ="fillrule_evenodd";
528     legacyNames["fill-rule-nonzero"] ="fillrule_nonzero";
529     legacyNames["stroke-join-miter"] ="join_miter";
530     legacyNames["stroke-join-bevel"] ="join_bevel";
531     legacyNames["stroke-join-round"] ="join_round";
532     legacyNames["stroke-cap-butt"] ="cap_butt";
533     legacyNames["stroke-cap-square"] ="cap_square";
534     legacyNames["stroke-cap-round"] ="cap_round";
535     legacyNames["guides"] ="guide";
536     legacyNames["grid-rectangular"] ="grid_xy";
537     legacyNames["grid-axonometric"] ="grid_axonom";
538     legacyNames["object-visible"] ="visible";
539     legacyNames["object-hidden"] ="hidden";
540     legacyNames["object-unlocked"] ="lock_unlocked";
541     legacyNames["object-locked"] ="width_height_lock";
542     legacyNames["zoom"] ="sticky_zoom";
545 static GtkWidget *
546 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 // returns true if icon needed preloading, false if nothing was done
1202 bool prerender_icon(gchar const *name, GtkIconSize lsize, unsigned psize)
1204     bool loadNeeded = false;
1205     static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1207     Glib::ustring key = icon_cache_key(name, psize);
1208     if ( !get_cached_pixbuf(key) ) {
1209         if ((internalNames.find(name) != internalNames.end())
1210             || (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name))) {
1211             if (dump) {
1212                 g_message("prerender_icon  [%s] %d:%d", name, lsize, psize);
1213             }
1214             guchar* px = load_svg_pixels(name, lsize, psize);
1215             if ( !px ) {
1216                 // check for a fallback name
1217                 if ( legacyNames.find(name) != legacyNames.end() ) {
1218                     if ( dump ) {
1219                         g_message("load_svg_pixels([%s]=%s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1220                     }
1221                     px = load_svg_pixels(legacyNames[name].c_str(), lsize, psize);
1222                 }
1223             }
1224             if (px) {
1225                 GdkPixbuf* pb = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, TRUE, 8,
1226                                                           psize, psize, psize * 4,
1227                                                           reinterpret_cast<GdkPixbufDestroyNotify>(g_free), NULL );
1228                 pb_cache[key] = pb;
1229                 addToIconSet(pb, name, lsize, psize);
1230                 loadNeeded = true;
1231                 if (internalNames.find(name) == internalNames.end()) {
1232                     internalNames.insert(name);
1233                 }
1234             } else if (dump) {
1235                 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX  error!!! pixels not found for '%s'", name);
1236             }
1237         }
1238         else if (dump) {
1239             g_message("prerender_icon  [%s] %d NOT!!!!!!", name, psize);
1240         }
1241     }
1242     return loadNeeded;
1245 static GdkPixbuf *sp_icon_image_load_svg(gchar const *name, GtkIconSize lsize, unsigned psize)
1247     Glib::ustring key = icon_cache_key(name, psize);
1249     // did we already load this icon at this scale/size?
1250     GdkPixbuf* pb = get_cached_pixbuf(key);
1251     if (!pb) {
1252         guchar *px = load_svg_pixels(name, lsize, psize);
1253         if (px) {
1254             pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1255                                           psize, psize, psize * 4,
1256                                           (GdkPixbufDestroyNotify)g_free, NULL);
1257             pb_cache[key] = pb;
1258             addToIconSet(pb, name, lsize, psize);
1259         }
1260     }
1262     if ( pb ) {
1263         // increase refcount since we're handing out ownership
1264         g_object_ref(G_OBJECT(pb));
1265     }
1266     return pb;
1269 void sp_icon_overlay_pixels(guchar *px, int width, int height, int stride,
1270                             unsigned r, unsigned g, unsigned b)
1272     int bytesPerPixel = 4;
1273     int spacing = 4;
1274     for ( int y = 0; y < height; y += spacing ) {
1275         guchar *ptr = px + y * stride;
1276         for ( int x = 0; x < width; x += spacing ) {
1277             *(ptr++) = r;
1278             *(ptr++) = g;
1279             *(ptr++) = b;
1280             *(ptr++) = 0xff;
1282             ptr += bytesPerPixel * (spacing - 1);
1283         }
1284     }
1286     if ( width > 1 && height > 1 ) {
1287         // point at the last pixel
1288         guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1290         if ( width > 2 ) {
1291             px[4] = r;
1292             px[5] = g;
1293             px[6] = b;
1294             px[7] = 0xff;
1296             ptr[-12] = r;
1297             ptr[-11] = g;
1298             ptr[-10] = b;
1299             ptr[-9] = 0xff;
1300         }
1302         ptr[-4] = r;
1303         ptr[-3] = g;
1304         ptr[-2] = b;
1305         ptr[-1] = 0xff;
1307         px[0 + stride] = r;
1308         px[1 + stride] = g;
1309         px[2 + stride] = b;
1310         px[3 + stride] = 0xff;
1312         ptr[0 - stride] = r;
1313         ptr[1 - stride] = g;
1314         ptr[2 - stride] = b;
1315         ptr[3 - stride] = 0xff;
1317         if ( height > 2 ) {
1318             ptr[0 - stride * 3] = r;
1319             ptr[1 - stride * 3] = g;
1320             ptr[2 - stride * 3] = b;
1321             ptr[3 - stride * 3] = 0xff;
1322         }
1323     }
1326 class preRenderItem
1328 public:
1329     preRenderItem( GtkIconSize lsize, gchar const *name ) :
1330         _lsize( lsize ),
1331         _name( name )
1332     {}
1333     GtkIconSize _lsize;
1334     Glib::ustring _name;
1335 };
1338 static std::vector<preRenderItem> pendingRenders;
1339 static bool callbackHooked = false;
1341 static void addPreRender( GtkIconSize lsize, gchar const *name )
1343     if ( !callbackHooked )
1344     {
1345         callbackHooked = true;
1346         g_idle_add_full( G_PRIORITY_LOW, &icon_prerender_task, NULL, NULL );
1347     }
1349     pendingRenders.push_back(preRenderItem(lsize, name));
1352 gboolean icon_prerender_task(gpointer /*data*/) {
1353     if ( inkscapeIsCrashing() ) {
1354         // stop
1355     } else if (!pendingRenders.empty()) {
1356         bool workDone = false;
1357         do {
1358             preRenderItem single = pendingRenders.front();
1359             pendingRenders.erase(pendingRenders.begin());
1360             int psize = sp_icon_get_phys_size(single._lsize);
1361             workDone = prerender_icon(single._name.c_str(), single._lsize, psize);
1362         } while (!pendingRenders.empty() && !workDone);
1363     }
1365     if (!inkscapeIsCrashing() && !pendingRenders.empty()) {
1366         return TRUE;
1367     } else {
1368         callbackHooked = false;
1369         return FALSE;
1370     }
1374 void imageMapCB(GtkWidget* widget, gpointer user_data) {
1375     gchar* id = 0;
1376     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1377     gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1378     GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1379     if ( id ) {
1380         int psize = sp_icon_get_phys_size(lsize);
1381         g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1382         for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1383             if ( (it->_name == id) && (it->_lsize == lsize) ) {
1384                 prerender_icon(id, lsize, psize);
1385                 pendingRenders.erase(it);
1386                 g_message("    prerender for %s:%d:%d", id, lsize, psize);
1387                 if (lsize != size) {
1388                     int psize = sp_icon_get_phys_size(size);
1389                     prerender_icon(id, size, psize);
1390                 }
1391                 break;
1392             }
1393         }
1394     }
1396     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1399 static void imageMapNamedCB(GtkWidget* widget, gpointer user_data) {
1400     GtkImage* img = GTK_IMAGE(widget);
1401     gchar const* iconName = 0;
1402     GtkIconSize size = GTK_ICON_SIZE_INVALID;
1403     gtk_image_get_icon_name(img, &iconName, &size);
1404     if ( iconName ) {
1405         GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1406         if ( type == GTK_IMAGE_ICON_NAME ) {
1408             gint iconSize = 0;
1409             gchar* iconName = 0;
1410             {
1411                 g_object_get(G_OBJECT(widget),
1412                              "icon-name", &iconName,
1413                              "icon-size", &iconSize,
1414                              NULL);
1415             }
1417             for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1418                 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1419                     int psize = sp_icon_get_phys_size(size);
1420                     prerender_icon(iconName, size, psize);
1421                     pendingRenders.erase(it);
1422                     break;
1423                 }
1424             }
1426             gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1427             gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1428         } else {
1429             g_warning("UNEXPECTED TYPE of %d", (int)type);
1430         }
1431     }
1433     g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1437 /*
1438   Local Variables:
1439   mode:c++
1440   c-file-style:"stroustrup"
1441   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1442   indent-tabs-mode:nil
1443   fill-column:99
1444   End:
1445 */
1446 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :