f44cba46d60cf7151746ed57e95b099d6a993572
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, 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 double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
963 sp_selected_path_do_offset(desktop, true, prefOffset);
964 }
965 void
966 sp_selected_path_inset(SPDesktop *desktop)
967 {
968 double prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", 1.0);
970 sp_selected_path_do_offset(desktop, false, prefOffset);
971 }
973 void
974 sp_selected_path_offset_screen(SPDesktop *desktop, double pixels)
975 {
976 sp_selected_path_do_offset(desktop, true, pixels / desktop->current_zoom());
977 }
979 void
980 sp_selected_path_inset_screen(SPDesktop *desktop, double pixels)
981 {
982 sp_selected_path_do_offset(desktop, false, pixels / desktop->current_zoom());
983 }
986 void sp_selected_path_create_offset_object_zero(SPDesktop *desktop)
987 {
988 sp_selected_path_create_offset_object(desktop, 0, false);
989 }
991 void sp_selected_path_create_offset(SPDesktop *desktop)
992 {
993 sp_selected_path_create_offset_object(desktop, 1, false);
994 }
995 void sp_selected_path_create_inset(SPDesktop *desktop)
996 {
997 sp_selected_path_create_offset_object(desktop, -1, false);
998 }
1000 void sp_selected_path_create_updating_offset_object_zero(SPDesktop *desktop)
1001 {
1002 sp_selected_path_create_offset_object(desktop, 0, true);
1003 }
1005 void sp_selected_path_create_updating_offset(SPDesktop *desktop)
1006 {
1007 sp_selected_path_create_offset_object(desktop, 1, true);
1008 }
1009 void sp_selected_path_create_updating_inset(SPDesktop *desktop)
1010 {
1011 sp_selected_path_create_offset_object(desktop, -1, true);
1012 }
1014 void
1015 sp_selected_path_create_offset_object(SPDesktop *desktop, int expand, bool updating)
1016 {
1017 Inkscape::Selection *selection;
1018 Inkscape::XML::Node *repr;
1019 SPItem *item;
1020 SPCurve *curve;
1021 gchar *style, *str;
1022 float o_width, o_miter;
1023 JoinType o_join;
1024 ButtType o_butt;
1026 curve = NULL;
1028 selection = sp_desktop_selection(desktop);
1030 item = selection->singleItem();
1032 if (item == NULL || ( !SP_IS_SHAPE(item) && !SP_IS_TEXT(item) ) ) {
1033 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("Selected object is <b>not a path</b>, cannot inset/outset."));
1034 return;
1035 }
1036 if (SP_IS_SHAPE(item))
1037 {
1038 curve = sp_shape_get_curve(SP_SHAPE(item));
1039 if (curve == NULL)
1040 return;
1041 }
1042 if (SP_IS_TEXT(item))
1043 {
1044 curve = SP_TEXT(item)->getNormalizedBpath();
1045 if (curve == NULL)
1046 return;
1047 }
1049 NR::Matrix const transform(item->transform);
1051 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1053 style = g_strdup(SP_OBJECT(item)->repr->attribute("style"));
1055 // remember the position of the item
1056 gint pos = SP_OBJECT_REPR(item)->position();
1057 // remember parent
1058 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1060 {
1061 SPStyle *i_style = SP_OBJECT(item)->style;
1062 int jointype, captype;
1064 jointype = i_style->stroke_linejoin.value;
1065 captype = i_style->stroke_linecap.value;
1066 o_width = i_style->stroke_width.computed;
1067 if (jointype == SP_STROKE_LINEJOIN_MITER)
1068 {
1069 o_join = join_pointy;
1070 }
1071 else if (jointype == SP_STROKE_LINEJOIN_ROUND)
1072 {
1073 o_join = join_round;
1074 }
1075 else
1076 {
1077 o_join = join_straight;
1078 }
1079 if (captype == SP_STROKE_LINECAP_SQUARE)
1080 {
1081 o_butt = butt_square;
1082 }
1083 else if (captype == SP_STROKE_LINECAP_ROUND)
1084 {
1085 o_butt = butt_round;
1086 }
1087 else
1088 {
1089 o_butt = butt_straight;
1090 }
1092 {
1093 double prefOffset = 1.0;
1094 prefOffset = prefs_get_double_attribute("options.defaultoffsetwidth", "value", prefOffset);
1095 o_width = prefOffset;
1096 }
1098 if (o_width < 0.01)
1099 o_width = 0.01;
1100 o_miter = i_style->stroke_miterlimit.value * o_width;
1101 }
1103 Path *orig = Path_for_item(item, true, false);
1104 if (orig == NULL)
1105 {
1106 g_free(style);
1107 curve->unref();
1108 return;
1109 }
1111 Path *res = new Path;
1112 res->SetBackData(false);
1114 {
1115 Shape *theShape = new Shape;
1116 Shape *theRes = new Shape;
1118 orig->ConvertWithBackData(1.0);
1119 orig->Fill(theShape, 0);
1121 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1122 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1123 if (val && strcmp(val, "nonzero") == 0)
1124 {
1125 theRes->ConvertToShape(theShape, fill_nonZero);
1126 }
1127 else if (val && strcmp(val, "evenodd") == 0)
1128 {
1129 theRes->ConvertToShape(theShape, fill_oddEven);
1130 }
1131 else
1132 {
1133 theRes->ConvertToShape(theShape, fill_nonZero);
1134 }
1136 Path *originaux[1];
1137 originaux[0] = orig;
1138 theRes->ConvertToForme(res, 1, originaux);
1140 delete theShape;
1141 delete theRes;
1142 }
1144 curve->unref();
1146 if (res->descr_cmd.size() <= 1)
1147 {
1148 // pas vraiment de points sur le resultat
1149 // donc il ne reste rien
1150 sp_document_done(sp_desktop_document(desktop),
1151 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1152 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1153 (updating ? _("Create linked offset")
1154 : _("Create dynamic offset")));
1155 selection->clear();
1157 delete res;
1158 delete orig;
1159 g_free(style);
1160 return;
1161 }
1163 {
1164 gchar tstr[80];
1166 tstr[79] = '\0';
1168 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1169 repr = xml_doc->createElement("svg:path");
1170 repr->setAttribute("sodipodi:type", "inkscape:offset");
1171 sp_repr_set_svg_double(repr, "inkscape:radius", ( expand > 0
1172 ? o_width
1173 : expand < 0
1174 ? -o_width
1175 : 0 ));
1177 str = res->svg_dump_path();
1178 repr->setAttribute("inkscape:original", str);
1179 g_free(str);
1181 if ( updating ) {
1182 char const *id = SP_OBJECT(item)->repr->attribute("id");
1183 char const *uri = g_strdup_printf("#%s", id);
1184 repr->setAttribute("xlink:href", uri);
1185 g_free((void *) uri);
1186 } else {
1187 repr->setAttribute("inkscape:href", NULL);
1188 }
1190 repr->setAttribute("style", style);
1192 // add the new repr to the parent
1193 parent->appendChild(repr);
1195 // move to the saved position
1196 repr->setPosition(pos > 0 ? pos : 0);
1198 SPItem *nitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1200 if ( updating ) {
1201 // on conserve l'original
1202 // we reapply the transform to the original (offset will feel it)
1203 sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
1204 } else {
1205 // delete original, apply the transform to the offset
1206 SP_OBJECT(item)->deleteObject(false);
1207 sp_item_write_transform(nitem, repr, transform);
1208 }
1210 // The object just created from a temporary repr is only a seed.
1211 // We need to invoke its write which will update its real repr (in particular adding d=)
1212 SP_OBJECT(nitem)->updateRepr();
1214 Inkscape::GC::release(repr);
1216 selection->set(nitem);
1217 }
1219 sp_document_done(sp_desktop_document(desktop),
1220 (updating ? SP_VERB_SELECTION_LINKED_OFFSET
1221 : SP_VERB_SELECTION_DYNAMIC_OFFSET),
1222 (updating ? _("Create linked offset")
1223 : _("Create dynamic offset")));
1225 delete res;
1226 delete orig;
1228 g_free(style);
1229 }
1242 void
1243 sp_selected_path_do_offset(SPDesktop *desktop, bool expand, double prefOffset)
1244 {
1245 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1247 if (selection->isEmpty()) {
1248 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>path(s)</b> to inset/outset."));
1249 return;
1250 }
1252 bool did = false;
1254 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1255 items != NULL;
1256 items = items->next) {
1258 SPItem *item = (SPItem *) items->data;
1260 if (!SP_IS_SHAPE(item) && !SP_IS_TEXT(item))
1261 continue;
1263 SPCurve *curve = NULL;
1264 if (SP_IS_SHAPE(item)) {
1265 curve = sp_shape_get_curve(SP_SHAPE(item));
1266 if (curve == NULL)
1267 continue;
1268 }
1269 if (SP_IS_TEXT(item)) {
1270 curve = SP_TEXT(item)->getNormalizedBpath();
1271 if (curve == NULL)
1272 continue;
1273 }
1275 NR::Matrix const transform(item->transform);
1277 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1279 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1281 float o_width, o_miter;
1282 JoinType o_join;
1283 ButtType o_butt;
1285 {
1286 SPStyle *i_style = SP_OBJECT(item)->style;
1287 int jointype, captype;
1289 jointype = i_style->stroke_linejoin.value;
1290 captype = i_style->stroke_linecap.value;
1291 o_width = i_style->stroke_width.computed;
1293 switch (jointype) {
1294 case SP_STROKE_LINEJOIN_MITER:
1295 o_join = join_pointy;
1296 break;
1297 case SP_STROKE_LINEJOIN_ROUND:
1298 o_join = join_round;
1299 break;
1300 default:
1301 o_join = join_straight;
1302 break;
1303 }
1305 switch (captype) {
1306 case SP_STROKE_LINECAP_SQUARE:
1307 o_butt = butt_square;
1308 break;
1309 case SP_STROKE_LINECAP_ROUND:
1310 o_butt = butt_round;
1311 break;
1312 default:
1313 o_butt = butt_straight;
1314 break;
1315 }
1317 o_width = prefOffset;
1319 if (o_width < 0.1)
1320 o_width = 0.1;
1321 o_miter = i_style->stroke_miterlimit.value * o_width;
1322 }
1324 Path *orig = Path_for_item(item, false);
1325 if (orig == NULL) {
1326 g_free(style);
1327 curve->unref();
1328 continue;
1329 }
1331 Path *res = new Path;
1332 res->SetBackData(false);
1334 {
1335 Shape *theShape = new Shape;
1336 Shape *theRes = new Shape;
1338 orig->ConvertWithBackData(0.03);
1339 orig->Fill(theShape, 0);
1341 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
1342 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
1343 if (val && strcmp(val, "nonzero") == 0)
1344 {
1345 theRes->ConvertToShape(theShape, fill_nonZero);
1346 }
1347 else if (val && strcmp(val, "evenodd") == 0)
1348 {
1349 theRes->ConvertToShape(theShape, fill_oddEven);
1350 }
1351 else
1352 {
1353 theRes->ConvertToShape(theShape, fill_nonZero);
1354 }
1356 // et maintenant: offset
1357 // methode inexacte
1358 /* Path *originaux[1];
1359 originaux[0] = orig;
1360 theRes->ConvertToForme(res, 1, originaux);
1362 if (expand) {
1363 res->OutsideOutline(orig, 0.5 * o_width, o_join, o_butt, o_miter);
1364 } else {
1365 res->OutsideOutline(orig, -0.5 * o_width, o_join, o_butt, o_miter);
1366 }
1368 orig->ConvertWithBackData(1.0);
1369 orig->Fill(theShape, 0);
1370 theRes->ConvertToShape(theShape, fill_positive);
1371 originaux[0] = orig;
1372 theRes->ConvertToForme(res, 1, originaux);
1374 if (o_width >= 0.5) {
1375 // res->Coalesce(1.0);
1376 res->ConvertEvenLines(1.0);
1377 res->Simplify(1.0);
1378 } else {
1379 // res->Coalesce(o_width);
1380 res->ConvertEvenLines(1.0*o_width);
1381 res->Simplify(1.0 * o_width);
1382 } */
1383 // methode par makeoffset
1385 if (expand)
1386 {
1387 theShape->MakeOffset(theRes, o_width, o_join, o_miter);
1388 }
1389 else
1390 {
1391 theShape->MakeOffset(theRes, -o_width, o_join, o_miter);
1392 }
1393 theRes->ConvertToShape(theShape, fill_positive);
1395 res->Reset();
1396 theRes->ConvertToForme(res);
1398 if (o_width >= 1.0)
1399 {
1400 res->ConvertEvenLines(1.0);
1401 res->Simplify(1.0);
1402 }
1403 else
1404 {
1405 res->ConvertEvenLines(1.0*o_width);
1406 res->Simplify(1.0 * o_width);
1407 }
1409 delete theShape;
1410 delete theRes;
1411 }
1413 did = true;
1415 curve->unref();
1416 // remember the position of the item
1417 gint pos = SP_OBJECT_REPR(item)->position();
1418 // remember parent
1419 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1420 // remember id
1421 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1423 selection->remove(item);
1424 SP_OBJECT(item)->deleteObject(false);
1426 if (res->descr_cmd.size() > 1) { // if there's 0 or 1 node left, drop this path altogether
1428 gchar tstr[80];
1430 tstr[79] = '\0';
1432 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1433 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1435 repr->setAttribute("style", style);
1437 gchar *str = res->svg_dump_path();
1438 repr->setAttribute("d", str);
1439 g_free(str);
1441 // add the new repr to the parent
1442 parent->appendChild(repr);
1444 // move to the saved position
1445 repr->setPosition(pos > 0 ? pos : 0);
1447 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1449 // reapply the transform
1450 sp_item_write_transform(newitem, repr, transform);
1452 repr->setAttribute("id", id);
1454 selection->add(repr);
1456 Inkscape::GC::release(repr);
1457 }
1459 delete orig;
1460 delete res;
1461 }
1463 if (did) {
1464 sp_document_done(sp_desktop_document(desktop),
1465 (expand ? SP_VERB_SELECTION_OFFSET : SP_VERB_SELECTION_INSET),
1466 (expand ? _("Outset path") : _("Inset path")));
1467 } else {
1468 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to inset/outset in the selection."));
1469 return;
1470 }
1471 }
1474 static bool
1475 sp_selected_path_simplify_items(SPDesktop *desktop,
1476 Inkscape::Selection *selection, GSList *items,
1477 float threshold, bool justCoalesce,
1478 float angleLimit, bool breakableAngles,
1479 bool modifySelection);
1482 //return true if we changed something, else false
1483 bool
1484 sp_selected_path_simplify_item(SPDesktop *desktop,
1485 Inkscape::Selection *selection, SPItem *item,
1486 float threshold, bool justCoalesce,
1487 float angleLimit, bool breakableAngles,
1488 gdouble size, bool modifySelection)
1489 {
1490 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1491 return false;
1493 //If this is a group, do the children instead
1494 if (SP_IS_GROUP(item)) {
1495 GSList *items = sp_item_group_item_list(SP_GROUP(item));
1497 return sp_selected_path_simplify_items(desktop, selection, items,
1498 threshold, justCoalesce,
1499 angleLimit, breakableAngles,
1500 false);
1501 }
1504 SPCurve *curve = NULL;
1506 if (SP_IS_SHAPE(item)) {
1507 curve = sp_shape_get_curve(SP_SHAPE(item));
1508 if (!curve)
1509 return false;
1510 }
1512 if (SP_IS_TEXT(item)) {
1513 curve = SP_TEXT(item)->getNormalizedBpath();
1514 if (!curve)
1515 return false;
1516 }
1518 // save the transform, to re-apply it after simplification
1519 NR::Matrix const transform(item->transform);
1521 /*
1522 reset the transform, effectively transforming the item by transform.inverse();
1523 this is necessary so that the item is transformed twice back and forth,
1524 allowing all compensations to cancel out regardless of the preferences
1525 */
1526 sp_item_write_transform(item, SP_OBJECT_REPR(item), Geom::identity());
1528 gchar *style = g_strdup(SP_OBJECT_REPR(item)->attribute("style"));
1529 gchar *mask = g_strdup(SP_OBJECT_REPR(item)->attribute("mask"));
1530 gchar *clip_path = g_strdup(SP_OBJECT_REPR(item)->attribute("clip-path"));
1532 Path *orig = Path_for_item(item, false);
1533 if (orig == NULL) {
1534 g_free(style);
1535 curve->unref();
1536 return false;
1537 }
1539 curve->unref();
1540 // remember the position of the item
1541 gint pos = SP_OBJECT_REPR(item)->position();
1542 // remember parent
1543 Inkscape::XML::Node *parent = SP_OBJECT_REPR(item)->parent();
1544 // remember id
1545 char const *id = SP_OBJECT_REPR(item)->attribute("id");
1546 // remember path effect
1547 char const *patheffect = SP_OBJECT_REPR(item)->attribute("inkscape:path-effect");
1548 // remember title
1549 gchar *title = item->title();
1550 // remember description
1551 gchar *desc = item->desc();
1553 //If a group was selected, to not change the selection list
1554 if (modifySelection)
1555 selection->remove(item);
1557 SP_OBJECT(item)->deleteObject(false);
1559 if ( justCoalesce ) {
1560 orig->Coalesce(threshold * size);
1561 } else {
1562 orig->ConvertEvenLines(threshold * size);
1563 orig->Simplify(threshold * size);
1564 }
1566 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1567 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1569 // restore style, mask and clip-path
1570 repr->setAttribute("style", style);
1571 g_free(style);
1573 if ( mask ) {
1574 repr->setAttribute("mask", mask);
1575 g_free(mask);
1576 }
1578 if ( clip_path ) {
1579 repr->setAttribute("clip-path", clip_path);
1580 g_free(clip_path);
1581 }
1583 // path
1584 gchar *str = orig->svg_dump_path();
1585 if (patheffect)
1586 repr->setAttribute("inkscape:original-d", str);
1587 else
1588 repr->setAttribute("d", str);
1589 g_free(str);
1591 // restore id
1592 repr->setAttribute("id", id);
1594 // add the new repr to the parent
1595 parent->appendChild(repr);
1597 // move to the saved position
1598 repr->setPosition(pos > 0 ? pos : 0);
1600 SPItem *newitem = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
1602 // reapply the transform
1603 sp_item_write_transform(newitem, repr, transform);
1605 // restore path effect
1606 repr->setAttribute("inkscape:path-effect", patheffect);
1608 // restore title & description
1609 if (title) {
1610 newitem->setTitle(title);
1611 g_free(title);
1612 }
1613 if (desc) {
1614 newitem->setDesc(desc);
1615 g_free(desc);
1616 }
1618 //If we are not in a selected group
1619 if (modifySelection)
1620 selection->add(repr);
1622 Inkscape::GC::release(repr);
1624 // clean up
1625 if (orig) delete orig;
1627 return true;
1628 }
1631 bool
1632 sp_selected_path_simplify_items(SPDesktop *desktop,
1633 Inkscape::Selection *selection, GSList *items,
1634 float threshold, bool justCoalesce,
1635 float angleLimit, bool breakableAngles,
1636 bool modifySelection)
1637 {
1638 bool simplifyIndividualPaths =
1639 (bool) prefs_get_int_attribute("options.simplifyindividualpaths", "value", 0);
1641 gchar *simplificationType;
1642 if (simplifyIndividualPaths) {
1643 simplificationType = _("Simplifying paths (separately):");
1644 } else {
1645 simplificationType = _("Simplifying paths:");
1646 }
1648 bool didSomething = false;
1650 boost::optional<NR::Rect> selectionBbox = selection->bounds();
1651 if (!selectionBbox) {
1652 return false;
1653 }
1654 gdouble selectionSize = L2(selectionBbox->dimensions());
1656 gdouble simplifySize = selectionSize;
1658 int pathsSimplified = 0;
1659 int totalPathCount = g_slist_length(items);
1661 // set "busy" cursor
1662 desktop->setWaitingCursor();
1664 for (; items != NULL; items = items->next) {
1665 SPItem *item = (SPItem *) items->data;
1667 if (!(SP_IS_GROUP(item) || SP_IS_SHAPE(item) || SP_IS_TEXT(item)))
1668 continue;
1670 if (simplifyIndividualPaths) {
1671 boost::optional<NR::Rect> itemBbox = item->getBounds(sp_item_i2d_affine(item));
1672 if (itemBbox) {
1673 simplifySize = L2(itemBbox->dimensions());
1674 } else {
1675 simplifySize = 0;
1676 }
1677 }
1679 pathsSimplified++;
1681 if (pathsSimplified % 20 == 0) {
1682 gchar *message = g_strdup_printf(_("%s <b>%d</b> of <b>%d</b> paths simplified..."), simplificationType, pathsSimplified, totalPathCount);
1683 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, message);
1684 }
1686 didSomething |= sp_selected_path_simplify_item(desktop, selection, item,
1687 threshold, justCoalesce, angleLimit, breakableAngles, simplifySize, modifySelection);
1688 }
1690 desktop->clearWaitingCursor();
1692 if (pathsSimplified > 20) {
1693 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strdup_printf(_("<b>%d</b> paths simplified."), pathsSimplified));
1694 }
1696 return didSomething;
1697 }
1699 void
1700 sp_selected_path_simplify_selection(SPDesktop *desktop, float threshold, bool justCoalesce,
1701 float angleLimit, bool breakableAngles)
1702 {
1703 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1705 if (selection->isEmpty()) {
1706 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1707 _("Select <b>path(s)</b> to simplify."));
1708 return;
1709 }
1711 GSList *items = g_slist_copy((GSList *) selection->itemList());
1713 bool didSomething = sp_selected_path_simplify_items(desktop, selection,
1714 items, threshold,
1715 justCoalesce,
1716 angleLimit,
1717 breakableAngles, true);
1719 if (didSomething)
1720 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_SIMPLIFY,
1721 _("Simplify"));
1722 else
1723 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No paths</b> to simplify in the selection."));
1725 }
1728 // globals for keeping track of accelerated simplify
1729 static double previousTime = 0.0;
1730 static gdouble simplifyMultiply = 1.0;
1732 void
1733 sp_selected_path_simplify(SPDesktop *desktop)
1734 {
1735 gdouble simplifyThreshold =
1736 prefs_get_double_attribute("options.simplifythreshold", "value", 0.003);
1737 bool simplifyJustCoalesce =
1738 (bool) prefs_get_int_attribute("options.simplifyjustcoalesce", "value", 0);
1740 //Get the current time
1741 GTimeVal currentTimeVal;
1742 g_get_current_time(¤tTimeVal);
1743 double currentTime = currentTimeVal.tv_sec * 1000000 +
1744 currentTimeVal.tv_usec;
1746 //Was the previous call to this function recent? (<0.5 sec)
1747 if (previousTime > 0.0 && currentTime - previousTime < 500000.0) {
1749 // add to the threshold 1/2 of its original value
1750 simplifyMultiply += 0.5;
1751 simplifyThreshold *= simplifyMultiply;
1753 } else {
1754 // reset to the default
1755 simplifyMultiply = 1;
1756 }
1758 //remember time for next call
1759 previousTime = currentTime;
1761 //g_print("%g\n", simplify_threshold);
1763 //Make the actual call
1764 sp_selected_path_simplify_selection(desktop, simplifyThreshold,
1765 simplifyJustCoalesce, 0.0, false);
1766 }
1770 // fonctions utilitaires
1772 bool
1773 Ancetre(Inkscape::XML::Node *a, Inkscape::XML::Node *who)
1774 {
1775 if (who == NULL || a == NULL)
1776 return false;
1777 if (who == a)
1778 return true;
1779 return Ancetre(sp_repr_parent(a), who);
1780 }
1782 Path *
1783 Path_for_item(SPItem *item, bool doTransformation, bool transformFull)
1784 {
1785 SPCurve *curve = curve_for_item(item);
1787 if (curve == NULL)
1788 return NULL;
1790 Geom::PathVector *pathv = pathvector_for_curve(item, curve, doTransformation, transformFull, Geom::identity(), Geom::identity());
1791 curve->unref();
1793 Path *dest = new Path;
1794 dest->LoadPathVector(*pathv);
1795 delete pathv;
1797 return dest;
1798 }
1800 /*
1801 * NOTE: Returns empty pathvector if curve == NULL
1802 * TODO: see if calling this method can be optimized. All the pathvector copying might be slow.
1803 */
1804 Geom::PathVector*
1805 pathvector_for_curve(SPItem *item, SPCurve *curve, bool doTransformation, bool transformFull, Geom::Matrix extraPreAffine, Geom::Matrix extraPostAffine)
1806 {
1807 if (curve == NULL)
1808 return NULL;
1810 Geom::PathVector *dest = new Geom::PathVector;
1811 *dest = curve->get_pathvector(); // Make a copy; must be freed by the caller!
1813 if (doTransformation) {
1814 if (transformFull) {
1815 *dest *= extraPreAffine * sp_item_i2doc_affine(item) * extraPostAffine;
1816 } else {
1817 *dest *= extraPreAffine * (Geom::Matrix)item->transform * extraPostAffine;
1818 }
1819 } else {
1820 *dest *= extraPreAffine * extraPostAffine;
1821 }
1823 return dest;
1824 }
1826 SPCurve* curve_for_item(SPItem *item)
1827 {
1828 if (!item)
1829 return NULL;
1831 SPCurve *curve = NULL;
1832 if (SP_IS_SHAPE(item)) {
1833 if (SP_IS_PATH(item)) {
1834 curve = sp_path_get_curve_for_edit(SP_PATH(item));
1835 } else {
1836 curve = sp_shape_get_curve(SP_SHAPE(item));
1837 }
1838 }
1839 else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1840 {
1841 curve = te_get_layout(item)->convertToCurves();
1842 }
1843 else if (SP_IS_IMAGE(item))
1844 {
1845 curve = sp_image_get_curve(SP_IMAGE(item));
1846 }
1848 return curve; // do not forget to unref the curve at some point!
1849 }
1851 boost::optional<Path::cut_position> get_nearest_position_on_Path(Path *path, NR::Point p, unsigned seg)
1852 {
1853 //get nearest position on path
1854 Path::cut_position pos = path->PointToCurvilignPosition(p, seg);
1855 return pos;
1856 }
1858 NR::Point get_point_on_Path(Path *path, int piece, double t)
1859 {
1860 NR::Point p;
1861 path->PointAt(piece, t, p);
1862 return p;
1863 }
1866 /*
1867 Local Variables:
1868 mode:c++
1869 c-file-style:"stroustrup"
1870 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1871 indent-tabs-mode:nil
1872 fill-column:99
1873 End:
1874 */
1875 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :