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