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