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