Code

Renaming sp-marker.* to marker.*
[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 "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 && bop != bool_op_union) {
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;
634         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
635         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
637         float o_width, o_miter;
638         JoinType o_join;
639         ButtType o_butt;
641         {
642             int jointype, captype;
644             jointype = i_style->stroke_linejoin.computed;
645             captype = i_style->stroke_linecap.computed;
646             o_width = i_style->stroke_width.computed;
648             switch (jointype) {
649                 case SP_STROKE_LINEJOIN_MITER:
650                     o_join = join_pointy;
651                     break;
652                 case SP_STROKE_LINEJOIN_ROUND:
653                     o_join = join_round;
654                     break;
655                 default:
656                     o_join = join_straight;
657                     break;
658             }
660             switch (captype) {
661                 case SP_STROKE_LINECAP_SQUARE:
662                     o_butt = butt_square;
663                     break;
664                 case SP_STROKE_LINECAP_ROUND:
665                     o_butt = butt_round;
666                     break;
667                 default:
668                     o_butt = butt_straight;
669                     break;
670             }
672             if (o_width < 0.1)
673                 o_width = 0.1;
674             o_miter = i_style->stroke_miterlimit.value * o_width;
675         }
677         Path *orig = Path_for_item(item, false);
678         if (orig == NULL) {
679             g_free(style);
680             sp_curve_unref(curve);
681             continue;
682         }
684         Path *res = new Path;
685         res->SetBackData(false);
687         if (i_style->stroke_dash.n_dash) {
688             // For dashed strokes, use Stroke method, because Outline can't do dashes
689             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
691             orig->ConvertWithBackData(0.1);
693             orig->DashPolylineFromStyle(i_style, scale, 0);
695             Shape* theShape = new Shape;
696             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
697                          0.5 * o_miter);
698             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
700             Shape *theRes = new Shape;
702             theRes->ConvertToShape(theShape, fill_positive);
704             Path *originaux[1];
705             originaux[0] = res;
706             theRes->ConvertToForme(orig, 1, originaux);
708             res->Coalesce(5.0);
710             delete theShape;
711             delete theRes;
713         } else {
715             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
717             orig->Coalesce(0.5 * o_width);
719             Shape *theShape = new Shape;
720             Shape *theRes = new Shape;
722             res->ConvertWithBackData(1.0);
723             res->Fill(theShape, 0);
724             theRes->ConvertToShape(theShape, fill_positive);
726             Path *originaux[1];
727             originaux[0] = res;
728             theRes->ConvertToForme(orig, 1, originaux);
730             delete theShape;
731             delete theRes;
732         }
734         if (orig->descr_cmd.size() <= 1) {
735             // ca a merd\8e, ou bien le resultat est vide
736             delete res;
737             delete orig;
738             g_free(style);
739             continue;
740         }
742         did = true;
744         // remember the position of the item
745         gint pos = SP_OBJECT_REPR(item)->position();
746         // remember parent
747         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
748         // remember id
749         char const *id = SP_OBJECT_REPR(item)->attribute("id");
751         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
753             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
755             // restore old style
756             repr->setAttribute("style", style);
758             // set old stroke style on fill
759             sp_repr_css_change(repr, ncss, "style");
761             sp_repr_css_attr_unref(ncss);
763             gchar *str = orig->svg_dump_path();
764             repr->setAttribute("d", str);
765             g_free(str);
767             if (mask)
768                 repr->setAttribute("mask", mask);
769             if (clip_path)
770                 repr->setAttribute("clip-path", clip_path);
772             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
774                 Inkscape::XML::Node *g_repr = sp_repr_new("svg:g");
776                 // add the group to the parent
777                 parent->appendChild(g_repr);
778                 // move to the saved position
779                 g_repr->setPosition(pos > 0 ? pos : 0);
781                 g_repr->appendChild(repr);
782                 repr->setAttribute("id", id);
783                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
784                 sp_item_write_transform(newitem, repr, transform);
786                 SPShape *shape = SP_SHAPE(item);
788                 for (NArtBpath* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
789                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
790                         if (sp_shape_marker_required (shape, m, bp)) {
792                             SPMarker* marker = SP_MARKER (shape->marker[m]);
793                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
795                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
797                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
798                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
799                             }
801                             // total marker transform
802                             tr = marker_item->transform * marker->c2p * tr * transform;
804                             if (SP_OBJECT_REPR(marker_item)) {
805                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate();
806                                 g_repr->appendChild(m_repr);
807                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
808                                 sp_item_write_transform(marker_item, m_repr, tr);
809                             }
810                         }
811                     }
812                 }
815                 selection->add(g_repr);
817                 Inkscape::GC::release(g_repr);
820             } else {
822                 // add the new repr to the parent
823                 parent->appendChild(repr);
825                 // move to the saved position
826                 repr->setPosition(pos > 0 ? pos : 0);
828                 repr->setAttribute("id", id);
830                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
831                 sp_item_write_transform(newitem, repr, transform);
833                 selection->add(repr);
835             }
837             Inkscape::GC::release(repr);
839             sp_curve_unref(curve);
840             selection->remove(item);
841             SP_OBJECT(item)->deleteObject(false);
843         }
845         delete res;
846         delete orig;
847         g_free(style);
849     }
851     if (did) {
852         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
853                          _("Convert stroke to path"));
854     } else {
855         // TRANSLATORS: "to outline" means "to convert stroke to path"
856         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
857         return;
858     }
862 void
863 sp_selected_path_offset()
865     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
867     sp_selected_path_do_offset(true, prefOffset);
869 void
870 sp_selected_path_inset()
872     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
874     sp_selected_path_do_offset(false, prefOffset);
877 void
878 sp_selected_path_offset_screen(double pixels)
880     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
883 void
884 sp_selected_path_inset_screen(double pixels)
886     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
890 void sp_selected_path_create_offset_object_zero()
892     sp_selected_path_create_offset_object(0, false);
895 void sp_selected_path_create_offset()
897     sp_selected_path_create_offset_object(1, false);
899 void sp_selected_path_create_inset()
901     sp_selected_path_create_offset_object(-1, false);
904 void sp_selected_path_create_updating_offset_object_zero()
906     sp_selected_path_create_offset_object(0, true);
909 void sp_selected_path_create_updating_offset()
911     sp_selected_path_create_offset_object(1, true);
913 void sp_selected_path_create_updating_inset()
915     sp_selected_path_create_offset_object(-1, true);
918 void
919 sp_selected_path_create_offset_object(int expand, bool updating)
921     Inkscape::Selection *selection;
922     Inkscape::XML::Node *repr;
923     SPItem *item;
924     SPCurve *curve;
925     gchar *style, *str;
926     SPDesktop *desktop;
927     float o_width, o_miter;
928     JoinType o_join;
929     ButtType o_butt;
931     curve = NULL;
933     desktop = SP_ACTIVE_DESKTOP;
935     selection = sp_desktop_selection(desktop);
937     item = selection->singleItem();
939     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
940         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
941         return;
942     }
943     if (SP_IS_SHAPE(item))
944     {
945         curve = sp_shape_get_curve(SP_SHAPE(item));
946         if (curve == NULL)
947             return;
948     }
949     if (SP_IS_TEXT(item))
950     {
951         curve = SP_TEXT(item)->getNormalizedBpath();
952         if (curve == NULL)
953             return;
954     }
956     NR::Matrix const transform(item->transform);
958     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
960     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
962     // remember the position of the item
963     gint pos = SP_OBJECT_REPR(item)->position();
964     // remember parent
965     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
967     {
968         SPStyle *i_style = SP_OBJECT(item)->style;
969         int jointype, captype;
971         jointype = i_style->stroke_linejoin.value;
972         captype = i_style->stroke_linecap.value;
973         o_width = i_style->stroke_width.computed;
974         if (jointype == SP_STROKE_LINEJOIN_MITER)
975         {
976             o_join = join_pointy;
977         }
978         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
979         {
980             o_join = join_round;
981         }
982         else
983         {
984             o_join = join_straight;
985         }
986         if (captype == SP_STROKE_LINECAP_SQUARE)
987         {
988             o_butt = butt_square;
989         }
990         else if (captype == SP_STROKE_LINECAP_ROUND)
991         {
992             o_butt = butt_round;
993         }
994         else
995         {
996             o_butt = butt_straight;
997         }
999         {
1000             double prefOffset = 1.0;
1001             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1002             o_width = prefOffset;
1003         }
1005         if (o_width < 0.01)
1006             o_width = 0.01;
1007         o_miter = i_style->stroke_miterlimit.value * o_width;
1008     }
1010     Path *orig = Path_for_item(item, true, false);
1011     if (orig == NULL)
1012     {
1013         g_free(style);
1014         sp_curve_unref(curve);
1015         return;
1016     }
1018     Path *res = new Path;
1019     res->SetBackData(false);
1021     {
1022         Shape *theShape = new Shape;
1023         Shape *theRes = new Shape;
1025         orig->ConvertWithBackData(1.0);
1026         orig->Fill(theShape, 0);
1028         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1029         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1030         if (val && strcmp(val, "nonzero") == 0)
1031         {
1032             theRes->ConvertToShape(theShape, fill_nonZero);
1033         }
1034         else if (val && strcmp(val, "evenodd") == 0)
1035         {
1036             theRes->ConvertToShape(theShape, fill_oddEven);
1037         }
1038         else
1039         {
1040             theRes->ConvertToShape(theShape, fill_nonZero);
1041         }
1043         Path *originaux[1];
1044         originaux[0] = orig;
1045         theRes->ConvertToForme(res, 1, originaux);
1047         delete theShape;
1048         delete theRes;
1049     }
1051     sp_curve_unref(curve);
1053     if (res->descr_cmd.size() <= 1)
1054     {
1055         // pas vraiment de points sur le resultat
1056         // donc il ne reste rien
1057         sp_document_done(sp_desktop_document(desktop), 
1058                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1059                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1060                          (updating ? _("Create linked offset")
1061                           : _("Create dynamic offset")));
1062         selection->clear();
1064         delete res;
1065         delete orig;
1066         g_free(style);
1067         return;
1068     }
1070     {
1071         gchar tstr[80];
1073         tstr[79] = '\0';
1075         repr = sp_repr_new("svg:path");
1076         repr->setAttribute("sodipodi:type", "inkscape:offset");
1077         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1078                                                           ? o_width
1079                                                           : expand < 0
1080                                                           ? -o_width
1081                                                           : 0 ));
1083         str = res->svg_dump_path();
1084         repr->setAttribute("inkscape:original", str);
1085         g_free(str);
1087         if ( updating ) {
1088             char const *id = SP_OBJECT(item)->repr->attribute("id");
1089             char const *uri = g_strdup_printf("#%s", id);
1090             repr->setAttribute("xlink:href", uri);
1091             g_free((void *) uri);
1092         } else {
1093             repr->setAttribute("inkscape:href", NULL);
1094         }
1096         repr->setAttribute("style", style);
1098         // add the new repr to the parent
1099         parent->appendChild(repr);
1101         // move to the saved position
1102         repr->setPosition(pos > 0 ? pos : 0);
1104         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1106         if ( updating ) {
1107             // on conserve l'original
1108             // we reapply the transform to the original (offset will feel it)
1109             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1110         } else {
1111             // delete original, apply the transform to the offset
1112             SP_OBJECT(item)->deleteObject(false);
1113             sp_item_write_transform(nitem, repr, transform);
1114         }
1116         // The object just created from a temporary repr is only a seed.
1117         // We need to invoke its write which will update its real repr (in particular adding d=)
1118         SP_OBJECT(nitem)->updateRepr();
1120         Inkscape::GC::release(repr);
1122         selection->set(nitem);
1123     }
1125     sp_document_done(sp_desktop_document(desktop), 
1126                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1127                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1128                      (updating ? _("Create linked offset")
1129                       : _("Create dynamic offset")));
1131     delete res;
1132     delete orig;
1134     g_free(style);
1148 void
1149 sp_selected_path_do_offset(bool expand, double prefOffset)
1151     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1153     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1155     if (selection->isEmpty()) {
1156         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1157         return;
1158     }
1160     bool did = false;
1162     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1163          items != NULL;
1164          items = items->next) {
1166         SPItem *item = (SPItem *) items->data;
1168         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1169             continue;
1171         SPCurve *curve = NULL;
1172         if (SP_IS_SHAPE(item)) {
1173             curve = sp_shape_get_curve(SP_SHAPE(item));
1174             if (curve == NULL)
1175                 continue;
1176         }
1177         if (SP_IS_TEXT(item)) {
1178             curve = SP_TEXT(item)->getNormalizedBpath();
1179             if (curve == NULL)
1180                 continue;
1181         }
1183         NR::Matrix const transform(item->transform);
1185         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1187         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1189         float o_width, o_miter;
1190         JoinType o_join;
1191         ButtType o_butt;
1193         {
1194             SPStyle *i_style = SP_OBJECT(item)->style;
1195             int jointype, captype;
1197             jointype = i_style->stroke_linejoin.value;
1198             captype = i_style->stroke_linecap.value;
1199             o_width = i_style->stroke_width.computed;
1201             switch (jointype) {
1202                 case SP_STROKE_LINEJOIN_MITER:
1203                     o_join = join_pointy;
1204                     break;
1205                 case SP_STROKE_LINEJOIN_ROUND:
1206                     o_join = join_round;
1207                     break;
1208                 default:
1209                     o_join = join_straight;
1210                     break;
1211             }
1213             switch (captype) {
1214                 case SP_STROKE_LINECAP_SQUARE:
1215                     o_butt = butt_square;
1216                     break;
1217                 case SP_STROKE_LINECAP_ROUND:
1218                     o_butt = butt_round;
1219                     break;
1220                 default:
1221                     o_butt = butt_straight;
1222                     break;
1223             }
1225             o_width = prefOffset;
1227             if (o_width < 0.1)
1228                 o_width = 0.1;
1229             o_miter = i_style->stroke_miterlimit.value * o_width;
1230         }
1232         Path *orig = Path_for_item(item, false);
1233         if (orig == NULL) {
1234             g_free(style);
1235             sp_curve_unref(curve);
1236             continue;
1237         }
1239         Path *res = new Path;
1240         res->SetBackData(false);
1242         {
1243             Shape *theShape = new Shape;
1244             Shape *theRes = new Shape;
1246             orig->ConvertWithBackData(0.03);
1247             orig->Fill(theShape, 0);
1249             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1250             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1251             if (val && strcmp(val, "nonzero") == 0)
1252             {
1253                 theRes->ConvertToShape(theShape, fill_nonZero);
1254             }
1255             else if (val && strcmp(val, "evenodd") == 0)
1256             {
1257                 theRes->ConvertToShape(theShape, fill_oddEven);
1258             }
1259             else
1260             {
1261                 theRes->ConvertToShape(theShape, fill_nonZero);
1262             }
1264             // et maintenant: offset
1265             // methode inexacte
1266 /*                      Path *originaux[1];
1267                         originaux[0] = orig;
1268                         theRes->ConvertToForme(res, 1, originaux);
1270                         if (expand) {
1271                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1272                         } else {
1273                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1274                         }
1276                         orig->ConvertWithBackData(1.0);
1277                         orig->Fill(theShape, 0);
1278                         theRes->ConvertToShape(theShape, fill_positive);
1279                         originaux[0] = orig;
1280                         theRes->ConvertToForme(res, 1, originaux);
1282                         if (o_width >= 0.5) {
1283                         //     res->Coalesce(1.0);
1284                         res->ConvertEvenLines(1.0);
1285                         res->Simplify(1.0);
1286                         } else {
1287                         //      res->Coalesce(o_width);
1288                         res->ConvertEvenLines(1.0*o_width);
1289                         res->Simplify(1.0 * o_width);
1290                         }    */
1291             // methode par makeoffset
1293             if (expand)
1294             {
1295                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1296             }
1297             else
1298             {
1299                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1300             }
1301             theRes->ConvertToShape(theShape, fill_positive);
1303             res->Reset();
1304             theRes->ConvertToForme(res);
1306             if (o_width >= 1.0)
1307             {
1308                 res->ConvertEvenLines(1.0);
1309                 res->Simplify(1.0);
1310             }
1311             else
1312             {
1313                 res->ConvertEvenLines(1.0*o_width);
1314                 res->Simplify(1.0 * o_width);
1315             }
1317             delete theShape;
1318             delete theRes;
1319         }
1321         did = true;
1323         sp_curve_unref(curve);
1324         // remember the position of the item
1325         gint pos = SP_OBJECT_REPR(item)->position();
1326         // remember parent
1327         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1328         // remember id
1329         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1331         selection->remove(item);
1332         SP_OBJECT(item)->deleteObject(false);
1334         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1336             gchar tstr[80];
1338             tstr[79] = '\0';
1340             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
1342             repr->setAttribute("style", style);
1344             gchar *str = res->svg_dump_path();
1345             repr->setAttribute("d", str);
1346             g_free(str);
1348             // add the new repr to the parent
1349             parent->appendChild(repr);
1351             // move to the saved position
1352             repr->setPosition(pos > 0 ? pos : 0);
1354             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1356             // reapply the transform
1357             sp_item_write_transform(newitem, repr, transform);
1359             repr->setAttribute("id", id);
1361             selection->add(repr);
1363             Inkscape::GC::release(repr);
1364         }
1366         delete orig;
1367         delete res;
1368     }
1370     if (did) {
1371         sp_document_done(sp_desktop_document(desktop), 
1372                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1373                          (expand ? _("Outset path") : _("Inset path")));
1374     } else {
1375         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1376         return;
1377     }
1381 static bool
1382 sp_selected_path_simplify_items(SPDesktop *desktop,
1383                                 Inkscape::Selection *selection, GSList *items,
1384                                 float threshold,  bool justCoalesce,
1385                                 float angleLimit, bool breakableAngles,
1386                                 bool modifySelection);
1389 //return true if we changed something, else false
1390 bool
1391 sp_selected_path_simplify_item(SPDesktop *desktop,
1392                  Inkscape::Selection *selection, SPItem *item,
1393                  float threshold,  bool justCoalesce,
1394                  float angleLimit, bool breakableAngles,
1395                  gdouble size,     bool modifySelection)
1397     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1398         return false;
1400     //If this is a group, do the children instead
1401     if (SP_IS_GROUP(item)) {
1402         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1403         
1404         return sp_selected_path_simplify_items(desktop, selection, items,
1405                                                threshold, justCoalesce,
1406                                                angleLimit, breakableAngles,
1407                                                false);
1408     }
1411     SPCurve *curve = NULL;
1413     if (SP_IS_SHAPE(item)) {
1414         curve = sp_shape_get_curve(SP_SHAPE(item));
1415         if (!curve)
1416             return false;
1417     }
1419     if (SP_IS_TEXT(item)) {
1420         curve = SP_TEXT(item)->getNormalizedBpath();
1421         if (!curve)
1422             return false;
1423     }
1425     // save the transform, to re-apply it after simplification
1426     NR::Matrix const transform(item->transform);
1428     /*
1429        reset the transform, effectively transforming the item by transform.inverse();
1430        this is necessary so that the item is transformed twice back and forth,
1431        allowing all compensations to cancel out regardless of the preferences
1432     */
1433     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1435     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1436     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1437     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1439     Path *orig = Path_for_item(item, false);
1440     if (orig == NULL) {
1441         g_free(style);
1442         sp_curve_unref(curve);
1443         return false;
1444     }
1446     sp_curve_unref(curve);
1447     // remember the position of the item
1448     gint pos = SP_OBJECT_REPR(item)->position();
1449     // remember parent
1450     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1451     // remember id
1452     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1454     //If a group was selected, to not change the selection list
1455     if (modifySelection)
1456         selection->remove(item);
1458     SP_OBJECT(item)->deleteObject(false);
1460     if ( justCoalesce ) {
1461         orig->Coalesce(threshold * size);
1462     } else {
1463         orig->ConvertEvenLines(threshold * size);
1464         orig->Simplify(threshold * size);
1465     }
1467     Inkscape::XML::Node *repr = sp_repr_new("svg:path");
1469     // restore style, mask and clip-path
1470     repr->setAttribute("style", style);
1471     g_free(style);
1473     if ( mask ) {
1474         repr->setAttribute("mask", mask);
1475         g_free(mask);
1476     }
1478     if ( clip_path ) {
1479         repr->setAttribute("clip-path", clip_path);
1480         g_free(clip_path);
1481     }
1483     // path
1484     gchar *str = orig->svg_dump_path();
1485     repr->setAttribute("d", str);
1486     g_free(str);
1488     // restore id
1489     repr->setAttribute("id", id);
1491     // add the new repr to the parent
1492     parent->appendChild(repr);
1494     // move to the saved position
1495     repr->setPosition(pos > 0 ? pos : 0);
1497     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1499     // reapply the transform
1500     sp_item_write_transform(newitem, repr, transform);
1502     //If we are not in a selected group
1503     if (modifySelection)
1504         selection->add(repr);
1506     Inkscape::GC::release(repr);
1508     // clean up
1509     if (orig) delete orig;
1511     return true;
1515 bool
1516 sp_selected_path_simplify_items(SPDesktop *desktop,
1517                                 Inkscape::Selection *selection, GSList *items,
1518                                 float threshold,  bool justCoalesce,
1519                                 float angleLimit, bool breakableAngles,
1520                                 bool modifySelection)
1522   bool simplifyIndividualPaths =
1523     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1524   
1525   gchar *simplificationType;
1526   if (simplifyIndividualPaths) {
1527     simplificationType = "individual paths";
1528   } else {
1529     simplificationType = "as a group";
1530   }
1532   bool didSomething = false;
1534   NR::Rect selectionBbox = selection->bounds();
1535   gdouble selectionSize  = L2(selectionBbox.dimensions());
1537   gdouble simplifySize  = selectionSize;
1538   
1539   int pathsSimplified = 0;
1540   int totalPathCount  = g_slist_length(items);
1541   
1542   desktop->disableInteraction();
1543   
1544   for (; items != NULL; items = items->next) {
1545       SPItem *item = (SPItem *) items->data;
1546       
1547       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1548           continue;
1550       if (simplifyIndividualPaths) {
1551           NR::Rect itemBbox = item->invokeBbox(sp_item_i2d_affine(item));        
1552           simplifySize      = L2(itemBbox.dimensions());
1553       }
1556       pathsSimplified++;
1558       if (pathsSimplified % 20 == 0) {
1559         gchar *message = g_strdup_printf(_("Simplifying %s - <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1560         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, message);
1561         desktop->updateCanvasNow();
1562       }
1564       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1565                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1566   }
1568   desktop->enableInteraction();
1569   
1570   if (pathsSimplified > 20) {
1571     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("Done - <b>%d</b> paths simplified."), pathsSimplified));
1572   }
1573   
1574   return didSomething;
1577 void
1578 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1579                        float angleLimit, bool breakableAngles)
1581     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1583     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1585     if (selection->isEmpty()) {
1586         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1587                          _("Select <b>path(s)</b> to simplify."));
1588         return;
1589     }
1591     GSList *items = g_slist_copy((GSList *) selection->itemList());
1593     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1594                                                         items, threshold,
1595                                                         justCoalesce,
1596                                                         angleLimit,
1597                                                         breakableAngles, true);
1599     if (didSomething)
1600         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1601                          _("Simplify"));
1602     else
1603         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1608 // globals for keeping track of accelerated simplify
1609 static double previousTime      = 0.0;
1610 static gdouble simplifyMultiply = 1.0;
1612 void
1613 sp_selected_path_simplify(void)
1615     gdouble simplifyThreshold =
1616         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1617     bool simplifyJustCoalesce =
1618         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1620     //Get the current time
1621     GTimeVal currentTimeVal;
1622     g_get_current_time(&currentTimeVal);
1623     double currentTime = currentTimeVal.tv_sec * 1000000 +
1624                 currentTimeVal.tv_usec;
1626     //Was the previous call to this function recent? (<0.5 sec)
1627     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1629         // add to the threshold 1/2 of its original value
1630         simplifyMultiply  += 0.5;
1631         simplifyThreshold *= simplifyMultiply;
1633     } else {
1634         // reset to the default
1635         simplifyMultiply = 1;
1636     }
1638     //remember time for next call
1639     previousTime = currentTime;
1641     //g_print("%g\n", simplify_threshold);
1643     //Make the actual call
1644     sp_selected_path_simplify_selection(simplifyThreshold,
1645                       simplifyJustCoalesce, 0.0, false);
1650 // fonctions utilitaires
1652 bool
1653 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1655     if (who == NULL || a == NULL)
1656         return false;
1657     if (who == a)
1658         return true;
1659     return Ancetre(sp_repr_parent(a), who);
1662 Path *
1663 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1665     SPCurve *curve;
1667     if (!item)
1668         return NULL;
1670     if (SP_IS_SHAPE(item))
1671     {
1672         curve = sp_shape_get_curve(SP_SHAPE(item));
1673     }
1674     else if (SP_IS_TEXT(item))
1675     {
1676         curve = SP_TEXT(item)->getNormalizedBpath();
1677     }
1678     else
1679     {
1680         curve = NULL;
1681     }
1683     if (!curve)
1684         return NULL;
1685     NArtBpath *bpath = SP_CURVE_BPATH(curve);
1686     if (bpath == NULL)
1687         return NULL;
1689     if ( doTransformation ) {
1690         if (transformFull)
1691             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), sp_item_i2doc_affine(item));
1692         else
1693             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), item->transform);
1694         sp_curve_unref(curve);
1695         curve=NULL;
1696     } else {
1697         bpath=SP_CURVE_BPATH(curve);
1698     }
1700     Path *dest = new Path;
1701     dest->SetBackData(false);
1702     {
1703         int   i;
1704         bool  closed = false;
1705         float lastX  = 0.0;
1706         float lastY  = 0.0;
1708         for (i = 0; bpath[i].code != NR_END; i++) {
1709             switch (bpath[i].code) {
1710                 case NR_LINETO:
1711                     lastX = bpath[i].x3;
1712                     lastY = bpath[i].y3;
1713                     {
1714                         NR::Point tmp(lastX, lastY);
1715                         dest->LineTo(tmp);
1716                     }
1717                     break;
1719                 case NR_CURVETO:
1720                 {
1721                     NR::Point tmp, tms, tme;
1722                     tmp[0]=bpath[i].x3;
1723                     tmp[1]=bpath[i].y3;
1724                     tms[0]=3 * (bpath[i].x1 - lastX);
1725                     tms[1]=3 * (bpath[i].y1 - lastY);
1726                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1727                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1728                     dest->CubicTo(tmp,tms,tme);
1729                 }
1730                 lastX = bpath[i].x3;
1731                 lastY = bpath[i].y3;
1732                 break;
1734                 case NR_MOVETO_OPEN:
1735                 case NR_MOVETO:
1736                     if (closed)
1737                         dest->Close();
1738                     closed = (bpath[i].code == NR_MOVETO);
1739                     lastX = bpath[i].x3;
1740                     lastY = bpath[i].y3;
1741                     {
1742                         NR::Point  tmp(lastX, lastY);
1743                         dest->MoveTo(tmp);
1744                     }
1745                     break;
1746                 default:
1747                     break;
1748             }
1749         }
1750         if (closed)
1751             dest->Close();
1752     }
1754     if ( doTransformation ) {
1755         if ( bpath ) g_free(bpath);
1756     } else {
1757         sp_curve_unref(curve);
1758     }
1759     return dest;
1762 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p)
1764     //get nearest position on path
1765     Path::cut_position pos = path->PointToCurvilignPosition(p);
1766     return pos;
1769 NR::Point get_point_on_Path(Path *path, int piece, double t)
1771     NR::Point p;
1772     path->PointAt(piece, t, p);
1773     return p;
1777 /*
1778   Local Variables:
1779   mode:c++
1780   c-file-style:"stroustrup"
1781   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1782   indent-tabs-mode:nil
1783   fill-column:99
1784   End:
1785 */
1786 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :