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