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