Salome HOME
c4035cc22e1a565b98e92ed14dd95a1190c8f7dd
[modules/shaper.git] / src / PartSet / PartSet_WidgetSketchCreator.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_WidgetSketchCreator.cpp
4 // Created:     08 June 2015
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_WidgetSketchCreator.h"
8 #include "PartSet_Module.h"
9 #include "PartSet_WidgetSketchLabel.h"
10 #include "PartSet_PreviewPlanes.h"
11
12 #include <Config_Keywords.h>
13
14 #include <XGUI_ModuleConnector.h>
15 #include <XGUI_Workshop.h>
16 #include <XGUI_Displayer.h>
17 #include <XGUI_SelectionMgr.h>
18 #include <XGUI_OperationMgr.h>
19 #include <XGUI_PropertyPanel.h>
20 #include <XGUI_Tools.h>
21 #include <XGUI_ViewerProxy.h>
22
23 #include <GeomAPI_Face.h>
24
25 #include <Events_InfoMessage.h>
26
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_ResultBody.h>
29 #include <ModelAPI_AttributeSelection.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Validator.h>
32 #include <ModelAPI_Events.h>
33 #include <ModelAPI_ResultConstruction.h>
34
35 #include <SketchPlugin_SketchEntity.h>
36 #include <FeaturesPlugin_CompositeBoolean.h>
37
38 #include <ModuleBase_Tools.h>
39 #include <ModuleBase_Operation.h>
40 #include <ModuleBase_IPropertyPanel.h>
41 #include <ModuleBase_OperationFeature.h>
42 #include <ModuleBase_ViewerPrs.h>
43
44 #include <Config_WidgetAPI.h>
45
46 #include <Events_Loop.h>
47
48 #include <QLabel>
49 #include <QLineEdit>
50 //#include <QFormLayout>
51 #include <QVBoxLayout>
52 #include <QMessageBox>
53 #include <QMainWindow>
54
55 #define DEBUG_UNDO_INVALID_SKETCH
56
57 PartSet_WidgetSketchCreator::PartSet_WidgetSketchCreator(QWidget* theParent, 
58                                                          PartSet_Module* theModule,
59                                                          const Config_WidgetAPI* theData)
60 : ModuleBase_WidgetSelector(theParent, theModule->workshop(), theData),
61   myModule(theModule), myIsCustomAttribute(false)
62 {
63   myAttributeListID = theData->getProperty("attribute_list_id");
64
65   //QFormLayout* aLayout = new QFormLayout(this);
66   QVBoxLayout* aLayout = new QVBoxLayout(this);
67   ModuleBase_Tools::zeroMargins(aLayout);
68
69   ModuleBase_Tools::adjustMargins(aLayout);
70
71   QString aLabelText = QString::fromStdString(theData->widgetLabel());
72   QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
73
74   myLabel = new QLabel(aLabelText, this);
75   myLabel->setWordWrap(true);
76   aLayout->addWidget(myLabel);
77   aLayout->addStretch(1);
78
79   std::string aTypes = theData->getProperty("shape_types");
80   myShapeTypes = QString(aTypes.c_str()).split(' ', QString::SkipEmptyParts);
81
82   myPreviewPlanes = new PartSet_PreviewPlanes();
83 }
84
85 PartSet_WidgetSketchCreator::~PartSet_WidgetSketchCreator()
86 {
87   // we need to deactivate here in order to hide preview planes if the selection mode is
88   // active
89   deactivate();
90 }
91
92 QList<QWidget*> PartSet_WidgetSketchCreator::getControls() const
93 {
94   QList<QWidget*> aControls;
95   aControls.append(myLabel);
96   return aControls;
97 }
98
99 bool PartSet_WidgetSketchCreator::restoreValueCustom()
100 {
101   return true;
102 }
103
104 bool PartSet_WidgetSketchCreator::storeValueCustom()
105 {
106   return true;
107 }
108
109 AttributePtr PartSet_WidgetSketchCreator::attribute() const
110 {
111   AttributePtr anAttribute;
112   if (myIsCustomAttribute)
113     anAttribute = myFeature->attribute(myAttributeListID);
114   else
115     anAttribute = ModuleBase_WidgetSelector::attribute();
116
117   return anAttribute;
118 }
119
120 //********************************************************************
121 void PartSet_WidgetSketchCreator::openExtrusionTransaction()
122 {
123   SessionPtr aMgr = ModelAPI_Session::get();
124   bool aIsOp = aMgr->isOperation();
125   if (!aIsOp) {
126     const static std::string aNestedOpID("Parameters modification");
127     aMgr->startOperation(aNestedOpID, true);
128   }
129 }
130
131 //********************************************************************
132 bool PartSet_WidgetSketchCreator::isValidSelection(const ModuleBase_ViewerPrsPtr& theValue)
133 {
134   bool aValid = false;
135   if (myIsCustomAttribute) {
136     // check only suiting of the value to custom attribute (myAttributeListID)
137     // do not cash of validation to avoid using states, stored for XML attribute
138     // there is an alternative is to call clearValidatedCash() in setSelection()
139     aValid = isValidSelectionForAttribute(theValue, attribute());
140   }
141   else { /// if the validated attribute is already custom
142     if (getValidState(theValue, aValid)) {
143       return aValid;
144     }
145     aValid = isValidSelectionCustom(theValue);
146     if (!aValid)
147       // check selection to create new sketh (XML current attribute)
148       aValid = isValidSelectionForAttribute(theValue, attribute());
149     if (!aValid) {
150       // check selection to fill list attribute (myAttributeListID)
151       bool isCustomAttribute = myIsCustomAttribute;
152       myIsCustomAttribute = true;
153       aValid = isValidSelectionForAttribute(theValue, attribute());
154       myIsCustomAttribute = isCustomAttribute;
155     }
156   }
157   storeValidState(theValue, aValid);
158   return aValid;
159 }
160
161 //********************************************************************
162 bool PartSet_WidgetSketchCreator::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& theValue)
163 {
164   return PartSet_WidgetSketchLabel::canFillSketch(theValue);
165 }
166
167 void PartSet_WidgetSketchCreator::activateSelectionControl()
168 {
169   // we need to call activate here as the widget has no focus accepted controls
170   // if these controls are added here, activate will happens automatically after focusIn()
171   XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
172   XGUI_PropertyPanel* aPanel = aWorkshop->propertyPanel();
173   aPanel->activateWidget(this, false);
174 }
175
176 void PartSet_WidgetSketchCreator::setVisibleSelectionControl(const bool theSelectionControl)
177 {
178   // hide current widget, activate the next widget
179   XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
180   XGUI_PropertyPanel* aPanel = aWorkshop->propertyPanel();
181   const QList<ModuleBase_ModelWidget*>& aWidgets = aPanel->modelWidgets();
182   foreach(ModuleBase_ModelWidget* aWidget, aWidgets) {
183     if (theSelectionControl) { // hide other controls
184       if (aWidget != this)
185         aWidget->setVisible(false);
186     }
187     else { // hide current control
188       if (aWidget == this)
189         aWidget->setVisible(false);
190       else {
191         aWidget->setVisible(true);
192         if (aWidget->attributeID() == myAttributeListID)
193           setEnabledModelWidget(aWidget, !hasSubObjects());
194       }
195     }
196   }
197
198   if (theSelectionControl) {
199     bool aBodyIsVisualized = myPreviewPlanes->hasVisualizedBodies(myWorkshop);
200     bool aSketchIsVisualized = myPreviewPlanes->hasVisualizedSketch(myWorkshop);
201     if (!aBodyIsVisualized && !aSketchIsVisualized) {
202       // We have to select a plane before any operation
203       myPreviewPlanes->showPreviewPlanes(myWorkshop);
204     }
205   } else {
206     bool aHidePreview = myPreviewPlanes->isPreviewDisplayed();
207     myPreviewPlanes->erasePreviewPlanes(myWorkshop);
208     if (aHidePreview)
209       aWorkshop->viewer()->update();
210   }
211 }
212
213 QIntList PartSet_WidgetSketchCreator::shapeTypes() const
214 {
215   QIntList aShapeTypes;
216   foreach(QString aType, myShapeTypes) {
217     aShapeTypes.append(ModuleBase_Tools::shapeType(aType));
218   }
219   return aShapeTypes;
220 }
221
222 void PartSet_WidgetSketchCreator::setEditingMode(bool isEditing)
223 {
224   ModuleBase_ModelWidget::setEditingMode(isEditing);
225   if (isEditing) {
226     setVisibleSelectionControl(false);
227
228     ModuleBase_ModelWidget* anAttributeListWidget = 0;
229     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
230     XGUI_PropertyPanel* aPanel = aWorkshop->propertyPanel();
231     const QList<ModuleBase_ModelWidget*>& aWidgets = aPanel->modelWidgets();
232     foreach(ModuleBase_ModelWidget* aWidget, aWidgets) {
233       if (aWidget->attributeID() == myAttributeListID) {
234         anAttributeListWidget = aWidget;
235         break;
236       }
237     }
238     if (anAttributeListWidget)
239       setEnabledModelWidget(anAttributeListWidget, !hasSubObjects());
240   }
241 }
242
243 bool PartSet_WidgetSketchCreator::isSelectionMode() const
244 {
245   AttributeSelectionListPtr anAttrList = myFeature->data()->selectionList(myAttributeListID);
246   bool aHasValueInList = anAttrList.get() && anAttrList->size() > 0;
247
248   return !aHasValueInList;
249 }
250
251 bool PartSet_WidgetSketchCreator::hasSubObjects() const
252 {
253   bool aHasSubObjects = false;
254
255   bool aCanSetFocus = true;
256   CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
257   if (aComposite.get())
258     aHasSubObjects = aComposite->numberOfSubs() > 0;
259   return aHasSubObjects;
260 }
261
262 bool PartSet_WidgetSketchCreator::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
263                                                const bool theToValidate)
264 {
265   bool aDone = false;
266   if (!startSketchOperation(theValues)) {
267     myIsCustomAttribute = true;
268     QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
269     bool aProcessed = false;
270     for (; anIt != aLast; anIt++) {
271       ModuleBase_ViewerPrsPtr aValue = *anIt;
272       if (!theToValidate || isValidInFilters(aValue))
273         aProcessed = setSelectionCustom(aValue) || aProcessed;
274     }
275     myIsCustomAttribute = false;
276     aDone = aProcessed;
277     if (aProcessed) {
278       emit valuesChanged();
279       updateObject(myFeature);
280       setVisibleSelectionControl(false);
281       // manually deactivation because the widget was not activated as has no focus acceptin controls
282       deactivate();
283       emit focusOutWidget(this);
284     }
285   }
286   return aDone;
287 }
288
289 //********************************************************************
290 void PartSet_WidgetSketchCreator::onSelectionChanged()
291 {
292   QList<ModuleBase_ViewerPrsPtr> aSelected = getFilteredSelected();
293   bool isDone = setSelection(aSelected, true/*false*/);
294 }
295
296 //********************************************************************
297 void PartSet_WidgetSketchCreator::updateOnSelectionChanged(const bool theDone)
298 {
299 }
300
301 bool PartSet_WidgetSketchCreator::startSketchOperation(const QList<ModuleBase_ViewerPrsPtr>& theValues)
302 {
303   bool aSketchStarted = false;
304
305   if (theValues.size() != 1)
306     return aSketchStarted;
307
308   ModuleBase_ViewerPrsPtr aValue = theValues.front();
309   if (!aValue.get() || !PartSet_WidgetSketchLabel::canFillSketch(aValue))
310     return aSketchStarted;
311
312   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aValue->object());
313   /// sketch should not started by object(face) selected as global. If Local face is selected,
314   /// sketch is started
315   if (aResult.get() && aValue->shape().get() && aResult->shape()->isEqual(aValue->shape())) {
316     ResultConstructionPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aResult);
317     if (!aConstruction.get() || !aConstruction->isInfinite())
318       return aSketchStarted;
319   }
320   aSketchStarted = true;
321
322   // manually deactivation because the widget was not activated as has no focus acceptin controls
323   deactivate();
324   bool aHidePreview = myPreviewPlanes->isPreviewDisplayed();
325   myPreviewPlanes->erasePreviewPlanes(myWorkshop);
326
327   // Launch Sketch operation
328   CompositeFeaturePtr aCompFeature = 
329     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
330
331   // start edit operation for the sketch
332   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
333                                                             (myModule->createOperation("Sketch"));
334   QList<ModuleBase_ViewerPrsPtr> aValues;
335   aValues.push_back(aValue);
336   aFOperation->setPreselection(aValues);
337
338   myModule->sendOperation(aFOperation);
339
340   return aSketchStarted;
341 }
342
343 bool PartSet_WidgetSketchCreator::focusTo()
344 {
345   // this method is called only in creation mode. In Edition mode this widget is hidden
346   if (isSelectionMode() && !hasSubObjects()) {
347     setVisibleSelectionControl(true);
348     activateSelectionControl();
349     openExtrusionTransaction();
350     return true;
351   }
352   else
353     connect(myModule, SIGNAL(resumed(ModuleBase_Operation*)), SLOT(onResumed(ModuleBase_Operation*)));
354
355   return true;
356 }
357
358 void PartSet_WidgetSketchCreator::deactivate()
359 {
360   ModuleBase_WidgetSelector::deactivate();
361
362   bool aHidePreview = myPreviewPlanes->isPreviewDisplayed();
363   myPreviewPlanes->erasePreviewPlanes(myWorkshop);
364   if (aHidePreview)
365     XGUI_Tools::workshop(myWorkshop)->viewer()->update();
366
367 }
368
369 void PartSet_WidgetSketchCreator::onResumed(ModuleBase_Operation* theOp)
370 {
371   SessionPtr aMgr = ModelAPI_Session::get();
372   bool aIsOp = aMgr->isOperation();
373   if (aIsOp) {
374     // in current implementation, all transactions are closed when resume happens
375     // so, this is a wrong case, which is not checked.
376     // To provide it, make correction in later rows about abort/undo transactions
377     return;
378   }
379   // Set visible only selection control
380   setVisibleSelectionControl(true);
381
382   // Validate the created sketch. If it is valid, it is set into the composite feature selection
383   // list, otherwise it is removed
384   CompositeFeaturePtr aCompFeature = 
385     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
386   AttributeSelectionListPtr anAttrList = myFeature->data()->selectionList(myAttributeListID);
387   if (aCompFeature->numberOfSubs() > 0) {
388     // set the sub feature to attribute selection list and check whether sketch is valid
389     SessionPtr aMgr = ModelAPI_Session::get();
390     const static std::string aNestedOpID("Set Sketch result into Selection list");
391     aMgr->startOperation(aNestedOpID, false); // false to not attach to Extrusion operation
392     setSketchObjectToList(aCompFeature, anAttrList);
393     aMgr->finishOperation();
394
395     if (!validateSelectionList()) {
396 #ifdef DEBUG_UNDO_INVALID_SKETCH
397       aMgr->undo(); // Extrusion modification parameters: setSketchObjectToList()
398       aMgr->undo(); /// Sketch creation
399 #else
400       aMgr->startOperation("Delete invalid Sketch feature", false);
401
402       // delete invalid sketch
403       CompositeFeaturePtr aSketchFeature = 
404               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCompFeature->subFeature(0));
405       QObjectPtrList anObjects;
406       anObjects.append(aSketchFeature);
407
408       XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
409       aWorkshop->deleteFeatures(anObjects);
410
411       aMgr->finishOperation();
412 #endif
413     }
414   }
415   openExtrusionTransaction();
416
417   if (aCompFeature->numberOfSubs() == 0) {
418     // call activateWidget() of the parent to connect to the viewer seleciton
419     activateSelectionControl();
420   }
421   else {
422     // check if the created sketch is valid. If it is invalid, it will be deleted with warning else
423     /// the attribute selection list will be filled by result of this sketch.
424     setVisibleSelectionControl(false);
425
426     // Update value in attribute selection list
427     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
428     XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
429     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
430     ModuleBase_ModelWidget* aListWidget = 0;
431     foreach(ModuleBase_ModelWidget* aWidget, aWidgets) {
432       if (aWidget->attributeID() == myAttributeListID) {
433         aListWidget = aWidget;
434         break;
435       }
436     }
437     if (aListWidget) {
438       aListWidget->restoreValue();
439       aPropertyPanel->activateNextWidget(aListWidget);
440     }
441
442     // Hide sketcher result
443     CompositeFeaturePtr aSketchFeature = 
444       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCompFeature->subFeature(0));
445     std::list<ResultPtr> aResults = aSketchFeature->results();
446     std::list<ResultPtr>::const_iterator aIt;
447     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
448       (*aIt)->setDisplayed(false);
449     }
450     aSketchFeature->setDisplayed(false);
451     static Events_Loop* aLoop = Events_Loop::loop();
452     aLoop->flush(aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY));
453
454     // Add Selected body were created the sketcher to list of selected objects
455     std::string anObjectsAttribute = FeaturesPlugin_CompositeBoolean::OBJECTS_ID();
456     AttributeSelectionListPtr aSelList = aCompFeature->data()->selectionList(anObjectsAttribute);
457     if (aSelList.get()) {
458       DataPtr aData = aSketchFeature->data();
459       AttributeSelectionPtr aSelAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
460                                     (aData->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID()));
461       ResultPtr aRes = aSelAttr.get() ? aSelAttr->context() : ResultPtr();
462       if (aRes.get()) {
463         SessionPtr aMgr = ModelAPI_Session::get();
464         ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
465         AttributePtr anAttribute = myFeature->attribute(anObjectsAttribute);
466         std::string aValidatorID;
467         Events_InfoMessage anError;
468         aSelList->append(aRes, GeomShapePtr());
469         if (aFactory->validate(anAttribute, aValidatorID, anError))
470           updateObject(aCompFeature);
471         else
472           aSelList->clear();
473       }
474     }
475   }
476   restoreValue();
477 }
478
479 bool PartSet_WidgetSketchCreator::validateSelectionList() const
480 {
481   AttributeSelectionListPtr anAttrList = myFeature->data()->selectionList(myAttributeListID);
482
483   SessionPtr aMgr = ModelAPI_Session::get();
484   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
485   std::string aValidatorID;
486   Events_InfoMessage anError;
487   bool isValidPComposite = aFactory->validate(anAttrList, aValidatorID, anError);
488   if (!isValidPComposite) {
489     XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myModule->workshop());
490     // TODO(spo): translate
491     QMessageBox::question(aWorkshop->desktop(), tr("Apply current feature"),
492                   tr("Sketch is invalid and will be deleted.\nError: %1").arg(anError.messageString().c_str()),
493                   QMessageBox::Ok);
494   }
495   return isValidPComposite;
496 }
497
498 void PartSet_WidgetSketchCreator::setSketchObjectToList(const CompositeFeaturePtr& theCompositeFeature,
499                                                         const AttributePtr& theAttribute)
500 {
501   if (!theCompositeFeature.get() || theCompositeFeature->numberOfSubs() != 1)
502     return;
503
504   AttributeSelectionListPtr aBaseObjectsSelectionList =
505                      std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(theAttribute);
506   if(!aBaseObjectsSelectionList.get() || aBaseObjectsSelectionList->isInitialized()) {
507     return;
508   }
509
510   FeaturePtr aSketchFeature = theCompositeFeature->subFeature(0);
511   if(!aSketchFeature.get() || aSketchFeature->results().empty()) {
512     return;
513   }
514
515   ResultPtr aSketchRes = aSketchFeature->results().front();
516   ResultConstructionPtr aConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aSketchRes);
517   if(!aConstruction.get()) {
518     return;
519   }
520
521   if(aBaseObjectsSelectionList->size() == 0) {
522     aBaseObjectsSelectionList->append(aSketchRes, GeomShapePtr());
523   }
524 }
525
526 void PartSet_WidgetSketchCreator::setEnabledModelWidget(ModuleBase_ModelWidget* theModelWidget,
527                                                         const bool theEnabled)
528 {
529   QList<QWidget*> aMyControls = theModelWidget->getControls();
530   foreach(QWidget*  eachControl, aMyControls) {
531     eachControl->setEnabled(theEnabled);
532   }
533 }