Salome HOME
be69043e92c72ee0c7b9910ebbbfe954a4d86b1e
[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 <Events_Loop.h>
27 #include <Events_LongOp.h>
28 #include <Events_Error.h>
29 #include <Config_PropManager.h>
30
31 using namespace std;
32
33 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
34
35 Model_Update::Model_Update()
36 {
37   Events_Loop* aLoop = Events_Loop::loop();
38   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
39   aLoop->registerListener(this, kChangedEvent);
40   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
41   aLoop->registerListener(this, kRebuildEvent);
42   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
43   aLoop->registerListener(this, kCreatedEvent);
44   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
45   aLoop->registerListener(this, kUpdatedEvent);
46   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
47   aLoop->registerListener(this, kMovedEvent);
48   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
49   aLoop->registerListener(this, kOpFinishEvent);
50   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
51   aLoop->registerListener(this, kOpAbortEvent);
52   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
53   aLoop->registerListener(this, kOpStartEvent);
54
55   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
56                                    Config_Prop::Boolean, "false");
57   myIsAutomatic =
58     Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
59 }
60
61 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
62 {
63   static Events_Loop* aLoop = Events_Loop::loop();
64   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
65   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
66   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
67   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
68   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
69   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
70   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
71   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
72   bool isOperationChanged = false;
73   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
74     bool aPropVal =
75       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
76     if (aPropVal != myIsAutomatic) { // something is changed
77       myIsAutomatic = aPropVal;
78       if (myIsAutomatic) // higher level of automatization => to rebuild
79         processOperation(false);
80     }
81   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
82     processOperation(true);
83   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
84              theMessage->eventID() == kMovedEvent) {
85     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
86         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
87     const std::set<ObjectPtr>& anObjs = aMsg->objects();
88     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
89     bool isOnlyResults = true; // check that only results were changed: only redisplay is needed
90     for(; anObjIter != anObjs.cend(); anObjIter++) {
91       if (!std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter).get()) {
92         isOnlyResults = false;
93       }
94       // created objects are always must be up to date (python box feature)
95       // and updated not in internal uptation chain
96       if (theMessage->eventID() == kCreatedEvent) {
97         myJustCreated.insert(*anObjIter);
98       } else if (myJustCreated.find(*anObjIter) == myJustCreated.end()) { // moved and updated
99         myJustUpdated.insert(*anObjIter);
100       }
101     }
102      // this event is for solver update, not here, do not react immideately
103     if (!isOnlyResults && !(theMessage->eventID() == kMovedEvent))
104       processOperation(false);
105   } else if (theMessage->eventID() == kOpStartEvent) {
106     // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
107     isOperationChanged = true;
108   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
109     processOperation(true, theMessage->eventID() == kOpFinishEvent);
110     isOperationChanged = true;
111   }
112   if (isOperationChanged) {
113     // remove all macros before clearing all created
114     std::set<ObjectPtr>::iterator aCreatedIter = myJustCreated.begin();
115     for(; aCreatedIter != myJustCreated.end(); aCreatedIter++) {
116       FeaturePtr aFeature = 
117         std::dynamic_pointer_cast<ModelAPI_Feature>(*aCreatedIter);
118       if (aFeature.get()) {
119         // execute not-previewed feature on "apply"
120         if (!aFeature->isPreviewNeeded() && (myJustCreated.find(aFeature) != myJustCreated.end() ||
121           myJustUpdated.find(aFeature) != myJustUpdated.end())) {
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         }
131       }
132     }
133     myJustCreated.clear();
134     myJustUpdated.clear();
135   }
136 }
137
138 void Model_Update::processOperation(const bool theTotalUpdate, const bool theFinish)
139 {
140   if (theFinish) {
141     // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
142     std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
143     for(aFIter = myJustCreated.begin(); aFIter != myJustCreated.end(); aFIter++)
144     {
145       FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
146       if (aF && aF->data().get() && aF->getKind() == "Extrusion") {
147         AttributeSelectionListPtr aBase = aF->selectionList("base");
148         if (aBase.get()) {
149           for(int a = aBase->size() - 1; a >= 0; a--) {
150             ResultPtr aSketchRes = aBase->value(a)->context();
151             if (aSketchRes) {
152               aSketchRes->setDisplayed(false);
153             }
154           }
155         }
156       }
157     }
158   }
159   // perform update of everything if needed
160   if (!myIsExecuted) {
161     myIsExecuted = true;
162
163     bool isAutomaticChanged = false;
164
165     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
166       isAutomaticChanged = true;
167       myIsAutomatic = true;
168     }
169
170     updateInDoc(ModelAPI_Session::get()->moduleDocument());
171
172     if (isAutomaticChanged) myIsAutomatic = false;
173     myIsExecuted = false;
174
175     // flush to update display
176     static Events_Loop* aLoop = Events_Loop::loop();
177     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
178     aLoop->flush(EVENT_DISP);
179   }
180 }
181
182 void Model_Update::updateInDoc(std::shared_ptr<ModelAPI_Document> theDoc)
183 {
184   std::set<FeaturePtr> alreadyProcessed; // features that are processed before others
185   // all features one by one
186   Model_Objects* anObjs = std::dynamic_pointer_cast<Model_Document>(theDoc)->objects();
187   if (!anObjs) return;
188   FeaturePtr aFeatureIter = anObjs->firstFeature();
189   for (; aFeatureIter.get(); aFeatureIter = anObjs->nextFeature(aFeatureIter)) {
190     if (aFeatureIter && alreadyProcessed.find(aFeatureIter) == alreadyProcessed.end()) {
191       // update selection and parameters attributes first, before sub-features analysis (sketch plane)
192       updateArguments(aFeatureIter);
193       // composite feature must be executed after sub-features execution
194       CompositeFeaturePtr aComposite = 
195         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeatureIter);
196       if (aComposite) {
197         // number of subs can be changed in execution: like fillet
198         for(int a = 0; a < aComposite->numberOfSubs(); a++) {
199           FeaturePtr aSub = aComposite->subFeature(a);
200           updateArguments(aSub);
201           updateFeature(aSub);
202           alreadyProcessed.insert(aSub);
203         }
204       }
205
206       updateFeature(aFeatureIter);
207       // update the document results recursively
208       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeatureIter->results();
209       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
210       for (; aRIter != aResults.cend(); aRIter++) {
211         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
212         if (aPart.get()) {
213           if (!aPart->isDisabled() && aPart->isActivated()) {
214             updateInDoc(aPart->partDoc());
215           }
216         }
217       }
218     }
219   }
220 }
221
222 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
223 {
224   // make updated and redisplay all results
225   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
226   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
227   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
228   for (; aRIter != aResults.cend(); aRIter++) {
229     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
230     aRes->data()->execState(theState);
231     myJustUpdated.insert(aRes);
232     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
233   }
234   // to redisplay "presentable" feature (for ex. distance constraint)
235   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
236   theFeature->data()->execState(theState);
237 }
238
239 /// Updates the state by the referenced object: if something bad with it, set state for this one
240 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
241 {
242   if (theTarget) {
243     ModelAPI_ExecState aRefState = theTarget->data()->execState();
244     if (aRefState == ModelAPI_StateMustBeUpdated) {
245       return ModelAPI_StateMustBeUpdated;
246     } else if (aRefState != ModelAPI_StateDone) {
247       return ModelAPI_StateInvalidArgument;
248     }
249   }
250   return theCurrent;
251 }
252
253 void Model_Update::updateArguments(FeaturePtr theFeature) {
254   // perform this method also for disabled features: to make "not done" state for
255   // featuers referenced to the active and modified features
256
257   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
258
259   bool aJustUpdated = false;
260   ModelAPI_ExecState aState = theFeature->data()->execState();
261   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
262     aState = ModelAPI_StateMustBeUpdated;
263   // check the parameters state
264   std::list<AttributePtr> aDoubles = 
265     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId()); 
266   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
267   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
268     AttributeDoublePtr aDouble = 
269       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
270     if (aDouble.get() && aDouble->expressionInvalid()) {
271       aState = ModelAPI_StateInvalidArgument;
272     }
273   }
274
275   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
276     //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
277     // before execution update the selection attributes if any
278     list<AttributePtr> aRefs = 
279       theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
280     list<AttributePtr>::iterator aRefsIter = aRefs.begin();
281     for (; aRefsIter != aRefs.end(); aRefsIter++) {
282       std::shared_ptr<ModelAPI_AttributeSelection> aSel =
283         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
284       ObjectPtr aContext = aSel->context();
285       // update argument onlt if the referenced object is changed
286       if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
287         if (aState == ModelAPI_StateDone)
288           aState = ModelAPI_StateMustBeUpdated;
289         if (!aSel->update()) { // this must be done on execution since it may be long operation
290           if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
291               aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
292             aState = ModelAPI_StateInvalidArgument;
293         }
294       }
295     }
296     aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
297     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
298       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
299         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
300       for(int a = aSel->size() - 1; a >= 0; a--) {
301         std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
302           std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
303         if (aSelAttr) {
304           ObjectPtr aContext = aSelAttr->context();
305           // update argument onlt if the referenced object is changed
306           if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
307             if (aState == ModelAPI_StateDone)
308               aState = ModelAPI_StateMustBeUpdated;
309             if (!aSelAttr->update()) {
310               if (!aFactory->isNotObligatory(
311                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
312                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
313                 aState = ModelAPI_StateInvalidArgument;
314             }
315           }
316         }
317       }
318     }
319   //}
320   if (aJustUpdated && myJustCreated.find(theFeature) == myJustCreated.end())
321   myJustUpdated.insert(theFeature);
322   if (aState != ModelAPI_StateDone)
323     theFeature->data()->execState(aState);
324 }
325
326 void Model_Update::updateFeature(FeaturePtr theFeature)
327 {
328   // check all features this feature depended on (recursive call of updateFeature)
329   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
330
331   if (theFeature->isDisabled() ||  // nothing to do with disabled feature
332       theFeature->data()->execState() == ModelAPI_StateInvalidArgument)
333     return;
334   bool aJustUpdated = false;
335
336   if (theFeature) {
337     if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
338       aJustUpdated = true;
339
340     ModelAPI_ExecState aState = ModelAPI_StateDone;
341
342     // check all references: if referenced objects are updated, this object also must be updated
343     // also check state of referenced objects: if they are not ready, inherit corresponding state
344     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
345     std::shared_ptr<Model_Data> aData = 
346       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
347     aData->referencesToObjects(aRefs);
348     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
349     for(; aRef != aRefs.end(); aRef++) {
350       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
351       for(; aRefObj != aRef->second.end(); aRefObj++) {
352         if (myJustCreated.find(*aRefObj) != myJustCreated.end() ||
353             myJustUpdated.find(*aRefObj) != myJustUpdated.end()) {
354           aJustUpdated = true;
355         }
356         aState = stateByReference(*aRefObj, aState);
357       }
358     }
359
360     // some arguments were changed, so, this feature must be updated
361     if (myJustCreated.find(theFeature) != myJustCreated.end()) {
362       aJustUpdated = true;
363     } else {
364       if (aJustUpdated) {
365         if (myJustUpdated.find(theFeature) == myJustUpdated.end())
366           myJustUpdated.insert(theFeature);
367       } else {
368         aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
369       }
370     }
371     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
372     // execute feature if it must be updated
373     if (aJustUpdated) {
374       if ((std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
375           !theFeature->isPersistentResult()) && theFeature->isPreviewNeeded()) {
376         if (aFactory->validate(theFeature)) {
377           if (myIsAutomatic || !theFeature->isPersistentResult() /* execute quick, not persistent results */
378               || (isUpdated(theFeature) && 
379                theFeature == theFeature->document()->currentFeature(false))) // currently edited
380           {
381             if (aState == ModelAPI_StateDone || aState == ModelAPI_StateMustBeUpdated) {
382               executeFeature(theFeature);
383             }
384           } else { // must be updatet, but not updated yet
385             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
386             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
387             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
388             for (; aRIter != aResults.cend(); aRIter++) {
389               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
390               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
391             }
392           }
393         } else {
394           theFeature->eraseResults();
395           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
396         }
397       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
398         redisplayWithResults(theFeature, ModelAPI_StateNothing);
399       }
400     }
401   }
402 }
403
404 void Model_Update::executeFeature(FeaturePtr theFeature)
405 {
406   // execute in try-catch to avoid internal problems of the feature
407   ModelAPI_ExecState aState = ModelAPI_StateDone;
408   theFeature->data()->execState(ModelAPI_StateDone);
409   try {
410     theFeature->execute();
411     if (theFeature->data()->execState() != ModelAPI_StateDone) {
412       aState = ModelAPI_StateExecFailed;
413     } else {
414       aState = ModelAPI_StateDone;
415     }
416   } catch(...) {
417     aState = ModelAPI_StateExecFailed;
418     Events_Error::send(
419       "Feature " + theFeature->getKind() + " has failed during the execution");
420   }
421   if (aState != ModelAPI_StateDone) {
422     theFeature->eraseResults();
423   }
424   redisplayWithResults(theFeature, aState);
425 }
426
427 bool Model_Update::isUpdated(const ObjectPtr& theObj)
428 {
429   return myJustCreated.find(theObj) != myJustCreated.end() ||
430          myJustUpdated.find(theObj) != myJustUpdated.end();
431 }