Code

convert path to linears and cubics only before creating outline. (workaround for...
[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"
51 #include <2geom/pathvector.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>
56 #include <libnr/n-art-bpath-2geom.h>
57 #include "helper/geom.h"
59 #include "livarot/Path.h"
60 #include "livarot/Shape.h"
62 #include "splivarot.h"
64 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
66 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
67 void sp_selected_path_do_offset(bool expand, double prefOffset);
68 void sp_selected_path_create_offset_object(int expand, bool updating);
70 void
71 sp_selected_path_union()
72 {
73     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
74 }
76 void
77 sp_selected_path_union_skip_undo()
78 {
79     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
80 }
82 void
83 sp_selected_path_intersect()
84 {
85     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
86 }
88 void
89 sp_selected_path_diff()
90 {
91     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
92 }
94 void
95 sp_selected_path_diff_skip_undo()
96 {
97     sp_selected_path_boolop(bool_op_diff, SP_VERB_NONE, _("Difference"));
98 }
100 void
101 sp_selected_path_symdiff()
103     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
105 void
106 sp_selected_path_cut()
108     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
110 void
111 sp_selected_path_slice()
113     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
117 // boolean operations
118 // take the source paths from the file, do the operation, delete the originals and add the results
119 void
120 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
122     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
124     Inkscape::Selection *selection = sp_desktop_selection(desktop);
125     
126     GSList *il = (GSList *) selection->itemList();
127     
128     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
129     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
130         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
131         return;
132     }
133     else if ( g_slist_length(il) < 1 ) {
134         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
135         return;
136     }
138     if (g_slist_length(il) > 2) {
139         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
140             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
141             return;
142         }
143     }
145     // reverseOrderForOp marks whether the order of the list is the top->down order
146     // it's only used when there are 2 objects, and for operations who need to know the
147     // topmost object (differences, cuts)
148     bool reverseOrderForOp = false;
150     // mettre les elements de la liste dans l'ordre pour ces operations
151     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
152         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
153         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
154         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
156         if (a == NULL || b == NULL) {
157             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."));
158             return;
159         }
161         if (Ancetre(a, b)) {
162             // a is the parent of b, already in the proper order
163         } else if (Ancetre(b, a)) {
164             // reverse order
165             reverseOrderForOp = true;
166         } else {
168             // objects are not in parent/child relationship;
169             // find their lowest common ancestor
170             Inkscape::XML::Node *dad = LCA(a, b);
171             if (dad == NULL) {
172                 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."));
173                 return;
174             }
176             // find the children of the LCA that lead from it to the a and b
177             Inkscape::XML::Node *as = AncetreFils(a, dad);
178             Inkscape::XML::Node *bs = AncetreFils(b, dad);
180             // find out which comes first
181             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
182                 if (child == as) {
183                     /* a first, so reverse. */
184                     reverseOrderForOp = true;
185                     break;
186                 }
187                 if (child == bs)
188                     break;
189             }
190         }
191     }
193     il = g_slist_copy(il);
195     // first check if all the input objects have shapes
196     // otherwise bail out
197     for (GSList *l = il; l != NULL; l = l->next)
198     {
199         SPItem *item = SP_ITEM(l->data);
200         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
201         {
202             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
203             g_slist_free(il);
204             return;
205         }
206     }
208     // extract the livarot Paths from the source objects
209     // also get the winding rule specified in the style
210     int nbOriginaux = g_slist_length(il);
211     std::vector<Path *> originaux(nbOriginaux);
212     std::vector<FillRule> origWind(nbOriginaux);
213     int curOrig;
214     {
215         curOrig = 0;
216         for (GSList *l = il; l != NULL; l = l->next)
217         {
218             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
219             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
220             if (val && strcmp(val, "nonzero") == 0) {
221                 origWind[curOrig]= fill_nonZero;
222             } else if (val && strcmp(val, "evenodd") == 0) {
223                 origWind[curOrig]= fill_oddEven;
224             } else {
225                 origWind[curOrig]= fill_nonZero;
226             }
228             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
229             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
230             {
231                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
232                 g_slist_free(il);
233                 return;
234             }
235             curOrig++;
236         }
237     }
238     // reverse if needed
239     // note that the selection list keeps its order
240     if ( reverseOrderForOp ) {
241         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
242         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
243     }
245     // and work
246     // some temporary instances, first
247     Shape *theShapeA = new Shape;
248     Shape *theShapeB = new Shape;
249     Shape *theShape = new Shape;
250     Path *res = new Path;
251     res->SetBackData(false);
252     Path::cut_position  *toCut=NULL;
253     int                  nbToCut=0;
255     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
256         // true boolean op
257         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
258         originaux[0]->ConvertWithBackData(0.1);
260         originaux[0]->Fill(theShape, 0);
262         theShapeA->ConvertToShape(theShape, origWind[0]);
264         curOrig = 1;
265         for (GSList *l = il->next; l != NULL; l = l->next) {
266             originaux[curOrig]->ConvertWithBackData(0.1);
268             originaux[curOrig]->Fill(theShape, curOrig);
270             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
272             // les elements arrivent en ordre inverse dans la liste
273             theShape->Booleen(theShapeB, theShapeA, bop);
275             {
276                 Shape *swap = theShape;
277                 theShape = theShapeA;
278                 theShapeA = swap;
279             }
280             curOrig++;
281         }
283         {
284             Shape *swap = theShape;
285             theShape = theShapeA;
286             theShapeA = swap;
287         }
289     } else if ( bop == bool_op_cut ) {
290         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
291         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
292         // it is just uncrossed, and cleaned from duplicate edges and points
293         // then it's fed to Booleen() which will uncross it against the other path
294         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
295         // thus making a polygon. the weight of the edges of the cut are all 0, but
296         // the Booleen need to invert the ones inside the source polygon (for the subsequent
297         // ConvertToForme)
299         // the cut path needs to have the highest pathID in the back data
300         // that's how the Booleen() function knows it's an edge of the cut
302         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
303         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
304         // left it at 1.0. Investigate replacing this by a combination of difference and
305         // intersection of the same two paths. -- bb
306         {
307             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
308             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
309         }
310         originaux[0]->ConvertWithBackData(1.0);
312         originaux[0]->Fill(theShape, 0);
314         theShapeA->ConvertToShape(theShape, origWind[0]);
316         originaux[1]->ConvertWithBackData(1.0);
318         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
320         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
322         // les elements arrivent en ordre inverse dans la liste
323         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
325     } else if ( bop == bool_op_slice ) {
326         // slice is not really a boolean operation
327         // you just put the 2 shapes in a single polygon, uncross it
328         // the points where the degree is > 2 are intersections
329         // just check it's an intersection on the path you want to cut, and keep it
330         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
331         // make new subpath at each one of these positions
332         // inversion pour l'op\8eration
333         {
334             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
335             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
336         }
337         originaux[0]->ConvertWithBackData(1.0);
339         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
341         originaux[1]->ConvertWithBackData(1.0);
343         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
345         theShape->ConvertToShape(theShapeA, fill_justDont);
347         if ( theShape->hasBackData() ) {
348             // should always be the case, but ya never know
349             {
350                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
351                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
352                         // possibly an intersection
353                         // we need to check that at least one edge from the source path is incident to it
354                         // before we declare it's an intersection
355                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
356                         int   nbOrig=0;
357                         int   nbOther=0;
358                         int   piece=-1;
359                         float t=0.0;
360                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
361                             if ( theShape->ebData[cb].pathID == 0 ) {
362                                 // the source has an edge incident to the point, get its position on the path
363                                 piece=theShape->ebData[cb].pieceID;
364                                 if ( theShape->getEdge(cb).st == i ) {
365                                     t=theShape->ebData[cb].tSt;
366                                 } else {
367                                     t=theShape->ebData[cb].tEn;
368                                 }
369                                 nbOrig++;
370                             }
371                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
372                             cb=theShape->NextAt(i, cb);
373                         }
374                         if ( nbOrig > 0 && nbOther > 0 ) {
375                             // point incident to both path and cut: an intersection
376                             // note that you only keep one position on the source; you could have degenerate
377                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
378                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
379                             toCut[nbToCut].piece=piece;
380                             toCut[nbToCut].t=t;
381                             nbToCut++;
382                         }
383                     }
384                 }
385             }
386             {
387                 // i think it's useless now
388                 int i = theShape->numberOfEdges() - 1;
389                 for (;i>=0;i--) {
390                     if ( theShape->ebData[i].pathID == 1 ) {
391                         theShape->SubEdge(i);
392                     }
393                 }
394             }
396         }
397     }
399     int*    nesting=NULL;
400     int*    conts=NULL;
401     int     nbNest=0;
402     // pour compenser le swap juste avant
403     if ( bop == bool_op_slice ) {
404 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
405 //    res->ConvertForcedToMoveTo();
406         res->Copy(originaux[0]);
407         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
408         free(toCut);
409     } else if ( bop == bool_op_cut ) {
410         // il faut appeler pour desallouer PointData (pas vital, mais bon)
411         // the Booleen() function did not deallocated the point_data array in theShape, because this
412         // function needs it.
413         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
414         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
415         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
416     } else {
417         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
418     }
420     delete theShape;
421     delete theShapeA;
422     delete theShapeB;
423     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
425     if (res->descr_cmd.size() <= 1)
426     {
427         // only one command, presumably a moveto: it isn't a path
428         for (GSList *l = il; l != NULL; l = l->next)
429         {
430             SP_OBJECT(l->data)->deleteObject();
431         }
432         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
433                          description);
434         selection->clear();
436         delete res;
437         g_slist_free(il);
438         return;
439     }
441     // get the source path object
442     SPObject *source;
443     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
444         if (reverseOrderForOp) {
445              source = SP_OBJECT(il->data);
446         } else {
447              source = SP_OBJECT(il->next->data);
448         }
449     } else {
450         // find out the bottom object
451         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
453         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
455         source = sp_desktop_document(desktop)->
456             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
458         g_slist_free(sorted);
459     }
461     // adjust style properties that depend on a possible transform in the source object in order
462     // to get a correct style attribute for the new path
463     SPItem* item_source = SP_ITEM(source);
464     NR::Matrix i2root = from_2geom(sp_item_i2root_affine(item_source));
465     sp_item_adjust_stroke(item_source, NR::expansion(i2root));
466     sp_item_adjust_pattern(item_source, i2root);
467     sp_item_adjust_gradient(item_source, i2root);
468     sp_item_adjust_livepatheffect(item_source, i2root);
470     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
472     // remember important aspects of the source path, to be restored
473     gint pos = repr_source->position();
474     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
475     gchar const *id = repr_source->attribute("id");
476     gchar const *style = repr_source->attribute("style");
477     gchar const *mask = repr_source->attribute("mask");
478     gchar const *clip_path = repr_source->attribute("clip-path");
480     // remove source paths
481     selection->clear();
482     for (GSList *l = il; l != NULL; l = l->next) {
483         // if this is the bottommost object,
484         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
485             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
486             SP_OBJECT(l->data)->deleteObject(false);
487         } else {
488             // delete the object for real, so that its clones can take appropriate action
489             SP_OBJECT(l->data)->deleteObject();
490         }
491     }
492     g_slist_free(il);
494     // premultiply by the inverse of parent's repr
495     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
496     NR::Matrix local = from_2geom(sp_item_i2doc_affine(parent_item));
497     gchar *transform = sp_svg_transform_write(local.inverse());
499     // now that we have the result, add it on the canvas
500     if ( bop == bool_op_cut || bop == bool_op_slice ) {
501         int    nbRP=0;
502         Path** resPath;
503         if ( bop == bool_op_slice ) {
504             // there are moveto's at each intersection, but it's still one unique path
505             // so break it down and add each subpath independently
506             // we could call break_apart to do this, but while we have the description...
507             resPath=res->SubPaths(nbRP, false);
508         } else {
509             // cut operation is a bit wicked: you need to keep holes
510             // that's why you needed the nesting
511             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
512             // to get the path for each part of the polygon. that's why you need the nesting info:
513             // to know in wich subpath to add a subpath
514             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
516             // cleaning
517             if ( conts ) free(conts);
518             if ( nesting ) free(nesting);
519         }
521         // add all the pieces resulting from cut or slice
522         for (int i=0;i<nbRP;i++) {
523             gchar *d = resPath[i]->svg_dump_path();
525             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
526             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
527             repr->setAttribute("style", style);
528             if (mask)
529                 repr->setAttribute("mask", mask);
530             if (clip_path)
531                 repr->setAttribute("clip-path", clip_path);
533             repr->setAttribute("d", d);
534             g_free(d);
536             // for slice, remove fill
537             if (bop == bool_op_slice) {
538                 SPCSSAttr *css;
540                 css = sp_repr_css_attr_new();
541                 sp_repr_css_set_property(css, "fill", "none");
543                 sp_repr_css_change(repr, css, "style");
545                 sp_repr_css_attr_unref(css);
546             }
548             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
549             // this means it's basically random which of the pieces inherits the original's id and clones
550             // a better algorithm might figure out e.g. the biggest piece
551             repr->setAttribute("id", id);
553             repr->setAttribute("transform", transform);
555             // add the new repr to the parent
556             parent->appendChild(repr);
558             // move to the saved position
559             repr->setPosition(pos > 0 ? pos : 0);
561             selection->add(repr);
562             Inkscape::GC::release(repr);
564             delete resPath[i];
565         }
566         if ( resPath ) free(resPath);
568     } else {
569         gchar *d = res->svg_dump_path();
571         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
572         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
573         repr->setAttribute("style", style);
575         if ( mask )
576             repr->setAttribute("mask", mask);
578         if ( clip_path )
579             repr->setAttribute("clip-path", clip_path);
581         repr->setAttribute("d", d);
582         g_free(d);
584         repr->setAttribute("transform", transform);
586         repr->setAttribute("id", id);
587         parent->appendChild(repr);
588         repr->setPosition(pos > 0 ? pos : 0);
590         selection->add(repr);
591         Inkscape::GC::release(repr);
592     }
594     g_free(transform);
596     if (verb != SP_VERB_NONE) {
597         sp_document_done(sp_desktop_document(desktop), verb, description);
598     }
600     delete res;
603 static
604 void sp_selected_path_outline_add_marker( SPObject *marker_object, Geom::Matrix marker_transform, NR::scale stroke_scale, NR::Matrix transform,
605                                        Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument * doc )
607     SPMarker* marker = SP_MARKER (marker_object);
608     SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker_object));
610     NR::Matrix tr(from_2geom(marker_transform));
612     if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
613         tr = stroke_scale * tr;
614     }
616     // total marker transform
617     tr = marker_item->transform * marker->c2p * tr * transform;
619     if (SP_OBJECT_REPR(marker_item)) {
620         Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
621         g_repr->appendChild(m_repr);
622         SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr);
623         sp_item_write_transform(marker_item, m_repr, tr);
624     }
627 void
628 sp_selected_path_outline()
630     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
632     Inkscape::Selection *selection = sp_desktop_selection(desktop);
634     if (selection->isEmpty()) {
635         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
636         return;
637     }
639     bool did = false;
641     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
642          items != NULL;
643          items = items->next) {
645         SPItem *item = (SPItem *) items->data;
647         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
648             continue;
650         SPCurve *curve = NULL;
651         if (SP_IS_SHAPE(item)) {
652             curve = sp_shape_get_curve(SP_SHAPE(item));
653             if (curve == NULL)
654                 continue;
655         }
656         if (SP_IS_TEXT(item)) {
657             curve = SP_TEXT(item)->getNormalizedBpath();
658             if (curve == NULL)
659                 continue;
660         }
662         // pas de stroke pas de chocolat
663         if (!SP_OBJECT_STYLE(item) || SP_OBJECT_STYLE(item)->stroke.noneSet) {
664             curve->unref();
665             continue;
666         }
668         // remember old stroke style, to be set on fill
669         SPStyle *i_style = SP_OBJECT_STYLE(item);
670         SPCSSAttr *ncss;
671         {
672             ncss = sp_css_attr_from_style(i_style, SP_STYLE_FLAG_ALWAYS);
673             gchar const *s_val = sp_repr_css_property(ncss, "stroke", NULL);
674             gchar const *s_opac = sp_repr_css_property(ncss, "stroke-opacity", NULL);
676             sp_repr_css_set_property(ncss, "stroke", "none");
677             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
678             sp_repr_css_set_property(ncss, "fill", s_val);
679             if ( s_opac ) {
680                 sp_repr_css_set_property(ncss, "fill-opacity", s_opac);
681             } else {
682                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
683             }
684             sp_repr_css_unset_property(ncss, "marker-start");
685             sp_repr_css_unset_property(ncss, "marker-mid");
686             sp_repr_css_unset_property(ncss, "marker-end");
687         }
689         NR::Matrix const transform(item->transform);
690         float const scale = NR::expansion(transform);
691         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
692         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
694         float o_width, o_miter;
695         JoinType o_join;
696         ButtType o_butt;
698         {
699             int jointype, captype;
701             jointype = i_style->stroke_linejoin.computed;
702             captype = i_style->stroke_linecap.computed;
703             o_width = i_style->stroke_width.computed;
705             switch (jointype) {
706                 case SP_STROKE_LINEJOIN_MITER:
707                     o_join = join_pointy;
708                     break;
709                 case SP_STROKE_LINEJOIN_ROUND:
710                     o_join = join_round;
711                     break;
712                 default:
713                     o_join = join_straight;
714                     break;
715             }
717             switch (captype) {
718                 case SP_STROKE_LINECAP_SQUARE:
719                     o_butt = butt_square;
720                     break;
721                 case SP_STROKE_LINECAP_ROUND:
722                     o_butt = butt_round;
723                     break;
724                 default:
725                     o_butt = butt_straight;
726                     break;
727             }
729             if (o_width < 0.1)
730                 o_width = 0.1;
731             o_miter = i_style->stroke_miterlimit.value * o_width;
732         }
734         SPCurve *curvetemp = curve_for_item(item);
735         if (curvetemp == NULL) {
736             curve->unref();
737             continue;
738         }
739         // Livarots outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is created correctly.
740         Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curvetemp->get_pathvector() );
741         curvetemp->unref();
743         Path *orig = new Path;
744         orig->LoadPathVector(pathv);
746         Path *res = new Path;
747         res->SetBackData(false);
749         if (i_style->stroke_dash.n_dash) {
750             // For dashed strokes, use Stroke method, because Outline can't do dashes
751             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
753             orig->ConvertWithBackData(0.1);
755             orig->DashPolylineFromStyle(i_style, scale, 0);
757             Shape* theShape = new Shape;
758             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
759                          0.5 * o_miter);
760             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
762             Shape *theRes = new Shape;
764             theRes->ConvertToShape(theShape, fill_positive);
766             Path *originaux[1];
767             originaux[0] = res;
768             theRes->ConvertToForme(orig, 1, originaux);
770             res->Coalesce(5.0);
772             delete theShape;
773             delete theRes;
775         } else {
777             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
779             orig->Coalesce(0.5 * o_width);
781             Shape *theShape = new Shape;
782             Shape *theRes = new Shape;
784             res->ConvertWithBackData(1.0);
785             res->Fill(theShape, 0);
786             theRes->ConvertToShape(theShape, fill_positive);
788             Path *originaux[1];
789             originaux[0] = res;
790             theRes->ConvertToForme(orig, 1, originaux);
792             delete theShape;
793             delete theRes;
794         }
796         if (orig->descr_cmd.size() <= 1) {
797             // ca a merd\8e, ou bien le resultat est vide
798             delete res;
799             delete orig;
800             continue;
801         }
803         did = true;
805         // remember the position of the item
806         gint pos = SP_OBJECT_REPR(item)->position();
807         // remember parent
808         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
809         // remember id
810         char const *id = SP_OBJECT_REPR(item)->attribute("id");
812         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
814             SPDocument * doc = sp_desktop_document(desktop);
815             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
816             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
818             // restore old style, but set old stroke style on fill
819             sp_repr_css_change(repr, ncss, "style");
821             sp_repr_css_attr_unref(ncss);
823             gchar *str = orig->svg_dump_path();
824             repr->setAttribute("d", str);
825             g_free(str);
827             if (mask)
828                 repr->setAttribute("mask", mask);
829             if (clip_path)
830                 repr->setAttribute("clip-path", clip_path);
832             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
834                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
835                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
837                 // add the group to the parent
838                 parent->appendChild(g_repr);
839                 // move to the saved position
840                 g_repr->setPosition(pos > 0 ? pos : 0);
842                 g_repr->appendChild(repr);
843                 repr->setAttribute("id", id);
844                 SPItem *newitem = (SPItem *) doc->getObjectByRepr(repr);
845                 sp_item_write_transform(newitem, repr, transform);
847                 SPShape *shape = SP_SHAPE(item);
849                 Geom::PathVector const & pathv = curve->get_pathvector();
850                 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
851                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_START] ) {
852                         Geom::Matrix const m (sp_shape_marker_get_transform_at_start(path_it->front()));
853                         sp_selected_path_outline_add_marker( marker_obj, m,
854                                                              NR::scale(i_style->stroke_width.computed), transform,
855                                                              g_repr, xml_doc, doc );
856                     }
858                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_MID] ) {
859                         Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
860                         Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
861                         while (curve_it2 != path_it->end_default())
862                         {
863                             /* Put marker between curve_it1 and curve_it2.
864                              * Loop to end_default (so including closing segment), because when a path is closed,
865                              * there should be a midpoint marker between last segment and closing straight line segment
866                              */
867                             Geom::Matrix const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2));
868                             sp_selected_path_outline_add_marker( marker_obj, m,
869                                                                  NR::scale(i_style->stroke_width.computed), transform,
870                                                                  g_repr, xml_doc, doc );
872                             ++curve_it1;
873                             ++curve_it2;
874                         }
875                     }
877                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_END] ) {
878                         Geom::Matrix const m (sp_shape_marker_get_transform_at_end(path_it->back_default()));
879                         sp_selected_path_outline_add_marker( marker_obj, m,
880                                                              NR::scale(i_style->stroke_width.computed), transform,
881                                                              g_repr, xml_doc, doc );
882                     }
883                 }
885                 selection->add(g_repr);
887                 Inkscape::GC::release(g_repr);
890             } else {
892                 // add the new repr to the parent
893                 parent->appendChild(repr);
895                 // move to the saved position
896                 repr->setPosition(pos > 0 ? pos : 0);
898                 repr->setAttribute("id", id);
900                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
901                 sp_item_write_transform(newitem, repr, transform);
903                 selection->add(repr);
905             }
907             Inkscape::GC::release(repr);
909             curve->unref();
910             selection->remove(item);
911             SP_OBJECT(item)->deleteObject(false);
913         }
915         delete res;
916         delete orig;
917     }
919     if (did) {
920         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
921                          _("Convert stroke to path"));
922     } else {
923         // TRANSLATORS: "to outline" means "to convert stroke to path"
924         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
925         return;
926     }
930 void
931 sp_selected_path_offset()
933     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
935     sp_selected_path_do_offset(true, prefOffset);
937 void
938 sp_selected_path_inset()
940     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
942     sp_selected_path_do_offset(false, prefOffset);
945 void
946 sp_selected_path_offset_screen(double pixels)
948     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
951 void
952 sp_selected_path_inset_screen(double pixels)
954     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
958 void sp_selected_path_create_offset_object_zero()
960     sp_selected_path_create_offset_object(0, false);
963 void sp_selected_path_create_offset()
965     sp_selected_path_create_offset_object(1, false);
967 void sp_selected_path_create_inset()
969     sp_selected_path_create_offset_object(-1, false);
972 void sp_selected_path_create_updating_offset_object_zero()
974     sp_selected_path_create_offset_object(0, true);
977 void sp_selected_path_create_updating_offset()
979     sp_selected_path_create_offset_object(1, true);
981 void sp_selected_path_create_updating_inset()
983     sp_selected_path_create_offset_object(-1, true);
986 void
987 sp_selected_path_create_offset_object(int expand, bool updating)
989     Inkscape::Selection *selection;
990     Inkscape::XML::Node *repr;
991     SPItem *item;
992     SPCurve *curve;
993     gchar *style, *str;
994     SPDesktop *desktop;
995     float o_width, o_miter;
996     JoinType o_join;
997     ButtType o_butt;
999     curve = NULL;
1001     desktop = SP_ACTIVE_DESKTOP;
1003     selection = sp_desktop_selection(desktop);
1005     item = selection->singleItem();
1007     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1008         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1009         return;
1010     }
1011     if (SP_IS_SHAPE(item))
1012     {
1013         curve = sp_shape_get_curve(SP_SHAPE(item));
1014         if (curve == NULL)
1015             return;
1016     }
1017     if (SP_IS_TEXT(item))
1018     {
1019         curve = SP_TEXT(item)->getNormalizedBpath();
1020         if (curve == NULL)
1021             return;
1022     }
1024     NR::Matrix const transform(item->transform);
1026     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1028     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1030     // remember the position of the item
1031     gint pos = SP_OBJECT_REPR(item)->position();
1032     // remember parent
1033     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1035     {
1036         SPStyle *i_style = SP_OBJECT(item)->style;
1037         int jointype, captype;
1039         jointype = i_style->stroke_linejoin.value;
1040         captype = i_style->stroke_linecap.value;
1041         o_width = i_style->stroke_width.computed;
1042         if (jointype == SP_STROKE_LINEJOIN_MITER)
1043         {
1044             o_join = join_pointy;
1045         }
1046         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1047         {
1048             o_join = join_round;
1049         }
1050         else
1051         {
1052             o_join = join_straight;
1053         }
1054         if (captype == SP_STROKE_LINECAP_SQUARE)
1055         {
1056             o_butt = butt_square;
1057         }
1058         else if (captype == SP_STROKE_LINECAP_ROUND)
1059         {
1060             o_butt = butt_round;
1061         }
1062         else
1063         {
1064             o_butt = butt_straight;
1065         }
1067         {
1068             double prefOffset = 1.0;
1069             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1070             o_width = prefOffset;
1071         }
1073         if (o_width < 0.01)
1074             o_width = 0.01;
1075         o_miter = i_style->stroke_miterlimit.value * o_width;
1076     }
1078     Path *orig = Path_for_item(item, true, false);
1079     if (orig == NULL)
1080     {
1081         g_free(style);
1082         curve->unref();
1083         return;
1084     }
1086     Path *res = new Path;
1087     res->SetBackData(false);
1089     {
1090         Shape *theShape = new Shape;
1091         Shape *theRes = new Shape;
1093         orig->ConvertWithBackData(1.0);
1094         orig->Fill(theShape, 0);
1096         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1097         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1098         if (val && strcmp(val, "nonzero") == 0)
1099         {
1100             theRes->ConvertToShape(theShape, fill_nonZero);
1101         }
1102         else if (val && strcmp(val, "evenodd") == 0)
1103         {
1104             theRes->ConvertToShape(theShape, fill_oddEven);
1105         }
1106         else
1107         {
1108             theRes->ConvertToShape(theShape, fill_nonZero);
1109         }
1111         Path *originaux[1];
1112         originaux[0] = orig;
1113         theRes->ConvertToForme(res, 1, originaux);
1115         delete theShape;
1116         delete theRes;
1117     }
1119     curve->unref();
1121     if (res->descr_cmd.size() <= 1)
1122     {
1123         // pas vraiment de points sur le resultat
1124         // donc il ne reste rien
1125         sp_document_done(sp_desktop_document(desktop), 
1126                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1127                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1128                          (updating ? _("Create linked offset")
1129                           : _("Create dynamic offset")));
1130         selection->clear();
1132         delete res;
1133         delete orig;
1134         g_free(style);
1135         return;
1136     }
1138     {
1139         gchar tstr[80];
1141         tstr[79] = '\0';
1143         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1144         repr = xml_doc->createElement("svg:path");
1145         repr->setAttribute("sodipodi:type", "inkscape:offset");
1146         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1147                                                           ? o_width
1148                                                           : expand < 0
1149                                                           ? -o_width
1150                                                           : 0 ));
1152         str = res->svg_dump_path();
1153         repr->setAttribute("inkscape:original", str);
1154         g_free(str);
1156         if ( updating ) {
1157             char const *id = SP_OBJECT(item)->repr->attribute("id");
1158             char const *uri = g_strdup_printf("#%s", id);
1159             repr->setAttribute("xlink:href", uri);
1160             g_free((void *) uri);
1161         } else {
1162             repr->setAttribute("inkscape:href", NULL);
1163         }
1165         repr->setAttribute("style", style);
1167         // add the new repr to the parent
1168         parent->appendChild(repr);
1170         // move to the saved position
1171         repr->setPosition(pos > 0 ? pos : 0);
1173         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1175         if ( updating ) {
1176             // on conserve l'original
1177             // we reapply the transform to the original (offset will feel it)
1178             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1179         } else {
1180             // delete original, apply the transform to the offset
1181             SP_OBJECT(item)->deleteObject(false);
1182             sp_item_write_transform(nitem, repr, transform);
1183         }
1185         // The object just created from a temporary repr is only a seed.
1186         // We need to invoke its write which will update its real repr (in particular adding d=)
1187         SP_OBJECT(nitem)->updateRepr();
1189         Inkscape::GC::release(repr);
1191         selection->set(nitem);
1192     }
1194     sp_document_done(sp_desktop_document(desktop), 
1195                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1196                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1197                      (updating ? _("Create linked offset")
1198                       : _("Create dynamic offset")));
1200     delete res;
1201     delete orig;
1203     g_free(style);
1217 void
1218 sp_selected_path_do_offset(bool expand, double prefOffset)
1220     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1222     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1224     if (selection->isEmpty()) {
1225         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1226         return;
1227     }
1229     bool did = false;
1231     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1232          items != NULL;
1233          items = items->next) {
1235         SPItem *item = (SPItem *) items->data;
1237         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1238             continue;
1240         SPCurve *curve = NULL;
1241         if (SP_IS_SHAPE(item)) {
1242             curve = sp_shape_get_curve(SP_SHAPE(item));
1243             if (curve == NULL)
1244                 continue;
1245         }
1246         if (SP_IS_TEXT(item)) {
1247             curve = SP_TEXT(item)->getNormalizedBpath();
1248             if (curve == NULL)
1249                 continue;
1250         }
1252         NR::Matrix const transform(item->transform);
1254         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1256         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1258         float o_width, o_miter;
1259         JoinType o_join;
1260         ButtType o_butt;
1262         {
1263             SPStyle *i_style = SP_OBJECT(item)->style;
1264             int jointype, captype;
1266             jointype = i_style->stroke_linejoin.value;
1267             captype = i_style->stroke_linecap.value;
1268             o_width = i_style->stroke_width.computed;
1270             switch (jointype) {
1271                 case SP_STROKE_LINEJOIN_MITER:
1272                     o_join = join_pointy;
1273                     break;
1274                 case SP_STROKE_LINEJOIN_ROUND:
1275                     o_join = join_round;
1276                     break;
1277                 default:
1278                     o_join = join_straight;
1279                     break;
1280             }
1282             switch (captype) {
1283                 case SP_STROKE_LINECAP_SQUARE:
1284                     o_butt = butt_square;
1285                     break;
1286                 case SP_STROKE_LINECAP_ROUND:
1287                     o_butt = butt_round;
1288                     break;
1289                 default:
1290                     o_butt = butt_straight;
1291                     break;
1292             }
1294             o_width = prefOffset;
1296             if (o_width < 0.1)
1297                 o_width = 0.1;
1298             o_miter = i_style->stroke_miterlimit.value * o_width;
1299         }
1301         Path *orig = Path_for_item(item, false);
1302         if (orig == NULL) {
1303             g_free(style);
1304             curve->unref();
1305             continue;
1306         }
1308         Path *res = new Path;
1309         res->SetBackData(false);
1311         {
1312             Shape *theShape = new Shape;
1313             Shape *theRes = new Shape;
1315             orig->ConvertWithBackData(0.03);
1316             orig->Fill(theShape, 0);
1318             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1319             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1320             if (val && strcmp(val, "nonzero") == 0)
1321             {
1322                 theRes->ConvertToShape(theShape, fill_nonZero);
1323             }
1324             else if (val && strcmp(val, "evenodd") == 0)
1325             {
1326                 theRes->ConvertToShape(theShape, fill_oddEven);
1327             }
1328             else
1329             {
1330                 theRes->ConvertToShape(theShape, fill_nonZero);
1331             }
1333             // et maintenant: offset
1334             // methode inexacte
1335 /*                      Path *originaux[1];
1336                         originaux[0] = orig;
1337                         theRes->ConvertToForme(res, 1, originaux);
1339                         if (expand) {
1340                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1341                         } else {
1342                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1343                         }
1345                         orig->ConvertWithBackData(1.0);
1346                         orig->Fill(theShape, 0);
1347                         theRes->ConvertToShape(theShape, fill_positive);
1348                         originaux[0] = orig;
1349                         theRes->ConvertToForme(res, 1, originaux);
1351                         if (o_width >= 0.5) {
1352                         //     res->Coalesce(1.0);
1353                         res->ConvertEvenLines(1.0);
1354                         res->Simplify(1.0);
1355                         } else {
1356                         //      res->Coalesce(o_width);
1357                         res->ConvertEvenLines(1.0*o_width);
1358                         res->Simplify(1.0 * o_width);
1359                         }    */
1360             // methode par makeoffset
1362             if (expand)
1363             {
1364                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1365             }
1366             else
1367             {
1368                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1369             }
1370             theRes->ConvertToShape(theShape, fill_positive);
1372             res->Reset();
1373             theRes->ConvertToForme(res);
1375             if (o_width >= 1.0)
1376             {
1377                 res->ConvertEvenLines(1.0);
1378                 res->Simplify(1.0);
1379             }
1380             else
1381             {
1382                 res->ConvertEvenLines(1.0*o_width);
1383                 res->Simplify(1.0 * o_width);
1384             }
1386             delete theShape;
1387             delete theRes;
1388         }
1390         did = true;
1392         curve->unref();
1393         // remember the position of the item
1394         gint pos = SP_OBJECT_REPR(item)->position();
1395         // remember parent
1396         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1397         // remember id
1398         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1400         selection->remove(item);
1401         SP_OBJECT(item)->deleteObject(false);
1403         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1405             gchar tstr[80];
1407             tstr[79] = '\0';
1409             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1410             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1412             repr->setAttribute("style", style);
1414             gchar *str = res->svg_dump_path();
1415             repr->setAttribute("d", str);
1416             g_free(str);
1418             // add the new repr to the parent
1419             parent->appendChild(repr);
1421             // move to the saved position
1422             repr->setPosition(pos > 0 ? pos : 0);
1424             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1426             // reapply the transform
1427             sp_item_write_transform(newitem, repr, transform);
1429             repr->setAttribute("id", id);
1431             selection->add(repr);
1433             Inkscape::GC::release(repr);
1434         }
1436         delete orig;
1437         delete res;
1438     }
1440     if (did) {
1441         sp_document_done(sp_desktop_document(desktop), 
1442                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1443                          (expand ? _("Outset path") : _("Inset path")));
1444     } else {
1445         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1446         return;
1447     }
1451 static bool
1452 sp_selected_path_simplify_items(SPDesktop *desktop,
1453                                 Inkscape::Selection *selection, GSList *items,
1454                                 float threshold,  bool justCoalesce,
1455                                 float angleLimit, bool breakableAngles,
1456                                 bool modifySelection);
1459 //return true if we changed something, else false
1460 bool
1461 sp_selected_path_simplify_item(SPDesktop *desktop,
1462                  Inkscape::Selection *selection, SPItem *item,
1463                  float threshold,  bool justCoalesce,
1464                  float angleLimit, bool breakableAngles,
1465                  gdouble size,     bool modifySelection)
1467     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1468         return false;
1470     //If this is a group, do the children instead
1471     if (SP_IS_GROUP(item)) {
1472         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1473         
1474         return sp_selected_path_simplify_items(desktop, selection, items,
1475                                                threshold, justCoalesce,
1476                                                angleLimit, breakableAngles,
1477                                                false);
1478     }
1481     SPCurve *curve = NULL;
1483     if (SP_IS_SHAPE(item)) {
1484         curve = sp_shape_get_curve(SP_SHAPE(item));
1485         if (!curve)
1486             return false;
1487     }
1489     if (SP_IS_TEXT(item)) {
1490         curve = SP_TEXT(item)->getNormalizedBpath();
1491         if (!curve)
1492             return false;
1493     }
1495     // save the transform, to re-apply it after simplification
1496     NR::Matrix const transform(item->transform);
1498     /*
1499        reset the transform, effectively transforming the item by transform.inverse();
1500        this is necessary so that the item is transformed twice back and forth,
1501        allowing all compensations to cancel out regardless of the preferences
1502     */
1503     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1505     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1506     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1507     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1509     Path *orig = Path_for_item(item, false);
1510     if (orig == NULL) {
1511         g_free(style);
1512         curve->unref();
1513         return false;
1514     }
1516     curve->unref();
1517     // remember the position of the item
1518     gint pos = SP_OBJECT_REPR(item)->position();
1519     // remember parent
1520     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1521     // remember id
1522     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1523     // remember path effect
1524     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1526     //If a group was selected, to not change the selection list
1527     if (modifySelection)
1528         selection->remove(item);
1530     SP_OBJECT(item)->deleteObject(false);
1532     if ( justCoalesce ) {
1533         orig->Coalesce(threshold * size);
1534     } else {
1535         orig->ConvertEvenLines(threshold * size);
1536         orig->Simplify(threshold * size);
1537     }
1539     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1540     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1542     // restore style, mask and clip-path
1543     repr->setAttribute("style", style);
1544     g_free(style);
1546     if ( mask ) {
1547         repr->setAttribute("mask", mask);
1548         g_free(mask);
1549     }
1551     if ( clip_path ) {
1552         repr->setAttribute("clip-path", clip_path);
1553         g_free(clip_path);
1554     }
1556     // path
1557     gchar *str = orig->svg_dump_path();
1558     if (patheffect)
1559         repr->setAttribute("inkscape:original-d", str);
1560     else 
1561         repr->setAttribute("d", str);
1562     g_free(str);
1564     // restore id
1565     repr->setAttribute("id", id);
1567     // add the new repr to the parent
1568     parent->appendChild(repr);
1570     // move to the saved position
1571     repr->setPosition(pos > 0 ? pos : 0);
1573     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1575     // reapply the transform
1576     sp_item_write_transform(newitem, repr, transform);
1578     // restore path effect
1579     repr->setAttribute("inkscape:path-effect", patheffect);
1581     //If we are not in a selected group
1582     if (modifySelection)
1583         selection->add(repr);
1585     Inkscape::GC::release(repr);
1587     // clean up
1588     if (orig) delete orig;
1590     return true;
1594 bool
1595 sp_selected_path_simplify_items(SPDesktop *desktop,
1596                                 Inkscape::Selection *selection, GSList *items,
1597                                 float threshold,  bool justCoalesce,
1598                                 float angleLimit, bool breakableAngles,
1599                                 bool modifySelection)
1601   bool simplifyIndividualPaths =
1602     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1603   
1604   gchar *simplificationType;
1605   if (simplifyIndividualPaths) {
1606       simplificationType = _("Simplifying paths (separately):");
1607   } else {
1608       simplificationType = _("Simplifying paths:");
1609   }
1611   bool didSomething = false;
1613   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1614   if (!selectionBbox) {
1615     return false;
1616   }
1617   gdouble selectionSize  = L2(selectionBbox->dimensions());
1619   gdouble simplifySize  = selectionSize;
1620   
1621   int pathsSimplified = 0;
1622   int totalPathCount  = g_slist_length(items);
1623   
1624   // set "busy" cursor
1625   desktop->setWaitingCursor();
1626   
1627   for (; items != NULL; items = items->next) {
1628       SPItem *item = (SPItem *) items->data;
1629       
1630       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1631           continue;
1633       if (simplifyIndividualPaths) {
1634           NR::Maybe<NR::Rect> itemBbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
1635           if (itemBbox) {
1636               simplifySize      = L2(itemBbox->dimensions());
1637           } else {
1638               simplifySize      = 0;
1639           }
1640       }
1642       pathsSimplified++;
1644       if (pathsSimplified % 20 == 0) {
1645         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1646         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1647       }
1649       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1650                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1651   }
1653   desktop->clearWaitingCursor();
1655   if (pathsSimplified > 20) {
1656     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1657   }
1658   
1659   return didSomething;
1662 void
1663 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1664                        float angleLimit, bool breakableAngles)
1666     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1668     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1670     if (selection->isEmpty()) {
1671         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1672                          _("Select <b>path(s)</b> to simplify."));
1673         return;
1674     }
1676     GSList *items = g_slist_copy((GSList *) selection->itemList());
1678     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1679                                                         items, threshold,
1680                                                         justCoalesce,
1681                                                         angleLimit,
1682                                                         breakableAngles, true);
1684     if (didSomething)
1685         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1686                          _("Simplify"));
1687     else
1688         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1693 // globals for keeping track of accelerated simplify
1694 static double previousTime      = 0.0;
1695 static gdouble simplifyMultiply = 1.0;
1697 void
1698 sp_selected_path_simplify(void)
1700     gdouble simplifyThreshold =
1701         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1702     bool simplifyJustCoalesce =
1703         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1705     //Get the current time
1706     GTimeVal currentTimeVal;
1707     g_get_current_time(&currentTimeVal);
1708     double currentTime = currentTimeVal.tv_sec * 1000000 +
1709                 currentTimeVal.tv_usec;
1711     //Was the previous call to this function recent? (<0.5 sec)
1712     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1714         // add to the threshold 1/2 of its original value
1715         simplifyMultiply  += 0.5;
1716         simplifyThreshold *= simplifyMultiply;
1718     } else {
1719         // reset to the default
1720         simplifyMultiply = 1;
1721     }
1723     //remember time for next call
1724     previousTime = currentTime;
1726     //g_print("%g\n", simplify_threshold);
1728     //Make the actual call
1729     sp_selected_path_simplify_selection(simplifyThreshold,
1730                       simplifyJustCoalesce, 0.0, false);
1735 // fonctions utilitaires
1737 bool
1738 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1740     if (who == NULL || a == NULL)
1741         return false;
1742     if (who == a)
1743         return true;
1744     return Ancetre(sp_repr_parent(a), who);
1747 Path *
1748 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1750     SPCurve *curve = curve_for_item(item);
1751     if (curve == NULL)
1752         return NULL;
1754     Geom::PathVector pathv = pathvector_for_curve(item, curve, doTransformation, transformFull);
1756     Path *dest = new Path;
1757     dest->LoadPathVector(pathv);
1759     curve->unref();
1760     
1761     return dest;
1764 /* 
1765  * This function always returns a new NArtBpath, the caller must g_free the returned path!
1766 */
1767 NArtBpath *
1768 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, NR::Matrix extraPreAffine, NR::Matrix extraPostAffine)
1770     if (curve == NULL)
1771         return NULL;
1773     NArtBpath *bpath = BPath_from_2GeomPath(curve->get_pathvector());
1774     if (bpath == NULL) {
1775         return NULL;
1776     }
1778     NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1779     if (doTransformation) {
1780         if (transformFull) {
1781             new_bpath = nr_artpath_affine(bpath, extraPreAffine * from_2geom(sp_item_i2doc_affine(item)) * extraPostAffine);
1782         } else {
1783             new_bpath = nr_artpath_affine(bpath, extraPreAffine * item->transform * extraPostAffine);
1784         }
1785     } else {
1786         new_bpath = nr_artpath_affine(bpath, extraPreAffine * NR::identity() * extraPostAffine);
1787     }
1789     g_free(bpath);
1790     return new_bpath;
1793 /* 
1794  * NOTE: Returns empty pathvector if curve == NULL
1795  * TODO: see if calling this method can be optimized. All the pathvector copying might be slow.
1796  */
1797 Geom::PathVector
1798 pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1800     if (curve == NULL)
1801         return Geom::PathVector();
1803     if (doTransformation) {
1804         if (transformFull) {
1805             return (curve->get_pathvector()) * sp_item_i2doc_affine(item);
1806         } else {
1807             return (curve->get_pathvector()) * to_2geom(item->transform);
1808         }
1809     } else {
1810         return curve->get_pathvector();
1811     }
1814 SPCurve* curve_for_item(SPItem *item)
1816     if (!item) {
1817         return NULL;
1818     }
1820     SPCurve *curve = NULL;
1821     if (SP_IS_SHAPE(item)) {
1822         if (SP_IS_PATH(item)) {
1823                 curve = sp_path_get_curve_for_edit(SP_PATH(item));
1824         } else {
1825             curve = sp_shape_get_curve(SP_SHAPE(item));
1826         }
1827     }
1828     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1829     {
1830         curve = te_get_layout(item)->convertToCurves();
1831     }
1832     else if (SP_IS_IMAGE(item))
1833     {
1834         curve = sp_image_get_curve(SP_IMAGE(item));
1835     }
1836     
1837     return curve; // do not forget to unref the curve at some point!
1840 Path *bpath_to_Path(NArtBpath const *bpath) {
1841     Path *dest = new Path;
1842     dest->SetBackData(false);
1843     {
1844         int   i;
1845         bool  closed = false;
1846         float lastX  = 0.0;
1847         float lastY  = 0.0;
1849         for (i = 0; bpath[i].code != NR_END; i++) {
1850             switch (bpath[i].code) {
1851                 case NR_LINETO:
1852                     lastX = bpath[i].x3;
1853                     lastY = bpath[i].y3;
1854                     {
1855                         NR::Point tmp(lastX, lastY);
1856                         dest->LineTo(tmp);
1857                     }
1858                     break;
1860                 case NR_CURVETO:
1861                 {
1862                     NR::Point tmp, tms, tme;
1863                     tmp[0]=bpath[i].x3;
1864                     tmp[1]=bpath[i].y3;
1865                     tms[0]=3 * (bpath[i].x1 - lastX);
1866                     tms[1]=3 * (bpath[i].y1 - lastY);
1867                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1868                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1869                     dest->CubicTo(tmp,tms,tme);
1870                 }
1871                 lastX = bpath[i].x3;
1872                 lastY = bpath[i].y3;
1873                 break;
1875                 case NR_MOVETO_OPEN:
1876                 case NR_MOVETO:
1877                     if (closed)
1878                         dest->Close();
1879                     closed = (bpath[i].code == NR_MOVETO);
1880                     lastX = bpath[i].x3;
1881                     lastY = bpath[i].y3;
1882                     {
1883                         NR::Point  tmp(lastX, lastY);
1884                         dest->MoveTo(tmp);
1885                     }
1886                     break;
1887                 default:
1888                     break;
1889             }
1890         }
1891         if (closed)
1892             dest->Close();
1893     }
1894     return dest;
1897 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1899     //get nearest position on path
1900     Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1901     return pos;
1904 NR::Point get_point_on_Path(Path *path, int piece, double t)
1906     NR::Point p;
1907     path->PointAt(piece, t, p);
1908     return p;
1912 /*
1913   Local Variables:
1914   mode:c++
1915   c-file-style:"stroustrup"
1916   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1917   indent-tabs-mode:nil
1918   fill-column:99
1919   End:
1920 */
1921 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :