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