]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Update.cpp
Salome HOME
If extrusion loses sketch contour, it becomes invalid and no results are displayed
[modules/shaper.git] / src / Model / Model_Update.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Update.cxx
4 // Created:     25 Jun 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Update.h>
8 #include <Model_Document.h>
9 #include <Model_Data.h>
10 #include <Model_Objects.h>
11 #include <ModelAPI_Feature.h>
12 #include <ModelAPI_Data.h>
13 #include <ModelAPI_Document.h>
14 #include <ModelAPI_Events.h>
15 #include <ModelAPI_AttributeReference.h>
16 #include <ModelAPI_AttributeRefList.h>
17 #include <ModelAPI_AttributeRefAttr.h>
18 #include <ModelAPI_AttributeSelection.h>
19 #include <ModelAPI_AttributeSelectionList.h>
20 #include <ModelAPI_Result.h>
21 #include <ModelAPI_ResultPart.h>
22 #include <ModelAPI_Validator.h>
23 #include <ModelAPI_CompositeFeature.h>
24 #include <ModelAPI_Session.h>
25 #include <ModelAPI_Tools.h>
26 #include <GeomDataAPI_Point.h>
27 #include <GeomDataAPI_Point2D.h>
28 #include <Events_Loop.h>
29 #include <Events_LongOp.h>
30 #include <Events_Error.h>
31 #include <Config_PropManager.h>
32
33 using namespace std;
34
35 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
36
37 Model_Update::Model_Update()
38 {
39   Events_Loop* aLoop = Events_Loop::loop();
40   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
41   aLoop->registerListener(this, kChangedEvent);
42   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
43   aLoop->registerListener(this, kRebuildEvent);
44   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
45   aLoop->registerListener(this, kCreatedEvent);
46   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
47   aLoop->registerListener(this, kUpdatedEvent);
48   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
49   aLoop->registerListener(this, kMovedEvent);
50   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
51   aLoop->registerListener(this, kOpFinishEvent);
52   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
53   aLoop->registerListener(this, kOpAbortEvent);
54   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
55   aLoop->registerListener(this, kOpStartEvent);
56
57   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
58                                    Config_Prop::Boolean, "false");
59   myIsAutomatic =
60     Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
61   myIsParamUpdated = false;
62 }
63
64 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
65 {
66   static Events_Loop* aLoop = Events_Loop::loop();
67   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
68   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
69   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
70   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
71   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
72   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
73   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
74   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
75   bool isOperationChanged = false;
76   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
77     bool aPropVal =
78       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
79     if (aPropVal != myIsAutomatic) { // something is changed
80       myIsAutomatic = aPropVal;
81       if (myIsAutomatic) // higher level of automatization => to rebuild
82         processOperation(false);
83     }
84   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
85     processOperation(true);
86   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
87              theMessage->eventID() == kMovedEvent) {
88     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
89         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
90     const std::set<ObjectPtr>& anObjs = aMsg->objects();
91     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
92     bool isOnlyResults = true; // check that only results were changed: only redisplay is needed
93     for(; anObjIter != anObjs.cend(); anObjIter++) {
94       if (!std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter).get()) {
95         isOnlyResults = false;
96       }
97       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
98         myIsParamUpdated = true;
99       }
100       // created objects are always must be up to date (python box feature)
101       // and updated not in internal uptation chain
102       myJustUpdated.insert(*anObjIter);
103     }
104     // this event is for solver update, not here, do not react immideately
105     if (!isOnlyResults && !(theMessage->eventID() == kMovedEvent))
106       processOperation(false);
107   } else if (theMessage->eventID() == kOpStartEvent) {
108     // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
109     isOperationChanged = true;
110   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
111     processOperation(true, theMessage->eventID() == kOpFinishEvent);
112     isOperationChanged = true;
113   }
114   if (isOperationChanged) {
115     // remove all macros before clearing all created and execute all not-previewed
116     std::set<ObjectPtr>::iterator anUpdatedIter = myJustUpdated.begin();
117     while(anUpdatedIter != myJustUpdated.end()) {
118       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
119       if (aFeature.get()) {
120         // execute not-previewed feature on "apply"
121         if (!aFeature->isPreviewNeeded()) {
122           static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
123           if (aFactory->validate(aFeature)) {
124             executeFeature(aFeature);
125           }
126         }
127         // remove macro on apply
128         if (aFeature->isMacro()) {
129           aFeature->document()->removeFeature(aFeature);
130           myJustUpdated.erase(aFeature);
131         }
132         // to avoid the map update problems on "remove"
133         if (myJustUpdated.find(aFeature) == myJustUpdated.end()) {
134           anUpdatedIter = myJustUpdated.begin();
135         } else {
136           anUpdatedIter++;
137         }
138       } else {
139         anUpdatedIter++;
140       }
141     }
142     myIsParamUpdated = false;
143   }
144 }
145
146 void Model_Update::processOperation(const bool theTotalUpdate, const bool theFinish)
147 {
148   if (theFinish) {
149     // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
150     std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
151     for(aFIter = myJustUpdated.begin(); aFIter != myJustUpdated.end(); aFIter++)
152     {
153       FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
154       if (aF && aF->data()->isValid() && aF->getKind() == "Extrusion") {
155         AttributeSelectionListPtr aBase = aF->selectionList("base");
156         if (aBase.get()) {
157           for(int a = aBase->size() - 1; a >= 0; a--) {
158             ResultPtr aSketchRes = aBase->value(a)->context();
159             if (aSketchRes) {
160               aSketchRes->setDisplayed(false);
161             }
162           }
163         }
164       }
165     }
166   }
167   // perform update of everything if needed
168   if (!myIsExecuted) {
169     myIsExecuted = true;
170
171     bool isAutomaticChanged = false;
172
173     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
174       isAutomaticChanged = true;
175       myIsAutomatic = true;
176     }
177
178     // iterate all features in the root document to update each
179     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
180     Model_Objects* anObjs = std::dynamic_pointer_cast<Model_Document>(aRootDoc)->objects();
181     if (!anObjs) return;
182     FeaturePtr aFeatureIter = anObjs->firstFeature();
183     std::set<FeaturePtr> aProcessedFeatures; // to avoid processing twice
184     for (; aFeatureIter.get(); aFeatureIter = anObjs->nextFeature(aFeatureIter)) {
185       updateFeature(aFeatureIter, aProcessedFeatures);
186     }
187
188     if (isAutomaticChanged) myIsAutomatic = false;
189     myIsExecuted = false;
190
191     // flush to update display
192     static Events_Loop* aLoop = Events_Loop::loop();
193     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
194     aLoop->flush(EVENT_DISP);
195   }
196 }
197
198 void Model_Update::updateFeature(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
199 {
200   // check all features this feature depended on (recursive call of updateFeature)
201   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
202
203   if (theProcessed.find(theFeature) != theProcessed.end())
204     return;
205   theProcessed.insert(theFeature);
206   if (theFeature->isDisabled())
207     return;
208
209   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
210   // If automatice update is not needed and feature attributes were not updated right now,
211   // do not execute it and do not update arguments.
212   if (!myIsAutomatic && myJustUpdated.find(theFeature) == myJustUpdated.end() && !aCompos.get()) {
213     // execute will be performed later, but some features may have not-result 
214     // presentations, so call update for them (like coincidence in the sketcher)
215     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
216     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
217     return;
218   }
219
220   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
221   updateArguments(theFeature);
222
223   // composite feature must be executed after sub-features execution
224   if (aCompos) {
225     // number of subs can be changed in execution: like fillet
226     for(int a = 0; a < aCompos->numberOfSubs(); a++) {
227       FeaturePtr aSub = aCompos->subFeature(a);
228       updateFeature(aSub, theProcessed);
229     }
230   }
231   // this checking must be after the composite feature sub-elements processing:
232   // composite feature status may depend on it's subelements
233   if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
234     theFeature->eraseResults();
235     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
236     return;
237   }
238
239   bool aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
240
241   if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
242     aJustUpdated = true;
243
244   // execute feature if it must be updated
245   if (theFeature->isPreviewNeeded()) {
246     if ((myIsAutomatic || aJustUpdated) &&
247       std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures()) {
248         ModelAPI_ExecState aState = theFeature->data()->execState();
249         if (aFactory->validate(theFeature)) {
250           executeFeature(theFeature);
251         } else {
252           theFeature->eraseResults();
253           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
254         }
255     }
256   } else { // preview is not needed => make state Done
257     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
258       theFeature->data()->execState(ModelAPI_StateDone);
259     }
260   }
261 }
262
263 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
264 {
265   // make updated and redisplay all results
266   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
267   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
268   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
269   for (; aRIter != aResults.cend(); aRIter++) {
270     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
271     aRes->data()->execState(theState);
272     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
273       aRes->data()->setUpdateID(theFeature->data()->updateID());
274     }
275     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
276   }
277   // to redisplay "presentable" feature (for ex. distance constraint)
278   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
279   theFeature->data()->execState(theState);
280 }
281
282 /// Updates the state by the referenced object: if something bad with it, set state for this one
283 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
284 {
285   if (theTarget) {
286     ModelAPI_ExecState aRefState = theTarget->data()->execState();
287     if (aRefState == ModelAPI_StateMustBeUpdated) {
288       if (theCurrent == ModelAPI_StateDone)
289         return ModelAPI_StateMustBeUpdated;
290     } else if (aRefState != ModelAPI_StateDone) {
291       return ModelAPI_StateInvalidArgument;
292     }
293   }
294   return theCurrent;
295 }
296
297 void Model_Update::updateArguments(FeaturePtr theFeature) {
298   // perform this method also for disabled features: to make "not done" state for
299   // featuers referenced to the active and modified features
300
301   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
302
303   ModelAPI_ExecState aState = theFeature->data()->execState();
304   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
305     aState = ModelAPI_StateMustBeUpdated;
306   // check the parameters state
307   // Double
308   std::list<AttributePtr> aDoubles =
309     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
310   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
311   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
312     AttributeDoublePtr aDouble =
313       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
314     if (aDouble.get() && !aDouble->text().empty()) {
315       if (myIsParamUpdated) {
316         ModelAPI_AttributeEvalMessage::send(aDouble, this);
317       }
318       if (aDouble->expressionInvalid()) {
319         aState = ModelAPI_StateInvalidArgument;
320       }
321     }
322   }
323   // Point
324   {
325     std::list<AttributePtr> anAttributes =
326       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
327     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
328     for(; anIter != anAttributes.end(); anIter++) {
329       AttributePointPtr aPointAttribute =
330         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
331       if (aPointAttribute.get()) {
332         if (myIsParamUpdated) {
333           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
334         }
335         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
336           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
337           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
338           aState = ModelAPI_StateInvalidArgument;
339       }
340     }
341   }
342   // Point2D
343   {
344     std::list<AttributePtr> anAttributes =
345       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
346     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
347     for(; anIter != anAttributes.end(); anIter++) {
348       AttributePoint2DPtr aPoint2DAttribute =
349         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
350       if (aPoint2DAttribute.get()) {
351         if (myIsParamUpdated) {
352           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
353         }
354         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
355           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
356           aState = ModelAPI_StateInvalidArgument;
357       }
358     }
359   }
360
361   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
362   //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
363   // before execution update the selection attributes if any
364   list<AttributePtr> aRefs = 
365     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
366   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
367   for (; aRefsIter != aRefs.end(); aRefsIter++) {
368     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
369       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
370     ObjectPtr aContext = aSel->context();
371     // update argument onlt if the referenced object is changed
372     if (aContext.get() && !aContext->isDisabled() && 
373       aContext->data()->updateID() > theFeature->data()->updateID()) {
374         if (aState == ModelAPI_StateDone)
375           aState = ModelAPI_StateMustBeUpdated;
376         if (!aSel->update()) { // this must be done on execution since it may be long operation
377           if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
378             aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
379             aState = ModelAPI_StateInvalidArgument;
380         }
381     }
382   }
383   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
384   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
385     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
386       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
387     for(int a = aSel->size() - 1; a >= 0; a--) {
388       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
389         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
390       if (aSelAttr) {
391         ObjectPtr aContext = aSelAttr->context();
392         // update argument onlt if the referenced object is changed
393         if (aContext.get() && !aContext->isDisabled() &&
394           aContext->data()->updateID() > theFeature->data()->updateID()) {
395             if (aState == ModelAPI_StateDone)
396               aState = ModelAPI_StateMustBeUpdated;
397             if (!aSelAttr->update()) {
398               if (!aFactory->isNotObligatory(
399                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
400                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
401                 aState = ModelAPI_StateInvalidArgument;
402             }
403         }
404       }
405     }
406   }
407   // check all references: if referenced objects are updated, this object also must be updated
408   // also check state of referenced objects: if they are not ready, inherit corresponding state
409   std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefsObj;
410   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
411   aData->referencesToObjects(aRefsObj);
412   std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefsObj.begin();
413   for(; aRef != aRefsObj.end(); aRef++) {
414     std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
415     for(; aRefObj != aRef->second.end(); aRefObj++) {
416       // if reference is null, it may mean that this reference is to other document
417       // the does not supported by RefList: parameters may be recomputed
418       if (!aRefObj->get() && theFeature->firstResult().get() && 
419                theFeature->firstResult()->groupName() == ModelAPI_ResultParameter::group()) {
420           if (aState == ModelAPI_StateDone)
421             aState = ModelAPI_StateMustBeUpdated;
422       } else if (myJustUpdated.find(*aRefObj) != myJustUpdated.end() || 
423              (aRefObj->get() && (*aRefObj)->data()->updateID() > theFeature->data()->updateID())) {
424           if (aState == ModelAPI_StateDone)
425             aState = ModelAPI_StateMustBeUpdated;
426       }
427       aState = stateByReference(*aRefObj, aState);
428     }
429   }
430
431   if (aState != ModelAPI_StateDone)
432     theFeature->data()->execState(aState);
433 }
434
435 void Model_Update::executeFeature(FeaturePtr theFeature)
436 {
437   // execute in try-catch to avoid internal problems of the feature
438   ModelAPI_ExecState aState = ModelAPI_StateDone;
439   theFeature->data()->execState(ModelAPI_StateDone);
440   try {
441     theFeature->execute();
442     myJustUpdated.erase(theFeature);
443     if (theFeature->data()->execState() != ModelAPI_StateDone) {
444       aState = ModelAPI_StateExecFailed;
445     } else {
446       aState = ModelAPI_StateDone;
447     }
448   } catch(...) {
449     aState = ModelAPI_StateExecFailed;
450     Events_Error::send(
451       "Feature " + theFeature->getKind() + " has failed during the execution");
452   }
453   if (aState != ModelAPI_StateDone) {
454     theFeature->eraseResults();
455   }
456   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
457   redisplayWithResults(theFeature, aState);
458 }