Salome HOME
Merge remote-tracking branch 'remotes/origin/master' into CEA_2019
[modules/shaper.git] / src / PartSet / PartSet_SketcherReentrantMgr.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 "PartSet_SketcherReentrantMgr.h"
21 #include "PartSet_ExternalObjectsMgr.h"
22 #include "PartSet_Module.h"
23 #include "PartSet_SketcherMgr.h"
24 #include "PartSet_WidgetPoint2d.h"
25
26 #include "ModelAPI_Session.h"
27 #include "ModelAPI_AttributeString.h"
28 #include "ModelAPI_AttributeRefAttr.h"
29 #include "ModelAPI_AttributeReference.h"
30 #include "ModelAPI_EventReentrantMessage.h"
31
32 #include "GeomDataAPI_Point2D.h"
33
34 #include "GeomAPI_Lin2d.h"
35 #include "GeomAPI_Dir2d.h"
36
37 #include <ModuleBase_IPropertyPanel.h>
38 #include <ModuleBase_ISelectionActivate.h>
39 #include <ModuleBase_OperationFeature.h>
40 #include <ModuleBase_ModelWidget.h>
41 #include <ModuleBase_ViewerPrs.h>
42 #include <ModuleBase_WidgetSelector.h>
43 #include <ModuleBase_PageWidget.h>
44 #include <ModuleBase_PageBase.h>
45 #include <ModuleBase_WidgetFactory.h>
46 #include <ModuleBase_OperationDescription.h>
47 #include "ModuleBase_ToolBox.h"
48 #include "ModuleBase_ISelection.h"
49
50 #include <SketchPlugin_Feature.h>
51 #include <SketchPlugin_Line.h>
52 #include <SketchPlugin_MacroArc.h>
53 #include <SketchPlugin_MacroCircle.h>
54 #include <SketchPlugin_Point.h>
55 #include <SketchPlugin_Trim.h>
56 #include <SketchPlugin_Split.h>
57 #include <SketchPlugin_ConstraintHorizontal.h>
58 #include <SketchPlugin_ConstraintVertical.h>
59
60 #include <XGUI_Workshop.h>
61 #include <XGUI_ModuleConnector.h>
62 #include <XGUI_OperationMgr.h>
63 #include <XGUI_PropertyPanel.h>
64 #include <XGUI_ErrorMgr.h>
65 #include <XGUI_SelectionMgr.h>
66
67 #include <QToolButton>
68
69 //#define DEBUG_RESTART
70
71 PartSet_SketcherReentrantMgr::PartSet_SketcherReentrantMgr(ModuleBase_IWorkshop* theWorkshop)
72 : QObject(theWorkshop),
73   myWorkshop(theWorkshop),
74   myRestartingMode(RM_None),
75   myIsFlagsBlocked(false),
76   myIsInternalEditOperation(false),
77   myNoMoreWidgetsAttribute(""),
78   myIsAutoConstraints(true)
79 {
80 }
81
82 PartSet_SketcherReentrantMgr::~PartSet_SketcherReentrantMgr()
83 {
84 }
85
86 bool PartSet_SketcherReentrantMgr::isInternalEditActive() const
87 {
88   return myIsInternalEditOperation;
89 }
90
91 void PartSet_SketcherReentrantMgr::updateInternalEditActiveState()
92 {
93   if  (myIsInternalEditOperation) {
94     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
95                                                          (myWorkshop->currentOperation());
96     if (aFOperation) {
97       FeaturePtr aFeature = aFOperation->feature();
98       QString anError = myWorkshop->module()->getFeatureError(aFeature);
99       // stop started internal edit operation as soon as the operation becomes invalid
100       // it is especially important for the sketch tangent arc feature
101       if (!anError.isEmpty()) {
102         aFOperation->setEditOperation(false);
103         //workshop()->operationMgr()->updateApplyOfOperations();
104         myIsInternalEditOperation = false;
105         updateAcceptAllAction();
106       }
107     }
108   }
109 }
110
111 bool PartSet_SketcherReentrantMgr::operationCommitted(ModuleBase_Operation* theOperation)
112 {
113   bool aProcessed = false;
114   if (!isActiveMgr())
115     return aProcessed;
116
117   aProcessed = myIsInternalEditOperation;
118   resetFlags();
119
120   return aProcessed;
121 }
122
123 void PartSet_SketcherReentrantMgr::operationStarted(ModuleBase_Operation* theOperation)
124 {
125   if (!isActiveMgr())
126     return;
127
128   //if (myPreviousFeature.get() && myRestartingMode == RM_LastFeatureUsed) {
129     //ModuleBase_OperationFeature* aCurrentOperation = dynamic_cast<ModuleBase_OperationFeature*>(
130     //                                                            myWorkshop->currentOperation());
131     //CompositeFeaturePtr aSketch = module()->sketchMgr()->activeSketch();
132     //if (myPreviousFeature.get() && myPreviousFeature->data()->isValid()) // it is not removed
133       //copyReetntrantAttributes(myPreviousFeature, aCurrentOperation->feature(), aSketch);
134   //}
135   resetFlags();
136 }
137
138 void PartSet_SketcherReentrantMgr::operationAborted(ModuleBase_Operation* theOperation)
139 {
140   if (!isActiveMgr())
141     return;
142
143   resetFlags();
144 }
145
146 bool PartSet_SketcherReentrantMgr::processMouseMoved(ModuleBase_IViewWindow* theWnd,
147                                                       QMouseEvent* theEvent)
148 {
149   bool aProcessed = false;
150   if (!isActiveMgr())
151     return aProcessed;
152
153   if  (myIsInternalEditOperation) {
154     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
155                                                          (myWorkshop->currentOperation());
156     FeaturePtr aLastFeature = myRestartingMode == RM_LastFeatureUsed ? aFOperation->feature()
157                                                                      : FeaturePtr();
158     if (aLastFeature) {
159       ModuleBase_ModelWidget* anActiveWidget = module()->activeWidget();
160       ModuleBase_IPropertyPanel* aPanel = myWorkshop->currentOperation()->propertyPanel();
161
162       FeaturePtr aCurrentFeature = aFOperation->feature();
163       bool isLineFeature = false, isReentrantArcFeature = false;
164       std::string anAttributeOnStart;
165       if (aCurrentFeature->getKind() == SketchPlugin_Line::ID()) {
166         anAttributeOnStart = SketchPlugin_Line::START_ID();
167         isLineFeature = anActiveWidget->attributeID() == anAttributeOnStart;
168       }
169       else if (isTangentArc(aFOperation, module()->sketchMgr()->activeSketch())) {
170         isReentrantArcFeature = true;
171       }
172       bool aCanBeActivatedByMove = isLineFeature || isReentrantArcFeature;
173       if (aCanBeActivatedByMove) {
174         /// before restarting of operation we need to clear selection, as it may take part in
175         /// new feature creation, e.g. tangent arc. But it is not necessary as it was processed
176         /// by mouse release when the operation was restarted.
177         workshop()->selector()->clearSelection();
178
179         myPreviousFeature = aFOperation->feature();
180         if (myIsAutoConstraints)
181           addConstraints(myPreviousFeature);
182         restartOperation();
183         myPreviousFeature = FeaturePtr();
184
185         anActiveWidget = module()->activeWidget();
186         aProcessed = true;
187         if (anActiveWidget && anActiveWidget->attributeID() == anAttributeOnStart) {
188           // it was not deactivated by preselection processing
189           aPanel->activateNextWidget(anActiveWidget);
190         }
191       } else {
192         // processing mouse move in active widget of restarted operation
193         ModuleBase_ModelWidget* anActiveWidget = module()->activeWidget();
194         PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
195         if (aProcessor)
196           aProcessor->mouseMoved(theWnd, theEvent);
197       }
198     }
199   }
200   return aProcessed;
201 }
202
203 bool PartSet_SketcherReentrantMgr::processMousePressed(ModuleBase_IViewWindow* /* theWnd*/,
204                                                         QMouseEvent* /* theEvent*/)
205 {
206   return isActiveMgr() && myIsInternalEditOperation;
207 }
208
209 bool PartSet_SketcherReentrantMgr::processMouseReleased(ModuleBase_IViewWindow* theWindow,
210                                                         QMouseEvent* theEvent)
211 {
212   bool aProcessed = false;
213   if (!isActiveMgr())
214     return aProcessed;
215
216   if (myIsInternalEditOperation) {
217     ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
218     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
219
220     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
221     if (!anActiveWidget || !anActiveWidget->isViewerSelector()) {
222
223       // block of viewer update
224       // we need to block update content of the viewer because of Sketch Point feature
225       // in activate() the value of the point is initialized and it can be displayed
226       // but the default value is [0, 0]. So, we block update viewer contentent until
227       // onMouseRelease happens, which correct the point position
228       ModuleBase_Tools::blockUpdateViewer(true);
229
230       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
231                                                            (myWorkshop->currentOperation());
232       myPreviousFeature = aFOperation->feature();
233
234       /// selection should be obtained from workshop before ask if the operation can be started as
235       /// the canStartOperation method performs commit/abort of previous operation.
236       /// Sometimes commit/abort
237       /// may cause selection clear(Sketch operation) as a result
238       /// it will be lost and is not used for preselection.
239       ModuleBase_ISelection* aSelection = myWorkshop->selection();
240       QList<ModuleBase_ViewerPrsPtr> aPreSelected =
241         aSelection->getSelected(ModuleBase_ISelection::AllControls);
242
243       myClickedSketchPoint = PartSet_Tools::getPnt2d(theEvent, theWindow,
244                                                      module()->sketchMgr()->activeSketch());
245       FeaturePtr anExternalCreatedFeature;
246       if (!aPreSelected.empty()) {
247         ModuleBase_ViewerPrsPtr aValue = aPreSelected.first();
248         module()->getGeomSelection(aValue, mySelectedObject, mySelectedAttribute);
249
250         PartSet_WidgetPoint2D* aPointWidget = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
251         if (aPointWidget) {
252           GeomShapePtr aShape;
253           aPointWidget->getGeomSelection_(aValue, mySelectedObject, aShape);
254           ObjectPtr anExternalObject =
255             aPointWidget->getExternalObjectMgr()->getExternalObjectValidated();
256           // if external object is during reentrant operation and is used as a parameter of feature
257           // it should be removed after the operation is restarted. (Circle feature, Projection)
258           if (anExternalObject.get())
259             anExternalCreatedFeature = ModelAPI_Feature::feature(anExternalObject);
260         }
261       }
262
263       restartOperation();
264       // remove created external feature
265       if (anExternalCreatedFeature.get()) {
266         QObjectPtrList anObjects;
267         anObjects.append(anExternalCreatedFeature);
268         workshop()->deleteFeatures(anObjects);
269       }
270
271       myClickedSketchPoint = std::shared_ptr<GeomAPI_Pnt2d>();
272       mySelectedObject = ObjectPtr();
273       mySelectedAttribute = AttributePtr();
274
275       myPreviousFeature = FeaturePtr();
276       aProcessed = true;
277
278       // fill the first widget by the mouse event point
279       // if the active widget is not the first, it means that the restarted operation is filled by
280       // the current preselection.
281       PartSet_MouseProcessor* aMouseProcessor = dynamic_cast<PartSet_MouseProcessor*>(
282                                                                        module()->activeWidget());
283       //PartSet_WidgetPoint2D* aPoint2DWdg =
284       //  dynamic_cast<PartSet_WidgetPoint2D*>(module()->activeWidget());
285       PartSet_MouseProcessor* aFirstWidget = dynamic_cast<PartSet_MouseProcessor*>(
286                                                         aPanel->findFirstAcceptingValueWidget());
287       //if (aPoint2DWdg && aPoint2DWdg == aFirstWidget) {
288       if (aMouseProcessor && aMouseProcessor == aFirstWidget) {
289         std::shared_ptr<ModuleBase_ViewerPrs> aSelectedPrs;
290         if (!aPreSelected.empty())
291           aSelectedPrs = aPreSelected.front();
292         if (aSelectedPrs.get() && aSelectedPrs->object().get()
293             && !aSelectedPrs->object()->data()->isValid()) {
294           // the selected object was removed diring restart, e.g. presentable macro feature
295           // there are created objects to replace the object depending on created feature kind
296           aSelectedPrs = std::shared_ptr<ModuleBase_ViewerPrs>();
297         }
298         aMouseProcessor->setPreSelection(aSelectedPrs, theWindow, theEvent);
299         //aPoint2DWdg->mouseReleased(theWindow, theEvent);
300         //if (!aPreSelected.empty())
301         //  aPoint2DWdg->setPreSelection(ModuleBase_ViewerPrsPtr());
302       }
303       // unblock viewer update
304       ModuleBase_Tools::blockUpdateViewer(false);
305     }
306   }
307   return aProcessed;
308 }
309
310 //******************************************************
311 void PartSet_SketcherReentrantMgr::setReentrantPreSelection(
312                                        const std::shared_ptr<Events_Message>& theMessage)
313 {
314   ReentrantMessagePtr aReentrantMessage =
315                       std::dynamic_pointer_cast<ModelAPI_EventReentrantMessage>(theMessage);
316   if (!aReentrantMessage.get())
317     return;
318
319   // if feature has already filled the selected object, we should not overwrite it
320   if (!aReentrantMessage->selectedObject().get())
321     aReentrantMessage->setSelectedObject(mySelectedObject);
322
323   aReentrantMessage->setSelectedAttribute(mySelectedAttribute);
324   aReentrantMessage->setClickedPoint(myClickedSketchPoint);
325 }
326
327 //void PartSet_SketcherReentrantMgr::onWidgetActivated()
328 //{
329 //  if (!isActiveMgr())
330 //    return;
331 //  if (!myIsInternalEditOperation)
332 //    return;
333 //
334 //  PartSet_Module* aModule = module();
335 //  ModuleBase_ModelWidget* aFirstWidget = aModule->activeWidget();
336 //  ModuleBase_IPropertyPanel* aPanel = aModule->currentOperation()->propertyPanel();
337 //  if (aFirstWidget != aPanel->activeWidget()) {
338 //    ModuleBase_WidgetSelector* aWSelector = dynamic_cast<ModuleBase_WidgetSelector*>
339 //      (aFirstWidget);
340 //    if (aWSelector) {
341 //      myWorkshop->selectionActivate()->updateSelectionModesAndFilters(aWSelector);
342 //    }
343 //  }
344 //}
345
346 void PartSet_SketcherReentrantMgr::onNoMoreWidgets(const std::string& thePreviousAttributeID)
347 {
348 #ifdef DEBUG_RESTART
349   std::cout << "PartSet_SketcherReentrantMgr::onNoMoreWidgets" << std::endl;
350 #endif
351
352   if (!isActiveMgr())
353     return;
354
355   // we should avoid processing of the signal about no more widgets attributes and
356   // do this after the restart operaion is finished if it was called
357   // onNoMoreWidgets depends on myIsFlagsBlocked and fill myNoMoreWidgetsAttribute
358   // if it should be called after restart
359   if (myIsFlagsBlocked) {
360     myNoMoreWidgetsAttribute = thePreviousAttributeID;
361     return;
362   }
363
364   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
365                                                        (myWorkshop->currentOperation());
366   if (!myWorkshop->module()->getFeatureError(aFOperation->feature()).isEmpty())
367     return;
368
369   if (aFOperation && module()->sketchMgr()->isNestedSketchOperation(aFOperation)) {
370     if (aFOperation->isNeedToBeAborted()) {
371       aFOperation->abort();
372     }
373     else {
374       bool isStarted = false;
375       if (!module()->sketchMgr()->sketchSolverError()) {
376         if (myRestartingMode != RM_Forbided) {
377           myRestartingMode = RM_LastFeatureUsed;
378           isStarted = startInternalEdit(thePreviousAttributeID);
379         }
380       }
381       if (!isStarted)
382         aFOperation->commit();
383     }
384   }
385 }
386
387 bool PartSet_SketcherReentrantMgr::processEnter(const std::string& thePreviousAttributeID)
388 {
389   bool isDone = false;
390
391   if (!isActiveMgr())
392     return isDone;
393
394   // empty previous attribute means that the Apply/Ok button has focus and the enter
395   // should not lead to start edition mode of the previous operation
396   if (thePreviousAttributeID.empty())
397     return isDone;
398
399   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
400                                                        (myWorkshop->currentOperation());
401   if (!myWorkshop->module()->getFeatureError(aFOperation->feature()).isEmpty())
402     return isDone;
403
404   bool isSketchSolverError = module()->sketchMgr()->sketchSolverError();
405
406   if (!isSketchSolverError) {
407     myRestartingMode = RM_EmptyFeatureUsed;
408     // It seems that the call is obsolete for Enter key processing
409     // It prevent finalysing of the current operation by Enter key
410     //isDone = startInternalEdit(thePreviousAttributeID);
411   }
412
413   return isDone;
414 }
415
416 void PartSet_SketcherReentrantMgr::onVertexSelected()
417 {
418   if (!isActiveMgr())
419     return;
420
421   ModuleBase_Operation* anOperation = myWorkshop->currentOperation();
422   std::string anOperationId = anOperation->id().toStdString();
423   if (anOperationId == SketchPlugin_Line::ID() ||
424       isTangentArc(anOperation, module()->sketchMgr()->activeSketch())) {
425     /// If last line finished on vertex the lines creation sequence has to be break
426     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
427     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
428     const QList<ModuleBase_ModelWidget*>& aWidgets = aPanel->modelWidgets();
429     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
430     bool aFoundWidget = false;
431     bool aFoundObligatory = false;
432     for (; anIt != aLast && !aFoundObligatory; anIt++) {
433       if (!aFoundWidget)
434         aFoundWidget = *anIt == anActiveWidget;
435       else
436         aFoundObligatory = (*anIt)->isObligatory();
437     }
438     if (!aFoundObligatory)
439       myRestartingMode = RM_Forbided;
440   }
441 }
442
443 void PartSet_SketcherReentrantMgr::onAfterValuesChangedInPropertyPanel()
444 {
445
446   if (isInternalEditActive()) {
447     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
448                                                        (myWorkshop->currentOperation());
449     ModuleBase_ModelWidget* aWidget = (ModuleBase_ModelWidget*)sender();
450     if (!aWidget->isModifiedInEdit().empty())
451       restartOperation();
452   }
453 }
454
455 void PartSet_SketcherReentrantMgr::onBeforeStopped()
456 {
457   if (!isActiveMgr() || !myIsInternalEditOperation)
458     return;
459
460   beforeStopInternalEdit();
461 }
462
463 bool PartSet_SketcherReentrantMgr::canBeCommittedByPreselection()
464 {
465   return !isActiveMgr() || myRestartingMode == RM_None;
466 }
467
468 bool PartSet_SketcherReentrantMgr::isActiveMgr() const
469 {
470   ModuleBase_Operation* aCurrentOperation = myWorkshop->currentOperation();
471
472   bool anActive = PartSet_SketcherMgr::isSketchOperation(aCurrentOperation);
473   if (!anActive) {
474     anActive = module()->sketchMgr()->isNestedSketchOperation(aCurrentOperation);
475     if (anActive) { // the manager is not active when the current operation is a usual Edit
476       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
477                                                        (myWorkshop->currentOperation());
478       if (aFOperation->isEditOperation())
479         anActive = myIsInternalEditOperation;
480     }
481   }
482   return anActive;
483 }
484
485 bool PartSet_SketcherReentrantMgr::startInternalEdit(const std::string& thePreviousAttributeID)
486 {
487 #ifdef DEBUG_RESTART
488   std::cout << "PartSet_SketcherReentrantMgr::startInternalEdit" << std::endl;
489 #endif
490
491   bool isDone = false;
492   /// this is workaround for ModuleBase_WidgetEditor, used in SALOME mode. Sometimes key enter
493   /// event comes two times, so we should not start another internal edit operation
494   /// the Apply button becomes disabled becase the second additional internal feature is created
495   if (myIsInternalEditOperation)
496     return true;
497
498   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
499                                                      (myWorkshop->currentOperation());
500
501   if (aFOperation && module()->sketchMgr()->isNestedSketchOperation(aFOperation)) {
502     /// improvement to deselect automatically all eventual selected objects, when
503     // returning to the neutral point of the Sketcher or start internal edit
504     workshop()->selector()->clearSelection();
505
506     aFOperation->setEditOperation(true/*, false*/);
507     createInternalFeature();
508
509     myIsInternalEditOperation = true;
510     updateAcceptAllAction();
511
512     isDone = true;
513     connect(aFOperation, SIGNAL(beforeCommitted()), this, SLOT(onBeforeStopped()));
514     connect(aFOperation, SIGNAL(beforeAborted()), this, SLOT(onBeforeStopped()));
515
516     // activate selection filters of the first widget in the viewer
517     //onWidgetActivated();
518
519     // activate the last active widget in the Property Panel
520     if (!thePreviousAttributeID.empty()) {
521       ModuleBase_Operation* anEditOperation = module()->currentOperation();
522       if (anEditOperation) {
523         ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
524         ModuleBase_ModelWidget* aPreviousAttributeWidget = 0;
525         QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
526         for (int i = 0, aNb = aWidgets.size(); i < aNb && !aPreviousAttributeWidget; i++) {
527           if (aWidgets[i]->attributeID() == thePreviousAttributeID) {
528           /// workaround for the same attributes used in different stacked widgets(attribute types)
529           if (ModuleBase_ToolBox::isOffToolBoxParent(aWidgets[i]))
530             continue;
531             aPreviousAttributeWidget = aWidgets[i];
532           }
533         }
534         // If the current widget is a selector, do nothing, it processes the mouse press
535         if (aPreviousAttributeWidget) {
536           if (!aPreviousAttributeWidget->isViewerSelector()) {
537             aPreviousAttributeWidget->focusTo();
538             aPreviousAttributeWidget->emitFocusInWidget();
539             aPreviousAttributeWidget->selectContent();
540           }
541           else {
542             // in case of shape multi selector, the widget does not lose focus by filling
543             // like it is in shape selector. So, if enter is pressed, the multi shape selector
544             // control should be deactivated. The focus is moved to Apply button and there
545             // should not be active control visualized in property panel
546             if (aPreviousAttributeWidget == aPanel->activeWidget()) {
547               aPanel->activateWidget(NULL, false);
548             }
549             // if there is no the next widget to be automatically activated,
550             // the Ok button in property
551             // panel should accept the focus(example is parallel constraint on sketch lines)
552             QToolButton* anOkBtn =
553               dynamic_cast<XGUI_PropertyPanel*>(aPanel)->findButton(PROP_PANEL_OK);
554             if (anOkBtn)
555               ModuleBase_Tools::setFocus(anOkBtn, "XGUI_PropertyPanel::activateNextWidget");
556           }
557         }
558       }
559     }
560   }
561   if (isDone)
562     module()->sketchMgr()->clearClickedFlags();
563
564   return isDone;
565 }
566
567 void PartSet_SketcherReentrantMgr::beforeStopInternalEdit()
568 {
569   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
570                                                       (myWorkshop->currentOperation());
571   if (aFOperation) {
572     disconnect(aFOperation, SIGNAL(beforeCommitted()), this, SLOT(onBeforeStopped()));
573     disconnect(aFOperation, SIGNAL(beforeAborted()), this, SLOT(onBeforeStopped()));
574   }
575
576   deleteInternalFeature();
577 }
578
579 void PartSet_SketcherReentrantMgr::restartOperation()
580 {
581 #ifdef DEBUG_RESTART
582   std::cout << "PartSet_SketcherReentrantMgr::restartOperation" << std::endl;
583 #endif
584
585   if (myIsInternalEditOperation) {
586     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(
587                                                                   myWorkshop->currentOperation());
588     if (aFOperation) {
589       ModuleBase_ISelection* aSelection = myWorkshop->selection();
590       QList<ModuleBase_ViewerPrsPtr> aPreSelected =
591         aSelection->getSelected(ModuleBase_ISelection::AllControls);
592
593       if (myInternalFeature.get())
594         copyReetntrantAttributes(myInternalFeature, aFOperation->feature(),
595                                  module()->sketchMgr()->activeSketch());
596
597       myNoMoreWidgetsAttribute = "";
598       myIsFlagsBlocked = true;
599       /// launch has 'false' parameter to do not start new operation if the previous operation
600       /// is not committed. It is important for Line Sketch feature as it uses the previous
601       /// created feature parameter(to build coincidence), but by abort the previous is removed
602       module()->launchOperation(aFOperation->id(), true);
603       myIsFlagsBlocked = false;
604       resetFlags();
605
606       // we should avoid processing of the signal about no more widgets attributes and
607       // do this after the restart operaion is finished if it was called
608       // onNoMoreWidgets depends on myIsFlagsBlocked and fill myNoMoreWidgetsAttribute
609       // if it should be called after restart
610       if (!myNoMoreWidgetsAttribute.empty()) {
611         onNoMoreWidgets(myNoMoreWidgetsAttribute);
612         myNoMoreWidgetsAttribute = "";
613       }
614     }
615   }
616 }
617
618 void PartSet_SketcherReentrantMgr::createInternalFeature()
619 {
620   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
621                                                      (myWorkshop->currentOperation());
622
623   if (aFOperation && module()->sketchMgr()->isNestedSketchOperation(aFOperation)) {
624     FeaturePtr anOperationFeature = aFOperation->feature();
625
626     CompositeFeaturePtr aSketch = module()->sketchMgr()->activeSketch();
627     myInternalFeature = aSketch->addFeature(anOperationFeature->getKind());
628
629 #ifdef DEBUG_RESTART
630     std::cout << "PartSet_SketcherReentrantMgr::createInternalFeature: "
631               << myInternalFeature->data()->name() << std::endl;
632 #endif
633
634     bool isFeatureChanged = copyReetntrantAttributes(anOperationFeature, myInternalFeature,
635                                                      aSketch, false);
636     XGUI_PropertyPanel* aPropertyPanel = dynamic_cast<XGUI_PropertyPanel*>
637                                                   (aFOperation->propertyPanel());
638
639     myInternalWidget = new QWidget(aPropertyPanel->contentWidget()->pageWidget());
640     myInternalWidget->setVisible(false);
641
642     ModuleBase_PageWidget* anInternalPage = new ModuleBase_PageWidget(myInternalWidget);
643
644     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
645     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myWorkshop);
646
647     aFactory.createWidget(anInternalPage);
648     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
649
650     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
651       bool isStoreValue = !aFOperation->isEditOperation() &&
652                           !aWidget->getDefaultValue().empty() &&
653                           !aWidget->isComputedDefault();
654       aWidget->setFeature(myInternalFeature, isStoreValue);
655       if (!isStoreValue && isFeatureChanged)
656         aWidget->restoreValue();
657     }
658
659     ModuleBase_ModelWidget* aFirstWidget = ModuleBase_IPropertyPanel::findFirstAcceptingValueWidget
660                                                                                         (aWidgets);
661     if (aFirstWidget)
662       setInternalActiveWidget(aFirstWidget);
663   }
664 }
665
666 void PartSet_SketcherReentrantMgr::deleteInternalFeature()
667 {
668 #ifdef DEBUG_RESTART
669   std::cout << "PartSet_SketcherReentrantMgr::deleteInternalFeature: "
670             << myInternalFeature->data()->name() << std::endl;
671 #endif
672   setInternalActiveWidget(0);
673   delete myInternalWidget;
674   myInternalWidget = 0;
675
676   QObjectPtrList anObjects;
677   anObjects.append(myInternalFeature);
678   workshop()->deleteFeatures(anObjects);
679   myInternalFeature = FeaturePtr();
680 }
681
682 void PartSet_SketcherReentrantMgr::resetFlags()
683 {
684   if (!myIsFlagsBlocked) {
685     myIsInternalEditOperation = false;
686     updateAcceptAllAction();
687     myRestartingMode = RM_None;
688     myReentrantMessage = std::shared_ptr<Events_Message>();
689   }
690 }
691
692 bool PartSet_SketcherReentrantMgr::copyReetntrantAttributes(const FeaturePtr& theSourceFeature,
693                                                              const FeaturePtr& theNewFeature,
694                                                              const CompositeFeaturePtr& theSketch,
695                                                              const bool /*isTemporary*/)
696 {
697   bool aChanged = false;
698   if (!theSourceFeature.get() || !theSourceFeature->data().get() ||
699       !theSourceFeature->data()->isValid())
700     return aChanged;
701
702 #ifdef DEBUG_RESTART
703   std::cout << "PartSet_SketcherReentrantMgr::copyReetntrantAttributes from '"
704             << theSourceFeature->data()->name() << "' to '" << theNewFeature->data()->name()
705             << "'" << std::endl;
706 #endif
707
708   std::string aFeatureKind = theSourceFeature->getKind();
709   /*if (aFeatureKind == SketchPlugin_Line::ID()) {
710     // Initialize new line with first point equal to end of previous
711     std::shared_ptr<ModelAPI_Data> aSFData = theSourceFeature->data();
712     std::shared_ptr<GeomDataAPI_Point2D> aSPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
713                                                  aSFData->attribute(SketchPlugin_Line::END_ID()));
714     std::shared_ptr<ModelAPI_Data> aNFData = theNewFeature->data();
715     std::shared_ptr<GeomDataAPI_Point2D> aNPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
716                                                  aNFData->attribute(SketchPlugin_Line::START_ID()));
717     aNPoint->setValue(aSPoint->x(), aSPoint->y());
718     PartSet_Tools::createConstraint(theSketch, aSPoint, aNPoint);
719
720     aNPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
721                                                  aSFData->attribute(SketchPlugin_Line::END_ID()));
722     aNPoint->setValue(aSPoint->x(), aSPoint->y());
723   }
724   else*/ if (aFeatureKind == SketchPlugin_MacroCircle::ID()) {
725     // set circle type
726     /*std::string aTypeAttributeId = SketchPlugin_MacroCircle::CIRCLE_TYPE();
727     AttributeStringPtr aSourceFeatureTypeAttr = theSourceFeature->data()->string(aTypeAttributeId);
728     AttributeStringPtr aNewFeatureTypeAttr = theNewFeature->data()->string(aTypeAttributeId);
729     if (aNewFeatureTypeAttr->value() != aTypeAttributeId) // do nothing if there is no changes
730       aNewFeatureTypeAttr->setValue(aSourceFeatureTypeAttr->value());
731     //ModuleBase_Tools::flushUpdated(theNewFeature);*/
732     //aChanged = true;
733   }
734   else if (aFeatureKind == SketchPlugin_MacroArc::ID()) {
735     // set arc type
736     /*std::string aTypeAttributeId = SketchPlugin_MacroArc::ARC_TYPE();
737     AttributeStringPtr aSourceFeatureTypeAttr = theSourceFeature->data()->string(aTypeAttributeId);
738     AttributeStringPtr aNewFeatureTypeAttr = theNewFeature->data()->string(aTypeAttributeId);
739     if (aNewFeatureTypeAttr->value() != aTypeAttributeId) // do nothing if there is no changes
740       aNewFeatureTypeAttr->setValue(aSourceFeatureTypeAttr->value());*/
741     //// if the arc is tangent, set coincidence to end point of the previous arc
742     //std::string anArcType = aSourceFeatureTypeAttr->value();
743     //if (anArcType == SketchPlugin_Arc::ARC_TYPE_TANGENT()) {
744     //  // get the last point of the previuos arc feature(geom point 2d)
745     //  std::shared_ptr<ModelAPI_Data> aSData = theSourceFeature->data();
746     //  std::shared_ptr<GeomDataAPI_Point2D> aSPointAttr =
747     //                                  std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
748     //                                  aSData->attribute(SketchPlugin_Arc::END_ID()));
749     //  // get point attribute on the current feature
750     //  AttributeRefAttrPtr aTangentPointAttr = theNewFeature->data()->refattr(
751     //                                                SketchPlugin_Arc::TANGENT_POINT_ID());
752     //  aTangentPointAttr->setAttr(aSPointAttr);
753
754     //  std::shared_ptr<GeomDataAPI_Point2D> aNPointAttr =
755     //                                std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
756     //                                theNewFeature->data()->attribute(SketchPlugin_Arc::END_ID()));
757     //  aNPointAttr->setValue(aSPointAttr->x(), aSPointAttr->y());
758
759     //}
760     //ModuleBase_Tools::flushUpdated(theNewFeature);
761     //aChanged = true;
762   }
763   else if (aFeatureKind == SketchPlugin_Trim::ID() ||
764            aFeatureKind == SketchPlugin_Split::ID()) {
765     std::string aPreviewObjectAttribute = aFeatureKind == SketchPlugin_Trim::ID() ?
766                 SketchPlugin_Trim::PREVIEW_OBJECT(): SketchPlugin_Split::PREVIEW_OBJECT();
767     std::string aPreviewPointAttribute = aFeatureKind == SketchPlugin_Trim::ID() ?
768                 SketchPlugin_Trim::PREVIEW_POINT(): SketchPlugin_Split::PREVIEW_POINT();
769     std::shared_ptr<ModelAPI_AttributeReference> aRefPreviewAttr =
770                       std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
771                       theSourceFeature->data()->attribute(aPreviewObjectAttribute));
772     std::shared_ptr<ModelAPI_AttributeReference> aNRefPreviewAttr =
773                         std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
774                         theNewFeature->data()->attribute(aPreviewObjectAttribute));
775     aNRefPreviewAttr->setValue(aRefPreviewAttr->value());
776     std::shared_ptr<GeomDataAPI_Point2D> aPointPreviewAttr =
777                       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
778                       theSourceFeature->data()->attribute(aPreviewPointAttribute));
779     std::shared_ptr<GeomDataAPI_Point2D> aNPointPreviewAttr =
780                       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
781                       theNewFeature->data()->attribute(aPreviewPointAttribute));
782     aNPointPreviewAttr->setValue(aPointPreviewAttr->x(), aPointPreviewAttr->y());
783   }
784   return aChanged;
785 }
786
787 bool PartSet_SketcherReentrantMgr::isTangentArc(ModuleBase_Operation* theOperation,
788                                                  const CompositeFeaturePtr& /*theSketch*/) const
789 {
790   bool aTangentArc = false;
791   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
792                                                                         (theOperation);
793   if (aFOperation && module()->sketchMgr()->isNestedSketchOperation(aFOperation)) {
794     FeaturePtr aFeature = aFOperation->feature();
795     if (aFeature.get() && aFeature->getKind() == SketchPlugin_MacroArc::ID()) {
796       AttributeStringPtr aTypeAttr = aFeature->data()->string(SketchPlugin_MacroArc::ARC_TYPE());
797       std::string anArcType = aTypeAttr.get() ? aTypeAttr->value() : "";
798       aTangentArc = anArcType == SketchPlugin_MacroArc::ARC_TYPE_BY_TANGENT_EDGE();
799     }
800   }
801   return aTangentArc;
802 }
803
804 void PartSet_SketcherReentrantMgr::updateAcceptAllAction()
805 {
806   CompositeFeaturePtr aSketch = module()->sketchMgr()->activeSketch();
807   if (aSketch.get())
808     workshop()->errorMgr()->updateAcceptAllAction(aSketch);
809 }
810
811 XGUI_Workshop* PartSet_SketcherReentrantMgr::workshop() const
812 {
813   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
814   return aConnector->workshop();
815 }
816
817 PartSet_Module* PartSet_SketcherReentrantMgr::module() const
818 {
819   return dynamic_cast<PartSet_Module*>(myWorkshop->module());
820 }
821
822 void PartSet_SketcherReentrantMgr::setInternalActiveWidget(ModuleBase_ModelWidget* theWidget)
823 {
824   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
825     (myWorkshop->currentOperation());
826   if (aFOperation)
827   {
828     XGUI_PropertyPanel* aPropertyPanel = dynamic_cast<XGUI_PropertyPanel*>
829       (aFOperation->propertyPanel());
830     if (aPropertyPanel)
831       aPropertyPanel->setInternalActiveWidget(theWidget);
832   }
833 }
834
835 void PartSet_SketcherReentrantMgr::onAutoConstraints(bool isOn)
836 {
837   myIsAutoConstraints = isOn;
838 }
839
840 void PartSet_SketcherReentrantMgr::addConstraints(const FeaturePtr& theFeature)
841 {
842   static GeomDir2dPtr myHorDir(new GeomAPI_Dir2d(1, 0));
843   static GeomDir2dPtr myVertDir(new GeomAPI_Dir2d(0, 1));
844
845   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
846     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
847     std::shared_ptr<GeomDataAPI_Point2D> aPoint1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
848         aData->attribute(SketchPlugin_Line::START_ID()));
849     std::shared_ptr<GeomDataAPI_Point2D> aPoint2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
850         aData->attribute(SketchPlugin_Line::END_ID()));
851     if (aPoint1.get() && aPoint2.get()) {
852       GeomLine2dPtr aLine(new GeomAPI_Lin2d(aPoint1->pnt(), aPoint2->pnt()));
853       GeomDir2dPtr aDir = aLine->direction();
854       double aHorAngle = fabs(myHorDir->angle(aDir));
855       double aVertAngle = fabs(myVertDir->angle(aDir));
856       if (aHorAngle > M_PI/2.)
857         aHorAngle = M_PI - aHorAngle;
858       if (aVertAngle > M_PI/2.)
859         aVertAngle = M_PI - aVertAngle;
860
861       double aTolerance = Config_PropManager::real(SKETCH_TAB_NAME, "angular_tolerance");
862       CompositeFeaturePtr aSketch = module()->sketchMgr()->activeSketch();
863       FeaturePtr aFeature;
864       if (aHorAngle < aTolerance)
865         // Add horizontal constraint
866         aFeature = aSketch->addFeature(SketchPlugin_ConstraintHorizontal::ID());
867       else if (aVertAngle < aTolerance)
868         // Add vertical constraint
869         aFeature = aSketch->addFeature(SketchPlugin_ConstraintVertical::ID());
870
871       if (aFeature.get()) {
872         aFeature->refattr(SketchPlugin_Constraint::ENTITY_A())->setObject(
873             theFeature->firstResult());
874       }
875     }
876   }
877 }