a3a4ce59ff1d9d28fbf17ea98ba3dd37eaca25bc
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 "document.h"
37 #include "message-stack.h"
38 #include "selection.h"
39 #include "desktop-handles.h"
40 #include "desktop.h"
41 #include "display/canvas-bpath.h"
42 #include "display/curve.h"
43 #include <glibmm/i18n.h>
44 #include "preferences.h"
46 #include "xml/repr.h"
47 #include "xml/repr-sorting.h"
48 #include <2geom/pathvector.h>
49 #include <libnr/nr-scale-matrix-ops.h>
50 #include "helper/geom.h"
52 #include "livarot/Path.h"
53 #include "livarot/Shape.h"
55 #include "splivarot.h"
57 bool Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who);
59 void sp_selected_path_boolop(SPDesktop *desktop, bool_op bop, const unsigned int verb=SP_VERB_NONE, const Glib::ustring description="");
60 void sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset);
61 void sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool updating);
63 void
64 sp_selected_path_union(SPDesktop *desktop)
65 {
66 sp_selected_path_boolop(desktop, bool_op_union, SP_VERB_SELECTION_UNION, _("Union"));
67 }
69 void
70 sp_selected_path_union_skip_undo(SPDesktop *desktop)
71 {
72 sp_selected_path_boolop(desktop, bool_op_union, SP_VERB_NONE, _("Union"));
73 }
75 void
76 sp_selected_path_intersect(SPDesktop *desktop)
77 {
78 sp_selected_path_boolop(desktop, bool_op_inters, SP_VERB_SELECTION_INTERSECT, _("Intersection"));
79 }
81 void
82 sp_selected_path_diff(SPDesktop *desktop)
83 {
84 sp_selected_path_boolop(desktop, bool_op_diff, SP_VERB_SELECTION_DIFF, _("Difference"));
85 }
87 void
88 sp_selected_path_diff_skip_undo(SPDesktop *desktop)
89 {
90 sp_selected_path_boolop(desktop, bool_op_diff, SP_VERB_NONE, _("Difference"));
91 }
93 void
94 sp_selected_path_symdiff(SPDesktop *desktop)
95 {
96 sp_selected_path_boolop(desktop, bool_op_symdiff, SP_VERB_SELECTION_SYMDIFF, _("Exclusion"));
97 }
98 void
99 sp_selected_path_cut(SPDesktop *desktop)
100 {
101 sp_selected_path_boolop(desktop, bool_op_cut, SP_VERB_SELECTION_CUT, _("Division"));
102 }
103 void
104 sp_selected_path_slice(SPDesktop *desktop)
105 {
106 sp_selected_path_boolop(desktop, bool_op_slice, SP_VERB_SELECTION_SLICE, _("Cut path"));
107 }
110 // boolean operations
111 // take the source paths from the file, do the operation, delete the originals and add the results
112 void
113 sp_selected_path_boolop(SPDesktop *desktop, bool_op bop, const unsigned int verb, const Glib::ustring description)
114 {
115 Inkscape::Selection *selection = sp_desktop_selection(desktop);
117 GSList *il = (GSList *) selection->itemList();
119 // allow union on a single object for the purpose of removing self overlapse (svn log, revision 13334)
120 if ( (g_slist_length(il) < 2) && (bop != bool_op_union)) {
121 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 2 paths</b> to perform a boolean operation."));
122 return;
123 }
124 else if ( g_slist_length(il) < 1 ) {
125 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>at least 1 path</b> to perform a boolean union."));
126 return;
127 }
129 if (g_slist_length(il) > 2) {
130 if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
131 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Select <b>exactly 2 paths</b> to perform difference, XOR, division, or path cut."));
132 return;
133 }
134 }
136 // reverseOrderForOp marks whether the order of the list is the top->down order
137 // it's only used when there are 2 objects, and for operations who need to know the
138 // topmost object (differences, cuts)
139 bool reverseOrderForOp = false;
141 // mettre les elements de la liste dans l'ordre pour ces operations
142 if (bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice) {
143 // check in the tree to find which element of the selection list is topmost (for 2-operand commands only)
144 Inkscape::XML::Node *a = SP_OBJECT_REPR(il->data);
145 Inkscape::XML::Node *b = SP_OBJECT_REPR(il->next->data);
147 if (a == NULL || b == NULL) {
148 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."));
149 return;
150 }
152 if (Ancetre(a, b)) {
153 // a is the parent of b, already in the proper order
154 } else if (Ancetre(b, a)) {
155 // reverse order
156 reverseOrderForOp = true;
157 } else {
159 // objects are not in parent/child relationship;
160 // find their lowest common ancestor
161 Inkscape::XML::Node *dad = LCA(a, b);
162 if (dad == NULL) {
163 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."));
164 return;
165 }
167 // find the children of the LCA that lead from it to the a and b
168 Inkscape::XML::Node *as = AncetreFils(a, dad);
169 Inkscape::XML::Node *bs = AncetreFils(b, dad);
171 // find out which comes first
172 for (Inkscape::XML::Node *child = dad->firstChild(); child; child = child->next()) {
173 if (child == as) {
174 /* a first, so reverse. */
175 reverseOrderForOp = true;
176 break;
177 }
178 if (child == bs)
179 break;
180 }
181 }
182 }
184 il = g_slist_copy(il);
186 // first check if all the input objects have shapes
187 // otherwise bail out
188 for (GSList *l = il; l != NULL; l = l->next)
189 {
190 SPItem *item = SP_ITEM(l->data);
191 if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item) && !SP_IS_FLOWTEXT(item))
192 {
193 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("One of the objects is <b>not a path</b>, cannot perform boolean operation."));
194 g_slist_free(il);
195 return;
196 }
197 }
199 // extract the livarot Paths from the source objects
200 // also get the winding rule specified in the style
201 int nbOriginaux = g_slist_length(il);
202 std::vector<Path *> originaux(nbOriginaux);
203 std::vector<FillRule> origWind(nbOriginaux);
204 int curOrig;
205 {
206 curOrig = 0;
207 for (GSList *l = il; l != NULL; l = l->next)
208 {
209 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(il->data), "style");
210 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
211 if (val && strcmp(val, "nonzero") == 0) {
212 origWind[curOrig]= fill_nonZero;
213 } else if (val && strcmp(val, "evenodd") == 0) {
214 origWind[curOrig]= fill_oddEven;
215 } else {
216 origWind[curOrig]= fill_nonZero;
217 }
219 originaux[curOrig] = Path_for_item((SPItem *) l->data, true, true);
220 if (originaux[curOrig] == NULL || originaux[curOrig]->descr_cmd.size() <= 1)
221 {
222 for (int i = curOrig; i >= 0; i--) delete originaux[i];
223 g_slist_free(il);
224 return;
225 }
226 curOrig++;
227 }
228 }
229 // reverse if needed
230 // note that the selection list keeps its order
231 if ( reverseOrderForOp ) {
232 Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
233 FillRule swai=origWind[0]; origWind[0]=origWind[1]; origWind[1]=swai;
234 }
236 // and work
237 // some temporary instances, first
238 Shape *theShapeA = new Shape;
239 Shape *theShapeB = new Shape;
240 Shape *theShape = new Shape;
241 Path *res = new Path;
242 res->SetBackData(false);
243 Path::cut_position *toCut=NULL;
244 int nbToCut=0;
246 if ( bop == bool_op_inters || bop == bool_op_union || bop == bool_op_diff || bop == bool_op_symdiff ) {
247 // true boolean op
248 // get the polygons of each path, with the winding rule specified, and apply the operation iteratively
249 originaux[0]->ConvertWithBackData(0.1);
251 originaux[0]->Fill(theShape, 0);
253 theShapeA->ConvertToShape(theShape, origWind[0]);
255 curOrig = 1;
256 for (GSList *l = il->next; l != NULL; l = l->next) {
257 originaux[curOrig]->ConvertWithBackData(0.1);
259 originaux[curOrig]->Fill(theShape, curOrig);
261 theShapeB->ConvertToShape(theShape, origWind[curOrig]);
263 // les elements arrivent en ordre inverse dans la liste
264 theShape->Booleen(theShapeB, theShapeA, bop);
266 {
267 Shape *swap = theShape;
268 theShape = theShapeA;
269 theShapeA = swap;
270 }
271 curOrig++;
272 }
274 {
275 Shape *swap = theShape;
276 theShape = theShapeA;
277 theShapeA = swap;
278 }
280 } else if ( bop == bool_op_cut ) {
281 // cuts= sort of a bastard boolean operation, thus not the axact same modus operandi
282 // technically, the cut path is not necessarily a polygon (thus has no winding rule)
283 // it is just uncrossed, and cleaned from duplicate edges and points
284 // then it's fed to Booleen() which will uncross it against the other path
285 // then comes the trick: each edge of the cut path is duplicated (one in each direction),
286 // thus making a polygon. the weight of the edges of the cut are all 0, but
287 // the Booleen need to invert the ones inside the source polygon (for the subsequent
288 // ConvertToForme)
290 // the cut path needs to have the highest pathID in the back data
291 // that's how the Booleen() function knows it's an edge of the cut
293 // FIXME: this gives poor results, the final paths are full of extraneous nodes. Decreasing
294 // ConvertWithBackData parameter below simply increases the number of nodes, so for now I
295 // left it at 1.0. Investigate replacing this by a combination of difference and
296 // intersection of the same two paths. -- bb
297 {
298 Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
299 int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
300 }
301 originaux[0]->ConvertWithBackData(1.0);
303 originaux[0]->Fill(theShape, 0);
305 theShapeA->ConvertToShape(theShape, origWind[0]);
307 originaux[1]->ConvertWithBackData(1.0);
309 originaux[1]->Fill(theShape, 1,false,false,false); //do not closeIfNeeded
311 theShapeB->ConvertToShape(theShape, fill_justDont); // fill_justDont doesn't computes winding numbers
313 // les elements arrivent en ordre inverse dans la liste
314 theShape->Booleen(theShapeB, theShapeA, bool_op_cut, 1);
316 } else if ( bop == bool_op_slice ) {
317 // slice is not really a boolean operation
318 // you just put the 2 shapes in a single polygon, uncross it
319 // the points where the degree is > 2 are intersections
320 // just check it's an intersection on the path you want to cut, and keep it
321 // the intersections you have found are then fed to ConvertPositionsToMoveTo() which will
322 // make new subpath at each one of these positions
323 // inversion pour l'op\8eration
324 {
325 Path* swap=originaux[0];originaux[0]=originaux[1];originaux[1]=swap;
326 int swai=origWind[0];origWind[0]=origWind[1];origWind[1]=(fill_typ)swai;
327 }
328 originaux[0]->ConvertWithBackData(1.0);
330 originaux[0]->Fill(theShapeA, 0,false,false,false); // don't closeIfNeeded
332 originaux[1]->ConvertWithBackData(1.0);
334 originaux[1]->Fill(theShapeA, 1,true,false,false);// don't closeIfNeeded and just dump in the shape, don't reset it
336 theShape->ConvertToShape(theShapeA, fill_justDont);
338 if ( theShape->hasBackData() ) {
339 // should always be the case, but ya never know
340 {
341 for (int i = 0; i < theShape->numberOfPoints(); i++) {
342 if ( theShape->getPoint(i).totalDegree() > 2 ) {
343 // possibly an intersection
344 // we need to check that at least one edge from the source path is incident to it
345 // before we declare it's an intersection
346 int cb = theShape->getPoint(i).incidentEdge[FIRST];
347 int nbOrig=0;
348 int nbOther=0;
349 int piece=-1;
350 float t=0.0;
351 while ( cb >= 0 && cb < theShape->numberOfEdges() ) {
352 if ( theShape->ebData[cb].pathID == 0 ) {
353 // the source has an edge incident to the point, get its position on the path
354 piece=theShape->ebData[cb].pieceID;
355 if ( theShape->getEdge(cb).st == i ) {
356 t=theShape->ebData[cb].tSt;
357 } else {
358 t=theShape->ebData[cb].tEn;
359 }
360 nbOrig++;
361 }
362 if ( theShape->ebData[cb].pathID == 1 ) nbOther++; // the cut is incident to this point
363 cb=theShape->NextAt(i, cb);
364 }
365 if ( nbOrig > 0 && nbOther > 0 ) {
366 // point incident to both path and cut: an intersection
367 // note that you only keep one position on the source; you could have degenerate
368 // cases where the source crosses itself at this point, and you wouyld miss an intersection
369 toCut=(Path::cut_position*)realloc(toCut, (nbToCut+1)*sizeof(Path::cut_position));
370 toCut[nbToCut].piece=piece;
371 toCut[nbToCut].t=t;
372 nbToCut++;
373 }
374 }
375 }
376 }
377 {
378 // i think it's useless now
379 int i = theShape->numberOfEdges() - 1;
380 for (;i>=0;i--) {
381 if ( theShape->ebData[i].pathID == 1 ) {
382 theShape->SubEdge(i);
383 }
384 }
385 }
387 }
388 }
390 int* nesting=NULL;
391 int* conts=NULL;
392 int nbNest=0;
393 // pour compenser le swap juste avant
394 if ( bop == bool_op_slice ) {
395 // theShape->ConvertToForme(res, nbOriginaux, originaux, true);
396 // res->ConvertForcedToMoveTo();
397 res->Copy(originaux[0]);
398 res->ConvertPositionsToMoveTo(nbToCut, toCut); // cut where you found intersections
399 free(toCut);
400 } else if ( bop == bool_op_cut ) {
401 // il faut appeler pour desallouer PointData (pas vital, mais bon)
402 // the Booleen() function did not deallocated the point_data array in theShape, because this
403 // function needs it.
404 // this function uses the point_data to get the winding number of each path (ie: is a hole or not)
405 // for later reconstruction in objects, you also need to extract which path is parent of holes (nesting info)
406 theShape->ConvertToFormeNested(res, nbOriginaux, &originaux[0], 1, nbNest, nesting, conts);
407 } else {
408 theShape->ConvertToForme(res, nbOriginaux, &originaux[0]);
409 }
411 delete theShape;
412 delete theShapeA;
413 delete theShapeB;
414 for (int i = 0; i < nbOriginaux; i++) delete originaux[i];
416 if (res->descr_cmd.size() <= 1)
417 {
418 // only one command, presumably a moveto: it isn't a path
419 for (GSList *l = il; l != NULL; l = l->next)
420 {
421 SP_OBJECT(l->data)->deleteObject();
422 }
423 sp_document_done(sp_desktop_document(desktop), SP_VERB_NONE,
424 description);
425 selection->clear();
427 delete res;
428 g_slist_free(il);
429 return;
430 }
432 // get the source path object
433 SPObject *source;
434 if ( bop == bool_op_diff || bop == bool_op_symdiff || bop == bool_op_cut || bop == bool_op_slice ) {
435 if (reverseOrderForOp) {
436 source = SP_OBJECT(il->data);
437 } else {
438 source = SP_OBJECT(il->next->data);
439 }
440 } else {
441 // find out the bottom object
442 GSList *sorted = g_slist_copy((GSList *) selection->reprList());
444 sorted = g_slist_sort(sorted, (GCompareFunc) sp_repr_compare_position);
446 source = sp_desktop_document(desktop)->
447 getObjectByRepr((Inkscape::XML::Node *)sorted->data);
449 g_slist_free(sorted);
450 }
452 // adjust style properties that depend on a possible transform in the source object in order
453 // to get a correct style attribute for the new path
454 SPItem* item_source = SP_ITEM(source);
455 NR::Matrix i2root(sp_item_i2root_affine(item_source));
456 sp_item_adjust_stroke(item_source, i2root.descrim());
457 sp_item_adjust_pattern(item_source, i2root);
458 sp_item_adjust_gradient(item_source, i2root);
459 sp_item_adjust_livepatheffect(item_source, i2root);
461 Inkscape::XML::Node *repr_source = SP_OBJECT_REPR(source);
463 // remember important aspects of the source path, to be restored
464 gint pos = repr_source->position();
465 Inkscape::XML::Node *parent = sp_repr_parent(repr_source);
466 gchar const *id = repr_source->attribute("id");
467 gchar const *style = repr_source->attribute("style");
468 gchar const *mask = repr_source->attribute("mask");
469 gchar const *clip_path = repr_source->attribute("clip-path");
470 gchar *title = source->title();
471 gchar *desc = source->desc();
472 // remove source paths
473 selection->clear();
474 for (GSList *l = il; l != NULL; l = l->next) {
475 // if this is the bottommost object,
476 if (!strcmp(SP_OBJECT_REPR(l->data)->attribute("id"), id)) {
477 // delete it so that its clones don't get alerted; this object will be restored shortly, with the same id
478 SP_OBJECT(l->data)->deleteObject(false);
479 } else {
480 // delete the object for real, so that its clones can take appropriate action
481 SP_OBJECT(l->data)->deleteObject();
482 }
483 }
484 g_slist_free(il);
486 // premultiply by the inverse of parent's repr
487 SPItem *parent_item = SP_ITEM(sp_desktop_document(desktop)->getObjectByRepr(parent));
488 NR::Matrix local (sp_item_i2doc_affine(parent_item));
489 gchar *transform = sp_svg_transform_write(local.inverse());
491 // now that we have the result, add it on the canvas
492 if ( bop == bool_op_cut || bop == bool_op_slice ) {
493 int nbRP=0;
494 Path** resPath;
495 if ( bop == bool_op_slice ) {
496 // there are moveto's at each intersection, but it's still one unique path
497 // so break it down and add each subpath independently
498 // we could call break_apart to do this, but while we have the description...
499 resPath=res->SubPaths(nbRP, false);
500 } else {
501 // cut operation is a bit wicked: you need to keep holes
502 // that's why you needed the nesting
503 // ConvertToFormeNested() dumped all the subpath in a single Path "res", so we need
504 // to get the path for each part of the polygon. that's why you need the nesting info:
505 // to know in wich subpath to add a subpath
506 resPath=res->SubPathsWithNesting(nbRP, true, nbNest, nesting, conts);
508 // cleaning
509 if ( conts ) free(conts);
510 if ( nesting ) free(nesting);
511 }
513 // add all the pieces resulting from cut or slice
514 for (int i=0;i<nbRP;i++) {
515 gchar *d = resPath[i]->svg_dump_path();
517 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
518 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
519 repr->setAttribute("style", style);
520 if (mask)
521 repr->setAttribute("mask", mask);
522 if (clip_path)
523 repr->setAttribute("clip-path", clip_path);
525 repr->setAttribute("d", d);
526 g_free(d);
528 // for slice, remove fill
529 if (bop == bool_op_slice) {
530 SPCSSAttr *css;
532 css = sp_repr_css_attr_new();
533 sp_repr_css_set_property(css, "fill", "none");
535 sp_repr_css_change(repr, css, "style");
537 sp_repr_css_attr_unref(css);
538 }
540 // we assign the same id on all pieces, but it on adding to document, it will be changed on all except one
541 // this means it's basically random which of the pieces inherits the original's id and clones
542 // a better algorithm might figure out e.g. the biggest piece
543 repr->setAttribute("id", id);
545 repr->setAttribute("transform", transform);
547 // add the new repr to the parent
548 parent->appendChild(repr);
550 // move to the saved position
551 repr->setPosition(pos > 0 ? pos : 0);
553 selection->add(repr);
554 Inkscape::GC::release(repr);
556 delete resPath[i];
557 }
558 if ( resPath ) free(resPath);
560 } else {
561 gchar *d = res->svg_dump_path();
563 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
564 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
565 repr->setAttribute("style", style);
567 if ( mask )
568 repr->setAttribute("mask", mask);
570 if ( clip_path )
571 repr->setAttribute("clip-path", clip_path);
573 repr->setAttribute("d", d);
574 g_free(d);
576 repr->setAttribute("transform", transform);
578 repr->setAttribute("id", id);
579 parent->appendChild(repr);
580 if (title) {
581 sp_desktop_document(desktop)->getObjectByRepr(repr)->setTitle(title);
582 }
583 if (desc) {
584 sp_desktop_document(desktop)->getObjectByRepr(repr)->setDesc(desc);
585 }
586 repr->setPosition(pos > 0 ? pos : 0);
588 selection->add(repr);
589 Inkscape::GC::release(repr);
590 }
592 g_free(transform);
593 if (title) g_free(title);
594 if (desc) g_free(desc);
596 if (verb != SP_VERB_NONE) {
597 sp_document_done(sp_desktop_document(desktop), verb, description);
598 }
600 delete res;
601 }
603 static
604 void sp_selected_path_outline_add_marker( SPObject *marker_object, Geom::Matrix marker_transform,
605 Geom::Scale stroke_scale, Geom::Matrix transform,
606 Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument * doc )
607 {
608 SPMarker* marker = SP_MARKER (marker_object);
609 SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker_object));
611 Geom::Matrix tr(marker_transform);
613 if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
614 tr = stroke_scale * tr;
615 }
617 // total marker transform
618 tr = marker_item->transform * marker->c2p * tr * transform;
620 if (SP_OBJECT_REPR(marker_item)) {
621 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
622 g_repr->appendChild(m_repr);
623 SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr);
624 sp_item_write_transform(marker_item, m_repr, tr);
625 }
626 }
628 void
629 sp_selected_path_outline(SPDesktop *desktop)
630 {
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 if (!SP_OBJECT_STYLE(item) || SP_OBJECT_STYLE(item)->stroke.noneSet) {
663 curve->unref();
664 continue;
665 }
667 // remember old stroke style, to be set on fill
668 SPStyle *i_style = SP_OBJECT_STYLE(item);
669 SPCSSAttr *ncss;
670 {
671 ncss = sp_css_attr_from_style(i_style, SP_STYLE_FLAG_ALWAYS);
672 gchar const *s_val = sp_repr_css_property(ncss, "stroke", NULL);
673 gchar const *s_opac = sp_repr_css_property(ncss, "stroke-opacity", NULL);
675 sp_repr_css_set_property(ncss, "stroke", "none");
676 sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
677 sp_repr_css_set_property(ncss, "fill", s_val);
678 if ( s_opac ) {
679 sp_repr_css_set_property(ncss, "fill-opacity", s_opac);
680 } else {
681 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
682 }
683 sp_repr_css_unset_property(ncss, "marker-start");
684 sp_repr_css_unset_property(ncss, "marker-mid");
685 sp_repr_css_unset_property(ncss, "marker-end");
686 }
688 NR::Matrix const transform(item->transform);
689 float const scale = transform.descrim();
690 gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
691 gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
693 float o_width, o_miter;
694 JoinType o_join;
695 ButtType o_butt;
697 {
698 int jointype, captype;
700 jointype = i_style->stroke_linejoin.computed;
701 captype = i_style->stroke_linecap.computed;
702 o_width = i_style->stroke_width.computed;
704 switch (jointype) {
705 case SP_STROKE_LINEJOIN_MITER:
706 o_join = join_pointy;
707 break;
708 case SP_STROKE_LINEJOIN_ROUND:
709 o_join = join_round;
710 break;
711 default:
712 o_join = join_straight;
713 break;
714 }
716 switch (captype) {
717 case SP_STROKE_LINECAP_SQUARE:
718 o_butt = butt_square;
719 break;
720 case SP_STROKE_LINECAP_ROUND:
721 o_butt = butt_round;
722 break;
723 default:
724 o_butt = butt_straight;
725 break;
726 }
728 if (o_width < 0.1)
729 o_width = 0.1;
730 o_miter = i_style->stroke_miterlimit.value * o_width;
731 }
733 SPCurve *curvetemp = curve_for_item(item);
734 if (curvetemp == NULL) {
735 curve->unref();
736 continue;
737 }
738 // Livarots outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is created correctly.
739 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curvetemp->get_pathvector() );
740 curvetemp->unref();
742 Path *orig = new Path;
743 orig->LoadPathVector(pathv);
745 Path *res = new Path;
746 res->SetBackData(false);
748 if (i_style->stroke_dash.n_dash) {
749 // For dashed strokes, use Stroke method, because Outline can't do dashes
750 // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
752 orig->ConvertWithBackData(0.1);
754 orig->DashPolylineFromStyle(i_style, scale, 0);
756 Shape* theShape = new Shape;
757 orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
758 0.5 * o_miter);
759 orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
761 Shape *theRes = new Shape;
763 theRes->ConvertToShape(theShape, fill_positive);
765 Path *originaux[1];
766 originaux[0] = res;
767 theRes->ConvertToForme(orig, 1, originaux);
769 res->Coalesce(5.0);
771 delete theShape;
772 delete theRes;
774 } else {
776 orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
778 orig->Coalesce(0.5 * o_width);
780 Shape *theShape = new Shape;
781 Shape *theRes = new Shape;
783 res->ConvertWithBackData(1.0);
784 res->Fill(theShape, 0);
785 theRes->ConvertToShape(theShape, fill_positive);
787 Path *originaux[1];
788 originaux[0] = res;
789 theRes->ConvertToForme(orig, 1, originaux);
791 delete theShape;
792 delete theRes;
793 }
795 if (orig->descr_cmd.size() <= 1) {
796 // ca a merd\8e, ou bien le resultat est vide
797 delete res;
798 delete orig;
799 continue;
800 }
802 did = true;
804 // remember the position of the item
805 gint pos = SP_OBJECT_REPR(item)->position();
806 // remember parent
807 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
808 // remember id
809 char const *id = SP_OBJECT_REPR(item)->attribute("id");
810 // remember title
811 gchar *title = item->title();
812 // remember description
813 gchar *desc = item->desc();
815 if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
817 SPDocument * doc = sp_desktop_document(desktop);
818 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
819 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
821 // restore old style, but set old stroke style on fill
822 sp_repr_css_change(repr, ncss, "style");
824 sp_repr_css_attr_unref(ncss);
826 gchar *str = orig->svg_dump_path();
827 repr->setAttribute("d", str);
828 g_free(str);
830 if (mask)
831 repr->setAttribute("mask", mask);
832 if (clip_path)
833 repr->setAttribute("clip-path", clip_path);
835 if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
837 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
838 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
840 // add the group to the parent
841 parent->appendChild(g_repr);
842 // move to the saved position
843 g_repr->setPosition(pos > 0 ? pos : 0);
845 g_repr->appendChild(repr);
846 // restore title, description, id, transform
847 repr->setAttribute("id", id);
848 SPItem *newitem = (SPItem *) doc->getObjectByRepr(repr);
849 sp_item_write_transform(newitem, repr, transform);
850 if (title) {
851 newitem->setTitle(title);
852 }
853 if (desc) {
854 newitem->setDesc(desc);
855 }
857 SPShape *shape = SP_SHAPE(item);
859 Geom::PathVector const & pathv = curve->get_pathvector();
860 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
861 if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_START] ) {
862 Geom::Matrix const m (sp_shape_marker_get_transform_at_start(path_it->front()));
863 sp_selected_path_outline_add_marker( marker_obj, m,
864 Geom::Scale(i_style->stroke_width.computed), transform,
865 g_repr, xml_doc, doc );
866 }
868 SPObject *midmarker_obj = shape->marker[SP_MARKER_LOC_MID];
869 if ( midmarker_obj && (path_it->size_default() > 1) ) {
870 Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve
871 Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve
872 while (curve_it2 != path_it->end_default())
873 {
874 /* Put marker between curve_it1 and curve_it2.
875 * Loop to end_default (so including closing segment), because when a path is closed,
876 * there should be a midpoint marker between last segment and closing straight line segment
877 */
878 Geom::Matrix const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2));
879 sp_selected_path_outline_add_marker(midmarker_obj, m,
880 Geom::Scale(i_style->stroke_width.computed), transform,
881 g_repr, xml_doc, doc);
883 ++curve_it1;
884 ++curve_it2;
885 }
886 }
888 if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_END] ) {
889 /* Get reference to last curve in the path.
890 * For moveto-only path, this returns the "closing line segment". */
891 unsigned int index = path_it->size_default();
892 if (index > 0) {
893 index--;
894 }
895 Geom::Curve const &lastcurve = (*path_it)[index];
897 Geom::Matrix const m = sp_shape_marker_get_transform_at_end(lastcurve);
898 sp_selected_path_outline_add_marker( marker_obj, m,
899 Geom::Scale(i_style->stroke_width.computed), transform,
900 g_repr, xml_doc, doc );
901 }
902 }
904 selection->add(g_repr);
906 Inkscape::GC::release(g_repr);
909 } else {
911 // add the new repr to the parent
912 parent->appendChild(repr);
914 // move to the saved position
915 repr->setPosition(pos > 0 ? pos : 0);
917 // restore title, description, id, transform
918 repr->setAttribute("id", id);
920 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
921 sp_item_write_transform(newitem, repr, transform);
922 if (title) {
923 newitem->setTitle(title);
924 }
925 if (desc) {
926 newitem->setDesc(desc);
927 }
929 selection->add(repr);
931 }
933 Inkscape::GC::release(repr);
935 curve->unref();
936 selection->remove(item);
937 SP_OBJECT(item)->deleteObject(false);
939 }
940 if (title) g_free(title);
941 if (desc) g_free(desc);
943 delete res;
944 delete orig;
945 }
947 if (did) {
948 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE,
949 _("Convert stroke to path"));
950 } else {
951 // TRANSLATORS: "to outline" means "to convert stroke to path"
952 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
953 return;
954 }
955 }
958 void
959 sp_selected_path_offset(SPDesktop *desktop)
960 {
961 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
962 double prefOffset = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0);
964 sp_selected_path_do_offset(desktop, true, prefOffset);
965 }
966 void
967 sp_selected_path_inset(SPDesktop *desktop)
968 {
969 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
970 double prefOffset = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0);
972 sp_selected_path_do_offset(desktop, false, prefOffset);
973 }
975 void
976 sp_selected_path_offset_screen(SPDesktop *desktop, double pixels)
977 {
978 sp_selected_path_do_offset(desktop, true, pixels / desktop->current_zoom());
979 }
981 void
982 sp_selected_path_inset_screen(SPDesktop *desktop, double pixels)
983 {
984 sp_selected_path_do_offset(desktop, false, pixels / desktop->current_zoom());
985 }
988 void sp_selected_path_create_offset_object_zero(SPDesktop *desktop)
989 {
990 sp_selected_path_create_offset_object(desktop, 0, false);
991 }
993 void sp_selected_path_create_offset(SPDesktop *desktop)
994 {
995 sp_selected_path_create_offset_object(desktop, 1, false);
996 }
997 void sp_selected_path_create_inset(SPDesktop *desktop)
998 {
999 sp_selected_path_create_offset_object(desktop, -1, false);
1000 }
1002 void sp_selected_path_create_updating_offset_object_zero(SPDesktop *desktop)
1003 {
1004 sp_selected_path_create_offset_object(desktop, 0, true);
1005 }
1007 void sp_selected_path_create_updating_offset(SPDesktop *desktop)
1008 {
1009 sp_selected_path_create_offset_object(desktop, 1, true);
1010 }
1011 void sp_selected_path_create_updating_inset(SPDesktop *desktop)
1012 {
1013 sp_selected_path_create_offset_object(desktop, -1, true);
1014 }
1016 void
1017 sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool updating)
1018 {
1019 Inkscape::Selection *selection;
1020 Inkscape::XML::Node *repr;
1021 SPItem *item;
1022 SPCurve *curve;
1023 gchar *style, *str;
1024 float o_width, o_miter;
1025 JoinType o_join;
1026 ButtType o_butt;
1028 curve = NULL;
1030 selection = sp_desktop_selection(desktop);
1032 item = selection->singleItem();
1034 if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1035 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1036 return;
1037 }
1038 if (SP_IS_SHAPE(item))
1039 {
1040 curve = sp_shape_get_curve(SP_SHAPE(item));
1041 if (curve == NULL)
1042 return;
1043 }
1044 if (SP_IS_TEXT(item))
1045 {
1046 curve = SP_TEXT(item)->getNormalizedBpath();
1047 if (curve == NULL)
1048 return;
1049 }
1051 NR::Matrix const transform(item->transform);
1053 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1055 style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1057 // remember the position of the item
1058 gint pos = SP_OBJECT_REPR(item)->position();
1059 // remember parent
1060 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1062 {
1063 SPStyle *i_style = SP_OBJECT(item)->style;
1064 int jointype, captype;
1066 jointype = i_style->stroke_linejoin.value;
1067 captype = i_style->stroke_linecap.value;
1068 o_width = i_style->stroke_width.computed;
1069 if (jointype == SP_STROKE_LINEJOIN_MITER)
1070 {
1071 o_join = join_pointy;
1072 }
1073 else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1074 {
1075 o_join = join_round;
1076 }
1077 else
1078 {
1079 o_join = join_straight;
1080 }
1081 if (captype == SP_STROKE_LINECAP_SQUARE)
1082 {
1083 o_butt = butt_square;
1084 }
1085 else if (captype == SP_STROKE_LINECAP_ROUND)
1086 {
1087 o_butt = butt_round;
1088 }
1089 else
1090 {
1091 o_butt = butt_straight;
1092 }
1094 {
1095 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1096 o_width = prefs->getDouble("/options/defaultoffsetwidth/value", 1.0);
1097 }
1099 if (o_width < 0.01)
1100 o_width = 0.01;
1101 o_miter = i_style->stroke_miterlimit.value * o_width;
1102 }
1104 Path *orig = Path_for_item(item, true, false);
1105 if (orig == NULL)
1106 {
1107 g_free(style);
1108 curve->unref();
1109 return;
1110 }
1112 Path *res = new Path;
1113 res->SetBackData(false);
1115 {
1116 Shape *theShape = new Shape;
1117 Shape *theRes = new Shape;
1119 orig->ConvertWithBackData(1.0);
1120 orig->Fill(theShape, 0);
1122 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1123 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1124 if (val && strcmp(val, "nonzero") == 0)
1125 {
1126 theRes->ConvertToShape(theShape, fill_nonZero);
1127 }
1128 else if (val && strcmp(val, "evenodd") == 0)
1129 {
1130 theRes->ConvertToShape(theShape, fill_oddEven);
1131 }
1132 else
1133 {
1134 theRes->ConvertToShape(theShape, fill_nonZero);
1135 }
1137 Path *originaux[1];
1138 originaux[0] = orig;
1139 theRes->ConvertToForme(res, 1, originaux);
1141 delete theShape;
1142 delete theRes;
1143 }
1145 curve->unref();
1147 if (res->descr_cmd.size() <= 1)
1148 {
1149 // pas vraiment de points sur le resultat
1150 // donc il ne reste rien
1151 sp_document_done(sp_desktop_document(desktop),
1152 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1153 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1154 (updating ? _("Create linked offset")
1155 : _("Create dynamic offset")));
1156 selection->clear();
1158 delete res;
1159 delete orig;
1160 g_free(style);
1161 return;
1162 }
1164 {
1165 gchar tstr[80];
1167 tstr[79] = '\0';
1169 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1170 repr = xml_doc->createElement("svg:path");
1171 repr->setAttribute("sodipodi:type", "inkscape:offset");
1172 sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1173 ? o_width
1174 : expand < 0
1175 ? -o_width
1176 : 0 ));
1178 str = res->svg_dump_path();
1179 repr->setAttribute("inkscape:original", str);
1180 g_free(str);
1182 if ( updating ) {
1183 char const *id = SP_OBJECT(item)->repr->attribute("id");
1184 char const *uri = g_strdup_printf("#%s", id);
1185 repr->setAttribute("xlink:href", uri);
1186 g_free((void *) uri);
1187 } else {
1188 repr->setAttribute("inkscape:href", NULL);
1189 }
1191 repr->setAttribute("style", style);
1193 // add the new repr to the parent
1194 parent->appendChild(repr);
1196 // move to the saved position
1197 repr->setPosition(pos > 0 ? pos : 0);
1199 SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1201 if ( updating ) {
1202 // on conserve l'original
1203 // we reapply the transform to the original (offset will feel it)
1204 sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1205 } else {
1206 // delete original, apply the transform to the offset
1207 SP_OBJECT(item)->deleteObject(false);
1208 sp_item_write_transform(nitem, repr, transform);
1209 }
1211 // The object just created from a temporary repr is only a seed.
1212 // We need to invoke its write which will update its real repr (in particular adding d=)
1213 SP_OBJECT(nitem)->updateRepr();
1215 Inkscape::GC::release(repr);
1217 selection->set(nitem);
1218 }
1220 sp_document_done(sp_desktop_document(desktop),
1221 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1222 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1223 (updating ? _("Create linked offset")
1224 : _("Create dynamic offset")));
1226 delete res;
1227 delete orig;
1229 g_free(style);
1230 }
1243 void
1244 sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset)
1245 {
1246 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1248 if (selection->isEmpty()) {
1249 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1250 return;
1251 }
1253 bool did = false;
1255 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1256 items != NULL;
1257 items = items->next) {
1259 SPItem *item = (SPItem *) items->data;
1261 if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1262 continue;
1264 SPCurve *curve = NULL;
1265 if (SP_IS_SHAPE(item)) {
1266 curve = sp_shape_get_curve(SP_SHAPE(item));
1267 if (curve == NULL)
1268 continue;
1269 }
1270 if (SP_IS_TEXT(item)) {
1271 curve = SP_TEXT(item)->getNormalizedBpath();
1272 if (curve == NULL)
1273 continue;
1274 }
1276 NR::Matrix const transform(item->transform);
1278 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1280 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1282 float o_width, o_miter;
1283 JoinType o_join;
1284 ButtType o_butt;
1286 {
1287 SPStyle *i_style = SP_OBJECT(item)->style;
1288 int jointype, captype;
1290 jointype = i_style->stroke_linejoin.value;
1291 captype = i_style->stroke_linecap.value;
1292 o_width = i_style->stroke_width.computed;
1294 switch (jointype) {
1295 case SP_STROKE_LINEJOIN_MITER:
1296 o_join = join_pointy;
1297 break;
1298 case SP_STROKE_LINEJOIN_ROUND:
1299 o_join = join_round;
1300 break;
1301 default:
1302 o_join = join_straight;
1303 break;
1304 }
1306 switch (captype) {
1307 case SP_STROKE_LINECAP_SQUARE:
1308 o_butt = butt_square;
1309 break;
1310 case SP_STROKE_LINECAP_ROUND:
1311 o_butt = butt_round;
1312 break;
1313 default:
1314 o_butt = butt_straight;
1315 break;
1316 }
1318 o_width = prefOffset;
1320 if (o_width < 0.1)
1321 o_width = 0.1;
1322 o_miter = i_style->stroke_miterlimit.value * o_width;
1323 }
1325 Path *orig = Path_for_item(item, false);
1326 if (orig == NULL) {
1327 g_free(style);
1328 curve->unref();
1329 continue;
1330 }
1332 Path *res = new Path;
1333 res->SetBackData(false);
1335 {
1336 Shape *theShape = new Shape;
1337 Shape *theRes = new Shape;
1339 orig->ConvertWithBackData(0.03);
1340 orig->Fill(theShape, 0);
1342 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1343 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1344 if (val && strcmp(val, "nonzero") == 0)
1345 {
1346 theRes->ConvertToShape(theShape, fill_nonZero);
1347 }
1348 else if (val && strcmp(val, "evenodd") == 0)
1349 {
1350 theRes->ConvertToShape(theShape, fill_oddEven);
1351 }
1352 else
1353 {
1354 theRes->ConvertToShape(theShape, fill_nonZero);
1355 }
1357 // et maintenant: offset
1358 // methode inexacte
1359 /* Path *originaux[1];
1360 originaux[0] = orig;
1361 theRes->ConvertToForme(res, 1, originaux);
1363 if (expand) {
1364 res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1365 } else {
1366 res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1367 }
1369 orig->ConvertWithBackData(1.0);
1370 orig->Fill(theShape, 0);
1371 theRes->ConvertToShape(theShape, fill_positive);
1372 originaux[0] = orig;
1373 theRes->ConvertToForme(res, 1, originaux);
1375 if (o_width >= 0.5) {
1376 // res->Coalesce(1.0);
1377 res->ConvertEvenLines(1.0);
1378 res->Simplify(1.0);
1379 } else {
1380 // res->Coalesce(o_width);
1381 res->ConvertEvenLines(1.0*o_width);
1382 res->Simplify(1.0 * o_width);
1383 } */
1384 // methode par makeoffset
1386 if (expand)
1387 {
1388 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1389 }
1390 else
1391 {
1392 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1393 }
1394 theRes->ConvertToShape(theShape, fill_positive);
1396 res->Reset();
1397 theRes->ConvertToForme(res);
1399 if (o_width >= 1.0)
1400 {
1401 res->ConvertEvenLines(1.0);
1402 res->Simplify(1.0);
1403 }
1404 else
1405 {
1406 res->ConvertEvenLines(1.0*o_width);
1407 res->Simplify(1.0 * o_width);
1408 }
1410 delete theShape;
1411 delete theRes;
1412 }
1414 did = true;
1416 curve->unref();
1417 // remember the position of the item
1418 gint pos = SP_OBJECT_REPR(item)->position();
1419 // remember parent
1420 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1421 // remember id
1422 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1424 selection->remove(item);
1425 SP_OBJECT(item)->deleteObject(false);
1427 if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1429 gchar tstr[80];
1431 tstr[79] = '\0';
1433 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1434 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1436 repr->setAttribute("style", style);
1438 gchar *str = res->svg_dump_path();
1439 repr->setAttribute("d", str);
1440 g_free(str);
1442 // add the new repr to the parent
1443 parent->appendChild(repr);
1445 // move to the saved position
1446 repr->setPosition(pos > 0 ? pos : 0);
1448 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1450 // reapply the transform
1451 sp_item_write_transform(newitem, repr, transform);
1453 repr->setAttribute("id", id);
1455 selection->add(repr);
1457 Inkscape::GC::release(repr);
1458 }
1460 delete orig;
1461 delete res;
1462 }
1464 if (did) {
1465 sp_document_done(sp_desktop_document(desktop),
1466 (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1467 (expand ? _("Outset path") : _("Inset path")));
1468 } else {
1469 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1470 return;
1471 }
1472 }
1475 static bool
1476 sp_selected_path_simplify_items(SPDesktop *desktop,
1477 Inkscape::Selection *selection, GSList *items,
1478 float threshold, bool justCoalesce,
1479 float angleLimit, bool breakableAngles,
1480 bool modifySelection);
1483 //return true if we changed something, else false
1484 bool
1485 sp_selected_path_simplify_item(SPDesktop *desktop,
1486 Inkscape::Selection *selection, SPItem *item,
1487 float threshold, bool justCoalesce,
1488 float angleLimit, bool breakableAngles,
1489 gdouble size, bool modifySelection)
1490 {
1491 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1492 return false;
1494 //If this is a group, do the children instead
1495 if (SP_IS_GROUP(item)) {
1496 GSList *items = sp_item_group_item_list(SP_GROUP(item));
1498 return sp_selected_path_simplify_items(desktop, selection, items,
1499 threshold, justCoalesce,
1500 angleLimit, breakableAngles,
1501 false);
1502 }
1505 SPCurve *curve = NULL;
1507 if (SP_IS_SHAPE(item)) {
1508 curve = sp_shape_get_curve(SP_SHAPE(item));
1509 if (!curve)
1510 return false;
1511 }
1513 if (SP_IS_TEXT(item)) {
1514 curve = SP_TEXT(item)->getNormalizedBpath();
1515 if (!curve)
1516 return false;
1517 }
1519 // save the transform, to re-apply it after simplification
1520 NR::Matrix const transform(item->transform);
1522 /*
1523 reset the transform, effectively transforming the item by transform.inverse();
1524 this is necessary so that the item is transformed twice back and forth,
1525 allowing all compensations to cancel out regardless of the preferences
1526 */
1527 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1529 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1530 gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1531 gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1533 Path *orig = Path_for_item(item, false);
1534 if (orig == NULL) {
1535 g_free(style);
1536 curve->unref();
1537 return false;
1538 }
1540 curve->unref();
1541 // remember the position of the item
1542 gint pos = SP_OBJECT_REPR(item)->position();
1543 // remember parent
1544 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1545 // remember id
1546 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1547 // remember path effect
1548 char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1549 // remember title
1550 gchar *title = item->title();
1551 // remember description
1552 gchar *desc = item->desc();
1554 //If a group was selected, to not change the selection list
1555 if (modifySelection)
1556 selection->remove(item);
1558 SP_OBJECT(item)->deleteObject(false);
1560 if ( justCoalesce ) {
1561 orig->Coalesce(threshold * size);
1562 } else {
1563 orig->ConvertEvenLines(threshold * size);
1564 orig->Simplify(threshold * size);
1565 }
1567 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1568 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1570 // restore style, mask and clip-path
1571 repr->setAttribute("style", style);
1572 g_free(style);
1574 if ( mask ) {
1575 repr->setAttribute("mask", mask);
1576 g_free(mask);
1577 }
1579 if ( clip_path ) {
1580 repr->setAttribute("clip-path", clip_path);
1581 g_free(clip_path);
1582 }
1584 // path
1585 gchar *str = orig->svg_dump_path();
1586 if (patheffect)
1587 repr->setAttribute("inkscape:original-d", str);
1588 else
1589 repr->setAttribute("d", str);
1590 g_free(str);
1592 // restore id
1593 repr->setAttribute("id", id);
1595 // add the new repr to the parent
1596 parent->appendChild(repr);
1598 // move to the saved position
1599 repr->setPosition(pos > 0 ? pos : 0);
1601 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1603 // reapply the transform
1604 sp_item_write_transform(newitem, repr, transform);
1606 // restore path effect
1607 repr->setAttribute("inkscape:path-effect", patheffect);
1609 // restore title & description
1610 if (title) {
1611 newitem->setTitle(title);
1612 g_free(title);
1613 }
1614 if (desc) {
1615 newitem->setDesc(desc);
1616 g_free(desc);
1617 }
1619 //If we are not in a selected group
1620 if (modifySelection)
1621 selection->add(repr);
1623 Inkscape::GC::release(repr);
1625 // clean up
1626 if (orig) delete orig;
1628 return true;
1629 }
1632 bool
1633 sp_selected_path_simplify_items(SPDesktop *desktop,
1634 Inkscape::Selection *selection, GSList *items,
1635 float threshold, bool justCoalesce,
1636 float angleLimit, bool breakableAngles,
1637 bool modifySelection)
1638 {
1639 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1640 bool simplifyIndividualPaths = prefs->getBool("/options/simplifyindividualpaths/value");
1642 gchar *simplificationType;
1643 if (simplifyIndividualPaths) {
1644 simplificationType = _("Simplifying paths (separately):");
1645 } else {
1646 simplificationType = _("Simplifying paths:");
1647 }
1649 bool didSomething = false;
1651 boost::optional<Geom::Rect> selectionBbox = selection->bounds();
1652 if (!selectionBbox) {
1653 return false;
1654 }
1655 gdouble selectionSize = L2(selectionBbox->dimensions());
1657 gdouble simplifySize = selectionSize;
1659 int pathsSimplified = 0;
1660 int totalPathCount = g_slist_length(items);
1662 // set "busy" cursor
1663 desktop->setWaitingCursor();
1665 for (; items != NULL; items = items->next) {
1666 SPItem *item = (SPItem *) items->data;
1668 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1669 continue;
1671 if (simplifyIndividualPaths) {
1672 boost::optional<Geom::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));
1673 if (itemBbox) {
1674 simplifySize = L2(itemBbox->dimensions());
1675 } else {
1676 simplifySize = 0;
1677 }
1678 }
1680 pathsSimplified++;
1682 if (pathsSimplified % 20 == 0) {
1683 gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."),
1684 simplificationType, pathsSimplified, totalPathCount);
1685 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1686 }
1688 didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1689 threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1690 }
1692 desktop->clearWaitingCursor();
1694 if (pathsSimplified > 20) {
1695 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1696 }
1698 return didSomething;
1699 }
1701 void
1702 sp_selected_path_simplify_selection(SPDesktop *desktop, float threshold, bool justCoalesce,
1703 float angleLimit, bool breakableAngles)
1704 {
1705 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1707 if (selection->isEmpty()) {
1708 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1709 _("Select <b>path(s)</b> to simplify."));
1710 return;
1711 }
1713 GSList *items = g_slist_copy((GSList *) selection->itemList());
1715 bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1716 items, threshold,
1717 justCoalesce,
1718 angleLimit,
1719 breakableAngles, true);
1721 if (didSomething)
1722 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY,
1723 _("Simplify"));
1724 else
1725 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1727 }
1730 // globals for keeping track of accelerated simplify
1731 static double previousTime = 0.0;
1732 static gdouble simplifyMultiply = 1.0;
1734 void
1735 sp_selected_path_simplify(SPDesktop *desktop)
1736 {
1737 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1738 gdouble simplifyThreshold =
1739 prefs->getDouble("/options/simplifythreshold/value", 0.003);
1740 bool simplifyJustCoalesce = prefs->getBool("/options/simplifyjustcoalesce/value", 0);
1742 //Get the current time
1743 GTimeVal currentTimeVal;
1744 g_get_current_time(¤tTimeVal);
1745 double currentTime = currentTimeVal.tv_sec * 1000000 +
1746 currentTimeVal.tv_usec;
1748 //Was the previous call to this function recent? (<0.5 sec)
1749 if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1751 // add to the threshold 1/2 of its original value
1752 simplifyMultiply += 0.5;
1753 simplifyThreshold *= simplifyMultiply;
1755 } else {
1756 // reset to the default
1757 simplifyMultiply = 1;
1758 }
1760 //remember time for next call
1761 previousTime = currentTime;
1763 //g_print("%g\n", simplify_threshold);
1765 //Make the actual call
1766 sp_selected_path_simplify_selection(desktop, simplifyThreshold,
1767 simplifyJustCoalesce, 0.0, false);
1768 }
1772 // fonctions utilitaires
1774 bool
1775 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1776 {
1777 if (who == NULL || a == NULL)
1778 return false;
1779 if (who == a)
1780 return true;
1781 return Ancetre(sp_repr_parent(a), who);
1782 }
1784 Path *
1785 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1786 {
1787 SPCurve *curve = curve_for_item(item);
1789 if (curve == NULL)
1790 return NULL;
1792 Geom::PathVector *pathv = pathvector_for_curve(item, curve, doTransformation, transformFull, Geom::identity(), Geom::identity());
1793 curve->unref();
1795 Path *dest = new Path;
1796 dest->LoadPathVector(*pathv);
1797 delete pathv;
1799 return dest;
1800 }
1802 /*
1803 * NOTE: Returns empty pathvector if curve == NULL
1804 * TODO: see if calling this method can be optimized. All the pathvector copying might be slow.
1805 */
1806 Geom::PathVector*
1807 pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, Geom::Matrix extraPreAffine, Geom::Matrix extraPostAffine)
1808 {
1809 if (curve == NULL)
1810 return NULL;
1812 Geom::PathVector *dest = new Geom::PathVector;
1813 *dest = curve->get_pathvector(); // Make a copy; must be freed by the caller!
1815 if (doTransformation) {
1816 if (transformFull) {
1817 *dest *= extraPreAffine * sp_item_i2doc_affine(item) * extraPostAffine;
1818 } else {
1819 *dest *= extraPreAffine * (Geom::Matrix)item->transform * extraPostAffine;
1820 }
1821 } else {
1822 *dest *= extraPreAffine * extraPostAffine;
1823 }
1825 return dest;
1826 }
1828 SPCurve* curve_for_item(SPItem *item)
1829 {
1830 if (!item)
1831 return NULL;
1833 SPCurve *curve = NULL;
1834 if (SP_IS_SHAPE(item)) {
1835 if (SP_IS_PATH(item)) {
1836 curve = sp_path_get_curve_for_edit(SP_PATH(item));
1837 } else {
1838 curve = sp_shape_get_curve(SP_SHAPE(item));
1839 }
1840 }
1841 else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1842 {
1843 curve = te_get_layout(item)->convertToCurves();
1844 }
1845 else if (SP_IS_IMAGE(item))
1846 {
1847 curve = sp_image_get_curve(SP_IMAGE(item));
1848 }
1850 return curve; // do not forget to unref the curve at some point!
1851 }
1853 boost::optional<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1854 {
1855 //get nearest position on path
1856 Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1857 return pos;
1858 }
1860 NR::Point get_point_on_Path(Path *path, int piece, double t)
1861 {
1862 NR::Point p;
1863 path->PointAt(piece, t, p);
1864 return p;
1865 }
1868 /*
1869 Local Variables:
1870 mode:c++
1871 c-file-style:"stroustrup"
1872 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1873 indent-tabs-mode:nil
1874 fill-column:99
1875 End:
1876 */
1877 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :