Code

change some SP_CURVE_BPATH to get_bpath
[inkscape.git] / src / splivarot.cpp
1 #define __SP_LIVAROT_C__
2 /*
3  *  splivarot.cpp
4  *  Inkscape
5  *
6  *  Created by fred on Fri Dec 05 2003.
7  *  tweaked endlessly by bulia byak <buliabyak@users.sf.net>
8  *  public domain
9  *
10  */
12 /*
13  * contains lots of stitched pieces of path-chemistry.c
14  */
16 #ifdef HAVE_CONFIG_H
17 # include <config.h>
18 #endif
20 #include <cstring>
21 #include <string>
22 #include <vector>
23 #include <glib/gmem.h>
24 #include "xml/repr.h"
25 #include "svg/svg.h"
26 #include "sp-path.h"
27 #include "sp-shape.h"
28 #include "sp-image.h"
29 #include "marker.h"
30 #include "enums.h"
31 #include "sp-text.h"
32 #include "sp-flowtext.h"
33 #include "text-editing.h"
34 #include "sp-item-group.h"
35 #include "style.h"
36 #include "inkscape.h"
37 #include "document.h"
38 #include "message-stack.h"
39 #include "selection.h"
40 #include "desktop-handles.h"
41 #include "desktop.h"
42 #include "display/canvas-bpath.h"
43 #include "display/curve.h"
44 #include <glibmm/i18n.h>
45 #include "prefs-utils.h"
47 #include "libnr/n-art-bpath.h"
48 #include "libnr/nr-path.h"
49 #include "xml/repr.h"
50 #include "xml/repr-sorting.h"
52 #include <libnr/nr-matrix-fns.h>
53 #include <libnr/nr-matrix-ops.h>
54 #include <libnr/nr-matrix-translate-ops.h>
55 #include <libnr/nr-scale-matrix-ops.h>
57 #include "livarot/Path.h"
58 #include "livarot/Shape.h"
60 #include "splivarot.h"
62 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
64 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
65 void sp_selected_path_do_offset(bool expand, double prefOffset);
66 void sp_selected_path_create_offset_object(int expand, bool updating);
68 void
69 sp_selected_path_union()
70 {
71     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
72 }
74 void
75 sp_selected_path_union_skip_undo()
76 {
77     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
78 }
80 void
81 sp_selected_path_intersect()
82 {
83     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
84 }
86 void
87 sp_selected_path_diff()
88 {
89     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
90 }
92 void
93 sp_selected_path_diff_skip_undo()
94 {
95     sp_selected_path_boolop(bool_op_diff, SP_VERB_NONE, _("Difference"));
96 }
98 void
99 sp_selected_path_symdiff()
101     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
103 void
104 sp_selected_path_cut()
106     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
108 void
109 sp_selected_path_slice()
111     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
115 // boolean operations
116 // take the source paths from the file, do the operation, delete the originals and add the results
117 void
118 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
120     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
122     Inkscape::Selection *selection = sp_desktop_selection(desktop);
123     
124     GSList *il = (GSList *) selection->itemList();
125     
126     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
127     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
128         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
129         return;
130     }
131     else if ( g_slist_length(il) < 1 ) {
132         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
133         return;
134     }
136     if (g_slist_length(il) > 2) {
137         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
138             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
139             return;
140         }
141     }
143     // reverseOrderForOp marks whether the order of the list is the top->down order
144     // it's only used when there are 2 objects, and for operations who need to know the
145     // topmost object (differences, cuts)
146     bool reverseOrderForOp = false;
148     // mettre les elements de la liste dans l'ordre pour ces operations
149     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
150         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
151         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
152         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
154         if (a == NULL || b == NULL) {
155             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."));
156             return;
157         }
159         if (Ancetre(a, b)) {
160             // a is the parent of b, already in the proper order
161         } else if (Ancetre(b, a)) {
162             // reverse order
163             reverseOrderForOp = true;
164         } else {
166             // objects are not in parent/child relationship;
167             // find their lowest common ancestor
168             Inkscape::XML::Node *dad = LCA(a, b);
169             if (dad == NULL) {
170                 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."));
171                 return;
172             }
174             // find the children of the LCA that lead from it to the a and b
175             Inkscape::XML::Node *as = AncetreFils(a, dad);
176             Inkscape::XML::Node *bs = AncetreFils(b, dad);
178             // find out which comes first
179             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
180                 if (child == as) {
181                     /* a first, so reverse. */
182                     reverseOrderForOp = true;
183                     break;
184                 }
185                 if (child == bs)
186                     break;
187             }
188         }
189     }
191     il = g_slist_copy(il);
193     // first check if all the input objects have shapes
194     // otherwise bail out
195     for (GSList *l = il; l != NULL; l = l->next)
196     {
197         SPItem *item = SP_ITEM(l->data);
198         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
199         {
200             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
201             g_slist_free(il);
202             return;
203         }
204     }
206     // extract the livarot Paths from the source objects
207     // also get the winding rule specified in the style
208     int nbOriginaux = g_slist_length(il);
209     std::vector<Path *> originaux(nbOriginaux);
210     std::vector<FillRule> origWind(nbOriginaux);
211     int curOrig;
212     {
213         curOrig = 0;
214         for (GSList *l = il; l != NULL; l = l->next)
215         {
216             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
217             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
218             if (val && strcmp(val, "nonzero") == 0) {
219                 origWind[curOrig]= fill_nonZero;
220             } else if (val && strcmp(val, "evenodd") == 0) {
221                 origWind[curOrig]= fill_oddEven;
222             } else {
223                 origWind[curOrig]= fill_nonZero;
224             }
226             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
227             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
228             {
229                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
230                 g_slist_free(il);
231                 return;
232             }
233             curOrig++;
234         }
235     }
236     // reverse if needed
237     // note that the selection list keeps its order
238     if ( reverseOrderForOp ) {
239         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
240         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
241     }
243     // and work
244     // some temporary instances, first
245     Shape *theShapeA = new Shape;
246     Shape *theShapeB = new Shape;
247     Shape *theShape = new Shape;
248     Path *res = new Path;
249     res->SetBackData(false);
250     Path::cut_position  *toCut=NULL;
251     int                  nbToCut=0;
253     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
254         // true boolean op
255         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
256         originaux[0]->ConvertWithBackData(0.1);
258         originaux[0]->Fill(theShape, 0);
260         theShapeA->ConvertToShape(theShape, origWind[0]);
262         curOrig = 1;
263         for (GSList *l = il->next; l != NULL; l = l->next) {
264             originaux[curOrig]->ConvertWithBackData(0.1);
266             originaux[curOrig]->Fill(theShape, curOrig);
268             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
270             // les elements arrivent en ordre inverse dans la liste
271             theShape->Booleen(theShapeB, theShapeA, bop);
273             {
274                 Shape *swap = theShape;
275                 theShape = theShapeA;
276                 theShapeA = swap;
277             }
278             curOrig++;
279         }
281         {
282             Shape *swap = theShape;
283             theShape = theShapeA;
284             theShapeA = swap;
285         }
287     } else if ( bop == bool_op_cut ) {
288         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
289         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
290         // it is just uncrossed, and cleaned from duplicate edges and points
291         // then it's fed to Booleen() which will uncross it against the other path
292         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
293         // thus making a polygon. the weight of the edges of the cut are all 0, but
294         // the Booleen need to invert the ones inside the source polygon (for the subsequent
295         // ConvertToForme)
297         // the cut path needs to have the highest pathID in the back data
298         // that's how the Booleen() function knows it's an edge of the cut
300         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
301         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
302         // left it at 1.0. Investigate replacing this by a combination of difference and
303         // intersection of the same two paths. -- bb
304         {
305             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
306             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
307         }
308         originaux[0]->ConvertWithBackData(1.0);
310         originaux[0]->Fill(theShape, 0);
312         theShapeA->ConvertToShape(theShape, origWind[0]);
314         originaux[1]->ConvertWithBackData(1.0);
316         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
318         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
320         // les elements arrivent en ordre inverse dans la liste
321         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
323     } else if ( bop == bool_op_slice ) {
324         // slice is not really a boolean operation
325         // you just put the 2 shapes in a single polygon, uncross it
326         // the points where the degree is > 2 are intersections
327         // just check it's an intersection on the path you want to cut, and keep it
328         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
329         // make new subpath at each one of these positions
330         // inversion pour l'op\8eration
331         {
332             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
333             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
334         }
335         originaux[0]->ConvertWithBackData(1.0);
337         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
339         originaux[1]->ConvertWithBackData(1.0);
341         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
343         theShape->ConvertToShape(theShapeA, fill_justDont);
345         if ( theShape->hasBackData() ) {
346             // should always be the case, but ya never know
347             {
348                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
349                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
350                         // possibly an intersection
351                         // we need to check that at least one edge from the source path is incident to it
352                         // before we declare it's an intersection
353                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
354                         int   nbOrig=0;
355                         int   nbOther=0;
356                         int   piece=-1;
357                         float t=0.0;
358                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
359                             if ( theShape->ebData[cb].pathID == 0 ) {
360                                 // the source has an edge incident to the point, get its position on the path
361                                 piece=theShape->ebData[cb].pieceID;
362                                 if ( theShape->getEdge(cb).st == i ) {
363                                     t=theShape->ebData[cb].tSt;
364                                 } else {
365                                     t=theShape->ebData[cb].tEn;
366                                 }
367                                 nbOrig++;
368                             }
369                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
370                             cb=theShape->NextAt(i, cb);
371                         }
372                         if ( nbOrig > 0 && nbOther > 0 ) {
373                             // point incident to both path and cut: an intersection
374                             // note that you only keep one position on the source; you could have degenerate
375                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
376                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
377                             toCut[nbToCut].piece=piece;
378                             toCut[nbToCut].t=t;
379                             nbToCut++;
380                         }
381                     }
382                 }
383             }
384             {
385                 // i think it's useless now
386                 int i = theShape->numberOfEdges() - 1;
387                 for (;i>=0;i--) {
388                     if ( theShape->ebData[i].pathID == 1 ) {
389                         theShape->SubEdge(i);
390                     }
391                 }
392             }
394         }
395     }
397     int*    nesting=NULL;
398     int*    conts=NULL;
399     int     nbNest=0;
400     // pour compenser le swap juste avant
401     if ( bop == bool_op_slice ) {
402 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
403 //    res->ConvertForcedToMoveTo();
404         res->Copy(originaux[0]);
405         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
406         free(toCut);
407     } else if ( bop == bool_op_cut ) {
408         // il faut appeler pour desallouer PointData (pas vital, mais bon)
409         // the Booleen() function did not deallocated the point_data array in theShape, because this
410         // function needs it.
411         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
412         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
413         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
414     } else {
415         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
416     }
418     delete theShape;
419     delete theShapeA;
420     delete theShapeB;
421     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
423     if (res->descr_cmd.size() <= 1)
424     {
425         // only one command, presumably a moveto: it isn't a path
426         for (GSList *l = il; l != NULL; l = l->next)
427         {
428             SP_OBJECT(l->data)->deleteObject();
429         }
430         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
431                          description);
432         selection->clear();
434         delete res;
435         g_slist_free(il);
436         return;
437     }
439     // get the source path object
440     SPObject *source;
441     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
442         if (reverseOrderForOp) {
443              source = SP_OBJECT(il->data);
444         } else {
445              source = SP_OBJECT(il->next->data);
446         }
447     } else {
448         // find out the bottom object
449         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
451         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
453         source = sp_desktop_document(desktop)->
454             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
456         g_slist_free(sorted);
457     }
459     // adjust style properties that depend on a possible transform in the source object in order
460     // to get a correct style attribute for the new path
461     SPItem* item_source = SP_ITEM(source);
462     NR::Matrix i2root = from_2geom(sp_item_i2root_affine(item_source));
463     sp_item_adjust_stroke(item_source, NR::expansion(i2root));
464     sp_item_adjust_pattern(item_source, i2root);
465     sp_item_adjust_gradient(item_source, i2root);
466     sp_item_adjust_livepatheffect(item_source, i2root);
468     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
470     // remember important aspects of the source path, to be restored
471     gint pos = repr_source->position();
472     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
473     gchar const *id = repr_source->attribute("id");
474     gchar const *style = repr_source->attribute("style");
475     gchar const *mask = repr_source->attribute("mask");
476     gchar const *clip_path = repr_source->attribute("clip-path");
478     // remove source paths
479     selection->clear();
480     for (GSList *l = il; l != NULL; l = l->next) {
481         // if this is the bottommost object,
482         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
483             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
484             SP_OBJECT(l->data)->deleteObject(false);
485         } else {
486             // delete the object for real, so that its clones can take appropriate action
487             SP_OBJECT(l->data)->deleteObject();
488         }
489     }
490     g_slist_free(il);
492     // premultiply by the inverse of parent's repr
493     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
494     NR::Matrix local = from_2geom(sp_item_i2doc_affine(parent_item));
495     gchar *transform = sp_svg_transform_write(local.inverse());
497     // now that we have the result, add it on the canvas
498     if ( bop == bool_op_cut || bop == bool_op_slice ) {
499         int    nbRP=0;
500         Path** resPath;
501         if ( bop == bool_op_slice ) {
502             // there are moveto's at each intersection, but it's still one unique path
503             // so break it down and add each subpath independently
504             // we could call break_apart to do this, but while we have the description...
505             resPath=res->SubPaths(nbRP, false);
506         } else {
507             // cut operation is a bit wicked: you need to keep holes
508             // that's why you needed the nesting
509             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
510             // to get the path for each part of the polygon. that's why you need the nesting info:
511             // to know in wich subpath to add a subpath
512             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
514             // cleaning
515             if ( conts ) free(conts);
516             if ( nesting ) free(nesting);
517         }
519         // add all the pieces resulting from cut or slice
520         for (int i=0;i<nbRP;i++) {
521             gchar *d = resPath[i]->svg_dump_path();
523             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
524             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
525             repr->setAttribute("style", style);
526             if (mask)
527                 repr->setAttribute("mask", mask);
528             if (clip_path)
529                 repr->setAttribute("clip-path", clip_path);
531             repr->setAttribute("d", d);
532             g_free(d);
534             // for slice, remove fill
535             if (bop == bool_op_slice) {
536                 SPCSSAttr *css;
538                 css = sp_repr_css_attr_new();
539                 sp_repr_css_set_property(css, "fill", "none");
541                 sp_repr_css_change(repr, css, "style");
543                 sp_repr_css_attr_unref(css);
544             }
546             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
547             // this means it's basically random which of the pieces inherits the original's id and clones
548             // a better algorithm might figure out e.g. the biggest piece
549             repr->setAttribute("id", id);
551             repr->setAttribute("transform", transform);
553             // add the new repr to the parent
554             parent->appendChild(repr);
556             // move to the saved position
557             repr->setPosition(pos > 0 ? pos : 0);
559             selection->add(repr);
560             Inkscape::GC::release(repr);
562             delete resPath[i];
563         }
564         if ( resPath ) free(resPath);
566     } else {
567         gchar *d = res->svg_dump_path();
569         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
570         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
571         repr->setAttribute("style", style);
573         if ( mask )
574             repr->setAttribute("mask", mask);
576         if ( clip_path )
577             repr->setAttribute("clip-path", clip_path);
579         repr->setAttribute("d", d);
580         g_free(d);
582         repr->setAttribute("transform", transform);
584         repr->setAttribute("id", id);
585         parent->appendChild(repr);
586         repr->setPosition(pos > 0 ? pos : 0);
588         selection->add(repr);
589         Inkscape::GC::release(repr);
590     }
592     g_free(transform);
594     if (verb != SP_VERB_NONE) {
595         sp_document_done(sp_desktop_document(desktop), verb, description);
596     }
598     delete res;
602 void
603 sp_selected_path_outline()
605     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
607     Inkscape::Selection *selection = sp_desktop_selection(desktop);
609     if (selection->isEmpty()) {
610         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
611         return;
612     }
614     bool did = false;
616     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
617          items != NULL;
618          items = items->next) {
620         SPItem *item = (SPItem *) items->data;
622         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
623             continue;
625         SPCurve *curve = NULL;
626         if (SP_IS_SHAPE(item)) {
627             curve = sp_shape_get_curve(SP_SHAPE(item));
628             if (curve == NULL)
629                 continue;
630         }
631         if (SP_IS_TEXT(item)) {
632             curve = SP_TEXT(item)->getNormalizedBpath();
633             if (curve == NULL)
634                 continue;
635         }
637         {   // pas de stroke pas de chocolat
638             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
639             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
641             if (val == NULL || strcmp(val, "none") == 0) {
642                 curve->unref();
643                 continue;
644             }
645         }
647         // remember old stroke style, to be set on fill
648         SPCSSAttr *ncss;
649         {
650             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
651             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
652             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
654             ncss = sp_repr_css_attr_new();
656             sp_repr_css_set_property(ncss, "stroke", "none");
657             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
658             sp_repr_css_set_property(ncss, "fill", val);
659             if ( opac ) {
660                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
661             } else {
662                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
663             }
664             sp_repr_css_unset_property(ncss, "marker-start");
665             sp_repr_css_unset_property(ncss, "marker-mid");
666             sp_repr_css_unset_property(ncss, "marker-end");
667         }
669         NR::Matrix const transform(item->transform);
670         float const scale = NR::expansion(transform);
671         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
672         SPStyle *i_style = SP_OBJECT(item)->style;
673         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
674         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
676         float o_width, o_miter;
677         JoinType o_join;
678         ButtType o_butt;
680         {
681             int jointype, captype;
683             jointype = i_style->stroke_linejoin.computed;
684             captype = i_style->stroke_linecap.computed;
685             o_width = i_style->stroke_width.computed;
687             switch (jointype) {
688                 case SP_STROKE_LINEJOIN_MITER:
689                     o_join = join_pointy;
690                     break;
691                 case SP_STROKE_LINEJOIN_ROUND:
692                     o_join = join_round;
693                     break;
694                 default:
695                     o_join = join_straight;
696                     break;
697             }
699             switch (captype) {
700                 case SP_STROKE_LINECAP_SQUARE:
701                     o_butt = butt_square;
702                     break;
703                 case SP_STROKE_LINECAP_ROUND:
704                     o_butt = butt_round;
705                     break;
706                 default:
707                     o_butt = butt_straight;
708                     break;
709             }
711             if (o_width < 0.1)
712                 o_width = 0.1;
713             o_miter = i_style->stroke_miterlimit.value * o_width;
714         }
716         Path *orig = Path_for_item(item, false);
717         if (orig == NULL) {
718             g_free(style);
719             curve->unref();
720             continue;
721         }
723         Path *res = new Path;
724         res->SetBackData(false);
726         if (i_style->stroke_dash.n_dash) {
727             // For dashed strokes, use Stroke method, because Outline can't do dashes
728             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
730             orig->ConvertWithBackData(0.1);
732             orig->DashPolylineFromStyle(i_style, scale, 0);
734             Shape* theShape = new Shape;
735             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
736                          0.5 * o_miter);
737             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
739             Shape *theRes = new Shape;
741             theRes->ConvertToShape(theShape, fill_positive);
743             Path *originaux[1];
744             originaux[0] = res;
745             theRes->ConvertToForme(orig, 1, originaux);
747             res->Coalesce(5.0);
749             delete theShape;
750             delete theRes;
752         } else {
754             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
756             orig->Coalesce(0.5 * o_width);
758             Shape *theShape = new Shape;
759             Shape *theRes = new Shape;
761             res->ConvertWithBackData(1.0);
762             res->Fill(theShape, 0);
763             theRes->ConvertToShape(theShape, fill_positive);
765             Path *originaux[1];
766             originaux[0] = res;
767             theRes->ConvertToForme(orig, 1, originaux);
769             delete theShape;
770             delete theRes;
771         }
773         if (orig->descr_cmd.size() <= 1) {
774             // ca a merd\8e, ou bien le resultat est vide
775             delete res;
776             delete orig;
777             g_free(style);
778             continue;
779         }
781         did = true;
783         // remember the position of the item
784         gint pos = SP_OBJECT_REPR(item)->position();
785         // remember parent
786         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
787         // remember id
788         char const *id = SP_OBJECT_REPR(item)->attribute("id");
790         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
792             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
793             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
795             // restore old style
796             repr->setAttribute("style", style);
798             // set old stroke style on fill
799             sp_repr_css_change(repr, ncss, "style");
801             sp_repr_css_attr_unref(ncss);
803             gchar *str = orig->svg_dump_path();
804             repr->setAttribute("d", str);
805             g_free(str);
807             if (mask)
808                 repr->setAttribute("mask", mask);
809             if (clip_path)
810                 repr->setAttribute("clip-path", clip_path);
812             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
814                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
815                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
817                 // add the group to the parent
818                 parent->appendChild(g_repr);
819                 // move to the saved position
820                 g_repr->setPosition(pos > 0 ? pos : 0);
822                 g_repr->appendChild(repr);
823                 repr->setAttribute("id", id);
824                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
825                 sp_item_write_transform(newitem, repr, transform);
827                 SPShape *shape = SP_SHAPE(item);
829                 for (NArtBpath const* bp = curve->get_bpath(); bp->code != NR_END; bp++) {
830                     for (int m = SP_MARKER_LOC_START; m < SP_MARKER_LOC_QTY; m++) {
831                         if (sp_shape_marker_required (shape, m, bp)) {
833                             SPMarker* marker = SP_MARKER (shape->marker[m]);
834                             SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[m]));
836                             NR::Matrix tr(sp_shape_marker_get_transform(shape, bp));
838                             if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
839                                 tr = NR::scale(i_style->stroke_width.computed) * tr;
840                             }
842                             // total marker transform
843                             tr = marker_item->transform * marker->c2p * tr * transform;
845                             if (SP_OBJECT_REPR(marker_item)) {
846                                 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
847                                 g_repr->appendChild(m_repr);
848                                 SPItem *marker_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(m_repr);
849                                 sp_item_write_transform(marker_item, m_repr, tr);
850                             }
851                         }
852                     }
853                 }
856                 selection->add(g_repr);
858                 Inkscape::GC::release(g_repr);
861             } else {
863                 // add the new repr to the parent
864                 parent->appendChild(repr);
866                 // move to the saved position
867                 repr->setPosition(pos > 0 ? pos : 0);
869                 repr->setAttribute("id", id);
871                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
872                 sp_item_write_transform(newitem, repr, transform);
874                 selection->add(repr);
876             }
878             Inkscape::GC::release(repr);
880             curve->unref();
881             selection->remove(item);
882             SP_OBJECT(item)->deleteObject(false);
884         }
886         delete res;
887         delete orig;
888         g_free(style);
890     }
892     if (did) {
893         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
894                          _("Convert stroke to path"));
895     } else {
896         // TRANSLATORS: "to outline" means "to convert stroke to path"
897         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
898         return;
899     }
903 void
904 sp_selected_path_offset()
906     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
908     sp_selected_path_do_offset(true, prefOffset);
910 void
911 sp_selected_path_inset()
913     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
915     sp_selected_path_do_offset(false, prefOffset);
918 void
919 sp_selected_path_offset_screen(double pixels)
921     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
924 void
925 sp_selected_path_inset_screen(double pixels)
927     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
931 void sp_selected_path_create_offset_object_zero()
933     sp_selected_path_create_offset_object(0, false);
936 void sp_selected_path_create_offset()
938     sp_selected_path_create_offset_object(1, false);
940 void sp_selected_path_create_inset()
942     sp_selected_path_create_offset_object(-1, false);
945 void sp_selected_path_create_updating_offset_object_zero()
947     sp_selected_path_create_offset_object(0, true);
950 void sp_selected_path_create_updating_offset()
952     sp_selected_path_create_offset_object(1, true);
954 void sp_selected_path_create_updating_inset()
956     sp_selected_path_create_offset_object(-1, true);
959 void
960 sp_selected_path_create_offset_object(int expand, bool updating)
962     Inkscape::Selection *selection;
963     Inkscape::XML::Node *repr;
964     SPItem *item;
965     SPCurve *curve;
966     gchar *style, *str;
967     SPDesktop *desktop;
968     float o_width, o_miter;
969     JoinType o_join;
970     ButtType o_butt;
972     curve = NULL;
974     desktop = SP_ACTIVE_DESKTOP;
976     selection = sp_desktop_selection(desktop);
978     item = selection->singleItem();
980     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
981         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
982         return;
983     }
984     if (SP_IS_SHAPE(item))
985     {
986         curve = sp_shape_get_curve(SP_SHAPE(item));
987         if (curve == NULL)
988             return;
989     }
990     if (SP_IS_TEXT(item))
991     {
992         curve = SP_TEXT(item)->getNormalizedBpath();
993         if (curve == NULL)
994             return;
995     }
997     NR::Matrix const transform(item->transform);
999     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1001     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1003     // remember the position of the item
1004     gint pos = SP_OBJECT_REPR(item)->position();
1005     // remember parent
1006     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1008     {
1009         SPStyle *i_style = SP_OBJECT(item)->style;
1010         int jointype, captype;
1012         jointype = i_style->stroke_linejoin.value;
1013         captype = i_style->stroke_linecap.value;
1014         o_width = i_style->stroke_width.computed;
1015         if (jointype == SP_STROKE_LINEJOIN_MITER)
1016         {
1017             o_join = join_pointy;
1018         }
1019         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1020         {
1021             o_join = join_round;
1022         }
1023         else
1024         {
1025             o_join = join_straight;
1026         }
1027         if (captype == SP_STROKE_LINECAP_SQUARE)
1028         {
1029             o_butt = butt_square;
1030         }
1031         else if (captype == SP_STROKE_LINECAP_ROUND)
1032         {
1033             o_butt = butt_round;
1034         }
1035         else
1036         {
1037             o_butt = butt_straight;
1038         }
1040         {
1041             double prefOffset = 1.0;
1042             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1043             o_width = prefOffset;
1044         }
1046         if (o_width < 0.01)
1047             o_width = 0.01;
1048         o_miter = i_style->stroke_miterlimit.value * o_width;
1049     }
1051     Path *orig = Path_for_item(item, true, false);
1052     if (orig == NULL)
1053     {
1054         g_free(style);
1055         curve->unref();
1056         return;
1057     }
1059     Path *res = new Path;
1060     res->SetBackData(false);
1062     {
1063         Shape *theShape = new Shape;
1064         Shape *theRes = new Shape;
1066         orig->ConvertWithBackData(1.0);
1067         orig->Fill(theShape, 0);
1069         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1070         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1071         if (val && strcmp(val, "nonzero") == 0)
1072         {
1073             theRes->ConvertToShape(theShape, fill_nonZero);
1074         }
1075         else if (val && strcmp(val, "evenodd") == 0)
1076         {
1077             theRes->ConvertToShape(theShape, fill_oddEven);
1078         }
1079         else
1080         {
1081             theRes->ConvertToShape(theShape, fill_nonZero);
1082         }
1084         Path *originaux[1];
1085         originaux[0] = orig;
1086         theRes->ConvertToForme(res, 1, originaux);
1088         delete theShape;
1089         delete theRes;
1090     }
1092     curve->unref();
1094     if (res->descr_cmd.size() <= 1)
1095     {
1096         // pas vraiment de points sur le resultat
1097         // donc il ne reste rien
1098         sp_document_done(sp_desktop_document(desktop), 
1099                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1100                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1101                          (updating ? _("Create linked offset")
1102                           : _("Create dynamic offset")));
1103         selection->clear();
1105         delete res;
1106         delete orig;
1107         g_free(style);
1108         return;
1109     }
1111     {
1112         gchar tstr[80];
1114         tstr[79] = '\0';
1116         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1117         repr = xml_doc->createElement("svg:path");
1118         repr->setAttribute("sodipodi:type", "inkscape:offset");
1119         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1120                                                           ? o_width
1121                                                           : expand < 0
1122                                                           ? -o_width
1123                                                           : 0 ));
1125         str = res->svg_dump_path();
1126         repr->setAttribute("inkscape:original", str);
1127         g_free(str);
1129         if ( updating ) {
1130             char const *id = SP_OBJECT(item)->repr->attribute("id");
1131             char const *uri = g_strdup_printf("#%s", id);
1132             repr->setAttribute("xlink:href", uri);
1133             g_free((void *) uri);
1134         } else {
1135             repr->setAttribute("inkscape:href", NULL);
1136         }
1138         repr->setAttribute("style", style);
1140         // add the new repr to the parent
1141         parent->appendChild(repr);
1143         // move to the saved position
1144         repr->setPosition(pos > 0 ? pos : 0);
1146         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1148         if ( updating ) {
1149             // on conserve l'original
1150             // we reapply the transform to the original (offset will feel it)
1151             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1152         } else {
1153             // delete original, apply the transform to the offset
1154             SP_OBJECT(item)->deleteObject(false);
1155             sp_item_write_transform(nitem, repr, transform);
1156         }
1158         // The object just created from a temporary repr is only a seed.
1159         // We need to invoke its write which will update its real repr (in particular adding d=)
1160         SP_OBJECT(nitem)->updateRepr();
1162         Inkscape::GC::release(repr);
1164         selection->set(nitem);
1165     }
1167     sp_document_done(sp_desktop_document(desktop), 
1168                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1169                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1170                      (updating ? _("Create linked offset")
1171                       : _("Create dynamic offset")));
1173     delete res;
1174     delete orig;
1176     g_free(style);
1190 void
1191 sp_selected_path_do_offset(bool expand, double prefOffset)
1193     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1195     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1197     if (selection->isEmpty()) {
1198         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1199         return;
1200     }
1202     bool did = false;
1204     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1205          items != NULL;
1206          items = items->next) {
1208         SPItem *item = (SPItem *) items->data;
1210         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1211             continue;
1213         SPCurve *curve = NULL;
1214         if (SP_IS_SHAPE(item)) {
1215             curve = sp_shape_get_curve(SP_SHAPE(item));
1216             if (curve == NULL)
1217                 continue;
1218         }
1219         if (SP_IS_TEXT(item)) {
1220             curve = SP_TEXT(item)->getNormalizedBpath();
1221             if (curve == NULL)
1222                 continue;
1223         }
1225         NR::Matrix const transform(item->transform);
1227         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1229         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1231         float o_width, o_miter;
1232         JoinType o_join;
1233         ButtType o_butt;
1235         {
1236             SPStyle *i_style = SP_OBJECT(item)->style;
1237             int jointype, captype;
1239             jointype = i_style->stroke_linejoin.value;
1240             captype = i_style->stroke_linecap.value;
1241             o_width = i_style->stroke_width.computed;
1243             switch (jointype) {
1244                 case SP_STROKE_LINEJOIN_MITER:
1245                     o_join = join_pointy;
1246                     break;
1247                 case SP_STROKE_LINEJOIN_ROUND:
1248                     o_join = join_round;
1249                     break;
1250                 default:
1251                     o_join = join_straight;
1252                     break;
1253             }
1255             switch (captype) {
1256                 case SP_STROKE_LINECAP_SQUARE:
1257                     o_butt = butt_square;
1258                     break;
1259                 case SP_STROKE_LINECAP_ROUND:
1260                     o_butt = butt_round;
1261                     break;
1262                 default:
1263                     o_butt = butt_straight;
1264                     break;
1265             }
1267             o_width = prefOffset;
1269             if (o_width < 0.1)
1270                 o_width = 0.1;
1271             o_miter = i_style->stroke_miterlimit.value * o_width;
1272         }
1274         Path *orig = Path_for_item(item, false);
1275         if (orig == NULL) {
1276             g_free(style);
1277             curve->unref();
1278             continue;
1279         }
1281         Path *res = new Path;
1282         res->SetBackData(false);
1284         {
1285             Shape *theShape = new Shape;
1286             Shape *theRes = new Shape;
1288             orig->ConvertWithBackData(0.03);
1289             orig->Fill(theShape, 0);
1291             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1292             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1293             if (val && strcmp(val, "nonzero") == 0)
1294             {
1295                 theRes->ConvertToShape(theShape, fill_nonZero);
1296             }
1297             else if (val && strcmp(val, "evenodd") == 0)
1298             {
1299                 theRes->ConvertToShape(theShape, fill_oddEven);
1300             }
1301             else
1302             {
1303                 theRes->ConvertToShape(theShape, fill_nonZero);
1304             }
1306             // et maintenant: offset
1307             // methode inexacte
1308 /*                      Path *originaux[1];
1309                         originaux[0] = orig;
1310                         theRes->ConvertToForme(res, 1, originaux);
1312                         if (expand) {
1313                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1314                         } else {
1315                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1316                         }
1318                         orig->ConvertWithBackData(1.0);
1319                         orig->Fill(theShape, 0);
1320                         theRes->ConvertToShape(theShape, fill_positive);
1321                         originaux[0] = orig;
1322                         theRes->ConvertToForme(res, 1, originaux);
1324                         if (o_width >= 0.5) {
1325                         //     res->Coalesce(1.0);
1326                         res->ConvertEvenLines(1.0);
1327                         res->Simplify(1.0);
1328                         } else {
1329                         //      res->Coalesce(o_width);
1330                         res->ConvertEvenLines(1.0*o_width);
1331                         res->Simplify(1.0 * o_width);
1332                         }    */
1333             // methode par makeoffset
1335             if (expand)
1336             {
1337                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1338             }
1339             else
1340             {
1341                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1342             }
1343             theRes->ConvertToShape(theShape, fill_positive);
1345             res->Reset();
1346             theRes->ConvertToForme(res);
1348             if (o_width >= 1.0)
1349             {
1350                 res->ConvertEvenLines(1.0);
1351                 res->Simplify(1.0);
1352             }
1353             else
1354             {
1355                 res->ConvertEvenLines(1.0*o_width);
1356                 res->Simplify(1.0 * o_width);
1357             }
1359             delete theShape;
1360             delete theRes;
1361         }
1363         did = true;
1365         curve->unref();
1366         // remember the position of the item
1367         gint pos = SP_OBJECT_REPR(item)->position();
1368         // remember parent
1369         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1370         // remember id
1371         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1373         selection->remove(item);
1374         SP_OBJECT(item)->deleteObject(false);
1376         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1378             gchar tstr[80];
1380             tstr[79] = '\0';
1382             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1383             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1385             repr->setAttribute("style", style);
1387             gchar *str = res->svg_dump_path();
1388             repr->setAttribute("d", str);
1389             g_free(str);
1391             // add the new repr to the parent
1392             parent->appendChild(repr);
1394             // move to the saved position
1395             repr->setPosition(pos > 0 ? pos : 0);
1397             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1399             // reapply the transform
1400             sp_item_write_transform(newitem, repr, transform);
1402             repr->setAttribute("id", id);
1404             selection->add(repr);
1406             Inkscape::GC::release(repr);
1407         }
1409         delete orig;
1410         delete res;
1411     }
1413     if (did) {
1414         sp_document_done(sp_desktop_document(desktop), 
1415                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1416                          (expand ? _("Outset path") : _("Inset path")));
1417     } else {
1418         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1419         return;
1420     }
1424 static bool
1425 sp_selected_path_simplify_items(SPDesktop *desktop,
1426                                 Inkscape::Selection *selection, GSList *items,
1427                                 float threshold,  bool justCoalesce,
1428                                 float angleLimit, bool breakableAngles,
1429                                 bool modifySelection);
1432 //return true if we changed something, else false
1433 bool
1434 sp_selected_path_simplify_item(SPDesktop *desktop,
1435                  Inkscape::Selection *selection, SPItem *item,
1436                  float threshold,  bool justCoalesce,
1437                  float angleLimit, bool breakableAngles,
1438                  gdouble size,     bool modifySelection)
1440     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1441         return false;
1443     //If this is a group, do the children instead
1444     if (SP_IS_GROUP(item)) {
1445         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1446         
1447         return sp_selected_path_simplify_items(desktop, selection, items,
1448                                                threshold, justCoalesce,
1449                                                angleLimit, breakableAngles,
1450                                                false);
1451     }
1454     SPCurve *curve = NULL;
1456     if (SP_IS_SHAPE(item)) {
1457         curve = sp_shape_get_curve(SP_SHAPE(item));
1458         if (!curve)
1459             return false;
1460     }
1462     if (SP_IS_TEXT(item)) {
1463         curve = SP_TEXT(item)->getNormalizedBpath();
1464         if (!curve)
1465             return false;
1466     }
1468     // save the transform, to re-apply it after simplification
1469     NR::Matrix const transform(item->transform);
1471     /*
1472        reset the transform, effectively transforming the item by transform.inverse();
1473        this is necessary so that the item is transformed twice back and forth,
1474        allowing all compensations to cancel out regardless of the preferences
1475     */
1476     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1478     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1479     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1480     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1482     Path *orig = Path_for_item(item, false);
1483     if (orig == NULL) {
1484         g_free(style);
1485         curve->unref();
1486         return false;
1487     }
1489     curve->unref();
1490     // remember the position of the item
1491     gint pos = SP_OBJECT_REPR(item)->position();
1492     // remember parent
1493     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1494     // remember id
1495     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1496     // remember path effect
1497     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1499     //If a group was selected, to not change the selection list
1500     if (modifySelection)
1501         selection->remove(item);
1503     SP_OBJECT(item)->deleteObject(false);
1505     if ( justCoalesce ) {
1506         orig->Coalesce(threshold * size);
1507     } else {
1508         orig->ConvertEvenLines(threshold * size);
1509         orig->Simplify(threshold * size);
1510     }
1512     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1513     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1515     // restore style, mask and clip-path
1516     repr->setAttribute("style", style);
1517     g_free(style);
1519     if ( mask ) {
1520         repr->setAttribute("mask", mask);
1521         g_free(mask);
1522     }
1524     if ( clip_path ) {
1525         repr->setAttribute("clip-path", clip_path);
1526         g_free(clip_path);
1527     }
1529     // path
1530     gchar *str = orig->svg_dump_path();
1531     if (patheffect)
1532         repr->setAttribute("inkscape:original-d", str);
1533     else 
1534         repr->setAttribute("d", str);
1535     g_free(str);
1537     // restore id
1538     repr->setAttribute("id", id);
1540     // add the new repr to the parent
1541     parent->appendChild(repr);
1543     // move to the saved position
1544     repr->setPosition(pos > 0 ? pos : 0);
1546     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1548     // reapply the transform
1549     sp_item_write_transform(newitem, repr, transform);
1551     // restore path effect
1552     repr->setAttribute("inkscape:path-effect", patheffect);
1554     //If we are not in a selected group
1555     if (modifySelection)
1556         selection->add(repr);
1558     Inkscape::GC::release(repr);
1560     // clean up
1561     if (orig) delete orig;
1563     return true;
1567 bool
1568 sp_selected_path_simplify_items(SPDesktop *desktop,
1569                                 Inkscape::Selection *selection, GSList *items,
1570                                 float threshold,  bool justCoalesce,
1571                                 float angleLimit, bool breakableAngles,
1572                                 bool modifySelection)
1574   bool simplifyIndividualPaths =
1575     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1576   
1577   gchar *simplificationType;
1578   if (simplifyIndividualPaths) {
1579       simplificationType = _("Simplifying paths (separately):");
1580   } else {
1581       simplificationType = _("Simplifying paths:");
1582   }
1584   bool didSomething = false;
1586   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1587   if (!selectionBbox) {
1588     return false;
1589   }
1590   gdouble selectionSize  = L2(selectionBbox->dimensions());
1592   gdouble simplifySize  = selectionSize;
1593   
1594   int pathsSimplified = 0;
1595   int totalPathCount  = g_slist_length(items);
1596   
1597   // set "busy" cursor
1598   desktop->setWaitingCursor();
1599   
1600   for (; items != NULL; items = items->next) {
1601       SPItem *item = (SPItem *) items->data;
1602       
1603       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1604           continue;
1606       if (simplifyIndividualPaths) {
1607           NR::Maybe<NR::Rect> itemBbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
1608           if (itemBbox) {
1609               simplifySize      = L2(itemBbox->dimensions());
1610           } else {
1611               simplifySize      = 0;
1612           }
1613       }
1615       pathsSimplified++;
1617       if (pathsSimplified % 20 == 0) {
1618         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1619         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1620       }
1622       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1623                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1624   }
1626   desktop->clearWaitingCursor();
1628   if (pathsSimplified > 20) {
1629     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1630   }
1631   
1632   return didSomething;
1635 void
1636 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1637                        float angleLimit, bool breakableAngles)
1639     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1641     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1643     if (selection->isEmpty()) {
1644         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1645                          _("Select <b>path(s)</b> to simplify."));
1646         return;
1647     }
1649     GSList *items = g_slist_copy((GSList *) selection->itemList());
1651     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1652                                                         items, threshold,
1653                                                         justCoalesce,
1654                                                         angleLimit,
1655                                                         breakableAngles, true);
1657     if (didSomething)
1658         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1659                          _("Simplify"));
1660     else
1661         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1666 // globals for keeping track of accelerated simplify
1667 static double previousTime      = 0.0;
1668 static gdouble simplifyMultiply = 1.0;
1670 void
1671 sp_selected_path_simplify(void)
1673     gdouble simplifyThreshold =
1674         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1675     bool simplifyJustCoalesce =
1676         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1678     //Get the current time
1679     GTimeVal currentTimeVal;
1680     g_get_current_time(&currentTimeVal);
1681     double currentTime = currentTimeVal.tv_sec * 1000000 +
1682                 currentTimeVal.tv_usec;
1684     //Was the previous call to this function recent? (<0.5 sec)
1685     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1687         // add to the threshold 1/2 of its original value
1688         simplifyMultiply  += 0.5;
1689         simplifyThreshold *= simplifyMultiply;
1691     } else {
1692         // reset to the default
1693         simplifyMultiply = 1;
1694     }
1696     //remember time for next call
1697     previousTime = currentTime;
1699     //g_print("%g\n", simplify_threshold);
1701     //Make the actual call
1702     sp_selected_path_simplify_selection(simplifyThreshold,
1703                       simplifyJustCoalesce, 0.0, false);
1708 // fonctions utilitaires
1710 bool
1711 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1713     if (who == NULL || a == NULL)
1714         return false;
1715     if (who == a)
1716         return true;
1717     return Ancetre(sp_repr_parent(a), who);
1720 Path *
1721 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1723     SPCurve *curve = curve_for_item(item);
1724     NArtBpath *bpath = bpath_for_curve(item, curve, doTransformation, transformFull);
1725     
1726     if (bpath == NULL) {
1727         return NULL;
1728     }
1729     
1730     Path *dest = bpath_to_Path(bpath);
1732     g_free(bpath);
1734     curve->unref();
1735     
1736     return dest;
1739 /* 
1740  * This function always returns a new NArtBpath, the caller must g_free the returned path!
1741 */
1742 NArtBpath *
1743 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1745     if (curve == NULL)
1746         return NULL;
1748     NArtBpath const *bpath = SP_CURVE_BPATH(curve);
1749     if (bpath == NULL) {
1750         return NULL;
1751     }
1753     NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1754     if (doTransformation) {
1755         if (transformFull) {
1756             new_bpath = nr_artpath_affine(bpath, from_2geom(sp_item_i2doc_affine(item)));
1757         } else {
1758             new_bpath = nr_artpath_affine(bpath, item->transform);
1759         }
1760     } else {
1761         new_bpath = nr_artpath_affine(bpath, NR::identity());
1762     }
1764     return new_bpath;
1767 SPCurve* curve_for_item(SPItem *item)
1769     if (!item)
1770         return NULL;
1772     SPCurve *curve = NULL;
1774     if (SP_IS_SHAPE(item)) {
1775         if (SP_IS_PATH(item)) {
1776             curve = sp_path_get_curve_for_edit(SP_PATH(item));
1777         } else {
1778             curve = sp_shape_get_curve(SP_SHAPE(item));
1779         }
1780     }
1781     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1782     {
1783         curve = te_get_layout(item)->convertToCurves();
1784     }
1785     else if (SP_IS_IMAGE(item))
1786     {
1787         curve = sp_image_get_curve(SP_IMAGE(item));
1788     }
1789     
1790     return curve; // do not forget to unref the curve at some point!
1793 Path *bpath_to_Path(NArtBpath const *bpath) {
1794     Path *dest = new Path;
1795     dest->SetBackData(false);
1796     {
1797         int   i;
1798         bool  closed = false;
1799         float lastX  = 0.0;
1800         float lastY  = 0.0;
1802         for (i = 0; bpath[i].code != NR_END; i++) {
1803             switch (bpath[i].code) {
1804                 case NR_LINETO:
1805                     lastX = bpath[i].x3;
1806                     lastY = bpath[i].y3;
1807                     {
1808                         NR::Point tmp(lastX, lastY);
1809                         dest->LineTo(tmp);
1810                     }
1811                     break;
1813                 case NR_CURVETO:
1814                 {
1815                     NR::Point tmp, tms, tme;
1816                     tmp[0]=bpath[i].x3;
1817                     tmp[1]=bpath[i].y3;
1818                     tms[0]=3 * (bpath[i].x1 - lastX);
1819                     tms[1]=3 * (bpath[i].y1 - lastY);
1820                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1821                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1822                     dest->CubicTo(tmp,tms,tme);
1823                 }
1824                 lastX = bpath[i].x3;
1825                 lastY = bpath[i].y3;
1826                 break;
1828                 case NR_MOVETO_OPEN:
1829                 case NR_MOVETO:
1830                     if (closed)
1831                         dest->Close();
1832                     closed = (bpath[i].code == NR_MOVETO);
1833                     lastX = bpath[i].x3;
1834                     lastY = bpath[i].y3;
1835                     {
1836                         NR::Point  tmp(lastX, lastY);
1837                         dest->MoveTo(tmp);
1838                     }
1839                     break;
1840                 default:
1841                     break;
1842             }
1843         }
1844         if (closed)
1845             dest->Close();
1846     }
1847     return dest;
1850 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1852     //get nearest position on path
1853     Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1854     return pos;
1857 NR::Point get_point_on_Path(Path *path, int piece, double t)
1859     NR::Point p;
1860     path->PointAt(piece, t, p);
1861     return p;
1865 /*
1866   Local Variables:
1867   mode:c++
1868   c-file-style:"stroustrup"
1869   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1870   indent-tabs-mode:nil
1871   fill-column:99
1872   End:
1873 */
1874 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :