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