Code

convert item to livarot path using 2geom path
[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>
57 #include "livarot/Path.h"
58 #include "livarot/Shape.h"
60 #include "splivarot.h"
62 bool   Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
64 void sp_selected_path_boolop(bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
65 void sp_selected_path_do_offset(bool expand, double prefOffset);
66 void sp_selected_path_create_offset_object(int expand, bool updating);
68 void
69 sp_selected_path_union()
70 {
71     sp_selected_path_boolop(bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
72 }
74 void
75 sp_selected_path_union_skip_undo()
76 {
77     sp_selected_path_boolop(bool_op_union, SP_VERB_NONE, _("Union"));
78 }
80 void
81 sp_selected_path_intersect()
82 {
83     sp_selected_path_boolop(bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
84 }
86 void
87 sp_selected_path_diff()
88 {
89     sp_selected_path_boolop(bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
90 }
92 void
93 sp_selected_path_diff_skip_undo()
94 {
95     sp_selected_path_boolop(bool_op_diff, SP_VERB_NONE, _("Difference"));
96 }
98 void
99 sp_selected_path_symdiff()
101     sp_selected_path_boolop(bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
103 void
104 sp_selected_path_cut()
106     sp_selected_path_boolop(bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
108 void
109 sp_selected_path_slice()
111     sp_selected_path_boolop(bool_op_slice, SP_VERB_SELECTION_SLICE,  _("Cut path"));
115 // boolean operations
116 // take the source paths from the file, do the operation, delete the originals and add the results
117 void
118 sp_selected_path_boolop(bool_op bop, const unsigned int verb, const Glib::ustring description)
120     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
122     Inkscape::Selection *selection = sp_desktop_selection(desktop);
123     
124     GSList *il = (GSList *) selection->itemList();
125     
126     // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
127     if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
128         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
129         return;
130     }
131     else if ( g_slist_length(il) < 1 ) {
132         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
133         return;
134     }
136     if (g_slist_length(il) > 2) {
137         if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
138             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
139             return;
140         }
141     }
143     // reverseOrderForOp marks whether the order of the list is the top->down order
144     // it's only used when there are 2 objects, and for operations who need to know the
145     // topmost object (differences, cuts)
146     bool reverseOrderForOp = false;
148     // mettre les elements de la liste dans l'ordre pour ces operations
149     if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
150         // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
151         Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
152         Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
154         if (a == NULL || b == NULL) {
155             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Unable to determine the <b>z-order</b> of the objects selected for difference, XOR, division, or path cut."));
156             return;
157         }
159         if (Ancetre(a, b)) {
160             // a is the parent of b, already in the proper order
161         } else if (Ancetre(b, a)) {
162             // reverse order
163             reverseOrderForOp = true;
164         } else {
166             // objects are not in parent/child relationship;
167             // find their lowest common ancestor
168             Inkscape::XML::Node *dad = LCA(a, b);
169             if (dad == NULL) {
170                 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Unable to determine the <b>z-order</b> of the objects selected for difference, XOR, division, or path cut."));
171                 return;
172             }
174             // find the children of the LCA that lead from it to the a and b
175             Inkscape::XML::Node *as = AncetreFils(a, dad);
176             Inkscape::XML::Node *bs = AncetreFils(b, dad);
178             // find out which comes first
179             for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
180                 if (child == as) {
181                     /* a first, so reverse. */
182                     reverseOrderForOp = true;
183                     break;
184                 }
185                 if (child == bs)
186                     break;
187             }
188         }
189     }
191     il = g_slist_copy(il);
193     // first check if all the input objects have shapes
194     // otherwise bail out
195     for (GSList *l = il; l != NULL; l = l->next)
196     {
197         SPItem *item = SP_ITEM(l->data);
198         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
199         {
200             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
201             g_slist_free(il);
202             return;
203         }
204     }
206     // extract the livarot Paths from the source objects
207     // also get the winding rule specified in the style
208     int nbOriginaux = g_slist_length(il);
209     std::vector<Path *> originaux(nbOriginaux);
210     std::vector<FillRule> origWind(nbOriginaux);
211     int curOrig;
212     {
213         curOrig = 0;
214         for (GSList *l = il; l != NULL; l = l->next)
215         {
216             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
217             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
218             if (val && strcmp(val, "nonzero") == 0) {
219                 origWind[curOrig]= fill_nonZero;
220             } else if (val && strcmp(val, "evenodd") == 0) {
221                 origWind[curOrig]= fill_oddEven;
222             } else {
223                 origWind[curOrig]= fill_nonZero;
224             }
226             originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
227             if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
228             {
229                 for (int i = curOrig; i >= 0; i--) delete originaux[i];
230                 g_slist_free(il);
231                 return;
232             }
233             curOrig++;
234         }
235     }
236     // reverse if needed
237     // note that the selection list keeps its order
238     if ( reverseOrderForOp ) {
239         Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
240         FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
241     }
243     // and work
244     // some temporary instances, first
245     Shape *theShapeA = new Shape;
246     Shape *theShapeB = new Shape;
247     Shape *theShape = new Shape;
248     Path *res = new Path;
249     res->SetBackData(false);
250     Path::cut_position  *toCut=NULL;
251     int                  nbToCut=0;
253     if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
254         // true boolean op
255         // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
256         originaux[0]->ConvertWithBackData(0.1);
258         originaux[0]->Fill(theShape, 0);
260         theShapeA->ConvertToShape(theShape, origWind[0]);
262         curOrig = 1;
263         for (GSList *l = il->next; l != NULL; l = l->next) {
264             originaux[curOrig]->ConvertWithBackData(0.1);
266             originaux[curOrig]->Fill(theShape, curOrig);
268             theShapeB->ConvertToShape(theShape, origWind[curOrig]);
270             // les elements arrivent en ordre inverse dans la liste
271             theShape->Booleen(theShapeB, theShapeA, bop);
273             {
274                 Shape *swap = theShape;
275                 theShape = theShapeA;
276                 theShapeA = swap;
277             }
278             curOrig++;
279         }
281         {
282             Shape *swap = theShape;
283             theShape = theShapeA;
284             theShapeA = swap;
285         }
287     } else if ( bop == bool_op_cut ) {
288         // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
289         // technically, the cut path is not necessarily a polygon (thus has no winding rule)
290         // it is just uncrossed, and cleaned from duplicate edges and points
291         // then it's fed to Booleen() which will uncross it against the other path
292         // then comes the trick: each edge of the cut path is duplicated (one in each direction),
293         // thus making a polygon. the weight of the edges of the cut are all 0, but
294         // the Booleen need to invert the ones inside the source polygon (for the subsequent
295         // ConvertToForme)
297         // the cut path needs to have the highest pathID in the back data
298         // that's how the Booleen() function knows it's an edge of the cut
300         // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
301         // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
302         // left it at 1.0. Investigate replacing this by a combination of difference and
303         // intersection of the same two paths. -- bb
304         {
305             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
306             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
307         }
308         originaux[0]->ConvertWithBackData(1.0);
310         originaux[0]->Fill(theShape, 0);
312         theShapeA->ConvertToShape(theShape, origWind[0]);
314         originaux[1]->ConvertWithBackData(1.0);
316         originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
318         theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
320         // les elements arrivent en ordre inverse dans la liste
321         theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
323     } else if ( bop == bool_op_slice ) {
324         // slice is not really a boolean operation
325         // you just put the 2 shapes in a single polygon, uncross it
326         // the points where the degree is > 2 are intersections
327         // just check it's an intersection on the path you want to cut, and keep it
328         // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
329         // make new subpath at each one of these positions
330         // inversion pour l'op\8eration
331         {
332             Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
333             int   swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
334         }
335         originaux[0]->ConvertWithBackData(1.0);
337         originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
339         originaux[1]->ConvertWithBackData(1.0);
341         originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
343         theShape->ConvertToShape(theShapeA, fill_justDont);
345         if ( theShape->hasBackData() ) {
346             // should always be the case, but ya never know
347             {
348                 for (int i = 0; i < theShape->numberOfPoints(); i++) {
349                     if ( theShape->getPoint(i).totalDegree() > 2 ) {
350                         // possibly an intersection
351                         // we need to check that at least one edge from the source path is incident to it
352                         // before we declare it's an intersection
353                         int cb = theShape->getPoint(i).incidentEdge[FIRST];
354                         int   nbOrig=0;
355                         int   nbOther=0;
356                         int   piece=-1;
357                         float t=0.0;
358                         while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
359                             if ( theShape->ebData[cb].pathID == 0 ) {
360                                 // the source has an edge incident to the point, get its position on the path
361                                 piece=theShape->ebData[cb].pieceID;
362                                 if ( theShape->getEdge(cb).st == i ) {
363                                     t=theShape->ebData[cb].tSt;
364                                 } else {
365                                     t=theShape->ebData[cb].tEn;
366                                 }
367                                 nbOrig++;
368                             }
369                             if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
370                             cb=theShape->NextAt(i, cb);
371                         }
372                         if ( nbOrig > 0 && nbOther > 0 ) {
373                             // point incident to both path and cut: an intersection
374                             // note that you only keep one position on the source; you could have degenerate
375                             // cases where the source crosses itself at this point, and you wouyld miss an intersection
376                             toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
377                             toCut[nbToCut].piece=piece;
378                             toCut[nbToCut].t=t;
379                             nbToCut++;
380                         }
381                     }
382                 }
383             }
384             {
385                 // i think it's useless now
386                 int i = theShape->numberOfEdges() - 1;
387                 for (;i>=0;i--) {
388                     if ( theShape->ebData[i].pathID == 1 ) {
389                         theShape->SubEdge(i);
390                     }
391                 }
392             }
394         }
395     }
397     int*    nesting=NULL;
398     int*    conts=NULL;
399     int     nbNest=0;
400     // pour compenser le swap juste avant
401     if ( bop == bool_op_slice ) {
402 //    theShape->ConvertToForme(res, nbOriginaux, originaux, true);
403 //    res->ConvertForcedToMoveTo();
404         res->Copy(originaux[0]);
405         res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
406         free(toCut);
407     } else if ( bop == bool_op_cut ) {
408         // il faut appeler pour desallouer PointData (pas vital, mais bon)
409         // the Booleen() function did not deallocated the point_data array in theShape, because this
410         // function needs it.
411         // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
412         // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
413         theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
414     } else {
415         theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
416     }
418     delete theShape;
419     delete theShapeA;
420     delete theShapeB;
421     for (int i = 0; i < nbOriginaux; i++)  delete originaux[i];
423     if (res->descr_cmd.size() <= 1)
424     {
425         // only one command, presumably a moveto: it isn't a path
426         for (GSList *l = il; l != NULL; l = l->next)
427         {
428             SP_OBJECT(l->data)->deleteObject();
429         }
430         sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE, 
431                          description);
432         selection->clear();
434         delete res;
435         g_slist_free(il);
436         return;
437     }
439     // get the source path object
440     SPObject *source;
441     if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
442         if (reverseOrderForOp) {
443              source = SP_OBJECT(il->data);
444         } else {
445              source = SP_OBJECT(il->next->data);
446         }
447     } else {
448         // find out the bottom object
449         GSList *sorted = g_slist_copy((GSList *) selection->reprList());
451         sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
453         source = sp_desktop_document(desktop)->
454             getObjectByRepr((Inkscape::XML::Node *)sorted->data);
456         g_slist_free(sorted);
457     }
459     // adjust style properties that depend on a possible transform in the source object in order
460     // to get a correct style attribute for the new path
461     SPItem* item_source = SP_ITEM(source);
462     NR::Matrix i2root = from_2geom(sp_item_i2root_affine(item_source));
463     sp_item_adjust_stroke(item_source, NR::expansion(i2root));
464     sp_item_adjust_pattern(item_source, i2root);
465     sp_item_adjust_gradient(item_source, i2root);
466     sp_item_adjust_livepatheffect(item_source, i2root);
468     Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
470     // remember important aspects of the source path, to be restored
471     gint pos = repr_source->position();
472     Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
473     gchar const *id = repr_source->attribute("id");
474     gchar const *style = repr_source->attribute("style");
475     gchar const *mask = repr_source->attribute("mask");
476     gchar const *clip_path = repr_source->attribute("clip-path");
478     // remove source paths
479     selection->clear();
480     for (GSList *l = il; l != NULL; l = l->next) {
481         // if this is the bottommost object,
482         if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
483             // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
484             SP_OBJECT(l->data)->deleteObject(false);
485         } else {
486             // delete the object for real, so that its clones can take appropriate action
487             SP_OBJECT(l->data)->deleteObject();
488         }
489     }
490     g_slist_free(il);
492     // premultiply by the inverse of parent's repr
493     SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
494     NR::Matrix local = from_2geom(sp_item_i2doc_affine(parent_item));
495     gchar *transform = sp_svg_transform_write(local.inverse());
497     // now that we have the result, add it on the canvas
498     if ( bop == bool_op_cut || bop == bool_op_slice ) {
499         int    nbRP=0;
500         Path** resPath;
501         if ( bop == bool_op_slice ) {
502             // there are moveto's at each intersection, but it's still one unique path
503             // so break it down and add each subpath independently
504             // we could call break_apart to do this, but while we have the description...
505             resPath=res->SubPaths(nbRP, false);
506         } else {
507             // cut operation is a bit wicked: you need to keep holes
508             // that's why you needed the nesting
509             // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
510             // to get the path for each part of the polygon. that's why you need the nesting info:
511             // to know in wich subpath to add a subpath
512             resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
514             // cleaning
515             if ( conts ) free(conts);
516             if ( nesting ) free(nesting);
517         }
519         // add all the pieces resulting from cut or slice
520         for (int i=0;i<nbRP;i++) {
521             gchar *d = resPath[i]->svg_dump_path();
523             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
524             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
525             repr->setAttribute("style", style);
526             if (mask)
527                 repr->setAttribute("mask", mask);
528             if (clip_path)
529                 repr->setAttribute("clip-path", clip_path);
531             repr->setAttribute("d", d);
532             g_free(d);
534             // for slice, remove fill
535             if (bop == bool_op_slice) {
536                 SPCSSAttr *css;
538                 css = sp_repr_css_attr_new();
539                 sp_repr_css_set_property(css, "fill", "none");
541                 sp_repr_css_change(repr, css, "style");
543                 sp_repr_css_attr_unref(css);
544             }
546             // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
547             // this means it's basically random which of the pieces inherits the original's id and clones
548             // a better algorithm might figure out e.g. the biggest piece
549             repr->setAttribute("id", id);
551             repr->setAttribute("transform", transform);
553             // add the new repr to the parent
554             parent->appendChild(repr);
556             // move to the saved position
557             repr->setPosition(pos > 0 ? pos : 0);
559             selection->add(repr);
560             Inkscape::GC::release(repr);
562             delete resPath[i];
563         }
564         if ( resPath ) free(resPath);
566     } else {
567         gchar *d = res->svg_dump_path();
569         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
570         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
571         repr->setAttribute("style", style);
573         if ( mask )
574             repr->setAttribute("mask", mask);
576         if ( clip_path )
577             repr->setAttribute("clip-path", clip_path);
579         repr->setAttribute("d", d);
580         g_free(d);
582         repr->setAttribute("transform", transform);
584         repr->setAttribute("id", id);
585         parent->appendChild(repr);
586         repr->setPosition(pos > 0 ? pos : 0);
588         selection->add(repr);
589         Inkscape::GC::release(repr);
590     }
592     g_free(transform);
594     if (verb != SP_VERB_NONE) {
595         sp_document_done(sp_desktop_document(desktop), verb, description);
596     }
598     delete res;
601 static
602 void sp_selected_path_outline_add_marker( SPObject *marker_object, Geom::Matrix marker_transform, NR::scale stroke_scale, NR::Matrix transform,
603                                        Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument * doc )
605     SPMarker* marker = SP_MARKER (marker_object);
606     SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker_object));
608     NR::Matrix tr(from_2geom(marker_transform));
610     if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
611         tr = stroke_scale * tr;
612     }
614     // total marker transform
615     tr = marker_item->transform * marker->c2p * tr * transform;
617     if (SP_OBJECT_REPR(marker_item)) {
618         Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
619         g_repr->appendChild(m_repr);
620         SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr);
621         sp_item_write_transform(marker_item, m_repr, tr);
622     }
625 void
626 sp_selected_path_outline()
628     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
630     Inkscape::Selection *selection = sp_desktop_selection(desktop);
632     if (selection->isEmpty()) {
633         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>stroked path(s)</b> to convert stroke to path."));
634         return;
635     }
637     bool did = false;
639     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
640          items != NULL;
641          items = items->next) {
643         SPItem *item = (SPItem *) items->data;
645         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
646             continue;
648         SPCurve *curve = NULL;
649         if (SP_IS_SHAPE(item)) {
650             curve = sp_shape_get_curve(SP_SHAPE(item));
651             if (curve == NULL)
652                 continue;
653         }
654         if (SP_IS_TEXT(item)) {
655             curve = SP_TEXT(item)->getNormalizedBpath();
656             if (curve == NULL)
657                 continue;
658         }
660         {   // pas de stroke pas de chocolat
661             SPCSSAttr *css = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
662             gchar const *val = sp_repr_css_property(css, "stroke", NULL);
664             if (val == NULL || strcmp(val, "none") == 0) {
665                 curve->unref();
666                 continue;
667             }
668         }
670         // remember old stroke style, to be set on fill
671         SPCSSAttr *ncss;
672         {
673             SPCSSAttr *ocss = sp_repr_css_attr_inherited(SP_OBJECT_REPR(item), "style");
674             gchar const *val = sp_repr_css_property(ocss, "stroke", NULL);
675             gchar const *opac = sp_repr_css_property(ocss, "stroke-opacity", NULL);
677             ncss = sp_repr_css_attr_new();
679             sp_repr_css_set_property(ncss, "stroke", "none");
680             sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
681             sp_repr_css_set_property(ncss, "fill", val);
682             if ( opac ) {
683                 sp_repr_css_set_property(ncss, "fill-opacity", opac);
684             } else {
685                 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
686             }
687             sp_repr_css_unset_property(ncss, "marker-start");
688             sp_repr_css_unset_property(ncss, "marker-mid");
689             sp_repr_css_unset_property(ncss, "marker-end");
690         }
692         NR::Matrix const transform(item->transform);
693         float const scale = NR::expansion(transform);
694         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
695         SPStyle *i_style = SP_OBJECT(item)->style;
696         gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
697         gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
699         float o_width, o_miter;
700         JoinType o_join;
701         ButtType o_butt;
703         {
704             int jointype, captype;
706             jointype = i_style->stroke_linejoin.computed;
707             captype = i_style->stroke_linecap.computed;
708             o_width = i_style->stroke_width.computed;
710             switch (jointype) {
711                 case SP_STROKE_LINEJOIN_MITER:
712                     o_join = join_pointy;
713                     break;
714                 case SP_STROKE_LINEJOIN_ROUND:
715                     o_join = join_round;
716                     break;
717                 default:
718                     o_join = join_straight;
719                     break;
720             }
722             switch (captype) {
723                 case SP_STROKE_LINECAP_SQUARE:
724                     o_butt = butt_square;
725                     break;
726                 case SP_STROKE_LINECAP_ROUND:
727                     o_butt = butt_round;
728                     break;
729                 default:
730                     o_butt = butt_straight;
731                     break;
732             }
734             if (o_width < 0.1)
735                 o_width = 0.1;
736             o_miter = i_style->stroke_miterlimit.value * o_width;
737         }
739         Path *orig = Path_for_item(item, false);
740         if (orig == NULL) {
741             g_free(style);
742             curve->unref();
743             continue;
744         }
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             g_free(style);
801             continue;
802         }
804         did = true;
806         // remember the position of the item
807         gint pos = SP_OBJECT_REPR(item)->position();
808         // remember parent
809         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
810         // remember id
811         char const *id = SP_OBJECT_REPR(item)->attribute("id");
813         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
815             SPDocument * doc = sp_desktop_document(desktop);
816             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
817             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
819             // restore old style
820             repr->setAttribute("style", style);
822             // set old stroke style on fill
823             sp_repr_css_change(repr, ncss, "style");
825             sp_repr_css_attr_unref(ncss);
827             gchar *str = orig->svg_dump_path();
828             repr->setAttribute("d", str);
829             g_free(str);
831             if (mask)
832                 repr->setAttribute("mask", mask);
833             if (clip_path)
834                 repr->setAttribute("clip-path", clip_path);
836             if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
838                 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
839                 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
841                 // add the group to the parent
842                 parent->appendChild(g_repr);
843                 // move to the saved position
844                 g_repr->setPosition(pos > 0 ? pos : 0);
846                 g_repr->appendChild(repr);
847                 repr->setAttribute("id", id);
848                 SPItem *newitem = (SPItem *) doc->getObjectByRepr(repr);
849                 sp_item_write_transform(newitem, repr, transform);
851                 SPShape *shape = SP_SHAPE(item);
853                 Geom::PathVector const & pathv = curve->get_pathvector();
854                 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
855                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_START] ) {
856                         Geom::Matrix const m (sp_shape_marker_get_transform_at_start(path_it->front()));
857                         sp_selected_path_outline_add_marker( marker_obj, m,
858                                                              NR::scale(i_style->stroke_width.computed), transform,
859                                                              g_repr, xml_doc, doc );
860                     }
862                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_MID] ) {
863                         Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
864                         Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
865                         while (curve_it2 != path_it->end_default())
866                         {
867                             /* Put marker between curve_it1 and curve_it2.
868                              * Loop to end_default (so including closing segment), because when a path is closed,
869                              * there should be a midpoint marker between last segment and closing straight line segment
870                              */
871                             Geom::Matrix const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2));
872                             sp_selected_path_outline_add_marker( marker_obj, m,
873                                                                  NR::scale(i_style->stroke_width.computed), transform,
874                                                                  g_repr, xml_doc, doc );
876                             ++curve_it1;
877                             ++curve_it2;
878                         }
879                     }
881                     if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_END] ) {
882                         Geom::Matrix const m (sp_shape_marker_get_transform_at_end(path_it->back_default()));
883                         sp_selected_path_outline_add_marker( marker_obj, m,
884                                                              NR::scale(i_style->stroke_width.computed), transform,
885                                                              g_repr, xml_doc, doc );
886                     }
887                 }
889                 selection->add(g_repr);
891                 Inkscape::GC::release(g_repr);
894             } else {
896                 // add the new repr to the parent
897                 parent->appendChild(repr);
899                 // move to the saved position
900                 repr->setPosition(pos > 0 ? pos : 0);
902                 repr->setAttribute("id", id);
904                 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
905                 sp_item_write_transform(newitem, repr, transform);
907                 selection->add(repr);
909             }
911             Inkscape::GC::release(repr);
913             curve->unref();
914             selection->remove(item);
915             SP_OBJECT(item)->deleteObject(false);
917         }
919         delete res;
920         delete orig;
921         g_free(style);
923     }
925     if (did) {
926         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE, 
927                          _("Convert stroke to path"));
928     } else {
929         // TRANSLATORS: "to outline" means "to convert stroke to path"
930         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
931         return;
932     }
936 void
937 sp_selected_path_offset()
939     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
941     sp_selected_path_do_offset(true, prefOffset);
943 void
944 sp_selected_path_inset()
946     double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
948     sp_selected_path_do_offset(false, prefOffset);
951 void
952 sp_selected_path_offset_screen(double pixels)
954     sp_selected_path_do_offset(true,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
957 void
958 sp_selected_path_inset_screen(double pixels)
960     sp_selected_path_do_offset(false,  pixels / SP_ACTIVE_DESKTOP->current_zoom());
964 void sp_selected_path_create_offset_object_zero()
966     sp_selected_path_create_offset_object(0, false);
969 void sp_selected_path_create_offset()
971     sp_selected_path_create_offset_object(1, false);
973 void sp_selected_path_create_inset()
975     sp_selected_path_create_offset_object(-1, false);
978 void sp_selected_path_create_updating_offset_object_zero()
980     sp_selected_path_create_offset_object(0, true);
983 void sp_selected_path_create_updating_offset()
985     sp_selected_path_create_offset_object(1, true);
987 void sp_selected_path_create_updating_inset()
989     sp_selected_path_create_offset_object(-1, true);
992 void
993 sp_selected_path_create_offset_object(int expand, bool updating)
995     Inkscape::Selection *selection;
996     Inkscape::XML::Node *repr;
997     SPItem *item;
998     SPCurve *curve;
999     gchar *style, *str;
1000     SPDesktop *desktop;
1001     float o_width, o_miter;
1002     JoinType o_join;
1003     ButtType o_butt;
1005     curve = NULL;
1007     desktop = SP_ACTIVE_DESKTOP;
1009     selection = sp_desktop_selection(desktop);
1011     item = selection->singleItem();
1013     if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1014         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1015         return;
1016     }
1017     if (SP_IS_SHAPE(item))
1018     {
1019         curve = sp_shape_get_curve(SP_SHAPE(item));
1020         if (curve == NULL)
1021             return;
1022     }
1023     if (SP_IS_TEXT(item))
1024     {
1025         curve = SP_TEXT(item)->getNormalizedBpath();
1026         if (curve == NULL)
1027             return;
1028     }
1030     NR::Matrix const transform(item->transform);
1032     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1034     style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1036     // remember the position of the item
1037     gint pos = SP_OBJECT_REPR(item)->position();
1038     // remember parent
1039     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1041     {
1042         SPStyle *i_style = SP_OBJECT(item)->style;
1043         int jointype, captype;
1045         jointype = i_style->stroke_linejoin.value;
1046         captype = i_style->stroke_linecap.value;
1047         o_width = i_style->stroke_width.computed;
1048         if (jointype == SP_STROKE_LINEJOIN_MITER)
1049         {
1050             o_join = join_pointy;
1051         }
1052         else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1053         {
1054             o_join = join_round;
1055         }
1056         else
1057         {
1058             o_join = join_straight;
1059         }
1060         if (captype == SP_STROKE_LINECAP_SQUARE)
1061         {
1062             o_butt = butt_square;
1063         }
1064         else if (captype == SP_STROKE_LINECAP_ROUND)
1065         {
1066             o_butt = butt_round;
1067         }
1068         else
1069         {
1070             o_butt = butt_straight;
1071         }
1073         {
1074             double prefOffset = 1.0;
1075             prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1076             o_width = prefOffset;
1077         }
1079         if (o_width < 0.01)
1080             o_width = 0.01;
1081         o_miter = i_style->stroke_miterlimit.value * o_width;
1082     }
1084     Path *orig = Path_for_item(item, true, false);
1085     if (orig == NULL)
1086     {
1087         g_free(style);
1088         curve->unref();
1089         return;
1090     }
1092     Path *res = new Path;
1093     res->SetBackData(false);
1095     {
1096         Shape *theShape = new Shape;
1097         Shape *theRes = new Shape;
1099         orig->ConvertWithBackData(1.0);
1100         orig->Fill(theShape, 0);
1102         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1103         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1104         if (val && strcmp(val, "nonzero") == 0)
1105         {
1106             theRes->ConvertToShape(theShape, fill_nonZero);
1107         }
1108         else if (val && strcmp(val, "evenodd") == 0)
1109         {
1110             theRes->ConvertToShape(theShape, fill_oddEven);
1111         }
1112         else
1113         {
1114             theRes->ConvertToShape(theShape, fill_nonZero);
1115         }
1117         Path *originaux[1];
1118         originaux[0] = orig;
1119         theRes->ConvertToForme(res, 1, originaux);
1121         delete theShape;
1122         delete theRes;
1123     }
1125     curve->unref();
1127     if (res->descr_cmd.size() <= 1)
1128     {
1129         // pas vraiment de points sur le resultat
1130         // donc il ne reste rien
1131         sp_document_done(sp_desktop_document(desktop), 
1132                          (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1133                           : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1134                          (updating ? _("Create linked offset")
1135                           : _("Create dynamic offset")));
1136         selection->clear();
1138         delete res;
1139         delete orig;
1140         g_free(style);
1141         return;
1142     }
1144     {
1145         gchar tstr[80];
1147         tstr[79] = '\0';
1149         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1150         repr = xml_doc->createElement("svg:path");
1151         repr->setAttribute("sodipodi:type", "inkscape:offset");
1152         sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1153                                                           ? o_width
1154                                                           : expand < 0
1155                                                           ? -o_width
1156                                                           : 0 ));
1158         str = res->svg_dump_path();
1159         repr->setAttribute("inkscape:original", str);
1160         g_free(str);
1162         if ( updating ) {
1163             char const *id = SP_OBJECT(item)->repr->attribute("id");
1164             char const *uri = g_strdup_printf("#%s", id);
1165             repr->setAttribute("xlink:href", uri);
1166             g_free((void *) uri);
1167         } else {
1168             repr->setAttribute("inkscape:href", NULL);
1169         }
1171         repr->setAttribute("style", style);
1173         // add the new repr to the parent
1174         parent->appendChild(repr);
1176         // move to the saved position
1177         repr->setPosition(pos > 0 ? pos : 0);
1179         SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1181         if ( updating ) {
1182             // on conserve l'original
1183             // we reapply the transform to the original (offset will feel it)
1184             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1185         } else {
1186             // delete original, apply the transform to the offset
1187             SP_OBJECT(item)->deleteObject(false);
1188             sp_item_write_transform(nitem, repr, transform);
1189         }
1191         // The object just created from a temporary repr is only a seed.
1192         // We need to invoke its write which will update its real repr (in particular adding d=)
1193         SP_OBJECT(nitem)->updateRepr();
1195         Inkscape::GC::release(repr);
1197         selection->set(nitem);
1198     }
1200     sp_document_done(sp_desktop_document(desktop), 
1201                      (updating ? SP_VERB_SELECTION_LINKED_OFFSET 
1202                       : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1203                      (updating ? _("Create linked offset")
1204                       : _("Create dynamic offset")));
1206     delete res;
1207     delete orig;
1209     g_free(style);
1223 void
1224 sp_selected_path_do_offset(bool expand, double prefOffset)
1226     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1228     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1230     if (selection->isEmpty()) {
1231         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1232         return;
1233     }
1235     bool did = false;
1237     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1238          items != NULL;
1239          items = items->next) {
1241         SPItem *item = (SPItem *) items->data;
1243         if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1244             continue;
1246         SPCurve *curve = NULL;
1247         if (SP_IS_SHAPE(item)) {
1248             curve = sp_shape_get_curve(SP_SHAPE(item));
1249             if (curve == NULL)
1250                 continue;
1251         }
1252         if (SP_IS_TEXT(item)) {
1253             curve = SP_TEXT(item)->getNormalizedBpath();
1254             if (curve == NULL)
1255                 continue;
1256         }
1258         NR::Matrix const transform(item->transform);
1260         sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1262         gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1264         float o_width, o_miter;
1265         JoinType o_join;
1266         ButtType o_butt;
1268         {
1269             SPStyle *i_style = SP_OBJECT(item)->style;
1270             int jointype, captype;
1272             jointype = i_style->stroke_linejoin.value;
1273             captype = i_style->stroke_linecap.value;
1274             o_width = i_style->stroke_width.computed;
1276             switch (jointype) {
1277                 case SP_STROKE_LINEJOIN_MITER:
1278                     o_join = join_pointy;
1279                     break;
1280                 case SP_STROKE_LINEJOIN_ROUND:
1281                     o_join = join_round;
1282                     break;
1283                 default:
1284                     o_join = join_straight;
1285                     break;
1286             }
1288             switch (captype) {
1289                 case SP_STROKE_LINECAP_SQUARE:
1290                     o_butt = butt_square;
1291                     break;
1292                 case SP_STROKE_LINECAP_ROUND:
1293                     o_butt = butt_round;
1294                     break;
1295                 default:
1296                     o_butt = butt_straight;
1297                     break;
1298             }
1300             o_width = prefOffset;
1302             if (o_width < 0.1)
1303                 o_width = 0.1;
1304             o_miter = i_style->stroke_miterlimit.value * o_width;
1305         }
1307         Path *orig = Path_for_item(item, false);
1308         if (orig == NULL) {
1309             g_free(style);
1310             curve->unref();
1311             continue;
1312         }
1314         Path *res = new Path;
1315         res->SetBackData(false);
1317         {
1318             Shape *theShape = new Shape;
1319             Shape *theRes = new Shape;
1321             orig->ConvertWithBackData(0.03);
1322             orig->Fill(theShape, 0);
1324             SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1325             gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1326             if (val && strcmp(val, "nonzero") == 0)
1327             {
1328                 theRes->ConvertToShape(theShape, fill_nonZero);
1329             }
1330             else if (val && strcmp(val, "evenodd") == 0)
1331             {
1332                 theRes->ConvertToShape(theShape, fill_oddEven);
1333             }
1334             else
1335             {
1336                 theRes->ConvertToShape(theShape, fill_nonZero);
1337             }
1339             // et maintenant: offset
1340             // methode inexacte
1341 /*                      Path *originaux[1];
1342                         originaux[0] = orig;
1343                         theRes->ConvertToForme(res, 1, originaux);
1345                         if (expand) {
1346                         res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1347                         } else {
1348                         res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1349                         }
1351                         orig->ConvertWithBackData(1.0);
1352                         orig->Fill(theShape, 0);
1353                         theRes->ConvertToShape(theShape, fill_positive);
1354                         originaux[0] = orig;
1355                         theRes->ConvertToForme(res, 1, originaux);
1357                         if (o_width >= 0.5) {
1358                         //     res->Coalesce(1.0);
1359                         res->ConvertEvenLines(1.0);
1360                         res->Simplify(1.0);
1361                         } else {
1362                         //      res->Coalesce(o_width);
1363                         res->ConvertEvenLines(1.0*o_width);
1364                         res->Simplify(1.0 * o_width);
1365                         }    */
1366             // methode par makeoffset
1368             if (expand)
1369             {
1370                 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1371             }
1372             else
1373             {
1374                 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1375             }
1376             theRes->ConvertToShape(theShape, fill_positive);
1378             res->Reset();
1379             theRes->ConvertToForme(res);
1381             if (o_width >= 1.0)
1382             {
1383                 res->ConvertEvenLines(1.0);
1384                 res->Simplify(1.0);
1385             }
1386             else
1387             {
1388                 res->ConvertEvenLines(1.0*o_width);
1389                 res->Simplify(1.0 * o_width);
1390             }
1392             delete theShape;
1393             delete theRes;
1394         }
1396         did = true;
1398         curve->unref();
1399         // remember the position of the item
1400         gint pos = SP_OBJECT_REPR(item)->position();
1401         // remember parent
1402         Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1403         // remember id
1404         char const *id = SP_OBJECT_REPR(item)->attribute("id");
1406         selection->remove(item);
1407         SP_OBJECT(item)->deleteObject(false);
1409         if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1411             gchar tstr[80];
1413             tstr[79] = '\0';
1415             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1416             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1418             repr->setAttribute("style", style);
1420             gchar *str = res->svg_dump_path();
1421             repr->setAttribute("d", str);
1422             g_free(str);
1424             // add the new repr to the parent
1425             parent->appendChild(repr);
1427             // move to the saved position
1428             repr->setPosition(pos > 0 ? pos : 0);
1430             SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1432             // reapply the transform
1433             sp_item_write_transform(newitem, repr, transform);
1435             repr->setAttribute("id", id);
1437             selection->add(repr);
1439             Inkscape::GC::release(repr);
1440         }
1442         delete orig;
1443         delete res;
1444     }
1446     if (did) {
1447         sp_document_done(sp_desktop_document(desktop), 
1448                          (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1449                          (expand ? _("Outset path") : _("Inset path")));
1450     } else {
1451         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1452         return;
1453     }
1457 static bool
1458 sp_selected_path_simplify_items(SPDesktop *desktop,
1459                                 Inkscape::Selection *selection, GSList *items,
1460                                 float threshold,  bool justCoalesce,
1461                                 float angleLimit, bool breakableAngles,
1462                                 bool modifySelection);
1465 //return true if we changed something, else false
1466 bool
1467 sp_selected_path_simplify_item(SPDesktop *desktop,
1468                  Inkscape::Selection *selection, SPItem *item,
1469                  float threshold,  bool justCoalesce,
1470                  float angleLimit, bool breakableAngles,
1471                  gdouble size,     bool modifySelection)
1473     if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1474         return false;
1476     //If this is a group, do the children instead
1477     if (SP_IS_GROUP(item)) {
1478         GSList *items = sp_item_group_item_list(SP_GROUP(item));
1479         
1480         return sp_selected_path_simplify_items(desktop, selection, items,
1481                                                threshold, justCoalesce,
1482                                                angleLimit, breakableAngles,
1483                                                false);
1484     }
1487     SPCurve *curve = NULL;
1489     if (SP_IS_SHAPE(item)) {
1490         curve = sp_shape_get_curve(SP_SHAPE(item));
1491         if (!curve)
1492             return false;
1493     }
1495     if (SP_IS_TEXT(item)) {
1496         curve = SP_TEXT(item)->getNormalizedBpath();
1497         if (!curve)
1498             return false;
1499     }
1501     // save the transform, to re-apply it after simplification
1502     NR::Matrix const transform(item->transform);
1504     /*
1505        reset the transform, effectively transforming the item by transform.inverse();
1506        this is necessary so that the item is transformed twice back and forth,
1507        allowing all compensations to cancel out regardless of the preferences
1508     */
1509     sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1511     gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1512     gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1513     gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1515     Path *orig = Path_for_item(item, false);
1516     if (orig == NULL) {
1517         g_free(style);
1518         curve->unref();
1519         return false;
1520     }
1522     curve->unref();
1523     // remember the position of the item
1524     gint pos = SP_OBJECT_REPR(item)->position();
1525     // remember parent
1526     Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1527     // remember id
1528     char const *id = SP_OBJECT_REPR(item)->attribute("id");
1529     // remember path effect
1530     char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1532     //If a group was selected, to not change the selection list
1533     if (modifySelection)
1534         selection->remove(item);
1536     SP_OBJECT(item)->deleteObject(false);
1538     if ( justCoalesce ) {
1539         orig->Coalesce(threshold * size);
1540     } else {
1541         orig->ConvertEvenLines(threshold * size);
1542         orig->Simplify(threshold * size);
1543     }
1545     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1546     Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1548     // restore style, mask and clip-path
1549     repr->setAttribute("style", style);
1550     g_free(style);
1552     if ( mask ) {
1553         repr->setAttribute("mask", mask);
1554         g_free(mask);
1555     }
1557     if ( clip_path ) {
1558         repr->setAttribute("clip-path", clip_path);
1559         g_free(clip_path);
1560     }
1562     // path
1563     gchar *str = orig->svg_dump_path();
1564     if (patheffect)
1565         repr->setAttribute("inkscape:original-d", str);
1566     else 
1567         repr->setAttribute("d", str);
1568     g_free(str);
1570     // restore id
1571     repr->setAttribute("id", id);
1573     // add the new repr to the parent
1574     parent->appendChild(repr);
1576     // move to the saved position
1577     repr->setPosition(pos > 0 ? pos : 0);
1579     SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1581     // reapply the transform
1582     sp_item_write_transform(newitem, repr, transform);
1584     // restore path effect
1585     repr->setAttribute("inkscape:path-effect", patheffect);
1587     //If we are not in a selected group
1588     if (modifySelection)
1589         selection->add(repr);
1591     Inkscape::GC::release(repr);
1593     // clean up
1594     if (orig) delete orig;
1596     return true;
1600 bool
1601 sp_selected_path_simplify_items(SPDesktop *desktop,
1602                                 Inkscape::Selection *selection, GSList *items,
1603                                 float threshold,  bool justCoalesce,
1604                                 float angleLimit, bool breakableAngles,
1605                                 bool modifySelection)
1607   bool simplifyIndividualPaths =
1608     (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1609   
1610   gchar *simplificationType;
1611   if (simplifyIndividualPaths) {
1612       simplificationType = _("Simplifying paths (separately):");
1613   } else {
1614       simplificationType = _("Simplifying paths:");
1615   }
1617   bool didSomething = false;
1619   NR::Maybe<NR::Rect> selectionBbox = selection->bounds();
1620   if (!selectionBbox) {
1621     return false;
1622   }
1623   gdouble selectionSize  = L2(selectionBbox->dimensions());
1625   gdouble simplifySize  = selectionSize;
1626   
1627   int pathsSimplified = 0;
1628   int totalPathCount  = g_slist_length(items);
1629   
1630   // set "busy" cursor
1631   desktop->setWaitingCursor();
1632   
1633   for (; items != NULL; items = items->next) {
1634       SPItem *item = (SPItem *) items->data;
1635       
1636       if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1637           continue;
1639       if (simplifyIndividualPaths) {
1640           NR::Maybe<NR::Rect> itemBbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
1641           if (itemBbox) {
1642               simplifySize      = L2(itemBbox->dimensions());
1643           } else {
1644               simplifySize      = 0;
1645           }
1646       }
1648       pathsSimplified++;
1650       if (pathsSimplified % 20 == 0) {
1651         gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1652         desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1653       }
1655       didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1656                           threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1657   }
1659   desktop->clearWaitingCursor();
1661   if (pathsSimplified > 20) {
1662     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1663   }
1664   
1665   return didSomething;
1668 void
1669 sp_selected_path_simplify_selection(float threshold, bool justCoalesce,
1670                        float angleLimit, bool breakableAngles)
1672     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1674     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1676     if (selection->isEmpty()) {
1677         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1678                          _("Select <b>path(s)</b> to simplify."));
1679         return;
1680     }
1682     GSList *items = g_slist_copy((GSList *) selection->itemList());
1684     bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1685                                                         items, threshold,
1686                                                         justCoalesce,
1687                                                         angleLimit,
1688                                                         breakableAngles, true);
1690     if (didSomething)
1691         sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY, 
1692                          _("Simplify"));
1693     else
1694         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1699 // globals for keeping track of accelerated simplify
1700 static double previousTime      = 0.0;
1701 static gdouble simplifyMultiply = 1.0;
1703 void
1704 sp_selected_path_simplify(void)
1706     gdouble simplifyThreshold =
1707         prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1708     bool simplifyJustCoalesce =
1709         (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1711     //Get the current time
1712     GTimeVal currentTimeVal;
1713     g_get_current_time(&currentTimeVal);
1714     double currentTime = currentTimeVal.tv_sec * 1000000 +
1715                 currentTimeVal.tv_usec;
1717     //Was the previous call to this function recent? (<0.5 sec)
1718     if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1720         // add to the threshold 1/2 of its original value
1721         simplifyMultiply  += 0.5;
1722         simplifyThreshold *= simplifyMultiply;
1724     } else {
1725         // reset to the default
1726         simplifyMultiply = 1;
1727     }
1729     //remember time for next call
1730     previousTime = currentTime;
1732     //g_print("%g\n", simplify_threshold);
1734     //Make the actual call
1735     sp_selected_path_simplify_selection(simplifyThreshold,
1736                       simplifyJustCoalesce, 0.0, false);
1741 // fonctions utilitaires
1743 bool
1744 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1746     if (who == NULL || a == NULL)
1747         return false;
1748     if (who == a)
1749         return true;
1750     return Ancetre(sp_repr_parent(a), who);
1753 Path *
1754 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1756     SPCurve *curve = curve_for_item(item);
1757     if (curve == NULL) {
1758         return NULL;
1759     }
1761     Geom::PathVector pathv = pathvector_for_curve(item, curve, doTransformation, transformFull);
1763     Path *dest = new Path;
1764     dest->LoadPathVector(pathv);
1766     curve->unref();
1767     
1768     return dest;
1771 /* 
1772  * This function always returns a new NArtBpath, the caller must g_free the returned path!
1773 */
1774 NArtBpath *
1775 bpath_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1777     if (curve == NULL)
1778         return NULL;
1780     NArtBpath const *bpath = SP_CURVE_BPATH(curve);
1781     if (bpath == NULL) {
1782         return NULL;
1783     }
1785     NArtBpath *new_bpath; // we will get a duplicate which has to be freed at some point!
1786     if (doTransformation) {
1787         if (transformFull) {
1788             new_bpath = nr_artpath_affine(bpath, from_2geom(sp_item_i2doc_affine(item)));
1789         } else {
1790             new_bpath = nr_artpath_affine(bpath, item->transform);
1791         }
1792     } else {
1793         new_bpath = nr_artpath_affine(bpath, NR::identity());
1794     }
1796     return new_bpath;
1799 /* 
1800  * NOTE: Returns empty pathvector if curve == NULL
1801  * TODO: see if calling this method can be optimized. All the pathvector copying might be slow.
1802  */
1803 Geom::PathVector
1804 pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull)
1806     if (curve == NULL)
1807         return Geom::PathVector();
1809     if (doTransformation) {
1810         if (transformFull) {
1811             return (curve->get_pathvector()) * sp_item_i2doc_affine(item);
1812         } else {
1813             return (curve->get_pathvector()) * to_2geom(item->transform);
1814         }
1815     } else {
1816         return curve->get_pathvector();
1817     }
1820 SPCurve* curve_for_item(SPItem *item)
1822     if (!item)
1823         return NULL;
1825     SPCurve *curve = NULL;
1827     if (SP_IS_SHAPE(item)) {
1828         if (SP_IS_PATH(item)) {
1829             curve = sp_path_get_curve_for_edit(SP_PATH(item));
1830         } else {
1831             curve = sp_shape_get_curve(SP_SHAPE(item));
1832         }
1833     }
1834     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1835     {
1836         curve = te_get_layout(item)->convertToCurves();
1837     }
1838     else if (SP_IS_IMAGE(item))
1839     {
1840         curve = sp_image_get_curve(SP_IMAGE(item));
1841     }
1842     
1843     return curve; // do not forget to unref the curve at some point!
1846 Path *bpath_to_Path(NArtBpath const *bpath) {
1847     Path *dest = new Path;
1848     dest->SetBackData(false);
1849     {
1850         int   i;
1851         bool  closed = false;
1852         float lastX  = 0.0;
1853         float lastY  = 0.0;
1855         for (i = 0; bpath[i].code != NR_END; i++) {
1856             switch (bpath[i].code) {
1857                 case NR_LINETO:
1858                     lastX = bpath[i].x3;
1859                     lastY = bpath[i].y3;
1860                     {
1861                         NR::Point tmp(lastX, lastY);
1862                         dest->LineTo(tmp);
1863                     }
1864                     break;
1866                 case NR_CURVETO:
1867                 {
1868                     NR::Point tmp, tms, tme;
1869                     tmp[0]=bpath[i].x3;
1870                     tmp[1]=bpath[i].y3;
1871                     tms[0]=3 * (bpath[i].x1 - lastX);
1872                     tms[1]=3 * (bpath[i].y1 - lastY);
1873                     tme[0]=3 * (bpath[i].x3 - bpath[i].x2);
1874                     tme[1]=3 * (bpath[i].y3 - bpath[i].y2);
1875                     dest->CubicTo(tmp,tms,tme);
1876                 }
1877                 lastX = bpath[i].x3;
1878                 lastY = bpath[i].y3;
1879                 break;
1881                 case NR_MOVETO_OPEN:
1882                 case NR_MOVETO:
1883                     if (closed)
1884                         dest->Close();
1885                     closed = (bpath[i].code == NR_MOVETO);
1886                     lastX = bpath[i].x3;
1887                     lastY = bpath[i].y3;
1888                     {
1889                         NR::Point  tmp(lastX, lastY);
1890                         dest->MoveTo(tmp);
1891                     }
1892                     break;
1893                 default:
1894                     break;
1895             }
1896         }
1897         if (closed)
1898             dest->Close();
1899     }
1900     return dest;
1903 NR::Maybe<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1905     //get nearest position on path
1906     Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1907     return pos;
1910 NR::Point get_point_on_Path(Path *path, int piece, double t)
1912     NR::Point p;
1913     path->PointAt(piece, t, p);
1914     return p;
1918 /*
1919   Local Variables:
1920   mode:c++
1921   c-file-style:"stroustrup"
1922   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1923   indent-tabs-mode:nil
1924   fill-column:99
1925   End:
1926 */
1927 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :