Code

remove all old nartbpath code from SPCurve!!! (in other words, lib2geomification...
[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>
58 #include "livarot/Path.h"
59 #include "livarot/Shape.h"
61 #include "splivarot.h"
63 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
65 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
66 void sp_selected_path_do_offset(bool expand, double prefOffset);
67 void sp_selected_path_create_offset_object(int expand, bool updating);
69 void
70 sp_selected_path_union()
71 {
72     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
73 }
75 void
76 sp_selected_path_union_skip_undo()
77 {
78     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
79 }
81 void
82 sp_selected_path_intersect()
83 {
84     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
85 }
87 void
88 sp_selected_path_diff()
89 {
90     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
91 }
93 void
94 sp_selected_path_diff_skip_undo()
95 {
96     sp_selected_path_boolop(bool_op_diff, SP_VERB_NONE, _("Difference"));
97 }
99 void
100 sp_selected_path_symdiff()
102     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
104 void
105 sp_selected_path_cut()
107     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
109 void
110 sp_selected_path_slice()
112     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
116 // boolean operations
117 // take the source paths from the file, do the operation, delete the originals and add the results
118 void
119 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
121     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
123     Inkscape::Selection *selection = sp_desktop_selection(desktop);
124     
125     GSList *il = (GSList *) selection->itemList();
126     
127     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
128     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
129         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
130         return;
131     }
132     else if ( g_slist_length(il) < 1 ) {
133         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
134         return;
135     }
137     if (g_slist_length(il) > 2) {
138         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
139             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
140             return;
141         }
142     }
144     // reverseOrderForOp marks whether the order of the list is the top->down order
145     // it's only used when there are 2 objects, and for operations who need to know the
146     // topmost object (differences, cuts)
147     bool reverseOrderForOp = false;
149     // mettre les elements de la liste dans l'ordre pour ces operations
150     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
151         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
152         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
153         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
155         if (a == NULL || b == NULL) {
156             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."));
157             return;
158         }
160         if (Ancetre(a, b)) {
161             // a is the parent of b, already in the proper order
162         } else if (Ancetre(b, a)) {
163             // reverse order
164             reverseOrderForOp = true;
165         } else {
167             // objects are not in parent/child relationship;
168             // find their lowest common ancestor
169             Inkscape::XML::Node *dad = LCA(a, b);
170             if (dad == NULL) {
171                 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."));
172                 return;
173             }
175             // find the children of the LCA that lead from it to the a and b
176             Inkscape::XML::Node *as = AncetreFils(a, dad);
177             Inkscape::XML::Node *bs = AncetreFils(b, dad);
179             // find out which comes first
180             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
181                 if (child == as) {
182                     /* a first, so reverse. */
183                     reverseOrderForOp = true;
184                     break;
185                 }
186                 if (child == bs)
187                     break;
188             }
189         }
190     }
192     il = g_slist_copy(il);
194     // first check if all the input objects have shapes
195     // otherwise bail out
196     for (GSList *l = il; l != NULL; l = l->next)
197     {
198         SPItem *item = SP_ITEM(l->data);
199         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
200         {
201             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
202             g_slist_free(il);
203             return;
204         }
205     }
207     // extract the livarot Paths from the source objects
208     // also get the winding rule specified in the style
209     int nbOriginaux = g_slist_length(il);
210     std::vector<Path *> originaux(nbOriginaux);
211     std::vector<FillRule> origWind(nbOriginaux);
212     int curOrig;
213     {
214         curOrig = 0;
215         for (GSList *l = il; l != NULL; l = l->next)
216         {
217             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
218             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
219             if (val && strcmp(val, "nonzero") == 0) {
220                 origWind[curOrig]= fill_nonZero;
221             } else if (val && strcmp(val, "evenodd") == 0) {
222                 origWind[curOrig]= fill_oddEven;
223             } else {
224                 origWind[curOrig]= fill_nonZero;
225             }
227             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
228             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
229             {
230                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
231                 g_slist_free(il);
232                 return;
233             }
234             curOrig++;
235         }
236     }
237     // reverse if needed
238     // note that the selection list keeps its order
239     if ( reverseOrderForOp ) {
240         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
241         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
242     }
244     // and work
245     // some temporary instances, first
246     Shape *theShapeA = new Shape;
247     Shape *theShapeB = new Shape;
248     Shape *theShape = new Shape;
249     Path *res = new Path;
250     res->SetBackData(false);
251     Path::cut_position  *toCut=NULL;
252     int                  nbToCut=0;
254     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
255         // true boolean op
256         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
257         originaux[0]->ConvertWithBackData(0.1);
259         originaux[0]->Fill(theShape, 0);
261         theShapeA->ConvertToShape(theShape, origWind[0]);
263         curOrig = 1;
264         for (GSList *l = il->next; l != NULL; l = l->next) {
265             originaux[curOrig]->ConvertWithBackData(0.1);
267             originaux[curOrig]->Fill(theShape, curOrig);
269             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
271             // les elements arrivent en ordre inverse dans la liste
272             theShape->Booleen(theShapeB, theShapeA, bop);
274             {
275                 Shape *swap = theShape;
276                 theShape = theShapeA;
277                 theShapeA = swap;
278             }
279             curOrig++;
280         }
282         {
283             Shape *swap = theShape;
284             theShape = theShapeA;
285             theShapeA = swap;
286         }
288     } else if ( bop == bool_op_cut ) {
289         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
290         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
291         // it is just uncrossed, and cleaned from duplicate edges and points
292         // then it's fed to Booleen() which will uncross it against the other path
293         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
294         // thus making a polygon. the weight of the edges of the cut are all 0, but
295         // the Booleen need to invert the ones inside the source polygon (for the subsequent
296         // ConvertToForme)
298         // the cut path needs to have the highest pathID in the back data
299         // that's how the Booleen() function knows it's an edge of the cut
301         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
302         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
303         // left it at 1.0. Investigate replacing this by a combination of difference and
304         // intersection of the same two paths. -- bb
305         {
306             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
307             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
308         }
309         originaux[0]->ConvertWithBackData(1.0);
311         originaux[0]->Fill(theShape, 0);
313         theShapeA->ConvertToShape(theShape, origWind[0]);
315         originaux[1]->ConvertWithBackData(1.0);
317         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
319         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
321         // les elements arrivent en ordre inverse dans la liste
322         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
324     } else if ( bop == bool_op_slice ) {
325         // slice is not really a boolean operation
326         // you just put the 2 shapes in a single polygon, uncross it
327         // the points where the degree is > 2 are intersections
328         // just check it's an intersection on the path you want to cut, and keep it
329         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
330         // make new subpath at each one of these positions
331         // inversion pour l'op\8eration
332         {
333             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
334             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
335         }
336         originaux[0]->ConvertWithBackData(1.0);
338         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
340         originaux[1]->ConvertWithBackData(1.0);
342         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
344         theShape->ConvertToShape(theShapeA, fill_justDont);
346         if ( theShape->hasBackData() ) {
347             // should always be the case, but ya never know
348             {
349                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
350                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
351                         // possibly an intersection
352                         // we need to check that at least one edge from the source path is incident to it
353                         // before we declare it's an intersection
354                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
355                         int   nbOrig=0;
356                         int   nbOther=0;
357                         int   piece=-1;
358                         float t=0.0;
359                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
360                             if ( theShape->ebData[cb].pathID == 0 ) {
361                                 // the source has an edge incident to the point, get its position on the path
362                                 piece=theShape->ebData[cb].pieceID;
363                                 if ( theShape->getEdge(cb).st == i ) {
364                                     t=theShape->ebData[cb].tSt;
365                                 } else {
366                                     t=theShape->ebData[cb].tEn;
367                                 }
368                                 nbOrig++;
369                             }
370                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
371                             cb=theShape->NextAt(i, cb);
372                         }
373                         if ( nbOrig > 0 && nbOther > 0 ) {
374                             // point incident to both path and cut: an intersection
375                             // note that you only keep one position on the source; you could have degenerate
376                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
377                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
378                             toCut[nbToCut].piece=piece;
379                             toCut[nbToCut].t=t;
380                             nbToCut++;
381                         }
382                     }
383                 }
384             }
385             {
386                 // i think it's useless now
387                 int i = theShape->numberOfEdges() - 1;
388                 for (;i>=0;i--) {
389                     if ( theShape->ebData[i].pathID == 1 ) {
390                         theShape->SubEdge(i);
391                     }
392                 }
393             }
395         }
396     }
398     int*    nesting=NULL;
399     int*    conts=NULL;
400     int     nbNest=0;
401     // pour compenser le swap juste avant
402     if ( bop == bool_op_slice ) {
403 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
404 //    res->ConvertForcedToMoveTo();
405         res->Copy(originaux[0]);
406         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
407         free(toCut);
408     } else if ( bop == bool_op_cut ) {
409         // il faut appeler pour desallouer PointData (pas vital, mais bon)
410         // the Booleen() function did not deallocated the point_data array in theShape, because this
411         // function needs it.
412         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
413         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
414         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
415     } else {
416         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
417     }
419     delete theShape;
420     delete theShapeA;
421     delete theShapeB;
422     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
424     if (res->descr_cmd.size() <= 1)
425     {
426         // only one command, presumably a moveto: it isn't a path
427         for (GSList *l = il; l != NULL; l = l->next)
428         {
429             SP_OBJECT(l->data)->deleteObject();
430         }
431         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
432                          description);
433         selection->clear();
435         delete res;
436         g_slist_free(il);
437         return;
438     }
440     // get the source path object
441     SPObject *source;
442     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
443         if (reverseOrderForOp) {
444              source = SP_OBJECT(il->data);
445         } else {
446              source = SP_OBJECT(il->next->data);
447         }
448     } else {
449         // find out the bottom object
450         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
452         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
454         source = sp_desktop_document(desktop)->
455             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
457         g_slist_free(sorted);
458     }
460     // adjust style properties that depend on a possible transform in the source object in order
461     // to get a correct style attribute for the new path
462     SPItem* item_source = SP_ITEM(source);
463     NR::Matrix i2root = from_2geom(sp_item_i2root_affine(item_source));
464     sp_item_adjust_stroke(item_source, NR::expansion(i2root));
465     sp_item_adjust_pattern(item_source, i2root);
466     sp_item_adjust_gradient(item_source, i2root);
467     sp_item_adjust_livepatheffect(item_source, i2root);
469     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
471     // remember important aspects of the source path, to be restored
472     gint pos = repr_source->position();
473     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
474     gchar const *id = repr_source->attribute("id");
475     gchar const *style = repr_source->attribute("style");
476     gchar const *mask = repr_source->attribute("mask");
477     gchar const *clip_path = repr_source->attribute("clip-path");
479     // remove source paths
480     selection->clear();
481     for (GSList *l = il; l != NULL; l = l->next) {
482         // if this is the bottommost object,
483         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
484             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
485             SP_OBJECT(l->data)->deleteObject(false);
486         } else {
487             // delete the object for real, so that its clones can take appropriate action
488             SP_OBJECT(l->data)->deleteObject();
489         }
490     }
491     g_slist_free(il);
493     // premultiply by the inverse of parent's repr
494     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
495     NR::Matrix local = from_2geom(sp_item_i2doc_affine(parent_item));
496     gchar *transform = sp_svg_transform_write(local.inverse());
498     // now that we have the result, add it on the canvas
499     if ( bop == bool_op_cut || bop == bool_op_slice ) {
500         int    nbRP=0;
501         Path** resPath;
502         if ( bop == bool_op_slice ) {
503             // there are moveto's at each intersection, but it's still one unique path
504             // so break it down and add each subpath independently
505             // we could call break_apart to do this, but while we have the description...
506             resPath=res->SubPaths(nbRP, false);
507         } else {
508             // cut operation is a bit wicked: you need to keep holes
509             // that's why you needed the nesting
510             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
511             // to get the path for each part of the polygon. that's why you need the nesting info:
512             // to know in wich subpath to add a subpath
513             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
515             // cleaning
516             if ( conts ) free(conts);
517             if ( nesting ) free(nesting);
518         }
520         // add all the pieces resulting from cut or slice
521         for (int i=0;i<nbRP;i++) {
522             gchar *d = resPath[i]->svg_dump_path();
524             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
525             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
526             repr->setAttribute("style", style);
527             if (mask)
528                 repr->setAttribute("mask", mask);
529             if (clip_path)
530                 repr->setAttribute("clip-path", clip_path);
532             repr->setAttribute("d", d);
533             g_free(d);
535             // for slice, remove fill
536             if (bop == bool_op_slice) {
537                 SPCSSAttr *css;
539                 css = sp_repr_css_attr_new();
540                 sp_repr_css_set_property(css, "fill", "none");
542                 sp_repr_css_change(repr, css, "style");
544                 sp_repr_css_attr_unref(css);
545             }
547             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
548             // this means it's basically random which of the pieces inherits the original's id and clones
549             // a better algorithm might figure out e.g. the biggest piece
550             repr->setAttribute("id", id);
552             repr->setAttribute("transform", transform);
554             // add the new repr to the parent
555             parent->appendChild(repr);
557             // move to the saved position
558             repr->setPosition(pos > 0 ? pos : 0);
560             selection->add(repr);
561             Inkscape::GC::release(repr);
563             delete resPath[i];
564         }
565         if ( resPath ) free(resPath);
567     } else {
568         gchar *d = res->svg_dump_path();
570         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
571         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
572         repr->setAttribute("style", style);
574         if ( mask )
575             repr->setAttribute("mask", mask);
577         if ( clip_path )
578             repr->setAttribute("clip-path", clip_path);
580         repr->setAttribute("d", d);
581         g_free(d);
583         repr->setAttribute("transform", transform);
585         repr->setAttribute("id", id);
586         parent->appendChild(repr);
587         repr->setPosition(pos > 0 ? pos : 0);
589         selection->add(repr);
590         Inkscape::GC::release(repr);
591     }
593     g_free(transform);
595     if (verb != SP_VERB_NONE) {
596         sp_document_done(sp_desktop_document(desktop), verb, description);
597     }
599     delete res;
602 static
603 void sp_selected_path_outline_add_marker( SPObject *marker_object, Geom::Matrix marker_transform, NR::scale stroke_scale, NR::Matrix transform,
604                                        Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument * doc )
606     SPMarker* marker = SP_MARKER (marker_object);
607     SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker_object));
609     NR::Matrix tr(from_2geom(marker_transform));
611     if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
612         tr = stroke_scale * tr;
613     }
615     // total marker transform
616     tr = marker_item->transform * marker->c2p * tr * transform;
618     if (SP_OBJECT_REPR(marker_item)) {
619         Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
620         g_repr->appendChild(m_repr);
621         SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr);
622         sp_item_write_transform(marker_item, m_repr, tr);
623     }
626 void
627 sp_selected_path_outline()
629     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
631     Inkscape::Selection *selection = sp_desktop_selection(desktop);
633     if (selection->isEmpty()) {
634         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
635         return;
636     }
638     bool did = false;
640     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
641          items != NULL;
642          items = items->next) {
644         SPItem *item = (SPItem *) items->data;
646         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
647             continue;
649         SPCurve *curve = NULL;
650         if (SP_IS_SHAPE(item)) {
651             curve = sp_shape_get_curve(SP_SHAPE(item));
652             if (curve == NULL)
653                 continue;
654         }
655         if (SP_IS_TEXT(item)) {
656             curve = SP_TEXT(item)->getNormalizedBpath();
657             if (curve == NULL)
658                 continue;
659         }
661         {   // pas de stroke pas de chocolat
662             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
663             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
665             if (val == NULL || strcmp(val, "none") == 0) {
666                 curve->unref();
667                 continue;
668             }
669         }
671         // remember old stroke style, to be set on fill
672         SPCSSAttr *ncss;
673         {
674             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
675             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
676             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
678             ncss = sp_repr_css_attr_new();
680             sp_repr_css_set_property(ncss, "stroke", "none");
681             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
682             sp_repr_css_set_property(ncss, "fill", val);
683             if ( opac ) {
684                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
685             } else {
686                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
687             }
688             sp_repr_css_unset_property(ncss, "marker-start");
689             sp_repr_css_unset_property(ncss, "marker-mid");
690             sp_repr_css_unset_property(ncss, "marker-end");
691         }
693         NR::Matrix const transform(item->transform);
694         float const scale = NR::expansion(transform);
695         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
696         SPStyle *i_style = SP_OBJECT(item)->style;
697         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
698         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
700         float o_width, o_miter;
701         JoinType o_join;
702         ButtType o_butt;
704         {
705             int jointype, captype;
707             jointype = i_style->stroke_linejoin.computed;
708             captype = i_style->stroke_linecap.computed;
709             o_width = i_style->stroke_width.computed;
711             switch (jointype) {
712                 case SP_STROKE_LINEJOIN_MITER:
713                     o_join = join_pointy;
714                     break;
715                 case SP_STROKE_LINEJOIN_ROUND:
716                     o_join = join_round;
717                     break;
718                 default:
719                     o_join = join_straight;
720                     break;
721             }
723             switch (captype) {
724                 case SP_STROKE_LINECAP_SQUARE:
725                     o_butt = butt_square;
726                     break;
727                 case SP_STROKE_LINECAP_ROUND:
728                     o_butt = butt_round;
729                     break;
730                 default:
731                     o_butt = butt_straight;
732                     break;
733             }
735             if (o_width < 0.1)
736                 o_width = 0.1;
737             o_miter = i_style->stroke_miterlimit.value * o_width;
738         }
740         Path *orig = Path_for_item(item, false);
741         if (orig == NULL) {
742             g_free(style);
743             curve->unref();
744             continue;
745         }
747         Path *res = new Path;
748         res->SetBackData(false);
750         if (i_style->stroke_dash.n_dash) {
751             // For dashed strokes, use Stroke method, because Outline can't do dashes
752             // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
754             orig->ConvertWithBackData(0.1);
756             orig->DashPolylineFromStyle(i_style, scale, 0);
758             Shape* theShape = new Shape;
759             orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
760                          0.5 * o_miter);
761             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
763             Shape *theRes = new Shape;
765             theRes->ConvertToShape(theShape, fill_positive);
767             Path *originaux[1];
768             originaux[0] = res;
769             theRes->ConvertToForme(orig, 1, originaux);
771             res->Coalesce(5.0);
773             delete theShape;
774             delete theRes;
776         } else {
778             orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
780             orig->Coalesce(0.5 * o_width);
782             Shape *theShape = new Shape;
783             Shape *theRes = new Shape;
785             res->ConvertWithBackData(1.0);
786             res->Fill(theShape, 0);
787             theRes->ConvertToShape(theShape, fill_positive);
789             Path *originaux[1];
790             originaux[0] = res;
791             theRes->ConvertToForme(orig, 1, originaux);
793             delete theShape;
794             delete theRes;
795         }
797         if (orig->descr_cmd.size() <= 1) {
798             // ca a merd\8e, ou bien le resultat est vide
799             delete res;
800             delete orig;
801             g_free(style);
802             continue;
803         }
805         did = true;
807         // remember the position of the item
808         gint pos = SP_OBJECT_REPR(item)->position();
809         // remember parent
810         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
811         // remember id
812         char const *id = SP_OBJECT_REPR(item)->attribute("id");
814         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
816             SPDocument * doc = sp_desktop_document(desktop);
817             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
818             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
820             // restore old style
821             repr->setAttribute("style", style);
823             // set old stroke style on fill
824             sp_repr_css_change(repr, ncss, "style");
826             sp_repr_css_attr_unref(ncss);
828             gchar *str = orig->svg_dump_path();
829             repr->setAttribute("d", str);
830             g_free(str);
832             if (mask)
833                 repr->setAttribute("mask", mask);
834             if (clip_path)
835                 repr->setAttribute("clip-path", clip_path);
837             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
839                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
840                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
842                 // add the group to the parent
843                 parent->appendChild(g_repr);
844                 // move to the saved position
845                 g_repr->setPosition(pos > 0 ? pos : 0);
847                 g_repr->appendChild(repr);
848                 repr->setAttribute("id", id);
849                 SPItem *newitem = (SPItem *) doc->getObjectByRepr(repr);
850                 sp_item_write_transform(newitem, repr, transform);
852                 SPShape *shape = SP_SHAPE(item);
854                 Geom::PathVector const & pathv = curve->get_pathvector();
855                 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
856                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_START] ) {
857                         Geom::Matrix const m (sp_shape_marker_get_transform_at_start(path_it->front()));
858                         sp_selected_path_outline_add_marker( marker_obj, m,
859                                                              NR::scale(i_style->stroke_width.computed), transform,
860                                                              g_repr, xml_doc, doc );
861                     }
863                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_MID] ) {
864                         Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
865                         Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
866                         while (curve_it2 != path_it->end_default())
867                         {
868                             /* Put marker between curve_it1 and curve_it2.
869                              * Loop to end_default (so including closing segment), because when a path is closed,
870                              * there should be a midpoint marker between last segment and closing straight line segment
871                              */
872                             Geom::Matrix const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2));
873                             sp_selected_path_outline_add_marker( marker_obj, m,
874                                                                  NR::scale(i_style->stroke_width.computed), transform,
875                                                                  g_repr, xml_doc, doc );
877                             ++curve_it1;
878                             ++curve_it2;
879                         }
880                     }
882                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_END] ) {
883                         Geom::Matrix const m (sp_shape_marker_get_transform_at_end(path_it->back_default()));
884                         sp_selected_path_outline_add_marker( marker_obj, m,
885                                                              NR::scale(i_style->stroke_width.computed), transform,
886                                                              g_repr, xml_doc, doc );
887                     }
888                 }
890                 selection->add(g_repr);
892                 Inkscape::GC::release(g_repr);
895             } else {
897                 // add the new repr to the parent
898                 parent->appendChild(repr);
900                 // move to the saved position
901                 repr->setPosition(pos > 0 ? pos : 0);
903                 repr->setAttribute("id", id);
905                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
906                 sp_item_write_transform(newitem, repr, transform);
908                 selection->add(repr);
910             }
912             Inkscape::GC::release(repr);
914             curve->unref();
915             selection->remove(item);
916             SP_OBJECT(item)->deleteObject(false);
918         }
920         delete res;
921         delete orig;
922         g_free(style);
924     }
926     if (did) {
927         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
928                          _("Convert stroke to path"));
929     } else {
930         // TRANSLATORS: "to outline" means "to convert stroke to path"
931         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
932         return;
933     }
937 void
938 sp_selected_path_offset()
940     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
942     sp_selected_path_do_offset(true, prefOffset);
944 void
945 sp_selected_path_inset()
947     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
949     sp_selected_path_do_offset(false, prefOffset);
952 void
953 sp_selected_path_offset_screen(double pixels)
955     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
958 void
959 sp_selected_path_inset_screen(double pixels)
961     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
965 void sp_selected_path_create_offset_object_zero()
967     sp_selected_path_create_offset_object(0, false);
970 void sp_selected_path_create_offset()
972     sp_selected_path_create_offset_object(1, false);
974 void sp_selected_path_create_inset()
976     sp_selected_path_create_offset_object(-1, false);
979 void sp_selected_path_create_updating_offset_object_zero()
981     sp_selected_path_create_offset_object(0, true);
984 void sp_selected_path_create_updating_offset()
986     sp_selected_path_create_offset_object(1, true);
988 void sp_selected_path_create_updating_inset()
990     sp_selected_path_create_offset_object(-1, true);
993 void
994 sp_selected_path_create_offset_object(int expand, bool updating)
996     Inkscape::Selection *selection;
997     Inkscape::XML::Node *repr;
998     SPItem *item;
999     SPCurve *curve;
1000     gchar *style, *str;
1001     SPDesktop *desktop;
1002     float o_width, o_miter;
1003     JoinType o_join;
1004     ButtType o_butt;
1006     curve = NULL;
1008     desktop = SP_ACTIVE_DESKTOP;
1010     selection = sp_desktop_selection(desktop);
1012     item = selection->singleItem();
1014     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1015         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1016         return;
1017     }
1018     if (SP_IS_SHAPE(item))
1019     {
1020         curve = sp_shape_get_curve(SP_SHAPE(item));
1021         if (curve == NULL)
1022             return;
1023     }
1024     if (SP_IS_TEXT(item))
1025     {
1026         curve = SP_TEXT(item)->getNormalizedBpath();
1027         if (curve == NULL)
1028             return;
1029     }
1031     NR::Matrix const transform(item->transform);
1033     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1035     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1037     // remember the position of the item
1038     gint pos = SP_OBJECT_REPR(item)->position();
1039     // remember parent
1040     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1042     {
1043         SPStyle *i_style = SP_OBJECT(item)->style;
1044         int jointype, captype;
1046         jointype = i_style->stroke_linejoin.value;
1047         captype = i_style->stroke_linecap.value;
1048         o_width = i_style->stroke_width.computed;
1049         if (jointype == SP_STROKE_LINEJOIN_MITER)
1050         {
1051             o_join = join_pointy;
1052         }
1053         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1054         {
1055             o_join = join_round;
1056         }
1057         else
1058         {
1059             o_join = join_straight;
1060         }
1061         if (captype == SP_STROKE_LINECAP_SQUARE)
1062         {
1063             o_butt = butt_square;
1064         }
1065         else if (captype == SP_STROKE_LINECAP_ROUND)
1066         {
1067             o_butt = butt_round;
1068         }
1069         else
1070         {
1071             o_butt = butt_straight;
1072         }
1074         {
1075             double prefOffset = 1.0;
1076             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1077             o_width = prefOffset;
1078         }
1080         if (o_width < 0.01)
1081             o_width = 0.01;
1082         o_miter = i_style->stroke_miterlimit.value * o_width;
1083     }
1085     Path *orig = Path_for_item(item, true, false);
1086     if (orig == NULL)
1087     {
1088         g_free(style);
1089         curve->unref();
1090         return;
1091     }
1093     Path *res = new Path;
1094     res->SetBackData(false);
1096     {
1097         Shape *theShape = new Shape;
1098         Shape *theRes = new Shape;
1100         orig->ConvertWithBackData(1.0);
1101         orig->Fill(theShape, 0);
1103         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1104         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1105         if (val && strcmp(val, "nonzero") == 0)
1106         {
1107             theRes->ConvertToShape(theShape, fill_nonZero);
1108         }
1109         else if (val && strcmp(val, "evenodd") == 0)
1110         {
1111             theRes->ConvertToShape(theShape, fill_oddEven);
1112         }
1113         else
1114         {
1115             theRes->ConvertToShape(theShape, fill_nonZero);
1116         }
1118         Path *originaux[1];
1119         originaux[0] = orig;
1120         theRes->ConvertToForme(res, 1, originaux);
1122         delete theShape;
1123         delete theRes;
1124     }
1126     curve->unref();
1128     if (res->descr_cmd.size() <= 1)
1129     {
1130         // pas vraiment de points sur le resultat
1131         // donc il ne reste rien
1132         sp_document_done(sp_desktop_document(desktop), 
1133                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1134                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1135                          (updating ? _("Create linked offset")
1136                           : _("Create dynamic offset")));
1137         selection->clear();
1139         delete res;
1140         delete orig;
1141         g_free(style);
1142         return;
1143     }
1145     {
1146         gchar tstr[80];
1148         tstr[79] = '\0';
1150         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1151         repr = xml_doc->createElement("svg:path");
1152         repr->setAttribute("sodipodi:type", "inkscape:offset");
1153         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1154                                                           ? o_width
1155                                                           : expand < 0
1156                                                           ? -o_width
1157                                                           : 0 ));
1159         str = res->svg_dump_path();
1160         repr->setAttribute("inkscape:original", str);
1161         g_free(str);
1163         if ( updating ) {
1164             char const *id = SP_OBJECT(item)->repr->attribute("id");
1165             char const *uri = g_strdup_printf("#%s", id);
1166             repr->setAttribute("xlink:href", uri);
1167             g_free((void *) uri);
1168         } else {
1169             repr->setAttribute("inkscape:href", NULL);
1170         }
1172         repr->setAttribute("style", style);
1174         // add the new repr to the parent
1175         parent->appendChild(repr);
1177         // move to the saved position
1178         repr->setPosition(pos > 0 ? pos : 0);
1180         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1182         if ( updating ) {
1183             // on conserve l'original
1184             // we reapply the transform to the original (offset will feel it)
1185             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1186         } else {
1187             // delete original, apply the transform to the offset
1188             SP_OBJECT(item)->deleteObject(false);
1189             sp_item_write_transform(nitem, repr, transform);
1190         }
1192         // The object just created from a temporary repr is only a seed.
1193         // We need to invoke its write which will update its real repr (in particular adding d=)
1194         SP_OBJECT(nitem)->updateRepr();
1196         Inkscape::GC::release(repr);
1198         selection->set(nitem);
1199     }
1201     sp_document_done(sp_desktop_document(desktop), 
1202                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1203                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1204                      (updating ? _("Create linked offset")
1205                       : _("Create dynamic offset")));
1207     delete res;
1208     delete orig;
1210     g_free(style);
1224 void
1225 sp_selected_path_do_offset(bool expand, double prefOffset)
1227     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1229     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1231     if (selection->isEmpty()) {
1232         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1233         return;
1234     }
1236     bool did = false;
1238     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1239          items != NULL;
1240          items = items->next) {
1242         SPItem *item = (SPItem *) items->data;
1244         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1245             continue;
1247         SPCurve *curve = NULL;
1248         if (SP_IS_SHAPE(item)) {
1249             curve = sp_shape_get_curve(SP_SHAPE(item));
1250             if (curve == NULL)
1251                 continue;
1252         }
1253         if (SP_IS_TEXT(item)) {
1254             curve = SP_TEXT(item)->getNormalizedBpath();
1255             if (curve == NULL)
1256                 continue;
1257         }
1259         NR::Matrix const transform(item->transform);
1261         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1263         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1265         float o_width, o_miter;
1266         JoinType o_join;
1267         ButtType o_butt;
1269         {
1270             SPStyle *i_style = SP_OBJECT(item)->style;
1271             int jointype, captype;
1273             jointype = i_style->stroke_linejoin.value;
1274             captype = i_style->stroke_linecap.value;
1275             o_width = i_style->stroke_width.computed;
1277             switch (jointype) {
1278                 case SP_STROKE_LINEJOIN_MITER:
1279                     o_join = join_pointy;
1280                     break;
1281                 case SP_STROKE_LINEJOIN_ROUND:
1282                     o_join = join_round;
1283                     break;
1284                 default:
1285                     o_join = join_straight;
1286                     break;
1287             }
1289             switch (captype) {
1290                 case SP_STROKE_LINECAP_SQUARE:
1291                     o_butt = butt_square;
1292                     break;
1293                 case SP_STROKE_LINECAP_ROUND:
1294                     o_butt = butt_round;
1295                     break;
1296                 default:
1297                     o_butt = butt_straight;
1298                     break;
1299             }
1301             o_width = prefOffset;
1303             if (o_width < 0.1)
1304                 o_width = 0.1;
1305             o_miter = i_style->stroke_miterlimit.value * o_width;
1306         }
1308         Path *orig = Path_for_item(item, false);
1309         if (orig == NULL) {
1310             g_free(style);
1311             curve->unref();
1312             continue;
1313         }
1315         Path *res = new Path;
1316         res->SetBackData(false);
1318         {
1319             Shape *theShape = new Shape;
1320             Shape *theRes = new Shape;
1322             orig->ConvertWithBackData(0.03);
1323             orig->Fill(theShape, 0);
1325             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1326             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1327             if (val && strcmp(val, "nonzero") == 0)
1328             {
1329                 theRes->ConvertToShape(theShape, fill_nonZero);
1330             }
1331             else if (val && strcmp(val, "evenodd") == 0)
1332             {
1333                 theRes->ConvertToShape(theShape, fill_oddEven);
1334             }
1335             else
1336             {
1337                 theRes->ConvertToShape(theShape, fill_nonZero);
1338             }
1340             // et maintenant: offset
1341             // methode inexacte
1342 /*                      Path *originaux[1];
1343                         originaux[0] = orig;
1344                         theRes->ConvertToForme(res, 1, originaux);
1346                         if (expand) {
1347                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1348                         } else {
1349                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1350                         }
1352                         orig->ConvertWithBackData(1.0);
1353                         orig->Fill(theShape, 0);
1354                         theRes->ConvertToShape(theShape, fill_positive);
1355                         originaux[0] = orig;
1356                         theRes->ConvertToForme(res, 1, originaux);
1358                         if (o_width >= 0.5) {
1359                         //     res->Coalesce(1.0);
1360                         res->ConvertEvenLines(1.0);
1361                         res->Simplify(1.0);
1362                         } else {
1363                         //      res->Coalesce(o_width);
1364                         res->ConvertEvenLines(1.0*o_width);
1365                         res->Simplify(1.0 * o_width);
1366                         }    */
1367             // methode par makeoffset
1369             if (expand)
1370             {
1371                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1372             }
1373             else
1374             {
1375                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1376             }
1377             theRes->ConvertToShape(theShape, fill_positive);
1379             res->Reset();
1380             theRes->ConvertToForme(res);
1382             if (o_width >= 1.0)
1383             {
1384                 res->ConvertEvenLines(1.0);
1385                 res->Simplify(1.0);
1386             }
1387             else
1388             {
1389                 res->ConvertEvenLines(1.0*o_width);
1390                 res->Simplify(1.0 * o_width);
1391             }
1393             delete theShape;
1394             delete theRes;
1395         }
1397         did = true;
1399         curve->unref();
1400         // remember the position of the item
1401         gint pos = SP_OBJECT_REPR(item)->position();
1402         // remember parent
1403         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1404         // remember id
1405         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1407         selection->remove(item);
1408         SP_OBJECT(item)->deleteObject(false);
1410         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1412             gchar tstr[80];
1414             tstr[79] = '\0';
1416             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1417             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1419             repr->setAttribute("style", style);
1421             gchar *str = res->svg_dump_path();
1422             repr->setAttribute("d", str);
1423             g_free(str);
1425             // add the new repr to the parent
1426             parent->appendChild(repr);
1428             // move to the saved position
1429             repr->setPosition(pos > 0 ? pos : 0);
1431             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1433             // reapply the transform
1434             sp_item_write_transform(newitem, repr, transform);
1436             repr->setAttribute("id", id);
1438             selection->add(repr);
1440             Inkscape::GC::release(repr);
1441         }
1443         delete orig;
1444         delete res;
1445     }
1447     if (did) {
1448         sp_document_done(sp_desktop_document(desktop), 
1449                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1450                          (expand ? _("Outset path") : _("Inset path")));
1451     } else {
1452         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1453         return;
1454     }
1458 static bool
1459 sp_selected_path_simplify_items(SPDesktop *desktop,
1460                                 Inkscape::Selection *selection, GSList *items,
1461                                 float threshold,  bool justCoalesce,
1462                                 float angleLimit, bool breakableAngles,
1463                                 bool modifySelection);
1466 //return true if we changed something, else false
1467 bool
1468 sp_selected_path_simplify_item(SPDesktop *desktop,
1469                  Inkscape::Selection *selection, SPItem *item,
1470                  float threshold,  bool justCoalesce,
1471                  float angleLimit, bool breakableAngles,
1472                  gdouble size,     bool modifySelection)
1474     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1475         return false;
1477     //If this is a group, do the children instead
1478     if (SP_IS_GROUP(item)) {
1479         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1480         
1481         return sp_selected_path_simplify_items(desktop, selection, items,
1482                                                threshold, justCoalesce,
1483                                                angleLimit, breakableAngles,
1484                                                false);
1485     }
1488     SPCurve *curve = NULL;
1490     if (SP_IS_SHAPE(item)) {
1491         curve = sp_shape_get_curve(SP_SHAPE(item));
1492         if (!curve)
1493             return false;
1494     }
1496     if (SP_IS_TEXT(item)) {
1497         curve = SP_TEXT(item)->getNormalizedBpath();
1498         if (!curve)
1499             return false;
1500     }
1502     // save the transform, to re-apply it after simplification
1503     NR::Matrix const transform(item->transform);
1505     /*
1506        reset the transform, effectively transforming the item by transform.inverse();
1507        this is necessary so that the item is transformed twice back and forth,
1508        allowing all compensations to cancel out regardless of the preferences
1509     */
1510     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1512     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1513     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1514     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1516     Path *orig = Path_for_item(item, false);
1517     if (orig == NULL) {
1518         g_free(style);
1519         curve->unref();
1520         return false;
1521     }
1523     curve->unref();
1524     // remember the position of the item
1525     gint pos = SP_OBJECT_REPR(item)->position();
1526     // remember parent
1527     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1528     // remember id
1529     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1530     // remember path effect
1531     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1533     //If a group was selected, to not change the selection list
1534     if (modifySelection)
1535         selection->remove(item);
1537     SP_OBJECT(item)->deleteObject(false);
1539     if ( justCoalesce ) {
1540         orig->Coalesce(threshold * size);
1541     } else {
1542         orig->ConvertEvenLines(threshold * size);
1543         orig->Simplify(threshold * size);
1544     }
1546     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1547     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1549     // restore style, mask and clip-path
1550     repr->setAttribute("style", style);
1551     g_free(style);
1553     if ( mask ) {
1554         repr->setAttribute("mask", mask);
1555         g_free(mask);
1556     }
1558     if ( clip_path ) {
1559         repr->setAttribute("clip-path", clip_path);
1560         g_free(clip_path);
1561     }
1563     // path
1564     gchar *str = orig->svg_dump_path();
1565     if (patheffect)
1566         repr->setAttribute("inkscape:original-d", str);
1567     else 
1568         repr->setAttribute("d", str);
1569     g_free(str);
1571     // restore id
1572     repr->setAttribute("id", id);
1574     // add the new repr to the parent
1575     parent->appendChild(repr);
1577     // move to the saved position
1578     repr->setPosition(pos > 0 ? pos : 0);
1580     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1582     // reapply the transform
1583     sp_item_write_transform(newitem, repr, transform);
1585     // restore path effect
1586     repr->setAttribute("inkscape:path-effect", patheffect);
1588     //If we are not in a selected group
1589     if (modifySelection)
1590         selection->add(repr);
1592     Inkscape::GC::release(repr);
1594     // clean up
1595     if (orig) delete orig;
1597     return true;
1601 bool
1602 sp_selected_path_simplify_items(SPDesktop *desktop,
1603                                 Inkscape::Selection *selection, GSList *items,
1604                                 float threshold,  bool justCoalesce,
1605                                 float angleLimit, bool breakableAngles,
1606                                 bool modifySelection)
1608   bool simplifyIndividualPaths =
1609     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1610   
1611   gchar *simplificationType;
1612   if (simplifyIndividualPaths) {
1613       simplificationType = _("Simplifying paths (separately):");
1614   } else {
1615       simplificationType = _("Simplifying paths:");
1616   }
1618   bool didSomething = false;
1620   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1621   if (!selectionBbox) {
1622     return false;
1623   }
1624   gdouble selectionSize  = L2(selectionBbox->dimensions());
1626   gdouble simplifySize  = selectionSize;
1627   
1628   int pathsSimplified = 0;
1629   int totalPathCount  = g_slist_length(items);
1630   
1631   // set "busy" cursor
1632   desktop->setWaitingCursor();
1633   
1634   for (; items != NULL; items = items->next) {
1635       SPItem *item = (SPItem *) items->data;
1636       
1637       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1638           continue;
1640       if (simplifyIndividualPaths) {
1641           NR::Maybe<NR::Rect> itemBbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
1642           if (itemBbox) {
1643               simplifySize      = L2(itemBbox->dimensions());
1644           } else {
1645               simplifySize      = 0;
1646           }
1647       }
1649       pathsSimplified++;
1651       if (pathsSimplified % 20 == 0) {
1652         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1653         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1654       }
1656       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1657                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1658   }
1660   desktop->clearWaitingCursor();
1662   if (pathsSimplified > 20) {
1663     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1664   }
1665   
1666   return didSomething;
1669 void
1670 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1671                        float angleLimit, bool breakableAngles)
1673     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1675     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1677     if (selection->isEmpty()) {
1678         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1679                          _("Select <b>path(s)</b> to simplify."));
1680         return;
1681     }
1683     GSList *items = g_slist_copy((GSList *) selection->itemList());
1685     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1686                                                         items, threshold,
1687                                                         justCoalesce,
1688                                                         angleLimit,
1689                                                         breakableAngles, true);
1691     if (didSomething)
1692         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1693                          _("Simplify"));
1694     else
1695         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1700 // globals for keeping track of accelerated simplify
1701 static double previousTime      = 0.0;
1702 static gdouble simplifyMultiply = 1.0;
1704 void
1705 sp_selected_path_simplify(void)
1707     gdouble simplifyThreshold =
1708         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1709     bool simplifyJustCoalesce =
1710         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1712     //Get the current time
1713     GTimeVal currentTimeVal;
1714     g_get_current_time(&currentTimeVal);
1715     double currentTime = currentTimeVal.tv_sec * 1000000 +
1716                 currentTimeVal.tv_usec;
1718     //Was the previous call to this function recent? (<0.5 sec)
1719     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1721         // add to the threshold 1/2 of its original value
1722         simplifyMultiply  += 0.5;
1723         simplifyThreshold *= simplifyMultiply;
1725     } else {
1726         // reset to the default
1727         simplifyMultiply = 1;
1728     }
1730     //remember time for next call
1731     previousTime = currentTime;
1733     //g_print("%g\n", simplify_threshold);
1735     //Make the actual call
1736     sp_selected_path_simplify_selection(simplifyThreshold,
1737                       simplifyJustCoalesce, 0.0, false);
1742 // fonctions utilitaires
1744 bool
1745 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1747     if (who == NULL || a == NULL)
1748         return false;
1749     if (who == a)
1750         return true;
1751     return Ancetre(sp_repr_parent(a), who);
1754 Path *
1755 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1757     SPCurve *curve = curve_for_item(item);
1758     if (curve == NULL) {
1759         return NULL;
1760     }
1762     Geom::PathVector pathv = pathvector_for_curve(item, curve, doTransformation, transformFull);
1764     Path *dest = new Path;
1765     dest->LoadPathVector(pathv);
1767     curve->unref();
1768     
1769     return dest;
1772 /* 
1773  * This function always returns a new NArtBpath, the caller must g_free the returned path!
1774 */
1775 NArtBpath *
1776 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1778     if (curve == NULL)
1779         return NULL;
1781     NArtBpath *bpath = BPath_from_2GeomPath(curve->get_pathvector());
1782     if (bpath == NULL) {
1783         return NULL;
1784     }
1786     NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1787     if (doTransformation) {
1788         if (transformFull) {
1789             new_bpath = nr_artpath_affine(bpath, from_2geom(sp_item_i2doc_affine(item)));
1790         } else {
1791             new_bpath = nr_artpath_affine(bpath, item->transform);
1792         }
1793     } else {
1794         new_bpath = nr_artpath_affine(bpath, NR::identity());
1795     }
1797     g_free(bpath);
1798     return new_bpath;
1801 /* 
1802  * NOTE: Returns empty pathvector if curve == NULL
1803  * TODO: see if calling this method can be optimized. All the pathvector copying might be slow.
1804  */
1805 Geom::PathVector
1806 pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1808     if (curve == NULL)
1809         return Geom::PathVector();
1811     if (doTransformation) {
1812         if (transformFull) {
1813             return (curve->get_pathvector()) * sp_item_i2doc_affine(item);
1814         } else {
1815             return (curve->get_pathvector()) * to_2geom(item->transform);
1816         }
1817     } else {
1818         return curve->get_pathvector();
1819     }
1822 SPCurve* curve_for_item(SPItem *item)
1824     if (!item)
1825         return NULL;
1827     SPCurve *curve = NULL;
1829     if (SP_IS_SHAPE(item)) {
1830         if (SP_IS_PATH(item)) {
1831             curve = sp_path_get_curve_for_edit(SP_PATH(item));
1832         } else {
1833             curve = sp_shape_get_curve(SP_SHAPE(item));
1834         }
1835     }
1836     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1837     {
1838         curve = te_get_layout(item)->convertToCurves();
1839     }
1840     else if (SP_IS_IMAGE(item))
1841     {
1842         curve = sp_image_get_curve(SP_IMAGE(item));
1843     }
1844     
1845     return curve; // do not forget to unref the curve at some point!
1848 Path *bpath_to_Path(NArtBpath const *bpath) {
1849     Path *dest = new Path;
1850     dest->SetBackData(false);
1851     {
1852         int   i;
1853         bool  closed = false;
1854         float lastX  = 0.0;
1855         float lastY  = 0.0;
1857         for (i = 0; bpath[i].code != NR_END; i++) {
1858             switch (bpath[i].code) {
1859                 case NR_LINETO:
1860                     lastX = bpath[i].x3;
1861                     lastY = bpath[i].y3;
1862                     {
1863                         NR::Point tmp(lastX, lastY);
1864                         dest->LineTo(tmp);
1865                     }
1866                     break;
1868                 case NR_CURVETO:
1869                 {
1870                     NR::Point tmp, tms, tme;
1871                     tmp[0]=bpath[i].x3;
1872                     tmp[1]=bpath[i].y3;
1873                     tms[0]=3 * (bpath[i].x1 - lastX);
1874                     tms[1]=3 * (bpath[i].y1 - lastY);
1875                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1876                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1877                     dest->CubicTo(tmp,tms,tme);
1878                 }
1879                 lastX = bpath[i].x3;
1880                 lastY = bpath[i].y3;
1881                 break;
1883                 case NR_MOVETO_OPEN:
1884                 case NR_MOVETO:
1885                     if (closed)
1886                         dest->Close();
1887                     closed = (bpath[i].code == NR_MOVETO);
1888                     lastX = bpath[i].x3;
1889                     lastY = bpath[i].y3;
1890                     {
1891                         NR::Point  tmp(lastX, lastY);
1892                         dest->MoveTo(tmp);
1893                     }
1894                     break;
1895                 default:
1896                     break;
1897             }
1898         }
1899         if (closed)
1900             dest->Close();
1901     }
1902     return dest;
1905 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1907     //get nearest position on path
1908     Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1909     return pos;
1912 NR::Point get_point_on_Path(Path *path, int piece, double t)
1914     NR::Point p;
1915     path->PointAt(piece, t, p);
1916     return p;
1920 /*
1921   Local Variables:
1922   mode:c++
1923   c-file-style:"stroustrup"
1924   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1925   indent-tabs-mode:nil
1926   fill-column:99
1927   End:
1928 */
1929 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :