Code

No more NRMatrix or NRPoint.
[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 <cstring>
21 #include <string>
22 #include <vector>
23 #include <glib/gmem.h>
24 #include "xml/repr.h"
25 #include "svg/svg.h"
26 #include "sp-path.h"
27 #include "sp-shape.h"
28 #include "sp-image.h"
29 #include "marker.h"
30 #include "enums.h"
31 #include "sp-text.h"
32 #include "sp-flowtext.h"
33 #include "text-editing.h"
34 #include "sp-item-group.h"
35 #include "style.h"
36 #include "inkscape.h"
37 #include "document.h"
38 #include "message-stack.h"
39 #include "selection.h"
40 #include "desktop-handles.h"
41 #include "desktop.h"
42 #include "display/canvas-bpath.h"
43 #include "display/curve.h"
44 #include <glibmm/i18n.h>
45 #include "prefs-utils.h"
47 #include "libnr/n-art-bpath.h"
48 #include "libnr/nr-path.h"
49 #include "xml/repr.h"
50 #include "xml/repr-sorting.h"
52 #include <libnr/nr-matrix-fns.h>
53 #include <libnr/nr-matrix-ops.h>
54 #include <libnr/nr-matrix-translate-ops.h>
55 #include <libnr/nr-scale-matrix-ops.h>
57 #include "livarot/Path.h"
58 #include "livarot/Shape.h"
60 #include "splivarot.h"
62 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
64 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
65 void sp_selected_path_do_offset(bool expand, double prefOffset);
66 void sp_selected_path_create_offset_object(int expand, bool updating);
68 void
69 sp_selected_path_union()
70 {
71     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
72 }
74 void
75 sp_selected_path_union_skip_undo()
76 {
77     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
78 }
80 void
81 sp_selected_path_intersect()
82 {
83     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
84 }
86 void
87 sp_selected_path_diff()
88 {
89     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
90 }
92 void
93 sp_selected_path_symdiff()
94 {
95     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
96 }
97 void
98 sp_selected_path_cut()
99 {
100     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
102 void
103 sp_selected_path_slice()
105     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
109 // boolean operations
110 // take the source paths from the file, do the operation, delete the originals and add the results
111 void
112 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
114     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
116     Inkscape::Selection *selection = sp_desktop_selection(desktop);
117     
118     GSList *il = (GSList *) selection->itemList();
119     
120     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
121     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
122         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
123         return;
124     }
125     else if ( g_slist_length(il) < 1 ) {
126         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
127         return;
128     }
130     if (g_slist_length(il) > 2) {
131         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
132             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
133             return;
134         }
135     }
137     // reverseOrderForOp marks whether the order of the list is the top->down order
138     // it's only used when there are 2 objects, and for operations who need to know the
139     // topmost object (differences, cuts)
140     bool reverseOrderForOp = false;
142     // mettre les elements de la liste dans l'ordre pour ces operations
143     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
144         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
145         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
146         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
148         if (a == NULL || b == NULL) {
149             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."));
150             return;
151         }
153         if (Ancetre(a, b)) {
154             // a is the parent of b, already in the proper order
155         } else if (Ancetre(b, a)) {
156             // reverse order
157             reverseOrderForOp = true;
158         } else {
160             // objects are not in parent/child relationship;
161             // find their lowest common ancestor
162             Inkscape::XML::Node *dad = LCA(a, b);
163             if (dad == NULL) {
164                 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."));
165                 return;
166             }
168             // find the children of the LCA that lead from it to the a and b
169             Inkscape::XML::Node *as = AncetreFils(a, dad);
170             Inkscape::XML::Node *bs = AncetreFils(b, dad);
172             // find out which comes first
173             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
174                 if (child == as) {
175                     /* a first, so reverse. */
176                     reverseOrderForOp = true;
177                     break;
178                 }
179                 if (child == bs)
180                     break;
181             }
182         }
183     }
185     il = g_slist_copy(il);
187     // first check if all the input objects have shapes
188     // otherwise bail out
189     for (GSList *l = il; l != NULL; l = l->next)
190     {
191         SPItem *item = SP_ITEM(l->data);
192         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
193         {
194             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
195             g_slist_free(il);
196             return;
197         }
198     }
200     // extract the livarot Paths from the source objects
201     // also get the winding rule specified in the style
202     int nbOriginaux = g_slist_length(il);
203     std::vector<Path *> originaux(nbOriginaux);
204     std::vector<FillRule> origWind(nbOriginaux);
205     int curOrig;
206     {
207         curOrig = 0;
208         for (GSList *l = il; l != NULL; l = l->next)
209         {
210             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
211             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
212             if (val && strcmp(val, "nonzero") == 0) {
213                 origWind[curOrig]= fill_nonZero;
214             } else if (val && strcmp(val, "evenodd") == 0) {
215                 origWind[curOrig]= fill_oddEven;
216             } else {
217                 origWind[curOrig]= fill_nonZero;
218             }
220             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
221             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
222             {
223                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
224                 g_slist_free(il);
225                 return;
226             }
227             curOrig++;
228         }
229     }
230     // reverse if needed
231     // note that the selection list keeps its order
232     if ( reverseOrderForOp ) {
233         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
234         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
235     }
237     // and work
238     // some temporary instances, first
239     Shape *theShapeA = new Shape;
240     Shape *theShapeB = new Shape;
241     Shape *theShape = new Shape;
242     Path *res = new Path;
243     res->SetBackData(false);
244     Path::cut_position  *toCut=NULL;
245     int                  nbToCut=0;
247     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
248         // true boolean op
249         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
250         originaux[0]->ConvertWithBackData(0.1);
252         originaux[0]->Fill(theShape, 0);
254         theShapeA->ConvertToShape(theShape, origWind[0]);
256         curOrig = 1;
257         for (GSList *l = il->next; l != NULL; l = l->next) {
258             originaux[curOrig]->ConvertWithBackData(0.1);
260             originaux[curOrig]->Fill(theShape, curOrig);
262             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
264             // les elements arrivent en ordre inverse dans la liste
265             theShape->Booleen(theShapeB, theShapeA, bop);
267             {
268                 Shape *swap = theShape;
269                 theShape = theShapeA;
270                 theShapeA = swap;
271             }
272             curOrig++;
273         }
275         {
276             Shape *swap = theShape;
277             theShape = theShapeA;
278             theShapeA = swap;
279         }
281     } else if ( bop == bool_op_cut ) {
282         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
283         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
284         // it is just uncrossed, and cleaned from duplicate edges and points
285         // then it's fed to Booleen() which will uncross it against the other path
286         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
287         // thus making a polygon. the weight of the edges of the cut are all 0, but
288         // the Booleen need to invert the ones inside the source polygon (for the subsequent
289         // ConvertToForme)
291         // the cut path needs to have the highest pathID in the back data
292         // that's how the Booleen() function knows it's an edge of the cut
294         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
295         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
296         // left it at 1.0. Investigate replacing this by a combination of difference and
297         // intersection of the same two paths. -- bb
298         {
299             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
300             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
301         }
302         originaux[0]->ConvertWithBackData(1.0);
304         originaux[0]->Fill(theShape, 0);
306         theShapeA->ConvertToShape(theShape, origWind[0]);
308         originaux[1]->ConvertWithBackData(1.0);
310         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
312         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
314         // les elements arrivent en ordre inverse dans la liste
315         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
317     } else if ( bop == bool_op_slice ) {
318         // slice is not really a boolean operation
319         // you just put the 2 shapes in a single polygon, uncross it
320         // the points where the degree is > 2 are intersections
321         // just check it's an intersection on the path you want to cut, and keep it
322         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
323         // make new subpath at each one of these positions
324         // inversion pour l'op\8eration
325         {
326             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
327             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
328         }
329         originaux[0]->ConvertWithBackData(1.0);
331         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
333         originaux[1]->ConvertWithBackData(1.0);
335         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
337         theShape->ConvertToShape(theShapeA, fill_justDont);
339         if ( theShape->hasBackData() ) {
340             // should always be the case, but ya never know
341             {
342                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
343                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
344                         // possibly an intersection
345                         // we need to check that at least one edge from the source path is incident to it
346                         // before we declare it's an intersection
347                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
348                         int   nbOrig=0;
349                         int   nbOther=0;
350                         int   piece=-1;
351                         float t=0.0;
352                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
353                             if ( theShape->ebData[cb].pathID == 0 ) {
354                                 // the source has an edge incident to the point, get its position on the path
355                                 piece=theShape->ebData[cb].pieceID;
356                                 if ( theShape->getEdge(cb).st == i ) {
357                                     t=theShape->ebData[cb].tSt;
358                                 } else {
359                                     t=theShape->ebData[cb].tEn;
360                                 }
361                                 nbOrig++;
362                             }
363                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
364                             cb=theShape->NextAt(i, cb);
365                         }
366                         if ( nbOrig > 0 && nbOther > 0 ) {
367                             // point incident to both path and cut: an intersection
368                             // note that you only keep one position on the source; you could have degenerate
369                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
370                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
371                             toCut[nbToCut].piece=piece;
372                             toCut[nbToCut].t=t;
373                             nbToCut++;
374                         }
375                     }
376                 }
377             }
378             {
379                 // i think it's useless now
380                 int i = theShape->numberOfEdges() - 1;
381                 for (;i>=0;i--) {
382                     if ( theShape->ebData[i].pathID == 1 ) {
383                         theShape->SubEdge(i);
384                     }
385                 }
386             }
388         }
389     }
391     int*    nesting=NULL;
392     int*    conts=NULL;
393     int     nbNest=0;
394     // pour compenser le swap juste avant
395     if ( bop == bool_op_slice ) {
396 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
397 //    res->ConvertForcedToMoveTo();
398         res->Copy(originaux[0]);
399         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
400         free(toCut);
401     } else if ( bop == bool_op_cut ) {
402         // il faut appeler pour desallouer PointData (pas vital, mais bon)
403         // the Booleen() function did not deallocated the point_data array in theShape, because this
404         // function needs it.
405         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
406         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
407         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
408     } else {
409         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
410     }
412     delete theShape;
413     delete theShapeA;
414     delete theShapeB;
415     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
417     if (res->descr_cmd.size() <= 1)
418     {
419         // only one command, presumably a moveto: it isn't a path
420         for (GSList *l = il; l != NULL; l = l->next)
421         {
422             SP_OBJECT(l->data)->deleteObject();
423         }
424         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
425                          description);
426         selection->clear();
428         delete res;
429         g_slist_free(il);
430         return;
431     }
433     // get the source path object
434     SPObject *source;
435     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
436         if (reverseOrderForOp) {
437              source = SP_OBJECT(il->data);
438         } else {
439              source = SP_OBJECT(il->next->data);
440         }
441     } else {
442         // find out the bottom object
443         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
445         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
447         source = sp_desktop_document(desktop)->
448             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
450         g_slist_free(sorted);
451     }
453     // adjust style properties that depend on a possible transform in the source object in order
454     // to get a correct style attribute for the new path
455     SPItem* item_source = SP_ITEM(source);
456     NR::Matrix i2root = sp_item_i2root_affine(item_source);
457     sp_item_adjust_stroke(item_source, NR::expansion(i2root));
458     sp_item_adjust_pattern(item_source, i2root);
459     sp_item_adjust_gradient(item_source, i2root);
460     sp_item_adjust_livepatheffect(item_source, i2root);
462     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
464     // remember important aspects of the source path, to be restored
465     gint pos = repr_source->position();
466     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
467     gchar const *id = repr_source->attribute("id");
468     gchar const *style = repr_source->attribute("style");
469     gchar const *mask = repr_source->attribute("mask");
470     gchar const *clip_path = repr_source->attribute("clip-path");
472     // remove source paths
473     selection->clear();
474     for (GSList *l = il; l != NULL; l = l->next) {
475         // if this is the bottommost object,
476         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
477             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
478             SP_OBJECT(l->data)->deleteObject(false);
479         } else {
480             // delete the object for real, so that its clones can take appropriate action
481             SP_OBJECT(l->data)->deleteObject();
482         }
483     }
484     g_slist_free(il);
486     // premultiply by the inverse of parent's repr
487     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
488     NR::Matrix local = sp_item_i2doc_affine(parent_item);
489     gchar *transform = sp_svg_transform_write(local.inverse());
491     // now that we have the result, add it on the canvas
492     if ( bop == bool_op_cut || bop == bool_op_slice ) {
493         int    nbRP=0;
494         Path** resPath;
495         if ( bop == bool_op_slice ) {
496             // there are moveto's at each intersection, but it's still one unique path
497             // so break it down and add each subpath independently
498             // we could call break_apart to do this, but while we have the description...
499             resPath=res->SubPaths(nbRP, false);
500         } else {
501             // cut operation is a bit wicked: you need to keep holes
502             // that's why you needed the nesting
503             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
504             // to get the path for each part of the polygon. that's why you need the nesting info:
505             // to know in wich subpath to add a subpath
506             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
508             // cleaning
509             if ( conts ) free(conts);
510             if ( nesting ) free(nesting);
511         }
513         // add all the pieces resulting from cut or slice
514         for (int i=0;i<nbRP;i++) {
515             gchar *d = resPath[i]->svg_dump_path();
517             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
518             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
519             repr->setAttribute("style", style);
520             if (mask)
521                 repr->setAttribute("mask", mask);
522             if (clip_path)
523                 repr->setAttribute("clip-path", clip_path);
525             repr->setAttribute("d", d);
526             g_free(d);
528             // for slice, remove fill
529             if (bop == bool_op_slice) {
530                 SPCSSAttr *css;
532                 css = sp_repr_css_attr_new();
533                 sp_repr_css_set_property(css, "fill", "none");
535                 sp_repr_css_change(repr, css, "style");
537                 sp_repr_css_attr_unref(css);
538             }
540             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
541             // this means it's basically random which of the pieces inherits the original's id and clones
542             // a better algorithm might figure out e.g. the biggest piece
543             repr->setAttribute("id", id);
545             repr->setAttribute("transform", transform);
547             // add the new repr to the parent
548             parent->appendChild(repr);
550             // move to the saved position
551             repr->setPosition(pos > 0 ? pos : 0);
553             selection->add(repr);
554             Inkscape::GC::release(repr);
556             delete resPath[i];
557         }
558         if ( resPath ) free(resPath);
560     } else {
561         gchar *d = res->svg_dump_path();
563         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
564         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
565         repr->setAttribute("style", style);
567         if ( mask )
568             repr->setAttribute("mask", mask);
570         if ( clip_path )
571             repr->setAttribute("clip-path", clip_path);
573         repr->setAttribute("d", d);
574         g_free(d);
576         repr->setAttribute("transform", transform);
578         repr->setAttribute("id", id);
579         parent->appendChild(repr);
580         repr->setPosition(pos > 0 ? pos : 0);
582         selection->add(repr);
583         Inkscape::GC::release(repr);
584     }
586     g_free(transform);
588     if (verb != SP_VERB_NONE) {
589         sp_document_done(sp_desktop_document(desktop), verb, description);
590     }
592     delete res;
596 void
597 sp_selected_path_outline()
599     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
601     Inkscape::Selection *selection = sp_desktop_selection(desktop);
603     if (selection->isEmpty()) {
604         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
605         return;
606     }
608     bool did = false;
610     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
611          items != NULL;
612          items = items->next) {
614         SPItem *item = (SPItem *) items->data;
616         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
617             continue;
619         SPCurve *curve = NULL;
620         if (SP_IS_SHAPE(item)) {
621             curve = sp_shape_get_curve(SP_SHAPE(item));
622             if (curve == NULL)
623                 continue;
624         }
625         if (SP_IS_TEXT(item)) {
626             curve = SP_TEXT(item)->getNormalizedBpath();
627             if (curve == NULL)
628                 continue;
629         }
631         {   // pas de stroke pas de chocolat
632             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
633             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
635             if (val == NULL || strcmp(val, "none") == 0) {
636                 sp_curve_unref(curve);
637                 continue;
638             }
639         }
641         // remember old stroke style, to be set on fill
642         SPCSSAttr *ncss;
643         {
644             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
645             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
646             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
648             ncss = sp_repr_css_attr_new();
650             sp_repr_css_set_property(ncss, "stroke", "none");
651             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
652             sp_repr_css_set_property(ncss, "fill", val);
653             if ( opac ) {
654                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
655             } else {
656                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
657             }
658             sp_repr_css_unset_property(ncss, "marker-start");
659             sp_repr_css_unset_property(ncss, "marker-mid");
660             sp_repr_css_unset_property(ncss, "marker-end");
661         }
663         NR::Matrix const transform(item->transform);
664         float const scale = NR::expansion(transform);
665         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
666         SPStyle *i_style = SP_OBJECT(item)->style;
667         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
668         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
670         float o_width, o_miter;
671         JoinType o_join;
672         ButtType o_butt;
674         {
675             int jointype, captype;
677             jointype = i_style->stroke_linejoin.computed;
678             captype = i_style->stroke_linecap.computed;
679             o_width = i_style->stroke_width.computed;
681             switch (jointype) {
682                 case SP_STROKE_LINEJOIN_MITER:
683                     o_join = join_pointy;
684                     break;
685                 case SP_STROKE_LINEJOIN_ROUND:
686                     o_join = join_round;
687                     break;
688                 default:
689                     o_join = join_straight;
690                     break;
691             }
693             switch (captype) {
694                 case SP_STROKE_LINECAP_SQUARE:
695                     o_butt = butt_square;
696                     break;
697                 case SP_STROKE_LINECAP_ROUND:
698                     o_butt = butt_round;
699                     break;
700                 default:
701                     o_butt = butt_straight;
702                     break;
703             }
705             if (o_width < 0.1)
706                 o_width = 0.1;
707             o_miter = i_style->stroke_miterlimit.value * o_width;
708         }
710         Path *orig = Path_for_item(item, false);
711         if (orig == NULL) {
712             g_free(style);
713             sp_curve_unref(curve);
714             continue;
715         }
717         Path *res = new Path;
718         res->SetBackData(false);
720         if (i_style->stroke_dash.n_dash) {
721             // For dashed strokes, use Stroke method, because Outline can't do dashes
722             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
724             orig->ConvertWithBackData(0.1);
726             orig->DashPolylineFromStyle(i_style, scale, 0);
728             Shape* theShape = new Shape;
729             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
730                          0.5 * o_miter);
731             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
733             Shape *theRes = new Shape;
735             theRes->ConvertToShape(theShape, fill_positive);
737             Path *originaux[1];
738             originaux[0] = res;
739             theRes->ConvertToForme(orig, 1, originaux);
741             res->Coalesce(5.0);
743             delete theShape;
744             delete theRes;
746         } else {
748             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
750             orig->Coalesce(0.5 * o_width);
752             Shape *theShape = new Shape;
753             Shape *theRes = new Shape;
755             res->ConvertWithBackData(1.0);
756             res->Fill(theShape, 0);
757             theRes->ConvertToShape(theShape, fill_positive);
759             Path *originaux[1];
760             originaux[0] = res;
761             theRes->ConvertToForme(orig, 1, originaux);
763             delete theShape;
764             delete theRes;
765         }
767         if (orig->descr_cmd.size() <= 1) {
768             // ca a merd\8e, ou bien le resultat est vide
769             delete res;
770             delete orig;
771             g_free(style);
772             continue;
773         }
775         did = true;
777         // remember the position of the item
778         gint pos = SP_OBJECT_REPR(item)->position();
779         // remember parent
780         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
781         // remember id
782         char const *id = SP_OBJECT_REPR(item)->attribute("id");
784         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
786             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
787             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
789             // restore old style
790             repr->setAttribute("style", style);
792             // set old stroke style on fill
793             sp_repr_css_change(repr, ncss, "style");
795             sp_repr_css_attr_unref(ncss);
797             gchar *str = orig->svg_dump_path();
798             repr->setAttribute("d", str);
799             g_free(str);
801             if (mask)
802                 repr->setAttribute("mask", mask);
803             if (clip_path)
804                 repr->setAttribute("clip-path", clip_path);
806             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
808                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
809                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
811                 // add the group to the parent
812                 parent->appendChild(g_repr);
813                 // move to the saved position
814                 g_repr->setPosition(pos > 0 ? pos : 0);
816                 g_repr->appendChild(repr);
817                 repr->setAttribute("id", id);
818                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
819                 sp_item_write_transform(newitem, repr, transform);
821                 SPShape *shape = SP_SHAPE(item);
823                 for (NArtBpath* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
824                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
825                         if (sp_shape_marker_required (shape, m, bp)) {
827                             SPMarker* marker = SP_MARKER (shape->marker[m]);
828                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
830                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
832                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
833                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
834                             }
836                             // total marker transform
837                             tr = marker_item->transform * marker->c2p * tr * transform;
839                             if (SP_OBJECT_REPR(marker_item)) {
840                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
841                                 g_repr->appendChild(m_repr);
842                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
843                                 sp_item_write_transform(marker_item, m_repr, tr);
844                             }
845                         }
846                     }
847                 }
850                 selection->add(g_repr);
852                 Inkscape::GC::release(g_repr);
855             } else {
857                 // add the new repr to the parent
858                 parent->appendChild(repr);
860                 // move to the saved position
861                 repr->setPosition(pos > 0 ? pos : 0);
863                 repr->setAttribute("id", id);
865                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
866                 sp_item_write_transform(newitem, repr, transform);
868                 selection->add(repr);
870             }
872             Inkscape::GC::release(repr);
874             sp_curve_unref(curve);
875             selection->remove(item);
876             SP_OBJECT(item)->deleteObject(false);
878         }
880         delete res;
881         delete orig;
882         g_free(style);
884     }
886     if (did) {
887         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
888                          _("Convert stroke to path"));
889     } else {
890         // TRANSLATORS: "to outline" means "to convert stroke to path"
891         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
892         return;
893     }
897 void
898 sp_selected_path_offset()
900     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
902     sp_selected_path_do_offset(true, prefOffset);
904 void
905 sp_selected_path_inset()
907     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
909     sp_selected_path_do_offset(false, prefOffset);
912 void
913 sp_selected_path_offset_screen(double pixels)
915     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
918 void
919 sp_selected_path_inset_screen(double pixels)
921     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
925 void sp_selected_path_create_offset_object_zero()
927     sp_selected_path_create_offset_object(0, false);
930 void sp_selected_path_create_offset()
932     sp_selected_path_create_offset_object(1, false);
934 void sp_selected_path_create_inset()
936     sp_selected_path_create_offset_object(-1, false);
939 void sp_selected_path_create_updating_offset_object_zero()
941     sp_selected_path_create_offset_object(0, true);
944 void sp_selected_path_create_updating_offset()
946     sp_selected_path_create_offset_object(1, true);
948 void sp_selected_path_create_updating_inset()
950     sp_selected_path_create_offset_object(-1, true);
953 void
954 sp_selected_path_create_offset_object(int expand, bool updating)
956     Inkscape::Selection *selection;
957     Inkscape::XML::Node *repr;
958     SPItem *item;
959     SPCurve *curve;
960     gchar *style, *str;
961     SPDesktop *desktop;
962     float o_width, o_miter;
963     JoinType o_join;
964     ButtType o_butt;
966     curve = NULL;
968     desktop = SP_ACTIVE_DESKTOP;
970     selection = sp_desktop_selection(desktop);
972     item = selection->singleItem();
974     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
975         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
976         return;
977     }
978     if (SP_IS_SHAPE(item))
979     {
980         curve = sp_shape_get_curve(SP_SHAPE(item));
981         if (curve == NULL)
982             return;
983     }
984     if (SP_IS_TEXT(item))
985     {
986         curve = SP_TEXT(item)->getNormalizedBpath();
987         if (curve == NULL)
988             return;
989     }
991     NR::Matrix const transform(item->transform);
993     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
995     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
997     // remember the position of the item
998     gint pos = SP_OBJECT_REPR(item)->position();
999     // remember parent
1000     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1002     {
1003         SPStyle *i_style = SP_OBJECT(item)->style;
1004         int jointype, captype;
1006         jointype = i_style->stroke_linejoin.value;
1007         captype = i_style->stroke_linecap.value;
1008         o_width = i_style->stroke_width.computed;
1009         if (jointype == SP_STROKE_LINEJOIN_MITER)
1010         {
1011             o_join = join_pointy;
1012         }
1013         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1014         {
1015             o_join = join_round;
1016         }
1017         else
1018         {
1019             o_join = join_straight;
1020         }
1021         if (captype == SP_STROKE_LINECAP_SQUARE)
1022         {
1023             o_butt = butt_square;
1024         }
1025         else if (captype == SP_STROKE_LINECAP_ROUND)
1026         {
1027             o_butt = butt_round;
1028         }
1029         else
1030         {
1031             o_butt = butt_straight;
1032         }
1034         {
1035             double prefOffset = 1.0;
1036             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1037             o_width = prefOffset;
1038         }
1040         if (o_width < 0.01)
1041             o_width = 0.01;
1042         o_miter = i_style->stroke_miterlimit.value * o_width;
1043     }
1045     Path *orig = Path_for_item(item, true, false);
1046     if (orig == NULL)
1047     {
1048         g_free(style);
1049         sp_curve_unref(curve);
1050         return;
1051     }
1053     Path *res = new Path;
1054     res->SetBackData(false);
1056     {
1057         Shape *theShape = new Shape;
1058         Shape *theRes = new Shape;
1060         orig->ConvertWithBackData(1.0);
1061         orig->Fill(theShape, 0);
1063         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1064         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1065         if (val && strcmp(val, "nonzero") == 0)
1066         {
1067             theRes->ConvertToShape(theShape, fill_nonZero);
1068         }
1069         else if (val && strcmp(val, "evenodd") == 0)
1070         {
1071             theRes->ConvertToShape(theShape, fill_oddEven);
1072         }
1073         else
1074         {
1075             theRes->ConvertToShape(theShape, fill_nonZero);
1076         }
1078         Path *originaux[1];
1079         originaux[0] = orig;
1080         theRes->ConvertToForme(res, 1, originaux);
1082         delete theShape;
1083         delete theRes;
1084     }
1086     sp_curve_unref(curve);
1088     if (res->descr_cmd.size() <= 1)
1089     {
1090         // pas vraiment de points sur le resultat
1091         // donc il ne reste rien
1092         sp_document_done(sp_desktop_document(desktop), 
1093                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1094                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1095                          (updating ? _("Create linked offset")
1096                           : _("Create dynamic offset")));
1097         selection->clear();
1099         delete res;
1100         delete orig;
1101         g_free(style);
1102         return;
1103     }
1105     {
1106         gchar tstr[80];
1108         tstr[79] = '\0';
1110         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1111         repr = xml_doc->createElement("svg:path");
1112         repr->setAttribute("sodipodi:type", "inkscape:offset");
1113         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1114                                                           ? o_width
1115                                                           : expand < 0
1116                                                           ? -o_width
1117                                                           : 0 ));
1119         str = res->svg_dump_path();
1120         repr->setAttribute("inkscape:original", str);
1121         g_free(str);
1123         if ( updating ) {
1124             char const *id = SP_OBJECT(item)->repr->attribute("id");
1125             char const *uri = g_strdup_printf("#%s", id);
1126             repr->setAttribute("xlink:href", uri);
1127             g_free((void *) uri);
1128         } else {
1129             repr->setAttribute("inkscape:href", NULL);
1130         }
1132         repr->setAttribute("style", style);
1134         // add the new repr to the parent
1135         parent->appendChild(repr);
1137         // move to the saved position
1138         repr->setPosition(pos > 0 ? pos : 0);
1140         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1142         if ( updating ) {
1143             // on conserve l'original
1144             // we reapply the transform to the original (offset will feel it)
1145             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1146         } else {
1147             // delete original, apply the transform to the offset
1148             SP_OBJECT(item)->deleteObject(false);
1149             sp_item_write_transform(nitem, repr, transform);
1150         }
1152         // The object just created from a temporary repr is only a seed.
1153         // We need to invoke its write which will update its real repr (in particular adding d=)
1154         SP_OBJECT(nitem)->updateRepr();
1156         Inkscape::GC::release(repr);
1158         selection->set(nitem);
1159     }
1161     sp_document_done(sp_desktop_document(desktop), 
1162                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1163                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1164                      (updating ? _("Create linked offset")
1165                       : _("Create dynamic offset")));
1167     delete res;
1168     delete orig;
1170     g_free(style);
1184 void
1185 sp_selected_path_do_offset(bool expand, double prefOffset)
1187     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1189     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1191     if (selection->isEmpty()) {
1192         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1193         return;
1194     }
1196     bool did = false;
1198     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1199          items != NULL;
1200          items = items->next) {
1202         SPItem *item = (SPItem *) items->data;
1204         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1205             continue;
1207         SPCurve *curve = NULL;
1208         if (SP_IS_SHAPE(item)) {
1209             curve = sp_shape_get_curve(SP_SHAPE(item));
1210             if (curve == NULL)
1211                 continue;
1212         }
1213         if (SP_IS_TEXT(item)) {
1214             curve = SP_TEXT(item)->getNormalizedBpath();
1215             if (curve == NULL)
1216                 continue;
1217         }
1219         NR::Matrix const transform(item->transform);
1221         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1223         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1225         float o_width, o_miter;
1226         JoinType o_join;
1227         ButtType o_butt;
1229         {
1230             SPStyle *i_style = SP_OBJECT(item)->style;
1231             int jointype, captype;
1233             jointype = i_style->stroke_linejoin.value;
1234             captype = i_style->stroke_linecap.value;
1235             o_width = i_style->stroke_width.computed;
1237             switch (jointype) {
1238                 case SP_STROKE_LINEJOIN_MITER:
1239                     o_join = join_pointy;
1240                     break;
1241                 case SP_STROKE_LINEJOIN_ROUND:
1242                     o_join = join_round;
1243                     break;
1244                 default:
1245                     o_join = join_straight;
1246                     break;
1247             }
1249             switch (captype) {
1250                 case SP_STROKE_LINECAP_SQUARE:
1251                     o_butt = butt_square;
1252                     break;
1253                 case SP_STROKE_LINECAP_ROUND:
1254                     o_butt = butt_round;
1255                     break;
1256                 default:
1257                     o_butt = butt_straight;
1258                     break;
1259             }
1261             o_width = prefOffset;
1263             if (o_width < 0.1)
1264                 o_width = 0.1;
1265             o_miter = i_style->stroke_miterlimit.value * o_width;
1266         }
1268         Path *orig = Path_for_item(item, false);
1269         if (orig == NULL) {
1270             g_free(style);
1271             sp_curve_unref(curve);
1272             continue;
1273         }
1275         Path *res = new Path;
1276         res->SetBackData(false);
1278         {
1279             Shape *theShape = new Shape;
1280             Shape *theRes = new Shape;
1282             orig->ConvertWithBackData(0.03);
1283             orig->Fill(theShape, 0);
1285             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1286             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1287             if (val && strcmp(val, "nonzero") == 0)
1288             {
1289                 theRes->ConvertToShape(theShape, fill_nonZero);
1290             }
1291             else if (val && strcmp(val, "evenodd") == 0)
1292             {
1293                 theRes->ConvertToShape(theShape, fill_oddEven);
1294             }
1295             else
1296             {
1297                 theRes->ConvertToShape(theShape, fill_nonZero);
1298             }
1300             // et maintenant: offset
1301             // methode inexacte
1302 /*                      Path *originaux[1];
1303                         originaux[0] = orig;
1304                         theRes->ConvertToForme(res, 1, originaux);
1306                         if (expand) {
1307                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1308                         } else {
1309                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1310                         }
1312                         orig->ConvertWithBackData(1.0);
1313                         orig->Fill(theShape, 0);
1314                         theRes->ConvertToShape(theShape, fill_positive);
1315                         originaux[0] = orig;
1316                         theRes->ConvertToForme(res, 1, originaux);
1318                         if (o_width >= 0.5) {
1319                         //     res->Coalesce(1.0);
1320                         res->ConvertEvenLines(1.0);
1321                         res->Simplify(1.0);
1322                         } else {
1323                         //      res->Coalesce(o_width);
1324                         res->ConvertEvenLines(1.0*o_width);
1325                         res->Simplify(1.0 * o_width);
1326                         }    */
1327             // methode par makeoffset
1329             if (expand)
1330             {
1331                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1332             }
1333             else
1334             {
1335                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1336             }
1337             theRes->ConvertToShape(theShape, fill_positive);
1339             res->Reset();
1340             theRes->ConvertToForme(res);
1342             if (o_width >= 1.0)
1343             {
1344                 res->ConvertEvenLines(1.0);
1345                 res->Simplify(1.0);
1346             }
1347             else
1348             {
1349                 res->ConvertEvenLines(1.0*o_width);
1350                 res->Simplify(1.0 * o_width);
1351             }
1353             delete theShape;
1354             delete theRes;
1355         }
1357         did = true;
1359         sp_curve_unref(curve);
1360         // remember the position of the item
1361         gint pos = SP_OBJECT_REPR(item)->position();
1362         // remember parent
1363         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1364         // remember id
1365         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1367         selection->remove(item);
1368         SP_OBJECT(item)->deleteObject(false);
1370         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1372             gchar tstr[80];
1374             tstr[79] = '\0';
1376             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1377             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1379             repr->setAttribute("style", style);
1381             gchar *str = res->svg_dump_path();
1382             repr->setAttribute("d", str);
1383             g_free(str);
1385             // add the new repr to the parent
1386             parent->appendChild(repr);
1388             // move to the saved position
1389             repr->setPosition(pos > 0 ? pos : 0);
1391             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1393             // reapply the transform
1394             sp_item_write_transform(newitem, repr, transform);
1396             repr->setAttribute("id", id);
1398             selection->add(repr);
1400             Inkscape::GC::release(repr);
1401         }
1403         delete orig;
1404         delete res;
1405     }
1407     if (did) {
1408         sp_document_done(sp_desktop_document(desktop), 
1409                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1410                          (expand ? _("Outset path") : _("Inset path")));
1411     } else {
1412         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1413         return;
1414     }
1418 static bool
1419 sp_selected_path_simplify_items(SPDesktop *desktop,
1420                                 Inkscape::Selection *selection, GSList *items,
1421                                 float threshold,  bool justCoalesce,
1422                                 float angleLimit, bool breakableAngles,
1423                                 bool modifySelection);
1426 //return true if we changed something, else false
1427 bool
1428 sp_selected_path_simplify_item(SPDesktop *desktop,
1429                  Inkscape::Selection *selection, SPItem *item,
1430                  float threshold,  bool justCoalesce,
1431                  float angleLimit, bool breakableAngles,
1432                  gdouble size,     bool modifySelection)
1434     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1435         return false;
1437     //If this is a group, do the children instead
1438     if (SP_IS_GROUP(item)) {
1439         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1440         
1441         return sp_selected_path_simplify_items(desktop, selection, items,
1442                                                threshold, justCoalesce,
1443                                                angleLimit, breakableAngles,
1444                                                false);
1445     }
1448     SPCurve *curve = NULL;
1450     if (SP_IS_SHAPE(item)) {
1451         curve = sp_shape_get_curve(SP_SHAPE(item));
1452         if (!curve)
1453             return false;
1454     }
1456     if (SP_IS_TEXT(item)) {
1457         curve = SP_TEXT(item)->getNormalizedBpath();
1458         if (!curve)
1459             return false;
1460     }
1462     // save the transform, to re-apply it after simplification
1463     NR::Matrix const transform(item->transform);
1465     /*
1466        reset the transform, effectively transforming the item by transform.inverse();
1467        this is necessary so that the item is transformed twice back and forth,
1468        allowing all compensations to cancel out regardless of the preferences
1469     */
1470     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1472     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1473     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1474     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1476     Path *orig = Path_for_item(item, false);
1477     if (orig == NULL) {
1478         g_free(style);
1479         sp_curve_unref(curve);
1480         return false;
1481     }
1483     sp_curve_unref(curve);
1484     // remember the position of the item
1485     gint pos = SP_OBJECT_REPR(item)->position();
1486     // remember parent
1487     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1488     // remember id
1489     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1490     // remember path effect
1491     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1493     //If a group was selected, to not change the selection list
1494     if (modifySelection)
1495         selection->remove(item);
1497     SP_OBJECT(item)->deleteObject(false);
1499     if ( justCoalesce ) {
1500         orig->Coalesce(threshold * size);
1501     } else {
1502         orig->ConvertEvenLines(threshold * size);
1503         orig->Simplify(threshold * size);
1504     }
1506     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1507     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1509     // restore style, mask and clip-path
1510     repr->setAttribute("style", style);
1511     g_free(style);
1513     if ( mask ) {
1514         repr->setAttribute("mask", mask);
1515         g_free(mask);
1516     }
1518     if ( clip_path ) {
1519         repr->setAttribute("clip-path", clip_path);
1520         g_free(clip_path);
1521     }
1523     // path
1524     gchar *str = orig->svg_dump_path();
1525     if (patheffect)
1526         repr->setAttribute("inkscape:original-d", str);
1527     else 
1528         repr->setAttribute("d", str);
1529     g_free(str);
1531     // restore id
1532     repr->setAttribute("id", id);
1534     // add the new repr to the parent
1535     parent->appendChild(repr);
1537     // move to the saved position
1538     repr->setPosition(pos > 0 ? pos : 0);
1540     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1542     // reapply the transform
1543     sp_item_write_transform(newitem, repr, transform);
1545     // restore path effect
1546     repr->setAttribute("inkscape:path-effect", patheffect);
1548     //If we are not in a selected group
1549     if (modifySelection)
1550         selection->add(repr);
1552     Inkscape::GC::release(repr);
1554     // clean up
1555     if (orig) delete orig;
1557     return true;
1561 bool
1562 sp_selected_path_simplify_items(SPDesktop *desktop,
1563                                 Inkscape::Selection *selection, GSList *items,
1564                                 float threshold,  bool justCoalesce,
1565                                 float angleLimit, bool breakableAngles,
1566                                 bool modifySelection)
1568   bool simplifyIndividualPaths =
1569     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1570   
1571   gchar *simplificationType;
1572   if (simplifyIndividualPaths) {
1573       simplificationType = _("Simplifying paths (separately):");
1574   } else {
1575       simplificationType = _("Simplifying paths:");
1576   }
1578   bool didSomething = false;
1580   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1581   if (!selectionBbox) {
1582     return false;
1583   }
1584   gdouble selectionSize  = L2(selectionBbox->dimensions());
1586   gdouble simplifySize  = selectionSize;
1587   
1588   int pathsSimplified = 0;
1589   int totalPathCount  = g_slist_length(items);
1590   
1591   // set "busy" cursor
1592   desktop->setWaitingCursor();
1593   
1594   for (; items != NULL; items = items->next) {
1595       SPItem *item = (SPItem *) items->data;
1596       
1597       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1598           continue;
1600       if (simplifyIndividualPaths) {
1601           NR::Maybe<NR::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));        
1602           if (itemBbox) {
1603               simplifySize      = L2(itemBbox->dimensions());
1604           } else {
1605               simplifySize      = 0;
1606           }
1607       }
1609       pathsSimplified++;
1611       if (pathsSimplified % 20 == 0) {
1612         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1613         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1614       }
1616       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1617                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1618   }
1620   desktop->clearWaitingCursor();
1622   if (pathsSimplified > 20) {
1623     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1624   }
1625   
1626   return didSomething;
1629 void
1630 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1631                        float angleLimit, bool breakableAngles)
1633     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1635     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1637     if (selection->isEmpty()) {
1638         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1639                          _("Select <b>path(s)</b> to simplify."));
1640         return;
1641     }
1643     GSList *items = g_slist_copy((GSList *) selection->itemList());
1645     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1646                                                         items, threshold,
1647                                                         justCoalesce,
1648                                                         angleLimit,
1649                                                         breakableAngles, true);
1651     if (didSomething)
1652         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1653                          _("Simplify"));
1654     else
1655         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1660 // globals for keeping track of accelerated simplify
1661 static double previousTime      = 0.0;
1662 static gdouble simplifyMultiply = 1.0;
1664 void
1665 sp_selected_path_simplify(void)
1667     gdouble simplifyThreshold =
1668         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1669     bool simplifyJustCoalesce =
1670         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1672     //Get the current time
1673     GTimeVal currentTimeVal;
1674     g_get_current_time(&currentTimeVal);
1675     double currentTime = currentTimeVal.tv_sec * 1000000 +
1676                 currentTimeVal.tv_usec;
1678     //Was the previous call to this function recent? (<0.5 sec)
1679     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1681         // add to the threshold 1/2 of its original value
1682         simplifyMultiply  += 0.5;
1683         simplifyThreshold *= simplifyMultiply;
1685     } else {
1686         // reset to the default
1687         simplifyMultiply = 1;
1688     }
1690     //remember time for next call
1691     previousTime = currentTime;
1693     //g_print("%g\n", simplify_threshold);
1695     //Make the actual call
1696     sp_selected_path_simplify_selection(simplifyThreshold,
1697                       simplifyJustCoalesce, 0.0, false);
1702 // fonctions utilitaires
1704 bool
1705 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1707     if (who == NULL || a == NULL)
1708         return false;
1709     if (who == a)
1710         return true;
1711     return Ancetre(sp_repr_parent(a), who);
1714 Path *
1715 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1717     SPCurve *curve = curve_for_item(item);
1718     NArtBpath *bpath = bpath_for_curve(item, curve, doTransformation, transformFull);
1719     
1720     if (bpath == NULL) {
1721         return NULL;
1722     }
1723     
1724     Path *dest = bpath_to_Path(bpath);
1726     if (doTransformation) {
1727         g_free(bpath); // see comment in bpath_for_curve
1728     }
1729     
1730     sp_curve_unref(curve);
1731     
1732     return dest;
1735 NArtBpath *
1736 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1738     if (curve == NULL)
1739         return NULL;
1741     NArtBpath *bpath = SP_CURVE_BPATH(curve);
1742     if (bpath == NULL) {
1743         return NULL;
1744     }
1745     
1746     if (doTransformation) {
1747         NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1748         if (transformFull) {
1749             new_bpath = nr_artpath_affine(bpath, sp_item_i2doc_affine(item));
1750         } else {
1751             new_bpath = nr_artpath_affine(bpath, item->transform);
1752         }
1753         bpath = new_bpath;
1754     }
1756     return bpath;
1759 SPCurve* curve_for_item(SPItem *item)
1761     if (!item)
1762         return NULL;
1764     SPCurve *curve = NULL;
1766     if (SP_IS_SHAPE(item)) {
1767         if (SP_IS_PATH(item)) {
1768             curve = sp_path_get_curve_for_edit(SP_PATH(item));
1769         } else {
1770             curve = sp_shape_get_curve(SP_SHAPE(item));
1771         }
1772     }
1773     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1774     {
1775         curve = te_get_layout(item)->convertToCurves();
1776     }
1777     else if (SP_IS_IMAGE(item))
1778     {
1779         curve = sp_image_get_curve(SP_IMAGE(item));
1780     }
1781     
1782     return curve; // do not forget to unref the curve at some point!
1785 Path *bpath_to_Path(NArtBpath const *bpath) {
1786     Path *dest = new Path;
1787     dest->SetBackData(false);
1788     {
1789         int   i;
1790         bool  closed = false;
1791         float lastX  = 0.0;
1792         float lastY  = 0.0;
1794         for (i = 0; bpath[i].code != NR_END; i++) {
1795             switch (bpath[i].code) {
1796                 case NR_LINETO:
1797                     lastX = bpath[i].x3;
1798                     lastY = bpath[i].y3;
1799                     {
1800                         NR::Point tmp(lastX, lastY);
1801                         dest->LineTo(tmp);
1802                     }
1803                     break;
1805                 case NR_CURVETO:
1806                 {
1807                     NR::Point tmp, tms, tme;
1808                     tmp[0]=bpath[i].x3;
1809                     tmp[1]=bpath[i].y3;
1810                     tms[0]=3 * (bpath[i].x1 - lastX);
1811                     tms[1]=3 * (bpath[i].y1 - lastY);
1812                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1813                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1814                     dest->CubicTo(tmp,tms,tme);
1815                 }
1816                 lastX = bpath[i].x3;
1817                 lastY = bpath[i].y3;
1818                 break;
1820                 case NR_MOVETO_OPEN:
1821                 case NR_MOVETO:
1822                     if (closed)
1823                         dest->Close();
1824                     closed = (bpath[i].code == NR_MOVETO);
1825                     lastX = bpath[i].x3;
1826                     lastY = bpath[i].y3;
1827                     {
1828                         NR::Point  tmp(lastX, lastY);
1829                         dest->MoveTo(tmp);
1830                     }
1831                     break;
1832                 default:
1833                     break;
1834             }
1835         }
1836         if (closed)
1837             dest->Close();
1838     }
1839     return dest;
1842 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1844     //get nearest position on path
1845     Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1846     return pos;
1849 NR::Point get_point_on_Path(Path *path, int piece, double t)
1851     NR::Point p;
1852     path->PointAt(piece, t, p);
1853     return p;
1857 /*
1858   Local Variables:
1859   mode:c++
1860   c-file-style:"stroustrup"
1861   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1862   indent-tabs-mode:nil
1863   fill-column:99
1864   End:
1865 */
1866 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :