Salome HOME
Issue #789: Detach a coincidence from a line object
[modules/shaper.git] / src / PartSet / PartSet_MenuMgr.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_MenuMgr.cpp
4 // Created:     03 April 2015
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_MenuMgr.h"
8 #include "PartSet_Module.h"
9 #include "PartSet_SketcherMgr.h"
10 #include "PartSet_Tools.h"
11
12 #include <PartSetPlugin_Part.h>
13
14 #include <GeomAPI_Pnt2d.h>
15 #include <GeomDataAPI_Point2D.h>
16
17 #include <SketchPlugin_ConstraintCoincidence.h>
18 #include <SketchPlugin_Line.h>
19 #include <SketchPlugin_Circle.h>
20 #include <SketchPlugin_Point.h>
21 #include <SketchPlugin_Sketch.h>
22
23 #include <ModuleBase_ISelection.h>
24 #include <ModuleBase_Operation.h>
25 #include <ModuleBase_OperationAction.h>
26 #include <ModuleBase_OperationFeature.h>
27
28 #include <XGUI_ModuleConnector.h>
29 #include <XGUI_Workshop.h>
30 #include <XGUI_Displayer.h>
31 #include <XGUI_DataModel.h>
32 #include <XGUI_ObjectsBrowser.h>
33 #include <XGUI_OperationMgr.h>
34
35 #include <Events_Loop.h>
36 #include <ModelAPI_Events.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_ResultPart.h>
39 #include <ModelAPI_ResultParameter.h>
40
41 #include <QAction>
42 #include <QMenu>
43
44 #include <TopoDS.hxx>
45 #include <BRep_Tool.hxx>
46
47 PartSet_MenuMgr::PartSet_MenuMgr(PartSet_Module* theModule)
48   : QObject(theModule), myModule(theModule), myPrevId(-1)
49 {
50   createActions();
51 }
52
53
54 QAction* PartSet_MenuMgr::action(const QString& theId) const
55 {
56   if (myActions.contains(theId))
57     return myActions[theId];
58   return 0;
59 }
60
61 void PartSet_MenuMgr::addAction(const QString& theId, QAction* theAction)
62 {
63   if (myActions.contains(theId))
64     qCritical("A command with Id = '%s' already defined!", qPrintable(theId));
65   theAction->setData(theId);
66   connect(theAction, SIGNAL(triggered(bool)), this, SLOT(onAction(bool)));
67   myActions[theId] = theAction;
68 }
69
70 void PartSet_MenuMgr::createActions()
71 {
72   QAction* aAction;
73
74   aAction = new QAction(tr("Auxiliary"), this);
75   aAction->setCheckable(true);
76   addAction("AUXILIARY_CMD", aAction);
77
78   aAction = new QAction(QIcon(":icons/activate.png"), tr("Activate"), this);
79   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onActivatePart(bool)));
80   myActions["ACTIVATE_PART_CMD"] = aAction;
81
82   // Activate PartSet
83   aAction = new QAction(QIcon(":icons/activate.png"), tr("Activate"), this);
84   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onActivatePartSet(bool)));
85   myActions["ACTIVATE_PARTSET_CMD"] = aAction;
86
87   aAction = new QAction(QIcon(":icons/edit.png"), tr("Edit..."), this);
88   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onEdit(bool)));
89   myActions["EDIT_CMD"] = aAction;
90
91   aAction = new QAction(QIcon(), tr("Select parent feature"), this);
92   aAction->setCheckable(false);
93   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSelectParentFeature()));
94   myActions["SELECT_PARENT_CMD"] = aAction;
95 }
96
97
98 void PartSet_MenuMgr::onAction(bool isChecked)
99 {
100   QAction* aAction = static_cast<QAction*>(sender());
101   QString anId = aAction->data().toString();
102
103   if (anId == "AUXILIARY_CMD") {
104     setAuxiliary(isChecked);
105   }
106 }
107
108 bool PartSet_MenuMgr::addViewerMenu(QMenu* theMenu, const QMap<QString, QAction*>& theStdActions) const
109 {
110   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
111   if (!PartSet_SketcherMgr::isSketchOperation(anOperation) &&
112       !PartSet_SketcherMgr::isNestedSketchOperation(anOperation))
113     return false;
114
115   myCoinsideLines.clear();
116   ModuleBase_ISelection* aSelection = myModule->workshop()->selection();
117
118   bool aIsDetach = false;
119   bool hasAttribute = false;
120   bool hasFeature = false;
121
122   QList<ModuleBase_ViewerPrs> aPrsList = aSelection->getSelected(ModuleBase_ISelection::Viewer);
123   TopoDS_Shape aShape;
124   ResultPtr aResult;
125   FeaturePtr aFeature;
126   foreach(ModuleBase_ViewerPrs aPrs, aPrsList) {
127     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPrs.object());
128     if (aResult.get() != NULL) {
129       aShape = aPrs.shape();
130       if (aShape.IsEqual(aResult->shape()->impl<TopoDS_Shape>()))
131         hasFeature = true;
132       else
133         hasAttribute = true;
134     } else {
135       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aPrs.object());
136       hasFeature = (aFeature.get() != NULL);
137     }
138   }
139
140   if (aPrsList.size() == 1) {
141     TopoDS_Shape aShape = aPrsList.first().shape();
142     if ((!aShape.IsNull()) && aShape.ShapeType() == TopAbs_VERTEX) {
143       // Find 2d coordinates
144       FeaturePtr aSketchFea = myModule->sketchMgr()->activeSketch();
145       if (aSketchFea->getKind() == SketchPlugin_Sketch::ID()) {
146         gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
147         std::shared_ptr<GeomAPI_Pnt> aPnt3d(new GeomAPI_Pnt(aPnt.X(), aPnt.Y(), aPnt.Z()));
148         std::shared_ptr<GeomAPI_Pnt2d> aSelPnt = PartSet_Tools::convertTo2D(aSketchFea, aPnt3d);
149
150         // Find coincident in these coordinates
151         ObjectPtr aObj = aPrsList.first().object();
152         FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
153         const std::set<AttributePtr>& aRefsList = aFeature->data()->refsToMe();
154         std::set<AttributePtr>::const_iterator aIt;
155         FeaturePtr aCoincident;
156         for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
157           std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
158           FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
159           if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) { 
160             std::shared_ptr<GeomAPI_Pnt2d> a2dPnt = 
161               PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
162             if (a2dPnt.get() && aSelPnt->isEqual(a2dPnt)) { 
163               aCoincident = aConstrFeature;
164               break;
165             } else {
166               a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
167                                                SketchPlugin_ConstraintCoincidence::ENTITY_B());
168               if (a2dPnt.get() && aSelPnt->isEqual(a2dPnt)) { 
169                 aCoincident = aConstrFeature;
170                 break;
171               }
172             }
173           }
174         }
175         // If we have coincidence then add Detach menu
176         if (aCoincident.get() != NULL) {
177           mySelectedFeature = aCoincident;
178           PartSet_Tools::findCoincidences(mySelectedFeature, myCoinsideLines,
179                                           SketchPlugin_ConstraintCoincidence::ENTITY_A());
180           PartSet_Tools::findCoincidences(mySelectedFeature, myCoinsideLines,
181                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
182           if (myCoinsideLines.size() > 0) {
183             aIsDetach = true;
184             QMenu* aSubMenu = theMenu->addMenu(tr("Detach"));
185             QAction* aAction;
186             int i = 0;
187             foreach (FeaturePtr aCoins, myCoinsideLines) {
188               aAction = aSubMenu->addAction(aCoins->data()->name().c_str());
189               aAction->setData(QVariant(i));
190               i++;
191             }
192             connect(aSubMenu, SIGNAL(hovered(QAction*)), SLOT(onLineHighlighted(QAction*)));
193             connect(aSubMenu, SIGNAL(aboutToHide()), SLOT(onDetachMenuHide()));
194             connect(aSubMenu, SIGNAL(triggered(QAction*)), SLOT(onLineDetach(QAction*)));
195           } 
196         }
197       }
198     }
199   }
200   if ((!aIsDetach) && hasFeature) {
201     theMenu->addAction(theStdActions["DELETE_CMD"]);
202   }
203   if (hasAttribute)
204     return true;
205   bool isAuxiliary;
206   if (canSetAuxiliary(isAuxiliary)) {
207     QAction* anAction = action("AUXILIARY_CMD");
208     theMenu->addAction(anAction);
209     anAction->setChecked(isAuxiliary);
210   }
211   return true;
212 }
213
214 void PartSet_MenuMgr::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
215 {
216   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
217
218   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
219                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
220   if (isActiveSketch) {
221     theStdActions["WIREFRAME_CMD"]->setEnabled(false);
222     theStdActions["SHADING_CMD"]->setEnabled(false);
223     theStdActions["SHOW_ONLY_CMD"]->setEnabled(false);
224     theStdActions["SHOW_CMD"]->setEnabled(false);
225     theStdActions["HIDE_CMD"]->setEnabled(false);
226     theStdActions["HIDEALL_CMD"]->setEnabled(false);
227   }
228 }
229
230
231 void PartSet_MenuMgr::onLineHighlighted(QAction* theAction)
232 {
233   if (myPrevId != -1) {
234     // Restore color for previous object
235     setLineColor(myPrevId, myColor, false);
236   }
237   myPrevId = theAction->data().toInt();
238   myColor = setLineColor(myPrevId, Qt::white, true);
239 }
240
241 QColor PartSet_MenuMgr::setLineColor(int theId, const QColor theColor, bool theUpdate)
242 {
243   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
244   XGUI_Workshop* aWorkshop = aConnector->workshop();
245   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
246
247   FeaturePtr aLine = myCoinsideLines.at(myPrevId);
248   std::list<ResultPtr>::const_iterator aIt;
249   const std::list<ResultPtr>& aResults = aLine->results();
250   QColor aColor;
251   for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
252     aColor = aDisplayer->setObjectColor((*aIt), theColor, false);
253   }
254   if (theUpdate)
255     aDisplayer->updateViewer();
256   return aColor;
257 }
258
259
260 void addRefCoincidentFeatures(const std::set<AttributePtr>& theRefList, 
261   std::shared_ptr<GeomAPI_Pnt2d>& theRefPnt,
262   QObjectPtrList& theOutList)
263 {
264   std::set<AttributePtr>::const_iterator aIt;
265   for (aIt = theRefList.cbegin(); aIt != theRefList.cend(); ++aIt) {
266     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
267     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
268     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) { 
269       std::shared_ptr<GeomAPI_Pnt2d> aPnt = PartSet_Tools::getCoincedencePoint(aConstrFeature);
270       if (aPnt.get() == NULL)
271         return;
272       gp_Pnt aP = aPnt->impl<gp_Pnt>();
273       if (theRefPnt->isEqual(aPnt) && (!theOutList.contains(aConstrFeature))) {
274         theOutList.append(aConstrFeature);
275       } 
276     }
277   }
278 }
279
280 void PartSet_MenuMgr::onLineDetach(QAction* theAction)
281 {
282   int aId = theAction->data().toInt();
283   FeaturePtr aLine = myCoinsideLines.at(aId);
284   std::shared_ptr<GeomAPI_Pnt2d> aOrig = PartSet_Tools::getCoincedencePoint(mySelectedFeature);
285   if (!aOrig.get())
286     return;
287   
288   const std::set<AttributePtr>& aRefsList = aLine->data()->refsToMe();
289
290   QObjectPtrList aToDelFeatures;
291
292   addRefCoincidentFeatures(aRefsList, aOrig, aToDelFeatures);
293
294   const std::list<ResultPtr>& aResults = aLine->results();
295   std::list<ResultPtr>::const_iterator aResIt;
296   for (aResIt = aResults.cbegin(); aResIt != aResults.cend(); aResIt++) {
297     ResultPtr aResult = (*aResIt);
298     const std::set<AttributePtr>& aRefList = aResult->data()->refsToMe();
299     addRefCoincidentFeatures(aRefList, aOrig, aToDelFeatures);
300   }
301   if (aToDelFeatures.size() > 0) {
302     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
303     XGUI_Workshop* aWorkshop = aConnector->workshop();
304     ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
305
306     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(
307                                    tr("Detach %1").arg(aLine->data()->name().c_str()), myModule);
308     bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation);
309     XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
310     // the active nested sketch operation should be aborted unconditionally
311     // the Delete action should be additionally granted for the Sketch operation
312     // in order to do not abort/commit it
313     if (!anOpMgr->canStartOperation(tr("Detach")))
314       return; // the objects are processed but can not be deleted
315
316     anOpMgr->startOperation(anOpAction);
317     aWorkshop->deleteFeatures(aToDelFeatures);
318     
319     anOpMgr->commitOperation();
320   }
321   myCoinsideLines.clear();
322 }
323
324
325 void PartSet_MenuMgr::onDetachMenuHide()
326 {
327   if (myPrevId != -1) {
328     // Restore color for previous object
329     setLineColor(myPrevId, myColor, false);
330   }
331   // Clear previous definitions
332   myPrevId = -1;
333 }
334
335   
336 void PartSet_MenuMgr::setAuxiliary(const bool isChecked)
337 {
338   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
339
340   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
341                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
342   if (!isActiveSketch)
343     return;
344
345   QObjectPtrList anObjects;
346   bool isUseTransaction = false;
347   // 1. change auxiliary type of a created feature
348   if (PartSet_SketcherMgr::isNestedCreateOperation(anOperation) &&
349       PartSet_SketcherMgr::isEntity(anOperation->id().toStdString()) ) {
350       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
351                                                                (anOperation);
352       if (aFOperation)
353         anObjects.append(aFOperation->feature());
354   }
355   else {
356     isUseTransaction = true;
357     // 2. change auxiliary type of selected sketch entities
358     ModuleBase_ISelection* aSelection = myModule->workshop()->selection();
359     anObjects = aSelection->selectedPresentations();
360   }
361
362   QAction* anAction = action("AUXILIARY_CMD");
363   //SessionPtr aMgr = ModelAPI_Session::get();
364   ModuleBase_OperationAction* anOpAction = 0;
365   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
366   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
367   if (isUseTransaction) {
368     anOpAction = new ModuleBase_OperationAction(anAction->text(), myModule);
369     bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation);
370
371     if (!anOpMgr->canStartOperation(anOpAction->id()))
372       return; // the objects are processed but can not be deleted
373
374     anOpMgr->startOperation(anOpAction);
375   }
376   myModule->sketchMgr()->storeSelection();
377
378   if (anObjects.size() > 0) {
379     QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
380     for (; anIt != aLast; anIt++) {
381       FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
382       if (aFeature.get() != NULL) {
383         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
384                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
385         if (aSketchFeature.get() != NULL) {
386           std::string anAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
387
388           std::shared_ptr<ModelAPI_AttributeBoolean> anAuxiliaryAttr = 
389             std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(aSketchFeature->data()->attribute(anAttribute));
390           if (anAuxiliaryAttr)
391             anAuxiliaryAttr->setValue(isChecked);
392         }
393       }
394     }
395   }
396   if (isUseTransaction)
397     anOpMgr->commitOperation();
398
399   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
400   myModule->sketchMgr()->restoreSelection();
401 }
402
403 bool PartSet_MenuMgr::canSetAuxiliary(bool& theValue) const
404 {
405   bool anEnabled = false;
406   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
407
408   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
409                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
410   if (!isActiveSketch)
411     return anEnabled;
412
413   QObjectPtrList anObjects;
414   // 1. change auxiliary type of a created feature
415   if (PartSet_SketcherMgr::isNestedCreateOperation(anOperation) &&
416     PartSet_SketcherMgr::isEntity(anOperation->id().toStdString()) ) {
417     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
418     if (aFOperation)
419       anObjects.append(aFOperation->feature());
420   }
421   else {
422     /// The operation should not be aborted here, because the method does not changed
423     /// the auxilliary state, but checks the possibility to perform this
424     ///if (PartSet_SketcherMgr::isNestedSketchOperation(anOperation))
425     ///  anOperation->abort();
426     // 2. change auxiliary type of selected sketch entities
427     ModuleBase_ISelection* aSelection = myModule->workshop()->selection();
428     anObjects = aSelection->selectedPresentations();
429   }
430
431   bool isNotAuxiliaryFound = false;
432   if (anObjects.size() > 0) {
433     QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
434     for (; anIt != aLast && !isNotAuxiliaryFound; anIt++) {
435       FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
436       if ((aFeature.get() != NULL) && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
437         anEnabled = true;
438         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
439                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
440         if (aSketchFeature.get() != NULL) {
441           std::string anAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
442
443           std::shared_ptr<ModelAPI_AttributeBoolean> anAuxiliaryAttr = 
444             std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(aSketchFeature->data()->attribute(anAttribute));
445           if (anAuxiliaryAttr)
446             isNotAuxiliaryFound = !anAuxiliaryAttr->value();
447         }
448       }
449     }
450   }
451   theValue = anObjects.size() && !isNotAuxiliaryFound;
452   return anEnabled;
453 }
454
455 void PartSet_MenuMgr::onActivatePart(bool)
456 {
457   if (myModule->workshop()->currentOperation())
458     return;
459   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
460   if (aObjects.size() > 0) {
461     ObjectPtr aObj = aObjects.first();
462     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
463     if (!aPart.get()) {
464       FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
465       if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
466         aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
467       }
468     }
469     if (aPart.get())
470       aPart->activate();
471   }
472 }
473
474 void PartSet_MenuMgr::onActivatePartSet(bool)
475 {
476   if (myModule->workshop()->currentOperation())
477     return;
478   activatePartSet();
479 }
480
481 void PartSet_MenuMgr::activatePartSet() const
482 {
483   SessionPtr aMgr = ModelAPI_Session::get();
484   bool isNewTransaction = !aMgr->isOperation();
485   // activation may cause changes in current features in document, so it must be in transaction
486   if (isNewTransaction) aMgr->startOperation("Activation");
487   aMgr->setActiveDocument(aMgr->moduleDocument());
488   if (isNewTransaction) aMgr->finishOperation();
489 }
490
491 void PartSet_MenuMgr::grantedOperationIds(ModuleBase_Operation* theOperation,
492                                           QStringList& theIds) const
493 {
494   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
495     theIds.append(tr("Detach"));
496     theIds.append(tr("Auxiliary"));
497   }
498 }
499
500 void PartSet_MenuMgr::onEdit(bool)
501 {
502   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
503   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
504   if (aFeature == NULL) {
505     ResultParameterPtr aParam = 
506       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aObjects.first());
507     if (aParam.get() != NULL) {
508       aFeature = ModelAPI_Feature::feature(aParam);
509     }
510   }
511   if (aFeature.get() != NULL)
512     myModule->editFeature(aFeature);
513 }
514
515 void PartSet_MenuMgr::onSelectParentFeature()
516 {
517   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
518   if (aObjects.size() != 1)
519     return;
520
521   SessionPtr aMgr = ModelAPI_Session::get();
522   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>( aObjects.first() );
523   if( !aResult.get() )
524     return;
525
526   FeaturePtr aParentFeature = aResult->document()->feature( aResult );
527   QObjectPtrList aSelection;
528   aSelection.append( aParentFeature );
529   myModule->workshop()->selection()->setSelectedObjects( aSelection );
530 }