Salome HOME
Merge Dev_2.1.0 with PythonAPI branch
[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_OperationMgr.h>
33
34 #include <Events_Loop.h>
35 #include <ModelAPI_Events.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_ResultPart.h>
38 #include <ModelAPI_ResultParameter.h>
39
40 #include <QAction>
41 #include <QMenu>
42 #include <QEvent>
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         FeaturePtr aCoincident = PartSet_Tools::findFirstCoincidence(aFeature, aSelPnt);
154         // If we have coincidence then add Detach menu
155         if (aCoincident.get() != NULL) {
156           mySelectedFeature = aCoincident;
157           PartSet_Tools::findCoincidences(mySelectedFeature, myCoinsideLines,
158                                           SketchPlugin_ConstraintCoincidence::ENTITY_A());
159           PartSet_Tools::findCoincidences(mySelectedFeature, myCoinsideLines,
160                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
161           if (myCoinsideLines.size() > 0) {
162             aIsDetach = true;
163             QMenu* aSubMenu = theMenu->addMenu(tr("Detach"));
164             QAction* aAction;
165             int i = 0;
166             foreach (FeaturePtr aCoins, myCoinsideLines) {
167               aAction = aSubMenu->addAction(aCoins->data()->name().c_str());
168               aAction->setData(QVariant(i));
169               i++;
170             }
171             connect(aSubMenu, SIGNAL(hovered(QAction*)), SLOT(onLineHighlighted(QAction*)));
172             connect(aSubMenu, SIGNAL(aboutToHide()), SLOT(onDetachMenuHide()));
173             connect(aSubMenu, SIGNAL(triggered(QAction*)), SLOT(onLineDetach(QAction*)));
174           } 
175         }
176       }
177     }
178   }
179   if ((!aIsDetach) && hasFeature) {
180     theMenu->addAction(theStdActions["DELETE_CMD"]);
181   }
182   if (hasAttribute)
183     return true;
184   bool isAuxiliary;
185   if (canSetAuxiliary(isAuxiliary)) {
186     QAction* anAction = action("AUXILIARY_CMD");
187     theMenu->addAction(anAction);
188     anAction->setChecked(isAuxiliary);
189   }
190   return true;
191 }
192
193 void PartSet_MenuMgr::updateViewerMenu(const QMap<QString, QAction*>& theStdActions)
194 {
195   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
196
197   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
198                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
199   if (isActiveSketch) {
200     theStdActions["WIREFRAME_CMD"]->setEnabled(false);
201     theStdActions["SHADING_CMD"]->setEnabled(false);
202     theStdActions["SHOW_ONLY_CMD"]->setEnabled(false);
203     theStdActions["SHOW_CMD"]->setEnabled(false);
204     theStdActions["HIDE_CMD"]->setEnabled(false);
205     theStdActions["HIDEALL_CMD"]->setEnabled(false);
206   }
207 }
208
209
210 void PartSet_MenuMgr::onLineHighlighted(QAction* theAction)
211 {
212   if (myPrevId != -1) {
213     // Restore color for previous object
214     setLineColor(myPrevId, myColor, false);
215   }
216   myPrevId = theAction->data().toInt();
217   myColor = setLineColor(myPrevId, Qt::white, true);
218 }
219
220 QColor PartSet_MenuMgr::setLineColor(int theId, const QColor theColor, bool theUpdate)
221 {
222   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
223   XGUI_Workshop* aWorkshop = aConnector->workshop();
224   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
225
226   FeaturePtr aLine = myCoinsideLines.at(myPrevId);
227   std::list<ResultPtr>::const_iterator aIt;
228   const std::list<ResultPtr>& aResults = aLine->results();
229   QColor aColor;
230   for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
231     aColor = aDisplayer->setObjectColor((*aIt), theColor, false);
232   }
233   if (theUpdate)
234     aDisplayer->updateViewer();
235   return aColor;
236 }
237
238
239 void addRefCoincidentFeatures(const std::set<AttributePtr>& theRefList, 
240   std::shared_ptr<GeomAPI_Pnt2d>& theRefPnt,
241   QObjectPtrList& theOutList)
242 {
243   std::set<AttributePtr>::const_iterator aIt;
244   for (aIt = theRefList.cbegin(); aIt != theRefList.cend(); ++aIt) {
245     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
246     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
247     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) { 
248       std::shared_ptr<GeomAPI_Pnt2d> aPnt = PartSet_Tools::getCoincedencePoint(aConstrFeature);
249       if (aPnt.get() == NULL)
250         return;
251       gp_Pnt aP = aPnt->impl<gp_Pnt>();
252       if (theRefPnt->isEqual(aPnt) && (!theOutList.contains(aConstrFeature))) {
253         theOutList.append(aConstrFeature);
254       } 
255     }
256   }
257 }
258
259 void PartSet_MenuMgr::onLineDetach(QAction* theAction)
260 {
261   int aId = theAction->data().toInt();
262   FeaturePtr aLine = myCoinsideLines.at(aId);
263   std::shared_ptr<GeomAPI_Pnt2d> aOrig = PartSet_Tools::getCoincedencePoint(mySelectedFeature);
264   if (!aOrig.get())
265     return;
266   
267   const std::set<AttributePtr>& aRefsList = aLine->data()->refsToMe();
268
269   QObjectPtrList aToDelFeatures;
270
271   addRefCoincidentFeatures(aRefsList, aOrig, aToDelFeatures);
272
273   const std::list<ResultPtr>& aResults = aLine->results();
274   std::list<ResultPtr>::const_iterator aResIt;
275   for (aResIt = aResults.cbegin(); aResIt != aResults.cend(); aResIt++) {
276     ResultPtr aResult = (*aResIt);
277     const std::set<AttributePtr>& aRefList = aResult->data()->refsToMe();
278     addRefCoincidentFeatures(aRefList, aOrig, aToDelFeatures);
279   }
280   if (aToDelFeatures.size() > 0) {
281     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
282     XGUI_Workshop* aWorkshop = aConnector->workshop();
283     ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
284
285     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(
286                                    tr("Detach %1").arg(aLine->data()->name().c_str()), myModule);
287     bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation);
288     XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
289     // the active nested sketch operation should be aborted unconditionally
290     // the Delete action should be additionally granted for the Sketch operation
291     // in order to do not abort/commit it
292     if (!anOpMgr->canStartOperation(tr("Detach")))
293       return; // the objects are processed but can not be deleted
294
295     anOpMgr->startOperation(anOpAction);
296     aWorkshop->deleteFeatures(aToDelFeatures);
297     
298     anOpMgr->commitOperation();
299   }
300   myCoinsideLines.clear();
301 }
302
303
304 void PartSet_MenuMgr::onDetachMenuHide()
305 {
306   if (myPrevId != -1) {
307     // Restore color for previous object
308     setLineColor(myPrevId, myColor, false);
309   }
310   // Clear previous definitions
311   myPrevId = -1;
312 }
313
314   
315 void PartSet_MenuMgr::setAuxiliary(const bool isChecked)
316 {
317   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
318
319   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
320                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
321   if (!isActiveSketch)
322     return;
323
324   QObjectPtrList anObjects;
325   bool isUseTransaction = false;
326   // 1. change auxiliary type of a created feature
327   if (PartSet_SketcherMgr::isNestedCreateOperation(anOperation) &&
328       PartSet_SketcherMgr::isEntity(anOperation->id().toStdString()) ) {
329       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
330                                                                (anOperation);
331       if (aFOperation)
332         anObjects.append(aFOperation->feature());
333   }
334   else {
335     isUseTransaction = true;
336     // 2. change auxiliary type of selected sketch entities
337     ModuleBase_ISelection* aSelection = myModule->workshop()->selection();
338     anObjects = aSelection->selectedPresentations();
339   }
340
341   QAction* anAction = action("AUXILIARY_CMD");
342   //SessionPtr aMgr = ModelAPI_Session::get();
343   ModuleBase_OperationAction* anOpAction = 0;
344   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
345   XGUI_OperationMgr* anOpMgr = aConnector->workshop()->operationMgr();
346   if (isUseTransaction) {
347     anOpAction = new ModuleBase_OperationAction(anAction->text(), myModule);
348     bool isSketchOp = PartSet_SketcherMgr::isSketchOperation(anOperation);
349
350     if (!anOpMgr->canStartOperation(anOpAction->id()))
351       return; // the objects are processed but can not be deleted
352
353     anOpMgr->startOperation(anOpAction);
354   }
355   myModule->sketchMgr()->storeSelection();
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   myModule->sketchMgr()->restoreSelection();
380 }
381
382 bool PartSet_MenuMgr::canSetAuxiliary(bool& theValue) const
383 {
384   bool anEnabled = false;
385   ModuleBase_Operation* anOperation = myModule->workshop()->currentOperation();
386
387   bool isActiveSketch = PartSet_SketcherMgr::isSketchOperation(anOperation) ||
388                         PartSet_SketcherMgr::isNestedSketchOperation(anOperation);
389   if (!isActiveSketch)
390     return anEnabled;
391
392   QObjectPtrList anObjects;
393   // 1. change auxiliary type of a created feature
394   if (PartSet_SketcherMgr::isNestedCreateOperation(anOperation) &&
395     PartSet_SketcherMgr::isEntity(anOperation->id().toStdString()) ) {
396     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(anOperation);
397     if (aFOperation)
398       anObjects.append(aFOperation->feature());
399   }
400   else {
401     /// The operation should not be aborted here, because the method does not changed
402     /// the auxilliary state, but checks the possibility to perform this
403     ///if (PartSet_SketcherMgr::isNestedSketchOperation(anOperation))
404     ///  anOperation->abort();
405     // 2. change auxiliary type of selected sketch entities
406     ModuleBase_ISelection* aSelection = myModule->workshop()->selection();
407     anObjects = aSelection->selectedPresentations();
408   }
409
410   bool isNotAuxiliaryFound = false;
411   if (anObjects.size() > 0) {
412     QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
413     for (; anIt != aLast && !isNotAuxiliaryFound; anIt++) {
414       FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
415       if ((aFeature.get() != NULL) && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
416         anEnabled = true;
417         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
418                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
419         if (aSketchFeature.get() != NULL) {
420           std::string anAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
421
422           std::shared_ptr<ModelAPI_AttributeBoolean> anAuxiliaryAttr = 
423             std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(aSketchFeature->data()->attribute(anAttribute));
424           if (anAuxiliaryAttr)
425             isNotAuxiliaryFound = !anAuxiliaryAttr->value();
426         }
427       }
428     }
429   }
430   theValue = anObjects.size() && !isNotAuxiliaryFound;
431   return anEnabled;
432 }
433
434 void PartSet_MenuMgr::onActivatePart(bool)
435 {
436   if (myModule->workshop()->currentOperation())
437     return;
438   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
439   if (aObjects.size() > 0) {
440     ObjectPtr aObj = aObjects.first();
441     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
442     if (!aPart.get()) {
443       FeaturePtr aPartFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
444       if (aPartFeature.get() && (aPartFeature->getKind() == PartSetPlugin_Part::ID())) {
445         aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->firstResult());
446       }
447     }
448     if (aPart.get())
449       aPart->activate();
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
470 void PartSet_MenuMgr::grantedOperationIds(ModuleBase_Operation* theOperation,
471                                           QStringList& theIds) const
472 {
473   if (PartSet_SketcherMgr::isSketchOperation(theOperation)) {
474     theIds.append(tr("Detach"));
475     theIds.append(tr("Auxiliary"));
476   }
477 }
478
479 void PartSet_MenuMgr::onEdit(bool)
480 {
481   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
482   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
483   if (aFeature == NULL) {
484     ResultParameterPtr aParam = 
485       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aObjects.first());
486     if (aParam.get() != NULL) {
487       aFeature = ModelAPI_Feature::feature(aParam);
488     }
489   }
490   if (aFeature.get() != NULL)
491     myModule->editFeature(aFeature);
492 }
493
494 void PartSet_MenuMgr::onSelectParentFeature()
495 {
496   QObjectPtrList aObjects = myModule->workshop()->selection()->selectedObjects();
497   if (aObjects.size() != 1)
498     return;
499
500   SessionPtr aMgr = ModelAPI_Session::get();
501   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>( aObjects.first() );
502   if( !aResult.get() )
503     return;
504
505   FeaturePtr aParentFeature = aResult->document()->feature( aResult );
506   QObjectPtrList aSelection;
507   aSelection.append( aParentFeature );
508   myModule->workshop()->selection()->setSelectedObjects( aSelection );
509 }
510
511 bool PartSet_MenuMgr::eventFilter(QObject* theObj, QEvent* theEvent)
512 {
513   if (theEvent->type() == QEvent::MouseButtonDblClick) {
514     SessionPtr aMgr = ModelAPI_Session::get();
515     if (aMgr->activeDocument() != aMgr->moduleDocument())
516       activatePartSet();
517   }
518   return QObject::eventFilter(theObj, theEvent);
519 }