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 if ( Glib::file_test(subdirName, Glib::FILE_TEST_IS_DIR) ) {
410 Glib::Dir subdir(subdirName);
411 for ( Glib::DirIterator subit = subdir.begin(); cacheValid && (subit != subdir.end()); ++subit ) {
412 std::string fullpath = Glib::build_filename( subdirName, *subit );
413 if ( Glib::file_test(fullpath, Glib::FILE_TEST_EXISTS) && !Glib::file_test(fullpath, Glib::FILE_TEST_IS_DIR) ) {
414 GStatBuf st;
415 memset(&st, 0, sizeof(st));
416 if ( !g_stat(fullpath.c_str(), &st) ) {
417 unsigned long when = st.st_mtime;
418 if ( when < lastSeen ) {
419 cacheValid = false;
420 }
421 }
422 }
423 }
424 }
425 }
426 }
427 }
429 if ( !cacheValid ) {
430 if ( Glib::file_test(iconCacheDir, Glib::FILE_TEST_EXISTS) ) {
431 // Purge existing icons, but not possible future sub-directories.
432 if ( Glib::file_test(iconCacheDir, Glib::FILE_TEST_IS_DIR) ) {
433 Glib::Dir dir(iconCacheDir);
434 for ( Glib::DirIterator it = dir.begin(); it != dir.end(); ++it ) {
435 if ( isSizedSubdir(*it) ) {
436 std::string subdirName = Glib::build_filename( iconCacheDir, *it );
437 if ( Glib::file_test(subdirName, Glib::FILE_TEST_IS_DIR) ) {
438 Glib::Dir subdir(subdirName);
439 for ( Glib::DirIterator subit = subdir.begin(); subit != subdir.end(); ++subit ) {
440 std::string fullpath = Glib::build_filename( subdirName, *subit );
441 if ( Glib::file_test(fullpath, Glib::FILE_TEST_EXISTS) && !Glib::file_test(fullpath, Glib::FILE_TEST_IS_DIR) ) {
442 g_remove(fullpath.c_str());
443 }
444 }
445 g_rmdir( subdirName.c_str() );
446 }
447 }
448 }
449 }
450 } else {
451 g_mkdir_with_parents( iconCacheDir.c_str(), 0x1ED );
452 }
454 if ( g_file_set_contents(iconCacheFile.c_str(), wanted.c_str(), wanted.size(), 0) ) {
455 // Caching may proceed
456 } else {
457 g_warning("Unable to write cache info file.");
458 }
459 }
460 }
462 static Glib::ustring icon_cache_key(Glib::ustring const &name, unsigned psize);
463 static GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key);
465 void IconImpl::setupLegacyNaming() {
466 legacyNames["document-import"] ="file_import";
467 legacyNames["document-export"] ="file_export";
468 legacyNames["document-import-ocal"] ="ocal_import";
469 legacyNames["document-export-ocal"] ="ocal_export";
470 legacyNames["document-metadata"] ="document_metadata";
471 legacyNames["dialog-input-devices"] ="input_devices";
472 legacyNames["edit-duplicate"] ="edit_duplicate";
473 legacyNames["edit-clone"] ="edit_clone";
474 legacyNames["edit-clone-unlink"] ="edit_unlink_clone";
475 legacyNames["edit-select-original"] ="edit_select_original";
476 legacyNames["edit-undo-history"] ="edit_undo_history";
477 legacyNames["edit-paste-in-place"] ="selection_paste_in_place";
478 legacyNames["edit-paste-style"] ="selection_paste_style";
479 legacyNames["selection-make-bitmap-copy"] ="selection_bitmap";
480 legacyNames["edit-select-all"] ="selection_select_all";
481 legacyNames["edit-select-all-layers"] ="selection_select_all_in_all_layers";
482 legacyNames["edit-select-invert"] ="selection_invert";
483 legacyNames["edit-select-none"] ="selection_deselect";
484 legacyNames["dialog-xml-editor"] ="xml_editor";
485 legacyNames["zoom-original"] ="zoom_1_to_1";
486 legacyNames["zoom-half-size"] ="zoom_1_to_2";
487 legacyNames["zoom-double-size"] ="zoom_2_to_1";
488 legacyNames["zoom-fit-selection"] ="zoom_select";
489 legacyNames["zoom-fit-drawing"] ="zoom_draw";
490 legacyNames["zoom-fit-page"] ="zoom_page";
491 legacyNames["zoom-fit-width"] ="zoom_pagewidth";
492 legacyNames["zoom-previous"] ="zoom_previous";
493 legacyNames["zoom-next"] ="zoom_next";
494 legacyNames["zoom-in"] ="zoom_in";
495 legacyNames["zoom-out"] ="zoom_out";
496 legacyNames["show-grid"] ="grid";
497 legacyNames["show-guides"] ="guides";
498 legacyNames["color-management"] ="color_management";
499 legacyNames["show-dialogs"] ="dialog_toggle";
500 legacyNames["dialog-messages"] ="messages";
501 legacyNames["dialog-scripts"] ="scripts";
502 legacyNames["window-previous"] ="window_previous";
503 legacyNames["window-next"] ="window_next";
504 legacyNames["dialog-icon-preview"] ="view_icon_preview";
505 legacyNames["window-new"] ="view_new";
506 legacyNames["view-fullscreen"] ="fullscreen";
507 legacyNames["layer-new"] ="new_layer";
508 legacyNames["layer-rename"] ="rename_layer";
509 legacyNames["layer-previous"] ="switch_to_layer_above";
510 legacyNames["layer-next"] ="switch_to_layer_below";
511 legacyNames["selection-move-to-layer-above"] ="move_selection_above";
512 legacyNames["selection-move-to-layer-below"] ="move_selection_below";
513 legacyNames["layer-raise"] ="raise_layer";
514 legacyNames["layer-lower"] ="lower_layer";
515 legacyNames["layer-top"] ="layer_to_top";
516 legacyNames["layer-bottom"] ="layer_to_bottom";
517 legacyNames["layer-delete"] ="delete_layer";
518 legacyNames["dialog-layers"] ="layers";
519 legacyNames["dialog-fill-and-stroke"] ="fill_and_stroke";
520 legacyNames["dialog-object-properties"] ="dialog_item_properties";
521 legacyNames["object-group"] ="selection_group";
522 legacyNames["object-ungroup"] ="selection_ungroup";
523 legacyNames["selection-raise"] ="selection_up";
524 legacyNames["selection-lower"] ="selection_down";
525 legacyNames["selection-top"] ="selection_top";
526 legacyNames["selection-bottom"] ="selection_bot";
527 legacyNames["object-rotate-left"] ="object_rotate_90_CCW";
528 legacyNames["object-rotate-right"] ="object_rotate_90_CW";
529 legacyNames["object-flip-horizontal"] ="object_flip_hor";
530 legacyNames["object-flip-vertical"] ="object_flip_ver";
531 legacyNames["dialog-transform"] ="object_trans";
532 legacyNames["dialog-align-and-distribute"] ="object_align";
533 legacyNames["dialog-rows-and-columns"] ="grid_arrange";
534 legacyNames["object-to-path"] ="object_tocurve";
535 legacyNames["stroke-to-path"] ="stroke_tocurve";
536 legacyNames["bitmap-trace"] ="selection_trace";
537 legacyNames["path-union"] ="union";
538 legacyNames["path-difference"] ="difference";
539 legacyNames["path-intersection"] ="intersection";
540 legacyNames["path-exclusion"] ="exclusion";
541 legacyNames["path-division"] ="division";
542 legacyNames["path-cut"] ="cut_path";
543 legacyNames["path-combine"] ="selection_combine";
544 legacyNames["path-break-apart"] ="selection_break";
545 legacyNames["path-outset"] ="outset_path";
546 legacyNames["path-inset"] ="inset_path";
547 legacyNames["path-offset-dynamic"] ="dynamic_offset";
548 legacyNames["path-offset-linked"] ="linked_offset";
549 legacyNames["path-simplify"] ="simplify";
550 legacyNames["path-reverse"] ="selection_reverse";
551 legacyNames["dialog-text-and-font"] ="object_font";
552 legacyNames["text-put-on-path"] ="put_on_path";
553 legacyNames["text-remove-from-path"] ="remove_from_path";
554 legacyNames["text-flow-into-frame"] ="flow_into_frame";
555 legacyNames["text-unflow"] ="unflow";
556 legacyNames["text-convert-to-regular"] ="convert_to_text";
557 legacyNames["text-unkern"] ="remove_manual_kerns";
558 legacyNames["help-keyboard-shortcuts"] ="help_keys";
559 legacyNames["help-contents"] ="help_tutorials";
560 legacyNames["inkscape-logo"] ="inkscape_options";
561 legacyNames["dialog-memory"] ="about_memory";
562 legacyNames["tool-pointer"] ="draw_select";
563 legacyNames["tool-node-editor"] ="draw_node";
564 legacyNames["tool-tweak"] ="draw_tweak";
565 legacyNames["zoom"] ="draw_zoom";
566 legacyNames["draw-rectangle"] ="draw_rect";
567 legacyNames["draw-cuboid"] ="draw_3dbox";
568 legacyNames["draw-ellipse"] ="draw_arc";
569 legacyNames["draw-polygon-star"] ="draw_star";
570 legacyNames["draw-spiral"] ="draw_spiral";
571 legacyNames["draw-freehand"] ="draw_freehand";
572 legacyNames["draw-path"] ="draw_pen";
573 legacyNames["draw-calligraphic"] ="draw_calligraphic";
574 legacyNames["draw-eraser"] ="draw_erase";
575 legacyNames["color-fill"] ="draw_paintbucket";
576 legacyNames["draw-text"] ="draw_text";
577 legacyNames["draw-connector"] ="draw_connector";
578 legacyNames["color-gradient"] ="draw_gradient";
579 legacyNames["color-picker"] ="draw_dropper";
580 legacyNames["transform-affect-stroke"] ="transform_stroke";
581 legacyNames["transform-affect-rounded-corners"] ="transform_corners";
582 legacyNames["transform-affect-gradient"] ="transform_gradient";
583 legacyNames["transform-affect-pattern"] ="transform_pattern";
584 legacyNames["node-add"] ="node_insert";
585 legacyNames["node-delete"] ="node_delete";
586 legacyNames["node-join"] ="node_join";
587 legacyNames["node-break"] ="node_break";
588 legacyNames["node-join-segment"] ="node_join_segment";
589 legacyNames["node-delete-segment"] ="node_delete_segment";
590 legacyNames["node-type-cusp"] ="node_cusp";
591 legacyNames["node-type-smooth"] ="node_smooth";
592 legacyNames["node-type-symmetric"] ="node_symmetric";
593 legacyNames["node-type-auto-smooth"] ="node_auto";
594 legacyNames["node-segment-curve"] ="node_curve";
595 legacyNames["node-segment-line"] ="node_line";
596 legacyNames["show-node-handles"] ="nodes_show_handles";
597 legacyNames["path-effect-parameter-next"] ="edit_next_parameter";
598 legacyNames["show-path-outline"] ="nodes_show_helperpath";
599 legacyNames["path-clip-edit"] ="nodeedit-clippath";
600 legacyNames["path-mask-edit"] ="nodeedit-mask";
601 legacyNames["node-type-cusp"] ="node_cusp";
602 legacyNames["object-tweak-push"] ="tweak_move_mode";
603 legacyNames["object-tweak-attract"] ="tweak_move_mode_inout";
604 legacyNames["object-tweak-randomize"] ="tweak_move_mode_jitter";
605 legacyNames["object-tweak-shrink"] ="tweak_scale_mode";
606 legacyNames["object-tweak-rotate"] ="tweak_rotate_mode";
607 legacyNames["object-tweak-duplicate"] ="tweak_moreless_mode";
608 legacyNames["object-tweak-push"] ="tweak_move_mode";
609 legacyNames["path-tweak-push"] ="tweak_push_mode";
610 legacyNames["path-tweak-shrink"] ="tweak_shrink_mode";
611 legacyNames["path-tweak-attract"] ="tweak_attract_mode";
612 legacyNames["path-tweak-roughen"] ="tweak_roughen_mode";
613 legacyNames["object-tweak-paint"] ="tweak_colorpaint_mode";
614 legacyNames["object-tweak-jitter-color"] ="tweak_colorjitter_mode";
615 legacyNames["object-tweak-blur"] ="tweak_blur_mode";
616 legacyNames["rectangle-make-corners-sharp"] ="squared_corner";
617 legacyNames["perspective-parallel"] ="toggle_vp_x";
618 legacyNames["draw-ellipse-whole"] ="reset_circle";
619 legacyNames["draw-ellipse-segment"] ="circle_closed_arc";
620 legacyNames["draw-ellipse-arc"] ="circle_open_arc";
621 legacyNames["draw-polygon"] ="star_flat";
622 legacyNames["draw-star"] ="star_angled";
623 legacyNames["path-mode-bezier"] ="bezier_mode";
624 legacyNames["path-mode-spiro"] ="spiro_splines_mode";
625 legacyNames["path-mode-polyline"] ="polylines_mode";
626 legacyNames["path-mode-polyline-paraxial"] ="paraxial_lines_mode";
627 legacyNames["draw-use-tilt"] ="guse_tilt";
628 legacyNames["draw-use-pressure"] ="guse_pressure";
629 legacyNames["draw-trace-background"] ="trace_background";
630 legacyNames["draw-eraser-delete-objects"] ="delete_object";
631 legacyNames["format-text-direction-vertical"] ="writing_mode_tb";
632 legacyNames["format-text-direction-horizontal"] ="writing_mode_lr";
633 legacyNames["connector-avoid"] ="connector_avoid";
634 legacyNames["connector-ignore"] ="connector_ignore";
635 legacyNames["object-fill"] ="controls_fill";
636 legacyNames["object-stroke"] ="controls_stroke";
637 legacyNames["snap"] ="toggle_snap_global";
638 legacyNames["snap-bounding-box"] ="toggle_snap_bbox";
639 legacyNames["snap-bounding-box-edges"] ="toggle_snap_to_bbox_path";
640 legacyNames["snap-bounding-box-corners"] ="toggle_snap_to_bbox_node";
641 legacyNames["snap-bounding-box-midpoints"] ="toggle_snap_to_bbox_edge_midpoints";
642 legacyNames["snap-bounding-box-center"] ="toggle_snap_to_bbox_midpoints";
643 legacyNames["snap-nodes"] ="toggle_snap_nodes";
644 legacyNames["snap-nodes-path"] ="toggle_snap_to_paths";
645 legacyNames["snap-nodes-cusp"] ="toggle_snap_to_nodes";
646 legacyNames["snap-nodes-smooth"] ="toggle_snap_to_smooth_nodes";
647 legacyNames["snap-nodes-midpoint"] ="toggle_snap_to_midpoints";
648 legacyNames["snap-nodes-intersection"] ="toggle_snap_to_path_intersections";
649 legacyNames["snap-nodes-center"] ="toggle_snap_to_bbox_midpoints-3";
650 legacyNames["snap-nodes-rotation-center"] ="toggle_snap_center";
651 legacyNames["snap-page"] ="toggle_snap_page_border";
652 legacyNames["snap-grid-guide-intersections"] ="toggle_snap_grid_guide_intersections";
653 legacyNames["align-horizontal-right-to-anchor"] ="al_left_out";
654 legacyNames["align-horizontal-left"] ="al_left_in";
655 legacyNames["align-horizontal-center"] ="al_center_hor";
656 legacyNames["align-horizontal-right"] ="al_right_in";
657 legacyNames["align-horizontal-left-to-anchor"] ="al_right_out";
658 legacyNames["align-horizontal-baseline"] ="al_baselines_vert";
659 legacyNames["align-vertical-bottom-to-anchor"] ="al_top_out";
660 legacyNames["align-vertical-top"] ="al_top_in";
661 legacyNames["align-vertical-center"] ="al_center_ver";
662 legacyNames["align-vertical-bottom"] ="al_bottom_in";
663 legacyNames["align-vertical-top-to-anchor"] ="al_bottom_out";
664 legacyNames["align-vertical-baseline"] ="al_baselines_hor";
665 legacyNames["distribute-horizontal-left"] ="distribute_left";
666 legacyNames["distribute-horizontal-center"] ="distribute_hcentre";
667 legacyNames["distribute-horizontal-right"] ="distribute_right";
668 legacyNames["distribute-horizontal-baseline"] ="distribute_baselines_hor";
669 legacyNames["distribute-vertical-bottom"] ="distribute_bottom";
670 legacyNames["distribute-vertical-center"] ="distribute_vcentre";
671 legacyNames["distribute-vertical-top"] ="distribute_top";
672 legacyNames["distribute-vertical-baseline"] ="distribute_baselines_vert";
673 legacyNames["distribute-randomize"] ="distribute_randomize";
674 legacyNames["distribute-unclump"] ="unclump";
675 legacyNames["distribute-graph"] ="graph_layout";
676 legacyNames["distribute-graph-directed"] ="directed_graph";
677 legacyNames["distribute-remove-overlaps"] ="remove_overlaps";
678 legacyNames["align-horizontal-node"] ="node_valign";
679 legacyNames["align-vertical-node"] ="node_halign";
680 legacyNames["distribute-vertical-node"] ="node_vdistribute";
681 legacyNames["distribute-horizontal-node"] ="node_hdistribute";
682 legacyNames["xml-element-new"] ="add_xml_element_node";
683 legacyNames["xml-text-new"] ="add_xml_text_node";
684 legacyNames["xml-node-delete"] ="delete_xml_node";
685 legacyNames["xml-node-duplicate"] ="duplicate_xml_node";
686 legacyNames["xml-attribute-delete"] ="delete_xml_attribute";
687 legacyNames["transform-move-horizontal"] ="arrows_hor";
688 legacyNames["transform-move-vertical"] ="arrows_ver";
689 legacyNames["transform-scale-horizontal"] ="transform_scale_hor";
690 legacyNames["transform-scale-vertical"] ="transform_scale_ver";
691 legacyNames["transform-skew-horizontal"] ="transform_scew_hor";
692 legacyNames["transform-skew-vertical"] ="transform_scew_ver";
693 legacyNames["object-fill"] ="properties_fill";
694 legacyNames["object-stroke"] ="properties_stroke_paint";
695 legacyNames["object-stroke-style"] ="properties_stroke";
696 legacyNames["paint-none"] ="fill_none";
697 legacyNames["paint-solid"] ="fill_solid";
698 legacyNames["paint-gradient-linear"] ="fill_gradient";
699 legacyNames["paint-gradient-radial"] ="fill_radial";
700 legacyNames["paint-pattern"] ="fill_pattern";
701 legacyNames["paint-unknown"] ="fill_unset";
702 legacyNames["fill-rule-even-odd"] ="fillrule_evenodd";
703 legacyNames["fill-rule-nonzero"] ="fillrule_nonzero";
704 legacyNames["stroke-join-miter"] ="join_miter";
705 legacyNames["stroke-join-bevel"] ="join_bevel";
706 legacyNames["stroke-join-round"] ="join_round";
707 legacyNames["stroke-cap-butt"] ="cap_butt";
708 legacyNames["stroke-cap-square"] ="cap_square";
709 legacyNames["stroke-cap-round"] ="cap_round";
710 legacyNames["guides"] ="guide";
711 legacyNames["grid-rectangular"] ="grid_xy";
712 legacyNames["grid-axonometric"] ="grid_axonom";
713 legacyNames["object-visible"] ="visible";
714 legacyNames["object-hidden"] ="hidden";
715 legacyNames["object-unlocked"] ="lock_unlocked";
716 legacyNames["object-locked"] ="width_height_lock";
717 legacyNames["zoom"] ="sticky_zoom";
718 }
720 GtkWidget *IconImpl::newFull( Inkscape::IconSize lsize, gchar const *name )
721 {
722 static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
724 GtkWidget *widget = 0;
725 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
726 if ( !sizeMapDone ) {
727 injectCustomSize();
728 }
729 GtkIconSize mappedSize = iconSizeLookup[trySize];
731 GtkStockItem stock;
732 gboolean stockFound = gtk_stock_lookup( name, &stock );
734 GtkWidget *img = 0;
735 if ( legacyNames.empty() ) {
736 setupLegacyNaming();
737 }
739 if ( stockFound ) {
740 img = gtk_image_new_from_stock( name, mappedSize );
741 } else {
742 img = gtk_image_new_from_icon_name( name, mappedSize );
743 if ( dump ) {
744 g_message("gtk_image_new_from_icon_name( '%s', %d ) = %p", name, mappedSize, img);
745 GtkImageType thing = gtk_image_get_storage_type(GTK_IMAGE(img));
746 g_message(" Type is %d %s", (int)thing, (thing == GTK_IMAGE_EMPTY ? "Empty" : "ok"));
747 }
748 }
750 if ( img ) {
751 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
752 if ( type == GTK_IMAGE_STOCK ) {
753 if ( !stockFound ) {
754 // It's not showing as a stock ID, so assume it will be present internally
755 addPreRender( mappedSize, name );
757 // Add a hook to render if set visible before prerender is done.
758 g_signal_connect( G_OBJECT(img), "map", G_CALLBACK(imageMapCB), GINT_TO_POINTER(static_cast<int>(mappedSize)) );
759 if ( dump ) {
760 g_message(" connecting %p for imageMapCB for [%s] %d", img, name, (int)mappedSize);
761 }
762 }
763 widget = GTK_WIDGET(img);
764 img = 0;
765 if ( dump ) {
766 g_message( "loaded gtk '%s' %d (GTK_IMAGE_STOCK) %s on %p", name, mappedSize, (stockFound ? "STOCK" : "local"), widget );
767 }
768 } else if ( type == GTK_IMAGE_ICON_NAME ) {
769 widget = GTK_WIDGET(img);
770 img = 0;
772 // Add a hook to render if set visible before prerender is done.
773 g_signal_connect( G_OBJECT(widget), "map", G_CALLBACK(imageMapNamedCB), GINT_TO_POINTER(0) );
775 if ( Inkscape::Preferences::get()->getBool("/options/iconrender/named_nodelay") ) {
776 int psize = getPhysSize(lsize);
777 prerenderIcon(name, mappedSize, psize);
778 } else {
779 addPreRender( mappedSize, name );
780 }
781 } else {
782 if ( dump ) {
783 g_message( "skipped gtk '%s' %d (not GTK_IMAGE_STOCK)", name, lsize );
784 }
785 //g_object_unref( (GObject *)img );
786 img = 0;
787 }
788 }
790 if ( !widget ) {
791 //g_message("Creating an SPIcon instance for %s:%d", name, (int)lsize);
792 SPIcon *icon = (SPIcon *)g_object_new(SP_TYPE_ICON, NULL);
793 icon->lsize = lsize;
794 icon->name = g_strdup(name);
795 icon->psize = getPhysSize(lsize);
797 widget = GTK_WIDGET(icon);
798 }
800 return widget;
801 }
803 // PUBLIC CALL:
804 GtkWidget *sp_icon_new( Inkscape::IconSize lsize, gchar const *name )
805 {
806 return IconImpl::newFull( lsize, name );
807 }
809 // PUBLIC CALL:
810 Gtk::Widget *sp_icon_get_icon( Glib::ustring const &oid, Inkscape::IconSize size )
811 {
812 Gtk::Widget *result = 0;
813 GtkWidget *widget = IconImpl::newFull( static_cast<Inkscape::IconSize>(Inkscape::getRegisteredIconSize(size)), oid.c_str() );
815 if ( widget ) {
816 if ( GTK_IS_IMAGE(widget) ) {
817 GtkImage *img = GTK_IMAGE(widget);
818 result = Glib::wrap( img );
819 } else {
820 result = Glib::wrap( widget );
821 }
822 }
824 return result;
825 }
827 void IconImpl::injectCustomSize()
828 {
829 // TODO - still need to handle the case of theme changes and resize, especially as we can't re-register a string.
830 if ( !sizeMapDone )
831 {
832 bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
833 gint width = 0;
834 gint height = 0;
835 if ( gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height ) ) {
836 gint newWidth = ((width * 3) / 4);
837 gint newHeight = ((height * 3) / 4);
838 GtkIconSize newSizeEnum = gtk_icon_size_register( "inkscape-decoration", newWidth, newHeight );
839 if ( newSizeEnum ) {
840 if ( dump ) {
841 g_message("Registered (%d, %d) <= (%d, %d) as index %d", newWidth, newHeight, width, height, newSizeEnum);
842 }
843 guint index = static_cast<guint>(Inkscape::ICON_SIZE_DECORATION);
844 if ( index < G_N_ELEMENTS(iconSizeLookup) ) {
845 iconSizeLookup[index] = newSizeEnum;
846 } else if ( dump ) {
847 g_message("size lookup array too small to store entry");
848 }
849 }
850 }
851 sizeMapDone = true;
852 }
853 }
855 GtkIconSize Inkscape::getRegisteredIconSize( Inkscape::IconSize size )
856 {
857 GtkIconSize other = GTK_ICON_SIZE_MENU;
858 IconImpl::injectCustomSize();
859 size = CLAMP( size, Inkscape::ICON_SIZE_MENU, Inkscape::ICON_SIZE_DECORATION );
860 if ( size == Inkscape::ICON_SIZE_DECORATION ) {
861 other = gtk_icon_size_from_name("inkscape-decoration");
862 } else {
863 other = static_cast<GtkIconSize>(size);
864 }
866 return other;
867 }
870 // PUBLIC CALL:
871 int sp_icon_get_phys_size(int size)
872 {
873 return IconImpl::getPhysSize(size);
874 }
876 int IconImpl::getPhysSize(int size)
877 {
878 static bool init = false;
879 static int lastSys[Inkscape::ICON_SIZE_DECORATION + 1];
880 static int vals[Inkscape::ICON_SIZE_DECORATION + 1];
882 size = CLAMP( size, static_cast<int>(GTK_ICON_SIZE_MENU), static_cast<int>(Inkscape::ICON_SIZE_DECORATION) );
884 if ( !sizeMapDone ) {
885 injectCustomSize();
886 }
888 if ( sizeDirty && init ) {
889 GtkIconSize const gtkSizes[] = {
890 GTK_ICON_SIZE_MENU,
891 GTK_ICON_SIZE_SMALL_TOOLBAR,
892 GTK_ICON_SIZE_LARGE_TOOLBAR,
893 GTK_ICON_SIZE_BUTTON,
894 GTK_ICON_SIZE_DND,
895 GTK_ICON_SIZE_DIALOG,
896 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
897 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
898 GTK_ICON_SIZE_MENU
899 };
900 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes) && init; ++i) {
901 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
903 g_assert( val_ix < G_N_ELEMENTS(vals) );
905 gint width = 0;
906 gint height = 0;
907 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
908 init &= (lastSys[val_ix] == std::max(width, height));
909 }
910 }
911 }
913 if ( !init ) {
914 sizeDirty = false;
915 bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpDefault");
916 if ( dump ) {
917 g_message( "Default icon sizes:" );
918 }
919 memset( vals, 0, sizeof(vals) );
920 memset( lastSys, 0, sizeof(lastSys) );
921 GtkIconSize const gtkSizes[] = {
922 GTK_ICON_SIZE_MENU,
923 GTK_ICON_SIZE_SMALL_TOOLBAR,
924 GTK_ICON_SIZE_LARGE_TOOLBAR,
925 GTK_ICON_SIZE_BUTTON,
926 GTK_ICON_SIZE_DND,
927 GTK_ICON_SIZE_DIALOG,
928 static_cast<guint>(Inkscape::ICON_SIZE_DECORATION) < G_N_ELEMENTS(iconSizeLookup) ?
929 iconSizeLookup[static_cast<int>(Inkscape::ICON_SIZE_DECORATION)] :
930 GTK_ICON_SIZE_MENU
931 };
932 gchar const *const names[] = {
933 "GTK_ICON_SIZE_MENU",
934 "GTK_ICON_SIZE_SMALL_TOOLBAR",
935 "GTK_ICON_SIZE_LARGE_TOOLBAR",
936 "GTK_ICON_SIZE_BUTTON",
937 "GTK_ICON_SIZE_DND",
938 "GTK_ICON_SIZE_DIALOG",
939 "inkscape-decoration"
940 };
942 GtkWidget *icon = (GtkWidget *)g_object_new(SP_TYPE_ICON, NULL);
944 for (unsigned i = 0; i < G_N_ELEMENTS(gtkSizes); ++i) {
945 guint const val_ix = (gtkSizes[i] <= GTK_ICON_SIZE_DIALOG) ? (guint)gtkSizes[i] : (guint)Inkscape::ICON_SIZE_DECORATION;
947 g_assert( val_ix < G_N_ELEMENTS(vals) );
949 gint width = 0;
950 gint height = 0;
951 bool used = false;
952 if ( gtk_icon_size_lookup(gtkSizes[i], &width, &height ) ) {
953 vals[val_ix] = std::max(width, height);
954 lastSys[val_ix] = vals[val_ix];
955 used = true;
956 }
957 if (dump) {
958 g_message(" =-- %u size:%d %c(%d, %d) '%s'",
959 i, gtkSizes[i],
960 ( used ? ' ' : 'X' ), width, height, names[i]);
961 }
963 // The following is needed due to this documented behavior of gtk_icon_size_lookup:
964 // "The rendered pixbuf may not even correspond to the width/height returned by
965 // gtk_icon_size_lookup(), because themes are free to render the pixbuf however
966 // they like, including changing the usual size."
967 gchar const *id = GTK_STOCK_OPEN;
968 GdkPixbuf *pb = gtk_widget_render_icon( icon, id, gtkSizes[i], NULL);
969 if (pb) {
970 width = gdk_pixbuf_get_width(pb);
971 height = gdk_pixbuf_get_height(pb);
972 int newSize = std::max( width, height );
973 // TODO perhaps check a few more stock icons to get a range on sizes.
974 if ( newSize > 0 ) {
975 vals[val_ix] = newSize;
976 }
977 if (dump) {
978 g_message(" %u size:%d (%d, %d)", i, gtkSizes[i], width, height);
979 }
981 g_object_unref(G_OBJECT(pb));
982 }
983 }
984 //g_object_unref(icon);
985 init = true;
986 }
988 return vals[size];
989 }
991 void IconImpl::paint(SPIcon *icon, GdkRectangle const */*area*/)
992 {
993 GtkWidget &widget = *GTK_WIDGET(icon);
994 GdkPixbuf *image = icon->pb;
995 bool unref_image = false;
997 /* copied from the expose function of GtkImage */
998 if (GTK_WIDGET_STATE (icon) != GTK_STATE_NORMAL && image) {
999 GtkIconSource *source = gtk_icon_source_new();
1000 gtk_icon_source_set_pixbuf(source, icon->pb);
1001 gtk_icon_source_set_size(source, GTK_ICON_SIZE_SMALL_TOOLBAR); // note: this is boilerplate and not used
1002 gtk_icon_source_set_size_wildcarded(source, FALSE);
1003 image = gtk_style_render_icon (widget.style, source, gtk_widget_get_direction(&widget),
1004 (GtkStateType) GTK_WIDGET_STATE(&widget), (GtkIconSize)-1, &widget, "gtk-image");
1005 gtk_icon_source_free(source);
1006 unref_image = true;
1007 }
1009 if (image) {
1010 int x = floor(widget.allocation.x + ((widget.allocation.width - widget.requisition.width) * 0.5));
1011 int y = floor(widget.allocation.y + ((widget.allocation.height - widget.requisition.height) * 0.5));
1012 int width = gdk_pixbuf_get_width(image);
1013 int height = gdk_pixbuf_get_height(image);
1014 // Limit drawing to when we actually have something. Avoids some crashes.
1015 if ( (width > 0) && (height > 0) ) {
1016 gdk_draw_pixbuf(GDK_DRAWABLE(widget.window), widget.style->black_gc, image,
1017 0, 0, x, y, width, height,
1018 GDK_RGB_DITHER_NORMAL, x, y);
1019 }
1020 }
1022 if (unref_image) {
1023 g_object_unref(G_OBJECT(image));
1024 }
1025 }
1027 GdkPixbuf *IconImpl::loadPixmap(gchar const *name, unsigned /*lsize*/, unsigned psize)
1028 {
1029 gchar *path = (gchar *) g_strdup_printf("%s/%s.png", INKSCAPE_PIXMAPDIR, name);
1030 // TODO: bulia, please look over
1031 gsize bytesRead = 0;
1032 gsize bytesWritten = 0;
1033 GError *error = NULL;
1034 gchar *localFilename = g_filename_from_utf8( path,
1035 -1,
1036 &bytesRead,
1037 &bytesWritten,
1038 &error);
1039 GdkPixbuf *pb = gdk_pixbuf_new_from_file(localFilename, NULL);
1040 g_free(localFilename);
1041 g_free(path);
1042 if (!pb) {
1043 path = (gchar *) g_strdup_printf("%s/%s.xpm", INKSCAPE_PIXMAPDIR, name);
1044 // TODO: bulia, please look over
1045 gsize bytesRead = 0;
1046 gsize bytesWritten = 0;
1047 GError *error = NULL;
1048 gchar *localFilename = g_filename_from_utf8( path,
1049 -1,
1050 &bytesRead,
1051 &bytesWritten,
1052 &error);
1053 pb = gdk_pixbuf_new_from_file(localFilename, NULL);
1054 g_free(localFilename);
1055 g_free(path);
1056 }
1058 if (pb) {
1059 if (!gdk_pixbuf_get_has_alpha(pb)) {
1060 gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
1061 }
1063 if ( ( static_cast<unsigned>(gdk_pixbuf_get_width(pb)) != psize )
1064 || ( static_cast<unsigned>(gdk_pixbuf_get_height(pb)) != psize ) ) {
1065 GdkPixbuf *spb = gdk_pixbuf_scale_simple(pb, psize, psize, GDK_INTERP_HYPER);
1066 g_object_unref(G_OBJECT(pb));
1067 pb = spb;
1068 }
1069 }
1071 return pb;
1072 }
1074 // takes doc, root, icon, and icon name to produce pixels
1075 extern "C" guchar *sp_icon_doc_icon( SPDocument *doc, NRArenaItem *root,
1076 gchar const *name, unsigned psize )
1077 {
1078 bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
1079 guchar *px = NULL;
1081 if (doc) {
1082 SPObject *object = doc->getObjectById(name);
1083 if (object && SP_IS_ITEM(object)) {
1084 /* Find bbox in document */
1085 Geom::Matrix const i2doc(SP_ITEM(object)->i2doc_affine());
1086 Geom::OptRect dbox = SP_ITEM(object)->getBounds(i2doc);
1088 if ( SP_OBJECT_PARENT(object) == NULL )
1089 {
1090 dbox = Geom::Rect(Geom::Point(0, 0),
1091 Geom::Point(doc->getWidth(), doc->getHeight()));
1092 }
1094 /* This is in document coordinates, i.e. pixels */
1095 if ( dbox ) {
1096 NRGC gc(NULL);
1097 /* Update to renderable state */
1098 double sf = 1.0;
1099 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
1100 gc.transform.setIdentity();
1101 nr_arena_item_invoke_update( root, NULL, &gc,
1102 NR_ARENA_ITEM_STATE_ALL,
1103 NR_ARENA_ITEM_STATE_NONE );
1104 /* Item integer bbox in points */
1105 NRRectL ibox;
1106 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
1107 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
1108 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
1109 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
1111 if ( dump ) {
1112 g_message( " box --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
1113 }
1115 /* Find button visible area */
1116 int width = ibox.x1 - ibox.x0;
1117 int height = ibox.y1 - ibox.y0;
1119 if ( dump ) {
1120 g_message( " vis --'%s' (%d,%d)", name, width, height );
1121 }
1123 {
1124 int block = std::max(width, height);
1125 if (block != static_cast<int>(psize) ) {
1126 if ( dump ) {
1127 g_message(" resizing" );
1128 }
1129 sf = (double)psize / (double)block;
1131 nr_arena_item_set_transform(root, (Geom::Matrix)Geom::Scale(sf, sf));
1132 gc.transform.setIdentity();
1133 nr_arena_item_invoke_update( root, NULL, &gc,
1134 NR_ARENA_ITEM_STATE_ALL,
1135 NR_ARENA_ITEM_STATE_NONE );
1136 /* Item integer bbox in points */
1137 ibox.x0 = (int) floor(sf * dbox->min()[Geom::X] + 0.5);
1138 ibox.y0 = (int) floor(sf * dbox->min()[Geom::Y] + 0.5);
1139 ibox.x1 = (int) floor(sf * dbox->max()[Geom::X] + 0.5);
1140 ibox.y1 = (int) floor(sf * dbox->max()[Geom::Y] + 0.5);
1142 if ( dump ) {
1143 g_message( " box2 --'%s' (%f,%f)-(%f,%f)", name, (double)ibox.x0, (double)ibox.y0, (double)ibox.x1, (double)ibox.y1 );
1144 }
1146 /* Find button visible area */
1147 width = ibox.x1 - ibox.x0;
1148 height = ibox.y1 - ibox.y0;
1149 if ( dump ) {
1150 g_message( " vis2 --'%s' (%d,%d)", name, width, height );
1151 }
1152 }
1153 }
1155 int dx, dy;
1156 //dx = (psize - width) / 2;
1157 //dy = (psize - height) / 2;
1158 dx=dy=psize;
1159 dx=(dx-width)/2; // watch out for psize, since 'unsigned'-'signed' can cause problems if the result is negative
1160 dy=(dy-height)/2;
1161 NRRectL area;
1162 area.x0 = ibox.x0 - dx;
1163 area.y0 = ibox.y0 - dy;
1164 area.x1 = area.x0 + psize;
1165 area.y1 = area.y0 + psize;
1166 /* Actual renderable area */
1167 NRRectL ua;
1168 ua.x0 = MAX(ibox.x0, area.x0);
1169 ua.y0 = MAX(ibox.y0, area.y0);
1170 ua.x1 = MIN(ibox.x1, area.x1);
1171 ua.y1 = MIN(ibox.y1, area.y1);
1173 if ( dump ) {
1174 g_message( " area --'%s' (%f,%f)-(%f,%f)", name, (double)area.x0, (double)area.y0, (double)area.x1, (double)area.y1 );
1175 g_message( " ua --'%s' (%f,%f)-(%f,%f)", name, (double)ua.x0, (double)ua.y0, (double)ua.x1, (double)ua.y1 );
1176 }
1177 /* Set up pixblock */
1178 px = g_new(guchar, 4 * psize * psize);
1179 memset(px, 0x00, 4 * psize * psize);
1180 /* Render */
1181 NRPixBlock B;
1182 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
1183 ua.x0, ua.y0, ua.x1, ua.y1,
1184 px + 4 * psize * (ua.y0 - area.y0) +
1185 4 * (ua.x0 - area.x0),
1186 4 * psize, FALSE, FALSE );
1187 nr_arena_item_invoke_render(NULL, root, &ua, &B,
1188 NR_ARENA_ITEM_RENDER_NO_CACHE );
1189 nr_pixblock_release(&B);
1191 if ( Inkscape::Preferences::get()->getBool("/debug/icons/overlaySvg") ) {
1192 IconImpl::overlayPixels( px, psize, psize, 4 * psize, 0x00, 0x00, 0xff );
1193 }
1194 }
1195 }
1196 }
1198 return px;
1199 } // end of sp_icon_doc_icon()
1203 class SVGDocCache
1204 {
1205 public:
1206 SVGDocCache( SPDocument *doc, NRArenaItem *root ) : doc(doc), root(root) {}
1207 SPDocument *doc;
1208 NRArenaItem *root;
1209 };
1211 static std::map<Glib::ustring, SVGDocCache *> doc_cache;
1212 static std::map<Glib::ustring, GdkPixbuf *> pb_cache;
1214 Glib::ustring icon_cache_key(Glib::ustring const & name, unsigned psize)
1215 {
1216 Glib::ustring key = name;
1217 key += ":";
1218 key += psize;
1219 return key;
1220 }
1222 GdkPixbuf *get_cached_pixbuf(Glib::ustring const &key) {
1223 GdkPixbuf* pb = 0;
1224 std::map<Glib::ustring, GdkPixbuf *>::iterator found = pb_cache.find(key);
1225 if ( found != pb_cache.end() ) {
1226 pb = found->second;
1227 }
1228 return pb;
1229 }
1231 std::list<gchar*> &IconImpl::icons_svg_paths()
1232 {
1233 static std::list<gchar *> sources;
1234 static bool initialized = false;
1235 if (!initialized) {
1236 // Fall back from user prefs dir into system locations.
1237 gchar *userdir = profile_path("icons");
1238 sources.push_back(g_build_filename(userdir,"icons.svg", NULL));
1239 sources.push_back(g_build_filename(INKSCAPE_PIXMAPDIR, "icons.svg", NULL));
1240 g_free(userdir);
1241 initialized = true;
1242 }
1243 return sources;
1244 }
1246 // this function renders icons from icons.svg and returns the pixels.
1247 guchar *IconImpl::load_svg_pixels(std::list<Glib::ustring> const &names,
1248 unsigned /*lsize*/, unsigned psize)
1249 {
1250 bool const dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpSvg");
1251 std::list<gchar *> &sources = icons_svg_paths();
1253 // Try each document in turn until we successfully load the icon from one
1254 guchar *px = NULL;
1255 for (std::list<gchar*>::iterator i = sources.begin(); (i != sources.end()) && !px; ++i) {
1256 gchar *doc_filename = *i;
1257 SVGDocCache *info = 0;
1259 // Did we already load this doc?
1260 Glib::ustring key(doc_filename);
1261 {
1262 std::map<Glib::ustring, SVGDocCache *>::iterator i = doc_cache.find(key);
1263 if ( i != doc_cache.end() ) {
1264 info = i->second;
1265 }
1266 }
1268 // Try to load from document.
1269 if (!info && Inkscape::IO::file_test( doc_filename, G_FILE_TEST_IS_REGULAR ) ) {
1270 SPDocument *doc = SPDocument::createNewDoc( doc_filename, FALSE );
1271 if ( doc ) {
1272 if ( dump ) {
1273 g_message("Loaded icon file %s", doc_filename);
1274 }
1275 // prep the document
1276 doc->ensureUpToDate();
1278 // Create new arena
1279 NRArena *arena = NRArena::create();
1281 // Create ArenaItem and set transform
1282 unsigned visionkey = SPItem::display_key_new(1);
1283 // fixme: Memory manage root if needed (Lauris)
1284 // This needs to be fixed indeed; this leads to a memory leak of a few megabytes these days
1285 // because shapes are being rendered which are not being freed
1286 NRArenaItem *root = SP_ITEM(doc->getRoot())->invoke_show( arena, visionkey, SP_ITEM_SHOW_DISPLAY );
1288 // store into the cache
1289 info = new SVGDocCache(doc, root);
1290 doc_cache[key] = info;
1291 }
1292 }
1293 if (info) {
1294 for (std::list<Glib::ustring>::const_iterator it = names.begin(); !px && (it != names.end()); ++it ) {
1295 px = sp_icon_doc_icon( info->doc, info->root, it->c_str(), psize );
1296 }
1297 }
1298 }
1300 return px;
1301 }
1303 static void addToIconSet(GdkPixbuf* pb, gchar const* name, GtkIconSize lsize, unsigned psize) {
1304 static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1305 GtkStockItem stock;
1306 gboolean stockFound = gtk_stock_lookup( name, &stock );
1307 if ( !stockFound ) {
1308 Gtk::IconTheme::add_builtin_icon( name, psize, Glib::wrap(pb) );
1309 if (dump) {
1310 g_message(" set in a builtin for %s:%d:%d", name, lsize, psize);
1311 }
1312 }
1313 }
1315 void Inkscape::queueIconPrerender( Glib::ustring const &name, Inkscape::IconSize lsize )
1316 {
1317 GtkStockItem stock;
1318 gboolean stockFound = gtk_stock_lookup( name.c_str(), &stock );
1319 gboolean themedFound = gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name.c_str());
1320 if (!stockFound && !themedFound ) {
1321 gint trySize = CLAMP( static_cast<gint>(lsize), 0, static_cast<gint>(G_N_ELEMENTS(iconSizeLookup) - 1) );
1322 if ( !sizeMapDone ) {
1323 IconImpl::injectCustomSize();
1324 }
1325 GtkIconSize mappedSize = iconSizeLookup[trySize];
1327 int psize = IconImpl::getPhysSize(lsize);
1328 // TODO place in a queue that is triggered by other map events
1329 IconImpl::prerenderIcon(name.c_str(), mappedSize, psize);
1330 }
1331 }
1333 static std::map<unsigned, Glib::ustring> sizePaths;
1335 static std::string getDestDir( unsigned psize )
1336 {
1337 if ( sizePaths.find(psize) == sizePaths.end() ) {
1338 gchar *tmp = g_strdup_printf("%dx%d", psize, psize);
1339 sizePaths[psize] = tmp;
1340 g_free(tmp);
1341 }
1343 return sizePaths[psize];
1344 }
1346 // returns true if icon needed preloading, false if nothing was done
1347 bool IconImpl::prerenderIcon(gchar const *name, GtkIconSize lsize, unsigned psize)
1348 {
1349 bool loadNeeded = false;
1350 static bool dump = Inkscape::Preferences::get()->getBool("/debug/icons/dumpGtk");
1351 static bool useCache = Inkscape::Preferences::get()->getBool("/debug/icons/useCache", true);
1352 static bool cacheValidated = false;
1353 if (!cacheValidated) {
1354 cacheValidated = true;
1355 if ( useCache ) {
1356 validateCache();
1357 }
1358 }
1360 Glib::ustring key = icon_cache_key(name, psize);
1361 if ( !get_cached_pixbuf(key) ) {
1362 if ((internalNames.find(name) != internalNames.end())
1363 || (!gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), name))) {
1364 if (dump) {
1365 g_message("prerenderIcon [%s] %d:%d", name, lsize, psize);
1366 }
1368 std::string potentialFile;
1369 bool dataLoaded = false;
1370 if ( useCache ) {
1371 // In file encoding:
1372 std::string iconCacheDir = Glib::build_filename(Glib::build_filename(Glib::get_user_cache_dir(), "inkscape"), "icons");
1373 std::string subpart = getDestDir(psize);
1374 std::string subdir = Glib::build_filename( iconCacheDir, subpart );
1375 if ( !Glib::file_test(subdir, Glib::FILE_TEST_EXISTS) ) {
1376 g_mkdir_with_parents( subdir.c_str(), 0x1ED );
1377 }
1378 potentialFile = Glib::build_filename( subdir, name );
1379 potentialFile += ".png";
1381 if ( Glib::file_test(potentialFile, Glib::FILE_TEST_EXISTS) && Glib::file_test(potentialFile, Glib::FILE_TEST_IS_REGULAR) ) {
1382 bool badFile = false;
1383 try {
1384 Glib::RefPtr<Gdk::Pixbuf> pb = Gdk::Pixbuf::create_from_file(potentialFile);
1385 if (pb) {
1386 dataLoaded = true;
1387 GdkPixbuf *obj = pb->gobj();
1388 g_object_ref(obj);
1389 pb_cache[key] = obj;
1390 addToIconSet(obj, name, lsize, psize);
1391 loadNeeded = true;
1392 if (internalNames.find(name) == internalNames.end()) {
1393 internalNames.insert(name);
1394 }
1395 }
1396 } catch ( Glib::FileError &ex ) {
1397 //g_warning("FileError [%s]", ex.what().c_str());
1398 badFile = true;
1399 } catch ( Gdk::PixbufError &ex ) {
1400 //g_warning("PixbufError [%s]", ex.what().c_str());
1401 // Invalid contents. Remove cached item
1402 badFile = true;
1403 }
1404 if ( badFile ) {
1405 g_remove(potentialFile.c_str());
1406 }
1407 }
1408 }
1410 if (!dataLoaded) {
1411 std::list<Glib::ustring> names;
1412 names.push_back(name);
1413 if ( legacyNames.find(name) != legacyNames.end() ) {
1414 names.push_back(legacyNames[name]);
1415 if ( dump ) {
1416 g_message("load_svg_pixels([%s] = %s, %d, %d)", name, legacyNames[name].c_str(), lsize, psize);
1417 }
1418 }
1419 guchar* px = load_svg_pixels(names, lsize, psize);
1420 if (px) {
1421 GdkPixbuf* pb = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, TRUE, 8,
1422 psize, psize, psize * 4,
1423 reinterpret_cast<GdkPixbufDestroyNotify>(g_free), NULL );
1424 pb_cache[key] = pb;
1425 addToIconSet(pb, name, lsize, psize);
1426 loadNeeded = true;
1427 if (internalNames.find(name) == internalNames.end()) {
1428 internalNames.insert(name);
1429 }
1430 if (useCache) {
1431 g_object_ref(pb);
1432 Glib::RefPtr<Gdk::Pixbuf> ppp = Glib::wrap(pb);
1433 try {
1434 ppp->save( potentialFile, "png" );
1435 } catch ( Glib::FileError &ex ) {
1436 //g_warning("FileError [%s]", ex.what().c_str());
1437 } catch ( Gdk::PixbufError &ex ) {
1438 //g_warning("PixbufError [%s]", ex.what().c_str());
1439 }
1440 }
1441 } else if (dump) {
1442 g_message("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX error!!! pixels not found for '%s'", name);
1443 }
1444 }
1445 }
1446 else if (dump) {
1447 g_message("prerenderIcon [%s] %d NOT!!!!!!", name, psize);
1448 }
1449 }
1450 return loadNeeded;
1451 }
1453 GdkPixbuf *IconImpl::loadSvg(std::list<Glib::ustring> const &names, GtkIconSize lsize, unsigned psize)
1454 {
1455 Glib::ustring key = icon_cache_key(*names.begin(), psize);
1457 // did we already load this icon at this scale/size?
1458 GdkPixbuf* pb = get_cached_pixbuf(key);
1459 if (!pb) {
1460 guchar *px = load_svg_pixels(names, lsize, psize);
1461 if (px) {
1462 pb = gdk_pixbuf_new_from_data(px, GDK_COLORSPACE_RGB, TRUE, 8,
1463 psize, psize, psize * 4,
1464 (GdkPixbufDestroyNotify)g_free, NULL);
1465 pb_cache[key] = pb;
1466 addToIconSet(pb, names.begin()->c_str(), lsize, psize);
1467 }
1468 }
1470 if ( pb ) {
1471 // increase refcount since we're handing out ownership
1472 g_object_ref(G_OBJECT(pb));
1473 }
1474 return pb;
1475 }
1477 void IconImpl::overlayPixels(guchar *px, int width, int height, int stride,
1478 unsigned r, unsigned g, unsigned b)
1479 {
1480 int bytesPerPixel = 4;
1481 int spacing = 4;
1482 for ( int y = 0; y < height; y += spacing ) {
1483 guchar *ptr = px + y * stride;
1484 for ( int x = 0; x < width; x += spacing ) {
1485 *(ptr++) = r;
1486 *(ptr++) = g;
1487 *(ptr++) = b;
1488 *(ptr++) = 0xff;
1490 ptr += bytesPerPixel * (spacing - 1);
1491 }
1492 }
1494 if ( width > 1 && height > 1 ) {
1495 // point at the last pixel
1496 guchar *ptr = px + ((height-1) * stride) + ((width - 1) * bytesPerPixel);
1498 if ( width > 2 ) {
1499 px[4] = r;
1500 px[5] = g;
1501 px[6] = b;
1502 px[7] = 0xff;
1504 ptr[-12] = r;
1505 ptr[-11] = g;
1506 ptr[-10] = b;
1507 ptr[-9] = 0xff;
1508 }
1510 ptr[-4] = r;
1511 ptr[-3] = g;
1512 ptr[-2] = b;
1513 ptr[-1] = 0xff;
1515 px[0 + stride] = r;
1516 px[1 + stride] = g;
1517 px[2 + stride] = b;
1518 px[3 + stride] = 0xff;
1520 ptr[0 - stride] = r;
1521 ptr[1 - stride] = g;
1522 ptr[2 - stride] = b;
1523 ptr[3 - stride] = 0xff;
1525 if ( height > 2 ) {
1526 ptr[0 - stride * 3] = r;
1527 ptr[1 - stride * 3] = g;
1528 ptr[2 - stride * 3] = b;
1529 ptr[3 - stride * 3] = 0xff;
1530 }
1531 }
1532 }
1534 class preRenderItem
1535 {
1536 public:
1537 preRenderItem( GtkIconSize lsize, gchar const *name ) :
1538 _lsize( lsize ),
1539 _name( name )
1540 {}
1541 GtkIconSize _lsize;
1542 Glib::ustring _name;
1543 };
1546 static std::vector<preRenderItem> pendingRenders;
1547 static bool callbackHooked = false;
1549 void IconImpl::addPreRender( GtkIconSize lsize, gchar const *name )
1550 {
1551 if ( !callbackHooked )
1552 {
1553 callbackHooked = true;
1554 g_idle_add_full( G_PRIORITY_LOW, &prerenderTask, NULL, NULL );
1555 }
1557 pendingRenders.push_back(preRenderItem(lsize, name));
1558 }
1560 gboolean IconImpl::prerenderTask(gpointer /*data*/) {
1561 if ( inkscapeIsCrashing() ) {
1562 // stop
1563 } else if (!pendingRenders.empty()) {
1564 bool workDone = false;
1565 do {
1566 preRenderItem single = pendingRenders.front();
1567 pendingRenders.erase(pendingRenders.begin());
1568 int psize = getPhysSize(single._lsize);
1569 workDone = prerenderIcon(single._name.c_str(), single._lsize, psize);
1570 } while (!pendingRenders.empty() && !workDone);
1571 }
1573 if (!inkscapeIsCrashing() && !pendingRenders.empty()) {
1574 return TRUE;
1575 } else {
1576 callbackHooked = false;
1577 return FALSE;
1578 }
1579 }
1582 void IconImpl::imageMapCB(GtkWidget* widget, gpointer user_data)
1583 {
1584 gchar* id = 0;
1585 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1586 gtk_image_get_stock(GTK_IMAGE(widget), &id, &size);
1587 GtkIconSize lsize = static_cast<GtkIconSize>(GPOINTER_TO_INT(user_data));
1588 if ( id ) {
1589 int psize = getPhysSize(lsize);
1590 g_message("imageMapCB(%p) for [%s]:%d:%d", widget, id, lsize, psize);
1591 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1592 if ( (it->_name == id) && (it->_lsize == lsize) ) {
1593 prerenderIcon(id, lsize, psize);
1594 pendingRenders.erase(it);
1595 g_message(" prerender for %s:%d:%d", id, lsize, psize);
1596 if (lsize != size) {
1597 int psize = getPhysSize(size);
1598 prerenderIcon(id, size, psize);
1599 }
1600 break;
1601 }
1602 }
1603 }
1605 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapCB, user_data);
1606 }
1608 void IconImpl::imageMapNamedCB(GtkWidget* widget, gpointer user_data)
1609 {
1610 GtkImage* img = GTK_IMAGE(widget);
1611 gchar const* iconName = 0;
1612 GtkIconSize size = GTK_ICON_SIZE_INVALID;
1613 gtk_image_get_icon_name(img, &iconName, &size);
1614 if ( iconName ) {
1615 GtkImageType type = gtk_image_get_storage_type( GTK_IMAGE(img) );
1616 if ( type == GTK_IMAGE_ICON_NAME ) {
1618 gint iconSize = 0;
1619 gchar* iconName = 0;
1620 {
1621 g_object_get(G_OBJECT(widget),
1622 "icon-name", &iconName,
1623 "icon-size", &iconSize,
1624 NULL);
1625 }
1627 for ( std::vector<preRenderItem>::iterator it = pendingRenders.begin(); it != pendingRenders.end(); ++it ) {
1628 if ( (it->_name == iconName) && (it->_lsize == size) ) {
1629 int psize = getPhysSize(size);
1630 prerenderIcon(iconName, size, psize);
1631 pendingRenders.erase(it);
1632 break;
1633 }
1634 }
1636 gtk_image_set_from_icon_name(img, "", (GtkIconSize)iconSize);
1637 gtk_image_set_from_icon_name(img, iconName, (GtkIconSize)iconSize);
1638 } else {
1639 g_warning("UNEXPECTED TYPE of %d", (int)type);
1640 }
1641 }
1643 g_signal_handlers_disconnect_by_func(widget, (gpointer)imageMapNamedCB, user_data);
1644 }
1647 /*
1648 Local Variables:
1649 mode:c++
1650 c-file-style:"stroustrup"
1651 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1652 indent-tabs-mode:nil
1653 fill-column:99
1654 End:
1655 */
1656 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :