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