Code

NR::Maybe => boost::optional
[inkscape.git] / src / sp-item.cpp
1 #define __SP_ITEM_C__
3 /** \file
4  * Base class for visual SVG elements
5  */
6 /*
7  * Authors:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   Johan Engelen <j.b.c.engelen@ewi.utwente.nl>
11  *
12  * Copyright (C) 2001-2006 authors
13  * Copyright (C) 2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 /** \class SPItem
19  *
20  * SPItem is an abstract base class for all graphic (visible) SVG nodes. It
21  * is a subclass of SPObject, with great deal of specific functionality.
22  */
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
29 #include "sp-item.h"
30 #include "svg/svg.h"
31 #include "print.h"
32 #include "display/nr-arena.h"
33 #include "display/nr-arena-item.h"
34 #include "attributes.h"
35 #include "document.h"
36 #include "uri.h"
37 #include "inkscape.h"
38 #include "desktop-handles.h"
40 #include "style.h"
41 #include <glibmm/i18n.h>
42 #include "sp-root.h"
43 #include "sp-clippath.h"
44 #include "sp-mask.h"
45 #include "sp-rect.h"
46 #include "sp-use.h"
47 #include "sp-text.h"
48 #include "sp-item-rm-unsatisfied-cns.h"
49 #include "sp-pattern.h"
50 #include "sp-switch.h"
51 #include "gradient-chemistry.h"
52 #include "prefs-utils.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"
59 #include "libnr/nr-matrix-fns.h"
60 #include "libnr/nr-matrix-scale-ops.h"
61 #include "libnr/nr-matrix-translate-ops.h"
62 #include "libnr/nr-scale-translate-ops.h"
63 #include "libnr/nr-translate-scale-ops.h"
64 #include "libnr/nr-convert2geom.h"
65 #include "algorithms/find-last-if.h"
66 #include "util/reverse-list.h"
67 #include <2geom/rect.h>
68 #include <2geom/transforms.h>
70 #include "xml/repr.h"
71 #include "extract-uri.h"
73 #include "live_effects/lpeobject.h"
74 #include "live_effects/effect.h"
75 #include "live_effects/lpeobject-reference.h"
77 #define noSP_ITEM_DEBUG_IDLE
79 static void sp_item_class_init(SPItemClass *klass);
80 static void sp_item_init(SPItem *item);
82 static void sp_item_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
83 static void sp_item_release(SPObject *object);
84 static void sp_item_set(SPObject *object, unsigned key, gchar const *value);
85 static void sp_item_update(SPObject *object, SPCtx *ctx, guint flags);
86 static Inkscape::XML::Node *sp_item_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
88 static gchar *sp_item_private_description(SPItem *item);
89 static void sp_item_private_snappoints(SPItem const *item, SnapPointsIter p);
91 static SPItemView *sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, NRArenaItem *arenaitem);
92 static SPItemView *sp_item_view_list_remove(SPItemView *list, SPItemView *view);
94 static SPObjectClass *parent_class;
96 static void clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item);
97 static void mask_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item);
99 /**
100  * Registers SPItem class and returns its type number.
101  */
102 GType
103 sp_item_get_type(void)
105     static GType type = 0;
106     if (!type) {
107         GTypeInfo info = {
108             sizeof(SPItemClass),
109             NULL, NULL,
110             (GClassInitFunc) sp_item_class_init,
111             NULL, NULL,
112             sizeof(SPItem),
113             16,
114             (GInstanceInitFunc) sp_item_init,
115             NULL,   /* value_table */
116         };
117         type = g_type_register_static(SP_TYPE_OBJECT, "SPItem", &info, (GTypeFlags)0);
118     }
119     return type;
122 /**
123  * SPItem vtable initialization.
124  */
125 static void
126 sp_item_class_init(SPItemClass *klass)
128     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
130     parent_class = (SPObjectClass *)g_type_class_ref(SP_TYPE_OBJECT);
132     sp_object_class->build = sp_item_build;
133     sp_object_class->release = sp_item_release;
134     sp_object_class->set = sp_item_set;
135     sp_object_class->update = sp_item_update;
136     sp_object_class->write = sp_item_write;
138     klass->description = sp_item_private_description;
139     klass->snappoints = sp_item_private_snappoints;
142 /**
143  * Callback for SPItem object initialization.
144  */
145 static void
146 sp_item_init(SPItem *item)
148     item->init();
151 void SPItem::init() {
152     this->sensitive = TRUE;
154     this->transform_center_x = 0;
155     this->transform_center_y = 0;
157     this->_is_evaluated = true;
158     this->_evaluated_status = StatusUnknown;
160     this->transform = NR::identity();
162     this->display = NULL;
164     this->clip_ref = new SPClipPathReference(this);
165                 sigc::signal<void, SPObject *, SPObject *> cs1=this->clip_ref->changedSignal();
166                 sigc::slot2<void,SPObject*, SPObject *> sl1=sigc::bind(sigc::ptr_fun(clip_ref_changed), this);
167     _clip_ref_connection = cs1.connect(sl1);
169     this->mask_ref = new SPMaskReference(this);
170                 sigc::signal<void, SPObject *, SPObject *> cs2=this->mask_ref->changedSignal();
171                 sigc::slot2<void,SPObject*, SPObject *> sl2=sigc::bind(sigc::ptr_fun(mask_ref_changed), this);
172     _mask_ref_connection = cs2.connect(sl2);
174     this->avoidRef = new SPAvoidRef(this);
176     new (&this->_transformed_signal) sigc::signal<void, NR::Matrix const *, SPItem *>();
179 bool SPItem::isVisibleAndUnlocked() const {
180     return (!isHidden() && !isLocked());
183 bool SPItem::isVisibleAndUnlocked(unsigned display_key) const {
184     return (!isHidden(display_key) && !isLocked());
187 bool SPItem::isLocked() const {
188     for (SPObject *o = SP_OBJECT(this); o != NULL; o = SP_OBJECT_PARENT(o)) {
189         if (SP_IS_ITEM(o) && !(SP_ITEM(o)->sensitive))
190             return true;
191     }
192     return false;
195 void SPItem::setLocked(bool locked) {
196     SP_OBJECT_REPR(this)->setAttribute("sodipodi:insensitive",
197                      ( locked ? "1" : NULL ));
198     updateRepr();
201 bool SPItem::isHidden() const {
202     if (!isEvaluated())
203         return true;
204     return style->display.computed == SP_CSS_DISPLAY_NONE;
207 void SPItem::setHidden(bool hide) {
208     style->display.set = TRUE;
209     style->display.value = ( hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE );
210     style->display.computed = style->display.value;
211     style->display.inherit = FALSE;
212     updateRepr();
215 bool SPItem::isHidden(unsigned display_key) const {
216     if (!isEvaluated())
217         return true;
218     for ( SPItemView *view(display) ; view ; view = view->next ) {
219         if ( view->key == display_key ) {
220             g_assert(view->arenaitem != NULL);
221             for ( NRArenaItem *arenaitem = view->arenaitem ;
222                   arenaitem ; arenaitem = arenaitem->parent )
223             {
224                 if (!arenaitem->visible) {
225                     return true;
226                 }
227             }
228             return false;
229         }
230     }
231     return true;
234 void SPItem::setEvaluated(bool evaluated) {
235     _is_evaluated = evaluated;
236     _evaluated_status = StatusSet;
239 void SPItem::resetEvaluated() {
240     if ( StatusCalculated == _evaluated_status ) {
241         _evaluated_status = StatusUnknown;
242         bool oldValue = _is_evaluated;
243         if ( oldValue != isEvaluated() ) {
244             requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
245         }
246     } if ( StatusSet == _evaluated_status ) {
247         SPObject const *const parent = SP_OBJECT_PARENT(this);
248         if (SP_IS_SWITCH(parent)) {
249             SP_SWITCH(parent)->resetChildEvaluated();
250         }
251     }
254 bool SPItem::isEvaluated() const {
255     if ( StatusUnknown == _evaluated_status ) {
256         _is_evaluated = sp_item_evaluate(this);
257         _evaluated_status = StatusCalculated;
258     }
259     return _is_evaluated;
262 /**
263  * Returns something suitable for the `Hide' checkbox in the Object Properties dialog box.
264  *  Corresponds to setExplicitlyHidden.
265  */
266 bool
267 SPItem::isExplicitlyHidden() const
269     return (this->style->display.set
270             && this->style->display.value == SP_CSS_DISPLAY_NONE);
273 /**
274  * Sets the display CSS property to `hidden' if \a val is true,
275  * otherwise makes it unset
276  */
277 void
278 SPItem::setExplicitlyHidden(bool const val) {
279     this->style->display.set = val;
280     this->style->display.value = ( val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE );
281     this->style->display.computed = this->style->display.value;
282     this->updateRepr();
285 /**
286  * Sets the transform_center_x and transform_center_y properties to retain the rotation centre
287  */
288 void
289 SPItem::setCenter(NR::Point object_centre) {
290     boost::optional<NR::Rect> bbox = getBounds(from_2geom(sp_item_i2d_affine(this)));
291     if (bbox) {
292         transform_center_x = object_centre[NR::X] - bbox->midpoint()[NR::X];
293         if (fabs(transform_center_x) < 1e-5) // rounding error
294             transform_center_x = 0;
295         transform_center_y = object_centre[NR::Y] - bbox->midpoint()[NR::Y];
296         if (fabs(transform_center_y) < 1e-5) // rounding error
297             transform_center_y = 0;
298     }
301 void
302 SPItem::unsetCenter() {
303     transform_center_x = 0;
304     transform_center_y = 0;
307 bool SPItem::isCenterSet() {
308     return (transform_center_x != 0 || transform_center_y != 0);
311 NR::Point SPItem::getCenter() const {
312     boost::optional<NR::Rect> bbox = getBounds(from_2geom(sp_item_i2d_affine(this)));
313     if (bbox) {
314         return bbox->midpoint() + NR::Point (this->transform_center_x, this->transform_center_y);
315     } else {
316         return NR::Point (0, 0); // something's wrong!
317     }
321 namespace {
323 bool is_item(SPObject const &object) {
324     return SP_IS_ITEM(&object);
329 void SPItem::raiseToTop() {
330     using Inkscape::Algorithms::find_last_if;
332     SPObject *topmost=find_last_if<SPObject::SiblingIterator>(
333         SP_OBJECT_NEXT(this), NULL, &is_item
334     );
335     if (topmost) {
336         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
337         sp_repr_parent(repr)->changeOrder(repr, SP_OBJECT_REPR(topmost));
338     }
341 void SPItem::raiseOne() {
342     SPObject *next_higher=std::find_if<SPObject::SiblingIterator>(
343         SP_OBJECT_NEXT(this), NULL, &is_item
344     );
345     if (next_higher) {
346         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
347         Inkscape::XML::Node *ref=SP_OBJECT_REPR(next_higher);
348         sp_repr_parent(repr)->changeOrder(repr, ref);
349     }
352 void SPItem::lowerOne() {
353     using Inkscape::Util::MutableList;
354     using Inkscape::Util::reverse_list;
356     MutableList<SPObject &> next_lower=std::find_if(
357         reverse_list<SPObject::SiblingIterator>(
358             SP_OBJECT_PARENT(this)->firstChild(), this
359         ),
360         MutableList<SPObject &>(),
361         &is_item
362     );
363     if (next_lower) {
364         ++next_lower;
365         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
366         Inkscape::XML::Node *ref=( next_lower ? SP_OBJECT_REPR(&*next_lower) : NULL );
367         sp_repr_parent(repr)->changeOrder(repr, ref);
368     }
371 void SPItem::lowerToBottom() {
372     using Inkscape::Algorithms::find_last_if;
373     using Inkscape::Util::MutableList;
374     using Inkscape::Util::reverse_list;
376     MutableList<SPObject &> bottom=find_last_if(
377         reverse_list<SPObject::SiblingIterator>(
378             SP_OBJECT_PARENT(this)->firstChild(), this
379         ),
380         MutableList<SPObject &>(),
381         &is_item
382     );
383     if (bottom) {
384         ++bottom;
385         Inkscape::XML::Node *repr=SP_OBJECT_REPR(this);
386         Inkscape::XML::Node *ref=( bottom ? SP_OBJECT_REPR(&*bottom) : NULL );
387         sp_repr_parent(repr)->changeOrder(repr, ref);
388     }
391 static void
392 sp_item_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
394     sp_object_read_attr(object, "style");
395     sp_object_read_attr(object, "transform");
396     sp_object_read_attr(object, "clip-path");
397     sp_object_read_attr(object, "mask");
398     sp_object_read_attr(object, "sodipodi:insensitive");
399     sp_object_read_attr(object, "sodipodi:nonprintable");
400     sp_object_read_attr(object, "inkscape:transform-center-x");
401     sp_object_read_attr(object, "inkscape:transform-center-y");
402     sp_object_read_attr(object, "inkscape:connector-avoid");
404     if (((SPObjectClass *) (parent_class))->build) {
405         (* ((SPObjectClass *) (parent_class))->build)(object, document, repr);
406     }
409 static void
410 sp_item_release(SPObject *object)
412     SPItem *item = (SPItem *) object;
414     item->_clip_ref_connection.disconnect();
415     item->_mask_ref_connection.disconnect();
417     // Note: do this here before the clip_ref is deleted, since calling
418     // sp_document_ensure_up_to_date for triggered routing may reference
419     // the deleted clip_ref.
420     if (item->avoidRef) {
421         delete item->avoidRef;
422         item->avoidRef = NULL;
423     }
425     if (item->clip_ref) {
426         item->clip_ref->detach();
427         delete item->clip_ref;
428         item->clip_ref = NULL;
429     }
431     if (item->mask_ref) {
432         item->mask_ref->detach();
433         delete item->mask_ref;
434         item->mask_ref = NULL;
435     }
437     if (((SPObjectClass *) (parent_class))->release) {
438         ((SPObjectClass *) parent_class)->release(object);
439     }
441     while (item->display) {
442         nr_arena_item_unparent(item->display->arenaitem);
443         item->display = sp_item_view_list_remove(item->display, item->display);
444     }
446     item->_transformed_signal.~signal();
449 static void
450 sp_item_set(SPObject *object, unsigned key, gchar const *value)
452     SPItem *item = (SPItem *) object;
454     switch (key) {
455         case SP_ATTR_TRANSFORM: {
456             NR::Matrix t;
457             if (value && sp_svg_transform_read(value, &t)) {
458                 sp_item_set_item_transform(item, t);
459             } else {
460                 sp_item_set_item_transform(item, NR::identity());
461             }
462             break;
463         }
464         case SP_PROP_CLIP_PATH: {
465             gchar *uri = extract_uri(value);
466             if (uri) {
467                 try {
468                     item->clip_ref->attach(Inkscape::URI(uri));
469                 } catch (Inkscape::BadURIException &e) {
470                     g_warning("%s", e.what());
471                     item->clip_ref->detach();
472                 }
473                 g_free(uri);
474             } else {
475                 item->clip_ref->detach();
476             }
478             break;
479         }
480         case SP_PROP_MASK: {
481             gchar *uri = extract_uri(value);
482             if (uri) {
483                 try {
484                     item->mask_ref->attach(Inkscape::URI(uri));
485                 } catch (Inkscape::BadURIException &e) {
486                     g_warning("%s", e.what());
487                     item->mask_ref->detach();
488                 }
489                 g_free(uri);
490             } else {
491                 item->mask_ref->detach();
492             }
494             break;
495         }
496         case SP_ATTR_SODIPODI_INSENSITIVE:
497             item->sensitive = !value;
498             for (SPItemView *v = item->display; v != NULL; v = v->next) {
499                 nr_arena_item_set_sensitive(v->arenaitem, item->sensitive);
500             }
501             break;
502         case SP_ATTR_CONNECTOR_AVOID:
503             item->avoidRef->setAvoid(value);
504             break;
505         case SP_ATTR_TRANSFORM_CENTER_X:
506             if (value) {
507                 item->transform_center_x = g_strtod(value, NULL);
508             } else {
509                 item->transform_center_x = 0;
510             }
511             object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
512             break;
513         case SP_ATTR_TRANSFORM_CENTER_Y:
514             if (value) {
515                 item->transform_center_y = g_strtod(value, NULL);
516             } else {
517                 item->transform_center_y = 0;
518             }
519             object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
520             break;
521         case SP_PROP_SYSTEM_LANGUAGE:
522         case SP_PROP_REQUIRED_FEATURES:
523         case SP_PROP_REQUIRED_EXTENSIONS:
524             {
525                 item->resetEvaluated();
526                 // pass to default handler
527             }
528         default:
529             if (SP_ATTRIBUTE_IS_CSS(key)) {
530                 sp_style_read_from_object(object->style, object);
531                 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
532             } else {
533                 if (((SPObjectClass *) (parent_class))->set) {
534                     (* ((SPObjectClass *) (parent_class))->set)(object, key, value);
535                 }
536             }
537             break;
538     }
541 static void
542 clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item)
544     if (old_clip) {
545         SPItemView *v;
546         /* Hide clippath */
547         for (v = item->display; v != NULL; v = v->next) {
548             sp_clippath_hide(SP_CLIPPATH(old_clip), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
549             nr_arena_item_set_clip(v->arenaitem, NULL);
550         }
551     }
552     if (SP_IS_CLIPPATH(clip)) {
553         NRRect bbox;
554         sp_item_invoke_bbox(item, &bbox, NR::identity(), TRUE);
555         for (SPItemView *v = item->display; v != NULL; v = v->next) {
556             if (!v->arenaitem->key) {
557                 NR_ARENA_ITEM_SET_KEY(v->arenaitem, sp_item_display_key_new(3));
558             }
559             NRArenaItem *ai = sp_clippath_show(SP_CLIPPATH(clip),
560                                                NR_ARENA_ITEM_ARENA(v->arenaitem),
561                                                NR_ARENA_ITEM_GET_KEY(v->arenaitem));
562             nr_arena_item_set_clip(v->arenaitem, ai);
563             nr_arena_item_unref(ai);
564             sp_clippath_set_bbox(SP_CLIPPATH(clip), NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
565             SP_OBJECT(clip)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
566         }
567     }
570 static void
571 mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item)
573     if (old_mask) {
574         /* Hide mask */
575         for (SPItemView *v = item->display; v != NULL; v = v->next) {
576             sp_mask_hide(SP_MASK(old_mask), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
577             nr_arena_item_set_mask(v->arenaitem, NULL);
578         }
579     }
580     if (SP_IS_MASK(mask)) {
581         NRRect bbox;
582         sp_item_invoke_bbox(item, &bbox, NR::identity(), TRUE);
583         for (SPItemView *v = item->display; v != NULL; v = v->next) {
584             if (!v->arenaitem->key) {
585                 NR_ARENA_ITEM_SET_KEY(v->arenaitem, sp_item_display_key_new(3));
586             }
587             NRArenaItem *ai = sp_mask_show(SP_MASK(mask),
588                                            NR_ARENA_ITEM_ARENA(v->arenaitem),
589                                            NR_ARENA_ITEM_GET_KEY(v->arenaitem));
590             nr_arena_item_set_mask(v->arenaitem, ai);
591             nr_arena_item_unref(ai);
592             sp_mask_set_bbox(SP_MASK(mask), NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
593             SP_OBJECT(mask)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
594         }
595     }
598 static void
599 sp_item_update(SPObject *object, SPCtx *ctx, guint flags)
601     SPItem *item = SP_ITEM(object);
603     if (((SPObjectClass *) (parent_class))->update)
604         (* ((SPObjectClass *) (parent_class))->update)(object, ctx, flags);
606     if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) {
607         if (flags & SP_OBJECT_MODIFIED_FLAG) {
608             for (SPItemView *v = item->display; v != NULL; v = v->next) {
609                 nr_arena_item_set_transform(v->arenaitem, item->transform);
610             }
611         }
613         SPClipPath *clip_path = item->clip_ref ? item->clip_ref->getObject() : NULL;
614         SPMask *mask = item->mask_ref ? item->mask_ref->getObject() : NULL;
616         if ( clip_path || mask ) {
617             NRRect bbox;
618             sp_item_invoke_bbox(item, &bbox, NR::identity(), TRUE);
619             if (clip_path) {
620                 for (SPItemView *v = item->display; v != NULL; v = v->next) {
621                     sp_clippath_set_bbox(clip_path, NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
622                 }
623             }
624             if (mask) {
625                 for (SPItemView *v = item->display; v != NULL; v = v->next) {
626                     sp_mask_set_bbox(mask, NR_ARENA_ITEM_GET_KEY(v->arenaitem), &bbox);
627                 }
628             }
629         }
631         if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
632             for (SPItemView *v = item->display; v != NULL; v = v->next) {
633                 nr_arena_item_set_opacity(v->arenaitem, SP_SCALE24_TO_FLOAT(object->style->opacity.value));
634                 nr_arena_item_set_visible(v->arenaitem, !item->isHidden());
635             }
636         }
637     }
639     /* Update bounding box data used by filters */
640     if (item->style->filter.set && item->display) {
641         NRRect item_bbox;
642         sp_item_invoke_bbox(item, &item_bbox, NR::identity(), TRUE, SPItem::GEOMETRIC_BBOX);
643         boost::optional<NR::Rect> i_bbox = item_bbox;
645         SPItemView *itemview = item->display;
646         do {
647             if (itemview->arenaitem)
648                 nr_arena_item_set_item_bbox(itemview->arenaitem, i_bbox);
649         } while ( (itemview = itemview->next) );
650     }
652     // Update libavoid with item geometry (for connector routing).
653     if (item->avoidRef)
654         item->avoidRef->handleSettingChange();
657 static Inkscape::XML::Node *
658 sp_item_write(SPObject *const object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
660     SPItem *item = SP_ITEM(object);
662     gchar *c = sp_svg_transform_write(item->transform);
663     repr->setAttribute("transform", c);
664     g_free(c);
666     if (flags & SP_OBJECT_WRITE_EXT) {
667         repr->setAttribute("sodipodi:insensitive", ( item->sensitive ? NULL : "true" ));
668         if (item->transform_center_x != 0)
669             sp_repr_set_svg_double (repr, "inkscape:transform-center-x", item->transform_center_x);
670         else
671             repr->setAttribute ("inkscape:transform-center-x", NULL);
672         if (item->transform_center_y != 0)
673             sp_repr_set_svg_double (repr, "inkscape:transform-center-y", item->transform_center_y);
674         else
675             repr->setAttribute ("inkscape:transform-center-y", NULL);
676     }
678     if (item->clip_ref->getObject()) {
679         const gchar *value = g_strdup_printf ("url(%s)", item->clip_ref->getURI()->toString());
680         repr->setAttribute ("clip-path", value);
681         g_free ((void *) value);
682     }
683     if (item->mask_ref->getObject()) {
684         const gchar *value = g_strdup_printf ("url(%s)", item->mask_ref->getURI()->toString());
685         repr->setAttribute ("mask", value);
686         g_free ((void *) value);
687     }
689     if (((SPObjectClass *) (parent_class))->write) {
690         ((SPObjectClass *) (parent_class))->write(object, xml_doc, repr, flags);
691     }
693     return repr;
696 boost::optional<NR::Rect> SPItem::getBounds(NR::Matrix const &transform,
697                                       SPItem::BBoxType type,
698                                       unsigned int /*dkey*/) const
700     boost::optional<NR::Rect> r;
701     sp_item_invoke_bbox_full(this, &r, transform, type, TRUE);
702     return r;
705 /*
706  * If the item is empty, or has an empty boundingbox for another reason, this method will
707  * return an empty rectangle. I.e. "getBounds(...).isEmpty() == true".
708  */
709 Geom::Rect
710 SPItem::getBounds(Geom::Matrix const &transform, SPItem::BBoxType type, unsigned int /*dkey*/)
711 const
713     boost::optional<NR::Rect> r;
714     sp_item_invoke_bbox_full(this, &r, from_2geom(transform), type, TRUE);
715     if (r)
716         return to_2geom(*r);
717     else
718         return Geom::Rect(); // return empty rectangle
721 void
722 sp_item_invoke_bbox(SPItem const *item, boost::optional<NR::Rect> *bbox, NR::Matrix const &transform, unsigned const clear, SPItem::BBoxType type)
724     sp_item_invoke_bbox_full(item, bbox, transform, type, clear);
727 // DEPRECATED to phase out the use of NRRect in favor of boost::optional<NR::Rect>
728 void
729 sp_item_invoke_bbox(SPItem const *item, NRRect *bbox, NR::Matrix const &transform, unsigned const clear, SPItem::BBoxType type)
731     sp_item_invoke_bbox_full(item, bbox, transform, type, clear);
734 /** Calls \a item's subclass' bounding box method; clips it by the bbox of clippath, if any; and
735  * unions the resulting bbox with \a bbox. If \a clear is true, empties \a bbox first. Passes the
736  * transform and the flags to the actual bbox methods. Note that many of subclasses (e.g. groups,
737  * clones), in turn, call this function in their bbox methods. */
738 void
739 sp_item_invoke_bbox_full(SPItem const *item, boost::optional<NR::Rect> *bbox, NR::Matrix const &transform, unsigned const flags, unsigned const clear)
741     g_assert(item != NULL);
742     g_assert(SP_IS_ITEM(item));
743     g_assert(bbox != NULL);
745     if (clear) {
746         *bbox = boost::optional<NR::Rect>();
747     }
749     // TODO: replace NRRect by NR::Rect, for all SPItemClasses, and for SP_CLIPPATH
751     NRRect temp_bbox;
752     temp_bbox.x0 = temp_bbox.y0 = NR_HUGE;
753     temp_bbox.x1 = temp_bbox.y1 = -NR_HUGE;
755     // call the subclass method
756     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox) {
757         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox(item, &temp_bbox, transform, flags);
758     }
760     // unless this is geometric bbox, extend by filter area and crop the bbox by clip path, if any
761     if ((SPItem::BBoxType) flags != SPItem::GEOMETRIC_BBOX) {
762         if (SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->filter.href) {
763             SPObject *filter = SP_OBJECT_STYLE(item)->getFilter();
764             if (filter && SP_IS_FILTER(filter)) {
765                 // default filer area per the SVG spec:
766                 double x = -0.1;
767                 double y = -0.1;
768                 double w = 1.2;
769                 double h = 1.2;
771                 // if area is explicitly set, override:
772                 if (SP_FILTER(filter)->x._set)
773                     x = SP_FILTER(filter)->x.computed;
774                 if (SP_FILTER(filter)->y._set)
775                     y = SP_FILTER(filter)->y.computed;
776                 if (SP_FILTER(filter)->width._set)
777                     w = SP_FILTER(filter)->width.computed;
778                 if (SP_FILTER(filter)->height._set) 
779                     h = SP_FILTER(filter)->height.computed;
781                 double dx0 = 0;
782                 double dx1 = 0;
783                 double dy0 = 0;
784                 double dy1 = 0;
785                 if (filter_is_single_gaussian_blur(SP_FILTER(filter))) {
786                     // if this is a single blur, use 2.4*radius 
787                     // which may be smaller than the default area;
788                     // see set_filter_area for why it's 2.4
789                     double r = get_single_gaussian_blur_radius (SP_FILTER(filter));
790                     dx0 = -2.4 * r;
791                     dx1 = 2.4 * r;
792                     dy0 = -2.4 * r;
793                     dy1 = 2.4 * r;
794                 } else {
795                     // otherwise, calculate expansion from relative to absolute units:
796                     dx0 = x * (temp_bbox.x1 - temp_bbox.x0);
797                     dx1 = (w + x - 1) * (temp_bbox.x1 - temp_bbox.x0);
798                     dy0 = y * (temp_bbox.y1 - temp_bbox.y0);
799                     dy1 = (h + y - 1) * (temp_bbox.y1 - temp_bbox.y0);
800                 }
802                 // transform the expansions by the item's transform:
803                 NR::Matrix i2d = from_2geom(sp_item_i2d_affine (item));
804                 dx0 *= NR::expansionX(i2d);
805                 dx1 *= NR::expansionX(i2d);
806                 dy0 *= NR::expansionY(i2d);
807                 dy1 *= NR::expansionY(i2d);
809                 // expand the bbox
810                 temp_bbox.x0 += dx0;
811                 temp_bbox.x1 += dx1;
812                 temp_bbox.y0 += dy0;
813                 temp_bbox.y1 += dy1;
814             }
815         }
816         if (item->clip_ref->getObject()) {
817             NRRect b;
818             sp_clippath_get_bbox(SP_CLIPPATH(item->clip_ref->getObject()), &b, transform, flags);
819             nr_rect_d_intersect (&temp_bbox, &temp_bbox, &b);
820         }
821     }
823     if (temp_bbox.x0 > temp_bbox.x1 || temp_bbox.y0 > temp_bbox.y1) {
824         // Either the bbox hasn't been touched by the SPItemClass' bbox method 
825         // (it still has its initial values, see above: x0 = y0 = NR_HUGE and x1 = y1 = -NR_HUGE)
826         // or it has explicitely been set to be like this (e.g. in sp_shape_bbox)
827         
828         // When x0 > x1 or y0 > y1, the bbox is considered to be "nothing", although it has not been 
829         // explicitely defined this way for NRRects (as opposed to boost::optional<NR::Rect>)
830         // So union bbox with nothing = do nothing, just return
831         return;
832     }
834     // Do not use temp_bbox.upgrade() here, because it uses a test that returns an empty boost::optional<NR::Rect>()
835     // for any rectangle with zero area. The geometrical bbox of for example a vertical line
836     // would therefore be translated into empty boost::optional<NR::Rect>() (see bug https://bugs.launchpad.net/inkscape/+bug/168684)
837     boost::optional<NR::Rect> temp_bbox_new = NR::Rect(NR::Point(temp_bbox.x0, temp_bbox.y0), NR::Point(temp_bbox.x1, temp_bbox.y1));
839     *bbox = NR::union_bounds(*bbox, temp_bbox_new);
842 // DEPRECATED to phase out the use of NRRect in favor of boost::optional<NR::Rect>
843 /** Calls \a item's subclass' bounding box method; clips it by the bbox of clippath, if any; and
844  * unions the resulting bbox with \a bbox. If \a clear is true, empties \a bbox first. Passes the
845  * transform and the flags to the actual bbox methods. Note that many of subclasses (e.g. groups,
846  * clones), in turn, call this function in their bbox methods. */
847 void
848 sp_item_invoke_bbox_full(SPItem const *item, NRRect *bbox, NR::Matrix const &transform, unsigned const flags, unsigned const clear)
850     g_assert(item != NULL);
851     g_assert(SP_IS_ITEM(item));
852     g_assert(bbox != NULL);
854     if (clear) {
855         bbox->x0 = bbox->y0 = 1e18;
856         bbox->x1 = bbox->y1 = -1e18;
857     }
859     NRRect this_bbox;
860     this_bbox.x0 = this_bbox.y0 = 1e18;
861     this_bbox.x1 = this_bbox.y1 = -1e18;
863     // call the subclass method
864     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox) {
865         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->bbox(item, &this_bbox, transform, flags);
866     }
868     // unless this is geometric bbox, crop the bbox by clip path, if any
869     if ((SPItem::BBoxType) flags != SPItem::GEOMETRIC_BBOX && item->clip_ref->getObject()) {
870         NRRect b;
871         sp_clippath_get_bbox(SP_CLIPPATH(item->clip_ref->getObject()), &b, transform, flags);
872         nr_rect_d_intersect (&this_bbox, &this_bbox, &b);
873     }
875     // if non-empty (with some tolerance - ?) union this_bbox with the bbox we've got passed
876     if ( fabs(this_bbox.x1-this_bbox.x0) > -0.00001 && fabs(this_bbox.y1-this_bbox.y0) > -0.00001 ) {
877         nr_rect_d_union (bbox, bbox, &this_bbox);
878     }
881 unsigned sp_item_pos_in_parent(SPItem *item)
883     g_assert(item != NULL);
884     g_assert(SP_IS_ITEM(item));
886     SPObject *parent = SP_OBJECT_PARENT(item);
887     g_assert(parent != NULL);
888     g_assert(SP_IS_OBJECT(parent));
890     SPObject *object = SP_OBJECT(item);
892     unsigned pos=0;
893     for ( SPObject *iter = sp_object_first_child(parent) ; iter ; iter = SP_OBJECT_NEXT(iter)) {
894         if ( iter == object ) {
895             return pos;
896         }
897         if (SP_IS_ITEM(iter)) {
898             pos++;
899         }
900     }
902     g_assert_not_reached();
903     return 0;
906 void
907 sp_item_bbox_desktop(SPItem *item, NRRect *bbox, SPItem::BBoxType type)
909     g_assert(item != NULL);
910     g_assert(SP_IS_ITEM(item));
911     g_assert(bbox != NULL);
913     sp_item_invoke_bbox(item, bbox, from_2geom(sp_item_i2d_affine(item)), TRUE, type);
916 boost::optional<NR::Rect> sp_item_bbox_desktop(SPItem *item, SPItem::BBoxType type)
918     boost::optional<NR::Rect> rect = boost::optional<NR::Rect>();
919     sp_item_invoke_bbox(item, &rect, from_2geom(sp_item_i2d_affine(item)), TRUE, type);
920     return rect;
923 static void sp_item_private_snappoints(SPItem const *item, SnapPointsIter p)
925     boost::optional<NR::Rect> bbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
926     /* Just the corners of the bounding box suffices given that we don't yet
927        support angled guide lines. */
929     if (bbox) {
930         NR::Point p1, p2;
931         p1 = bbox->min();
932         p2 = bbox->max();
933         *p = p1;
934         *p = NR::Point(p1[NR::X], p2[NR::Y]);
935         *p = p2;
936         *p = NR::Point(p1[NR::Y], p2[NR::X]);
937     }
940 void sp_item_snappoints(SPItem const *item, bool includeItemCenter, SnapPointsIter p)
942         g_assert (item != NULL);
943     g_assert (SP_IS_ITEM(item));
945     // Get the snappoints of the item
946     SPItemClass const &item_class = *(SPItemClass const *) G_OBJECT_GET_CLASS(item);
947     if (item_class.snappoints) {
948         item_class.snappoints(item, p);
949     }
951     // Get the snappoints at the item's center
952     if (includeItemCenter) {
953         *p = item->getCenter();
954     }    
955     
956     // Get the snappoints of clipping paths and mask, if any
957     std::list<SPObject const *> clips_and_masks;
958     
959     clips_and_masks.push_back(SP_OBJECT(item->clip_ref->getObject()));
960     clips_and_masks.push_back(SP_OBJECT(item->mask_ref->getObject()));
961     
962     for (std::list<SPObject const *>::const_iterator o = clips_and_masks.begin(); o != clips_and_masks.end(); o++) {
963         if (*o) {
964                 // obj is a group object, the children are the actual clippers
965                 for (SPObject *child = (*o)->children ; child ; child = child->next) {
966                     if (SP_IS_ITEM(child)) {
967                         std::vector<NR::Point> p_clip_or_mask;                      
968                         // Please note the recursive call here!
969                         sp_item_snappoints(SP_ITEM(child), includeItemCenter, SnapPointsIter(p_clip_or_mask));
970                         // Take into account the transformation of the item being clipped or masked
971                         for (std::vector<NR::Point>::const_iterator p_orig = p_clip_or_mask.begin(); p_orig != p_clip_or_mask.end(); p_orig++) {
972                         // All snappoints are in desktop coordinates, but the item's transformation is
973                                 // in document coordinates. Hence the awkward construction below
974                                 *p = (*p_orig) * from_2geom(matrix_to_desktop (matrix_from_desktop (to_2geom(item->transform), item), item));
975                     }
976                     }
977                 }
978         }
979     }
982 void
983 sp_item_invoke_print(SPItem *item, SPPrintContext *ctx)
985     if (!item->isHidden()) {
986         if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->print) {
987             if (!item->transform.test_identity()
988                 || SP_OBJECT_STYLE(item)->opacity.value != SP_SCALE24_MAX)
989             {
990                 sp_print_bind(ctx, item->transform, SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value));
991                 ((SPItemClass *) G_OBJECT_GET_CLASS(item))->print(item, ctx);
992                 sp_print_release(ctx);
993             } else {
994                 ((SPItemClass *) G_OBJECT_GET_CLASS(item))->print(item, ctx);
995             }
996         }
997     }
1000 static gchar *
1001 sp_item_private_description(SPItem */*item*/)
1003     return g_strdup(_("Object"));
1006 /**
1007  * Returns a string suitable for status bar, formatted in pango markup language.
1008  *
1009  * Must be freed by caller.
1010  */
1011 gchar *
1012 sp_item_description(SPItem *item)
1014     g_assert(item != NULL);
1015     g_assert(SP_IS_ITEM(item));
1017     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->description) {
1018         gchar *s = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->description(item);
1019         if (s && item->clip_ref->getObject()) {
1020             gchar *snew = g_strdup_printf (_("%s; <i>clipped</i>"), s);
1021             g_free (s);
1022             s = snew;
1023         }
1024         if (s && item->mask_ref->getObject()) {
1025             gchar *snew = g_strdup_printf (_("%s; <i>masked</i>"), s);
1026             g_free (s);
1027             s = snew;
1028         }
1029         if (SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->filter.href) {
1030             gchar *snew = g_strdup_printf (_("%s; <i>filtered</i>"), s);
1031             g_free (s);
1032             s = snew;
1033         }
1034         return s;
1035     }
1037     g_assert_not_reached();
1038     return NULL;
1041 /**
1042  * Allocates unique integer keys.
1043  * \param numkeys Number of keys required.
1044  * \return First allocated key; hence if the returned key is n
1045  * you can use n, n + 1, ..., n + (numkeys - 1)
1046  */
1047 unsigned
1048 sp_item_display_key_new(unsigned numkeys)
1050     static unsigned dkey = 0;
1052     dkey += numkeys;
1054     return dkey - numkeys;
1057 NRArenaItem *
1058 sp_item_invoke_show(SPItem *item, NRArena *arena, unsigned key, unsigned flags)
1060     g_assert(item != NULL);
1061     g_assert(SP_IS_ITEM(item));
1062     g_assert(arena != NULL);
1063     g_assert(NR_IS_ARENA(arena));
1065     NRArenaItem *ai = NULL;
1066     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->show) {
1067         ai = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->show(item, arena, key, flags);
1068     }
1070     if (ai != NULL) {
1071         item->display = sp_item_view_new_prepend(item->display, item, flags, key, ai);
1072         nr_arena_item_set_transform(ai, item->transform);
1073         nr_arena_item_set_opacity(ai, SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value));
1074         nr_arena_item_set_visible(ai, !item->isHidden());
1075         nr_arena_item_set_sensitive(ai, item->sensitive);
1076         if (item->clip_ref->getObject()) {
1077             SPClipPath *cp = item->clip_ref->getObject();
1079             if (!item->display->arenaitem->key) {
1080                 NR_ARENA_ITEM_SET_KEY(item->display->arenaitem, sp_item_display_key_new(3));
1081             }
1082             int clip_key = NR_ARENA_ITEM_GET_KEY(item->display->arenaitem);
1084             // Show and set clip
1085             NRArenaItem *ac = sp_clippath_show(cp, arena, clip_key);
1086             nr_arena_item_set_clip(ai, ac);
1087             nr_arena_item_unref(ac);
1089             // Update bbox, in case the clip uses bbox units
1090             NRRect bbox;
1091             sp_item_invoke_bbox(item, &bbox, NR::identity(), TRUE);
1092             sp_clippath_set_bbox(SP_CLIPPATH(cp), clip_key, &bbox);
1093             SP_OBJECT(cp)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1094         }
1095         if (item->mask_ref->getObject()) {
1096             SPMask *mask = item->mask_ref->getObject();
1098             if (!item->display->arenaitem->key) {
1099                 NR_ARENA_ITEM_SET_KEY(item->display->arenaitem, sp_item_display_key_new(3));
1100             }
1101             int mask_key = NR_ARENA_ITEM_GET_KEY(item->display->arenaitem);
1103             // Show and set mask
1104             NRArenaItem *ac = sp_mask_show(mask, arena, mask_key);
1105             nr_arena_item_set_mask(ai, ac);
1106             nr_arena_item_unref(ac);
1108             // Update bbox, in case the mask uses bbox units
1109             NRRect bbox;
1110             sp_item_invoke_bbox(item, &bbox, NR::identity(), TRUE);
1111             sp_mask_set_bbox(SP_MASK(mask), mask_key, &bbox);
1112             SP_OBJECT(mask)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1113         }
1114         NR_ARENA_ITEM_SET_DATA(ai, item);
1115         NRRect item_bbox;
1116         sp_item_invoke_bbox(item, &item_bbox, NR::identity(), TRUE, SPItem::GEOMETRIC_BBOX);
1117         boost::optional<NR::Rect> i_bbox = item_bbox;
1118         nr_arena_item_set_item_bbox(ai, i_bbox);
1119     }
1121     return ai;
1124 void
1125 sp_item_invoke_hide(SPItem *item, unsigned key)
1127     g_assert(item != NULL);
1128     g_assert(SP_IS_ITEM(item));
1130     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->hide) {
1131         ((SPItemClass *) G_OBJECT_GET_CLASS(item))->hide(item, key);
1132     }
1134     SPItemView *ref = NULL;
1135     SPItemView *v = item->display;
1136     while (v != NULL) {
1137         SPItemView *next = v->next;
1138         if (v->key == key) {
1139             if (item->clip_ref->getObject()) {
1140                 sp_clippath_hide(item->clip_ref->getObject(), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
1141                 nr_arena_item_set_clip(v->arenaitem, NULL);
1142             }
1143             if (item->mask_ref->getObject()) {
1144                 sp_mask_hide(item->mask_ref->getObject(), NR_ARENA_ITEM_GET_KEY(v->arenaitem));
1145                 nr_arena_item_set_mask(v->arenaitem, NULL);
1146             }
1147             if (!ref) {
1148                 item->display = v->next;
1149             } else {
1150                 ref->next = v->next;
1151             }
1152             nr_arena_item_unparent(v->arenaitem);
1153             nr_arena_item_unref(v->arenaitem);
1154             g_free(v);
1155         } else {
1156             ref = v;
1157         }
1158         v = next;
1159     }
1162 // Adjusters
1164 void
1165 sp_item_adjust_pattern (SPItem *item, NR::Matrix const &postmul, bool set)
1167     SPStyle *style = SP_OBJECT_STYLE (item);
1169     if (style && (style->fill.isPaintserver())) {
1170         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER (item);
1171         if (SP_IS_PATTERN (server)) {
1172             SPPattern *pattern = sp_pattern_clone_if_necessary (item, SP_PATTERN (server), "fill");
1173             sp_pattern_transform_multiply (pattern, postmul, set);
1174         }
1175     }
1177     if (style && (style->stroke.isPaintserver())) {
1178         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER (item);
1179         if (SP_IS_PATTERN (server)) {
1180             SPPattern *pattern = sp_pattern_clone_if_necessary (item, SP_PATTERN (server), "stroke");
1181             sp_pattern_transform_multiply (pattern, postmul, set);
1182         }
1183     }
1187 void
1188 sp_item_adjust_gradient (SPItem *item, NR::Matrix const &postmul, bool set)
1190     SPStyle *style = SP_OBJECT_STYLE (item);
1192     if (style && (style->fill.isPaintserver())) {
1193         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
1194         if (SP_IS_GRADIENT (server)) {
1196             /**
1197              * \note Bbox units for a gradient are generally a bad idea because
1198              * with them, you cannot preserve the relative position of the
1199              * object and its gradient after rotation or skew. So now we
1200              * convert them to userspace units which are easy to keep in sync
1201              * just by adding the object's transform to gradientTransform.
1202              * \todo FIXME: convert back to bbox units after transforming with
1203              * the item, so as to preserve the original units.
1204              */
1205             SPGradient *gradient = sp_gradient_convert_to_userspace (SP_GRADIENT (server), item, "fill");
1207             sp_gradient_transform_multiply (gradient, postmul, set);
1208         }
1209     }
1211     if (style && (style->stroke.isPaintserver())) {
1212         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
1213         if (SP_IS_GRADIENT (server)) {
1214             SPGradient *gradient = sp_gradient_convert_to_userspace (SP_GRADIENT (server), item, "stroke");
1215             sp_gradient_transform_multiply (gradient, postmul, set);
1216         }
1217     }
1220 void
1221 sp_item_adjust_stroke (SPItem *item, gdouble ex)
1223     SPStyle *style = SP_OBJECT_STYLE (item);
1225     if (style && !style->stroke.isNone() && !NR_DF_TEST_CLOSE (ex, 1.0, NR_EPSILON)) {
1227         style->stroke_width.computed *= ex;
1228         style->stroke_width.set = TRUE;
1230         if (style->stroke_dash.n_dash != 0) {
1231             int i;
1232             for (i = 0; i < style->stroke_dash.n_dash; i++) {
1233                 style->stroke_dash.dash[i] *= ex;
1234             }
1235             style->stroke_dash.offset *= ex;
1236         }
1238         SP_OBJECT(item)->updateRepr();
1239     }
1242 /**
1243  * Find out the inverse of previous transform of an item (from its repr)
1244  */
1245 NR::Matrix
1246 sp_item_transform_repr (SPItem *item)
1248     NR::Matrix t_old(NR::identity());
1249     gchar const *t_attr = SP_OBJECT_REPR(item)->attribute("transform");
1250     if (t_attr) {
1251         NR::Matrix t;
1252         if (sp_svg_transform_read(t_attr, &t)) {
1253             t_old = t;
1254         }
1255     }
1257     return t_old;
1261 /**
1262  * Recursively scale stroke width in \a item and its children by \a expansion.
1263  */
1264 void
1265 sp_item_adjust_stroke_width_recursive(SPItem *item, double expansion)
1267     sp_item_adjust_stroke (item, expansion);
1269 // A clone's child is the ghost of its original - we must not touch it, skip recursion
1270     if (item && SP_IS_USE(item))
1271         return;
1273     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1274         if (SP_IS_ITEM(o))
1275             sp_item_adjust_stroke_width_recursive(SP_ITEM(o), expansion);
1276     }
1279 /**
1280  * Recursively adjust rx and ry of rects.
1281  */
1282 void
1283 sp_item_adjust_rects_recursive(SPItem *item, NR::Matrix advertized_transform)
1285     if (SP_IS_RECT (item)) {
1286         sp_rect_compensate_rxry (SP_RECT(item), advertized_transform);
1287     }
1289     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1290         if (SP_IS_ITEM(o))
1291             sp_item_adjust_rects_recursive(SP_ITEM(o), advertized_transform);
1292     }
1295 /**
1296  * Recursively compensate pattern or gradient transform.
1297  */
1298 void
1299 sp_item_adjust_paint_recursive (SPItem *item, NR::Matrix advertized_transform, NR::Matrix t_ancestors, bool is_pattern)
1301 // _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors
1302 // _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform
1303 // By equating these two expressions we get t_paint_new = t_paint * paint_delta, where:
1304     NR::Matrix t_item = sp_item_transform_repr (item);
1305     NR::Matrix paint_delta = t_item * t_ancestors * advertized_transform * t_ancestors.inverse() * t_item.inverse();
1307 // Within text, we do not fork gradients, and so must not recurse to avoid double compensation;
1308 // also we do not recurse into clones, because a clone's child is the ghost of its original -
1309 // we must not touch it
1310     if (!(item && (SP_IS_TEXT(item) || SP_IS_USE(item)))) {
1311         for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
1312             if (SP_IS_ITEM(o)) {
1313 // At the level of the transformed item, t_ancestors is identity;
1314 // below it, it is the accmmulated chain of transforms from this level to the top level
1315                 sp_item_adjust_paint_recursive (SP_ITEM(o), advertized_transform, t_item * t_ancestors, is_pattern);
1316             }
1317         }
1318     }
1320 // We recursed into children first, and are now adjusting this object second;
1321 // this is so that adjustments in a tree are done from leaves up to the root,
1322 // and paintservers on leaves inheriting their values from ancestors could adjust themselves properly
1323 // before ancestors themselves are adjusted, probably differently (bug 1286535)
1325     if (is_pattern)
1326         sp_item_adjust_pattern (item, paint_delta);
1327     else
1328         sp_item_adjust_gradient (item, paint_delta);
1332 void
1333 sp_item_adjust_livepatheffect (SPItem *item, NR::Matrix const &postmul, bool set)
1335     if ( !SP_IS_LPE_ITEM(item) )
1336         return;
1338     SPLPEItem *lpeitem = SP_LPE_ITEM (item);
1339     if ( sp_lpe_item_has_path_effect(lpeitem) ) {
1340         PathEffectList effect_list =  sp_lpe_item_get_effect_list(lpeitem);
1341         for (PathEffectList::iterator it = effect_list.begin(); it != effect_list.end(); it++)
1342         {
1343             // If the path effect is used by 2 or more items, fork it
1344             // so that each object has its own independent copy of the effect
1345             LivePathEffectObject *lpeobj = (*it)->lpeobject;
1346             if (lpeobj) {
1347                 LivePathEffectObject *new_lpeobj = lpeobj->fork_private_if_necessary();
1348                 if (new_lpeobj != lpeobj) {
1349                     sp_lpe_item_replace_path_effect(lpeitem, lpeobj, new_lpeobj);
1350                 }
1351         
1352                 if (lpeobj->lpe) {
1353                     Inkscape::LivePathEffect::Effect * effect = lpeobj->lpe;
1354                     effect->transform_multiply(to_2geom(postmul), set);
1355                 }
1356             }
1357         }
1358     }
1361 /**
1362  * A temporary wrapper for the next function accepting the NR::Matrix
1363  * instead of NR::Matrix
1364  */
1365 void
1366 sp_item_write_transform(SPItem *item, Inkscape::XML::Node *repr, NR::Matrix const *transform, NR::Matrix const *adv)
1368     if (transform == NULL)
1369         sp_item_write_transform(item, repr, NR::identity(), adv);
1370     else
1371         sp_item_write_transform(item, repr, *transform, adv);
1374 /**
1375  * Set a new transform on an object.
1376  *
1377  * Compensate for stroke scaling and gradient/pattern fill transform, if
1378  * necessary. Call the object's set_transform method if transforms are
1379  * stored optimized. Send _transformed_signal. Invoke _write method so that
1380  * the repr is updated with the new transform.
1381  */
1382 void
1383 sp_item_write_transform(SPItem *item, Inkscape::XML::Node *repr, NR::Matrix const &transform, NR::Matrix const *adv, bool compensate)
1385     g_return_if_fail(item != NULL);
1386     g_return_if_fail(SP_IS_ITEM(item));
1387     g_return_if_fail(repr != NULL);
1389     // calculate the relative transform, if not given by the adv attribute
1390     NR::Matrix advertized_transform;
1391     if (adv != NULL) {
1392         advertized_transform = *adv;
1393     } else {
1394         advertized_transform = sp_item_transform_repr (item).inverse() * transform;
1395     }
1397     if (compensate) {
1399          // recursively compensate for stroke scaling, depending on user preference
1400         if (prefs_get_int_attribute("options.transform", "stroke", 1) == 0) {
1401             double const expansion = 1. / NR::expansion(advertized_transform);
1402             sp_item_adjust_stroke_width_recursive(item, expansion);
1403         }
1405         // recursively compensate rx/ry of a rect if requested
1406         if (prefs_get_int_attribute("options.transform", "rectcorners", 1) == 0) {
1407             sp_item_adjust_rects_recursive(item, advertized_transform);
1408         }
1410         // recursively compensate pattern fill if it's not to be transformed
1411         if (prefs_get_int_attribute("options.transform", "pattern", 1) == 0) {
1412             sp_item_adjust_paint_recursive (item, advertized_transform.inverse(), NR::identity(), true);
1413         }
1414         /// \todo FIXME: add the same else branch as for gradients below, to convert patterns to userSpaceOnUse as well
1415         /// recursively compensate gradient fill if it's not to be transformed
1416         if (prefs_get_int_attribute("options.transform", "gradient", 1) == 0) {
1417             sp_item_adjust_paint_recursive (item, advertized_transform.inverse(), NR::identity(), false);
1418         } else {
1419             // this converts the gradient/pattern fill/stroke, if any, to userSpaceOnUse; we need to do
1420             // it here _before_ the new transform is set, so as to use the pre-transform bbox
1421             sp_item_adjust_paint_recursive (item, NR::identity(), NR::identity(), false);
1422         }
1424     } // endif(compensate)
1426     gint preserve = prefs_get_int_attribute("options.preservetransform", "value", 0);
1427     NR::Matrix transform_attr (transform);
1428     if ( // run the object's set_transform (i.e. embed transform) only if:
1429          ((SPItemClass *) G_OBJECT_GET_CLASS(item))->set_transform && // it does have a set_transform method
1430              !preserve && // user did not chose to preserve all transforms
1431              !item->clip_ref->getObject() && // the object does not have a clippath
1432              !item->mask_ref->getObject() && // the object does not have a mask
1433          !(!transform.is_translation() && SP_OBJECT_STYLE(item) && SP_OBJECT_STYLE(item)->getFilter())
1434              // the object does not have a filter, or the transform is translation (which is supposed to not affect filters)
1435         ) {
1436         transform_attr = ((SPItemClass *) G_OBJECT_GET_CLASS(item))->set_transform(item, transform);
1437     }
1438     sp_item_set_item_transform(item, transform_attr);
1440     // Note: updateRepr comes before emitting the transformed signal since
1441     // it causes clone SPUse's copy of the original object to brought up to
1442     // date with the original.  Otherwise, sp_use_bbox returns incorrect
1443     // values if called in code handling the transformed signal.
1444     SP_OBJECT(item)->updateRepr();
1446     // send the relative transform with a _transformed_signal
1447     item->_transformed_signal.emit(&advertized_transform, item);
1450 gint
1451 sp_item_event(SPItem *item, SPEvent *event)
1453     g_return_val_if_fail(item != NULL, FALSE);
1454     g_return_val_if_fail(SP_IS_ITEM(item), FALSE);
1455     g_return_val_if_fail(event != NULL, FALSE);
1457     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->event)
1458         return ((SPItemClass *) G_OBJECT_GET_CLASS(item))->event(item, event);
1460     return FALSE;
1463 /**
1464  * Sets item private transform (not propagated to repr), without compensating stroke widths,
1465  * gradients, patterns as sp_item_write_transform does.
1466  */
1467 void
1468 sp_item_set_item_transform(SPItem *item, NR::Matrix const &transform)
1470     g_return_if_fail(item != NULL);
1471     g_return_if_fail(SP_IS_ITEM(item));
1473     if (!matrix_equalp(transform, item->transform, NR_EPSILON)) {
1474         item->transform = transform;
1475         /* The SP_OBJECT_USER_MODIFIED_FLAG_B is used to mark the fact that it's only a
1476            transformation.  It's apparently not used anywhere else. */
1477         item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_USER_MODIFIED_FLAG_B);
1478         sp_item_rm_unsatisfied_cns(*item);
1479     }
1482 void
1483 sp_item_convert_item_to_guides(SPItem *item) {
1484     g_return_if_fail(item != NULL);
1485     g_return_if_fail(SP_IS_ITEM(item));
1487     /* Use derived method if present ... */
1488     if (((SPItemClass *) G_OBJECT_GET_CLASS(item))->convert_to_guides) {
1489         (*((SPItemClass *) G_OBJECT_GET_CLASS(item))->convert_to_guides)(item);
1490         return;
1491     }
1493     /* .. otherwise simply place the guides around the item's bounding box */
1495     sp_item_convert_to_guides(item);
1499 /**
1500  * \pre \a ancestor really is an ancestor (\>=) of \a object, or NULL.
1501  *   ("Ancestor (\>=)" here includes as far as \a object itself.)
1502  */
1503 Geom::Matrix
1504 i2anc_affine(SPObject const *object, SPObject const *const ancestor) {
1505     Geom::Matrix ret(Geom::identity());
1506     g_return_val_if_fail(object != NULL, ret);
1508     /* stop at first non-renderable ancestor */
1509     while ( object != ancestor && SP_IS_ITEM(object) ) {
1510         if (SP_IS_ROOT(object)) {
1511             ret *= to_2geom(SP_ROOT(object)->c2p);
1512         }
1513         ret *= to_2geom(SP_ITEM(object)->transform);
1514         object = SP_OBJECT_PARENT(object);
1515     }
1516     return ret;
1519 Geom::Matrix
1520 i2i_affine(SPObject const *src, SPObject const *dest) {
1521     g_return_val_if_fail(src != NULL && dest != NULL, Geom::identity());
1522     SPObject const *ancestor = src->nearestCommonAncestor(dest);
1523     return i2anc_affine(src, ancestor) * i2anc_affine(dest, ancestor).inverse();
1526 NR::Matrix SPItem::getRelativeTransform(SPObject const *dest) const {
1527     return from_2geom(i2i_affine(this, dest));
1530 /**
1531  * Returns the accumulated transformation of the item and all its ancestors, including root's viewport.
1532  * \pre (item != NULL) and SP_IS_ITEM(item).
1533  */
1534 Geom::Matrix sp_item_i2doc_affine(SPItem const *item)
1536     return i2anc_affine(item, NULL);
1539 /**
1540  * Returns the accumulated transformation of the item and all its ancestors, but excluding root's viewport.
1541  * Used in path operations mostly.
1542  * \pre (item != NULL) and SP_IS_ITEM(item).
1543  */
1544 Geom::Matrix sp_item_i2root_affine(SPItem const *item)
1546     g_assert(item != NULL);
1547     g_assert(SP_IS_ITEM(item));
1549     Geom::Matrix ret(Geom::identity());
1550     g_assert(ret.isIdentity());
1551     while ( NULL != SP_OBJECT_PARENT(item) ) {
1552         ret *= to_2geom(item->transform);
1553         item = SP_ITEM(SP_OBJECT_PARENT(item));
1554     }
1555     g_assert(SP_IS_ROOT(item));
1557     ret *= to_2geom(item->transform);
1559     return ret;
1562 /* fixme: This is EVIL!!! */
1563 // fix this note: why/what evil? :)
1564 Geom::Matrix sp_item_i2d_affine(SPItem const *item)
1566     g_assert(item != NULL);
1567     g_assert(SP_IS_ITEM(item));
1569     Geom::Matrix const ret( sp_item_i2doc_affine(item)
1570                           * Geom::Scale(1, -1)
1571                           * Geom::Translate(0, sp_document_height(SP_OBJECT_DOCUMENT(item))) );
1572     return ret;
1575 // same as i2d but with i2root instead of i2doc
1576 Geom::Matrix sp_item_i2r_affine(SPItem const *item)
1578     g_assert(item != NULL);
1579     g_assert(SP_IS_ITEM(item));
1581     Geom::Matrix const ret( sp_item_i2root_affine(item)
1582                           * Geom::Scale(1, -1)
1583                           * Geom::Translate(0, sp_document_height(SP_OBJECT_DOCUMENT(item))) );
1584     return ret;
1587 /**
1588  * Converts a matrix \a m into the desktop coords of the \a item.
1589  * Will become a noop when we eliminate the coordinate flipping.
1590  */
1591 Geom::Matrix matrix_to_desktop(Geom::Matrix const m, SPItem const *item)
1593     Geom::Matrix const ret(m
1594                          * Geom::Translate(0, -sp_document_height(SP_OBJECT_DOCUMENT(item)))
1595                          * Geom::Scale(1, -1));
1596     return ret;
1599 /**
1600  * Converts a matrix \a m from the desktop coords of the \a item.
1601  * Will become a noop when we eliminate the coordinate flipping.
1602  */
1603 Geom::Matrix matrix_from_desktop(Geom::Matrix const m, SPItem const *item)
1605     Geom::Matrix const ret(Geom::Scale(1, -1)
1606                          * Geom::Translate(0, sp_document_height(SP_OBJECT_DOCUMENT(item)))
1607                          * m);
1608     return ret;
1611 void sp_item_set_i2d_affine(SPItem *item, Geom::Matrix const &i2dt)
1613     g_return_if_fail( item != NULL );
1614     g_return_if_fail( SP_IS_ITEM(item) );
1616     Geom::Matrix dt2p; /* desktop to item parent transform */
1617     if (SP_OBJECT_PARENT(item)) {
1618         dt2p = sp_item_i2d_affine((SPItem *) SP_OBJECT_PARENT(item)).inverse();
1619     } else {
1620         dt2p = ( Geom::Translate(0, -sp_document_height(SP_OBJECT_DOCUMENT(item)))
1621                  * Geom::Scale(1, -1) );
1622     }
1624     Geom::Matrix const i2p( i2dt * dt2p );
1625     sp_item_set_item_transform(item, from_2geom(i2p));
1629 Geom::Matrix
1630 sp_item_dt2i_affine(SPItem const *item)
1632     /* fixme: Implement the right way (Lauris) */
1633     return sp_item_i2d_affine(item).inverse();
1636 /* Item views */
1638 static SPItemView *
1639 sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, NRArenaItem *arenaitem)
1641     SPItemView *new_view;
1643     g_assert(item != NULL);
1644     g_assert(SP_IS_ITEM(item));
1645     g_assert(arenaitem != NULL);
1646     g_assert(NR_IS_ARENA_ITEM(arenaitem));
1648     new_view = g_new(SPItemView, 1);
1650     new_view->next = list;
1651     new_view->flags = flags;
1652     new_view->key = key;
1653     new_view->arenaitem = nr_arena_item_ref(arenaitem);
1655     return new_view;
1658 static SPItemView *
1659 sp_item_view_list_remove(SPItemView *list, SPItemView *view)
1661     if (view == list) {
1662         list = list->next;
1663     } else {
1664         SPItemView *prev;
1665         prev = list;
1666         while (prev->next != view) prev = prev->next;
1667         prev->next = view->next;
1668     }
1670     nr_arena_item_unref(view->arenaitem);
1671     g_free(view);
1673     return list;
1676 /**
1677  * Return the arenaitem corresponding to the given item in the display
1678  * with the given key
1679  */
1680 NRArenaItem *
1681 sp_item_get_arenaitem(SPItem *item, unsigned key)
1683     for ( SPItemView *iv = item->display ; iv ; iv = iv->next ) {
1684         if ( iv->key == key ) {
1685             return iv->arenaitem;
1686         }
1687     }
1689     return NULL;
1692 int
1693 sp_item_repr_compare_position(SPItem *first, SPItem *second)
1695     return sp_repr_compare_position(SP_OBJECT_REPR(first),
1696                                     SP_OBJECT_REPR(second));
1699 SPItem *
1700 sp_item_first_item_child (SPObject *obj)
1702     for ( SPObject *iter = sp_object_first_child(obj) ; iter ; iter = SP_OBJECT_NEXT(iter)) {
1703         if (SP_IS_ITEM (iter))
1704             return SP_ITEM (iter);
1705     }
1706     return NULL;
1709 void
1710 sp_item_convert_to_guides(SPItem *item) {
1711     SPDesktop *dt = inkscape_active_desktop();
1712     SPNamedView *nv = sp_desktop_namedview(dt);
1713     (void)nv;
1715     int prefs_bbox = prefs_get_int_attribute("tools", "bounding_box", 0);
1716     SPItem::BBoxType bbox_type = (prefs_bbox ==0)? 
1717         SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
1719     boost::optional<NR::Rect> bbox = sp_item_bbox_desktop(item, bbox_type);
1720     if (!bbox) {
1721         g_warning ("Cannot determine item's bounding box during conversion to guides.\n");
1722         return;
1723     }
1725     std::list<std::pair<Geom::Point, Geom::Point> > pts;
1727     NR::Point A((*bbox).min());
1728     NR::Point C((*bbox).max());
1729     NR::Point B(A[NR::X], C[NR::Y]);
1730     NR::Point D(C[NR::X], A[NR::Y]);
1732     pts.push_back(std::make_pair(A, B));
1733     pts.push_back(std::make_pair(B, C));
1734     pts.push_back(std::make_pair(C, D));
1735     pts.push_back(std::make_pair(D, A));
1737     sp_guide_pt_pairs_to_guides(dt, pts);
1740 /*
1741   Local Variables:
1742   mode:c++
1743   c-file-style:"stroustrup"
1744   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1745   indent-tabs-mode:nil
1746   fill-column:99
1747   End:
1748 */
1749 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :