Salome HOME
Remove debug output for SketchPlugin_Trim.
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Trim.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "SketchPlugin_Trim.h"
21
22 #include <GeomAPI_Dir2d.h>
23 #include <GeomAPI_Edge.h>
24 #include <GeomAPI_Pnt2d.h>
25 #include <GeomAPI_XY.h>
26 #include <GeomDataAPI_Point2D.h>
27 #include <GeomAlgoAPI_ShapeTools.h>
28
29 #include <ModelAPI_AttributeReference.h>
30 #include <ModelAPI_AttributeString.h>
31 #include <ModelAPI_AttributeRefAttr.h>
32 #include <ModelAPI_Tools.h>
33 #include <ModelAPI_AttributeBoolean.h>
34
35 #include <ModelAPI_Validator.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_AttributeDouble.h>
38
39 #include <ModelGeomAlgo_Shape.h>
40
41 #include <SketchPlugin_Arc.h>
42 #include <SketchPlugin_ConstraintMiddle.h>
43 #include <SketchPlugin_Circle.h>
44 #include <SketchPlugin_ConstraintCoincidence.h>
45 #include <SketchPlugin_ConstraintEqual.h>
46 #include <SketchPlugin_ConstraintTangent.h>
47 #include <SketchPlugin_ConstraintLength.h>
48 #include <SketchPlugin_ConstraintMirror.h>
49 #include <SketchPlugin_ConstraintCollinear.h>
50 #include <SketchPlugin_Ellipse.h>
51 #include <SketchPlugin_EllipticArc.h>
52 #include <SketchPlugin_Line.h>
53 #include <SketchPlugin_MultiRotation.h>
54 #include <SketchPlugin_MultiTranslation.h>
55 #include <SketchPlugin_Point.h>
56
57 #include <ModelAPI_EventReentrantMessage.h>
58
59 #include <ModelAPI_Events.h>
60 #include <SketchPlugin_Line.h>
61 #include <SketchPlugin_Arc.h>
62 #include <SketchPlugin_Circle.h>
63
64 #include <ModelGeomAlgo_Point2D.h>
65 #include <Events_Loop.h>
66
67 #include <cmath>
68
69 #ifdef DEBUG_TRIM
70 #include <iostream>
71 #endif
72
73 #ifdef DEBUG_TRIM_METHODS
74 #include <iostream>
75 #endif
76
77 static const double PI = 3.141592653589793238463;
78
79 static const std::string OPERATION_HIGHLIGHT_COLOR() { return "128, 0, 0"; }
80 static const std::string OPERATION_REMOVE_FEATURE_COLOR() { return "255, 174, 201"; }
81
82 SketchPlugin_Trim::SketchPlugin_Trim()
83 {
84 }
85
86 void SketchPlugin_Trim::initAttributes()
87 {
88   data()->addAttribute(SELECTED_OBJECT(), ModelAPI_AttributeReference::typeId());
89   data()->addAttribute(SELECTED_POINT(), GeomDataAPI_Point2D::typeId());
90
91   data()->addAttribute(PREVIEW_POINT(), GeomDataAPI_Point2D::typeId());
92   data()->addAttribute(PREVIEW_OBJECT(), ModelAPI_AttributeReference::typeId());
93
94   data()->attribute(PREVIEW_POINT())->setIsArgument(false);
95   data()->attribute(SELECTED_POINT())->setIsArgument(false);
96   data()->attribute(PREVIEW_OBJECT())->setIsArgument(false);
97
98   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), PREVIEW_POINT());
99   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(), PREVIEW_OBJECT());
100 }
101
102 void SketchPlugin_Trim::findShapePoints(const std::string& theObjectAttributeId,
103                                         const std::string& thePointAttributeId,
104                                         std::shared_ptr<GeomAPI_Pnt>& aStartPoint,
105                                         std::shared_ptr<GeomAPI_Pnt>& aLastPoint)
106 {
107   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
108                                             data()->attribute(theObjectAttributeId));
109   ObjectPtr aBaseObject = aBaseObjectAttr->value();
110
111   AttributePoint2DPtr aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
112                                               data()->attribute(thePointAttributeId));
113   std::shared_ptr<GeomAPI_Pnt2d> anAttributePnt2d = aPoint->pnt();
114   std::shared_ptr<GeomAPI_Pnt> anAttributePnt = sketch()->to3D(anAttributePnt2d->x(),
115                                                                anAttributePnt2d->y());
116
117   if (myCashedShapes.find(aBaseObject) == myCashedShapes.end()) {
118     SketchPlugin_SegmentationTools::fillObjectShapes(
119         this, aBaseObject, myCashedShapes, myObjectToPoints);
120   }
121
122   const std::set<GeomShapePtr>& aShapes = myCashedShapes[aBaseObject];
123   if (!aShapes.empty()) {
124     std::set<GeomShapePtr>::const_iterator anIt = aShapes.begin(), aLast = aShapes.end();
125     for (; anIt != aLast; anIt++) {
126       GeomShapePtr aBaseShape = *anIt;
127       std::shared_ptr<GeomAPI_Pnt> aProjectedPoint;
128       if (ModelGeomAlgo_Point2D::isPointOnEdge(aBaseShape, anAttributePnt, aProjectedPoint)) {
129
130         if (aBaseShape->shapeType() == GeomAPI_Shape::EDGE) {
131           std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aBaseShape));
132           //GeomAPI_Shape::Orientation anOrientation = anEdge->orientation();
133           //if (anOrientation == GeomAPI_Shape::REVERSED) {
134             aStartPoint = anEdge->lastPoint();
135             aLastPoint = anEdge->firstPoint();
136           //}
137           //else {
138             //aStartPoint = anEdge->firstPoint();
139             //aLastPoint = anEdge->lastPoint();
140           //}
141         }
142       }
143     }
144   }
145 #ifdef DEBUG_TRIM
146   std::cout << "<findShapePoints> => "
147     << std::endl << "Attribute point: "
148     << anAttributePnt->x() << ", " << anAttributePnt->y() << ", " << anAttributePnt->z() << "]"
149     << std::endl << "Start Point: ["
150     << aStartPoint->x() << ", " << aStartPoint->y() << ", " << aStartPoint->z() << "]"
151     << std::endl << "Last Point: ["
152     << aLastPoint->x() << ", " << aLastPoint->y() << ", " << aLastPoint->z() << "]"
153     << std::endl;
154 #endif
155 }
156
157 std::shared_ptr<GeomAPI_Pnt2d> SketchPlugin_Trim::convertPoint(
158                                                    const std::shared_ptr<GeomAPI_Pnt>& thePoint)
159 {
160   std::shared_ptr<GeomAPI_Pnt2d> aPoint;
161   if (!thePoint.get())
162     return aPoint;
163
164   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
165                                         data()->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
166   ObjectPtr aBaseObject = aBaseObjectAttr->value();
167   if (myObjectToPoints.find(aBaseObject) == myObjectToPoints.end()) {
168     SketchPlugin_SegmentationTools::fillObjectShapes(
169         this, aBaseObject, myCashedShapes, myObjectToPoints);
170   }
171
172   bool aFound = false;
173   const GeomAlgoAPI_ShapeTools::PointToRefsMap& aRefsMap = myObjectToPoints.at(aBaseObject);
174   for (GeomAlgoAPI_ShapeTools::PointToRefsMap::const_iterator aPointIt = aRefsMap.begin();
175        aPointIt != aRefsMap.end() && !aFound; aPointIt++) {
176     if (aPointIt->first->isEqual(thePoint)) {
177       const std::pair<std::list<AttributePoint2DPtr >,
178                std::list<ObjectPtr > >& anInfo = aPointIt->second;
179       const std::list<AttributePoint2DPtr >& anAttributes = anInfo.first;
180       if (!anAttributes.empty()) {
181         aPoint = anAttributes.front()->pnt();
182         aFound = true;
183       }
184       else {
185         aPoint = sketch()->to2D(thePoint);
186         aFound = true;
187       }
188     }
189   }
190   if (!aFound) {
191     // returns an end of the shape to define direction of split if feature's attribute
192     // participates
193     aPoint = sketch()->to2D(thePoint);
194   }
195   return aPoint;
196 }
197
198 void SketchPlugin_Trim::execute()
199 {
200 #ifdef DEBUG_TRIM_METHODS
201   std::cout << "SketchPlugin_Trim::execute: " << data()->name() << std::endl;
202 #endif
203
204   SketchPlugin_Sketch* aSketch = sketch();
205   if (!aSketch) {
206     setError("Error: Sketch object is empty.");
207     return;
208   }
209
210   // Check the base objects are initialized.
211   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
212                                         data()->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
213   if(!aBaseObjectAttr->isInitialized()) {
214     setError("Error: Base object is not initialized.");
215     return;
216   }
217   ObjectPtr aBaseObject = aBaseObjectAttr->value();
218   if (!aBaseObject.get()) {
219     setError("Error: Base object is not initialized.");
220     return;
221   }
222   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
223
224   /// Remove reference of this feature to feature used in preview, it is not necessary anymore
225   /// as trim will be removed after execute
226   AttributeReferencePtr aPreviewObjectAttr =
227                      std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
228                      data()->attribute(SketchPlugin_Trim::PREVIEW_OBJECT()));
229
230   ObjectPtr aPreviewObject = aPreviewObjectAttr->value();
231   AttributePoint2DPtr aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
232                                            data()->attribute(PREVIEW_POINT()));
233   std::shared_ptr<GeomAPI_Pnt2d> aPreviewPnt2d = aPoint->pnt();
234   // nullify pointer of preview attribute
235   aPreviewObjectAttr->setValue(ResultPtr());
236
237   bool anIsEqualPreviewAndSelected = aPreviewObject == aBaseObject;
238
239   /// points of trim
240   std::shared_ptr<GeomAPI_Pnt> aStartShapePoint, aLastShapePoint;
241 #ifdef DEBUG_TRIM
242   std::cout << " Base Feature: " << aBaseFeature->data()->name() << std::endl;
243 #endif
244   findShapePoints(SELECTED_OBJECT(), SELECTED_POINT(), aStartShapePoint, aLastShapePoint);
245   if (!aStartShapePoint || !aLastShapePoint) {
246     setError("Error: Selected point is not placed on any edge");
247     return;
248   }
249
250   std::shared_ptr<GeomAPI_Pnt2d> aStartShapePoint2d = convertPoint(aStartShapePoint);
251   std::shared_ptr<GeomAPI_Pnt2d> aLastShapePoint2d = convertPoint(aLastShapePoint);
252   /// find features that should be deleted (e.g. Middle Point) or updated (e.g. Length)
253   std::set<FeaturePtr> aFeaturesToDelete, aFeaturesToUpdate;
254   getConstraints(aFeaturesToDelete, aFeaturesToUpdate);
255   // find references(attributes and features) to the base feature
256   std::map<AttributePtr, std::list<AttributePtr> > aBaseRefAttributes;
257   std::list<AttributePtr> aRefsToFeature;
258   SketchPlugin_SegmentationTools::getRefAttributes(
259       aBaseFeature, aBaseRefAttributes, aRefsToFeature);
260 #ifdef DEBUG_TRIM
261   std::cout << "---- getRefAttributes ----" << std::endl;
262   std::map<AttributePtr, std::list<AttributePtr> >::const_iterator
263     aRefIt = aBaseRefAttributes.begin(), aRefLast = aBaseRefAttributes.end();
264   std::cout << std::endl << "References to attributes of base feature [" <<
265     aBaseRefAttributes.size() << "]" << std::endl;
266   for (; aRefIt != aRefLast; aRefIt++) {
267     AttributePtr aBaseAttr = aRefIt->first;
268     std::list<AttributePtr> aRefAttributes = aRefIt->second;
269     std::string aRefsInfo;
270     std::list<AttributePtr>::const_iterator aRefAttrIt = aRefAttributes.begin(),
271                                             aRefAttrLast = aRefAttributes.end();
272     for (; aRefAttrIt != aRefAttrLast; aRefAttrIt++) {
273       if (!aRefsInfo.empty())
274         aRefsInfo.append(",");
275       AttributePtr aRAttr = *aRefAttrIt;
276       aRefsInfo.append(aRAttr->id());
277       FeaturePtr aRFeature = ModelAPI_Feature::feature(aRAttr->owner());
278       aRefsInfo.append("(" + aRFeature->name() + ") ");
279     }
280     std::shared_ptr<GeomDataAPI_Point2D> aPointAttr =
281       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aBaseAttr);
282     std::cout << aPointAttr->id().c_str() <<
283       ": " << "[" << aRefAttributes.size() << "] " << aRefsInfo << std::endl;
284   }
285   std::cout << std::endl;
286   std::cout << std::endl << "References to base feature [" <<
287     aRefsToFeature.size() << "]" << std::endl;
288   std::list<AttributePtr>::const_iterator aRefAttrIt = aRefsToFeature.begin(),
289                                           aRefAttrLast = aRefsToFeature.end();
290   std::string aRefsInfo;
291   for (; aRefAttrIt != aRefAttrLast; aRefAttrIt++) {
292     if (!aRefsInfo.empty())
293       aRefsInfo.append(",");
294     AttributePtr aRAttr = *aRefAttrIt;
295     aRefsInfo.append(aRAttr->id());
296     FeaturePtr aRFeature = ModelAPI_Feature::feature(aRAttr->owner());
297     aRefsInfo.append("(" + aRFeature->name() + ") ");
298   }
299   std::cout << "[" << aRefsToFeature.size() << "] " << aRefsInfo << std::endl;
300   std::cout << "---- getRefAttributes:end ----" << std::endl;
301 #endif
302
303   keepCurrentFeature();
304
305   std::set<AttributePoint2DPtr> aFurtherCoincidences;
306   std::set<std::pair<AttributePtr, AttributePtr>> aModifiedAttributes;
307   const std::string& aKind = aBaseFeature->getKind();
308   FeaturePtr aReplacingFeature, aNewFeature;
309   if (aKind == SketchPlugin_Circle::ID() ||
310       aKind == SketchPlugin_Ellipse::ID()) {
311     aReplacingFeature = trimClosed(aStartShapePoint2d, aLastShapePoint2d,
312                aFurtherCoincidences, aModifiedAttributes);
313
314     aFeaturesToDelete.insert(aBaseFeature);
315     // as circle is removed, erase it from dependencies(arguments) of this feature
316     // otherwise Trim feature will be removed with the circle before
317     // this operation is finished
318     aBaseObjectAttr->setObject(ResultPtr());
319   }
320   else if (aKind == SketchPlugin_Line::ID()) {
321     aNewFeature = trimLine(aStartShapePoint2d, aLastShapePoint2d, aBaseRefAttributes,
322                            aFurtherCoincidences, aModifiedAttributes);
323   }
324   else if (aKind == SketchPlugin_Arc::ID()) {
325     aNewFeature = trimArc(aStartShapePoint2d, aLastShapePoint2d, aBaseRefAttributes,
326                           aFurtherCoincidences, aModifiedAttributes);
327   }
328   else if (aKind == SketchPlugin_EllipticArc::ID()) {
329     aNewFeature = trimEllipticArc(aStartShapePoint2d, aLastShapePoint2d, aBaseRefAttributes,
330                           aFurtherCoincidences, aModifiedAttributes);
331   }
332
333   restoreCurrentFeature();
334
335   // constraints to end points of trim feature
336   if (myObjectToPoints.find(aBaseObject) == myObjectToPoints.end()) {
337     SketchPlugin_SegmentationTools::fillObjectShapes(
338         this, aBaseObject, myCashedShapes, myObjectToPoints);
339   }
340
341   // create coincidence to objects, intersected the base object
342   const GeomAlgoAPI_ShapeTools::PointToRefsMap& aRefsMap = myObjectToPoints.at(aBaseObject);
343   for (std::set<AttributePoint2DPtr>::const_iterator anIt = aFurtherCoincidences.begin(),
344                                                      aLast = aFurtherCoincidences.end();
345        anIt != aLast; anIt++) {
346     AttributePoint2DPtr aPointAttribute = (*anIt);
347     std::shared_ptr<GeomAPI_Pnt2d> aPoint2d = aPointAttribute->pnt();
348
349 #ifdef DEBUG_TRIM
350     std::cout << "<compare Points> => " << std::endl
351             << "aPoint2d: [" << aPoint2d->x() << ", " << aPoint2d->y() << "]" << std::endl;
352     if (aStartShapePoint2d.get())
353       std::cout << "Start Point: [" << aStartShapePoint2d->x() << ", " << aStartShapePoint2d->y()
354                 << "]" << std::endl;
355     if (aLastShapePoint2d.get())
356       std::cout << "Last Point: [" << aLastShapePoint2d->x() << ", " << aLastShapePoint2d->y()
357                 << "]" << std::endl;
358 #endif
359
360     std::shared_ptr<GeomAPI_Pnt> aPoint;
361     if (aStartShapePoint2d.get() && aPoint2d->isEqual(aStartShapePoint2d))
362       aPoint = aStartShapePoint;
363     else if (aLastShapePoint2d.get() && aPoint2d->isEqual(aLastShapePoint2d))
364       aPoint = aLastShapePoint;
365
366     if (!aPoint.get())
367       continue;
368
369     std::pair<std::list<AttributePoint2DPtr >, std::list<ObjectPtr > > anInfo;
370     for (GeomAlgoAPI_ShapeTools::PointToRefsMap::const_iterator aRefIt = aRefsMap.begin();
371          aRefIt != aRefsMap.end(); aRefIt++)
372     {
373       if (aRefIt->first->isEqual(aPoint)) {
374         anInfo = aRefIt->second;
375         break;
376       }
377     }
378     const std::list<ObjectPtr>& anObjects = anInfo.second;
379     for (std::list<ObjectPtr>::const_iterator anObjectIt = anObjects.begin();
380       anObjectIt != anObjects.end(); anObjectIt++) {
381       SketchPlugin_Tools::createConstraintAttrObject(sketch(),
382             SketchPlugin_ConstraintCoincidence::ID(),
383             aPointAttribute, *anObjectIt);
384     }
385   }
386
387   // move constraints from base feature to replacing feature: ignore coincidences to feature
388   // if attributes of coincidence participated in split
389   ResultPtr aReplacingResult;
390   if (aReplacingFeature.get()) {
391     aReplacingFeature->execute(); // need it to obtain result
392     aReplacingResult = aReplacingFeature->lastResult();
393   }
394   for(std::list<AttributePtr>::const_iterator anIt = aRefsToFeature.begin(),
395                                           aLast = aRefsToFeature.end();
396       anIt != aLast; anIt++) {
397     AttributePtr anAttribute = *anIt;
398
399     if (setCoincidenceToAttribute(anAttribute, aFurtherCoincidences, aFeaturesToDelete))
400       continue;
401
402     // move tangency constraint to the nearest feature if possible
403     if (aNewFeature.get() && moveTangency(anAttribute, aNewFeature))
404       continue;
405
406     if (aReplacingResult.get()) {
407       AttributeRefAttrPtr aRefAttr =
408           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttribute);
409       if (aRefAttr.get())
410         aRefAttr->setObject(aReplacingResult);
411       else {
412         AttributeReferencePtr aReferenceAttr =
413                              std::dynamic_pointer_cast<ModelAPI_AttributeReference>(anAttribute);
414         if (aReferenceAttr.get())
415           aReferenceAttr->setObject(aReplacingResult);
416       }
417     }
418   }
419
420   SketchPlugin_SegmentationTools::updateRefAttConstraints(aBaseRefAttributes, aModifiedAttributes);
421
422   // Wait all constraints being created, then send update events
423   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
424   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
425   if (isUpdateFlushed)
426     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
427
428   // delete constraints
429 #ifdef DEBUG_TRIM
430   if (aFeaturesToDelete.size() > 0) {
431     std::cout << "after SPlit: removeFeaturesAndReferences: " << std::endl;
432     std::string aValue;
433     for (std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin();
434          anIt != aFeaturesToDelete.end(); anIt++) {
435       FeaturePtr aFeature = *anIt;
436       std::cout << aFeature->data()->name() << std::endl;
437     }
438   }
439 #endif
440   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToDelete);
441   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
442
443   SketchPlugin_SegmentationTools::updateFeaturesAfterOperation(aFeaturesToUpdate);
444
445   // Send events to update the sub-features by the solver.
446   if(isUpdateFlushed) {
447     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
448   }
449
450   if (anIsEqualPreviewAndSelected) {
451     // equal preview and selected objects
452     // nothing to do if the preview and selected objects are different
453     if (aReplacingResult.get()) { // base object was removed
454       aPreviewObject = aReplacingResult;
455       //aMessage->setSelectedObject(aReplacingResult);
456 #ifdef DEBUG_TRIM_METHODS
457       if (!aSelectedShape.get())
458         std::cout << "Set empty selected object" << std::endl;
459       else
460         std::cout << "Set shape with ShapeType: " << aSelectedShape->shapeTypeStr() << std::endl;
461 #endif
462     }
463     else {
464       aPreviewObject = ObjectPtr();
465
466       aBaseFeature->execute(); // should recompute shapes of result to do not check obsolete one
467       aBaseObject = aBaseFeature->lastResult();
468       std::shared_ptr<GeomAPI_Pnt> aPreviewPnt = sketch()->to3D(aPreviewPnt2d->x(),
469                                                                 aPreviewPnt2d->y());
470       ResultPtr aBaseResult = std::dynamic_pointer_cast<ModelAPI_Result>(aBaseObject);
471       if (aBaseResult) {
472         GeomShapePtr aShape = aBaseResult->shape();
473         std::shared_ptr<GeomAPI_Pnt> aProjectedPoint;
474         if (ModelGeomAlgo_Point2D::isPointOnEdge(aShape, aPreviewPnt, aProjectedPoint))
475           aPreviewObject = aBaseResult;
476       }
477       if (!aPreviewObject.get() && aNewFeature.get()) {
478         ResultPtr aNewFeatureResult = aNewFeature->lastResult();
479         if (aNewFeatureResult.get()) {
480           GeomShapePtr aShape = aNewFeatureResult->shape();
481           std::shared_ptr<GeomAPI_Pnt> aProjectedPoint;
482           if (ModelGeomAlgo_Point2D::isPointOnEdge(aShape, aPreviewPnt, aProjectedPoint))
483             aPreviewObject = aNewFeatureResult;
484         }
485       }
486     }
487   }
488   if (aPreviewObject.get()) {
489     std::shared_ptr<ModelAPI_EventReentrantMessage> aMessage = std::shared_ptr
490       <ModelAPI_EventReentrantMessage>(new ModelAPI_EventReentrantMessage(
491                                            ModelAPI_EventReentrantMessage::eventId(), this));
492     aMessage->setSelectedObject(aPreviewObject);
493     Events_Loop::loop()->send(aMessage);
494   }
495 #ifdef DEBUG_TRIM
496   std::cout << "SketchPlugin_Trim::done" << std::endl;
497 #endif
498 }
499
500 // LCOV_EXCL_START
501 std::string SketchPlugin_Trim::processEvent(const std::shared_ptr<Events_Message>& theMessage)
502 {
503 #ifdef DEBUG_TRIM_METHODS
504   std::cout << "SketchPlugin_Trim::processEvent:" << data()->name() << std::endl;
505 #endif
506   std::string aFilledAttributeName;
507
508   std::shared_ptr<ModelAPI_EventReentrantMessage> aMessage =
509         std::dynamic_pointer_cast<ModelAPI_EventReentrantMessage>(theMessage);
510   if (aMessage.get()) {
511     ObjectPtr anObject = aMessage->selectedObject();
512     std::shared_ptr<GeomAPI_Pnt2d> aPoint = aMessage->clickedPoint();
513
514     if (anObject.get() && aPoint.get()) {
515       if (myCashedShapes.find(anObject) == myCashedShapes.end()) {
516         SketchPlugin_SegmentationTools::fillObjectShapes(
517             this, anObject, myCashedShapes, myObjectToPoints);
518       }
519       const std::set<GeomShapePtr>& aShapes = myCashedShapes[anObject];
520       if (aShapes.size() > 1) {
521         std::shared_ptr<ModelAPI_AttributeReference> aRefSelectedAttr =
522                               std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
523                               data()->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
524         std::shared_ptr<ModelAPI_AttributeReference> aRefPreviewAttr =
525                               std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
526                               data()->attribute(SketchPlugin_Trim::PREVIEW_OBJECT()));
527         aRefSelectedAttr->setValue(anObject);
528         aRefPreviewAttr->setValue(anObject);
529
530         std::shared_ptr<GeomDataAPI_Point2D> aPointSelectedAttr =
531                               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
532                               data()->attribute(SketchPlugin_Trim::SELECTED_POINT()));
533         std::shared_ptr<GeomDataAPI_Point2D> aPointPreviewAttr =
534                               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
535                               data()->attribute(SketchPlugin_Trim::PREVIEW_POINT()));
536         aPointSelectedAttr->setValue(aPoint);
537         aPointPreviewAttr->setValue(aPoint);
538
539         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
540
541         GeomShapePtr aSelectedShape = SketchPlugin_SegmentationTools::getSubShape(this,
542             SELECTED_OBJECT(), SELECTED_POINT(), myCashedShapes, myObjectToPoints);
543   #ifdef DEBUG_TRIM_METHODS
544         if (!aSelectedShape.get())
545           std::cout << "Set empty selected object" << std::endl;
546         else
547           std::cout << "Set shape with ShapeType: " << aSelectedShape->shapeTypeStr() << std::endl;
548   #endif
549         aFilledAttributeName = SketchPlugin_Trim::SELECTED_OBJECT();
550       }
551     }
552   }
553   return aFilledAttributeName;
554 }
555 // LCOV_EXCL_STOP
556
557 bool SketchPlugin_Trim::setCoincidenceToAttribute(const AttributePtr& theAttribute,
558                                 const std::set<AttributePoint2DPtr>& theFurtherCoincidences,
559                                 std::set<std::shared_ptr<ModelAPI_Feature>>& theFeaturesToDelete)
560 {
561   FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
562   if (aFeature->getKind() != SketchPlugin_ConstraintCoincidence::ID())
563     return false;
564
565   AttributePoint2DPtr aRefPointAttr = SketchPlugin_ConstraintCoincidence::getPoint(aFeature);
566   if (!aRefPointAttr.get())
567     return false;
568   std::shared_ptr<GeomAPI_Pnt2d> aRefPnt2d = aRefPointAttr->pnt();
569
570   std::set<AttributePoint2DPtr>::const_iterator anIt = theFurtherCoincidences.begin(),
571                                                 aLast = theFurtherCoincidences.end();
572   bool aFoundPoint = false;
573   for (; anIt != aLast && !aFoundPoint; anIt++) {
574     AttributePoint2DPtr aPointAttribute = (*anIt);
575     std::shared_ptr<GeomAPI_Pnt2d> aPoint2d = aPointAttribute->pnt();
576     if (aPoint2d->isEqual(aRefPnt2d)) {
577       // create new coincidence and then remove the old one
578       SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
579           SketchPlugin_ConstraintCoincidence::ID(),
580           aRefPointAttr, aPointAttribute);
581       theFeaturesToDelete.insert(aFeature);
582     }
583   }
584   return aFoundPoint;
585 }
586
587 bool SketchPlugin_Trim::moveTangency(const AttributePtr& theAttribute,
588                                      const FeaturePtr& theFeature)
589 {
590   FeaturePtr aFeature = ModelAPI_Feature::feature(theAttribute->owner());
591   if (aFeature->getKind() != SketchPlugin_ConstraintTangent::ID())
592     return false;
593
594   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
595                                                                            theAttribute);
596   if (!aRefAttr.get())
597     return false;
598
599   // get shape of tangent object to the current
600   std::string aTangentAttr = SketchPlugin_Constraint::ENTITY_A();
601   if (aRefAttr->id() == SketchPlugin_Constraint::ENTITY_A())
602     aTangentAttr = SketchPlugin_Constraint::ENTITY_B();
603   AttributeRefAttrPtr aTangentRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
604                                                      aFeature->attribute(aTangentAttr));
605   FeaturePtr aTangentFeature = ModelAPI_Feature::feature(aTangentRefAttr->object());
606
607   // get shape of the feature of the attribute
608   FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(aRefAttr->object());
609   anAttributeFeature->execute(); // the modified value should be applyed to recompute shape
610   GeomAlgoAPI_ShapeTools::PointToRefsMap aPointToAttributeOrObject;
611   std::list<FeaturePtr> aFeatures;
612   aFeatures.push_back(anAttributeFeature);
613   ModelGeomAlgo_Point2D::getPointsIntersectedShape(aTangentFeature, aFeatures,
614                                                    aPointToAttributeOrObject);
615   if (!aPointToAttributeOrObject.empty())
616     return true; // the attribute feature has a point of intersection, so we do not replace it
617
618   // get shape of the feature
619   aPointToAttributeOrObject.clear();
620   aFeatures.clear();
621   aFeatures.push_back(theFeature);
622   ModelGeomAlgo_Point2D::getPointsIntersectedShape(aTangentFeature, aFeatures,
623                                                    aPointToAttributeOrObject);
624   if (!aPointToAttributeOrObject.empty()) {
625     std::set<ResultPtr> anEdgeShapes;
626     ModelGeomAlgo_Shape::shapesOfType(theFeature, GeomAPI_Shape::EDGE, anEdgeShapes);
627     if (!anEdgeShapes.empty()) {
628       ResultPtr aResult = *anEdgeShapes.begin();
629       if (aResult.get()) {
630         aRefAttr->setObject(aResult);
631         return true; // the attribute feature has a point of intersection, so we do not replace it
632       }
633     }
634   }
635   return false;
636 }
637
638 AISObjectPtr SketchPlugin_Trim::getAISObject(AISObjectPtr thePrevious)
639 {
640   return SketchPlugin_SegmentationTools::getAISObject(thePrevious,
641       this, PREVIEW_OBJECT(), PREVIEW_POINT(), SELECTED_OBJECT(), SELECTED_POINT());
642 }
643
644 void SketchPlugin_Trim::getConstraints(std::set<FeaturePtr>& theFeaturesToDelete,
645                                        std::set<FeaturePtr>& theFeaturesToUpdate)
646 {
647   std::shared_ptr<ModelAPI_Data> aData = data();
648
649   // Check the base objects are initialized.
650   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
651                                          aData->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
652   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
653   ResultPtr aBaseFeatureResult = aBaseFeature->lastResult();
654
655   std::set<AttributePtr> aRefsList = aBaseFeatureResult->data()->refsToMe();
656   std::set<AttributePtr> aFRefsList = aBaseFeature->data()->refsToMe();
657   aRefsList.insert(aFRefsList.begin(), aFRefsList.end());
658
659   std::set<AttributePtr>::const_iterator aIt;
660   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
661     std::shared_ptr<ModelAPI_Attribute> anAttr = (*aIt);
662     FeaturePtr aRefFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
663     std::string aRefFeatureKind = aRefFeature->getKind();
664     std::string anAttributeId = anAttr->id();
665     if ((aRefFeatureKind == SketchPlugin_ConstraintMirror::ID() &&
666          anAttributeId == SketchPlugin_ConstraintMirror::MIRROR_LIST_ID()) ||
667         (aRefFeatureKind == SketchPlugin_MultiRotation::ID() &&
668          anAttributeId == SketchPlugin_MultiRotation::ROTATION_LIST_ID()) ||
669         (aRefFeatureKind == SketchPlugin_MultiTranslation::ID() &&
670          anAttributeId == SketchPlugin_MultiTranslation::TRANSLATION_LIST_ID()) ||
671         aRefFeatureKind == SketchPlugin_ConstraintMiddle::ID())
672       theFeaturesToDelete.insert(aRefFeature);
673     else if (aRefFeatureKind == SketchPlugin_ConstraintLength::ID())
674       theFeaturesToUpdate.insert(aRefFeature);
675   }
676 }
677
678 void SketchPlugin_Trim::removeReferencesToAttribute(const AttributePtr& theAttribute,
679                   std::map<AttributePtr, std::list<AttributePtr> >& theBaseRefAttributes)
680 {
681   /// not found in references
682   if (theBaseRefAttributes.find(theAttribute) == theBaseRefAttributes.end())
683     return;
684
685   std::list<AttributePtr> aRefAttributes = theBaseRefAttributes.at(theAttribute);
686   std::list<AttributePtr>::const_iterator aRefIt = aRefAttributes.begin(),
687                                           aRLast = aRefAttributes.end();
688
689   std::set<FeaturePtr> aFeaturesToDelete;
690   for (; aRefIt != aRLast; aRefIt++) {
691     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefIt);
692     if (aRefAttr.get()) {
693       aFeaturesToDelete.insert(ModelAPI_Feature::feature(aRefAttr->owner()));
694     }
695   }
696
697 #ifdef DEBUG_TRIM
698   // delete constraints
699   if (aFeaturesToDelete.size() > 0) {
700     std::cout << "removeReferencesToAttribute: " << std::endl;
701     std::string aValue;
702     for (std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin();
703          anIt != aFeaturesToDelete.end(); anIt++) {
704       FeaturePtr aFeature = *anIt;
705       std::cout << aFeature->data()->name() << std::endl;
706     }
707   }
708 #endif
709   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToDelete);
710   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
711 }
712
713 FeaturePtr SketchPlugin_Trim::trimLine(const std::shared_ptr<GeomAPI_Pnt2d>& theStartShapePoint,
714                   const std::shared_ptr<GeomAPI_Pnt2d>& theLastShapePoint,
715                   std::map<AttributePtr, std::list<AttributePtr> >& theBaseRefAttributes,
716                   std::set<AttributePoint2DPtr>& thePoints,
717                   std::set<std::pair<AttributePtr, AttributePtr>>& theModifiedAttributes)
718 {
719   FeaturePtr anNewFeature;
720
721   // Check the base objects are initialized.
722   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
723                                         data()->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
724   ObjectPtr aBaseObject = aBaseObjectAttr->value();
725   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
726
727   /// points of trim
728   AttributePoint2DPtr aStartPointAttrOfBase, anEndPointAttrOfBase;
729   SketchPlugin_SegmentationTools::getFeaturePoints(
730       aBaseFeature, aStartPointAttrOfBase, anEndPointAttrOfBase);
731
732   std::shared_ptr<GeomAPI_Pnt2d> aStartFeaturePoint = aStartPointAttrOfBase->pnt();
733   std::shared_ptr<GeomAPI_Pnt2d> aLastFeaturePoint = anEndPointAttrOfBase->pnt();
734
735   std::shared_ptr<GeomAPI_Pnt2d> aStartShapePoint = theStartShapePoint;
736   std::shared_ptr<GeomAPI_Pnt2d> aLastShapePoint = theLastShapePoint;
737   arrangePointsOnLine(aStartPointAttrOfBase, anEndPointAttrOfBase,
738                       aStartShapePoint, aLastShapePoint);
739 #ifdef DEBUG_TRIM
740   std::cout << "Arranged points (to build split between 1st and 2nd points:" << std::endl;
741   if (aStartShapePoint.get())
742     std::cout << "Start point: [" << aStartShapePoint->x() << ", " <<
743                                        aStartShapePoint->y() << "]" << std::endl;
744   std::cout << "1st point:   [" << aStartFeaturePoint->x() << ", " <<
745                                    aStartFeaturePoint->y() << "]" << std::endl;
746   if (aLastShapePoint.get())
747     std::cout << "2st point:   [" << aLastShapePoint->x() << ", " <<
748                                      aLastShapePoint->y() << "]" << std::endl;
749   std::cout << "End point:   [" << aLastFeaturePoint->x() << ", " <<
750                                    aLastFeaturePoint->y() << "]" << std::endl;
751 #endif
752
753   bool isStartPoint = !aStartShapePoint.get() || aStartFeaturePoint->isEqual(aStartShapePoint);
754   bool isLastPoint = !aLastShapePoint.get() || aLastFeaturePoint->isEqual(aLastShapePoint);
755   if (isStartPoint || isLastPoint) {
756     // result is one line: changed existing line
757     std::string aModifiedAttribute = isStartPoint ? SketchPlugin_Line::START_ID()
758                                                   : SketchPlugin_Line::END_ID();
759     std::shared_ptr<GeomAPI_Pnt2d> aPoint;
760     if (aStartShapePoint.get() && aLastShapePoint.get())
761       aPoint = isStartPoint ? aLastShapePoint : aStartShapePoint;
762     else
763       aPoint = aStartShapePoint.get() ? aStartShapePoint : aLastShapePoint;
764
765     // it is important to delete references before the feature modification because
766     // if deletion will be after the feature modification, solver returns the feature back
767     removeReferencesToAttribute(aBaseFeature->attribute(aModifiedAttribute),
768                                 theBaseRefAttributes);
769
770     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aPoint);
771     //theModifiedAttributes.insert(
772     //  std::make_pair(aBaseFeature->attribute(aModifiedAttribute), AttributePtr()));
773
774     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
775                                (aBaseFeature->attribute(aModifiedAttribute)));
776   }
777   else {
778     // result is two lines: start line point - start shape point,
779     // last shape point - last line point
780     // create second line
781     anNewFeature = SketchPlugin_SegmentationTools::createLineFeature(
782         aBaseFeature, aLastShapePoint, aLastFeaturePoint);
783     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
784                                (anNewFeature->attribute(SketchPlugin_Line::START_ID())));
785
786     std::string aModifiedAttribute = SketchPlugin_Line::END_ID();
787     theModifiedAttributes.insert(
788       std::make_pair(aBaseFeature->attribute(aModifiedAttribute),
789                                    anNewFeature->attribute(SketchPlugin_Line::END_ID())));
790
791     // modify base arc
792     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aStartShapePoint);
793
794     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
795                                (aBaseFeature->attribute(aModifiedAttribute)));
796
797     // Collinear constraint for lines
798     SketchPlugin_Tools::createConstraintObjectObject(sketch(),
799                                          SketchPlugin_ConstraintCollinear::ID(),
800                                          aBaseFeature->lastResult(),
801                                          anNewFeature->lastResult());
802   }
803   return anNewFeature;
804 }
805
806 FeaturePtr SketchPlugin_Trim::trimArc(const std::shared_ptr<GeomAPI_Pnt2d>& theStartShapePoint,
807                  const std::shared_ptr<GeomAPI_Pnt2d>& theLastShapePoint,
808                  std::map<AttributePtr, std::list<AttributePtr> >& theBaseRefAttributes,
809                  std::set<AttributePoint2DPtr>& thePoints,
810                  std::set<std::pair<AttributePtr, AttributePtr>>& theModifiedAttributes)
811 {
812   FeaturePtr anNewFeature;
813   // Check the base objects are initialized.
814   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
815                                         data()->attribute(SketchPlugin_Trim::SELECTED_OBJECT()));
816   ObjectPtr aBaseObject = aBaseObjectAttr->value();
817   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
818
819   /// points of trim
820   AttributePoint2DPtr aStartPointAttrOfBase, anEndPointAttrOfBase;
821   SketchPlugin_SegmentationTools::getFeaturePoints(
822       aBaseFeature, aStartPointAttrOfBase, anEndPointAttrOfBase);
823
824   std::shared_ptr<GeomAPI_Pnt2d> aStartArcPoint = aStartPointAttrOfBase->pnt();
825   std::shared_ptr<GeomAPI_Pnt2d> aLastArcPoint = anEndPointAttrOfBase->pnt();
826
827   std::shared_ptr<GeomAPI_Pnt2d> aStartShapePoint = theStartShapePoint;
828   std::shared_ptr<GeomAPI_Pnt2d> aLastShapePoint = theLastShapePoint;
829   arrangePointsOnArc(aBaseFeature, aStartPointAttrOfBase, anEndPointAttrOfBase,
830                      aStartShapePoint, aLastShapePoint);
831 #ifdef DEBUG_TRIM
832   std::cout << "Arranged points (to build split between 1st and 2nd points:" << std::endl;
833   if (aStartShapePoint.get())
834     std::cout << "Start shape point: [" << aStartShapePoint->x() << ", " <<
835                                        aStartShapePoint->y() << "]" << std::endl;
836   std::cout << "Start arc attribute point:   [" << aStartArcPoint->x() << ", " <<
837                                    aStartArcPoint->y() << "]" << std::endl;
838   if (aLastShapePoint.get())
839     std::cout << "Last shape point:   [" << aLastShapePoint->x() << ", " <<
840                                      aLastShapePoint->y() << "]" << std::endl;
841   std::cout << "Last arc attribute point:   [" << aLastArcPoint->x() << ", " <<
842                                    aLastArcPoint->y() << "]" << std::endl;
843 #endif
844
845   bool isStartPoint = !aStartShapePoint.get() || aStartArcPoint->isEqual(aStartShapePoint);
846   bool isLastPoint = !aLastShapePoint.get() || aLastArcPoint->isEqual(aLastShapePoint);
847   if (isStartPoint || isLastPoint) {
848     // result is one arc: changed existing arc
849     std::string aModifiedAttribute = isStartPoint ? SketchPlugin_Arc::START_ID()
850                                                   : SketchPlugin_Arc::END_ID();
851     std::shared_ptr<GeomAPI_Pnt2d> aPoint;
852     if (aStartShapePoint.get() && aLastShapePoint.get())
853       aPoint = isStartPoint ? aLastShapePoint : aStartShapePoint;
854     else
855       aPoint = aStartShapePoint.get() ? aStartShapePoint : aLastShapePoint;
856
857     removeReferencesToAttribute(aBaseFeature->attribute(aModifiedAttribute),
858                                 theBaseRefAttributes);
859
860     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aPoint);
861
862     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
863                                (aBaseFeature->attribute(aModifiedAttribute)));
864   }
865   else {
866     // result is two arcs: start arc point - start shape point, last shape point - last arc point
867     // create second arc
868     anNewFeature = SketchPlugin_SegmentationTools::createArcFeature(
869         aBaseFeature, aLastShapePoint, aLastArcPoint);
870     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
871                                (anNewFeature->attribute(SketchPlugin_Arc::START_ID())));
872
873     std::string aModifiedAttribute = SketchPlugin_Arc::END_ID();
874     theModifiedAttributes.insert(
875       std::make_pair(aBaseFeature->attribute(aModifiedAttribute),
876                                    anNewFeature->attribute(SketchPlugin_Arc::END_ID())));
877
878     // modify base arc
879     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aStartShapePoint);
880
881     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
882                                (aBaseFeature->attribute(aModifiedAttribute)));
883
884     // equal Radius constraint for arcs
885     SketchPlugin_Tools::createConstraintObjectObject(sketch(),
886                                          SketchPlugin_ConstraintEqual::ID(),
887                                          aBaseFeature->lastResult(),
888                                          anNewFeature->lastResult());
889     // coincident centers constraint
890     SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
891                                          SketchPlugin_ConstraintCoincidence::ID(),
892                                          aBaseFeature->attribute(SketchPlugin_Arc::CENTER_ID()),
893                                          anNewFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
894
895 #ifdef DEBUG_TRIM
896     std::cout << "Created arc on points:" << std::endl;
897     std::cout << "Start shape point: [" << aStartShapePoint->x() << ", " <<
898                                            aStartShapePoint->y() << "]" << std::endl;
899 #endif
900   }
901   return anNewFeature;
902 }
903
904 FeaturePtr SketchPlugin_Trim::trimEllipticArc(
905                  const std::shared_ptr<GeomAPI_Pnt2d>& theStartShapePoint,
906                  const std::shared_ptr<GeomAPI_Pnt2d>& theLastShapePoint,
907                  std::map<AttributePtr, std::list<AttributePtr> >& theBaseRefAttributes,
908                  std::set<AttributePoint2DPtr>& thePoints,
909                  std::set<std::pair<AttributePtr, AttributePtr>>& theModifiedAttributes)
910 {
911   FeaturePtr anNewFeature;
912   // Check the base objects are initialized.
913   AttributeReferencePtr aBaseObjectAttr = reference(SELECTED_OBJECT());
914   ObjectPtr aBaseObject = aBaseObjectAttr->value();
915   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
916
917   // points of trim
918   AttributePoint2DPtr aStartPointAttrOfBase, anEndPointAttrOfBase;
919   SketchPlugin_SegmentationTools::getFeaturePoints(
920       aBaseFeature, aStartPointAttrOfBase, anEndPointAttrOfBase);
921
922   std::shared_ptr<GeomAPI_Pnt2d> aStartArcPoint = aStartPointAttrOfBase->pnt();
923   std::shared_ptr<GeomAPI_Pnt2d> aLastArcPoint = anEndPointAttrOfBase->pnt();
924
925   std::shared_ptr<GeomAPI_Pnt2d> aStartShapePoint = theStartShapePoint;
926   std::shared_ptr<GeomAPI_Pnt2d> aLastShapePoint = theLastShapePoint;
927   arrangePointsOnArc(aBaseFeature, aStartPointAttrOfBase, anEndPointAttrOfBase,
928                      aStartShapePoint, aLastShapePoint);
929 #ifdef DEBUG_TRIM
930   std::cout << "Arranged points (to build split between 1st and 2nd points:" << std::endl;
931   if (aStartShapePoint.get())
932     std::cout << "Start shape point: [" << aStartShapePoint->x() << ", " <<
933                                        aStartShapePoint->y() << "]" << std::endl;
934   std::cout << "Start arc attribute point:   [" << aStartArcPoint->x() << ", " <<
935                                    aStartArcPoint->y() << "]" << std::endl;
936   if (aLastShapePoint.get())
937     std::cout << "Last shape point:   [" << aLastShapePoint->x() << ", " <<
938                                      aLastShapePoint->y() << "]" << std::endl;
939   std::cout << "Last arc attribute point:   [" << aLastArcPoint->x() << ", " <<
940                                    aLastArcPoint->y() << "]" << std::endl;
941 #endif
942
943   bool isStartPoint = !aStartShapePoint.get() || aStartArcPoint->isEqual(aStartShapePoint);
944   bool isLastPoint = !aLastShapePoint.get() || aLastArcPoint->isEqual(aLastShapePoint);
945   if (isStartPoint || isLastPoint) {
946     // result is one arc: changed existing arc
947     std::string aModifiedAttribute = isStartPoint ? SketchPlugin_EllipticArc::START_POINT_ID()
948                                                   : SketchPlugin_EllipticArc::END_POINT_ID();
949     std::shared_ptr<GeomAPI_Pnt2d> aPoint;
950     if (aStartShapePoint.get() && aLastShapePoint.get())
951       aPoint = isStartPoint ? aLastShapePoint : aStartShapePoint;
952     else
953       aPoint = aStartShapePoint.get() ? aStartShapePoint : aLastShapePoint;
954
955     removeReferencesToAttribute(aBaseFeature->attribute(aModifiedAttribute),
956                                 theBaseRefAttributes);
957
958     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aPoint);
959
960     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
961                                (aBaseFeature->attribute(aModifiedAttribute)));
962   }
963   else {
964     // result is two arcs: start arc point - start shape point, last shape point - last arc point
965     // create second arc
966     anNewFeature = SketchPlugin_SegmentationTools::createArcFeature(
967         aBaseFeature, aLastShapePoint, aLastArcPoint);
968     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
969                      anNewFeature->attribute(SketchPlugin_EllipticArc::START_POINT_ID())));
970
971     std::string aModifiedAttribute = SketchPlugin_EllipticArc::END_POINT_ID();
972     theModifiedAttributes.insert(
973       std::make_pair(aBaseFeature->attribute(aModifiedAttribute),
974                      anNewFeature->attribute(SketchPlugin_EllipticArc::END_POINT_ID())));
975
976     // modify base arc
977     fillPointAttribute(aBaseFeature->attribute(aModifiedAttribute), aStartShapePoint);
978
979     thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
980                                (aBaseFeature->attribute(aModifiedAttribute)));
981
982     // make elliptic arcs equal
983     SketchPlugin_Tools::createConstraintObjectObject(sketch(),
984                                          SketchPlugin_ConstraintEqual::ID(),
985                                          aBaseFeature->lastResult(),
986                                          anNewFeature->lastResult());
987     // coincident centers constraint
988     SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
989         SketchPlugin_ConstraintCoincidence::ID(),
990         aBaseFeature->attribute(SketchPlugin_EllipticArc::CENTER_ID()),
991         anNewFeature->attribute(SketchPlugin_EllipticArc::CENTER_ID()));
992
993 #ifdef DEBUG_TRIM
994     std::cout << "Created arc on points:" << std::endl;
995     std::cout << "Start shape point: [" << aStartShapePoint->x() << ", " <<
996                                            aStartShapePoint->y() << "]" << std::endl;
997 #endif
998   }
999   return anNewFeature;
1000 }
1001
1002 FeaturePtr SketchPlugin_Trim::trimClosed(const std::shared_ptr<GeomAPI_Pnt2d>& theStartShapePoint,
1003                                          const std::shared_ptr<GeomAPI_Pnt2d>& theLastShapePoint,
1004                                          std::set<AttributePoint2DPtr>& thePoints,
1005                            std::set<std::pair<AttributePtr, AttributePtr>>& theModifiedAttributes)
1006 {
1007   // Check the base objects are initialized.
1008   AttributeReferencePtr aBaseObjectAttr = reference(SELECTED_OBJECT());
1009   ObjectPtr aBaseObject = aBaseObjectAttr->value();
1010   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
1011
1012   // trim feature
1013   FeaturePtr anNewFeature = SketchPlugin_SegmentationTools::createArcFeature(
1014       aBaseFeature, theStartShapePoint, theLastShapePoint);
1015   // arc created by trim of circle is always correct, that means that it is not inversed
1016   const std::string& aReversedAttrName = anNewFeature->getKind() == SketchPlugin_Arc::ID() ?
1017       SketchPlugin_Arc::REVERSED_ID() : SketchPlugin_EllipticArc::REVERSED_ID();
1018   anNewFeature->boolean(aReversedAttrName)->setValue(false);
1019
1020   if (aBaseFeature->getKind() == SketchPlugin_Circle::ID()) {
1021     theModifiedAttributes.insert(
1022       std::make_pair(aBaseFeature->attribute(SketchPlugin_Circle::CENTER_ID()),
1023                      anNewFeature->attribute(SketchPlugin_Arc::CENTER_ID())));
1024   }
1025   else if (aBaseFeature->getKind() == SketchPlugin_Ellipse::ID()) {
1026     theModifiedAttributes.insert(std::make_pair(
1027         aBaseFeature->attribute(SketchPlugin_Ellipse::CENTER_ID()),
1028         anNewFeature->attribute(SketchPlugin_EllipticArc::CENTER_ID())));
1029     theModifiedAttributes.insert(std::make_pair(
1030         aBaseFeature->attribute(SketchPlugin_Ellipse::FIRST_FOCUS_ID()),
1031         anNewFeature->attribute(SketchPlugin_EllipticArc::FIRST_FOCUS_ID())));
1032     theModifiedAttributes.insert(std::make_pair(
1033         aBaseFeature->attribute(SketchPlugin_Ellipse::SECOND_FOCUS_ID()),
1034         anNewFeature->attribute(SketchPlugin_EllipticArc::SECOND_FOCUS_ID())));
1035     theModifiedAttributes.insert(std::make_pair(
1036         aBaseFeature->attribute(SketchPlugin_Ellipse::MAJOR_AXIS_START_ID()),
1037         anNewFeature->attribute(SketchPlugin_EllipticArc::MAJOR_AXIS_START_ID())));
1038     theModifiedAttributes.insert(std::make_pair(
1039         aBaseFeature->attribute(SketchPlugin_Ellipse::MAJOR_AXIS_END_ID()),
1040         anNewFeature->attribute(SketchPlugin_EllipticArc::MAJOR_AXIS_END_ID())));
1041     theModifiedAttributes.insert(std::make_pair(
1042         aBaseFeature->attribute(SketchPlugin_Ellipse::MINOR_AXIS_START_ID()),
1043         anNewFeature->attribute(SketchPlugin_EllipticArc::MINOR_AXIS_START_ID())));
1044     theModifiedAttributes.insert(std::make_pair(
1045         aBaseFeature->attribute(SketchPlugin_Ellipse::MINOR_AXIS_END_ID()),
1046         anNewFeature->attribute(SketchPlugin_EllipticArc::MINOR_AXIS_END_ID())));
1047
1048     // update the PARENT_ID reference for all the features created by the ellipse
1049     const std::set<AttributePtr>& aRefs = aBaseFeature->data()->refsToMe();
1050     std::list<AttributePtr> aRefsToParent;
1051     for (std::set<AttributePtr>::const_iterator aRef = aRefs.begin(); aRef != aRefs.end(); ++aRef) {
1052       if ((*aRef)->id() == SketchPlugin_Line::PARENT_ID() ||
1053           (*aRef)->id() == SketchPlugin_Point::PARENT_ID())
1054         aRefsToParent.push_back(*aRef);
1055     }
1056     for (std::list<AttributePtr>::iterator aRef = aRefsToParent.begin();
1057          aRef != aRefsToParent.end(); ++aRef)
1058       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(*aRef)->setValue(anNewFeature);
1059   }
1060
1061   const std::string& aStartAttrName = anNewFeature->getKind() == SketchPlugin_Arc::ID() ?
1062       SketchPlugin_Arc::START_ID() : SketchPlugin_EllipticArc::START_POINT_ID();
1063   const std::string& aEndAttrName = anNewFeature->getKind() == SketchPlugin_Arc::ID() ?
1064       SketchPlugin_Arc::END_ID() : SketchPlugin_EllipticArc::END_POINT_ID();
1065
1066   thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
1067                              (anNewFeature->attribute(aStartAttrName)));
1068   thePoints.insert(std::dynamic_pointer_cast<GeomDataAPI_Point2D>
1069                              (anNewFeature->attribute(aEndAttrName)));
1070
1071   return anNewFeature;
1072 }
1073
1074 void SketchPlugin_Trim::arrangePointsOnLine(const AttributePoint2DPtr& theStartPointAttr,
1075                                             const AttributePoint2DPtr& theEndPointAttr,
1076                                             std::shared_ptr<GeomAPI_Pnt2d>& theFirstPoint,
1077                                             std::shared_ptr<GeomAPI_Pnt2d>& theLastPoint) const
1078 {
1079   if (!theFirstPoint.get() || !theLastPoint.get())
1080     return;
1081
1082   // if first point is closer to last point, swap first and last values
1083   if (theStartPointAttr->pnt()->distance(theFirstPoint) >
1084       theStartPointAttr->pnt()->distance(theLastPoint)) {
1085     std::shared_ptr<GeomAPI_Pnt2d> aTmpPoint = theFirstPoint;
1086     theFirstPoint = theLastPoint;
1087     theLastPoint = aTmpPoint;
1088   }
1089 }
1090
1091 void SketchPlugin_Trim::arrangePointsOnArc(const FeaturePtr& theArc,
1092                                   const AttributePoint2DPtr& theStartPointAttr,
1093                                   const AttributePoint2DPtr& theEndPointAttr,
1094                                   std::shared_ptr<GeomAPI_Pnt2d>& theFirstPoint,
1095                                   std::shared_ptr<GeomAPI_Pnt2d>& theSecondPoint) const
1096 {
1097   if (!theFirstPoint.get() || !theSecondPoint.get())
1098     return;
1099
1100   static const double anAngleTol = 1.e-12;
1101
1102   const std::string& aCenterAttrName = theArc->getKind() == SketchPlugin_Arc::ID() ?
1103       SketchPlugin_Arc::CENTER_ID() : SketchPlugin_EllipticArc::CENTER_ID();
1104   const std::string& aReversedAttrName = theArc->getKind() == SketchPlugin_Arc::ID() ?
1105       SketchPlugin_Arc::REVERSED_ID() : SketchPlugin_EllipticArc::REVERSED_ID();
1106
1107   std::shared_ptr<GeomAPI_Pnt2d> aCenter = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1108       theArc->attribute(aCenterAttrName))->pnt();
1109   bool isReversed = theArc->boolean(aReversedAttrName)->value();
1110
1111   // collect directions to each point
1112   std::shared_ptr<GeomAPI_Dir2d> aStartDir(
1113       new GeomAPI_Dir2d(theStartPointAttr->pnt()->xy()->decreased(aCenter->xy())));
1114   std::shared_ptr<GeomAPI_Dir2d> aFirstPtDir(
1115       new GeomAPI_Dir2d(theFirstPoint->xy()->decreased(aCenter->xy())));
1116   std::shared_ptr<GeomAPI_Dir2d> aSecondPtDir(
1117       new GeomAPI_Dir2d(theSecondPoint->xy()->decreased(aCenter->xy())));
1118
1119   // sort points by their angular values
1120   double aFirstPtAngle = aStartDir->angle(aFirstPtDir);
1121   double aSecondPtAngle = aStartDir->angle(aSecondPtDir);
1122   double aPeriod = isReversed ? -2.0 * PI : 2.0 * PI;
1123   if (fabs(aFirstPtAngle) > anAngleTol && isReversed == (aFirstPtAngle > 0.))
1124     aFirstPtAngle += aPeriod;
1125   if (fabs(aSecondPtAngle) > anAngleTol && isReversed == (aSecondPtAngle > 0.))
1126     aSecondPtAngle += aPeriod;
1127
1128   if (fabs(aFirstPtAngle) > fabs(aSecondPtAngle)) {
1129     std::shared_ptr<GeomAPI_Pnt2d> aTmpPoint = theFirstPoint;
1130     theFirstPoint = theSecondPoint;
1131     theSecondPoint = aTmpPoint;
1132   }
1133 }
1134
1135 void SketchPlugin_Trim::fillPointAttribute(const AttributePtr& theModifiedAttribute,
1136                                            const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
1137 {
1138   std::string anAttributeType = theModifiedAttribute->attributeType();
1139   if (anAttributeType == GeomDataAPI_Point2D::typeId()) {
1140     AttributePoint2DPtr aModifiedAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1141                                               theModifiedAttribute);
1142     aModifiedAttribute->setValue(thePoint);
1143
1144 #ifdef DEBUG_TRIM
1145     FeaturePtr aFeature = ModelAPI_Feature::feature(theModifiedAttribute->owner());
1146     std::cout << "<fillPointAttribute[" << aFeature->data()->name() << ": " <<
1147       theModifiedAttribute->id() <<
1148       "]> => Pnt2d - [" << thePoint->x() << ", " << thePoint->y() << "]" << std::endl;
1149 #endif
1150   }
1151 }
1152
1153 void SketchPlugin_Trim::fillAttribute(const AttributePtr& theModifiedAttribute,
1154                                       const AttributePtr& theSourceAttribute)
1155 {
1156   std::string anAttributeType = theModifiedAttribute->attributeType();
1157   if (anAttributeType == GeomDataAPI_Point2D::typeId()) {
1158     AttributePoint2DPtr aModifiedAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1159                                               theModifiedAttribute);
1160     AttributePoint2DPtr aSourceAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1161                                               theSourceAttribute);
1162
1163     if (aModifiedAttribute.get() && aSourceAttribute.get())
1164       aModifiedAttribute->setValue(aSourceAttribute->pnt());
1165   }
1166   else if (anAttributeType == ModelAPI_AttributeBoolean::typeId()) {
1167     AttributeBooleanPtr aModifiedAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(
1168                                               theModifiedAttribute);
1169     AttributeBooleanPtr aSourceAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(
1170                                               theSourceAttribute);
1171
1172     if (aModifiedAttribute.get() && aSourceAttribute.get())
1173       aModifiedAttribute->setValue(aSourceAttribute->value());
1174   }
1175 }