Code

Fixed erroneous overwriting of temporary images inside filter effects
[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) && !SP_IS_FLOWTEXT(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);
458     sp_item_adjust_livepatheffect(item_source, i2root);
460     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
462     // remember important aspects of the source path, to be restored
463     gint pos = repr_source->position();
464     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
465     gchar const *id = repr_source->attribute("id");
466     gchar const *style = repr_source->attribute("style");
467     gchar const *mask = repr_source->attribute("mask");
468     gchar const *clip_path = repr_source->attribute("clip-path");
470     // remove source paths
471     selection->clear();
472     for (GSList *l = il; l != NULL; l = l->next) {
473         // if this is the bottommost object,
474         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
475             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
476             SP_OBJECT(l->data)->deleteObject(false);
477         } else {
478             // delete the object for real, so that its clones can take appropriate action
479             SP_OBJECT(l->data)->deleteObject();
480         }
481     }
482     g_slist_free(il);
484     // premultiply by the inverse of parent's repr
485     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
486     NR::Matrix local = sp_item_i2doc_affine(parent_item);
487     gchar *transform = sp_svg_transform_write(local.inverse());
489     // now that we have the result, add it on the canvas
490     if ( bop == bool_op_cut || bop == bool_op_slice ) {
491         int    nbRP=0;
492         Path** resPath;
493         if ( bop == bool_op_slice ) {
494             // there are moveto's at each intersection, but it's still one unique path
495             // so break it down and add each subpath independently
496             // we could call break_apart to do this, but while we have the description...
497             resPath=res->SubPaths(nbRP, false);
498         } else {
499             // cut operation is a bit wicked: you need to keep holes
500             // that's why you needed the nesting
501             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
502             // to get the path for each part of the polygon. that's why you need the nesting info:
503             // to know in wich subpath to add a subpath
504             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
506             // cleaning
507             if ( conts ) free(conts);
508             if ( nesting ) free(nesting);
509         }
511         // add all the pieces resulting from cut or slice
512         for (int i=0;i<nbRP;i++) {
513             gchar *d = resPath[i]->svg_dump_path();
515             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
516             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
517             repr->setAttribute("style", style);
518             if (mask)
519                 repr->setAttribute("mask", mask);
520             if (clip_path)
521                 repr->setAttribute("clip-path", clip_path);
523             repr->setAttribute("d", d);
524             g_free(d);
526             // for slice, remove fill
527             if (bop == bool_op_slice) {
528                 SPCSSAttr *css;
530                 css = sp_repr_css_attr_new();
531                 sp_repr_css_set_property(css, "fill", "none");
533                 sp_repr_css_change(repr, css, "style");
535                 sp_repr_css_attr_unref(css);
536             }
538             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
539             // this means it's basically random which of the pieces inherits the original's id and clones
540             // a better algorithm might figure out e.g. the biggest piece
541             repr->setAttribute("id", id);
543             repr->setAttribute("transform", transform);
545             // add the new repr to the parent
546             parent->appendChild(repr);
548             // move to the saved position
549             repr->setPosition(pos > 0 ? pos : 0);
551             selection->add(repr);
552             Inkscape::GC::release(repr);
554             delete resPath[i];
555         }
556         if ( resPath ) free(resPath);
558     } else {
559         gchar *d = res->svg_dump_path();
561         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
562         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
563         repr->setAttribute("style", style);
565         if ( mask )
566             repr->setAttribute("mask", mask);
568         if ( clip_path )
569             repr->setAttribute("clip-path", clip_path);
571         repr->setAttribute("d", d);
572         g_free(d);
574         repr->setAttribute("transform", transform);
576         repr->setAttribute("id", id);
577         parent->appendChild(repr);
578         repr->setPosition(pos > 0 ? pos : 0);
580         selection->add(repr);
581         Inkscape::GC::release(repr);
582     }
584     g_free(transform);
586     if (verb != SP_VERB_NONE) {
587         sp_document_done(sp_desktop_document(desktop), verb, description);
588     }
590     delete res;
594 void
595 sp_selected_path_outline()
597     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
599     Inkscape::Selection *selection = sp_desktop_selection(desktop);
601     if (selection->isEmpty()) {
602         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
603         return;
604     }
606     bool did = false;
608     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
609          items != NULL;
610          items = items->next) {
612         SPItem *item = (SPItem *) items->data;
614         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
615             continue;
617         SPCurve *curve = NULL;
618         if (SP_IS_SHAPE(item)) {
619             curve = sp_shape_get_curve(SP_SHAPE(item));
620             if (curve == NULL)
621                 continue;
622         }
623         if (SP_IS_TEXT(item)) {
624             curve = SP_TEXT(item)->getNormalizedBpath();
625             if (curve == NULL)
626                 continue;
627         }
629         {   // pas de stroke pas de chocolat
630             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
631             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
633             if (val == NULL || strcmp(val, "none") == 0) {
634                 sp_curve_unref(curve);
635                 continue;
636             }
637         }
639         // remember old stroke style, to be set on fill
640         SPCSSAttr *ncss;
641         {
642             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
643             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
644             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
646             ncss = sp_repr_css_attr_new();
648             sp_repr_css_set_property(ncss, "stroke", "none");
649             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
650             sp_repr_css_set_property(ncss, "fill", val);
651             if ( opac ) {
652                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
653             } else {
654                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
655             }
656             sp_repr_css_unset_property(ncss, "marker-start");
657             sp_repr_css_unset_property(ncss, "marker-mid");
658             sp_repr_css_unset_property(ncss, "marker-end");
659         }
661         NR::Matrix const transform(item->transform);
662         float const scale = transform.expansion();
663         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
664         SPStyle *i_style = SP_OBJECT(item)->style;
665         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
666         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
668         float o_width, o_miter;
669         JoinType o_join;
670         ButtType o_butt;
672         {
673             int jointype, captype;
675             jointype = i_style->stroke_linejoin.computed;
676             captype = i_style->stroke_linecap.computed;
677             o_width = i_style->stroke_width.computed;
679             switch (jointype) {
680                 case SP_STROKE_LINEJOIN_MITER:
681                     o_join = join_pointy;
682                     break;
683                 case SP_STROKE_LINEJOIN_ROUND:
684                     o_join = join_round;
685                     break;
686                 default:
687                     o_join = join_straight;
688                     break;
689             }
691             switch (captype) {
692                 case SP_STROKE_LINECAP_SQUARE:
693                     o_butt = butt_square;
694                     break;
695                 case SP_STROKE_LINECAP_ROUND:
696                     o_butt = butt_round;
697                     break;
698                 default:
699                     o_butt = butt_straight;
700                     break;
701             }
703             if (o_width < 0.1)
704                 o_width = 0.1;
705             o_miter = i_style->stroke_miterlimit.value * o_width;
706         }
708         Path *orig = Path_for_item(item, false);
709         if (orig == NULL) {
710             g_free(style);
711             sp_curve_unref(curve);
712             continue;
713         }
715         Path *res = new Path;
716         res->SetBackData(false);
718         if (i_style->stroke_dash.n_dash) {
719             // For dashed strokes, use Stroke method, because Outline can't do dashes
720             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
722             orig->ConvertWithBackData(0.1);
724             orig->DashPolylineFromStyle(i_style, scale, 0);
726             Shape* theShape = new Shape;
727             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
728                          0.5 * o_miter);
729             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
731             Shape *theRes = new Shape;
733             theRes->ConvertToShape(theShape, fill_positive);
735             Path *originaux[1];
736             originaux[0] = res;
737             theRes->ConvertToForme(orig, 1, originaux);
739             res->Coalesce(5.0);
741             delete theShape;
742             delete theRes;
744         } else {
746             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
748             orig->Coalesce(0.5 * o_width);
750             Shape *theShape = new Shape;
751             Shape *theRes = new Shape;
753             res->ConvertWithBackData(1.0);
754             res->Fill(theShape, 0);
755             theRes->ConvertToShape(theShape, fill_positive);
757             Path *originaux[1];
758             originaux[0] = res;
759             theRes->ConvertToForme(orig, 1, originaux);
761             delete theShape;
762             delete theRes;
763         }
765         if (orig->descr_cmd.size() <= 1) {
766             // ca a merd\8e, ou bien le resultat est vide
767             delete res;
768             delete orig;
769             g_free(style);
770             continue;
771         }
773         did = true;
775         // remember the position of the item
776         gint pos = SP_OBJECT_REPR(item)->position();
777         // remember parent
778         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
779         // remember id
780         char const *id = SP_OBJECT_REPR(item)->attribute("id");
782         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
784             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
785             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
787             // restore old style
788             repr->setAttribute("style", style);
790             // set old stroke style on fill
791             sp_repr_css_change(repr, ncss, "style");
793             sp_repr_css_attr_unref(ncss);
795             gchar *str = orig->svg_dump_path();
796             repr->setAttribute("d", str);
797             g_free(str);
799             if (mask)
800                 repr->setAttribute("mask", mask);
801             if (clip_path)
802                 repr->setAttribute("clip-path", clip_path);
804             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
806                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
807                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
809                 // add the group to the parent
810                 parent->appendChild(g_repr);
811                 // move to the saved position
812                 g_repr->setPosition(pos > 0 ? pos : 0);
814                 g_repr->appendChild(repr);
815                 repr->setAttribute("id", id);
816                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
817                 sp_item_write_transform(newitem, repr, transform);
819                 SPShape *shape = SP_SHAPE(item);
821                 for (NArtBpath* bp = SP_CURVE_BPATH(shape->curve); bp->code != NR_END; bp++) {
822                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
823                         if (sp_shape_marker_required (shape, m, bp)) {
825                             SPMarker* marker = SP_MARKER (shape->marker[m]);
826                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
828                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
830                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
831                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
832                             }
834                             // total marker transform
835                             tr = marker_item->transform * marker->c2p * tr * transform;
837                             if (SP_OBJECT_REPR(marker_item)) {
838                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
839                                 g_repr->appendChild(m_repr);
840                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
841                                 sp_item_write_transform(marker_item, m_repr, tr);
842                             }
843                         }
844                     }
845                 }
848                 selection->add(g_repr);
850                 Inkscape::GC::release(g_repr);
853             } else {
855                 // add the new repr to the parent
856                 parent->appendChild(repr);
858                 // move to the saved position
859                 repr->setPosition(pos > 0 ? pos : 0);
861                 repr->setAttribute("id", id);
863                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
864                 sp_item_write_transform(newitem, repr, transform);
866                 selection->add(repr);
868             }
870             Inkscape::GC::release(repr);
872             sp_curve_unref(curve);
873             selection->remove(item);
874             SP_OBJECT(item)->deleteObject(false);
876         }
878         delete res;
879         delete orig;
880         g_free(style);
882     }
884     if (did) {
885         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
886                          _("Convert stroke to path"));
887     } else {
888         // TRANSLATORS: "to outline" means "to convert stroke to path"
889         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
890         return;
891     }
895 void
896 sp_selected_path_offset()
898     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
900     sp_selected_path_do_offset(true, prefOffset);
902 void
903 sp_selected_path_inset()
905     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
907     sp_selected_path_do_offset(false, prefOffset);
910 void
911 sp_selected_path_offset_screen(double pixels)
913     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
916 void
917 sp_selected_path_inset_screen(double pixels)
919     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
923 void sp_selected_path_create_offset_object_zero()
925     sp_selected_path_create_offset_object(0, false);
928 void sp_selected_path_create_offset()
930     sp_selected_path_create_offset_object(1, false);
932 void sp_selected_path_create_inset()
934     sp_selected_path_create_offset_object(-1, false);
937 void sp_selected_path_create_updating_offset_object_zero()
939     sp_selected_path_create_offset_object(0, true);
942 void sp_selected_path_create_updating_offset()
944     sp_selected_path_create_offset_object(1, true);
946 void sp_selected_path_create_updating_inset()
948     sp_selected_path_create_offset_object(-1, true);
951 void
952 sp_selected_path_create_offset_object(int expand, bool updating)
954     Inkscape::Selection *selection;
955     Inkscape::XML::Node *repr;
956     SPItem *item;
957     SPCurve *curve;
958     gchar *style, *str;
959     SPDesktop *desktop;
960     float o_width, o_miter;
961     JoinType o_join;
962     ButtType o_butt;
964     curve = NULL;
966     desktop = SP_ACTIVE_DESKTOP;
968     selection = sp_desktop_selection(desktop);
970     item = selection->singleItem();
972     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
973         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
974         return;
975     }
976     if (SP_IS_SHAPE(item))
977     {
978         curve = sp_shape_get_curve(SP_SHAPE(item));
979         if (curve == NULL)
980             return;
981     }
982     if (SP_IS_TEXT(item))
983     {
984         curve = SP_TEXT(item)->getNormalizedBpath();
985         if (curve == NULL)
986             return;
987     }
989     NR::Matrix const transform(item->transform);
991     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
993     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
995     // remember the position of the item
996     gint pos = SP_OBJECT_REPR(item)->position();
997     // remember parent
998     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1000     {
1001         SPStyle *i_style = SP_OBJECT(item)->style;
1002         int jointype, captype;
1004         jointype = i_style->stroke_linejoin.value;
1005         captype = i_style->stroke_linecap.value;
1006         o_width = i_style->stroke_width.computed;
1007         if (jointype == SP_STROKE_LINEJOIN_MITER)
1008         {
1009             o_join = join_pointy;
1010         }
1011         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1012         {
1013             o_join = join_round;
1014         }
1015         else
1016         {
1017             o_join = join_straight;
1018         }
1019         if (captype == SP_STROKE_LINECAP_SQUARE)
1020         {
1021             o_butt = butt_square;
1022         }
1023         else if (captype == SP_STROKE_LINECAP_ROUND)
1024         {
1025             o_butt = butt_round;
1026         }
1027         else
1028         {
1029             o_butt = butt_straight;
1030         }
1032         {
1033             double prefOffset = 1.0;
1034             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1035             o_width = prefOffset;
1036         }
1038         if (o_width < 0.01)
1039             o_width = 0.01;
1040         o_miter = i_style->stroke_miterlimit.value * o_width;
1041     }
1043     Path *orig = Path_for_item(item, true, false);
1044     if (orig == NULL)
1045     {
1046         g_free(style);
1047         sp_curve_unref(curve);
1048         return;
1049     }
1051     Path *res = new Path;
1052     res->SetBackData(false);
1054     {
1055         Shape *theShape = new Shape;
1056         Shape *theRes = new Shape;
1058         orig->ConvertWithBackData(1.0);
1059         orig->Fill(theShape, 0);
1061         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1062         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1063         if (val && strcmp(val, "nonzero") == 0)
1064         {
1065             theRes->ConvertToShape(theShape, fill_nonZero);
1066         }
1067         else if (val && strcmp(val, "evenodd") == 0)
1068         {
1069             theRes->ConvertToShape(theShape, fill_oddEven);
1070         }
1071         else
1072         {
1073             theRes->ConvertToShape(theShape, fill_nonZero);
1074         }
1076         Path *originaux[1];
1077         originaux[0] = orig;
1078         theRes->ConvertToForme(res, 1, originaux);
1080         delete theShape;
1081         delete theRes;
1082     }
1084     sp_curve_unref(curve);
1086     if (res->descr_cmd.size() <= 1)
1087     {
1088         // pas vraiment de points sur le resultat
1089         // donc il ne reste rien
1090         sp_document_done(sp_desktop_document(desktop), 
1091                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1092                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1093                          (updating ? _("Create linked offset")
1094                           : _("Create dynamic offset")));
1095         selection->clear();
1097         delete res;
1098         delete orig;
1099         g_free(style);
1100         return;
1101     }
1103     {
1104         gchar tstr[80];
1106         tstr[79] = '\0';
1108         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1109         repr = xml_doc->createElement("svg:path");
1110         repr->setAttribute("sodipodi:type", "inkscape:offset");
1111         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1112                                                           ? o_width
1113                                                           : expand < 0
1114                                                           ? -o_width
1115                                                           : 0 ));
1117         str = res->svg_dump_path();
1118         repr->setAttribute("inkscape:original", str);
1119         g_free(str);
1121         if ( updating ) {
1122             char const *id = SP_OBJECT(item)->repr->attribute("id");
1123             char const *uri = g_strdup_printf("#%s", id);
1124             repr->setAttribute("xlink:href", uri);
1125             g_free((void *) uri);
1126         } else {
1127             repr->setAttribute("inkscape:href", NULL);
1128         }
1130         repr->setAttribute("style", style);
1132         // add the new repr to the parent
1133         parent->appendChild(repr);
1135         // move to the saved position
1136         repr->setPosition(pos > 0 ? pos : 0);
1138         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1140         if ( updating ) {
1141             // on conserve l'original
1142             // we reapply the transform to the original (offset will feel it)
1143             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1144         } else {
1145             // delete original, apply the transform to the offset
1146             SP_OBJECT(item)->deleteObject(false);
1147             sp_item_write_transform(nitem, repr, transform);
1148         }
1150         // The object just created from a temporary repr is only a seed.
1151         // We need to invoke its write which will update its real repr (in particular adding d=)
1152         SP_OBJECT(nitem)->updateRepr();
1154         Inkscape::GC::release(repr);
1156         selection->set(nitem);
1157     }
1159     sp_document_done(sp_desktop_document(desktop), 
1160                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1161                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1162                      (updating ? _("Create linked offset")
1163                       : _("Create dynamic offset")));
1165     delete res;
1166     delete orig;
1168     g_free(style);
1182 void
1183 sp_selected_path_do_offset(bool expand, double prefOffset)
1185     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1187     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1189     if (selection->isEmpty()) {
1190         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1191         return;
1192     }
1194     bool did = false;
1196     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1197          items != NULL;
1198          items = items->next) {
1200         SPItem *item = (SPItem *) items->data;
1202         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1203             continue;
1205         SPCurve *curve = NULL;
1206         if (SP_IS_SHAPE(item)) {
1207             curve = sp_shape_get_curve(SP_SHAPE(item));
1208             if (curve == NULL)
1209                 continue;
1210         }
1211         if (SP_IS_TEXT(item)) {
1212             curve = SP_TEXT(item)->getNormalizedBpath();
1213             if (curve == NULL)
1214                 continue;
1215         }
1217         NR::Matrix const transform(item->transform);
1219         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1221         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1223         float o_width, o_miter;
1224         JoinType o_join;
1225         ButtType o_butt;
1227         {
1228             SPStyle *i_style = SP_OBJECT(item)->style;
1229             int jointype, captype;
1231             jointype = i_style->stroke_linejoin.value;
1232             captype = i_style->stroke_linecap.value;
1233             o_width = i_style->stroke_width.computed;
1235             switch (jointype) {
1236                 case SP_STROKE_LINEJOIN_MITER:
1237                     o_join = join_pointy;
1238                     break;
1239                 case SP_STROKE_LINEJOIN_ROUND:
1240                     o_join = join_round;
1241                     break;
1242                 default:
1243                     o_join = join_straight;
1244                     break;
1245             }
1247             switch (captype) {
1248                 case SP_STROKE_LINECAP_SQUARE:
1249                     o_butt = butt_square;
1250                     break;
1251                 case SP_STROKE_LINECAP_ROUND:
1252                     o_butt = butt_round;
1253                     break;
1254                 default:
1255                     o_butt = butt_straight;
1256                     break;
1257             }
1259             o_width = prefOffset;
1261             if (o_width < 0.1)
1262                 o_width = 0.1;
1263             o_miter = i_style->stroke_miterlimit.value * o_width;
1264         }
1266         Path *orig = Path_for_item(item, false);
1267         if (orig == NULL) {
1268             g_free(style);
1269             sp_curve_unref(curve);
1270             continue;
1271         }
1273         Path *res = new Path;
1274         res->SetBackData(false);
1276         {
1277             Shape *theShape = new Shape;
1278             Shape *theRes = new Shape;
1280             orig->ConvertWithBackData(0.03);
1281             orig->Fill(theShape, 0);
1283             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1284             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1285             if (val && strcmp(val, "nonzero") == 0)
1286             {
1287                 theRes->ConvertToShape(theShape, fill_nonZero);
1288             }
1289             else if (val && strcmp(val, "evenodd") == 0)
1290             {
1291                 theRes->ConvertToShape(theShape, fill_oddEven);
1292             }
1293             else
1294             {
1295                 theRes->ConvertToShape(theShape, fill_nonZero);
1296             }
1298             // et maintenant: offset
1299             // methode inexacte
1300 /*                      Path *originaux[1];
1301                         originaux[0] = orig;
1302                         theRes->ConvertToForme(res, 1, originaux);
1304                         if (expand) {
1305                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1306                         } else {
1307                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1308                         }
1310                         orig->ConvertWithBackData(1.0);
1311                         orig->Fill(theShape, 0);
1312                         theRes->ConvertToShape(theShape, fill_positive);
1313                         originaux[0] = orig;
1314                         theRes->ConvertToForme(res, 1, originaux);
1316                         if (o_width >= 0.5) {
1317                         //     res->Coalesce(1.0);
1318                         res->ConvertEvenLines(1.0);
1319                         res->Simplify(1.0);
1320                         } else {
1321                         //      res->Coalesce(o_width);
1322                         res->ConvertEvenLines(1.0*o_width);
1323                         res->Simplify(1.0 * o_width);
1324                         }    */
1325             // methode par makeoffset
1327             if (expand)
1328             {
1329                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1330             }
1331             else
1332             {
1333                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1334             }
1335             theRes->ConvertToShape(theShape, fill_positive);
1337             res->Reset();
1338             theRes->ConvertToForme(res);
1340             if (o_width >= 1.0)
1341             {
1342                 res->ConvertEvenLines(1.0);
1343                 res->Simplify(1.0);
1344             }
1345             else
1346             {
1347                 res->ConvertEvenLines(1.0*o_width);
1348                 res->Simplify(1.0 * o_width);
1349             }
1351             delete theShape;
1352             delete theRes;
1353         }
1355         did = true;
1357         sp_curve_unref(curve);
1358         // remember the position of the item
1359         gint pos = SP_OBJECT_REPR(item)->position();
1360         // remember parent
1361         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1362         // remember id
1363         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1365         selection->remove(item);
1366         SP_OBJECT(item)->deleteObject(false);
1368         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1370             gchar tstr[80];
1372             tstr[79] = '\0';
1374             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1375             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1377             repr->setAttribute("style", style);
1379             gchar *str = res->svg_dump_path();
1380             repr->setAttribute("d", str);
1381             g_free(str);
1383             // add the new repr to the parent
1384             parent->appendChild(repr);
1386             // move to the saved position
1387             repr->setPosition(pos > 0 ? pos : 0);
1389             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1391             // reapply the transform
1392             sp_item_write_transform(newitem, repr, transform);
1394             repr->setAttribute("id", id);
1396             selection->add(repr);
1398             Inkscape::GC::release(repr);
1399         }
1401         delete orig;
1402         delete res;
1403     }
1405     if (did) {
1406         sp_document_done(sp_desktop_document(desktop), 
1407                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1408                          (expand ? _("Outset path") : _("Inset path")));
1409     } else {
1410         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1411         return;
1412     }
1416 static bool
1417 sp_selected_path_simplify_items(SPDesktop *desktop,
1418                                 Inkscape::Selection *selection, GSList *items,
1419                                 float threshold,  bool justCoalesce,
1420                                 float angleLimit, bool breakableAngles,
1421                                 bool modifySelection);
1424 //return true if we changed something, else false
1425 bool
1426 sp_selected_path_simplify_item(SPDesktop *desktop,
1427                  Inkscape::Selection *selection, SPItem *item,
1428                  float threshold,  bool justCoalesce,
1429                  float angleLimit, bool breakableAngles,
1430                  gdouble size,     bool modifySelection)
1432     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1433         return false;
1435     //If this is a group, do the children instead
1436     if (SP_IS_GROUP(item)) {
1437         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1438         
1439         return sp_selected_path_simplify_items(desktop, selection, items,
1440                                                threshold, justCoalesce,
1441                                                angleLimit, breakableAngles,
1442                                                false);
1443     }
1446     SPCurve *curve = NULL;
1448     if (SP_IS_SHAPE(item)) {
1449         curve = sp_shape_get_curve(SP_SHAPE(item));
1450         if (!curve)
1451             return false;
1452     }
1454     if (SP_IS_TEXT(item)) {
1455         curve = SP_TEXT(item)->getNormalizedBpath();
1456         if (!curve)
1457             return false;
1458     }
1460     // save the transform, to re-apply it after simplification
1461     NR::Matrix const transform(item->transform);
1463     /*
1464        reset the transform, effectively transforming the item by transform.inverse();
1465        this is necessary so that the item is transformed twice back and forth,
1466        allowing all compensations to cancel out regardless of the preferences
1467     */
1468     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1470     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1471     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1472     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1474     Path *orig = Path_for_item(item, false);
1475     if (orig == NULL) {
1476         g_free(style);
1477         sp_curve_unref(curve);
1478         return false;
1479     }
1481     sp_curve_unref(curve);
1482     // remember the position of the item
1483     gint pos = SP_OBJECT_REPR(item)->position();
1484     // remember parent
1485     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1486     // remember id
1487     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1488     // remember path effect
1489     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1491     //If a group was selected, to not change the selection list
1492     if (modifySelection)
1493         selection->remove(item);
1495     SP_OBJECT(item)->deleteObject(false);
1497     if ( justCoalesce ) {
1498         orig->Coalesce(threshold * size);
1499     } else {
1500         orig->ConvertEvenLines(threshold * size);
1501         orig->Simplify(threshold * size);
1502     }
1504     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1505     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1507     // restore style, mask and clip-path
1508     repr->setAttribute("style", style);
1509     g_free(style);
1511     if ( mask ) {
1512         repr->setAttribute("mask", mask);
1513         g_free(mask);
1514     }
1516     if ( clip_path ) {
1517         repr->setAttribute("clip-path", clip_path);
1518         g_free(clip_path);
1519     }
1521     // path
1522     gchar *str = orig->svg_dump_path();
1523     if (patheffect)
1524         repr->setAttribute("inkscape:original-d", str);
1525     else 
1526         repr->setAttribute("d", str);
1527     g_free(str);
1529     // restore id
1530     repr->setAttribute("id", id);
1532     // add the new repr to the parent
1533     parent->appendChild(repr);
1535     // move to the saved position
1536     repr->setPosition(pos > 0 ? pos : 0);
1538     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1540     // reapply the transform
1541     sp_item_write_transform(newitem, repr, transform);
1543     // restore path effect
1544     repr->setAttribute("inkscape:path-effect", patheffect);
1546     //If we are not in a selected group
1547     if (modifySelection)
1548         selection->add(repr);
1550     Inkscape::GC::release(repr);
1552     // clean up
1553     if (orig) delete orig;
1555     return true;
1559 bool
1560 sp_selected_path_simplify_items(SPDesktop *desktop,
1561                                 Inkscape::Selection *selection, GSList *items,
1562                                 float threshold,  bool justCoalesce,
1563                                 float angleLimit, bool breakableAngles,
1564                                 bool modifySelection)
1566   bool simplifyIndividualPaths =
1567     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1568   
1569   gchar *simplificationType;
1570   if (simplifyIndividualPaths) {
1571       simplificationType = _("Simplifying paths (separately):");
1572   } else {
1573       simplificationType = _("Simplifying paths:");
1574   }
1576   bool didSomething = false;
1578   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1579   if (!selectionBbox) {
1580     return false;
1581   }
1582   gdouble selectionSize  = L2(selectionBbox->dimensions());
1584   gdouble simplifySize  = selectionSize;
1585   
1586   int pathsSimplified = 0;
1587   int totalPathCount  = g_slist_length(items);
1588   
1589   // set "busy" cursor
1590   desktop->setWaitingCursor();
1591   
1592   for (; items != NULL; items = items->next) {
1593       SPItem *item = (SPItem *) items->data;
1594       
1595       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1596           continue;
1598       if (simplifyIndividualPaths) {
1599           NR::Maybe<NR::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));        
1600           if (itemBbox) {
1601               simplifySize      = L2(itemBbox->dimensions());
1602           } else {
1603               simplifySize      = 0;
1604           }
1605       }
1607       pathsSimplified++;
1609       if (pathsSimplified % 20 == 0) {
1610         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1611         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1612       }
1614       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1615                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1616   }
1618   desktop->clearWaitingCursor();
1620   if (pathsSimplified > 20) {
1621     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1622   }
1623   
1624   return didSomething;
1627 void
1628 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1629                        float angleLimit, bool breakableAngles)
1631     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1633     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1635     if (selection->isEmpty()) {
1636         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1637                          _("Select <b>path(s)</b> to simplify."));
1638         return;
1639     }
1641     GSList *items = g_slist_copy((GSList *) selection->itemList());
1643     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1644                                                         items, threshold,
1645                                                         justCoalesce,
1646                                                         angleLimit,
1647                                                         breakableAngles, true);
1649     if (didSomething)
1650         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1651                          _("Simplify"));
1652     else
1653         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1658 // globals for keeping track of accelerated simplify
1659 static double previousTime      = 0.0;
1660 static gdouble simplifyMultiply = 1.0;
1662 void
1663 sp_selected_path_simplify(void)
1665     gdouble simplifyThreshold =
1666         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1667     bool simplifyJustCoalesce =
1668         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1670     //Get the current time
1671     GTimeVal currentTimeVal;
1672     g_get_current_time(&currentTimeVal);
1673     double currentTime = currentTimeVal.tv_sec * 1000000 +
1674                 currentTimeVal.tv_usec;
1676     //Was the previous call to this function recent? (<0.5 sec)
1677     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1679         // add to the threshold 1/2 of its original value
1680         simplifyMultiply  += 0.5;
1681         simplifyThreshold *= simplifyMultiply;
1683     } else {
1684         // reset to the default
1685         simplifyMultiply = 1;
1686     }
1688     //remember time for next call
1689     previousTime = currentTime;
1691     //g_print("%g\n", simplify_threshold);
1693     //Make the actual call
1694     sp_selected_path_simplify_selection(simplifyThreshold,
1695                       simplifyJustCoalesce, 0.0, false);
1700 // fonctions utilitaires
1702 bool
1703 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1705     if (who == NULL || a == NULL)
1706         return false;
1707     if (who == a)
1708         return true;
1709     return Ancetre(sp_repr_parent(a), who);
1712 Path *
1713 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1715     SPCurve *curve = curve_for_item(item);
1716     NArtBpath *bpath = bpath_for_curve(item, curve, doTransformation, transformFull);
1717     
1718     if (bpath == NULL) {
1719         return NULL;
1720     }
1721     
1722     Path *dest = bpath_to_Path(bpath);
1724     if (doTransformation) {
1725         g_free(bpath); // see comment in bpath_for_curve
1726     }
1727     
1728     sp_curve_unref(curve);
1729     
1730     return dest;
1733 NArtBpath *
1734 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1736     if (curve == NULL)
1737         return NULL;
1739     NArtBpath *bpath = SP_CURVE_BPATH(curve);
1740     if (bpath == NULL) {
1741         return NULL;
1742     }
1743     
1744     if (doTransformation) {
1745         NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1746         if (transformFull) {
1747             new_bpath = nr_artpath_affine(bpath, sp_item_i2doc_affine(item));
1748         } else {
1749             new_bpath = nr_artpath_affine(bpath, item->transform);
1750         }
1751         bpath = new_bpath;
1752     }
1754     return bpath;
1757 SPCurve* curve_for_item(SPItem *item)
1759     if (!item)
1760         return NULL;
1762     SPCurve *curve = NULL;
1764     if (SP_IS_SHAPE(item)) {
1765         if (SP_IS_PATH(item)) {
1766             curve = sp_path_get_curve_for_edit(SP_PATH(item));
1767         } else {
1768             curve = sp_shape_get_curve(SP_SHAPE(item));
1769         }
1770     }
1771     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1772     {
1773         curve = te_get_layout(item)->convertToCurves();
1774     }
1775     else if (SP_IS_IMAGE(item))
1776     {
1777         curve = sp_image_get_curve(SP_IMAGE(item));
1778     }
1779     
1780     return curve; // do not forget to unref the curve at some point!
1783 Path *bpath_to_Path(NArtBpath const *bpath) {
1784     Path *dest = new Path;
1785     dest->SetBackData(false);
1786     {
1787         int   i;
1788         bool  closed = false;
1789         float lastX  = 0.0;
1790         float lastY  = 0.0;
1792         for (i = 0; bpath[i].code != NR_END; i++) {
1793             switch (bpath[i].code) {
1794                 case NR_LINETO:
1795                     lastX = bpath[i].x3;
1796                     lastY = bpath[i].y3;
1797                     {
1798                         NR::Point tmp(lastX, lastY);
1799                         dest->LineTo(tmp);
1800                     }
1801                     break;
1803                 case NR_CURVETO:
1804                 {
1805                     NR::Point tmp, tms, tme;
1806                     tmp[0]=bpath[i].x3;
1807                     tmp[1]=bpath[i].y3;
1808                     tms[0]=3 * (bpath[i].x1 - lastX);
1809                     tms[1]=3 * (bpath[i].y1 - lastY);
1810                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1811                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1812                     dest->CubicTo(tmp,tms,tme);
1813                 }
1814                 lastX = bpath[i].x3;
1815                 lastY = bpath[i].y3;
1816                 break;
1818                 case NR_MOVETO_OPEN:
1819                 case NR_MOVETO:
1820                     if (closed)
1821                         dest->Close();
1822                     closed = (bpath[i].code == NR_MOVETO);
1823                     lastX = bpath[i].x3;
1824                     lastY = bpath[i].y3;
1825                     {
1826                         NR::Point  tmp(lastX, lastY);
1827                         dest->MoveTo(tmp);
1828                     }
1829                     break;
1830                 default:
1831                     break;
1832             }
1833         }
1834         if (closed)
1835             dest->Close();
1836     }
1837     return dest;
1840 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p)
1842     //get nearest position on path
1843     Path::cut_position pos = path->PointToCurvilignPosition(p);
1844     return pos;
1847 NR::Point get_point_on_Path(Path *path, int piece, double t)
1849     NR::Point p;
1850     path->PointAt(piece, t, p);
1851     return p;
1855 /*
1856   Local Variables:
1857   mode:c++
1858   c-file-style:"stroustrup"
1859   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1860   indent-tabs-mode:nil
1861   fill-column:99
1862   End:
1863 */
1864 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :