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