Code

sp_shape now uses 2geom PathVector for all marker positions
[inkscape.git] / src / sp-shape.cpp
1 /*
2  * Base class for shapes, including <path> element
3  *
4  * Author:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *
7  * Copyright (C) 1999-2002 Lauris Kaplinski
8  * Copyright (C) 2000-2001 Ximian, Inc.
9  * Copyright (C) 2004 John Cliff
10  * Copyright (C) 2007-2008 Johan Engelen
11  *
12  * Released under GNU GPL, read the file 'COPYING' for more information
13  */
15 #ifdef HAVE_CONFIG_H
16 # include "config.h"
17 #endif
19 #include <libnr/n-art-bpath.h>
20 #include <libnr/nr-matrix-fns.h>
21 #include <libnr/nr-matrix-ops.h>
22 #include <libnr/nr-matrix-translate-ops.h>
23 #include <libnr/nr-scale-matrix-ops.h>
24 #include <2geom/rect.h>
25 #include <2geom/transforms.h>
26 #include <2geom/pathvector.h>
27 #include "helper/geom.h"
29 #include <sigc++/functors/ptr_fun.h>
30 #include <sigc++/adaptors/bind.h>
32 #include "macros.h"
33 #include "display/nr-arena-shape.h"
34 #include "display/curve.h"
35 #include "print.h"
36 #include "document.h"
37 #include "style.h"
38 #include "marker.h"
39 #include "sp-path.h"
40 #include "prefs-utils.h"
41 #include "attributes.h"
43 #include "live_effects/lpeobject.h"
44 #include "uri.h"
45 #include "extract-uri.h"
46 #include "uri-references.h"
47 #include "bad-uri-exception.h"
48 #include "xml/repr.h"
50 #include "util/mathfns.h" // for triangle_area()
52 #define noSHAPE_VERBOSE
54 static void sp_shape_class_init (SPShapeClass *klass);
55 static void sp_shape_init (SPShape *shape);
56 static void sp_shape_finalize (GObject *object);
58 static void sp_shape_build (SPObject * object, SPDocument * document, Inkscape::XML::Node * repr);
59 static void sp_shape_release (SPObject *object);
61 static void sp_shape_set(SPObject *object, unsigned key, gchar const *value);
62 static void sp_shape_update (SPObject *object, SPCtx *ctx, unsigned int flags);
63 static void sp_shape_modified (SPObject *object, unsigned int flags);
64 static Inkscape::XML::Node *sp_shape_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
66 static void sp_shape_bbox(SPItem const *item, NRRect *bbox, NR::Matrix const &transform, unsigned const flags);
67 void sp_shape_print (SPItem * item, SPPrintContext * ctx);
68 static NRArenaItem *sp_shape_show (SPItem *item, NRArena *arena, unsigned int key, unsigned int flags);
69 static void sp_shape_hide (SPItem *item, unsigned int key);
70 static void sp_shape_snappoints (SPItem const *item, SnapPointsIter p);
72 static void sp_shape_update_marker_view (SPShape *shape, NRArenaItem *ai);
74 static SPLPEItemClass *parent_class;
76 /**
77  * Registers the SPShape class with Gdk and returns its type number.
78  */
79 GType
80 sp_shape_get_type (void)
81 {
82         static GType type = 0;
83         if (!type) {
84                 GTypeInfo info = {
85                         sizeof (SPShapeClass),
86                         NULL, NULL,
87                         (GClassInitFunc) sp_shape_class_init,
88                         NULL, NULL,
89                         sizeof (SPShape),
90                         16,
91                         (GInstanceInitFunc) sp_shape_init,
92                         NULL,   /* value_table */
93                 };
94                 type = g_type_register_static (SP_TYPE_LPE_ITEM, "SPShape", &info, (GTypeFlags)0);
95         }
96         return type;
97 }
99 /**
100  * Initializes a SPShapeClass object.  Establishes the function pointers to the class'
101  * member routines in the class vtable, and sets pointers to parent classes.
102  */
103 static void
104 sp_shape_class_init (SPShapeClass *klass)
106     GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
107     SPObjectClass *sp_object_class = SP_OBJECT_CLASS(klass);
108     SPItemClass * item_class = SP_ITEM_CLASS(klass);
109     SPLPEItemClass * lpe_item_class = SP_LPE_ITEM_CLASS(klass);
111     parent_class = (SPLPEItemClass *)g_type_class_peek_parent (klass);
113     gobject_class->finalize = sp_shape_finalize;
115         sp_object_class->build = sp_shape_build;
116         sp_object_class->release = sp_shape_release;
117     sp_object_class->set = sp_shape_set;
118         sp_object_class->update = sp_shape_update;
119         sp_object_class->modified = sp_shape_modified;
120     sp_object_class->write = sp_shape_write;
122         item_class->bbox = sp_shape_bbox;
123         item_class->print = sp_shape_print;
124         item_class->show = sp_shape_show;
125         item_class->hide = sp_shape_hide;
126     item_class->snappoints = sp_shape_snappoints;
127     lpe_item_class->update_patheffect = NULL;
129     klass->set_shape = NULL;
132 /**
133  * Initializes an SPShape object.
134  */
135 static void
136 sp_shape_init (SPShape *shape)
138     for ( int i = 0 ; i < SP_MARKER_LOC_QTY ; i++ ) {
139         new (&shape->release_connect[i]) sigc::connection();
140         new (&shape->modified_connect[i]) sigc::connection();
141     }
144 static void
145 sp_shape_finalize (GObject *object)
147     SPShape *shape=(SPShape *)object;
149     for ( int i = 0 ; i < SP_MARKER_LOC_QTY ; i++ ) {
150         shape->release_connect[i].disconnect();
151         shape->release_connect[i].~connection();
152         shape->modified_connect[i].disconnect();
153         shape->modified_connect[i].~connection();
154     }
156     if (((GObjectClass *) (parent_class))->finalize) {
157         (* ((GObjectClass *) (parent_class))->finalize)(object);
158     }
161 /**
162  * Virtual build callback for SPMarker.
163  *
164  * This is to be invoked immediately after creation of an SPShape.
165  *
166  * \see sp_object_build()
167  */
168 static void
169 sp_shape_build (SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
171     if (((SPObjectClass *) (parent_class))->build) {
172        (*((SPObjectClass *) (parent_class))->build) (object, document, repr);
173     }
176 /**
177  * Removes, releases and unrefs all children of object
178  *
179  * This is the inverse of sp_shape_build().  It must be invoked as soon
180  * as the shape is removed from the tree, even if it is still referenced
181  * by other objects.  This routine also disconnects/unrefs markers and
182  * curves attached to it.
183  *
184  * \see sp_object_release()
185  */
186 static void
187 sp_shape_release (SPObject *object)
189         SPItem *item;
190         SPShape *shape;
191         SPItemView *v;
192         int i;
194         item = (SPItem *) object;
195         shape = (SPShape *) object;
197         for (i=SP_MARKER_LOC_START; i<SP_MARKER_LOC_QTY; i++) {
198           if (shape->marker[i]) {
199             sp_signal_disconnect_by_data (shape->marker[i], object);
200             for (v = item->display; v != NULL; v = v->next) {
201               sp_marker_hide ((SPMarker *) shape->marker[i], NR_ARENA_ITEM_GET_KEY (v->arenaitem) + i);
202             }
203             shape->marker[i] = sp_object_hunref (shape->marker[i], object);
204           }
205         }
206         if (shape->curve) {
207                 shape->curve = shape->curve->unref();
208         }
209     
210         if (((SPObjectClass *) parent_class)->release) {
211           ((SPObjectClass *) parent_class)->release (object);
212         }
217 static void
218 sp_shape_set(SPObject *object, unsigned int key, gchar const *value)
220     if (((SPObjectClass *) parent_class)->set) {
221         ((SPObjectClass *) parent_class)->set(object, key, value);
222     }
225 static Inkscape::XML::Node *
226 sp_shape_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags)
228     if (((SPObjectClass *)(parent_class))->write) {
229         ((SPObjectClass *)(parent_class))->write(object, doc, repr, flags);
230     }
232     return repr;
235 /** 
236  * Updates the shape when its attributes have changed.  Also establishes
237  * marker objects to match the style settings.  
238  */
239 static void
240 sp_shape_update (SPObject *object, SPCtx *ctx, unsigned int flags)
242     SPItem *item = (SPItem *) object;
243     SPShape *shape = (SPShape *) object;
245         if (((SPObjectClass *) (parent_class))->update) {
246           (* ((SPObjectClass *) (parent_class))->update) (object, ctx, flags);
247         }
249         /* This stanza checks that an object's marker style agrees with
250          * the marker objects it has allocated.  sp_shape_set_marker ensures
251          * that the appropriate marker objects are present (or absent) to
252          * match the style.
253          */
254         /* TODO:  It would be nice if this could be done at an earlier level */
255         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
256             sp_shape_set_marker (object, i, object->style->marker[i].value);
257           }
259         if (flags & (SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
260                 SPStyle *style;
261                 style = SP_OBJECT_STYLE (object);
262                 if (style->stroke_width.unit == SP_CSS_UNIT_PERCENT) {
263                         SPItemCtx *ictx = (SPItemCtx *) ctx;
264                         double const aw = 1.0 / NR::expansion(ictx->i2vp);
265                         style->stroke_width.computed = style->stroke_width.value * aw;
266                         for (SPItemView *v = ((SPItem *) (shape))->display; v != NULL; v = v->next) {
267                                 nr_arena_shape_set_style ((NRArenaShape *) v->arenaitem, style);
268                         }
269                 }
270         }
272         if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG)) {
273                 /* This is suboptimal, because changing parent style schedules recalculation */
274                 /* But on the other hand - how can we know that parent does not tie style and transform */
275                 NR::Maybe<NR::Rect> paintbox = SP_ITEM(object)->getBounds(NR::identity());
276                 for (SPItemView *v = SP_ITEM (shape)->display; v != NULL; v = v->next) {
277                     NRArenaShape * const s = NR_ARENA_SHAPE(v->arenaitem);
278                     if (flags & SP_OBJECT_MODIFIED_FLAG) {
279                         nr_arena_shape_set_path(s, shape->curve, (flags & SP_OBJECT_USER_MODIFIED_FLAG_B));
280                     }
281                     if (paintbox) {
282                         s->setPaintBox(*paintbox);
283                     }
284                 }
285         }
287         if (sp_shape_has_markers (shape)) {
289             /* Dimension marker views */
290             for (SPItemView *v = item->display; v != NULL; v = v->next) {
292                 if (!v->arenaitem->key) {
293                     /* Get enough keys for all, start, mid and end marker types,
294                     ** and set this view's arenaitem key to the first of these keys.
295                     */
296                     NR_ARENA_ITEM_SET_KEY (
297                         v->arenaitem,
298                         sp_item_display_key_new (SP_MARKER_LOC_QTY)
299                         );
300                 }
302                 for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
303                     if (shape->marker[i]) {
304                         sp_marker_show_dimension ((SPMarker *) shape->marker[i],
305                                                   NR_ARENA_ITEM_GET_KEY (v->arenaitem) + i - SP_MARKER_LOC,
306                                                   sp_shape_number_of_markers (shape, i));
307                     }
308                 }
309             }
311             /* Update marker views */
312             for (SPItemView *v = item->display; v != NULL; v = v->next) {
313                 sp_shape_update_marker_view (shape, v->arenaitem);
314             }
315         }
319 /**
320 * Works out whether a marker of a given type is required at a particular
321 * point on a shape.
323 * \param shape Shape of interest.
324 * \param m Marker type (e.g. SP_MARKER_LOC_START)
325 * \param bp Path segment.
326 * \return 1 if a marker is required here, otherwise 0.
327 */
328 bool
329 sp_shape_marker_required(SPShape const *shape, int const m, NArtBpath const *bp)
331     if (shape->marker[m] == NULL) {
332         return false;
333     }
335     if (bp == SP_CURVE_BPATH(shape->curve))
336         return m == SP_MARKER_LOC_START;
337     else if (bp[1].code == NR_END)
338         return m == SP_MARKER_LOC_END;
339     else
340         return m == SP_MARKER_LOC_MID;
343 static bool
344 is_moveto(NRPathcode const c)
346     return c == NR_MOVETO || c == NR_MOVETO_OPEN;
349 /** 
350  * Helper function that advances a subpath's bpath to the first subpath
351  * by checking for moveto segments.
352  *
353  * \pre The bpath[] containing bp begins with a moveto. 
354  */
355 static NArtBpath const *
356 first_seg_in_subpath(NArtBpath const *bp)
358     while (!is_moveto(bp->code)) {
359         --bp;
360     }
361     return bp;
364 /**
365  * Advances the bpath to the last segment in the subpath.
366  */
367 static NArtBpath const *
368 last_seg_in_subpath(NArtBpath const *bp)
370     for(;;) {
371         ++bp;
372         switch (bp->code) {
373             case NR_MOVETO:
374             case NR_MOVETO_OPEN:
375             case NR_END:
376                 --bp;
377                 return bp;
379             default: continue;
380         }
381     }
385 /* A subpath begins with a moveto and ends immediately before the next moveto or NR_END.
386  * (`moveto' here means either NR_MOVETO or NR_MOVETO_OPEN.)  I'm assuming that non-empty
387  * paths always begin with a moveto.
388  *
389  * The control points of the subpath are the control points of the path elements of the subpath.
390  *
391  * As usual, the control points of a moveto or NR_LINETO are {c(3)}, and
392  * the control points of a NR_CURVETO are {c(1), c(2), c(3)}.
393  * (It follows from the definition that NR_END isn't part of a subpath.)
394  *
395  * The initial control point is bpath[bi0].c(3).
396  *
397  * Reference: http://www.w3.org/TR/SVG11/painting.html#MarkerElement, the `orient' attribute.
398  * Reference for behaviour of zero-length segments:
399  * http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
400  */
402 static double const no_tangent = 128.0;  /* arbitrarily-chosen value outside the range of atan2,
403                                           * i.e. outside of [-pi, pi]. This value is incremented by
404                                           * 1 and checked using > to be safe from floating-point
405                                           * equality comparison madness.*/
407 /**
408  * Helper function to calculate the outgoing tangent of a path 
409  * ( atan2(other - p0) )
410  * \pre The bpath[] containing bp0 begins with a moveto. 
411  */
412 static double
413 outgoing_tangent(NArtBpath const *bp0)
415     /* See notes in comment block above. */
417     g_assert(bp0->code != NR_END);
418     NR::Point const &p0 = bp0->c(3);
419     NR::Point other;
420     for (NArtBpath const *bp = bp0;;) {
421         ++bp;
422         switch (bp->code) {
423             case NR_LINETO:
424                 other = bp->c(3);
425                 if (other != p0) {
426                     goto found;
427                 }
428                 break;
430             case NR_CURVETO:
431                 for (unsigned ci = 1; ci <= 3; ++ci) {
432                     other = bp->c(ci);
433                     if (other != p0) {
434                         goto found;
435                     }
436                 }
437                 break;
439             case NR_MOVETO_OPEN:
440             case NR_END:
441             case NR_MOVETO:
442                 bp = first_seg_in_subpath(bp0);
443                 if (bp == bp0) {
444                     /* Gone right around the subpath without finding any different point since the
445                      * initial moveto. */
446                     return no_tangent + 1;
447                 }
448                 if (bp->code != NR_MOVETO) {
449                     /* Open subpath. */
450                     return no_tangent + 1;
451                 }
452                 other = bp->c(3);
453                 if (other != p0) {
454                     goto found;
455                 }
456                 break;
457         }
459         if (bp == bp0) {
460             /* Back where we started, so zero-length subpath. */
461             return no_tangent + 1;
463             /* Note: this test must come after we've looked at element bp, in case bp0 is a curve:
464              * we must look at c(1) and c(2).  (E.g. single-curve subpath.)
465              */
466         }
467     }
469 found:
470     return atan2( other - p0 );
473 /**
474  * Helper function to calculate the incoming tangent of a path
475  * ( atan2(p0 - other) )
476  * 
477  * \pre The bpath[] containing bp0 begins with a moveto. 
478  */
479 static double
480 incoming_tangent(NArtBpath const *bp0)
482     /* See notes in comment block before outgoing_tangent. */
484     g_assert(bp0->code != NR_END);
485     NR::Point const &p0 = bp0->c(3);
486     NR::Point other;
487     for (NArtBpath const *bp = bp0;;) {
488         switch (bp->code) {
489             case NR_LINETO:
490                 other = bp->c(3);
491                 if (other != p0) {
492                     goto found;
493                 }
494                 --bp;
495                 break;
497             case NR_CURVETO:
498                 for (unsigned ci = 3; ci != 0; --ci) {
499                     other = bp->c(ci);
500                     if (other != p0) {
501                         goto found;
502                     }
503                 }
504                 --bp;
505                 break;
507             case NR_MOVETO:
508             case NR_MOVETO_OPEN:
509                 other = bp->c(3);
510                 if (other != p0) {
511                     goto found;
512                 }
513                 if (bp->code != NR_MOVETO) {
514                     /* Open subpath. */
515                     return no_tangent + 1;
516                 }
517                 bp = last_seg_in_subpath(bp0);
518                 break;
520             default: /* includes NR_END */
521                 g_error("Found invalid path code %u in middle of path.", bp->code);
522                 return no_tangent + 1;
523         }
525         if (bp == bp0) {
526             /* Back where we started from: zero-length subpath. */
527             return no_tangent + 1;
528         }
529     }
531 found:
532     return atan2( p0 - other );
536 /**
537  * Calculate the transform required to get a marker's path object in the
538  * right place for particular path segment on a shape.  You should
539  * call sp_shape_marker_required first to see if a marker is required
540  * at this point.
541  *
542  * \see sp_shape_marker_required.
543  *
544  * \param shape Shape which the marker is for.
545  * \param m Marker type (e.g. SP_MARKER_LOC_START)
546  * \param bp Path segment which the arrow is for.
547  * \return Transform matrix.
548  */
549 NR::Matrix
550 sp_shape_marker_get_transform(SPShape const *shape, NArtBpath const *bp)
552     g_return_val_if_fail(( is_moveto(SP_CURVE_BPATH(shape->curve)[0].code)
553                            && ( 0 < shape->curve->get_length() )
554                            && ( SP_CURVE_BPATH(shape->curve)[shape->curve->get_length()].code == NR_END ) ),
555                          NR::Matrix(NR::translate(bp->c(3))));
556     double const angle1 = incoming_tangent(bp);
557     double const angle2 = outgoing_tangent(bp);
559     double ret_angle;
560     if (angle1 > no_tangent) {
561         /* First vertex of an open subpath. */
562         ret_angle = ( angle2 > no_tangent
563                       ? 0.
564                       : angle2 );
565     } else if (angle2 > no_tangent) {
566         /* Last vertex of an open subpath. */
567         ret_angle = angle1;
568     } else {
569         ret_angle = .5 * (angle1 + angle2);
571         if ( fabs( angle2 - angle1 ) > M_PI ) {
572             /* ret_angle is in the middle of the larger of the two sectors between angle1 and
573              * angle2, so flip it by 180degrees to force it to the middle of the smaller sector.
574              *
575              * (Imagine a circle with rays drawn at angle1 and angle2 from the centre of the
576              * circle.  Those two rays divide the circle into two sectors.)
577              */
578             ret_angle += M_PI;
579         }
580     }
582     return NR::Matrix(NR::rotate(ret_angle)) * NR::translate(bp->c(3));
585 /**
586  * Calculate the transform required to get a marker's path object in the
587  * right place for particular path segment on a shape.
588  *
589  * \see sp_shape_marker_update_marker_view.
590  *
591  * \param p Point where the marker should be placed.
592  * \param t1 Tangent of end of curvesegment before marker
593  * \param t2 Tangent of start of curvesegment after marker
594  * \return Transform matrix.
595  *
596  * From SVG spec:
597  * The axes of the temporary new user coordinate system are aligned according to the orient attribute on the 'marker'
598  * element and the slope of the curve at the given vertex. (Note: if there is a discontinuity at a vertex, the slope
599  * is the average of the slopes of the two segments of the curve that join at the given vertex. If a slope cannot be
600  * determined, the slope is assumed to be zero.)
601  */
602 Geom::Matrix
603 sp_shape_marker_get_transform(Geom::Point & p, Geom::Point & t1, Geom::Point & t2)
605     double const angle1 = Geom::atan2(t1);
606     double const angle2 = Geom::atan2(t2);
608     double ret_angle;
609     ret_angle = .5 * (angle1 + angle2);
611     if ( fabs( angle2 - angle1 ) > M_PI ) {
612         /* ret_angle is in the middle of the larger of the two sectors between angle1 and
613          * angle2, so flip it by 180degrees to force it to the middle of the smaller sector.
614          *
615          * (Imagine a circle with rays drawn at angle1 and angle2 from the centre of the
616          * circle.  Those two rays divide the circle into two sectors.)
617          */
618         ret_angle += M_PI;
619     }
621     return Geom::Rotate(ret_angle) * Geom::Translate(p);
624 /**
625  * Updates the instances (views) of a given marker in a shape.
626  * Marker views have to be scaled already.  The transformation
627  * is retrieved and then shown by calling sp_marker_show_instance.
628  *
629  * TODO: correctly handle the 'marker' attribute.
630  * "Using the marker property from a style sheet is equivalent to using all three (start, mid, end)."
631  * See painting-marker-03-f.svg in SVG 1.1 Full test suite.
632  */
633 static void
634 sp_shape_update_marker_view (SPShape *shape, NRArenaItem *ai)
636     SPStyle *style = ((SPObject *) shape)->style;
638     // position arguments to sp_marker_show_instance, basically counts the amount of markers.
639     int start_pos = 0;
640     int mid_pos = 0;
641     int end_pos = 0;
643     Geom::PathVector const & pathv = shape->curve->get_pathvector();
644     for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
645         if ( shape->marker[SP_MARKER_LOC_START] ) {
646             Geom::Point p = path_it->front().pointAt(0);
647             Geom::Point tang = path_it->front().unitTangentAt(0);
648             Geom::Matrix const m (sp_shape_marker_get_transform(p, tang, tang));
649             sp_marker_show_instance ((SPMarker* ) shape->marker[SP_MARKER_LOC_START], ai,
650                                      NR_ARENA_ITEM_GET_KEY(ai) + SP_MARKER_LOC_START, start_pos, m,
651                                      style->stroke_width.computed);
652              start_pos++;
653         }
655         if ( shape->marker[SP_MARKER_LOC_MID] ) {
656             Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
657             Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
658             while (curve_it2 != path_it->end_default())
659             {
660                 /* Put marker between curve_it1 and curve_it2.
661                  * Loop to end_default (so including closing segment), because when a path is closed,
662                  * there should be a midpoint marker between last segment and closing straight line segment
663                  */
664                 Geom::Point p = curve_it1->pointAt(1);
665                 Geom::Point tang1 = curve_it1->unitTangentAt(1);
666                 Geom::Point tang2 = curve_it2->unitTangentAt(0);
667                 Geom::Matrix const m (sp_shape_marker_get_transform(p, tang1, tang2));
668                 sp_marker_show_instance ((SPMarker* ) shape->marker[SP_MARKER_LOC_MID], ai,
669                                          NR_ARENA_ITEM_GET_KEY(ai) + SP_MARKER_LOC_MID, mid_pos, m,
670                                          style->stroke_width.computed);
671                 mid_pos++;
673                 ++curve_it1;
674                 ++curve_it2;
675             }
676         }
678         if ( shape->marker[SP_MARKER_LOC_END] ) {
679             Geom::Point p = path_it->back_default().pointAt(1);
680             Geom::Point tang = path_it->back_default().unitTangentAt(1);
681             Geom::Matrix const m (sp_shape_marker_get_transform(p, tang, tang));
682             sp_marker_show_instance ((SPMarker* ) shape->marker[SP_MARKER_LOC_END], ai,
683                                      NR_ARENA_ITEM_GET_KEY(ai) + SP_MARKER_LOC_END, end_pos, m,
684                                      style->stroke_width.computed);
685             end_pos++;
686         }
687     }
690 /**
691  * Sets modified flag for all sub-item views.
692  */
693 static void
694 sp_shape_modified (SPObject *object, unsigned int flags)
696         SPShape *shape = SP_SHAPE (object);
698         if (((SPObjectClass *) (parent_class))->modified) {
699           (* ((SPObjectClass *) (parent_class))->modified) (object, flags);
700         }
702         if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
703                 for (SPItemView *v = SP_ITEM (shape)->display; v != NULL; v = v->next) {
704                         nr_arena_shape_set_style (NR_ARENA_SHAPE (v->arenaitem), object->style);
705                 }
706         }
709 /**
710  * Calculates the bounding box for item, storing it into bbox.
711  * This also includes the bounding boxes of any markers included in the shape.
712  */
713 static void sp_shape_bbox(SPItem const *item, NRRect *bbox, NR::Matrix const &transform, unsigned const flags)
715     SPShape const *shape = SP_SHAPE (item);
717     if (shape->curve) {
719         NRRect  cbbox;
721         Geom::Rect geombbox = bounds_exact_transformed(shape->curve->get_pathvector(), to_2geom(transform));
722         cbbox.x0 = geombbox[0][0];
723         cbbox.y0 = geombbox[1][0];
724         cbbox.x1 = geombbox[0][1];
725         cbbox.y1 = geombbox[1][1];
727         if ((SPItem::BBoxType) flags != SPItem::GEOMETRIC_BBOX) {
728             
729             SPStyle* style=SP_OBJECT_STYLE (item);
730             if (!style->stroke.isNone()) {
731                 double const scale = expansion(transform);
732                 if ( fabs(style->stroke_width.computed * scale) > 0.01 ) { // sinon c'est 0=oon veut pas de bord
733                     double const width = MAX(0.125, style->stroke_width.computed * scale);
734                     if ( fabs(cbbox.x1-cbbox.x0) > -0.00001 && fabs(cbbox.y1-cbbox.y0) > -0.00001 ) {
735                         cbbox.x0-=0.5*width;
736                         cbbox.x1+=0.5*width;
737                         cbbox.y0-=0.5*width;
738                         cbbox.y1+=0.5*width;
739                     }
740                 }
741             }
743             // Union with bboxes of the markers, if any
744             if (sp_shape_has_markers (shape)) {
745                 /* TODO: make code prettier: lots of variables can be taken out of the loop! */
746                 Geom::PathVector const & pathv = shape->curve->get_pathvector();
747                 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
748                     if ( shape->marker[SP_MARKER_LOC_START] ) {
749                         SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_START]);
750                         SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_START]));
752                         Geom::Point p = path_it->front().pointAt(0);
753                         Geom::Point tang = path_it->front().unitTangentAt(0);
754                         NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
756                         if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
757                             tr = NR::scale(style->stroke_width.computed) * tr;
758                         }
760                         // total marker transform
761                         tr = marker_item->transform * marker->c2p * tr * transform;
763                         // get bbox of the marker with that transform
764                         NRRect marker_bbox;
765                         sp_item_invoke_bbox (marker_item, &marker_bbox, tr, true);
766                         // union it with the shape bbox
767                         nr_rect_d_union (&cbbox, &cbbox, &marker_bbox);
768                     }
770                     if ( shape->marker[SP_MARKER_LOC_MID] ) {
771                         Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
772                         Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
773                         while (curve_it2 != path_it->end_default())
774                         {
775                             /* Put marker between curve_it1 and curve_it2.
776                              * Loop to end_default (so including closing segment), because when a path is closed,
777                              * there should be a midpoint marker between last segment and closing straight line segment */
779                             SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_MID]);
780                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_MID]));
782                             Geom::Point p = curve_it1->pointAt(1);
783                             Geom::Point tang1 = curve_it1->unitTangentAt(1);
784                             Geom::Point tang2 = curve_it2->unitTangentAt(0);
785                             NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang1, tang2)));
787                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
788                                 tr = NR::scale(style->stroke_width.computed) * tr;
789                             }
791                             // total marker transform
792                             tr = marker_item->transform * marker->c2p * tr * transform;
794                             // get bbox of the marker with that transform
795                             NRRect marker_bbox;
796                             sp_item_invoke_bbox (marker_item, &marker_bbox, tr, true);
797                             // union it with the shape bbox
798                             nr_rect_d_union (&cbbox, &cbbox, &marker_bbox);
800                             ++curve_it1;
801                             ++curve_it2;
802                         }
803                     }
805                     if ( shape->marker[SP_MARKER_LOC_END] ) {
806                         SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_END]);
807                         SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_END]));
809                         Geom::Point p = path_it->back_default().pointAt(1);
810                         Geom::Point tang = path_it->back_default().unitTangentAt(1);
811                         NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
813                         if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
814                             tr = NR::scale(style->stroke_width.computed) * tr;
815                         }
817                         // total marker transform
818                         tr = marker_item->transform * marker->c2p * tr * transform;
820                         // get bbox of the marker with that transform
821                         NRRect marker_bbox;
822                         sp_item_invoke_bbox (marker_item, &marker_bbox, tr, true);
823                         // union it with the shape bbox
824                         nr_rect_d_union (&cbbox, &cbbox, &marker_bbox);
825                     }
826                 }
827             }
828         }
830         // copy our bbox to the variable we're given
831         *bbox = cbbox;
832     }
835 /**
836  * Prepares shape for printing.  Handles printing of comments for printing
837  * debugging, sizes the item to fit into the document width/height,
838  * applies print fill/stroke, sets transforms for markers, and adds
839  * comment labels.
840  */
841 void
842 sp_shape_print (SPItem *item, SPPrintContext *ctx)
844         NRRect pbox, dbox, bbox;
846         SPShape *shape = SP_SHAPE(item);
848         if (!shape->curve) return;
850         gint add_comments = prefs_get_int_attribute_limited ("printing.debug", "add-label-comments", 0, 0, 1);
851         if (add_comments) {
852             gchar * comment = g_strdup_printf("begin '%s'",
853                                               SP_OBJECT(item)->defaultLabel());
854             sp_print_comment(ctx, comment);
855             g_free(comment);
856         }
858         /* fixme: Think (Lauris) */
859         sp_item_invoke_bbox(item, &pbox, NR::identity(), TRUE);
860         dbox.x0 = 0.0;
861         dbox.y0 = 0.0;
862         dbox.x1 = sp_document_width (SP_OBJECT_DOCUMENT (item));
863         dbox.y1 = sp_document_height (SP_OBJECT_DOCUMENT (item));
864         sp_item_bbox_desktop (item, &bbox);
865         NR::Matrix const i2d = from_2geom(sp_item_i2d_affine(item));
867         SPStyle* style = SP_OBJECT_STYLE (item);
869     if (!style->fill.isNone()) {
870         const_NRBPath bp;
871         bp.path = SP_CURVE_BPATH(shape->curve);
872         sp_print_fill (ctx, &bp, &i2d, style, &pbox, &dbox, &bbox);
873     }
875     if (!style->stroke.isNone()) {
876         const_NRBPath bp;
877         bp.path = SP_CURVE_BPATH(shape->curve);
878         sp_print_stroke (ctx, &bp, &i2d, style, &pbox, &dbox, &bbox);
879     }
881     /* TODO: make code prettier: lots of variables can be taken out of the loop! */
882     Geom::PathVector const & pathv = shape->curve->get_pathvector();
883     for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
884         if ( shape->marker[SP_MARKER_LOC_START] ) {
885             SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_START]);
886             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_START]));
888             Geom::Point p = path_it->front().pointAt(0);
889             Geom::Point tang = path_it->front().unitTangentAt(0);
890             NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
892             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
893                 tr = NR::scale(style->stroke_width.computed) * tr;
894             }
896             tr = marker_item->transform * marker->c2p * tr;
898             NR::Matrix old_tr = marker_item->transform;
899             marker_item->transform = tr;
900             sp_item_invoke_print (marker_item, ctx);
901             marker_item->transform = old_tr;
902         }
904         if ( shape->marker[SP_MARKER_LOC_MID] ) {
905             Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
906             Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
907             while (curve_it2 != path_it->end_default())
908             {
909                 /* Put marker between curve_it1 and curve_it2.
910                  * Loop to end_default (so including closing segment), because when a path is closed,
911                  * there should be a midpoint marker between last segment and closing straight line segment */
913                 SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_MID]);
914                 SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_MID]));
916                 Geom::Point p = curve_it1->pointAt(1);
917                 Geom::Point tang1 = curve_it1->unitTangentAt(1);
918                 Geom::Point tang2 = curve_it2->unitTangentAt(0);
919                 NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang1, tang2)));
921                 if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
922                     tr = NR::scale(style->stroke_width.computed) * tr;
923                 }
925                 tr = marker_item->transform * marker->c2p * tr;
927                 NR::Matrix old_tr = marker_item->transform;
928                 marker_item->transform = tr;
929                 sp_item_invoke_print (marker_item, ctx);
930                 marker_item->transform = old_tr;
932                 ++curve_it1;
933                 ++curve_it2;
934             }
935         }
937         if ( shape->marker[SP_MARKER_LOC_END] ) {
938             SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_END]);
939             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_END]));
941             Geom::Point p = path_it->back_default().pointAt(1);
942             Geom::Point tang = path_it->back_default().unitTangentAt(1);
943             NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
945             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
946                 tr = NR::scale(style->stroke_width.computed) * tr;
947             }
949             tr = marker_item->transform * marker->c2p * tr;
951             NR::Matrix old_tr = marker_item->transform;
952             marker_item->transform = tr;
953             sp_item_invoke_print (marker_item, ctx);
954             marker_item->transform = old_tr;
955         }
956     }
958         if (add_comments) {
959             gchar * comment = g_strdup_printf("end '%s'",
960                                               SP_OBJECT(item)->defaultLabel());
961             sp_print_comment(ctx, comment);
962             g_free(comment);
963         }
966 /**
967  * Sets style, path, and paintbox.  Updates marker views, including dimensions.
968  */
969 static NRArenaItem *
970 sp_shape_show (SPItem *item, NRArena *arena, unsigned int /*key*/, unsigned int /*flags*/)
972         SPObject *object = SP_OBJECT(item);
973         SPShape *shape = SP_SHAPE(item);
975         NRArenaItem *arenaitem = NRArenaShape::create(arena);
976         NRArenaShape * const s = NR_ARENA_SHAPE(arenaitem);
977         nr_arena_shape_set_style(s, object->style);
978         nr_arena_shape_set_path(s, shape->curve, false);
979         NR::Maybe<NR::Rect> paintbox = item->getBounds(NR::identity());
980         if (paintbox) {
981             s->setPaintBox(*paintbox);
982         }
984         if (sp_shape_has_markers (shape)) {
986             /* Dimension the marker views */
987             if (!arenaitem->key) {
988                 NR_ARENA_ITEM_SET_KEY (arenaitem, sp_item_display_key_new (SP_MARKER_LOC_QTY));
989             }
991             for (int i = 0; i < SP_MARKER_LOC_QTY; i++) {
992                 if (shape->marker[i]) {
993                     sp_marker_show_dimension ((SPMarker *) shape->marker[i],
994                                               NR_ARENA_ITEM_GET_KEY (arenaitem) + i - SP_MARKER_LOC,
995                                               sp_shape_number_of_markers (shape, i));
996                 }
997             }
1000             /* Update marker views */
1001             sp_shape_update_marker_view (shape, arenaitem);
1002         }
1004         return arenaitem;
1007 /**
1008  * Hides/removes marker views from the shape.
1009  */
1010 static void
1011 sp_shape_hide (SPItem *item, unsigned int key)
1013         SPShape *shape;
1014         SPItemView *v;
1015         int i;
1017         shape = (SPShape *) item;
1019         for (i=0; i<SP_MARKER_LOC_QTY; i++) {
1020           if (shape->marker[i]) {
1021             for (v = item->display; v != NULL; v = v->next) {
1022                 if (key == v->key) {
1023               sp_marker_hide ((SPMarker *) shape->marker[i],
1024                                     NR_ARENA_ITEM_GET_KEY (v->arenaitem) + i);
1025                 }
1026             }
1027           }
1028         }
1030         if (((SPItemClass *) parent_class)->hide) {
1031           ((SPItemClass *) parent_class)->hide (item, key);
1032         }
1035 /**
1036 * \param shape Shape.
1037 * \return TRUE if the shape has any markers, or FALSE if not.
1038 */
1039 int
1040 sp_shape_has_markers (SPShape const *shape)
1042     /* Note, we're ignoring 'marker' settings, which technically should apply for
1043        all three settings.  This should be fixed later such that if 'marker' is
1044        specified, then all three should appear. */
1046     return (
1047         shape->curve &&
1048         (shape->marker[SP_MARKER_LOC_START] ||
1049          shape->marker[SP_MARKER_LOC_MID] ||
1050          shape->marker[SP_MARKER_LOC_END])
1051         );
1055 /**
1056 * \param shape Shape.
1057 * \param type Marker type (e.g. SP_MARKER_LOC_START)
1058 * \return Number of markers that the shape has of this type.
1059 */
1060 int
1061 sp_shape_number_of_markers (SPShape *shape, int type)
1063     int n = 0;
1064     for (NArtBpath const* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
1065         if (sp_shape_marker_required (shape, type, bp)) {
1066             n++;
1067         }
1068     }
1070     return n;
1073 /**
1074  * Checks if the given marker is used in the shape, and if so, it
1075  * releases it by calling sp_marker_hide.  Also detaches signals
1076  * and unrefs the marker from the shape.
1077  */
1078 static void
1079 sp_shape_marker_release (SPObject *marker, SPShape *shape)
1081         SPItem *item;
1082         int i;
1084         item = (SPItem *) shape;
1086         for (i = SP_MARKER_LOC_START; i < SP_MARKER_LOC_QTY; i++) {
1087           if (marker == shape->marker[i]) {
1088             SPItemView *v;
1089             /* Hide marker */
1090             for (v = item->display; v != NULL; v = v->next) {
1091               sp_marker_hide ((SPMarker *) (shape->marker[i]), NR_ARENA_ITEM_GET_KEY (v->arenaitem) + i);
1092               /* fixme: Do we need explicit remove here? (Lauris) */
1093               /* nr_arena_item_set_mask (v->arenaitem, NULL); */
1094             }
1095             /* Detach marker */
1096             sp_signal_disconnect_by_data (shape->marker[i], item);
1097             shape->marker[i] = sp_object_hunref (shape->marker[i], item);
1098           }
1099         }
1102 /**
1103  * No-op.  Exists for handling 'modified' messages
1104  */
1105 static void
1106 sp_shape_marker_modified (SPObject */*marker*/, guint /*flags*/, SPItem */*item*/)
1108         /* I think mask does update automagically */
1109         /* g_warning ("Item %s mask %s modified", SP_OBJECT_ID (item), SP_OBJECT_ID (mask)); */
1112 /**
1113  * Adds a new marker to shape object at the location indicated by key.  value 
1114  * must be a valid URI reference resolvable from the shape object (i.e., present
1115  * in the document <defs>).  If the shape object already has a marker
1116  * registered at the given position, it is removed first.  Then the
1117  * new marker is hrefed and its signals connected.
1118  */
1119 void
1120 sp_shape_set_marker (SPObject *object, unsigned int key, const gchar *value)
1122     SPItem *item = (SPItem *) object;
1123     SPShape *shape = (SPShape *) object;
1125     if (key < SP_MARKER_LOC_START || key > SP_MARKER_LOC_END) {
1126         return;
1127     }
1129     SPObject *mrk = sp_css_uri_reference_resolve (SP_OBJECT_DOCUMENT (object), value);
1130     if (mrk != shape->marker[key]) {
1131         if (shape->marker[key]) {
1132             SPItemView *v;
1134             /* Detach marker */
1135             shape->release_connect[key].disconnect();
1136             shape->modified_connect[key].disconnect();
1138             /* Hide marker */
1139             for (v = item->display; v != NULL; v = v->next) {
1140                 sp_marker_hide ((SPMarker *) (shape->marker[key]),
1141                                 NR_ARENA_ITEM_GET_KEY (v->arenaitem) + key);
1142                 /* fixme: Do we need explicit remove here? (Lauris) */
1143                 /* nr_arena_item_set_mask (v->arenaitem, NULL); */
1144             }
1146             /* Unref marker */
1147             shape->marker[key] = sp_object_hunref (shape->marker[key], object);
1148         }
1149         if (SP_IS_MARKER (mrk)) {
1150             shape->marker[key] = sp_object_href (mrk, object);
1151             shape->release_connect[key] = mrk->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_shape_marker_release), shape));
1152             shape->modified_connect[key] = mrk->connectModified(sigc::bind<2>(sigc::ptr_fun(&sp_shape_marker_modified), shape));
1153         }
1154     }
1159 /* Shape section */
1161 /**
1162  * Calls any registered handlers for the set_shape action
1163  */
1164 void
1165 sp_shape_set_shape (SPShape *shape)
1167         g_return_if_fail (shape != NULL);
1168         g_return_if_fail (SP_IS_SHAPE (shape));
1170         if (SP_SHAPE_CLASS (G_OBJECT_GET_CLASS (shape))->set_shape) {
1171           SP_SHAPE_CLASS (G_OBJECT_GET_CLASS (shape))->set_shape (shape);
1172         }
1175 /**
1176  * Adds a curve to the shape.  If owner is specified, a reference
1177  * will be made, otherwise the curve will be copied into the shape.
1178  * Any existing curve in the shape will be unreferenced first.
1179  * This routine also triggers a request to update the display.
1180  */
1181 void
1182 sp_shape_set_curve (SPShape *shape, SPCurve *curve, unsigned int owner)
1184         if (shape->curve) {
1185                 shape->curve = shape->curve->unref();
1186         }
1187         if (curve) {
1188                 if (owner) {
1189                         shape->curve = curve->ref();
1190                 } else {
1191                         shape->curve = curve->copy();
1192                 }
1193         }
1194         SP_OBJECT(shape)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1197 /**
1198  * Return duplicate of curve (if any exists) or NULL if there is no curve
1199  */
1200 SPCurve *
1201 sp_shape_get_curve (SPShape *shape)
1203         if (shape->curve) {
1204                 return shape->curve->copy();
1205         }
1206         return NULL;
1209 /**
1210  * Same as sp_shape_set_curve but without updating the display
1211  */
1212 void
1213 sp_shape_set_curve_insync (SPShape *shape, SPCurve *curve, unsigned int owner)
1215         if (shape->curve) {
1216                 shape->curve = shape->curve->unref();
1217         }
1218         if (curve) {
1219                 if (owner) {
1220                         shape->curve = curve->ref();
1221                 } else {
1222                         shape->curve = curve->copy();
1223                 }
1224         }
1227 /**
1228  * Return all nodes in a path that are to be considered for snapping
1229  */
1230 static void sp_shape_snappoints(SPItem const *item, SnapPointsIter p)
1232     g_assert(item != NULL);
1233     g_assert(SP_IS_SHAPE(item));
1235     SPShape const *shape = SP_SHAPE(item);
1236     if (shape->curve == NULL) {
1237         return;
1238     }
1239     
1240     NR::Matrix const i2d (from_2geom(sp_item_i2d_affine (item)));
1241     NArtBpath const *b = SP_CURVE_BPATH(shape->curve);    
1242     
1243     // Cycle through the nodes in the concatenated subpaths
1244     while (b->code != NR_END) {
1245         NR::Point pos = b->c(3) * i2d; // this is the current node
1246         
1247         // NR_MOVETO Indicates the start of a closed subpath, see nr-path-code.h
1248         // If we're looking at a closed subpath, then we can skip this first 
1249         // point of the subpath because it's coincident with the last point.  
1250         if (b->code != NR_MOVETO) {
1251             if (b->code == NR_MOVETO_OPEN || b->code == NR_LINETO || b[1].code == NR_LINETO || b[1].code == NR_END) {
1252                 // end points of a line segment are always considered for snapping
1253                 *p = pos; 
1254             } else {        
1255                 // g_assert(b->code == NR_CURVETO);
1256                 NR::Point ppos, npos;
1257                 ppos = b->code == NR_CURVETO ? b->c(2) * i2d : pos; // backward handle 
1258                 npos = b[1].code == NR_CURVETO ? b[1].c(1) * i2d : pos; // forward handle            
1259                 // Determine whether a node is at a smooth part of the path, by 
1260                 // calculating a measure for the collinearity of the handles
1261                 bool c1 = fabs (Inkscape::Util::triangle_area (pos, ppos, npos)) < 1; // points are (almost) collinear
1262                 bool c2 = NR::L2(pos - ppos) < 1e-6 || NR::L2(pos - npos) < 1e-6; // endnode, or a node with a retracted handle
1263                 if (!(c1 & !c2)) {
1264                     *p = pos; // only return non-smooth nodes ("cusps")
1265                 }
1266             }
1267         }
1268         
1269         b++;
1270     }
1273 /*
1274   Local Variables:
1275   mode:c++
1276   c-file-style:"stroustrup"
1277   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1278   indent-tabs-mode:nil
1279   fill-column:99
1280   End:
1281 */
1282 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :