Code

1a5ca6f772a72f7ba94fd99c153062bdabf9502b
[inkscape.git] / src / sp-item.cpp
1 /** \file
2  * Base class for visual SVG elements
3  */
4 /*
5  * Authors:
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *   bulia byak <buliabyak@users.sf.net>
8  *   Johan Engelen <j.b.c.engelen@ewi.utwente.nl>
9  *
10  * Copyright (C) 2001-2006 authors
11  * Copyright (C) 2001 Ximian, Inc.
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 /** \class SPItem
17  *
18  * SPItem is an abstract base class for all graphic (visible) SVG nodes. It
19  * is a subclass of SPObject, with great deal of specific functionality.
20  */
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif
27 #include "sp-item.h"
28 #include "svg/svg.h"
29 #include "print.h"
30 #include "display/nr-arena.h"
31 #include "display/nr-arena-item.h"
32 #include "attributes.h"
33 #include "document.h"
34 #include "uri.h"
35 #include "inkscape.h"
36 #include "desktop.h"
37 #include "desktop-handles.h"
39 #include "style.h"
40 #include <glibmm/i18n.h>
41 #include "sp-root.h"
42 #include "sp-clippath.h"
43 #include "sp-mask.h"
44 #include "sp-rect.h"
45 #include "sp-use.h"
46 #include "sp-text.h"
47 #include "sp-item-rm-unsatisfied-cns.h"
48 #include "sp-pattern.h"
49 #include "sp-switch.h"
50 #include "sp-guide-constraint.h"
51 #include "gradient-chemistry.h"
52 #include "preferences.h"
53 #include "conn-avoid-ref.h"
54 #include "conditions.h"
55 #include "sp-filter-reference.h"
56 #include "filter-chemistry.h"
57 #include "sp-guide.h"
58 #include "sp-title.h"
59 #include "sp-desc.h"
61 #include "libnr/nr-matrix-fns.h"
62 #include "libnr/nr-matrix-scale-ops.h"
63 #include "libnr/nr-matrix-translate-ops.h"
64 #include "libnr/nr-scale-translate-ops.h"
65 #include "libnr/nr-translate-scale-ops.h"
66 #include "libnr/nr-convert2geom.h"
67 #include "algorithms/find-last-if.h"
68 #include "util/reverse-list.h"
69 #include <2geom/rect.h>
70 #include <2geom/matrix.h>
71 #include <2geom/transforms.h>
73 #include "xml/repr.h"
74 #include "extract-uri.h"
75 #include "helper/geom.h"
77 #include "live_effects/lpeobject.h"
78 #include "live_effects/effect.h"
79 #include "live_effects/lpeobject-reference.h"
81 #define noSP_ITEM_DEBUG_IDLE
83 static void sp_item_class_init(SPItemClass *klass);
84 static void sp_item_init(SPItem *item);
86 static void sp_item_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
87 static void sp_item_release(SPObject *object);
88 static void sp_item_set(SPObject *object, unsigned key, gchar const *value);
89 static void sp_item_update(SPObject *object, SPCtx *ctx, guint flags);
90 static Inkscape::XML::Node *sp_item_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
92 static gchar *sp_item_private_description(SPItem *item);
93 static void sp_item_private_snappoints(SPItem const *item, bool const target, SnapPointsWithType &p, Inkscape::SnapPreferences const *snapprefs);
95 static SPItemView *sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, NRArenaItem *arenaitem);
96 static SPItemView *sp_item_view_list_remove(SPItemView *list, SPItemView *view);
98 static SPObjectClass *parent_class;
100 static void clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item);
101 static void mask_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item);
103 /**
104  * Registers SPItem class and returns its type number.
105  */
106 GType
107 sp_item_get_type(void)
109     static GType type = 0;
110     if (!type) {
111         GTypeInfo info = {
112             sizeof(SPItemClass),
113             NULL, NULL,
114             (GClassInitFunc) sp_item_class_init,
115             NULL, NULL,
116             sizeof(SPItem),
117             16,
118             (GInstanceInitFunc) sp_item_init,
119             NULL,   /* value_table */
120         };
121         type = g_type_register_static(SP_TYPE_OBJECT, "SPItem", &info, (GTypeFlags)0);
122     }
123     return type;
126 /**
127  * SPItem vtable initialization.
128  */
129 static void
130 sp_item_class_init(SPItemClass *klass)
132     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
134     parent_class = (SPObjectClass *)g_type_class_ref(SP_TYPE_OBJECT);
136     sp_object_class->build = sp_item_build;
137     sp_object_class->release = sp_item_release;
138     sp_object_class->set = sp_item_set;
139     sp_object_class->update = sp_item_update;
140     sp_object_class->write = sp_item_write;
142     klass->description = sp_item_private_description;
143     klass->snappoints = sp_item_private_snappoints;
146 /**
147  * Callback for SPItem object initialization.
148  */
149 static void
150 sp_item_init(SPItem *item)
152     item->init();
155 void SPItem::init() {
156     this->sensitive = TRUE;
158     this->transform_center_x = 0;
159     this->transform_center_y = 0;
161     this->_is_evaluated = true;
162     this->_evaluated_status = StatusUnknown;
164     this->transform = Geom::identity();
166     this->display = NULL;
168     this->clip_ref = new SPClipPathReference(this);
169     sigc::signal<void, SPObject *, SPObject *> cs1=this->clip_ref->changedSignal();
170     sigc::slot2<void,SPObject*, SPObject *> sl1=sigc::bind(sigc::ptr_fun(clip_ref_changed), this);
171     _clip_ref_connection = cs1.connect(sl1);
173     this->mask_ref = new SPMaskReference(this);
174     sigc::signal<void, SPObject *, SPObject *> cs2=this->mask_ref->changedSignal();
175     sigc::slot2<void,SPObject*, SPObject *> sl2=sigc::bind(sigc::ptr_fun(mask_ref_changed), this);
176     _mask_ref_connection = cs2.connect(sl2);
178     this->avoidRef = new SPAvoidRef(this);
180     new (&this->constraints) std::vector<SPGuideConstraint>();
182     new (&this->_transformed_signal) sigc::signal<void, Geom::Matrix const *, SPItem *>();
185 bool SPItem::isVisibleAndUnlocked() const {
186     return (!isHidden() && !isLocked());
189 bool SPItem::isVisibleAndUnlocked(unsigned display_key) const {
190     return (!isHidden(display_key) && !isLocked());
193 bool SPItem::isLocked() const {
194     for (SPObject *o = SP_OBJECT(this); o != NULL; o = SP_OBJECT_PARENT(o)) {
195         if (SP_IS_ITEM(o) && !(SP_ITEM(o)->sensitive))
196             return true;
197     }
198     return false;
201 void SPItem::setLocked(bool locked) {
202     SP_OBJECT_REPR(this)->setAttribute("sodipodi:insensitive",
203                      ( locked ? "1" : NULL ));
204     updateRepr();
207 bool SPItem::isHidden() const {
208     if (!isEvaluated())
209         return true;
210     return style->display.computed == SP_CSS_DISPLAY_NONE;
213 void SPItem::setHidden(bool hide) {
214     style->display.set = TRUE;
215     style->display.value = ( hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE );
216     style->display.computed = style->display.value;
217     style->display.inherit = FALSE;
218     updateRepr();
221 bool SPItem::isHidden(unsigned display_key) const {
222     if (!isEvaluated())
223         return true;
224     for ( SPItemView *view(display) ; view ; view = view->next ) {
225         if ( view->key == display_key ) {
226             g_assert(view->arenaitem != NULL);
227             for ( NRArenaItem *arenaitem = view->arenaitem ;
228                   arenaitem ; arenaitem = arenaitem->parent )
229             {
230                 if (!arenaitem->visible) {
231                     return true;
232                 }
233             }
234             return false;
235         }
236     }
237     return true;
240 void SPItem::setEvaluated(bool evaluated) {
241     _is_evaluated = evaluated;
242     _evaluated_status = StatusSet;
245 void SPItem::resetEvaluated() {
246     if ( StatusCalculated == _evaluated_status ) {
247         _evaluated_status = StatusUnknown;
248         bool oldValue = _is_evaluated;
249         if ( oldValue != isEvaluated() ) {
250             requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
251         }
252     } if ( StatusSet == _evaluated_status ) {
253         SPObject const *const parent = SP_OBJECT_PARENT(this);
254         if (SP_IS_SWITCH(parent)) {
255             SP_SWITCH(parent)->resetChildEvaluated();
256         }
257     }
260 bool SPItem::isEvaluated() const {
261     if ( StatusUnknown == _evaluated_status ) {
262         _is_evaluated = sp_item_evaluate(this);
263         _evaluated_status = StatusCalculated;
264     }
265     return _is_evaluated;
268 /**
269  * Returns something suitable for the `Hide' checkbox in the Object Properties dialog box.
270  *  Corresponds to setExplicitlyHidden.
271  */
272 bool
273 SPItem::isExplicitlyHidden() const
275     return (this->style->display.set
276             && this->style->display.value == SP_CSS_DISPLAY_NONE);
279 /**
280  * Sets the display CSS property to `hidden' if \a val is true,
281  * otherwise makes it unset
282  */
283 void
284 SPItem::setExplicitlyHidden(bool const val) {
285     this->style->display.set = val;
286     this->style->display.value = ( val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE );
287     this->style->display.computed = this->style->display.value;
288     this->updateRepr();
291 /**
292  * Sets the transform_center_x and transform_center_y properties to retain the rotation centre
293  */
294 void
295 SPItem::setCenter(Geom::Point object_centre) {
296     // for getBounds() to work
297     sp_document_ensure_up_to_date(SP_OBJECT_DOCUMENT(this));
299     Geom::OptRect bbox = getBounds(sp_item_i2d_affine(this));
300     if (bbox) {
301         transform_center_x = object_centre[Geom::X] - bbox->midpoint()[Geom::X];
302         if (fabs(transform_center_x) < 1e-5) // rounding error
303             transform_center_x = 0;
304         transform_center_y = object_centre[Geom::Y] - bbox->midpoint()[Geom::Y];
305         if (fabs(transform_center_y) < 1e-5) // rounding error
306             transform_center_y = 0;
307     }
310 void
311 SPItem::unsetCenter() {
312     transform_center_x = 0;
313     transform_center_y = 0;
316 bool SPItem::isCenterSet() {
317     return (transform_center_x != 0 || transform_center_y != 0);
320 Geom::Point SPItem::getCenter() const {
321     // for getBounds() to work
322     sp_document_ensure_up_to_date(SP_OBJECT_DOCUMENT(this));
324     Geom::OptRect bbox = getBounds(sp_item_i2d_affine(this));
325     if (bbox) {
326         return to_2geom(bbox->midpoint()) + Geom::Point (this->transform_center_x, this->transform_center_y);
327     } else {
328         return Geom::Point (0, 0); // something's wrong!
329     }
333 namespace {
335 bool is_item(SPObject const &object) {
336     return SP_IS_ITEM(&object);
341 void SPItem::raiseToTop() {
342     using Inkscape::Algorithms::find_last_if;
344     SPObject *topmost=find_last_if<SPObject::SiblingIterator>(
345         SP_OBJECT_NEXT(this), NULL, &is_item
346     );
347     if (topmost) {
348         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
349         sp_repr_parent(repr)->changeOrder(repr, SP_OBJECT_REPR(topmost));
350     }
353 void SPItem::raiseOne() {
354     SPObject *next_higher=std::find_if<SPObject::SiblingIterator>(
355         SP_OBJECT_NEXT(this), NULL, &is_item
356     );
357     if (next_higher) {
358         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
359         Inkscape::XML::Node *ref=SP_OBJECT_REPR(next_higher);
360         sp_repr_parent(repr)->changeOrder(repr, ref);
361     }
364 void SPItem::lowerOne() {
365     using Inkscape::Util::MutableList;
366     using Inkscape::Util::reverse_list;
368     MutableList<SPObject &> next_lower=std::find_if(
369         reverse_list<SPObject::SiblingIterator>(
370             SP_OBJECT_PARENT(this)->firstChild(), this
371         ),
372         MutableList<SPObject &>(),
373         &is_item
374     );
375     if (next_lower) {
376         ++next_lower;
377         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
378         Inkscape::XML::Node *ref=( next_lower ? SP_OBJECT_REPR(&*next_lower) : NULL );
379         sp_repr_parent(repr)->changeOrder(repr, ref);
380     }
383 void SPItem::lowerToBottom() {
384     using Inkscape::Algorithms::find_last_if;
385     using Inkscape::Util::MutableList;
386     using Inkscape::Util::reverse_list;
388     MutableList<SPObject &> bottom=find_last_if(
389         reverse_list<SPObject::SiblingIterator>(
390             SP_OBJECT_PARENT(this)->firstChild(), this
391         ),
392         MutableList<SPObject &>(),
393         &is_item
394     );
395     if (bottom) {
396         ++bottom;
397         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
398         Inkscape::XML::Node *ref=( bottom ? SP_OBJECT_REPR(&*bottom) : NULL );
399         sp_repr_parent(repr)->changeOrder(repr, ref);
400     }
403 static void
404 sp_item_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
406     sp_object_read_attr(object, "style");
407     sp_object_read_attr(object, "transform");
408     sp_object_read_attr(object, "clip-path");
409     sp_object_read_attr(object, "mask");
410     sp_object_read_attr(object, "sodipodi:insensitive");
411     sp_object_read_attr(object, "sodipodi:nonprintable");
412     sp_object_read_attr(object, "inkscape:transform-center-x");
413     sp_object_read_attr(object, "inkscape:transform-center-y");
414     sp_object_read_attr(object, "inkscape:connector-avoid");
415     sp_object_read_attr(object, "inkscape:connection-points");
417     if (((SPObjectClass *) (parent_class))->build) {
418         (* ((SPObjectClass *) (parent_class))->build)(object, document, repr);
419     }
422 static void
423 sp_item_release(SPObject *object)
425     SPItem *item = (SPItem *) object;
427     item->_clip_ref_connection.disconnect();
428     item->_mask_ref_connection.disconnect();
430     // Note: do this here before the clip_ref is deleted, since calling
431     // sp_document_ensure_up_to_date for triggered routing may reference
432     // the deleted clip_ref.
433     if (item->avoidRef) {
434         delete item->avoidRef;
435         item->avoidRef = NULL;
436     }
438     if (item->clip_ref) {
439         item->clip_ref->detach();
440         delete item->clip_ref;
441         item->clip_ref = NULL;
442     }
444     if (item->mask_ref) {
445         item->mask_ref->detach();
446         delete item->mask_ref;
447         item->mask_ref = NULL;
448     }
450     if (((SPObjectClass *) (parent_class))->release) {
451         ((SPObjectClass *) parent_class)->release(object);
452     }
454     while (item->display) {
455         nr_arena_item_unparent(item->display->arenaitem);
456         item->display = sp_item_view_list_remove(item->display, item->display);
457     }
459     item->_transformed_signal.~signal();
462 static void
463 sp_item_set(SPObject *object, unsigned key, gchar const *value)
465     SPItem *item = (SPItem *) object;
467     switch (key) {
468         case SP_ATTR_TRANSFORM: {
469             Geom::Matrix t;
470             if (value && sp_svg_transform_read(value, &t)) {
471                 sp_item_set_item_transform(item, t);
472             } else {
473                 sp_item_set_item_transform(item, Geom::identity());
474             }
475             break;
476         }
477         case SP_PROP_CLIP_PATH: {
478             gchar *uri = extract_uri(value);
479             if (uri) {
480                 try {
481                     item->clip_ref->attach(Inkscape::URI(uri));
482                 } catch (Inkscape::BadURIException &e) {
483                     g_warning("%s", e.what());
484                     item->clip_ref->detach();
485                 }
486                 g_free(uri);
487             } else {
488                 item->clip_ref->detach();
489             }
491             break;
492         }
493         case SP_PROP_MASK: {
494             gchar *uri = extract_uri(value);
495             if (uri) {
496                 try {
497                     item->mask_ref->attach(Inkscape::URI(uri));
498                 } catch (Inkscape::BadURIException &e) {
499                     g_warning("%s", e.what());
500                     item->mask_ref->detach();
501                 }
502                 g_free(uri);
503             } else {
504                 item->mask_ref->detach();
505             }
507             break;
508         }
509         case SP_ATTR_SODIPODI_INSENSITIVE:
510             item->sensitive = !value;
511             for (SPItemView *v = item->display; v != NULL; v = v->next) {
512                 nr_arena_item_set_sensitive(v->arenaitem, item->sensitive);
513             }
514             break;
515         case SP_ATTR_CONNECTOR_AVOID:
516             item->avoidRef->setAvoid(value);
517             break;
518         case SP_ATTR_CONNECTION_POINTS:
519             item->avoidRef->setConnectionPoints(value);
520             break;
521         case SP_ATTR_TRANSFORM_CENTER_X:
522             if (value) {
523                 item->transform_center_x = g_strtod(value, NULL);
524             } else {
525                 item->transform_center_x = 0;
526             }
527             object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
528             break;
529         case SP_ATTR_TRANSFORM_CENTER_Y:
530             if (value) {
531                 item->transform_center_y = g_strtod(value, NULL);
532             } else {
533                 item->transform_center_y = 0;
534             }
535             object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
536             break;
537         case SP_PROP_SYSTEM_LANGUAGE:
538         case SP_PROP_REQUIRED_FEATURES:
539         case SP_PROP_REQUIRED_EXTENSIONS:
540             {
541                 item->resetEvaluated();
542                 // pass to default handler
543             }
544         default:
545             if (SP_ATTRIBUTE_IS_CSS(key)) {
546                 sp_style_read_from_object(object->style, object);
547                 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
548             } else {
549                 if (((SPObjectClass *) (parent_class))->set) {
550                     (* ((SPObjectClass *) (parent_class))->set)(object, key, value);
551                 }
552             }
553             break;
554     }
557 static void
558 clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item)
560     if (old_clip) {
561         SPItemView *v;
562         /* Hide clippath */
563         for (v = item->display; v != NULL; v = v->next) {
564             sp_clippath_hide(SP_CLIPPATH(old_clip), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
565             nr_arena_item_set_clip(v->arenaitem, NULL);
566         }
567     }
568     if (SP_IS_CLIPPATH(clip)) {
569         NRRect bbox;
570         sp_item_invoke_bbox(item, &bbox, Geom::identity(), TRUE);
571         for (SPItemView *v = item->display; v != NULL; v = v->next) {
572             if (!v->arenaitem->key) {
573                 NR_ARENA_ITEM_SET_KEY(v->arenaitem, sp_item_display_key_new(3));
574             }
575             NRArenaItem *ai = sp_clippath_show(SP_CLIPPATH(clip),
576                                                NR_ARENA_ITEM_ARENA(v->arenaitem),
577                                                NR_ARENA_ITEM_GET_KEY(v->arenaitem));
578             nr_arena_item_set_clip(v->arenaitem, ai);
579             nr_arena_item_unref(ai);
580             sp_clippath_set_bbox(SP_CLIPPATH(clip), NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
581             SP_OBJECT(clip)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
582         }
583     }
586 static void
587 mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item)
589     if (old_mask) {
590         /* Hide mask */
591         for (SPItemView *v = item->display; v != NULL; v = v->next) {
592             sp_mask_hide(SP_MASK(old_mask), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
593             nr_arena_item_set_mask(v->arenaitem, NULL);
594         }
595     }
596     if (SP_IS_MASK(mask)) {
597         NRRect bbox;
598         sp_item_invoke_bbox(item, &bbox, Geom::identity(), TRUE);
599         for (SPItemView *v = item->display; v != NULL; v = v->next) {
600             if (!v->arenaitem->key) {
601                 NR_ARENA_ITEM_SET_KEY(v->arenaitem, sp_item_display_key_new(3));
602             }
603             NRArenaItem *ai = sp_mask_show(SP_MASK(mask),
604                                            NR_ARENA_ITEM_ARENA(v->arenaitem),
605                                            NR_ARENA_ITEM_GET_KEY(v->arenaitem));
606             nr_arena_item_set_mask(v->arenaitem, ai);
607             nr_arena_item_unref(ai);
608             sp_mask_set_bbox(SP_MASK(mask), NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
609             SP_OBJECT(mask)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
610         }
611     }
614 static void
615 sp_item_update(SPObject *object, SPCtx *ctx, guint flags)
617     SPItem *item = SP_ITEM(object);
619     if (((SPObjectClass *) (parent_class))->update)
620         (* ((SPObjectClass *) (parent_class))->update)(object, ctx, flags);
622     if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) {
623         if (flags & SP_OBJECT_MODIFIED_FLAG) {
624             for (SPItemView *v = item->display; v != NULL; v = v->next) {
625                 nr_arena_item_set_transform(v->arenaitem, item->transform);
626             }
627         }
629         SPClipPath *clip_path = item->clip_ref ? item->clip_ref->getObject() : NULL;
630         SPMask *mask = item->mask_ref ? item->mask_ref->getObject() : NULL;
632         if ( clip_path || mask ) {
633             NRRect bbox;
634             sp_item_invoke_bbox(item, &bbox, Geom::identity(), TRUE);
635             if (clip_path) {
636                 for (SPItemView *v = item->display; v != NULL; v = v->next) {
637                     sp_clippath_set_bbox(clip_path, NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
638                 }
639             }
640             if (mask) {
641                 for (SPItemView *v = item->display; v != NULL; v = v->next) {
642                     sp_mask_set_bbox(mask, NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
643                 }
644             }
645         }
647         if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
648             for (SPItemView *v = item->display; v != NULL; v = v->next) {
649                 nr_arena_item_set_opacity(v->arenaitem, SP_SCALE24_TO_FLOAT(object->style->opacity.value));
650                 nr_arena_item_set_visible(v->arenaitem, !item->isHidden());
651             }
652         }
653     }
655     /* Update bounding box data used by filters */
656     if (item->style->filter.set && item->display) {
657         Geom::OptRect item_bbox;
658         sp_item_invoke_bbox(item, item_bbox, Geom::identity(), TRUE, SPItem::GEOMETRIC_BBOX);
660         SPItemView *itemview = item->display;
661         do {
662             if (itemview->arenaitem)
663                 nr_arena_item_set_item_bbox(itemview->arenaitem, item_bbox);
664         } while ( (itemview = itemview->next) );
665     }
667     // Update libavoid with item geometry (for connector routing).
668     if (item->avoidRef)
669         item->avoidRef->handleSettingChange();
672 static Inkscape::XML::Node *
673 sp_item_write(SPObject *const object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
675     SPObject *child;
676     SPItem *item = SP_ITEM(object);
678     // in the case of SP_OBJECT_WRITE_BUILD, the item should always be newly created,
679     // so we need to add any children from the underlying object to the new repr
680     if (flags & SP_OBJECT_WRITE_BUILD) {
681         Inkscape::XML::Node *crepr;
682         GSList *l;
683         l = NULL;
684         for (child = sp_object_first_child(object); child != NULL; child = SP_OBJECT_NEXT(child) ) {
685             if (!SP_IS_TITLE(child) && !SP_IS_DESC(child)) continue;
686             crepr = child->updateRepr(xml_doc, NULL, flags);
687             if (crepr) l = g_slist_prepend (l, crepr);
688         }
689         while (l) {
690             repr->addChild((Inkscape::XML::Node *) l->data, NULL);
691             Inkscape::GC::release((Inkscape::XML::Node *) l->data);
692             l = g_slist_remove (l, l->data);
693         }
694     } else {
695         for (child = sp_object_first_child(object) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
696             if (!SP_IS_TITLE(child) && !SP_IS_DESC(child)) continue;
697             child->updateRepr(flags);
698         }
699     }
701     gchar *c = sp_svg_transform_write(item->transform);
702     repr->setAttribute("transform", c);
703     g_free(c);
705     if (flags & SP_OBJECT_WRITE_EXT) {
706         repr->setAttribute("sodipodi:insensitive", ( item->sensitive ? NULL : "true" ));
707         if (item->transform_center_x != 0)
708             sp_repr_set_svg_double (repr, "inkscape:transform-center-x", item->transform_center_x);
709         else
710             repr->setAttribute ("inkscape:transform-center-x", NULL);
711         if (item->transform_center_y != 0)
712             sp_repr_set_svg_double (repr, "inkscape:transform-center-y", item->transform_center_y);
713         else
714             repr->setAttribute ("inkscape:transform-center-y", NULL);
715     }
717     if (item->clip_ref->getObject()) {
718         const gchar *value = g_strdup_printf ("url(%s)", item->clip_ref->getURI()->toString());
719         repr->setAttribute ("clip-path", value);
720         g_free ((void *) value);
721     }
722     if (item->mask_ref->getObject()) {
723         const gchar *value = g_strdup_printf ("url(%s)", item->mask_ref->getURI()->toString());
724         repr->setAttribute ("mask", value);
725         g_free ((void *) value);
726     }
728     if (((SPObjectClass *) (parent_class))->write) {
729         ((SPObjectClass *) (parent_class))->write(object, xml_doc, repr, flags);
730     }
732     return repr;
735 /**
736  * \return  There is no guarantee that the return value will contain a rectangle.
737             If this item does not have a boundingbox, it might well be empty.
738  */
739 Geom::OptRect SPItem::getBounds(Geom::Matrix const &transform,
740                                       SPItem::BBoxType type,
741                                       unsigned int /*dkey*/) const
743     Geom::OptRect r;
744     sp_item_invoke_bbox_full(this, r, transform, type, TRUE);
745     return r;
748 void
749 sp_item_invoke_bbox(SPItem const *item, Geom::OptRect &bbox, Geom::Matrix const &transform, unsigned const clear, SPItem::BBoxType type)
751     sp_item_invoke_bbox_full(item, bbox, transform, type, clear);
754 // DEPRECATED to phase out the use of NRRect in favor of Geom::OptRect
755 void
756 sp_item_invoke_bbox(SPItem const *item, NRRect *bbox, Geom::Matrix const &transform, unsigned const clear, SPItem::BBoxType type)
758     sp_item_invoke_bbox_full(item, bbox, transform, type, clear);
761 /** Calls \a item's subclass' bounding box method; clips it by the bbox of clippath, if any; and
762  * unions the resulting bbox with \a bbox. If \a clear is true, empties \a bbox first. Passes the
763  * transform and the flags to the actual bbox methods. Note that many of subclasses (e.g. groups,
764  * clones), in turn, call this function in their bbox methods.
765  * \retval bbox  Note that there is no guarantee that bbox will contain a rectangle when the
766  *               function returns. If this item does not have a boundingbox, this might well be empty.
767  */
768 void
769 sp_item_invoke_bbox_full(SPItem const *item, Geom::OptRect &bbox, Geom::Matrix const &transform, unsigned const flags, unsigned const clear)
771     g_assert(item != NULL);
772     g_assert(SP_IS_ITEM(item));
774     if (clear) {
775         bbox = Geom::OptRect();
776     }
778     // TODO: replace NRRect by Geom::Rect, for all SPItemClasses, and for SP_CLIPPATH
780     NRRect temp_bbox;
781     temp_bbox.x0 = temp_bbox.y0 = NR_HUGE;
782     temp_bbox.x1 = temp_bbox.y1 = -NR_HUGE;
784     // call the subclass method
785     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox) {
786         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox(item, &temp_bbox, transform, flags);
787     }
789     // unless this is geometric bbox, extend by filter area and crop the bbox by clip path, if any
790     if ((SPItem::BBoxType) flags != SPItem::GEOMETRIC_BBOX) {
791         if (SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->filter.href) {
792             SPObject *filter = SP_OBJECT_STYLE(item)->getFilter();
793             if (filter && SP_IS_FILTER(filter)) {
794                 // default filer area per the SVG spec:
795                 double x = -0.1;
796                 double y = -0.1;
797                 double w = 1.2;
798                 double h = 1.2;
800                 // if area is explicitly set, override:
801                 if (SP_FILTER(filter)->x._set)
802                     x = SP_FILTER(filter)->x.computed;
803                 if (SP_FILTER(filter)->y._set)
804                     y = SP_FILTER(filter)->y.computed;
805                 if (SP_FILTER(filter)->width._set)
806                     w = SP_FILTER(filter)->width.computed;
807                 if (SP_FILTER(filter)->height._set)
808                     h = SP_FILTER(filter)->height.computed;
810                 double dx0 = 0;
811                 double dx1 = 0;
812                 double dy0 = 0;
813                 double dy1 = 0;
814                 if (filter_is_single_gaussian_blur(SP_FILTER(filter))) {
815                     // if this is a single blur, use 2.4*radius
816                     // which may be smaller than the default area;
817                     // see set_filter_area for why it's 2.4
818                     double r = get_single_gaussian_blur_radius (SP_FILTER(filter));
819                     dx0 = -2.4 * r;
820                     dx1 = 2.4 * r;
821                     dy0 = -2.4 * r;
822                     dy1 = 2.4 * r;
823                 } else {
824                     // otherwise, calculate expansion from relative to absolute units:
825                     dx0 = x * (temp_bbox.x1 - temp_bbox.x0);
826                     dx1 = (w + x - 1) * (temp_bbox.x1 - temp_bbox.x0);
827                     dy0 = y * (temp_bbox.y1 - temp_bbox.y0);
828                     dy1 = (h + y - 1) * (temp_bbox.y1 - temp_bbox.y0);
829                 }
831                 // transform the expansions by the item's transform:
832                 Geom::Matrix i2d(sp_item_i2d_affine (item));
833                 dx0 *= i2d.expansionX();
834                 dx1 *= i2d.expansionX();
835                 dy0 *= i2d.expansionY();
836                 dy1 *= i2d.expansionY();
838                 // expand the bbox
839                 temp_bbox.x0 += dx0;
840                 temp_bbox.x1 += dx1;
841                 temp_bbox.y0 += dy0;
842                 temp_bbox.y1 += dy1;
843             }
844         }
845         if (item->clip_ref->getObject()) {
846             NRRect b;
847             sp_clippath_get_bbox(SP_CLIPPATH(item->clip_ref->getObject()), &b, transform, flags);
848             nr_rect_d_intersect (&temp_bbox, &temp_bbox, &b);
849         }
850     }
852     if (temp_bbox.x0 > temp_bbox.x1 || temp_bbox.y0 > temp_bbox.y1) {
853         // Either the bbox hasn't been touched by the SPItemClass' bbox method
854         // (it still has its initial values, see above: x0 = y0 = NR_HUGE and x1 = y1 = -NR_HUGE)
855         // or it has explicitely been set to be like this (e.g. in sp_shape_bbox)
857         // When x0 > x1 or y0 > y1, the bbox is considered to be "nothing", although it has not been
858         // explicitely defined this way for NRRects (as opposed to Geom::OptRect)
859         // So union bbox with nothing = do nothing, just return
860         return;
861     }
863     // Do not use temp_bbox.upgrade() here, because it uses a test that returns an empty Geom::OptRect()
864     // for any rectangle with zero area. The geometrical bbox of for example a vertical line
865     // would therefore be translated into empty Geom::OptRect() (see bug https://bugs.launchpad.net/inkscape/+bug/168684)
866     Geom::OptRect temp_bbox_new = Geom::Rect(Geom::Point(temp_bbox.x0, temp_bbox.y0), Geom::Point(temp_bbox.x1, temp_bbox.y1));
868     bbox = Geom::unify(bbox, temp_bbox_new);
871 // DEPRECATED to phase out the use of NRRect in favor of Geom::OptRect
872 /** Calls \a item's subclass' bounding box method; clips it by the bbox of clippath, if any; and
873  * unions the resulting bbox with \a bbox. If \a clear is true, empties \a bbox first. Passes the
874  * transform and the flags to the actual bbox methods. Note that many of subclasses (e.g. groups,
875  * clones), in turn, call this function in their bbox methods. */
876 void
877 sp_item_invoke_bbox_full(SPItem const *item, NRRect *bbox, Geom::Matrix const &transform, unsigned const flags, unsigned const clear)
879     g_assert(item != NULL);
880     g_assert(SP_IS_ITEM(item));
881     g_assert(bbox != NULL);
883     if (clear) {
884         bbox->x0 = bbox->y0 = 1e18;
885         bbox->x1 = bbox->y1 = -1e18;
886     }
888     NRRect this_bbox;
889     this_bbox.x0 = this_bbox.y0 = 1e18;
890     this_bbox.x1 = this_bbox.y1 = -1e18;
892     // call the subclass method
893     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox) {
894         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox(item, &this_bbox, transform, flags);
895     }
897     // unless this is geometric bbox, crop the bbox by clip path, if any
898     if ((SPItem::BBoxType) flags != SPItem::GEOMETRIC_BBOX && item->clip_ref->getObject()) {
899         NRRect b;
900         sp_clippath_get_bbox(SP_CLIPPATH(item->clip_ref->getObject()), &b, transform, flags);
901         nr_rect_d_intersect (&this_bbox, &this_bbox, &b);
902     }
904     // if non-empty (with some tolerance - ?) union this_bbox with the bbox we've got passed
905     if ( fabs(this_bbox.x1-this_bbox.x0) > -0.00001 && fabs(this_bbox.y1-this_bbox.y0) > -0.00001 ) {
906         nr_rect_d_union (bbox, bbox, &this_bbox);
907     }
910 unsigned sp_item_pos_in_parent(SPItem *item)
912     g_assert(item != NULL);
913     g_assert(SP_IS_ITEM(item));
915     SPObject *parent = SP_OBJECT_PARENT(item);
916     g_assert(parent != NULL);
917     g_assert(SP_IS_OBJECT(parent));
919     SPObject *object = SP_OBJECT(item);
921     unsigned pos=0;
922     for ( SPObject *iter = sp_object_first_child(parent) ; iter ; iter = SP_OBJECT_NEXT(iter)) {
923         if ( iter == object ) {
924             return pos;
925         }
926         if (SP_IS_ITEM(iter)) {
927             pos++;
928         }
929     }
931     g_assert_not_reached();
932     return 0;
935 void
936 sp_item_bbox_desktop(SPItem *item, NRRect *bbox, SPItem::BBoxType type)
938     g_assert(item != NULL);
939     g_assert(SP_IS_ITEM(item));
940     g_assert(bbox != NULL);
942     sp_item_invoke_bbox(item, bbox, sp_item_i2d_affine(item), TRUE, type);
945 Geom::OptRect sp_item_bbox_desktop(SPItem *item, SPItem::BBoxType type)
947     Geom::OptRect rect = Geom::OptRect();
948     sp_item_invoke_bbox(item, rect, sp_item_i2d_affine(item), TRUE, type);
949     return rect;
952 static void sp_item_private_snappoints(SPItem const *item, bool const target, SnapPointsWithType &p, Inkscape::SnapPreferences const */*snapprefs*/)
954     /* This will only be called if the derived class doesn't override this.
955      * see for example sp_genericellipse_snappoints in sp-ellipse.cpp
956      * We don't know what shape we could be dealing with here, so we'll just
957      * return the corners of the bounding box */
959     Geom::OptRect bbox = item->getBounds(sp_item_i2d_affine(item));
961     if (bbox) {
962         Geom::Point p1, p2;
963         p1 = bbox->min();
964         p2 = bbox->max();
965         int type = target ? int(Inkscape::SNAPTARGET_BBOX_CORNER) : int(Inkscape::SNAPSOURCE_BBOX_CORNER);
966         p.push_back(std::make_pair(p1, type));
967         p.push_back(std::make_pair(Geom::Point(p1[Geom::X], p2[Geom::Y]), type));
968         p.push_back(std::make_pair(p2, type));
969         p.push_back(std::make_pair(Geom::Point(p2[Geom::X], p1[Geom::Y]), type));
970     }
974 void sp_item_snappoints(SPItem const *item, bool const target, SnapPointsWithType &p, Inkscape::SnapPreferences const *snapprefs)
976     g_assert (item != NULL);
977     g_assert (SP_IS_ITEM(item));
979     // Get the snappoints of the item
980     SPItemClass const &item_class = *(SPItemClass const *) G_OBJECT_GET_CLASS(item);
981     if (item_class.snappoints) {
982         item_class.snappoints(item, target, p, snapprefs);
983     }
985     // Get the snappoints at the item's center
986     if (snapprefs != NULL && snapprefs->getIncludeItemCenter()) {
987         p.push_back(std::make_pair(item->getCenter(), target ? int(Inkscape::SNAPTARGET_ROTATION_CENTER) : int(Inkscape::SNAPSOURCE_ROTATION_CENTER)));
988     }
990     // Get the snappoints of clipping paths and mask, if any
991     std::list<SPObject const *> clips_and_masks;
993     clips_and_masks.push_back(SP_OBJECT(item->clip_ref->getObject()));
994     clips_and_masks.push_back(SP_OBJECT(item->mask_ref->getObject()));
996     SPDesktop *desktop = inkscape_active_desktop();
997     for (std::list<SPObject const *>::const_iterator o = clips_and_masks.begin(); o != clips_and_masks.end(); o++) {
998         if (*o) {
999             // obj is a group object, the children are the actual clippers
1000             for (SPObject *child = (*o)->children ; child ; child = child->next) {
1001                 if (SP_IS_ITEM(child)) {
1002                         SnapPointsWithType p_clip_or_mask;
1003                     // Please note the recursive call here!
1004                     sp_item_snappoints(SP_ITEM(child), target, p_clip_or_mask, snapprefs);
1005                     // Take into account the transformation of the item being clipped or masked
1006                     for (SnapPointsWithType::const_iterator p_orig = p_clip_or_mask.begin(); p_orig != p_clip_or_mask.end(); p_orig++) {
1007                         // All snappoints are in desktop coordinates, but the item's transformation is
1008                         // in document coordinates. Hence the awkward construction below
1009                         Geom::Point pt = desktop->dt2doc((*p_orig).first) * sp_item_i2d_affine(item);
1010                         p.push_back(std::make_pair(pt, (*p_orig).second));
1011                     }
1012                 }
1013             }
1014         }
1015     }
1018 void
1019 sp_item_invoke_print(SPItem *item, SPPrintContext *ctx)
1021     if (!item->isHidden()) {
1022         if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->print) {
1023             if (!item->transform.isIdentity()
1024                 || SP_OBJECT_STYLE(item)->opacity.value != SP_SCALE24_MAX)
1025             {
1026                 sp_print_bind(ctx, item->transform, SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value));
1027                 ((SPItemClass *) G_OBJECT_GET_CLASS(item))->print(item, ctx);
1028                 sp_print_release(ctx);
1029             } else {
1030                 ((SPItemClass *) G_OBJECT_GET_CLASS(item))->print(item, ctx);
1031             }
1032         }
1033     }
1036 static gchar *
1037 sp_item_private_description(SPItem */*item*/)
1039     return g_strdup(_("Object"));
1042 /**
1043  * Returns a string suitable for status bar, formatted in pango markup language.
1044  *
1045  * Must be freed by caller.
1046  */
1047 gchar *
1048 sp_item_description(SPItem *item)
1050     g_assert(item != NULL);
1051     g_assert(SP_IS_ITEM(item));
1053     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->description) {
1054         gchar *s = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->description(item);
1055         if (s && item->clip_ref->getObject()) {
1056             gchar *snew = g_strdup_printf (_("%s; <i>clipped</i>"), s);
1057             g_free (s);
1058             s = snew;
1059         }
1060         if (s && item->mask_ref->getObject()) {
1061             gchar *snew = g_strdup_printf (_("%s; <i>masked</i>"), s);
1062             g_free (s);
1063             s = snew;
1064         }
1065         if (SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->filter.href && SP_OBJECT_STYLE(item)->filter.href->getObject()) {
1066             const gchar *label = SP_OBJECT_STYLE(item)->filter.href->getObject()->label();
1067             gchar *snew;
1068             if (label) {
1069                 snew = g_strdup_printf (_("%s; <i>filtered (%s)</i>"), s, _(label));
1070             } else {
1071                 snew = g_strdup_printf (_("%s; <i>filtered</i>"), s);
1072             }
1073             g_free (s);
1074             s = snew;
1075         }
1076         return s;
1077     }
1079     g_assert_not_reached();
1080     return NULL;
1083 /**
1084  * Allocates unique integer keys.
1085  * \param numkeys Number of keys required.
1086  * \return First allocated key; hence if the returned key is n
1087  * you can use n, n + 1, ..., n + (numkeys - 1)
1088  */
1089 unsigned
1090 sp_item_display_key_new(unsigned numkeys)
1092     static unsigned dkey = 0;
1094     dkey += numkeys;
1096     return dkey - numkeys;
1099 NRArenaItem *
1100 sp_item_invoke_show(SPItem *item, NRArena *arena, unsigned key, unsigned flags)
1102     g_assert(item != NULL);
1103     g_assert(SP_IS_ITEM(item));
1104     g_assert(arena != NULL);
1105     g_assert(NR_IS_ARENA(arena));
1107     NRArenaItem *ai = NULL;
1108     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->show) {
1109         ai = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->show(item, arena, key, flags);
1110     }
1112     if (ai != NULL) {
1113         item->display = sp_item_view_new_prepend(item->display, item, flags, key, ai);
1114         nr_arena_item_set_transform(ai, item->transform);
1115         nr_arena_item_set_opacity(ai, SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value));
1116         nr_arena_item_set_visible(ai, !item->isHidden());
1117         nr_arena_item_set_sensitive(ai, item->sensitive);
1118         if (item->clip_ref->getObject()) {
1119             SPClipPath *cp = item->clip_ref->getObject();
1121             if (!item->display->arenaitem->key) {
1122                 NR_ARENA_ITEM_SET_KEY(item->display->arenaitem, sp_item_display_key_new(3));
1123             }
1124             int clip_key = NR_ARENA_ITEM_GET_KEY(item->display->arenaitem);
1126             // Show and set clip
1127             NRArenaItem *ac = sp_clippath_show(cp, arena, clip_key);
1128             nr_arena_item_set_clip(ai, ac);
1129             nr_arena_item_unref(ac);
1131             // Update bbox, in case the clip uses bbox units
1132             NRRect bbox;
1133             sp_item_invoke_bbox(item, &bbox, Geom::identity(), TRUE);
1134             sp_clippath_set_bbox(SP_CLIPPATH(cp), clip_key, &bbox);
1135             SP_OBJECT(cp)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1136         }
1137         if (item->mask_ref->getObject()) {
1138             SPMask *mask = item->mask_ref->getObject();
1140             if (!item->display->arenaitem->key) {
1141                 NR_ARENA_ITEM_SET_KEY(item->display->arenaitem, sp_item_display_key_new(3));
1142             }
1143             int mask_key = NR_ARENA_ITEM_GET_KEY(item->display->arenaitem);
1145             // Show and set mask
1146             NRArenaItem *ac = sp_mask_show(mask, arena, mask_key);
1147             nr_arena_item_set_mask(ai, ac);
1148             nr_arena_item_unref(ac);
1150             // Update bbox, in case the mask uses bbox units
1151             NRRect bbox;
1152             sp_item_invoke_bbox(item, &bbox, Geom::identity(), TRUE);
1153             sp_mask_set_bbox(SP_MASK(mask), mask_key, &bbox);
1154             SP_OBJECT(mask)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1155         }
1156         NR_ARENA_ITEM_SET_DATA(ai, item);
1157         Geom::OptRect item_bbox;
1158         sp_item_invoke_bbox(item, item_bbox, Geom::identity(), TRUE, SPItem::GEOMETRIC_BBOX);
1159         nr_arena_item_set_item_bbox(ai, item_bbox);
1160     }
1162     return ai;
1165 void
1166 sp_item_invoke_hide(SPItem *item, unsigned key)
1168     g_assert(item != NULL);
1169     g_assert(SP_IS_ITEM(item));
1171     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->hide) {
1172         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->hide(item, key);
1173     }
1175     SPItemView *ref = NULL;
1176     SPItemView *v = item->display;
1177     while (v != NULL) {
1178         SPItemView *next = v->next;
1179         if (v->key == key) {
1180             if (item->clip_ref->getObject()) {
1181                 sp_clippath_hide(item->clip_ref->getObject(), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
1182                 nr_arena_item_set_clip(v->arenaitem, NULL);
1183             }
1184             if (item->mask_ref->getObject()) {
1185                 sp_mask_hide(item->mask_ref->getObject(), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
1186                 nr_arena_item_set_mask(v->arenaitem, NULL);
1187             }
1188             if (!ref) {
1189                 item->display = v->next;
1190             } else {
1191                 ref->next = v->next;
1192             }
1193             nr_arena_item_unparent(v->arenaitem);
1194             nr_arena_item_unref(v->arenaitem);
1195             g_free(v);
1196         } else {
1197             ref = v;
1198         }
1199         v = next;
1200     }
1203 // Adjusters
1205 void
1206 sp_item_adjust_pattern (SPItem *item, Geom::Matrix const &postmul, bool set)
1208     SPStyle *style = SP_OBJECT_STYLE (item);
1210     if (style && (style->fill.isPaintserver())) {
1211         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER (item);
1212         if (SP_IS_PATTERN (server)) {
1213             SPPattern *pattern = sp_pattern_clone_if_necessary (item, SP_PATTERN (server), "fill");
1214             sp_pattern_transform_multiply (pattern, postmul, set);
1215         }
1216     }
1218     if (style && (style->stroke.isPaintserver())) {
1219         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER (item);
1220         if (SP_IS_PATTERN (server)) {
1221             SPPattern *pattern = sp_pattern_clone_if_necessary (item, SP_PATTERN (server), "stroke");
1222             sp_pattern_transform_multiply (pattern, postmul, set);
1223         }
1224     }
1228 void
1229 sp_item_adjust_gradient (SPItem *item, Geom::Matrix const &postmul, bool set)
1231     SPStyle *style = SP_OBJECT_STYLE (item);
1233     if (style && (style->fill.isPaintserver())) {
1234         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
1235         if (SP_IS_GRADIENT (server)) {
1237             /**
1238              * \note Bbox units for a gradient are generally a bad idea because
1239              * with them, you cannot preserve the relative position of the
1240              * object and its gradient after rotation or skew. So now we
1241              * convert them to userspace units which are easy to keep in sync
1242              * just by adding the object's transform to gradientTransform.
1243              * \todo FIXME: convert back to bbox units after transforming with
1244              * the item, so as to preserve the original units.
1245              */
1246             SPGradient *gradient = sp_gradient_convert_to_userspace (SP_GRADIENT (server), item, "fill");
1248             sp_gradient_transform_multiply (gradient, postmul, set);
1249         }
1250     }
1252     if (style && (style->stroke.isPaintserver())) {
1253         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
1254         if (SP_IS_GRADIENT (server)) {
1255             SPGradient *gradient = sp_gradient_convert_to_userspace (SP_GRADIENT (server), item, "stroke");
1256             sp_gradient_transform_multiply (gradient, postmul, set);
1257         }
1258     }
1261 void
1262 sp_item_adjust_stroke (SPItem *item, gdouble ex)
1264     SPStyle *style = SP_OBJECT_STYLE (item);
1266     if (style && !style->stroke.isNone() && !NR_DF_TEST_CLOSE (ex, 1.0, NR_EPSILON)) {
1268         style->stroke_width.computed *= ex;
1269         style->stroke_width.set = TRUE;
1271         if (style->stroke_dash.n_dash != 0) {
1272             int i;
1273             for (i = 0; i < style->stroke_dash.n_dash; i++) {
1274                 style->stroke_dash.dash[i] *= ex;
1275             }
1276             style->stroke_dash.offset *= ex;
1277         }
1279         SP_OBJECT(item)->updateRepr();
1280     }
1283 /**
1284  * Find out the inverse of previous transform of an item (from its repr)
1285  */
1286 Geom::Matrix
1287 sp_item_transform_repr (SPItem *item)
1289     Geom::Matrix t_old(Geom::identity());
1290     gchar const *t_attr = SP_OBJECT_REPR(item)->attribute("transform");
1291     if (t_attr) {
1292         Geom::Matrix t;
1293         if (sp_svg_transform_read(t_attr, &t)) {
1294             t_old = t;
1295         }
1296     }
1298     return t_old;
1302 /**
1303  * Recursively scale stroke width in \a item and its children by \a expansion.
1304  */
1305 void
1306 sp_item_adjust_stroke_width_recursive(SPItem *item, double expansion)
1308     sp_item_adjust_stroke (item, expansion);
1310 // A clone's child is the ghost of its original - we must not touch it, skip recursion
1311     if (item && SP_IS_USE(item))
1312         return;
1314     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1315         if (SP_IS_ITEM(o))
1316             sp_item_adjust_stroke_width_recursive(SP_ITEM(o), expansion);
1317     }
1320 /**
1321  * Recursively adjust rx and ry of rects.
1322  */
1323 void
1324 sp_item_adjust_rects_recursive(SPItem *item, Geom::Matrix advertized_transform)
1326     if (SP_IS_RECT (item)) {
1327         sp_rect_compensate_rxry (SP_RECT(item), advertized_transform);
1328     }
1330     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1331         if (SP_IS_ITEM(o))
1332             sp_item_adjust_rects_recursive(SP_ITEM(o), advertized_transform);
1333     }
1336 /**
1337  * Recursively compensate pattern or gradient transform.
1338  */
1339 void
1340 sp_item_adjust_paint_recursive (SPItem *item, Geom::Matrix advertized_transform, Geom::Matrix t_ancestors, bool is_pattern)
1342 // _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors
1343 // _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform
1344 // By equating these two expressions we get t_paint_new = t_paint * paint_delta, where:
1345     Geom::Matrix t_item = sp_item_transform_repr (item);
1346     Geom::Matrix paint_delta = t_item * t_ancestors * advertized_transform * t_ancestors.inverse() * t_item.inverse();
1348 // Within text, we do not fork gradients, and so must not recurse to avoid double compensation;
1349 // also we do not recurse into clones, because a clone's child is the ghost of its original -
1350 // we must not touch it
1351     if (!(item && (SP_IS_TEXT(item) || SP_IS_USE(item)))) {
1352         for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1353             if (SP_IS_ITEM(o)) {
1354 // At the level of the transformed item, t_ancestors is identity;
1355 // below it, it is the accmmulated chain of transforms from this level to the top level
1356                 sp_item_adjust_paint_recursive (SP_ITEM(o), advertized_transform, t_item * t_ancestors, is_pattern);
1357             }
1358         }
1359     }
1361 // We recursed into children first, and are now adjusting this object second;
1362 // this is so that adjustments in a tree are done from leaves up to the root,
1363 // and paintservers on leaves inheriting their values from ancestors could adjust themselves properly
1364 // before ancestors themselves are adjusted, probably differently (bug 1286535)
1366     if (is_pattern)
1367         sp_item_adjust_pattern (item, paint_delta);
1368     else
1369         sp_item_adjust_gradient (item, paint_delta);
1373 void
1374 sp_item_adjust_livepatheffect (SPItem *item, Geom::Matrix const &postmul, bool set)
1376     if ( !SP_IS_LPE_ITEM(item) )
1377         return;
1379     SPLPEItem *lpeitem = SP_LPE_ITEM (item);
1380     if ( sp_lpe_item_has_path_effect(lpeitem) ) {
1381         PathEffectList effect_list =  sp_lpe_item_get_effect_list(lpeitem);
1382         for (PathEffectList::iterator it = effect_list.begin(); it != effect_list.end(); it++)
1383         {
1384             // If the path effect is used by 2 or more items, fork it
1385             // so that each object has its own independent copy of the effect
1386             LivePathEffectObject *lpeobj = (*it)->lpeobject;
1387             if (lpeobj) {
1388                 LivePathEffectObject *new_lpeobj = lpeobj->fork_private_if_necessary();
1389                 if (new_lpeobj != lpeobj) {
1390                     sp_lpe_item_replace_path_effect(lpeitem, lpeobj, new_lpeobj);
1391                 }
1393                 if (lpeobj->get_lpe()) {
1394                     Inkscape::LivePathEffect::Effect * effect = lpeobj->get_lpe();
1395                     effect->transform_multiply(postmul, set);
1396                 }
1397             }
1398         }
1399     }
1402 /**
1403  * Set a new transform on an object.
1404  *
1405  * Compensate for stroke scaling and gradient/pattern fill transform, if
1406  * necessary. Call the object's set_transform method if transforms are
1407  * stored optimized. Send _transformed_signal. Invoke _write method so that
1408  * the repr is updated with the new transform.
1409  */
1410 void
1411 sp_item_write_transform(SPItem *item, Inkscape::XML::Node *repr, Geom::Matrix const &transform, Geom::Matrix const *adv, bool compensate)
1413     g_return_if_fail(item != NULL);
1414     g_return_if_fail(SP_IS_ITEM(item));
1415     g_return_if_fail(repr != NULL);
1417     // calculate the relative transform, if not given by the adv attribute
1418     Geom::Matrix advertized_transform;
1419     if (adv != NULL) {
1420         advertized_transform = *adv;
1421     } else {
1422         advertized_transform = sp_item_transform_repr (item).inverse() * transform;
1423     }
1425     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1426     if (compensate) {
1428          // recursively compensate for stroke scaling, depending on user preference
1429         if (!prefs->getBool("/options/transform/stroke", true)) {
1430             double const expansion = 1. / advertized_transform.descrim();
1431             sp_item_adjust_stroke_width_recursive(item, expansion);
1432         }
1434         // recursively compensate rx/ry of a rect if requested
1435         if (!prefs->getBool("/options/transform/rectcorners", true)) {
1436             sp_item_adjust_rects_recursive(item, advertized_transform);
1437         }
1439         // recursively compensate pattern fill if it's not to be transformed
1440         if (!prefs->getBool("/options/transform/pattern", true)) {
1441             sp_item_adjust_paint_recursive (item, advertized_transform.inverse(), Geom::identity(), true);
1442         }
1443         /// \todo FIXME: add the same else branch as for gradients below, to convert patterns to userSpaceOnUse as well
1444         /// recursively compensate gradient fill if it's not to be transformed
1445         if (!prefs->getBool("/options/transform/gradient", true)) {
1446             sp_item_adjust_paint_recursive (item, advertized_transform.inverse(), Geom::identity(), false);
1447         } else {
1448             // this converts the gradient/pattern fill/stroke, if any, to userSpaceOnUse; we need to do
1449             // it here _before_ the new transform is set, so as to use the pre-transform bbox
1450             sp_item_adjust_paint_recursive (item, Geom::identity(), Geom::identity(), false);
1451         }
1453     } // endif(compensate)
1455     gint preserve = prefs->getBool("/options/preservetransform/value", 0);
1456     Geom::Matrix transform_attr (transform);
1457     if ( // run the object's set_transform (i.e. embed transform) only if:
1458          ((SPItemClass *) G_OBJECT_GET_CLASS(item))->set_transform && // it does have a set_transform method
1459              !preserve && // user did not chose to preserve all transforms
1460              !item->clip_ref->getObject() && // the object does not have a clippath
1461              !item->mask_ref->getObject() && // the object does not have a mask
1462          !(!transform.isTranslation() && SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->getFilter())
1463              // the object does not have a filter, or the transform is translation (which is supposed to not affect filters)
1464         ) {
1465         transform_attr = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->set_transform(item, transform);
1466     }
1467     sp_item_set_item_transform(item, transform_attr);
1469     // Note: updateRepr comes before emitting the transformed signal since
1470     // it causes clone SPUse's copy of the original object to brought up to
1471     // date with the original.  Otherwise, sp_use_bbox returns incorrect
1472     // values if called in code handling the transformed signal.
1473     SP_OBJECT(item)->updateRepr();
1475     // send the relative transform with a _transformed_signal
1476     item->_transformed_signal.emit(&advertized_transform, item);
1479 gint
1480 sp_item_event(SPItem *item, SPEvent *event)
1482     g_return_val_if_fail(item != NULL, FALSE);
1483     g_return_val_if_fail(SP_IS_ITEM(item), FALSE);
1484     g_return_val_if_fail(event != NULL, FALSE);
1486     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->event)
1487         return ((SPItemClass *) G_OBJECT_GET_CLASS(item))->event(item, event);
1489     return FALSE;
1492 /**
1493  * Sets item private transform (not propagated to repr), without compensating stroke widths,
1494  * gradients, patterns as sp_item_write_transform does.
1495  */
1496 void
1497 sp_item_set_item_transform(SPItem *item, Geom::Matrix const &transform)
1499     g_return_if_fail(item != NULL);
1500     g_return_if_fail(SP_IS_ITEM(item));
1502     if (!matrix_equalp(transform, item->transform, NR_EPSILON)) {
1503         item->transform = transform;
1504         /* The SP_OBJECT_USER_MODIFIED_FLAG_B is used to mark the fact that it's only a
1505            transformation.  It's apparently not used anywhere else. */
1506         item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_USER_MODIFIED_FLAG_B);
1507         sp_item_rm_unsatisfied_cns(*item);
1508     }
1511 void
1512 sp_item_convert_item_to_guides(SPItem *item) {
1513     g_return_if_fail(item != NULL);
1514     g_return_if_fail(SP_IS_ITEM(item));
1516     /* Use derived method if present ... */
1517     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->convert_to_guides) {
1518         (*((SPItemClass *) G_OBJECT_GET_CLASS(item))->convert_to_guides)(item);
1519         return;
1520     }
1522     /* .. otherwise simply place the guides around the item's bounding box */
1524     sp_item_convert_to_guides(item);
1528 /**
1529  * \pre \a ancestor really is an ancestor (\>=) of \a object, or NULL.
1530  *   ("Ancestor (\>=)" here includes as far as \a object itself.)
1531  */
1532 Geom::Matrix
1533 i2anc_affine(SPObject const *object, SPObject const *const ancestor) {
1534     Geom::Matrix ret(Geom::identity());
1535     g_return_val_if_fail(object != NULL, ret);
1537     /* stop at first non-renderable ancestor */
1538     while ( object != ancestor && SP_IS_ITEM(object) ) {
1539         if (SP_IS_ROOT(object)) {
1540             ret *= SP_ROOT(object)->c2p;
1541         } else {
1542             ret *= SP_ITEM(object)->transform;
1543         }
1544         object = SP_OBJECT_PARENT(object);
1545     }
1546     return ret;
1549 Geom::Matrix
1550 i2i_affine(SPObject const *src, SPObject const *dest) {
1551     g_return_val_if_fail(src != NULL && dest != NULL, Geom::identity());
1552     SPObject const *ancestor = src->nearestCommonAncestor(dest);
1553     return i2anc_affine(src, ancestor) * i2anc_affine(dest, ancestor).inverse();
1556 Geom::Matrix SPItem::getRelativeTransform(SPObject const *dest) const {
1557     return i2i_affine(this, dest);
1560 /**
1561  * Returns the accumulated transformation of the item and all its ancestors, including root's viewport.
1562  * \pre (item != NULL) and SP_IS_ITEM(item).
1563  */
1564 Geom::Matrix sp_item_i2doc_affine(SPItem const *item)
1566     return i2anc_affine(item, NULL);
1569 /**
1570  * Returns the transformation from item to desktop coords
1571  */
1572 Geom::Matrix sp_item_i2d_affine(SPItem const *item)
1574     g_assert(item != NULL);
1575     g_assert(SP_IS_ITEM(item));
1577     Geom::Matrix const ret( sp_item_i2doc_affine(item)
1578                           * Geom::Scale(1, -1)
1579                           * Geom::Translate(0, sp_document_height(SP_OBJECT_DOCUMENT(item))) );
1580     return ret;
1583 void sp_item_set_i2d_affine(SPItem *item, Geom::Matrix const &i2dt)
1585     g_return_if_fail( item != NULL );
1586     g_return_if_fail( SP_IS_ITEM(item) );
1588     Geom::Matrix dt2p; /* desktop to item parent transform */
1589     if (SP_OBJECT_PARENT(item)) {
1590         dt2p = sp_item_i2d_affine((SPItem *) SP_OBJECT_PARENT(item)).inverse();
1591     } else {
1592         dt2p = ( Geom::Translate(0, -sp_document_height(SP_OBJECT_DOCUMENT(item)))
1593                  * Geom::Scale(1, -1) );
1594     }
1596     Geom::Matrix const i2p( i2dt * dt2p );
1597     sp_item_set_item_transform(item, i2p);
1601 /**
1602  * should rather be named "sp_item_d2i_affine" to match "sp_item_i2d_affine" (or vice versa)
1603  */
1604 Geom::Matrix
1605 sp_item_dt2i_affine(SPItem const *item)
1607     /* fixme: Implement the right way (Lauris) */
1608     return sp_item_i2d_affine(item).inverse();
1611 /* Item views */
1613 static SPItemView *
1614 sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, NRArenaItem *arenaitem)
1616     SPItemView *new_view;
1618     g_assert(item != NULL);
1619     g_assert(SP_IS_ITEM(item));
1620     g_assert(arenaitem != NULL);
1621     g_assert(NR_IS_ARENA_ITEM(arenaitem));
1623     new_view = g_new(SPItemView, 1);
1625     new_view->next = list;
1626     new_view->flags = flags;
1627     new_view->key = key;
1628     new_view->arenaitem = arenaitem;
1630     return new_view;
1633 static SPItemView *
1634 sp_item_view_list_remove(SPItemView *list, SPItemView *view)
1636     if (view == list) {
1637         list = list->next;
1638     } else {
1639         SPItemView *prev;
1640         prev = list;
1641         while (prev->next != view) prev = prev->next;
1642         prev->next = view->next;
1643     }
1645     nr_arena_item_unref(view->arenaitem);
1646     g_free(view);
1648     return list;
1651 /**
1652  * Return the arenaitem corresponding to the given item in the display
1653  * with the given key
1654  */
1655 NRArenaItem *
1656 sp_item_get_arenaitem(SPItem *item, unsigned key)
1658     for ( SPItemView *iv = item->display ; iv ; iv = iv->next ) {
1659         if ( iv->key == key ) {
1660             return iv->arenaitem;
1661         }
1662     }
1664     return NULL;
1667 int
1668 sp_item_repr_compare_position(SPItem *first, SPItem *second)
1670     return sp_repr_compare_position(SP_OBJECT_REPR(first),
1671                                     SP_OBJECT_REPR(second));
1674 SPItem *
1675 sp_item_first_item_child (SPObject *obj)
1677     for ( SPObject *iter = sp_object_first_child(obj) ; iter ; iter = SP_OBJECT_NEXT(iter)) {
1678         if (SP_IS_ITEM (iter))
1679             return SP_ITEM (iter);
1680     }
1681     return NULL;
1684 void
1685 sp_item_convert_to_guides(SPItem *item) {
1686     SPDesktop *dt = inkscape_active_desktop();
1687     SPNamedView *nv = sp_desktop_namedview(dt);
1688     (void)nv;
1690     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1691     int prefs_bbox = prefs->getInt("/tools/bounding_box", 0);
1692     SPItem::BBoxType bbox_type = (prefs_bbox ==0)?
1693         SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
1695     Geom::OptRect bbox = sp_item_bbox_desktop(item, bbox_type);
1696     if (!bbox) {
1697         g_warning ("Cannot determine item's bounding box during conversion to guides.\n");
1698         return;
1699     }
1701     std::list<std::pair<Geom::Point, Geom::Point> > pts;
1703     Geom::Point A((*bbox).min());
1704     Geom::Point C((*bbox).max());
1705     Geom::Point B(A[Geom::X], C[Geom::Y]);
1706     Geom::Point D(C[Geom::X], A[Geom::Y]);
1708     pts.push_back(std::make_pair(A, B));
1709     pts.push_back(std::make_pair(B, C));
1710     pts.push_back(std::make_pair(C, D));
1711     pts.push_back(std::make_pair(D, A));
1713     sp_guide_pt_pairs_to_guides(dt, pts);
1716 /*
1717   Local Variables:
1718   mode:c++
1719   c-file-style:"stroustrup"
1720   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1721   indent-tabs-mode:nil
1722   fill-column:99
1723   End:
1724 */
1725 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :