Code

enable Path_for_item to work on flowtext
[inkscape.git] / src / splivarot.cpp
1 #define __SP_LIVAROT_C__
2 /*
3  *  splivarot.cpp
4  *  Inkscape
5  *
6  *  Created by fred on Fri Dec 05 2003.
7  *  tweaked endlessly by bulia byak <buliabyak@users.sf.net>
8  *  public domain
9  *
10  */
12 /*
13  * contains lots of stitched pieces of path-chemistry.c
14  */
16 #ifdef HAVE_CONFIG_H
17 # include <config.h>
18 #endif
20 #include <vector>
21 #include <glib/gmem.h>
22 #include "xml/repr.h"
23 #include "svg/svg.h"
24 #include "sp-path.h"
25 #include "sp-shape.h"
26 #include "sp-image.h"
27 #include "marker.h"
28 #include "enums.h"
29 #include "sp-text.h"
30 #include "sp-flowtext.h"
31 #include "text-editing.h"
32 #include "sp-item-group.h"
33 #include "style.h"
34 #include "inkscape.h"
35 #include "document.h"
36 #include "message-stack.h"
37 #include "selection.h"
38 #include "desktop-handles.h"
39 #include "desktop.h"
40 #include "display/canvas-bpath.h"
41 #include "display/curve.h"
42 #include <glibmm/i18n.h>
43 #include "prefs-utils.h"
45 #include "libnr/n-art-bpath.h"
46 #include "libnr/nr-path.h"
47 #include "xml/repr.h"
48 #include "xml/repr-sorting.h"
50 #include <libnr/nr-matrix-fns.h>
51 #include <libnr/nr-matrix-ops.h>
52 #include <libnr/nr-matrix-translate-ops.h>
53 #include <libnr/nr-scale-matrix-ops.h>
55 #include "livarot/Path.h"
56 #include "livarot/Shape.h"
58 #include "splivarot.h"
60 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
62 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
63 void sp_selected_path_do_offset(bool expand, double prefOffset);
64 void sp_selected_path_create_offset_object(int expand, bool updating);
66 void
67 sp_selected_path_union()
68 {
69     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
70 }
72 void
73 sp_selected_path_union_skip_undo()
74 {
75     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
76 }
78 void
79 sp_selected_path_intersect()
80 {
81     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
82 }
84 void
85 sp_selected_path_diff()
86 {
87     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
88 }
90 void
91 sp_selected_path_symdiff()
92 {
93     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
94 }
95 void
96 sp_selected_path_cut()
97 {
98     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
99 }
100 void
101 sp_selected_path_slice()
103     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
107 // boolean operations
108 // take the source paths from the file, do the operation, delete the originals and add the results
109 void
110 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
112     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
114     Inkscape::Selection *selection = sp_desktop_selection(desktop);
115     
116     GSList *il = (GSList *) selection->itemList();
117     
118     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
119     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
120         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
121         return;
122     }
123     else if ( g_slist_length(il) < 1 ) {
124         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
125         return;
126     }
128     if (g_slist_length(il) > 2) {
129         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
130             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
131             return;
132         }
133     }
135     // reverseOrderForOp marks whether the order of the list is the top->down order
136     // it's only used when there are 2 objects, and for operations who need to know the
137     // topmost object (differences, cuts)
138     bool reverseOrderForOp = false;
140     // mettre les elements de la liste dans l'ordre pour ces operations
141     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
142         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
143         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
144         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
146         if (a == NULL || b == NULL) {
147             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."));
148             return;
149         }
151         if (Ancetre(a, b)) {
152             // a is the parent of b, already in the proper order
153         } else if (Ancetre(b, a)) {
154             // reverse order
155             reverseOrderForOp = true;
156         } else {
158             // objects are not in parent/child relationship;
159             // find their lowest common ancestor
160             Inkscape::XML::Node *dad = LCA(a, b);
161             if (dad == NULL) {
162                 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."));
163                 return;
164             }
166             // find the children of the LCA that lead from it to the a and b
167             Inkscape::XML::Node *as = AncetreFils(a, dad);
168             Inkscape::XML::Node *bs = AncetreFils(b, dad);
170             // find out which comes first
171             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
172                 if (child == as) {
173                     /* a first, so reverse. */
174                     reverseOrderForOp = true;
175                     break;
176                 }
177                 if (child == bs)
178                     break;
179             }
180         }
181     }
183     il = g_slist_copy(il);
185     // first check if all the input objects have shapes
186     // otherwise bail out
187     for (GSList *l = il; l != NULL; l = l->next)
188     {
189         SPItem *item = SP_ITEM(l->data);
190         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
191         {
192             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
193             g_slist_free(il);
194             return;
195         }
196     }
198     // extract the livarot Paths from the source objects
199     // also get the winding rule specified in the style
200     int nbOriginaux = g_slist_length(il);
201     std::vector<Path *> originaux(nbOriginaux);
202     std::vector<FillRule> origWind(nbOriginaux);
203     int curOrig;
204     {
205         curOrig = 0;
206         for (GSList *l = il; l != NULL; l = l->next)
207         {
208             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
209             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
210             if (val && strcmp(val, "nonzero") == 0) {
211                 origWind[curOrig]= fill_nonZero;
212             } else if (val && strcmp(val, "evenodd") == 0) {
213                 origWind[curOrig]= fill_oddEven;
214             } else {
215                 origWind[curOrig]= fill_nonZero;
216             }
218             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
219             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
220             {
221                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
222                 g_slist_free(il);
223                 return;
224             }
225             curOrig++;
226         }
227     }
228     // reverse if needed
229     // note that the selection list keeps its order
230     if ( reverseOrderForOp ) {
231         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
232         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
233     }
235     // and work
236     // some temporary instances, first
237     Shape *theShapeA = new Shape;
238     Shape *theShapeB = new Shape;
239     Shape *theShape = new Shape;
240     Path *res = new Path;
241     res->SetBackData(false);
242     Path::cut_position  *toCut=NULL;
243     int                  nbToCut=0;
245     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
246         // true boolean op
247         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
248         originaux[0]->ConvertWithBackData(0.1);
250         originaux[0]->Fill(theShape, 0);
252         theShapeA->ConvertToShape(theShape, origWind[0]);
254         curOrig = 1;
255         for (GSList *l = il->next; l != NULL; l = l->next) {
256             originaux[curOrig]->ConvertWithBackData(0.1);
258             originaux[curOrig]->Fill(theShape, curOrig);
260             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
262             // les elements arrivent en ordre inverse dans la liste
263             theShape->Booleen(theShapeB, theShapeA, bop);
265             {
266                 Shape *swap = theShape;
267                 theShape = theShapeA;
268                 theShapeA = swap;
269             }
270             curOrig++;
271         }
273         {
274             Shape *swap = theShape;
275             theShape = theShapeA;
276             theShapeA = swap;
277         }
279     } else if ( bop == bool_op_cut ) {
280         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
281         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
282         // it is just uncrossed, and cleaned from duplicate edges and points
283         // then it's fed to Booleen() which will uncross it against the other path
284         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
285         // thus making a polygon. the weight of the edges of the cut are all 0, but
286         // the Booleen need to invert the ones inside the source polygon (for the subsequent
287         // ConvertToForme)
289         // the cut path needs to have the highest pathID in the back data
290         // that's how the Booleen() function knows it's an edge of the cut
292         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
293         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
294         // left it at 1.0. Investigate replacing this by a combination of difference and
295         // intersection of the same two paths. -- bb
296         {
297             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
298             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
299         }
300         originaux[0]->ConvertWithBackData(1.0);
302         originaux[0]->Fill(theShape, 0);
304         theShapeA->ConvertToShape(theShape, origWind[0]);
306         originaux[1]->ConvertWithBackData(1.0);
308         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
310         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
312         // les elements arrivent en ordre inverse dans la liste
313         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
315     } else if ( bop == bool_op_slice ) {
316         // slice is not really a boolean operation
317         // you just put the 2 shapes in a single polygon, uncross it
318         // the points where the degree is > 2 are intersections
319         // just check it's an intersection on the path you want to cut, and keep it
320         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
321         // make new subpath at each one of these positions
322         // inversion pour l'op\8eration
323         {
324             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
325             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
326         }
327         originaux[0]->ConvertWithBackData(1.0);
329         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
331         originaux[1]->ConvertWithBackData(1.0);
333         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
335         theShape->ConvertToShape(theShapeA, fill_justDont);
337         if ( theShape->hasBackData() ) {
338             // should always be the case, but ya never know
339             {
340                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
341                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
342                         // possibly an intersection
343                         // we need to check that at least one edge from the source path is incident to it
344                         // before we declare it's an intersection
345                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
346                         int   nbOrig=0;
347                         int   nbOther=0;
348                         int   piece=-1;
349                         float t=0.0;
350                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
351                             if ( theShape->ebData[cb].pathID == 0 ) {
352                                 // the source has an edge incident to the point, get its position on the path
353                                 piece=theShape->ebData[cb].pieceID;
354                                 if ( theShape->getEdge(cb).st == i ) {
355                                     t=theShape->ebData[cb].tSt;
356                                 } else {
357                                     t=theShape->ebData[cb].tEn;
358                                 }
359                                 nbOrig++;
360                             }
361                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
362                             cb=theShape->NextAt(i, cb);
363                         }
364                         if ( nbOrig > 0 && nbOther > 0 ) {
365                             // point incident to both path and cut: an intersection
366                             // note that you only keep one position on the source; you could have degenerate
367                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
368                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
369                             toCut[nbToCut].piece=piece;
370                             toCut[nbToCut].t=t;
371                             nbToCut++;
372                         }
373                     }
374                 }
375             }
376             {
377                 // i think it's useless now
378                 int i = theShape->numberOfEdges() - 1;
379                 for (;i>=0;i--) {
380                     if ( theShape->ebData[i].pathID == 1 ) {
381                         theShape->SubEdge(i);
382                     }
383                 }
384             }
386         }
387     }
389     int*    nesting=NULL;
390     int*    conts=NULL;
391     int     nbNest=0;
392     // pour compenser le swap juste avant
393     if ( bop == bool_op_slice ) {
394 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
395 //    res->ConvertForcedToMoveTo();
396         res->Copy(originaux[0]);
397         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
398         free(toCut);
399     } else if ( bop == bool_op_cut ) {
400         // il faut appeler pour desallouer PointData (pas vital, mais bon)
401         // the Booleen() function did not deallocated the point_data array in theShape, because this
402         // function needs it.
403         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
404         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
405         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
406     } else {
407         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
408     }
410     delete theShape;
411     delete theShapeA;
412     delete theShapeB;
413     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
415     if (res->descr_cmd.size() <= 1)
416     {
417         // only one command, presumably a moveto: it isn't a path
418         for (GSList *l = il; l != NULL; l = l->next)
419         {
420             SP_OBJECT(l->data)->deleteObject();
421         }
422         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
423                          description);
424         selection->clear();
426         delete res;
427         g_slist_free(il);
428         return;
429     }
431     // get the source path object
432     SPObject *source;
433     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
434         if (reverseOrderForOp) {
435              source = SP_OBJECT(il->data);
436         } else {
437              source = SP_OBJECT(il->next->data);
438         }
439     } else {
440         // find out the bottom object
441         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
443         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
445         source = sp_desktop_document(desktop)->
446             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
448         g_slist_free(sorted);
449     }
451     // adjust style properties that depend on a possible transform in the source object in order
452     // to get a correct style attribute for the new path
453     SPItem* item_source = SP_ITEM(source);
454     NR::Matrix i2root = sp_item_i2root_affine(item_source);
455     sp_item_adjust_stroke(item_source, i2root.expansion());
456     sp_item_adjust_pattern(item_source, i2root);
457     sp_item_adjust_gradient(item_source, i2root);
459     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
461     // remember important aspects of the source path, to be restored
462     gint pos = repr_source->position();
463     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
464     gchar const *id = repr_source->attribute("id");
465     gchar const *style = repr_source->attribute("style");
466     gchar const *mask = repr_source->attribute("mask");
467     gchar const *clip_path = repr_source->attribute("clip-path");
469     // remove source paths
470     selection->clear();
471     for (GSList *l = il; l != NULL; l = l->next) {
472         // if this is the bottommost object,
473         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
474             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
475             SP_OBJECT(l->data)->deleteObject(false);
476         } else {
477             // delete the object for real, so that its clones can take appropriate action
478             SP_OBJECT(l->data)->deleteObject();
479         }
480     }
481     g_slist_free(il);
483     // premultiply by the inverse of parent's repr
484     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
485     NR::Matrix local = sp_item_i2doc_affine(parent_item);
486     gchar *transform = sp_svg_transform_write(local.inverse());
488     // now that we have the result, add it on the canvas
489     if ( bop == bool_op_cut || bop == bool_op_slice ) {
490         int    nbRP=0;
491         Path** resPath;
492         if ( bop == bool_op_slice ) {
493             // there are moveto's at each intersection, but it's still one unique path
494             // so break it down and add each subpath independently
495             // we could call break_apart to do this, but while we have the description...
496             resPath=res->SubPaths(nbRP, false);
497         } else {
498             // cut operation is a bit wicked: you need to keep holes
499             // that's why you needed the nesting
500             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
501             // to get the path for each part of the polygon. that's why you need the nesting info:
502             // to know in wich subpath to add a subpath
503             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
505             // cleaning
506             if ( conts ) free(conts);
507             if ( nesting ) free(nesting);
508         }
510         // add all the pieces resulting from cut or slice
511         for (int i=0;i<nbRP;i++) {
512             gchar *d = resPath[i]->svg_dump_path();
514             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
515             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
516             repr->setAttribute("style", style);
517             if (mask)
518                 repr->setAttribute("mask", mask);
519             if (clip_path)
520                 repr->setAttribute("clip-path", clip_path);
522             repr->setAttribute("d", d);
523             g_free(d);
525             // for slice, remove fill
526             if (bop == bool_op_slice) {
527                 SPCSSAttr *css;
529                 css = sp_repr_css_attr_new();
530                 sp_repr_css_set_property(css, "fill", "none");
532                 sp_repr_css_change(repr, css, "style");
534                 sp_repr_css_attr_unref(css);
535             }
537             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
538             // this means it's basically random which of the pieces inherits the original's id and clones
539             // a better algorithm might figure out e.g. the biggest piece
540             repr->setAttribute("id", id);
542             repr->setAttribute("transform", transform);
544             // add the new repr to the parent
545             parent->appendChild(repr);
547             // move to the saved position
548             repr->setPosition(pos > 0 ? pos : 0);
550             selection->add(repr);
551             Inkscape::GC::release(repr);
553             delete resPath[i];
554         }
555         if ( resPath ) free(resPath);
557     } else {
558         gchar *d = res->svg_dump_path();
560         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
561         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
562         repr->setAttribute("style", style);
564         if ( mask )
565             repr->setAttribute("mask", mask);
567         if ( clip_path )
568             repr->setAttribute("clip-path", clip_path);
570         repr->setAttribute("d", d);
571         g_free(d);
573         repr->setAttribute("transform", transform);
575         repr->setAttribute("id", id);
576         parent->appendChild(repr);
577         repr->setPosition(pos > 0 ? pos : 0);
579         selection->add(repr);
580         Inkscape::GC::release(repr);
581     }
583     g_free(transform);
585     if (verb != SP_VERB_NONE) {
586         sp_document_done(sp_desktop_document(desktop), verb, description);
587     }
589     delete res;
593 void
594 sp_selected_path_outline()
596     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
598     Inkscape::Selection *selection = sp_desktop_selection(desktop);
600     if (selection->isEmpty()) {
601         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
602         return;
603     }
605     bool did = false;
607     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
608          items != NULL;
609          items = items->next) {
611         SPItem *item = (SPItem *) items->data;
613         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
614             continue;
616         SPCurve *curve = NULL;
617         if (SP_IS_SHAPE(item)) {
618             curve = sp_shape_get_curve(SP_SHAPE(item));
619             if (curve == NULL)
620                 continue;
621         }
622         if (SP_IS_TEXT(item)) {
623             curve = SP_TEXT(item)->getNormalizedBpath();
624             if (curve == NULL)
625                 continue;
626         }
628         {   // pas de stroke pas de chocolat
629             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
630             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
632             if (val == NULL || strcmp(val, "none") == 0) {
633                 sp_curve_unref(curve);
634                 continue;
635             }
636         }
638         // remember old stroke style, to be set on fill
639         SPCSSAttr *ncss;
640         {
641             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
642             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
643             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
645             ncss = sp_repr_css_attr_new();
647             sp_repr_css_set_property(ncss, "stroke", "none");
648             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
649             sp_repr_css_set_property(ncss, "fill", val);
650             if ( opac ) {
651                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
652             } else {
653                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
654             }
655             sp_repr_css_unset_property(ncss, "marker-start");
656             sp_repr_css_unset_property(ncss, "marker-mid");
657             sp_repr_css_unset_property(ncss, "marker-end");
658         }
660         NR::Matrix const transform(item->transform);
661         float const scale = transform.expansion();
662         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
663         SPStyle *i_style = SP_OBJECT(item)->style;
664         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
665         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
667         float o_width, o_miter;
668         JoinType o_join;
669         ButtType o_butt;
671         {
672             int jointype, captype;
674             jointype = i_style->stroke_linejoin.computed;
675             captype = i_style->stroke_linecap.computed;
676             o_width = i_style->stroke_width.computed;
678             switch (jointype) {
679                 case SP_STROKE_LINEJOIN_MITER:
680                     o_join = join_pointy;
681                     break;
682                 case SP_STROKE_LINEJOIN_ROUND:
683                     o_join = join_round;
684                     break;
685                 default:
686                     o_join = join_straight;
687                     break;
688             }
690             switch (captype) {
691                 case SP_STROKE_LINECAP_SQUARE:
692                     o_butt = butt_square;
693                     break;
694                 case SP_STROKE_LINECAP_ROUND:
695                     o_butt = butt_round;
696                     break;
697                 default:
698                     o_butt = butt_straight;
699                     break;
700             }
702             if (o_width < 0.1)
703                 o_width = 0.1;
704             o_miter = i_style->stroke_miterlimit.value * o_width;
705         }
707         Path *orig = Path_for_item(item, false);
708         if (orig == NULL) {
709             g_free(style);
710             sp_curve_unref(curve);
711             continue;
712         }
714         Path *res = new Path;
715         res->SetBackData(false);
717         if (i_style->stroke_dash.n_dash) {
718             // For dashed strokes, use Stroke method, because Outline can't do dashes
719             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
721             orig->ConvertWithBackData(0.1);
723             orig->DashPolylineFromStyle(i_style, scale, 0);
725             Shape* theShape = new Shape;
726             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
727                          0.5 * o_miter);
728             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
730             Shape *theRes = new Shape;
732             theRes->ConvertToShape(theShape, fill_positive);
734             Path *originaux[1];
735             originaux[0] = res;
736             theRes->ConvertToForme(orig, 1, originaux);
738             res->Coalesce(5.0);
740             delete theShape;
741             delete theRes;
743         } else {
745             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
747             orig->Coalesce(0.5 * o_width);
749             Shape *theShape = new Shape;
750             Shape *theRes = new Shape;
752             res->ConvertWithBackData(1.0);
753             res->Fill(theShape, 0);
754             theRes->ConvertToShape(theShape, fill_positive);
756             Path *originaux[1];
757             originaux[0] = res;
758             theRes->ConvertToForme(orig, 1, originaux);
760             delete theShape;
761             delete theRes;
762         }
764         if (orig->descr_cmd.size() <= 1) {
765             // ca a merd\8e, ou bien le resultat est vide
766             delete res;
767             delete orig;
768             g_free(style);
769             continue;
770         }
772         did = true;
774         // remember the position of the item
775         gint pos = SP_OBJECT_REPR(item)->position();
776         // remember parent
777         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
778         // remember id
779         char const *id = SP_OBJECT_REPR(item)->attribute("id");
781         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
783             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
784             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
786             // restore old style
787             repr->setAttribute("style", style);
789             // set old stroke style on fill
790             sp_repr_css_change(repr, ncss, "style");
792             sp_repr_css_attr_unref(ncss);
794             gchar *str = orig->svg_dump_path();
795             repr->setAttribute("d", str);
796             g_free(str);
798             if (mask)
799                 repr->setAttribute("mask", mask);
800             if (clip_path)
801                 repr->setAttribute("clip-path", clip_path);
803             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
805                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
806                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
808                 // add the group to the parent
809                 parent->appendChild(g_repr);
810                 // move to the saved position
811                 g_repr->setPosition(pos > 0 ? pos : 0);
813                 g_repr->appendChild(repr);
814                 repr->setAttribute("id", id);
815                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
816                 sp_item_write_transform(newitem, repr, transform);
818                 SPShape *shape = SP_SHAPE(item);
820                 for (NArtBpath* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
821                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
822                         if (sp_shape_marker_required (shape, m, bp)) {
824                             SPMarker* marker = SP_MARKER (shape->marker[m]);
825                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
827                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
829                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
830                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
831                             }
833                             // total marker transform
834                             tr = marker_item->transform * marker->c2p * tr * transform;
836                             if (SP_OBJECT_REPR(marker_item)) {
837                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
838                                 g_repr->appendChild(m_repr);
839                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
840                                 sp_item_write_transform(marker_item, m_repr, tr);
841                             }
842                         }
843                     }
844                 }
847                 selection->add(g_repr);
849                 Inkscape::GC::release(g_repr);
852             } else {
854                 // add the new repr to the parent
855                 parent->appendChild(repr);
857                 // move to the saved position
858                 repr->setPosition(pos > 0 ? pos : 0);
860                 repr->setAttribute("id", id);
862                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
863                 sp_item_write_transform(newitem, repr, transform);
865                 selection->add(repr);
867             }
869             Inkscape::GC::release(repr);
871             sp_curve_unref(curve);
872             selection->remove(item);
873             SP_OBJECT(item)->deleteObject(false);
875         }
877         delete res;
878         delete orig;
879         g_free(style);
881     }
883     if (did) {
884         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
885                          _("Convert stroke to path"));
886     } else {
887         // TRANSLATORS: "to outline" means "to convert stroke to path"
888         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
889         return;
890     }
894 void
895 sp_selected_path_offset()
897     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
899     sp_selected_path_do_offset(true, prefOffset);
901 void
902 sp_selected_path_inset()
904     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
906     sp_selected_path_do_offset(false, prefOffset);
909 void
910 sp_selected_path_offset_screen(double pixels)
912     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
915 void
916 sp_selected_path_inset_screen(double pixels)
918     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
922 void sp_selected_path_create_offset_object_zero()
924     sp_selected_path_create_offset_object(0, false);
927 void sp_selected_path_create_offset()
929     sp_selected_path_create_offset_object(1, false);
931 void sp_selected_path_create_inset()
933     sp_selected_path_create_offset_object(-1, false);
936 void sp_selected_path_create_updating_offset_object_zero()
938     sp_selected_path_create_offset_object(0, true);
941 void sp_selected_path_create_updating_offset()
943     sp_selected_path_create_offset_object(1, true);
945 void sp_selected_path_create_updating_inset()
947     sp_selected_path_create_offset_object(-1, true);
950 void
951 sp_selected_path_create_offset_object(int expand, bool updating)
953     Inkscape::Selection *selection;
954     Inkscape::XML::Node *repr;
955     SPItem *item;
956     SPCurve *curve;
957     gchar *style, *str;
958     SPDesktop *desktop;
959     float o_width, o_miter;
960     JoinType o_join;
961     ButtType o_butt;
963     curve = NULL;
965     desktop = SP_ACTIVE_DESKTOP;
967     selection = sp_desktop_selection(desktop);
969     item = selection->singleItem();
971     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
972         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
973         return;
974     }
975     if (SP_IS_SHAPE(item))
976     {
977         curve = sp_shape_get_curve(SP_SHAPE(item));
978         if (curve == NULL)
979             return;
980     }
981     if (SP_IS_TEXT(item))
982     {
983         curve = SP_TEXT(item)->getNormalizedBpath();
984         if (curve == NULL)
985             return;
986     }
988     NR::Matrix const transform(item->transform);
990     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
992     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
994     // remember the position of the item
995     gint pos = SP_OBJECT_REPR(item)->position();
996     // remember parent
997     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
999     {
1000         SPStyle *i_style = SP_OBJECT(item)->style;
1001         int jointype, captype;
1003         jointype = i_style->stroke_linejoin.value;
1004         captype = i_style->stroke_linecap.value;
1005         o_width = i_style->stroke_width.computed;
1006         if (jointype == SP_STROKE_LINEJOIN_MITER)
1007         {
1008             o_join = join_pointy;
1009         }
1010         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1011         {
1012             o_join = join_round;
1013         }
1014         else
1015         {
1016             o_join = join_straight;
1017         }
1018         if (captype == SP_STROKE_LINECAP_SQUARE)
1019         {
1020             o_butt = butt_square;
1021         }
1022         else if (captype == SP_STROKE_LINECAP_ROUND)
1023         {
1024             o_butt = butt_round;
1025         }
1026         else
1027         {
1028             o_butt = butt_straight;
1029         }
1031         {
1032             double prefOffset = 1.0;
1033             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1034             o_width = prefOffset;
1035         }
1037         if (o_width < 0.01)
1038             o_width = 0.01;
1039         o_miter = i_style->stroke_miterlimit.value * o_width;
1040     }
1042     Path *orig = Path_for_item(item, true, false);
1043     if (orig == NULL)
1044     {
1045         g_free(style);
1046         sp_curve_unref(curve);
1047         return;
1048     }
1050     Path *res = new Path;
1051     res->SetBackData(false);
1053     {
1054         Shape *theShape = new Shape;
1055         Shape *theRes = new Shape;
1057         orig->ConvertWithBackData(1.0);
1058         orig->Fill(theShape, 0);
1060         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1061         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1062         if (val && strcmp(val, "nonzero") == 0)
1063         {
1064             theRes->ConvertToShape(theShape, fill_nonZero);
1065         }
1066         else if (val && strcmp(val, "evenodd") == 0)
1067         {
1068             theRes->ConvertToShape(theShape, fill_oddEven);
1069         }
1070         else
1071         {
1072             theRes->ConvertToShape(theShape, fill_nonZero);
1073         }
1075         Path *originaux[1];
1076         originaux[0] = orig;
1077         theRes->ConvertToForme(res, 1, originaux);
1079         delete theShape;
1080         delete theRes;
1081     }
1083     sp_curve_unref(curve);
1085     if (res->descr_cmd.size() <= 1)
1086     {
1087         // pas vraiment de points sur le resultat
1088         // donc il ne reste rien
1089         sp_document_done(sp_desktop_document(desktop), 
1090                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1091                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1092                          (updating ? _("Create linked offset")
1093                           : _("Create dynamic offset")));
1094         selection->clear();
1096         delete res;
1097         delete orig;
1098         g_free(style);
1099         return;
1100     }
1102     {
1103         gchar tstr[80];
1105         tstr[79] = '\0';
1107         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1108         repr = xml_doc->createElement("svg:path");
1109         repr->setAttribute("sodipodi:type", "inkscape:offset");
1110         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1111                                                           ? o_width
1112                                                           : expand < 0
1113                                                           ? -o_width
1114                                                           : 0 ));
1116         str = res->svg_dump_path();
1117         repr->setAttribute("inkscape:original", str);
1118         g_free(str);
1120         if ( updating ) {
1121             char const *id = SP_OBJECT(item)->repr->attribute("id");
1122             char const *uri = g_strdup_printf("#%s", id);
1123             repr->setAttribute("xlink:href", uri);
1124             g_free((void *) uri);
1125         } else {
1126             repr->setAttribute("inkscape:href", NULL);
1127         }
1129         repr->setAttribute("style", style);
1131         // add the new repr to the parent
1132         parent->appendChild(repr);
1134         // move to the saved position
1135         repr->setPosition(pos > 0 ? pos : 0);
1137         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1139         if ( updating ) {
1140             // on conserve l'original
1141             // we reapply the transform to the original (offset will feel it)
1142             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1143         } else {
1144             // delete original, apply the transform to the offset
1145             SP_OBJECT(item)->deleteObject(false);
1146             sp_item_write_transform(nitem, repr, transform);
1147         }
1149         // The object just created from a temporary repr is only a seed.
1150         // We need to invoke its write which will update its real repr (in particular adding d=)
1151         SP_OBJECT(nitem)->updateRepr();
1153         Inkscape::GC::release(repr);
1155         selection->set(nitem);
1156     }
1158     sp_document_done(sp_desktop_document(desktop), 
1159                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1160                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1161                      (updating ? _("Create linked offset")
1162                       : _("Create dynamic offset")));
1164     delete res;
1165     delete orig;
1167     g_free(style);
1181 void
1182 sp_selected_path_do_offset(bool expand, double prefOffset)
1184     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1186     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1188     if (selection->isEmpty()) {
1189         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1190         return;
1191     }
1193     bool did = false;
1195     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1196          items != NULL;
1197          items = items->next) {
1199         SPItem *item = (SPItem *) items->data;
1201         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1202             continue;
1204         SPCurve *curve = NULL;
1205         if (SP_IS_SHAPE(item)) {
1206             curve = sp_shape_get_curve(SP_SHAPE(item));
1207             if (curve == NULL)
1208                 continue;
1209         }
1210         if (SP_IS_TEXT(item)) {
1211             curve = SP_TEXT(item)->getNormalizedBpath();
1212             if (curve == NULL)
1213                 continue;
1214         }
1216         NR::Matrix const transform(item->transform);
1218         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1220         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1222         float o_width, o_miter;
1223         JoinType o_join;
1224         ButtType o_butt;
1226         {
1227             SPStyle *i_style = SP_OBJECT(item)->style;
1228             int jointype, captype;
1230             jointype = i_style->stroke_linejoin.value;
1231             captype = i_style->stroke_linecap.value;
1232             o_width = i_style->stroke_width.computed;
1234             switch (jointype) {
1235                 case SP_STROKE_LINEJOIN_MITER:
1236                     o_join = join_pointy;
1237                     break;
1238                 case SP_STROKE_LINEJOIN_ROUND:
1239                     o_join = join_round;
1240                     break;
1241                 default:
1242                     o_join = join_straight;
1243                     break;
1244             }
1246             switch (captype) {
1247                 case SP_STROKE_LINECAP_SQUARE:
1248                     o_butt = butt_square;
1249                     break;
1250                 case SP_STROKE_LINECAP_ROUND:
1251                     o_butt = butt_round;
1252                     break;
1253                 default:
1254                     o_butt = butt_straight;
1255                     break;
1256             }
1258             o_width = prefOffset;
1260             if (o_width < 0.1)
1261                 o_width = 0.1;
1262             o_miter = i_style->stroke_miterlimit.value * o_width;
1263         }
1265         Path *orig = Path_for_item(item, false);
1266         if (orig == NULL) {
1267             g_free(style);
1268             sp_curve_unref(curve);
1269             continue;
1270         }
1272         Path *res = new Path;
1273         res->SetBackData(false);
1275         {
1276             Shape *theShape = new Shape;
1277             Shape *theRes = new Shape;
1279             orig->ConvertWithBackData(0.03);
1280             orig->Fill(theShape, 0);
1282             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1283             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1284             if (val && strcmp(val, "nonzero") == 0)
1285             {
1286                 theRes->ConvertToShape(theShape, fill_nonZero);
1287             }
1288             else if (val && strcmp(val, "evenodd") == 0)
1289             {
1290                 theRes->ConvertToShape(theShape, fill_oddEven);
1291             }
1292             else
1293             {
1294                 theRes->ConvertToShape(theShape, fill_nonZero);
1295             }
1297             // et maintenant: offset
1298             // methode inexacte
1299 /*                      Path *originaux[1];
1300                         originaux[0] = orig;
1301                         theRes->ConvertToForme(res, 1, originaux);
1303                         if (expand) {
1304                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1305                         } else {
1306                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1307                         }
1309                         orig->ConvertWithBackData(1.0);
1310                         orig->Fill(theShape, 0);
1311                         theRes->ConvertToShape(theShape, fill_positive);
1312                         originaux[0] = orig;
1313                         theRes->ConvertToForme(res, 1, originaux);
1315                         if (o_width >= 0.5) {
1316                         //     res->Coalesce(1.0);
1317                         res->ConvertEvenLines(1.0);
1318                         res->Simplify(1.0);
1319                         } else {
1320                         //      res->Coalesce(o_width);
1321                         res->ConvertEvenLines(1.0*o_width);
1322                         res->Simplify(1.0 * o_width);
1323                         }    */
1324             // methode par makeoffset
1326             if (expand)
1327             {
1328                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1329             }
1330             else
1331             {
1332                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1333             }
1334             theRes->ConvertToShape(theShape, fill_positive);
1336             res->Reset();
1337             theRes->ConvertToForme(res);
1339             if (o_width >= 1.0)
1340             {
1341                 res->ConvertEvenLines(1.0);
1342                 res->Simplify(1.0);
1343             }
1344             else
1345             {
1346                 res->ConvertEvenLines(1.0*o_width);
1347                 res->Simplify(1.0 * o_width);
1348             }
1350             delete theShape;
1351             delete theRes;
1352         }
1354         did = true;
1356         sp_curve_unref(curve);
1357         // remember the position of the item
1358         gint pos = SP_OBJECT_REPR(item)->position();
1359         // remember parent
1360         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1361         // remember id
1362         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1364         selection->remove(item);
1365         SP_OBJECT(item)->deleteObject(false);
1367         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1369             gchar tstr[80];
1371             tstr[79] = '\0';
1373             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1374             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1376             repr->setAttribute("style", style);
1378             gchar *str = res->svg_dump_path();
1379             repr->setAttribute("d", str);
1380             g_free(str);
1382             // add the new repr to the parent
1383             parent->appendChild(repr);
1385             // move to the saved position
1386             repr->setPosition(pos > 0 ? pos : 0);
1388             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1390             // reapply the transform
1391             sp_item_write_transform(newitem, repr, transform);
1393             repr->setAttribute("id", id);
1395             selection->add(repr);
1397             Inkscape::GC::release(repr);
1398         }
1400         delete orig;
1401         delete res;
1402     }
1404     if (did) {
1405         sp_document_done(sp_desktop_document(desktop), 
1406                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1407                          (expand ? _("Outset path") : _("Inset path")));
1408     } else {
1409         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1410         return;
1411     }
1415 static bool
1416 sp_selected_path_simplify_items(SPDesktop *desktop,
1417                                 Inkscape::Selection *selection, GSList *items,
1418                                 float threshold,  bool justCoalesce,
1419                                 float angleLimit, bool breakableAngles,
1420                                 bool modifySelection);
1423 //return true if we changed something, else false
1424 bool
1425 sp_selected_path_simplify_item(SPDesktop *desktop,
1426                  Inkscape::Selection *selection, SPItem *item,
1427                  float threshold,  bool justCoalesce,
1428                  float angleLimit, bool breakableAngles,
1429                  gdouble size,     bool modifySelection)
1431     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1432         return false;
1434     //If this is a group, do the children instead
1435     if (SP_IS_GROUP(item)) {
1436         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1437         
1438         return sp_selected_path_simplify_items(desktop, selection, items,
1439                                                threshold, justCoalesce,
1440                                                angleLimit, breakableAngles,
1441                                                false);
1442     }
1445     SPCurve *curve = NULL;
1447     if (SP_IS_SHAPE(item)) {
1448         curve = sp_shape_get_curve(SP_SHAPE(item));
1449         if (!curve)
1450             return false;
1451     }
1453     if (SP_IS_TEXT(item)) {
1454         curve = SP_TEXT(item)->getNormalizedBpath();
1455         if (!curve)
1456             return false;
1457     }
1459     // save the transform, to re-apply it after simplification
1460     NR::Matrix const transform(item->transform);
1462     /*
1463        reset the transform, effectively transforming the item by transform.inverse();
1464        this is necessary so that the item is transformed twice back and forth,
1465        allowing all compensations to cancel out regardless of the preferences
1466     */
1467     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1469     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1470     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1471     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1473     Path *orig = Path_for_item(item, false);
1474     if (orig == NULL) {
1475         g_free(style);
1476         sp_curve_unref(curve);
1477         return false;
1478     }
1480     sp_curve_unref(curve);
1481     // remember the position of the item
1482     gint pos = SP_OBJECT_REPR(item)->position();
1483     // remember parent
1484     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1485     // remember id
1486     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1488     //If a group was selected, to not change the selection list
1489     if (modifySelection)
1490         selection->remove(item);
1492     SP_OBJECT(item)->deleteObject(false);
1494     if ( justCoalesce ) {
1495         orig->Coalesce(threshold * size);
1496     } else {
1497         orig->ConvertEvenLines(threshold * size);
1498         orig->Simplify(threshold * size);
1499     }
1501     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1502     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1504     // restore style, mask and clip-path
1505     repr->setAttribute("style", style);
1506     g_free(style);
1508     if ( mask ) {
1509         repr->setAttribute("mask", mask);
1510         g_free(mask);
1511     }
1513     if ( clip_path ) {
1514         repr->setAttribute("clip-path", clip_path);
1515         g_free(clip_path);
1516     }
1518     // path
1519     gchar *str = orig->svg_dump_path();
1520     repr->setAttribute("d", str);
1521     g_free(str);
1523     // restore id
1524     repr->setAttribute("id", id);
1526     // add the new repr to the parent
1527     parent->appendChild(repr);
1529     // move to the saved position
1530     repr->setPosition(pos > 0 ? pos : 0);
1532     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1534     // reapply the transform
1535     sp_item_write_transform(newitem, repr, transform);
1537     //If we are not in a selected group
1538     if (modifySelection)
1539         selection->add(repr);
1541     Inkscape::GC::release(repr);
1543     // clean up
1544     if (orig) delete orig;
1546     return true;
1550 bool
1551 sp_selected_path_simplify_items(SPDesktop *desktop,
1552                                 Inkscape::Selection *selection, GSList *items,
1553                                 float threshold,  bool justCoalesce,
1554                                 float angleLimit, bool breakableAngles,
1555                                 bool modifySelection)
1557   bool simplifyIndividualPaths =
1558     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1559   
1560   gchar *simplificationType;
1561   if (simplifyIndividualPaths) {
1562       simplificationType = _("Simplifying paths (separately):");
1563   } else {
1564       simplificationType = _("Simplifying paths:");
1565   }
1567   bool didSomething = false;
1569   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1570   if (!selectionBbox) {
1571     return false;
1572   }
1573   gdouble selectionSize  = L2(selectionBbox->dimensions());
1575   gdouble simplifySize  = selectionSize;
1576   
1577   int pathsSimplified = 0;
1578   int totalPathCount  = g_slist_length(items);
1579   
1580   // set "busy" cursor
1581   desktop->setWaitingCursor();
1582   
1583   for (; items != NULL; items = items->next) {
1584       SPItem *item = (SPItem *) items->data;
1585       
1586       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1587           continue;
1589       if (simplifyIndividualPaths) {
1590           NR::Maybe<NR::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));        
1591           if (itemBbox) {
1592               simplifySize      = L2(itemBbox->dimensions());
1593           } else {
1594               simplifySize      = 0;
1595           }
1596       }
1598       pathsSimplified++;
1600       if (pathsSimplified % 20 == 0) {
1601         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1602         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1603       }
1605       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1606                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1607   }
1609   desktop->clearWaitingCursor();
1611   if (pathsSimplified > 20) {
1612     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1613   }
1614   
1615   return didSomething;
1618 void
1619 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1620                        float angleLimit, bool breakableAngles)
1622     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1624     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1626     if (selection->isEmpty()) {
1627         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1628                          _("Select <b>path(s)</b> to simplify."));
1629         return;
1630     }
1632     GSList *items = g_slist_copy((GSList *) selection->itemList());
1634     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1635                                                         items, threshold,
1636                                                         justCoalesce,
1637                                                         angleLimit,
1638                                                         breakableAngles, true);
1640     if (didSomething)
1641         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1642                          _("Simplify"));
1643     else
1644         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1649 // globals for keeping track of accelerated simplify
1650 static double previousTime      = 0.0;
1651 static gdouble simplifyMultiply = 1.0;
1653 void
1654 sp_selected_path_simplify(void)
1656     gdouble simplifyThreshold =
1657         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1658     bool simplifyJustCoalesce =
1659         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1661     //Get the current time
1662     GTimeVal currentTimeVal;
1663     g_get_current_time(&currentTimeVal);
1664     double currentTime = currentTimeVal.tv_sec * 1000000 +
1665                 currentTimeVal.tv_usec;
1667     //Was the previous call to this function recent? (<0.5 sec)
1668     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1670         // add to the threshold 1/2 of its original value
1671         simplifyMultiply  += 0.5;
1672         simplifyThreshold *= simplifyMultiply;
1674     } else {
1675         // reset to the default
1676         simplifyMultiply = 1;
1677     }
1679     //remember time for next call
1680     previousTime = currentTime;
1682     //g_print("%g\n", simplify_threshold);
1684     //Make the actual call
1685     sp_selected_path_simplify_selection(simplifyThreshold,
1686                       simplifyJustCoalesce, 0.0, false);
1691 // fonctions utilitaires
1693 bool
1694 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1696     if (who == NULL || a == NULL)
1697         return false;
1698     if (who == a)
1699         return true;
1700     return Ancetre(sp_repr_parent(a), who);
1703 Path *
1704 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1706     SPCurve *curve;
1708     if (!item)
1709         return NULL;
1711     if (SP_IS_SHAPE(item))
1712     {
1713         curve = sp_shape_get_curve(SP_SHAPE(item));
1714     }
1715     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1716     {
1717         curve = te_get_layout(item)->convertToCurves();
1718     }
1719     else if (SP_IS_IMAGE(item))
1720     {
1721         curve = sp_image_get_curve(SP_IMAGE(item));
1722     }
1723     else
1724     {
1725         curve = NULL;
1726     }
1728     if (!curve)
1729         return NULL;
1730     NArtBpath *bpath = SP_CURVE_BPATH(curve);
1731     if (bpath == NULL)
1732         return NULL;
1734     if ( doTransformation ) {
1735         if (transformFull)
1736             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), sp_item_i2doc_affine(item));
1737         else
1738             bpath = nr_artpath_affine(SP_CURVE_BPATH(curve), item->transform);
1739         sp_curve_unref(curve);
1740         curve=NULL;
1741     } else {
1742         bpath=SP_CURVE_BPATH(curve);
1743     }
1745     Path *dest = bpath_to_Path(bpath);
1747     if ( doTransformation ) {
1748         if ( bpath ) g_free(bpath);
1749     } else {
1750         sp_curve_unref(curve);
1751     }
1752     return dest;
1755 Path *bpath_to_Path(NArtBpath const *bpath) {
1756     Path *dest = new Path;
1757     dest->SetBackData(false);
1758     {
1759         int   i;
1760         bool  closed = false;
1761         float lastX  = 0.0;
1762         float lastY  = 0.0;
1764         for (i = 0; bpath[i].code != NR_END; i++) {
1765             switch (bpath[i].code) {
1766                 case NR_LINETO:
1767                     lastX = bpath[i].x3;
1768                     lastY = bpath[i].y3;
1769                     {
1770                         NR::Point tmp(lastX, lastY);
1771                         dest->LineTo(tmp);
1772                     }
1773                     break;
1775                 case NR_CURVETO:
1776                 {
1777                     NR::Point tmp, tms, tme;
1778                     tmp[0]=bpath[i].x3;
1779                     tmp[1]=bpath[i].y3;
1780                     tms[0]=3 * (bpath[i].x1 - lastX);
1781                     tms[1]=3 * (bpath[i].y1 - lastY);
1782                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1783                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1784                     dest->CubicTo(tmp,tms,tme);
1785                 }
1786                 lastX = bpath[i].x3;
1787                 lastY = bpath[i].y3;
1788                 break;
1790                 case NR_MOVETO_OPEN:
1791                 case NR_MOVETO:
1792                     if (closed)
1793                         dest->Close();
1794                     closed = (bpath[i].code == NR_MOVETO);
1795                     lastX = bpath[i].x3;
1796                     lastY = bpath[i].y3;
1797                     {
1798                         NR::Point  tmp(lastX, lastY);
1799                         dest->MoveTo(tmp);
1800                     }
1801                     break;
1802                 default:
1803                     break;
1804             }
1805         }
1806         if (closed)
1807             dest->Close();
1808     }
1809     return dest;
1812 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p)
1814     //get nearest position on path
1815     Path::cut_position pos = path->PointToCurvilignPosition(p);
1816     return pos;
1819 NR::Point get_point_on_Path(Path *path, int piece, double t)
1821     NR::Point p;
1822     path->PointAt(piece, t, p);
1823     return p;
1827 /*
1828   Local Variables:
1829   mode:c++
1830   c-file-style:"stroustrup"
1831   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1832   indent-tabs-mode:nil
1833   fill-column:99
1834   End:
1835 */
1836 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :