Code

Committed double code because of the hurry to let you use the axonom-snapping stuff.
[inkscape.git] / src / splivarot.cpp
1 #define __SP_LIVAROT_C__
2 /*
3  *  splivarot.cpp
4  *  Inkscape
5  *
6  *  Created by fred on Fri Dec 05 2003.
7  *  tweaked endlessly by bulia byak <buliabyak@users.sf.net>
8  *  public domain
9  *
10  */
12 /*
13  * contains lots of stitched pieces of path-chemistry.c
14  */
16 #ifdef HAVE_CONFIG_H
17 # include <config.h>
18 #endif
20 #include <vector>
21 #include <glib/gmem.h>
22 #include "xml/repr.h"
23 #include "svg/svg.h"
24 #include "sp-path.h"
25 #include "sp-shape.h"
26 #include "sp-marker.h"
27 #include "enums.h"
28 #include "sp-text.h"
29 #include "sp-item-group.h"
30 #include "style.h"
31 #include "inkscape.h"
32 #include "document.h"
33 #include "message-stack.h"
34 #include "selection.h"
35 #include "desktop-handles.h"
36 #include "desktop.h"
37 #include "display/canvas-bpath.h"
38 #include "display/curve.h"
39 #include <glibmm/i18n.h>
40 #include "prefs-utils.h"
42 #include "libnr/n-art-bpath.h"
43 #include "libnr/nr-path.h"
44 #include "xml/repr.h"
45 #include "xml/repr-sorting.h"
47 #include <libnr/nr-matrix-fns.h>
48 #include <libnr/nr-matrix-ops.h>
49 #include <libnr/nr-matrix-translate-ops.h>
50 #include <libnr/nr-scale-matrix-ops.h>
52 #include "livarot/Path.h"
53 #include "livarot/Shape.h"
55 #include "splivarot.h"
57 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
59 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
60 void sp_selected_path_do_offset(bool expand, double prefOffset);
61 void sp_selected_path_create_offset_object(int expand, bool updating);
63 void
64 sp_selected_path_union()
65 {
66     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
67 }
69 void
70 sp_selected_path_intersect()
71 {
72     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
73 }
75 void
76 sp_selected_path_diff()
77 {
78     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
79 }
81 void
82 sp_selected_path_symdiff()
83 {
84     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
85 }
86 void
87 sp_selected_path_cut()
88 {
89     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
90 }
91 void
92 sp_selected_path_slice()
93 {
94     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
95 }
98 // boolean operations
99 // take the source paths from the file, do the operation, delete the originals and add the results
100 void
101 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
103     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
105     Inkscape::Selection *selection = sp_desktop_selection(desktop);
107     GSList *il = (GSList *) selection->itemList();
109     if (g_slist_length(il) < 2) {
110         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
111         return;
112     }
114     if (g_slist_length(il) > 2) {
115         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
116             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
117             return;
118         }
119     }
121     // reverseOrderForOp marks whether the order of the list is the top->down order
122     // it's only used when there are 2 objects, and for operations who need to know the
123     // topmost object (differences, cuts)
124     bool reverseOrderForOp = false;
126     // mettre les elements de la liste dans l'ordre pour ces operations
127     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
128         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
129         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
130         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
132         if (a == NULL || b == NULL) {
133             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Unable to determine the <b>z-order</b> of the objects selected for difference, XOR, division, or path cut."));
134             return;
135         }
137         if (Ancetre(a, b)) {
138             // a is the parent of b, already in the proper order
139         } else if (Ancetre(b, a)) {
140             // reverse order
141             reverseOrderForOp = true;
142         } else {
144             // objects are not in parent/child relationship;
145             // find their lowest common ancestor
146             Inkscape::XML::Node *dad = LCA(a, b);
147             if (dad == NULL) {
148                 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Unable to determine the <b>z-order</b> of the objects selected for difference, XOR, division, or path cut."));
149                 return;
150             }
152             // find the children of the LCA that lead from it to the a and b
153             Inkscape::XML::Node *as = AncetreFils(a, dad);
154             Inkscape::XML::Node *bs = AncetreFils(b, dad);
156             // find out which comes first
157             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
158                 if (child == as) {
159                     /* a first, so reverse. */
160                     reverseOrderForOp = true;
161                     break;
162                 }
163                 if (child == bs)
164                     break;
165             }
166         }
167     }
169     il = g_slist_copy(il);
171     // first check if all the input objects have shapes
172     // otherwise bail out
173     for (GSList *l = il; l != NULL; l = l->next)
174     {
175         SPItem *item = SP_ITEM(l->data);
176         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
177         {
178             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
179             g_slist_free(il);
180             return;
181         }
182     }
184     // extract the livarot Paths from the source objects
185     // also get the winding rule specified in the style
186     int nbOriginaux = g_slist_length(il);
187     std::vector<Path *> originaux(nbOriginaux);
188     std::vector<FillRule> origWind(nbOriginaux);
189     int curOrig;
190     {
191         curOrig = 0;
192         for (GSList *l = il; l != NULL; l = l->next)
193         {
194             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
195             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
196             if (val && strcmp(val, "nonzero") == 0) {
197                 origWind[curOrig]= fill_nonZero;
198             } else if (val && strcmp(val, "evenodd") == 0) {
199                 origWind[curOrig]= fill_oddEven;
200             } else {
201                 origWind[curOrig]= fill_nonZero;
202             }
204             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
205             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
206             {
207                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
208                 g_slist_free(il);
209                 return;
210             }
211             curOrig++;
212         }
213     }
214     // reverse if needed
215     // note that the selection list keeps its order
216     if ( reverseOrderForOp ) {
217         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
218         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
219     }
221     // and work
222     // some temporary instances, first
223     Shape *theShapeA = new Shape;
224     Shape *theShapeB = new Shape;
225     Shape *theShape = new Shape;
226     Path *res = new Path;
227     res->SetBackData(false);
228     Path::cut_position  *toCut=NULL;
229     int                  nbToCut=0;
231     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
232         // true boolean op
233         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
234         originaux[0]->ConvertWithBackData(0.1);
236         originaux[0]->Fill(theShape, 0);
238         theShapeA->ConvertToShape(theShape, origWind[0]);
240         curOrig = 1;
241         for (GSList *l = il->next; l != NULL; l = l->next) {
242             originaux[curOrig]->ConvertWithBackData(0.1);
244             originaux[curOrig]->Fill(theShape, curOrig);
246             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
248             // les elements arrivent en ordre inverse dans la liste
249             theShape->Booleen(theShapeB, theShapeA, bop);
251             {
252                 Shape *swap = theShape;
253                 theShape = theShapeA;
254                 theShapeA = swap;
255             }
256             curOrig++;
257         }
259         {
260             Shape *swap = theShape;
261             theShape = theShapeA;
262             theShapeA = swap;
263         }
265     } else if ( bop == bool_op_cut ) {
266         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
267         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
268         // it is just uncrossed, and cleaned from duplicate edges and points
269         // then it's fed to Booleen() which will uncross it against the other path
270         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
271         // thus making a polygon. the weight of the edges of the cut are all 0, but
272         // the Booleen need to invert the ones inside the source polygon (for the subsequent
273         // ConvertToForme)
275         // the cut path needs to have the highest pathID in the back data
276         // that's how the Booleen() function knows it's an edge of the cut
278         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
279         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
280         // left it at 1.0. Investigate replacing this by a combination of difference and
281         // intersection of the same two paths. -- bb
282         {
283             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
284             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
285         }
286         originaux[0]->ConvertWithBackData(1.0);
288         originaux[0]->Fill(theShape, 0);
290         theShapeA->ConvertToShape(theShape, origWind[0]);
292         originaux[1]->ConvertWithBackData(1.0);
294         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
296         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
298         // les elements arrivent en ordre inverse dans la liste
299         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
301     } else if ( bop == bool_op_slice ) {
302         // slice is not really a boolean operation
303         // you just put the 2 shapes in a single polygon, uncross it
304         // the points where the degree is > 2 are intersections
305         // just check it's an intersection on the path you want to cut, and keep it
306         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
307         // make new subpath at each one of these positions
308         // inversion pour l'op\8eration
309         {
310             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
311             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
312         }
313         originaux[0]->ConvertWithBackData(1.0);
315         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
317         originaux[1]->ConvertWithBackData(1.0);
319         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
321         theShape->ConvertToShape(theShapeA, fill_justDont);
323         if ( theShape->hasBackData() ) {
324             // should always be the case, but ya never know
325             {
326                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
327                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
328                         // possibly an intersection
329                         // we need to check that at least one edge from the source path is incident to it
330                         // before we declare it's an intersection
331                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
332                         int   nbOrig=0;
333                         int   nbOther=0;
334                         int   piece=-1;
335                         float t=0.0;
336                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
337                             if ( theShape->ebData[cb].pathID == 0 ) {
338                                 // the source has an edge incident to the point, get its position on the path
339                                 piece=theShape->ebData[cb].pieceID;
340                                 if ( theShape->getEdge(cb).st == i ) {
341                                     t=theShape->ebData[cb].tSt;
342                                 } else {
343                                     t=theShape->ebData[cb].tEn;
344                                 }
345                                 nbOrig++;
346                             }
347                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
348                             cb=theShape->NextAt(i, cb);
349                         }
350                         if ( nbOrig > 0 && nbOther > 0 ) {
351                             // point incident to both path and cut: an intersection
352                             // note that you only keep one position on the source; you could have degenerate
353                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
354                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
355                             toCut[nbToCut].piece=piece;
356                             toCut[nbToCut].t=t;
357                             nbToCut++;
358                         }
359                     }
360                 }
361             }
362             {
363                 // i think it's useless now
364                 int i = theShape->numberOfEdges() - 1;
365                 for (;i>=0;i--) {
366                     if ( theShape->ebData[i].pathID == 1 ) {
367                         theShape->SubEdge(i);
368                     }
369                 }
370             }
372         }
373     }
375     int*    nesting=NULL;
376     int*    conts=NULL;
377     int     nbNest=0;
378     // pour compenser le swap juste avant
379     if ( bop == bool_op_slice ) {
380 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
381 //    res->ConvertForcedToMoveTo();
382         res->Copy(originaux[0]);
383         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
384         free(toCut);
385     } else if ( bop == bool_op_cut ) {
386         // il faut appeler pour desallouer PointData (pas vital, mais bon)
387         // the Booleen() function did not deallocated the point_data array in theShape, because this
388         // function needs it.
389         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
390         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
391         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
392     } else {
393         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
394     }
396     delete theShape;
397     delete theShapeA;
398     delete theShapeB;
399     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
401     if (res->descr_cmd.size() <= 1)
402     {
403         // only one command, presumably a moveto: it isn't a path
404         for (GSList *l = il; l != NULL; l = l->next)
405         {
406             SP_OBJECT(l->data)->deleteObject();
407         }
408         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
409                          description);
410         selection->clear();
412         delete res;
413         g_slist_free(il);
414         return;
415     }
417     // remember important aspects of the source path, to be restored
418     Inkscape::XML::Node *repr_source;
419     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
420         if (reverseOrderForOp) {
421              repr_source = SP_OBJECT_REPR(il->data);
422         } else {
423              repr_source = SP_OBJECT_REPR(il->next->data);
424         }
425     } else {
426         // find out the bottom object
427         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
429         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
430         repr_source = ((Inkscape::XML::Node *) sorted->data);
431         g_slist_free(sorted);
432     }
433     gint pos = repr_source->position();
434     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
435     gchar const *id = repr_source->attribute("id");
436     gchar const *style = repr_source->attribute("style");
437     gchar const *mask = repr_source->attribute("mask");
438     gchar const *clip_path = repr_source->attribute("clip-path");
441     // remove source paths
442     selection->clear();
443     for (GSList *l = il; l != NULL; l = l->next) {
444         // if this is the bottommost object,
445         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
446             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
447             SP_OBJECT(l->data)->deleteObject(false);
448         } else {
449             // delete the object for real, so that its clones can take appropriate action
450             SP_OBJECT(l->data)->deleteObject();
451         }
452     }
453     g_slist_free(il);
455     // premultiply by the inverse of parent's repr
456     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
457     NR::Matrix local = sp_item_i2doc_affine(parent_item);
458     gchar affinestr[80];
459     gchar *transform = NULL;
460     if (!local.test_identity() && sp_svg_transform_write(affinestr, 79, local.inverse())) {
461         transform = affinestr;
462     }
464     // now that we have the result, add it on the canvas
465     if ( bop == bool_op_cut || bop == bool_op_slice ) {
466         int    nbRP=0;
467         Path** resPath;
468         if ( bop == bool_op_slice ) {
469             // there are moveto's at each intersection, but it's still one unique path
470             // so break it down and add each subpath independently
471             // we could call break_apart to do this, but while we have the description...
472             resPath=res->SubPaths(nbRP, false);
473         } else {
474             // cut operation is a bit wicked: you need to keep holes
475             // that's why you needed the nesting
476             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
477             // to get the path for each part of the polygon. that's why you need the nesting info:
478             // to know in wich subpath to add a subpath
479             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
481             // cleaning
482             if ( conts ) free(conts);
483             if ( nesting ) free(nesting);
484         }
486         // add all the pieces resulting from cut or slice
487         for (int i=0;i<nbRP;i++) {
488             gchar *d = resPath[i]->svg_dump_path();
490             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
491             repr->setAttribute("style", style);
492             if (mask)
493                 repr->setAttribute("mask", mask);
494             if (clip_path)
495                 repr->setAttribute("clip-path", clip_path);
497             repr->setAttribute("d", d);
498             g_free(d);
500             // for slice, remove fill
501             if (bop == bool_op_slice) {
502                 SPCSSAttr *css;
504                 css = sp_repr_css_attr_new();
505                 sp_repr_css_set_property(css, "fill", "none");
507                 sp_repr_css_change(repr, css, "style");
509                 sp_repr_css_attr_unref(css);
510             }
512             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
513             // this means it's basically random which of the pieces inherits the original's id and clones
514             // a better algorithm might figure out e.g. the biggest piece
515             repr->setAttribute("id", id);
517             repr->setAttribute("transform", transform);
519             // add the new repr to the parent
520             parent->appendChild(repr);
522             // move to the saved position
523             repr->setPosition(pos > 0 ? pos : 0);
525             selection->add(repr);
526             Inkscape::GC::release(repr);
528             delete resPath[i];
529         }
530         if ( resPath ) free(resPath);
532     } else {
533         gchar *d = res->svg_dump_path();
535         Inkscape::XML::Node *repr = sp_repr_new("svg:path");
536         repr->setAttribute("style", style);
538         if ( mask )
539             repr->setAttribute("mask", mask);
541         if ( clip_path )
542             repr->setAttribute("clip-path", clip_path);
544         repr->setAttribute("d", d);
545         g_free(d);
547         repr->setAttribute("transform", transform);
549         repr->setAttribute("id", id);
550         parent->appendChild(repr);
551         repr->setPosition(pos > 0 ? pos : 0);
553         selection->add(repr);
554         Inkscape::GC::release(repr);
555     }
557     sp_document_done(sp_desktop_document(desktop), verb, description);
559     delete res;
563 void
564 sp_selected_path_outline()
566     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
568     Inkscape::Selection *selection = sp_desktop_selection(desktop);
570     if (selection->isEmpty()) {
571         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
572         return;
573     }
575     bool did = false;
577     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
578          items != NULL;
579          items = items->next) {
581         SPItem *item = (SPItem *) items->data;
583         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
584             continue;
586         SPCurve *curve = NULL;
587         if (SP_IS_SHAPE(item)) {
588             curve = sp_shape_get_curve(SP_SHAPE(item));
589             if (curve == NULL)
590                 continue;
591         }
592         if (SP_IS_TEXT(item)) {
593             curve = SP_TEXT(item)->getNormalizedBpath();
594             if (curve == NULL)
595                 continue;
596         }
598         {   // pas de stroke pas de chocolat
599             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
600             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
602             if (val == NULL || strcmp(val, "none") == 0) {
603                 sp_curve_unref(curve);
604                 continue;
605             }
606         }
608         // remember old stroke style, to be set on fill
609         SPCSSAttr *ncss;
610         {
611             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
612             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
613             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
615             ncss = sp_repr_css_attr_new();
617             sp_repr_css_set_property(ncss, "stroke", "none");
618             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
619             sp_repr_css_set_property(ncss, "fill", val);
620             if ( opac ) {
621                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
622             } else {
623                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
624             }
625             sp_repr_css_unset_property(ncss, "marker-start");
626             sp_repr_css_unset_property(ncss, "marker-mid");
627             sp_repr_css_unset_property(ncss, "marker-end");
628         }
630         NR::Matrix const transform(item->transform);
631         float const scale = transform.expansion();
632         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
633         SPStyle *i_style = SP_OBJECT(item)->style;
635         float o_width, o_miter;
636         JoinType o_join;
637         ButtType o_butt;
639         {
640             int jointype, captype;
642             jointype = i_style->stroke_linejoin.computed;
643             captype = i_style->stroke_linecap.computed;
644             o_width = i_style->stroke_width.computed;
646             switch (jointype) {
647                 case SP_STROKE_LINEJOIN_MITER:
648                     o_join = join_pointy;
649                     break;
650                 case SP_STROKE_LINEJOIN_ROUND:
651                     o_join = join_round;
652                     break;
653                 default:
654                     o_join = join_straight;
655                     break;
656             }
658             switch (captype) {
659                 case SP_STROKE_LINECAP_SQUARE:
660                     o_butt = butt_square;
661                     break;
662                 case SP_STROKE_LINECAP_ROUND:
663                     o_butt = butt_round;
664                     break;
665                 default:
666                     o_butt = butt_straight;
667                     break;
668             }
670             if (o_width < 0.1)
671                 o_width = 0.1;
672             o_miter = i_style->stroke_miterlimit.value * o_width;
673         }
675         Path *orig = Path_for_item(item, false);
676         if (orig == NULL) {
677             g_free(style);
678             sp_curve_unref(curve);
679             continue;
680         }
682         Path *res = new Path;
683         res->SetBackData(false);
685         if (i_style->stroke_dash.n_dash) {
686             // For dashed strokes, use Stroke method, because Outline can't do dashes
687             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
689             orig->ConvertWithBackData(0.1);
691             orig->DashPolylineFromStyle(i_style, scale, 0);
693             Shape* theShape = new Shape;
694             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
695                          0.5 * o_miter);
696             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
698             Shape *theRes = new Shape;
700             theRes->ConvertToShape(theShape, fill_positive);
702             Path *originaux[1];
703             originaux[0] = res;
704             theRes->ConvertToForme(orig, 1, originaux);
706             res->Coalesce(5.0);
708             delete theShape;
709             delete theRes;
711         } else {
713             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
715             orig->Coalesce(0.5 * o_width);
717             Shape *theShape = new Shape;
718             Shape *theRes = new Shape;
720             res->ConvertWithBackData(1.0);
721             res->Fill(theShape, 0);
722             theRes->ConvertToShape(theShape, fill_positive);
724             Path *originaux[1];
725             originaux[0] = res;
726             theRes->ConvertToForme(orig, 1, originaux);
728             delete theShape;
729             delete theRes;
730         }
732         if (orig->descr_cmd.size() <= 1) {
733             // ca a merd\8e, ou bien le resultat est vide
734             delete res;
735             delete orig;
736             g_free(style);
737             continue;
738         }
740         did = true;
742         // remember the position of the item
743         gint pos = SP_OBJECT_REPR(item)->position();
744         // remember parent
745         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
746         // remember id
747         char const *id = SP_OBJECT_REPR(item)->attribute("id");
749         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
751             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
753             // restore old style
754             repr->setAttribute("style", style);
756             // set old stroke style on fill
757             sp_repr_css_change(repr, ncss, "style");
759             sp_repr_css_attr_unref(ncss);
761             gchar *str = orig->svg_dump_path();
762             repr->setAttribute("d", str);
763             g_free(str);
766             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
768                 Inkscape::XML::Node *g_repr = sp_repr_new("svg:g");
770                 // add the group to the parent
771                 parent->appendChild(g_repr);
772                 // move to the saved position
773                 g_repr->setPosition(pos > 0 ? pos : 0);
775                 g_repr->appendChild(repr);
776                 repr->setAttribute("id", id);
777                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
778                 sp_item_write_transform(newitem, repr, transform);
780                 SPShape *shape = SP_SHAPE(item);
782                 for (NArtBpath* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
783                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
784                         if (sp_shape_marker_required (shape, m, bp)) {
786                             SPMarker* marker = SP_MARKER (shape->marker[m]);
787                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
789                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
791                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
792                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
793                             }
795                             // total marker transform
796                             tr = marker_item->transform * marker->c2p * tr * transform;
798                             if (SP_OBJECT_REPR(marker_item)) {
799                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate();
800                                 g_repr->appendChild(m_repr);
801                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
802                                 sp_item_write_transform(marker_item, m_repr, tr);
803                             }
804                         }
805                     }
806                 }
809                 selection->add(g_repr);
811                 Inkscape::GC::release(g_repr);
814             } else {
816                 // add the new repr to the parent
817                 parent->appendChild(repr);
819                 // move to the saved position
820                 repr->setPosition(pos > 0 ? pos : 0);
822                 repr->setAttribute("id", id);
824                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
825                 sp_item_write_transform(newitem, repr, transform);
827                 selection->add(repr);
829             }
831             Inkscape::GC::release(repr);
833             sp_curve_unref(curve);
834             selection->remove(item);
835             SP_OBJECT(item)->deleteObject(false);
837         }
839         delete res;
840         delete orig;
841         g_free(style);
843     }
845     if (did) {
846         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
847                          _("Convert stroke to path"));
848     } else {
849         // TRANSLATORS: "to outline" means "to convert stroke to path"
850         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
851         return;
852     }
856 void
857 sp_selected_path_offset()
859     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
861     sp_selected_path_do_offset(true, prefOffset);
863 void
864 sp_selected_path_inset()
866     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
868     sp_selected_path_do_offset(false, prefOffset);
871 void
872 sp_selected_path_offset_screen(double pixels)
874     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
877 void
878 sp_selected_path_inset_screen(double pixels)
880     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
884 void sp_selected_path_create_offset_object_zero()
886     sp_selected_path_create_offset_object(0, false);
889 void sp_selected_path_create_offset()
891     sp_selected_path_create_offset_object(1, false);
893 void sp_selected_path_create_inset()
895     sp_selected_path_create_offset_object(-1, false);
898 void sp_selected_path_create_updating_offset_object_zero()
900     sp_selected_path_create_offset_object(0, true);
903 void sp_selected_path_create_updating_offset()
905     sp_selected_path_create_offset_object(1, true);
907 void sp_selected_path_create_updating_inset()
909     sp_selected_path_create_offset_object(-1, true);
912 void
913 sp_selected_path_create_offset_object(int expand, bool updating)
915     Inkscape::Selection *selection;
916     Inkscape::XML::Node *repr;
917     SPItem *item;
918     SPCurve *curve;
919     gchar *style, *str;
920     SPDesktop *desktop;
921     float o_width, o_miter;
922     JoinType o_join;
923     ButtType o_butt;
925     curve = NULL;
927     desktop = SP_ACTIVE_DESKTOP;
929     selection = sp_desktop_selection(desktop);
931     item = selection->singleItem();
933     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
934         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
935         return;
936     }
937     if (SP_IS_SHAPE(item))
938     {
939         curve = sp_shape_get_curve(SP_SHAPE(item));
940         if (curve == NULL)
941             return;
942     }
943     if (SP_IS_TEXT(item))
944     {
945         curve = SP_TEXT(item)->getNormalizedBpath();
946         if (curve == NULL)
947             return;
948     }
950     NR::Matrix const transform(item->transform);
952     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
954     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
956     // remember the position of the item
957     gint pos = SP_OBJECT_REPR(item)->position();
958     // remember parent
959     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
961     {
962         SPStyle *i_style = SP_OBJECT(item)->style;
963         int jointype, captype;
965         jointype = i_style->stroke_linejoin.value;
966         captype = i_style->stroke_linecap.value;
967         o_width = i_style->stroke_width.computed;
968         if (jointype == SP_STROKE_LINEJOIN_MITER)
969         {
970             o_join = join_pointy;
971         }
972         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
973         {
974             o_join = join_round;
975         }
976         else
977         {
978             o_join = join_straight;
979         }
980         if (captype == SP_STROKE_LINECAP_SQUARE)
981         {
982             o_butt = butt_square;
983         }
984         else if (captype == SP_STROKE_LINECAP_ROUND)
985         {
986             o_butt = butt_round;
987         }
988         else
989         {
990             o_butt = butt_straight;
991         }
993         {
994             double prefOffset = 1.0;
995             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
996             o_width = prefOffset;
997         }
999         if (o_width < 0.01)
1000             o_width = 0.01;
1001         o_miter = i_style->stroke_miterlimit.value * o_width;
1002     }
1004     Path *orig = Path_for_item(item, true, false);
1005     if (orig == NULL)
1006     {
1007         g_free(style);
1008         sp_curve_unref(curve);
1009         return;
1010     }
1012     Path *res = new Path;
1013     res->SetBackData(false);
1015     {
1016         Shape *theShape = new Shape;
1017         Shape *theRes = new Shape;
1019         orig->ConvertWithBackData(1.0);
1020         orig->Fill(theShape, 0);
1022         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1023         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1024         if (val && strcmp(val, "nonzero") == 0)
1025         {
1026             theRes->ConvertToShape(theShape, fill_nonZero);
1027         }
1028         else if (val && strcmp(val, "evenodd") == 0)
1029         {
1030             theRes->ConvertToShape(theShape, fill_oddEven);
1031         }
1032         else
1033         {
1034             theRes->ConvertToShape(theShape, fill_nonZero);
1035         }
1037         Path *originaux[1];
1038         originaux[0] = orig;
1039         theRes->ConvertToForme(res, 1, originaux);
1041         delete theShape;
1042         delete theRes;
1043     }
1045     sp_curve_unref(curve);
1047     if (res->descr_cmd.size() <= 1)
1048     {
1049         // pas vraiment de points sur le resultat
1050         // donc il ne reste rien
1051         sp_document_done(sp_desktop_document(desktop), 
1052                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1053                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1054                          (updating ? _("Create linked offset")
1055                           : _("Create dynamic offset")));
1056         selection->clear();
1058         delete res;
1059         delete orig;
1060         g_free(style);
1061         return;
1062     }
1064     {
1065         gchar tstr[80];
1067         tstr[79] = '\0';
1069         repr = sp_repr_new("svg:path");
1070         repr->setAttribute("sodipodi:type", "inkscape:offset");
1071         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1072                                                           ? o_width
1073                                                           : expand < 0
1074                                                           ? -o_width
1075                                                           : 0 ));
1077         str = res->svg_dump_path();
1078         repr->setAttribute("inkscape:original", str);
1079         g_free(str);
1081         if ( updating ) {
1082             char const *id = SP_OBJECT(item)->repr->attribute("id");
1083             char const *uri = g_strdup_printf("#%s", id);
1084             repr->setAttribute("xlink:href", uri);
1085             g_free((void *) uri);
1086         } else {
1087             repr->setAttribute("inkscape:href", NULL);
1088         }
1090         repr->setAttribute("style", style);
1092         // add the new repr to the parent
1093         parent->appendChild(repr);
1095         // move to the saved position
1096         repr->setPosition(pos > 0 ? pos : 0);
1098         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1100         if ( updating ) {
1101             // on conserve l'original
1102             // we reapply the transform to the original (offset will feel it)
1103             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1104         } else {
1105             // delete original, apply the transform to the offset
1106             SP_OBJECT(item)->deleteObject(false);
1107             sp_item_write_transform(nitem, repr, transform);
1108         }
1110         // The object just created from a temporary repr is only a seed.
1111         // We need to invoke its write which will update its real repr (in particular adding d=)
1112         SP_OBJECT(nitem)->updateRepr();
1114         Inkscape::GC::release(repr);
1116         selection->set(nitem);
1117     }
1119     sp_document_done(sp_desktop_document(desktop), 
1120                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1121                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1122                      (updating ? _("Create linked offset")
1123                       : _("Create dynamic offset")));
1125     delete res;
1126     delete orig;
1128     g_free(style);
1142 void
1143 sp_selected_path_do_offset(bool expand, double prefOffset)
1145     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1147     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1149     if (selection->isEmpty()) {
1150         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1151         return;
1152     }
1154     bool did = false;
1156     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1157          items != NULL;
1158          items = items->next) {
1160         SPItem *item = (SPItem *) items->data;
1162         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1163             continue;
1165         SPCurve *curve = NULL;
1166         if (SP_IS_SHAPE(item)) {
1167             curve = sp_shape_get_curve(SP_SHAPE(item));
1168             if (curve == NULL)
1169                 continue;
1170         }
1171         if (SP_IS_TEXT(item)) {
1172             curve = SP_TEXT(item)->getNormalizedBpath();
1173             if (curve == NULL)
1174                 continue;
1175         }
1177         NR::Matrix const transform(item->transform);
1179         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1181         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1183         float o_width, o_miter;
1184         JoinType o_join;
1185         ButtType o_butt;
1187         {
1188             SPStyle *i_style = SP_OBJECT(item)->style;
1189             int jointype, captype;
1191             jointype = i_style->stroke_linejoin.value;
1192             captype = i_style->stroke_linecap.value;
1193             o_width = i_style->stroke_width.computed;
1195             switch (jointype) {
1196                 case SP_STROKE_LINEJOIN_MITER:
1197                     o_join = join_pointy;
1198                     break;
1199                 case SP_STROKE_LINEJOIN_ROUND:
1200                     o_join = join_round;
1201                     break;
1202                 default:
1203                     o_join = join_straight;
1204                     break;
1205             }
1207             switch (captype) {
1208                 case SP_STROKE_LINECAP_SQUARE:
1209                     o_butt = butt_square;
1210                     break;
1211                 case SP_STROKE_LINECAP_ROUND:
1212                     o_butt = butt_round;
1213                     break;
1214                 default:
1215                     o_butt = butt_straight;
1216                     break;
1217             }
1219             o_width = prefOffset;
1221             if (o_width < 0.1)
1222                 o_width = 0.1;
1223             o_miter = i_style->stroke_miterlimit.value * o_width;
1224         }
1226         Path *orig = Path_for_item(item, false);
1227         if (orig == NULL) {
1228             g_free(style);
1229             sp_curve_unref(curve);
1230             continue;
1231         }
1233         Path *res = new Path;
1234         res->SetBackData(false);
1236         {
1237             Shape *theShape = new Shape;
1238             Shape *theRes = new Shape;
1240             orig->ConvertWithBackData(0.03);
1241             orig->Fill(theShape, 0);
1243             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1244             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1245             if (val && strcmp(val, "nonzero") == 0)
1246             {
1247                 theRes->ConvertToShape(theShape, fill_nonZero);
1248             }
1249             else if (val && strcmp(val, "evenodd") == 0)
1250             {
1251                 theRes->ConvertToShape(theShape, fill_oddEven);
1252             }
1253             else
1254             {
1255                 theRes->ConvertToShape(theShape, fill_nonZero);
1256             }
1258             // et maintenant: offset
1259             // methode inexacte
1260 /*                      Path *originaux[1];
1261                         originaux[0] = orig;
1262                         theRes->ConvertToForme(res, 1, originaux);
1264                         if (expand) {
1265                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1266                         } else {
1267                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1268                         }
1270                         orig->ConvertWithBackData(1.0);
1271                         orig->Fill(theShape, 0);
1272                         theRes->ConvertToShape(theShape, fill_positive);
1273                         originaux[0] = orig;
1274                         theRes->ConvertToForme(res, 1, originaux);
1276                         if (o_width >= 0.5) {
1277                         //     res->Coalesce(1.0);
1278                         res->ConvertEvenLines(1.0);
1279                         res->Simplify(1.0);
1280                         } else {
1281                         //      res->Coalesce(o_width);
1282                         res->ConvertEvenLines(1.0*o_width);
1283                         res->Simplify(1.0 * o_width);
1284                         }    */
1285             // methode par makeoffset
1287             if (expand)
1288             {
1289                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1290             }
1291             else
1292             {
1293                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1294             }
1295             theRes->ConvertToShape(theShape, fill_positive);
1297             res->Reset();
1298             theRes->ConvertToForme(res);
1300             if (o_width >= 1.0)
1301             {
1302                 res->ConvertEvenLines(1.0);
1303                 res->Simplify(1.0);
1304             }
1305             else
1306             {
1307                 res->ConvertEvenLines(1.0*o_width);
1308                 res->Simplify(1.0 * o_width);
1309             }
1311             delete theShape;
1312             delete theRes;
1313         }
1315         did = true;
1317         sp_curve_unref(curve);
1318         // remember the position of the item
1319         gint pos = SP_OBJECT_REPR(item)->position();
1320         // remember parent
1321         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1322         // remember id
1323         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1325         selection->remove(item);
1326         SP_OBJECT(item)->deleteObject(false);
1328         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1330             gchar tstr[80];
1332             tstr[79] = '\0';
1334             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
1336             repr->setAttribute("style", style);
1338             gchar *str = res->svg_dump_path();
1339             repr->setAttribute("d", str);
1340             g_free(str);
1342             // add the new repr to the parent
1343             parent->appendChild(repr);
1345             // move to the saved position
1346             repr->setPosition(pos > 0 ? pos : 0);
1348             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1350             // reapply the transform
1351             sp_item_write_transform(newitem, repr, transform);
1353             repr->setAttribute("id", id);
1355             selection->add(repr);
1357             Inkscape::GC::release(repr);
1358         }
1360         delete orig;
1361         delete res;
1362     }
1364     if (did) {
1365         sp_document_done(sp_desktop_document(desktop), 
1366                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1367                          (expand ? _("Outset path") : _("Inset path")));
1368     } else {
1369         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1370         return;
1371     }
1375 static bool
1376 sp_selected_path_simplify_items(SPDesktop *desktop,
1377                                 Inkscape::Selection *selection, GSList *items,
1378                                 float threshold,  bool justCoalesce,
1379                                 float angleLimit, bool breakableAngles,
1380                                 bool modifySelection);
1383 //return true if we changed something, else false
1384 bool
1385 sp_selected_path_simplify_item(SPDesktop *desktop,
1386                  Inkscape::Selection *selection, SPItem *item,
1387                  float threshold,  bool justCoalesce,
1388                  float angleLimit, bool breakableAngles,
1389                  gdouble size,     bool modifySelection)
1391     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1392         return false;
1394     //If this is a group, do the children instead
1395     if (SP_IS_GROUP(item)) {
1396         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1397         
1398         return sp_selected_path_simplify_items(desktop, selection, items,
1399                                                threshold, justCoalesce,
1400                                                angleLimit, breakableAngles,
1401                                                false);
1402     }
1405     SPCurve *curve = NULL;
1407     if (SP_IS_SHAPE(item)) {
1408         curve = sp_shape_get_curve(SP_SHAPE(item));
1409         if (!curve)
1410             return false;
1411     }
1413     if (SP_IS_TEXT(item)) {
1414         curve = SP_TEXT(item)->getNormalizedBpath();
1415         if (!curve)
1416             return false;
1417     }
1419     // save the transform, to re-apply it after simplification
1420     NR::Matrix const transform(item->transform);
1422     /*
1423        reset the transform, effectively transforming the item by transform.inverse();
1424        this is necessary so that the item is transformed twice back and forth,
1425        allowing all compensations to cancel out regardless of the preferences
1426     */
1427     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1429     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1430     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1431     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1433     Path *orig = Path_for_item(item, false);
1434     if (orig == NULL) {
1435         g_free(style);
1436         sp_curve_unref(curve);
1437         return false;
1438     }
1440     sp_curve_unref(curve);
1441     // remember the position of the item
1442     gint pos = SP_OBJECT_REPR(item)->position();
1443     // remember parent
1444     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1445     // remember id
1446     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1448     //If a group was selected, to not change the selection list
1449     if (modifySelection)
1450         selection->remove(item);
1452     SP_OBJECT(item)->deleteObject(false);
1454     if ( justCoalesce ) {
1455         orig->Coalesce(threshold * size);
1456     } else {
1457         orig->ConvertEvenLines(threshold * size);
1458         orig->Simplify(threshold * size);
1459     }
1461     Inkscape::XML::Node *repr = sp_repr_new("svg:path");
1463     // restore style, mask and clip-path
1464     repr->setAttribute("style", style);
1465     g_free(style);
1467     if ( mask ) {
1468         repr->setAttribute("mask", mask);
1469         g_free(mask);
1470     }
1472     if ( clip_path ) {
1473         repr->setAttribute("clip-path", clip_path);
1474         g_free(clip_path);
1475     }
1477     // path
1478     gchar *str = orig->svg_dump_path();
1479     repr->setAttribute("d", str);
1480     g_free(str);
1482     // restore id
1483     repr->setAttribute("id", id);
1485     // add the new repr to the parent
1486     parent->appendChild(repr);
1488     // move to the saved position
1489     repr->setPosition(pos > 0 ? pos : 0);
1491     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1493     // reapply the transform
1494     sp_item_write_transform(newitem, repr, transform);
1496     //If we are not in a selected group
1497     if (modifySelection)
1498         selection->add(repr);
1500     Inkscape::GC::release(repr);
1502     // clean up
1503     if (orig) delete orig;
1505     return true;
1509 bool
1510 sp_selected_path_simplify_items(SPDesktop *desktop,
1511                                 Inkscape::Selection *selection, GSList *items,
1512                                 float threshold,  bool justCoalesce,
1513                                 float angleLimit, bool breakableAngles,
1514                                 bool modifySelection)
1516   bool simplifyIndividualPaths =
1517     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1518   
1519   gchar *simplificationType;
1520   if (simplifyIndividualPaths) {
1521     simplificationType = "individual paths";
1522   } else {
1523     simplificationType = "as a group";
1524   }
1526   bool didSomething = false;
1528   NR::Rect selectionBbox = selection->bounds();
1529   gdouble selectionSize  = L2(selectionBbox.dimensions());
1531   gdouble simplifySize  = selectionSize;
1532   
1533   int pathsSimplified = 0;
1534   int totalPathCount  = g_slist_length(items);
1535   
1536   desktop->disableInteraction();
1537   
1538   for (; items != NULL; items = items->next) {
1539       SPItem *item = (SPItem *) items->data;
1540       
1541       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1542           continue;
1544       if (simplifyIndividualPaths) {
1545           NR::Rect itemBbox = item->invokeBbox(sp_item_i2d_affine(item));        
1546           simplifySize      = L2(itemBbox.dimensions());
1547       }
1550       pathsSimplified++;
1552       if (pathsSimplified % 20 == 0) {
1553         gchar *message = g_strdup_printf(_("Simplifying %s - <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1554         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, message);
1555         desktop->updateCanvasNow();
1556       }
1558       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1559                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1560   }
1562   desktop->enableInteraction();
1563   
1564   if (pathsSimplified > 20) {
1565     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("Done - <b>%d</b> paths simplified."), pathsSimplified));
1566   }
1567   
1568   return didSomething;
1571 void
1572 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1573                        float angleLimit, bool breakableAngles)
1575     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1577     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1579     if (selection->isEmpty()) {
1580         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1581                          _("Select <b>path(s)</b> to simplify."));
1582         return;
1583     }
1585     GSList *items = g_slist_copy((GSList *) selection->itemList());
1587     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1588                                                         items, threshold,
1589                                                         justCoalesce,
1590                                                         angleLimit,
1591                                                         breakableAngles, true);
1593     if (didSomething)
1594         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1595                          _("Simplify"));
1596     else
1597         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1602 // globals for keeping track of accelerated simplify
1603 static double previousTime      = 0.0;
1604 static gdouble simplifyMultiply = 1.0;
1606 void
1607 sp_selected_path_simplify(void)
1609     gdouble simplifyThreshold =
1610         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1611     bool simplifyJustCoalesce =
1612         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1614     //Get the current time
1615     GTimeVal currentTimeVal;
1616     g_get_current_time(&currentTimeVal);
1617     double currentTime = currentTimeVal.tv_sec * 1000000 +
1618                 currentTimeVal.tv_usec;
1620     //Was the previous call to this function recent? (<0.5 sec)
1621     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1623         // add to the threshold 1/2 of its original value
1624         simplifyMultiply  += 0.5;
1625         simplifyThreshold *= simplifyMultiply;
1627     } else {
1628         // reset to the default
1629         simplifyMultiply = 1;
1630     }
1632     //remember time for next call
1633     previousTime = currentTime;
1635     //g_print("%g\n", simplify_threshold);
1637     //Make the actual call
1638     sp_selected_path_simplify_selection(simplifyThreshold,
1639                       simplifyJustCoalesce, 0.0, false);
1644 // fonctions utilitaires
1646 bool
1647 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1649     if (who == NULL || a == NULL)
1650         return false;
1651     if (who == a)
1652         return true;
1653     return Ancetre(sp_repr_parent(a), who);
1656 Path *
1657 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1659     SPCurve *curve;
1661     if (!item)
1662         return NULL;
1664     if (SP_IS_SHAPE(item))
1665     {
1666         curve = sp_shape_get_curve(SP_SHAPE(item));
1667     }
1668     else if (SP_IS_TEXT(item))
1669     {
1670         curve = SP_TEXT(item)->getNormalizedBpath();
1671     }
1672     else
1673     {
1674         curve = NULL;
1675     }
1677     if (!curve)
1678         return NULL;
1679     NArtBpath *bpath = SP_CURVE_BPATH(curve);
1680     if (bpath == NULL)
1681         return NULL;
1683     if ( doTransformation ) {
1684         if (transformFull)
1685             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), sp_item_i2doc_affine(item));
1686         else
1687             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), item->transform);
1688         sp_curve_unref(curve);
1689         curve=NULL;
1690     } else {
1691         bpath=SP_CURVE_BPATH(curve);
1692     }
1694     Path *dest = new Path;
1695     dest->SetBackData(false);
1696     {
1697         int   i;
1698         bool  closed = false;
1699         float lastX  = 0.0;
1700         float lastY  = 0.0;
1702         for (i = 0; bpath[i].code != NR_END; i++) {
1703             switch (bpath[i].code) {
1704                 case NR_LINETO:
1705                     lastX = bpath[i].x3;
1706                     lastY = bpath[i].y3;
1707                     {
1708                         NR::Point tmp(lastX, lastY);
1709                         dest->LineTo(tmp);
1710                     }
1711                     break;
1713                 case NR_CURVETO:
1714                 {
1715                     NR::Point tmp, tms, tme;
1716                     tmp[0]=bpath[i].x3;
1717                     tmp[1]=bpath[i].y3;
1718                     tms[0]=3 * (bpath[i].x1 - lastX);
1719                     tms[1]=3 * (bpath[i].y1 - lastY);
1720                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1721                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1722                     dest->CubicTo(tmp,tms,tme);
1723                 }
1724                 lastX = bpath[i].x3;
1725                 lastY = bpath[i].y3;
1726                 break;
1728                 case NR_MOVETO_OPEN:
1729                 case NR_MOVETO:
1730                     if (closed)
1731                         dest->Close();
1732                     closed = (bpath[i].code == NR_MOVETO);
1733                     lastX = bpath[i].x3;
1734                     lastY = bpath[i].y3;
1735                     {
1736                         NR::Point  tmp(lastX, lastY);
1737                         dest->MoveTo(tmp);
1738                     }
1739                     break;
1740                 default:
1741                     break;
1742             }
1743         }
1744         if (closed)
1745             dest->Close();
1746     }
1748     if ( doTransformation ) {
1749         if ( bpath ) g_free(bpath);
1750     } else {
1751         sp_curve_unref(curve);
1752     }
1753     return dest;
1756 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p)
1758     //get nearest position on path
1759     Path::cut_position pos = path->PointToCurvilignPosition(p);
1760     return pos;
1763 NR::Point get_point_on_Path(Path *path, int piece, double t)
1765     NR::Point p;
1766     path->PointAt(piece, t, p);
1767     return p;
1771 /*
1772   Local Variables:
1773   mode:c++
1774   c-file-style:"stroustrup"
1775   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1776   indent-tabs-mode:nil
1777   fill-column:99
1778   End:
1779 */
1780 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :