Code

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