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 "prefs-utils.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, NR::expansion(i2root));
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, NR::scale stroke_scale, NR::Matrix transform,
605 Inkscape::XML::Node *g_repr, Inkscape::XML::Document *xml_doc, SPDocument * doc )
606 {
607 SPMarker* marker = SP_MARKER (marker_object);
608 SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker_object));
610 NR::Matrix tr(marker_transform);
612 if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
613 tr = stroke_scale * tr;
614 }
616 // total marker transform
617 tr = marker_item->transform * marker->c2p * tr * transform;
619 if (SP_OBJECT_REPR(marker_item)) {
620 Inkscape::XML::Node *m_repr = SP_OBJECT_REPR(marker_item)->duplicate(xml_doc);
621 g_repr->appendChild(m_repr);
622 SPItem *marker_item = (SPItem *) doc->getObjectByRepr(m_repr);
623 sp_item_write_transform(marker_item, m_repr, tr);
624 }
625 }
627 void
628 sp_selected_path_outline(SPDesktop *desktop)
629 {
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 if (!SP_OBJECT_STYLE(item) || SP_OBJECT_STYLE(item)->stroke.noneSet) {
662 curve->unref();
663 continue;
664 }
666 // remember old stroke style, to be set on fill
667 SPStyle *i_style = SP_OBJECT_STYLE(item);
668 SPCSSAttr *ncss;
669 {
670 ncss = sp_css_attr_from_style(i_style, SP_STYLE_FLAG_ALWAYS);
671 gchar const *s_val = sp_repr_css_property(ncss, "stroke", NULL);
672 gchar const *s_opac = sp_repr_css_property(ncss, "stroke-opacity", NULL);
674 sp_repr_css_set_property(ncss, "stroke", "none");
675 sp_repr_css_set_property(ncss, "stroke-opacity", "1.0");
676 sp_repr_css_set_property(ncss, "fill", s_val);
677 if ( s_opac ) {
678 sp_repr_css_set_property(ncss, "fill-opacity", s_opac);
679 } else {
680 sp_repr_css_set_property(ncss, "fill-opacity", "1.0");
681 }
682 sp_repr_css_unset_property(ncss, "marker-start");
683 sp_repr_css_unset_property(ncss, "marker-mid");
684 sp_repr_css_unset_property(ncss, "marker-end");
685 }
687 NR::Matrix const transform(item->transform);
688 float const scale = NR::expansion(transform);
689 gchar const *mask = SP_OBJECT_REPR(item)->attribute("mask");
690 gchar const *clip_path = SP_OBJECT_REPR(item)->attribute("clip-path");
692 float o_width, o_miter;
693 JoinType o_join;
694 ButtType o_butt;
696 {
697 int jointype, captype;
699 jointype = i_style->stroke_linejoin.computed;
700 captype = i_style->stroke_linecap.computed;
701 o_width = i_style->stroke_width.computed;
703 switch (jointype) {
704 case SP_STROKE_LINEJOIN_MITER:
705 o_join = join_pointy;
706 break;
707 case SP_STROKE_LINEJOIN_ROUND:
708 o_join = join_round;
709 break;
710 default:
711 o_join = join_straight;
712 break;
713 }
715 switch (captype) {
716 case SP_STROKE_LINECAP_SQUARE:
717 o_butt = butt_square;
718 break;
719 case SP_STROKE_LINECAP_ROUND:
720 o_butt = butt_round;
721 break;
722 default:
723 o_butt = butt_straight;
724 break;
725 }
727 if (o_width < 0.1)
728 o_width = 0.1;
729 o_miter = i_style->stroke_miterlimit.value * o_width;
730 }
732 SPCurve *curvetemp = curve_for_item(item);
733 if (curvetemp == NULL) {
734 curve->unref();
735 continue;
736 }
737 // Livarots outline of arcs is broken. So convert the path to linear and cubics only, for which the outline is created correctly.
738 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curvetemp->get_pathvector() );
739 curvetemp->unref();
741 Path *orig = new Path;
742 orig->LoadPathVector(pathv);
744 Path *res = new Path;
745 res->SetBackData(false);
747 if (i_style->stroke_dash.n_dash) {
748 // For dashed strokes, use Stroke method, because Outline can't do dashes
749 // However Stroke adds lots of extra nodes _or_ makes the path crooked, so consider this a temporary workaround
751 orig->ConvertWithBackData(0.1);
753 orig->DashPolylineFromStyle(i_style, scale, 0);
755 Shape* theShape = new Shape;
756 orig->Stroke(theShape, false, 0.5*o_width, o_join, o_butt,
757 0.5 * o_miter);
758 orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
760 Shape *theRes = new Shape;
762 theRes->ConvertToShape(theShape, fill_positive);
764 Path *originaux[1];
765 originaux[0] = res;
766 theRes->ConvertToForme(orig, 1, originaux);
768 res->Coalesce(5.0);
770 delete theShape;
771 delete theRes;
773 } else {
775 orig->Outline(res, 0.5 * o_width, o_join, o_butt, 0.5 * o_miter);
777 orig->Coalesce(0.5 * o_width);
779 Shape *theShape = new Shape;
780 Shape *theRes = new Shape;
782 res->ConvertWithBackData(1.0);
783 res->Fill(theShape, 0);
784 theRes->ConvertToShape(theShape, fill_positive);
786 Path *originaux[1];
787 originaux[0] = res;
788 theRes->ConvertToForme(orig, 1, originaux);
790 delete theShape;
791 delete theRes;
792 }
794 if (orig->descr_cmd.size() <= 1) {
795 // ca a merd\8e, ou bien le resultat est vide
796 delete res;
797 delete orig;
798 continue;
799 }
801 did = true;
803 // remember the position of the item
804 gint pos = SP_OBJECT_REPR(item)->position();
805 // remember parent
806 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
807 // remember id
808 char const *id = SP_OBJECT_REPR(item)->attribute("id");
809 // remember title
810 gchar *title = item->title();
811 // remember description
812 gchar *desc = item->desc();
814 if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
816 SPDocument * doc = sp_desktop_document(desktop);
817 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
818 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
820 // restore old style, but set old stroke style on fill
821 sp_repr_css_change(repr, ncss, "style");
823 sp_repr_css_attr_unref(ncss);
825 gchar *str = orig->svg_dump_path();
826 repr->setAttribute("d", str);
827 g_free(str);
829 if (mask)
830 repr->setAttribute("mask", mask);
831 if (clip_path)
832 repr->setAttribute("clip-path", clip_path);
834 if (SP_IS_SHAPE(item) && sp_shape_has_markers (SP_SHAPE(item))) {
836 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
837 Inkscape::XML::Node *g_repr = xml_doc->createElement("svg:g");
839 // add the group to the parent
840 parent->appendChild(g_repr);
841 // move to the saved position
842 g_repr->setPosition(pos > 0 ? pos : 0);
844 g_repr->appendChild(repr);
845 // restore title, description, id, transform
846 repr->setAttribute("id", id);
847 SPItem *newitem = (SPItem *) doc->getObjectByRepr(repr);
848 sp_item_write_transform(newitem, repr, transform);
849 if (title) {
850 newitem->setTitle(title);
851 }
852 if (desc) {
853 newitem->setDesc(desc);
854 }
856 SPShape *shape = SP_SHAPE(item);
858 Geom::PathVector const & pathv = curve->get_pathvector();
859 for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
860 if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_START] ) {
861 Geom::Matrix const m (sp_shape_marker_get_transform_at_start(path_it->front()));
862 sp_selected_path_outline_add_marker( marker_obj, m,
863 NR::scale(i_style->stroke_width.computed), transform,
864 g_repr, xml_doc, doc );
865 }
867 SPObject *midmarker_obj = shape->marker[SP_MARKER_LOC_MID];
868 if ( midmarker_obj && (path_it->size_default() > 1) ) {
869 Geom::Path::const_iterator curve_it1 = path_it->begin(); // incoming curve
870 Geom::Path::const_iterator curve_it2 = ++(path_it->begin()); // outgoing curve
871 while (curve_it2 != path_it->end_default())
872 {
873 /* Put marker between curve_it1 and curve_it2.
874 * Loop to end_default (so including closing segment), because when a path is closed,
875 * there should be a midpoint marker between last segment and closing straight line segment
876 */
877 Geom::Matrix const m (sp_shape_marker_get_transform(*curve_it1, *curve_it2));
878 sp_selected_path_outline_add_marker( midmarker_obj, m,
879 NR::scale(i_style->stroke_width.computed), transform,
880 g_repr, xml_doc, doc );
882 ++curve_it1;
883 ++curve_it2;
884 }
885 }
887 if ( SPObject *marker_obj = shape->marker[SP_MARKER_LOC_END] ) {
888 /* Get reference to last curve in the path.
889 * For moveto-only path, this returns the "closing line segment". */
890 unsigned int index = path_it->size_default();
891 if (index > 0) {
892 index--;
893 }
894 Geom::Curve const &lastcurve = (*path_it)[index];
896 Geom::Matrix const m = sp_shape_marker_get_transform_at_end(lastcurve);
897 sp_selected_path_outline_add_marker( marker_obj, m,
898 NR::scale(i_style->stroke_width.computed), transform,
899 g_repr, xml_doc, doc );
900 }
901 }
903 selection->add(g_repr);
905 Inkscape::GC::release(g_repr);
908 } else {
910 // add the new repr to the parent
911 parent->appendChild(repr);
913 // move to the saved position
914 repr->setPosition(pos > 0 ? pos : 0);
916 // restore title, description, id, transform
917 repr->setAttribute("id", id);
919 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
920 sp_item_write_transform(newitem, repr, transform);
921 if (title) {
922 newitem->setTitle(title);
923 }
924 if (desc) {
925 newitem->setDesc(desc);
926 }
928 selection->add(repr);
930 }
932 Inkscape::GC::release(repr);
934 curve->unref();
935 selection->remove(item);
936 SP_OBJECT(item)->deleteObject(false);
938 }
939 if (title) g_free(title);
940 if (desc) g_free(desc);
942 delete res;
943 delete orig;
944 }
946 if (did) {
947 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_OUTLINE,
948 _("Convert stroke to path"));
949 } else {
950 // TRANSLATORS: "to outline" means "to convert stroke to path"
951 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No stroked paths</b> in the selection."));
952 return;
953 }
954 }
957 void
958 sp_selected_path_offset(SPDesktop *desktop)
959 {
960 double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
962 sp_selected_path_do_offset(desktop, true, prefOffset);
963 }
964 void
965 sp_selected_path_inset(SPDesktop *desktop)
966 {
967 double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
969 sp_selected_path_do_offset(desktop, false, prefOffset);
970 }
972 void
973 sp_selected_path_offset_screen(SPDesktop *desktop, double pixels)
974 {
975 sp_selected_path_do_offset(desktop, true, pixels / desktop->current_zoom());
976 }
978 void
979 sp_selected_path_inset_screen(SPDesktop *desktop, double pixels)
980 {
981 sp_selected_path_do_offset(desktop, false, pixels / desktop->current_zoom());
982 }
985 void sp_selected_path_create_offset_object_zero(SPDesktop *desktop)
986 {
987 sp_selected_path_create_offset_object(desktop, 0, false);
988 }
990 void sp_selected_path_create_offset(SPDesktop *desktop)
991 {
992 sp_selected_path_create_offset_object(desktop, 1, false);
993 }
994 void sp_selected_path_create_inset(SPDesktop *desktop)
995 {
996 sp_selected_path_create_offset_object(desktop, -1, false);
997 }
999 void sp_selected_path_create_updating_offset_object_zero(SPDesktop *desktop)
1000 {
1001 sp_selected_path_create_offset_object(desktop, 0, true);
1002 }
1004 void sp_selected_path_create_updating_offset(SPDesktop *desktop)
1005 {
1006 sp_selected_path_create_offset_object(desktop, 1, true);
1007 }
1008 void sp_selected_path_create_updating_inset(SPDesktop *desktop)
1009 {
1010 sp_selected_path_create_offset_object(desktop, -1, true);
1011 }
1013 void
1014 sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool updating)
1015 {
1016 Inkscape::Selection *selection;
1017 Inkscape::XML::Node *repr;
1018 SPItem *item;
1019 SPCurve *curve;
1020 gchar *style, *str;
1021 float o_width, o_miter;
1022 JoinType o_join;
1023 ButtType o_butt;
1025 curve = NULL;
1027 selection = sp_desktop_selection(desktop);
1029 item = selection->singleItem();
1031 if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1032 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1033 return;
1034 }
1035 if (SP_IS_SHAPE(item))
1036 {
1037 curve = sp_shape_get_curve(SP_SHAPE(item));
1038 if (curve == NULL)
1039 return;
1040 }
1041 if (SP_IS_TEXT(item))
1042 {
1043 curve = SP_TEXT(item)->getNormalizedBpath();
1044 if (curve == NULL)
1045 return;
1046 }
1048 NR::Matrix const transform(item->transform);
1050 sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1052 style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1054 // remember the position of the item
1055 gint pos = SP_OBJECT_REPR(item)->position();
1056 // remember parent
1057 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1059 {
1060 SPStyle *i_style = SP_OBJECT(item)->style;
1061 int jointype, captype;
1063 jointype = i_style->stroke_linejoin.value;
1064 captype = i_style->stroke_linecap.value;
1065 o_width = i_style->stroke_width.computed;
1066 if (jointype == SP_STROKE_LINEJOIN_MITER)
1067 {
1068 o_join = join_pointy;
1069 }
1070 else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1071 {
1072 o_join = join_round;
1073 }
1074 else
1075 {
1076 o_join = join_straight;
1077 }
1078 if (captype == SP_STROKE_LINECAP_SQUARE)
1079 {
1080 o_butt = butt_square;
1081 }
1082 else if (captype == SP_STROKE_LINECAP_ROUND)
1083 {
1084 o_butt = butt_round;
1085 }
1086 else
1087 {
1088 o_butt = butt_straight;
1089 }
1091 {
1092 double prefOffset = 1.0;
1093 prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1094 o_width = prefOffset;
1095 }
1097 if (o_width < 0.01)
1098 o_width = 0.01;
1099 o_miter = i_style->stroke_miterlimit.value * o_width;
1100 }
1102 Path *orig = Path_for_item(item, true, false);
1103 if (orig == NULL)
1104 {
1105 g_free(style);
1106 curve->unref();
1107 return;
1108 }
1110 Path *res = new Path;
1111 res->SetBackData(false);
1113 {
1114 Shape *theShape = new Shape;
1115 Shape *theRes = new Shape;
1117 orig->ConvertWithBackData(1.0);
1118 orig->Fill(theShape, 0);
1120 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1121 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1122 if (val && strcmp(val, "nonzero") == 0)
1123 {
1124 theRes->ConvertToShape(theShape, fill_nonZero);
1125 }
1126 else if (val && strcmp(val, "evenodd") == 0)
1127 {
1128 theRes->ConvertToShape(theShape, fill_oddEven);
1129 }
1130 else
1131 {
1132 theRes->ConvertToShape(theShape, fill_nonZero);
1133 }
1135 Path *originaux[1];
1136 originaux[0] = orig;
1137 theRes->ConvertToForme(res, 1, originaux);
1139 delete theShape;
1140 delete theRes;
1141 }
1143 curve->unref();
1145 if (res->descr_cmd.size() <= 1)
1146 {
1147 // pas vraiment de points sur le resultat
1148 // donc il ne reste rien
1149 sp_document_done(sp_desktop_document(desktop),
1150 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1151 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1152 (updating ? _("Create linked offset")
1153 : _("Create dynamic offset")));
1154 selection->clear();
1156 delete res;
1157 delete orig;
1158 g_free(style);
1159 return;
1160 }
1162 {
1163 gchar tstr[80];
1165 tstr[79] = '\0';
1167 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1168 repr = xml_doc->createElement("svg:path");
1169 repr->setAttribute("sodipodi:type", "inkscape:offset");
1170 sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1171 ? o_width
1172 : expand < 0
1173 ? -o_width
1174 : 0 ));
1176 str = res->svg_dump_path();
1177 repr->setAttribute("inkscape:original", str);
1178 g_free(str);
1180 if ( updating ) {
1181 char const *id = SP_OBJECT(item)->repr->attribute("id");
1182 char const *uri = g_strdup_printf("#%s", id);
1183 repr->setAttribute("xlink:href", uri);
1184 g_free((void *) uri);
1185 } else {
1186 repr->setAttribute("inkscape:href", NULL);
1187 }
1189 repr->setAttribute("style", style);
1191 // add the new repr to the parent
1192 parent->appendChild(repr);
1194 // move to the saved position
1195 repr->setPosition(pos > 0 ? pos : 0);
1197 SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1199 if ( updating ) {
1200 // on conserve l'original
1201 // we reapply the transform to the original (offset will feel it)
1202 sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1203 } else {
1204 // delete original, apply the transform to the offset
1205 SP_OBJECT(item)->deleteObject(false);
1206 sp_item_write_transform(nitem, repr, transform);
1207 }
1209 // The object just created from a temporary repr is only a seed.
1210 // We need to invoke its write which will update its real repr (in particular adding d=)
1211 SP_OBJECT(nitem)->updateRepr();
1213 Inkscape::GC::release(repr);
1215 selection->set(nitem);
1216 }
1218 sp_document_done(sp_desktop_document(desktop),
1219 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1220 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1221 (updating ? _("Create linked offset")
1222 : _("Create dynamic offset")));
1224 delete res;
1225 delete orig;
1227 g_free(style);
1228 }
1241 void
1242 sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset)
1243 {
1244 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1246 if (selection->isEmpty()) {
1247 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1248 return;
1249 }
1251 bool did = false;
1253 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1254 items != NULL;
1255 items = items->next) {
1257 SPItem *item = (SPItem *) items->data;
1259 if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1260 continue;
1262 SPCurve *curve = NULL;
1263 if (SP_IS_SHAPE(item)) {
1264 curve = sp_shape_get_curve(SP_SHAPE(item));
1265 if (curve == NULL)
1266 continue;
1267 }
1268 if (SP_IS_TEXT(item)) {
1269 curve = SP_TEXT(item)->getNormalizedBpath();
1270 if (curve == NULL)
1271 continue;
1272 }
1274 NR::Matrix const transform(item->transform);
1276 sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1278 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1280 float o_width, o_miter;
1281 JoinType o_join;
1282 ButtType o_butt;
1284 {
1285 SPStyle *i_style = SP_OBJECT(item)->style;
1286 int jointype, captype;
1288 jointype = i_style->stroke_linejoin.value;
1289 captype = i_style->stroke_linecap.value;
1290 o_width = i_style->stroke_width.computed;
1292 switch (jointype) {
1293 case SP_STROKE_LINEJOIN_MITER:
1294 o_join = join_pointy;
1295 break;
1296 case SP_STROKE_LINEJOIN_ROUND:
1297 o_join = join_round;
1298 break;
1299 default:
1300 o_join = join_straight;
1301 break;
1302 }
1304 switch (captype) {
1305 case SP_STROKE_LINECAP_SQUARE:
1306 o_butt = butt_square;
1307 break;
1308 case SP_STROKE_LINECAP_ROUND:
1309 o_butt = butt_round;
1310 break;
1311 default:
1312 o_butt = butt_straight;
1313 break;
1314 }
1316 o_width = prefOffset;
1318 if (o_width < 0.1)
1319 o_width = 0.1;
1320 o_miter = i_style->stroke_miterlimit.value * o_width;
1321 }
1323 Path *orig = Path_for_item(item, false);
1324 if (orig == NULL) {
1325 g_free(style);
1326 curve->unref();
1327 continue;
1328 }
1330 Path *res = new Path;
1331 res->SetBackData(false);
1333 {
1334 Shape *theShape = new Shape;
1335 Shape *theRes = new Shape;
1337 orig->ConvertWithBackData(0.03);
1338 orig->Fill(theShape, 0);
1340 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1341 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1342 if (val && strcmp(val, "nonzero") == 0)
1343 {
1344 theRes->ConvertToShape(theShape, fill_nonZero);
1345 }
1346 else if (val && strcmp(val, "evenodd") == 0)
1347 {
1348 theRes->ConvertToShape(theShape, fill_oddEven);
1349 }
1350 else
1351 {
1352 theRes->ConvertToShape(theShape, fill_nonZero);
1353 }
1355 // et maintenant: offset
1356 // methode inexacte
1357 /* Path *originaux[1];
1358 originaux[0] = orig;
1359 theRes->ConvertToForme(res, 1, originaux);
1361 if (expand) {
1362 res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1363 } else {
1364 res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1365 }
1367 orig->ConvertWithBackData(1.0);
1368 orig->Fill(theShape, 0);
1369 theRes->ConvertToShape(theShape, fill_positive);
1370 originaux[0] = orig;
1371 theRes->ConvertToForme(res, 1, originaux);
1373 if (o_width >= 0.5) {
1374 // res->Coalesce(1.0);
1375 res->ConvertEvenLines(1.0);
1376 res->Simplify(1.0);
1377 } else {
1378 // res->Coalesce(o_width);
1379 res->ConvertEvenLines(1.0*o_width);
1380 res->Simplify(1.0 * o_width);
1381 } */
1382 // methode par makeoffset
1384 if (expand)
1385 {
1386 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1387 }
1388 else
1389 {
1390 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1391 }
1392 theRes->ConvertToShape(theShape, fill_positive);
1394 res->Reset();
1395 theRes->ConvertToForme(res);
1397 if (o_width >= 1.0)
1398 {
1399 res->ConvertEvenLines(1.0);
1400 res->Simplify(1.0);
1401 }
1402 else
1403 {
1404 res->ConvertEvenLines(1.0*o_width);
1405 res->Simplify(1.0 * o_width);
1406 }
1408 delete theShape;
1409 delete theRes;
1410 }
1412 did = true;
1414 curve->unref();
1415 // remember the position of the item
1416 gint pos = SP_OBJECT_REPR(item)->position();
1417 // remember parent
1418 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1419 // remember id
1420 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1422 selection->remove(item);
1423 SP_OBJECT(item)->deleteObject(false);
1425 if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1427 gchar tstr[80];
1429 tstr[79] = '\0';
1431 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1432 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1434 repr->setAttribute("style", style);
1436 gchar *str = res->svg_dump_path();
1437 repr->setAttribute("d", str);
1438 g_free(str);
1440 // add the new repr to the parent
1441 parent->appendChild(repr);
1443 // move to the saved position
1444 repr->setPosition(pos > 0 ? pos : 0);
1446 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1448 // reapply the transform
1449 sp_item_write_transform(newitem, repr, transform);
1451 repr->setAttribute("id", id);
1453 selection->add(repr);
1455 Inkscape::GC::release(repr);
1456 }
1458 delete orig;
1459 delete res;
1460 }
1462 if (did) {
1463 sp_document_done(sp_desktop_document(desktop),
1464 (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1465 (expand ? _("Outset path") : _("Inset path")));
1466 } else {
1467 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1468 return;
1469 }
1470 }
1473 static bool
1474 sp_selected_path_simplify_items(SPDesktop *desktop,
1475 Inkscape::Selection *selection, GSList *items,
1476 float threshold, bool justCoalesce,
1477 float angleLimit, bool breakableAngles,
1478 bool modifySelection);
1481 //return true if we changed something, else false
1482 bool
1483 sp_selected_path_simplify_item(SPDesktop *desktop,
1484 Inkscape::Selection *selection, SPItem *item,
1485 float threshold, bool justCoalesce,
1486 float angleLimit, bool breakableAngles,
1487 gdouble size, bool modifySelection)
1488 {
1489 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1490 return false;
1492 //If this is a group, do the children instead
1493 if (SP_IS_GROUP(item)) {
1494 GSList *items = sp_item_group_item_list(SP_GROUP(item));
1496 return sp_selected_path_simplify_items(desktop, selection, items,
1497 threshold, justCoalesce,
1498 angleLimit, breakableAngles,
1499 false);
1500 }
1503 SPCurve *curve = NULL;
1505 if (SP_IS_SHAPE(item)) {
1506 curve = sp_shape_get_curve(SP_SHAPE(item));
1507 if (!curve)
1508 return false;
1509 }
1511 if (SP_IS_TEXT(item)) {
1512 curve = SP_TEXT(item)->getNormalizedBpath();
1513 if (!curve)
1514 return false;
1515 }
1517 // save the transform, to re-apply it after simplification
1518 NR::Matrix const transform(item->transform);
1520 /*
1521 reset the transform, effectively transforming the item by transform.inverse();
1522 this is necessary so that the item is transformed twice back and forth,
1523 allowing all compensations to cancel out regardless of the preferences
1524 */
1525 sp_item_write_transform(item, SP_OBJECT_REPR(item), NR::identity());
1527 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1528 gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1529 gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1531 Path *orig = Path_for_item(item, false);
1532 if (orig == NULL) {
1533 g_free(style);
1534 curve->unref();
1535 return false;
1536 }
1538 curve->unref();
1539 // remember the position of the item
1540 gint pos = SP_OBJECT_REPR(item)->position();
1541 // remember parent
1542 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1543 // remember id
1544 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1545 // remember path effect
1546 char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1547 // remember title
1548 gchar *title = item->title();
1549 // remember description
1550 gchar *desc = item->desc();
1552 //If a group was selected, to not change the selection list
1553 if (modifySelection)
1554 selection->remove(item);
1556 SP_OBJECT(item)->deleteObject(false);
1558 if ( justCoalesce ) {
1559 orig->Coalesce(threshold * size);
1560 } else {
1561 orig->ConvertEvenLines(threshold * size);
1562 orig->Simplify(threshold * size);
1563 }
1565 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1566 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1568 // restore style, mask and clip-path
1569 repr->setAttribute("style", style);
1570 g_free(style);
1572 if ( mask ) {
1573 repr->setAttribute("mask", mask);
1574 g_free(mask);
1575 }
1577 if ( clip_path ) {
1578 repr->setAttribute("clip-path", clip_path);
1579 g_free(clip_path);
1580 }
1582 // path
1583 gchar *str = orig->svg_dump_path();
1584 if (patheffect)
1585 repr->setAttribute("inkscape:original-d", str);
1586 else
1587 repr->setAttribute("d", str);
1588 g_free(str);
1590 // restore id
1591 repr->setAttribute("id", id);
1593 // add the new repr to the parent
1594 parent->appendChild(repr);
1596 // move to the saved position
1597 repr->setPosition(pos > 0 ? pos : 0);
1599 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1601 // reapply the transform
1602 sp_item_write_transform(newitem, repr, transform);
1604 // restore path effect
1605 repr->setAttribute("inkscape:path-effect", patheffect);
1607 // restore title & description
1608 if (title) {
1609 newitem->setTitle(title);
1610 g_free(title);
1611 }
1612 if (desc) {
1613 newitem->setDesc(desc);
1614 g_free(desc);
1615 }
1617 //If we are not in a selected group
1618 if (modifySelection)
1619 selection->add(repr);
1621 Inkscape::GC::release(repr);
1623 // clean up
1624 if (orig) delete orig;
1626 return true;
1627 }
1630 bool
1631 sp_selected_path_simplify_items(SPDesktop *desktop,
1632 Inkscape::Selection *selection, GSList *items,
1633 float threshold, bool justCoalesce,
1634 float angleLimit, bool breakableAngles,
1635 bool modifySelection)
1636 {
1637 bool simplifyIndividualPaths =
1638 (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1640 gchar *simplificationType;
1641 if (simplifyIndividualPaths) {
1642 simplificationType = _("Simplifying paths (separately):");
1643 } else {
1644 simplificationType = _("Simplifying paths:");
1645 }
1647 bool didSomething = false;
1649 boost::optional<NR::Rect> selectionBbox = selection->bounds();
1650 if (!selectionBbox) {
1651 return false;
1652 }
1653 gdouble selectionSize = L2(selectionBbox->dimensions());
1655 gdouble simplifySize = selectionSize;
1657 int pathsSimplified = 0;
1658 int totalPathCount = g_slist_length(items);
1660 // set "busy" cursor
1661 desktop->setWaitingCursor();
1663 for (; items != NULL; items = items->next) {
1664 SPItem *item = (SPItem *) items->data;
1666 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1667 continue;
1669 if (simplifyIndividualPaths) {
1670 boost::optional<NR::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));
1671 if (itemBbox) {
1672 simplifySize = L2(itemBbox->dimensions());
1673 } else {
1674 simplifySize = 0;
1675 }
1676 }
1678 pathsSimplified++;
1680 if (pathsSimplified % 20 == 0) {
1681 gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1682 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1683 }
1685 didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1686 threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1687 }
1689 desktop->clearWaitingCursor();
1691 if (pathsSimplified > 20) {
1692 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1693 }
1695 return didSomething;
1696 }
1698 void
1699 sp_selected_path_simplify_selection(SPDesktop *desktop, float threshold, bool justCoalesce,
1700 float angleLimit, bool breakableAngles)
1701 {
1702 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1704 if (selection->isEmpty()) {
1705 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1706 _("Select <b>path(s)</b> to simplify."));
1707 return;
1708 }
1710 GSList *items = g_slist_copy((GSList *) selection->itemList());
1712 bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1713 items, threshold,
1714 justCoalesce,
1715 angleLimit,
1716 breakableAngles, true);
1718 if (didSomething)
1719 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY,
1720 _("Simplify"));
1721 else
1722 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1724 }
1727 // globals for keeping track of accelerated simplify
1728 static double previousTime = 0.0;
1729 static gdouble simplifyMultiply = 1.0;
1731 void
1732 sp_selected_path_simplify(SPDesktop *desktop)
1733 {
1734 gdouble simplifyThreshold =
1735 prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1736 bool simplifyJustCoalesce =
1737 (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1739 //Get the current time
1740 GTimeVal currentTimeVal;
1741 g_get_current_time(¤tTimeVal);
1742 double currentTime = currentTimeVal.tv_sec * 1000000 +
1743 currentTimeVal.tv_usec;
1745 //Was the previous call to this function recent? (<0.5 sec)
1746 if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1748 // add to the threshold 1/2 of its original value
1749 simplifyMultiply += 0.5;
1750 simplifyThreshold *= simplifyMultiply;
1752 } else {
1753 // reset to the default
1754 simplifyMultiply = 1;
1755 }
1757 //remember time for next call
1758 previousTime = currentTime;
1760 //g_print("%g\n", simplify_threshold);
1762 //Make the actual call
1763 sp_selected_path_simplify_selection(desktop, simplifyThreshold,
1764 simplifyJustCoalesce, 0.0, false);
1765 }
1769 // fonctions utilitaires
1771 bool
1772 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1773 {
1774 if (who == NULL || a == NULL)
1775 return false;
1776 if (who == a)
1777 return true;
1778 return Ancetre(sp_repr_parent(a), who);
1779 }
1781 Path *
1782 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1783 {
1784 SPCurve *curve = curve_for_item(item);
1786 if (curve == NULL)
1787 return NULL;
1789 Geom::PathVector *pathv = pathvector_for_curve(item, curve, doTransformation, transformFull, Geom::identity(), Geom::identity());
1790 curve->unref();
1792 Path *dest = new Path;
1793 dest->LoadPathVector(*pathv);
1794 delete pathv;
1796 return dest;
1797 }
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, Geom::Matrix extraPreAffine, Geom::Matrix extraPostAffine)
1805 {
1806 if (curve == NULL)
1807 return NULL;
1809 Geom::PathVector *dest = new Geom::PathVector;
1810 *dest = curve->get_pathvector(); // Make a copy; must be freed by the caller!
1812 if (doTransformation) {
1813 if (transformFull) {
1814 *dest *= extraPreAffine * sp_item_i2doc_affine(item) * extraPostAffine;
1815 } else {
1816 *dest *= extraPreAffine * (Geom::Matrix)item->transform * extraPostAffine;
1817 }
1818 } else {
1819 *dest *= extraPreAffine * extraPostAffine;
1820 }
1822 return dest;
1823 }
1825 SPCurve* curve_for_item(SPItem *item)
1826 {
1827 if (!item)
1828 return NULL;
1830 SPCurve *curve = NULL;
1831 if (SP_IS_SHAPE(item)) {
1832 if (SP_IS_PATH(item)) {
1833 curve = sp_path_get_curve_for_edit(SP_PATH(item));
1834 } else {
1835 curve = sp_shape_get_curve(SP_SHAPE(item));
1836 }
1837 }
1838 else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1839 {
1840 curve = te_get_layout(item)->convertToCurves();
1841 }
1842 else if (SP_IS_IMAGE(item))
1843 {
1844 curve = sp_image_get_curve(SP_IMAGE(item));
1845 }
1847 return curve; // do not forget to unref the curve at some point!
1848 }
1850 boost::optional<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1851 {
1852 //get nearest position on path
1853 Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1854 return pos;
1855 }
1857 NR::Point get_point_on_Path(Path *path, int piece, double t)
1858 {
1859 NR::Point p;
1860 path->PointAt(piece, t, p);
1861 return p;
1862 }
1865 /*
1866 Local Variables:
1867 mode:c++
1868 c-file-style:"stroustrup"
1869 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1870 indent-tabs-mode:nil
1871 fill-column:99
1872 End:
1873 */
1874 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :