Salome HOME
Make correct management of concealed on history position changes (on edit, manual...
[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 = myWaitForFinish.begin(); aFIter != myWaitForFinish.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     myWaitForFinish.clear();
167   }
168   // perform update of everything if needed
169   if (!myIsExecuted) {
170     myIsExecuted = true;
171
172     bool isAutomaticChanged = false;
173
174     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
175       isAutomaticChanged = true;
176       myIsAutomatic = true;
177     }
178
179     // iterate all features in the root document to update each
180     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
181     Model_Objects* anObjs = std::dynamic_pointer_cast<Model_Document>(aRootDoc)->objects();
182     if (!anObjs) return;
183     FeaturePtr aFeatureIter = anObjs->firstFeature();
184     std::set<FeaturePtr> aProcessedFeatures; // to avoid processing twice
185     for (; aFeatureIter.get(); aFeatureIter = anObjs->nextFeature(aFeatureIter)) {
186       updateFeature(aFeatureIter, aProcessedFeatures);
187     }
188
189     if (isAutomaticChanged) myIsAutomatic = false;
190     myIsExecuted = false;
191
192     // flush to update display
193     static Events_Loop* aLoop = Events_Loop::loop();
194     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
195     aLoop->flush(EVENT_DISP);
196   }
197 }
198
199 void Model_Update::updateFeature(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
200 {
201   // check all features this feature depended on (recursive call of updateFeature)
202   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
203
204   if (theProcessed.find(theFeature) != theProcessed.end())
205     return;
206   theProcessed.insert(theFeature);
207   if (theFeature->isDisabled())
208     return;
209
210   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
211   // If automatice update is not needed and feature attributes were not updated right now,
212   // do not execute it and do not update arguments.
213   if (!myIsAutomatic && myJustUpdated.find(theFeature) == myJustUpdated.end() && !aCompos.get()) {
214     // execute will be performed later, but some features may have not-result 
215     // presentations, so call update for them (like coincidence in the sketcher)
216     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
217     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
218     return;
219   }
220
221   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
222   updateArguments(theFeature);
223
224   // composite feature must be executed after sub-features execution
225   if (aCompos) {
226     // number of subs can be changed in execution: like fillet
227     for(int a = 0; a < aCompos->numberOfSubs(); a++) {
228       FeaturePtr aSub = aCompos->subFeature(a);
229       updateFeature(aSub, theProcessed);
230     }
231   }
232   // this checking must be after the composite feature sub-elements processing:
233   // composite feature status may depend on it's subelements
234   if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
235     theFeature->eraseResults();
236     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
237     return;
238   }
239
240   bool aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
241
242   if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
243     aJustUpdated = true;
244
245   // execute feature if it must be updated
246   if (theFeature->isPreviewNeeded()) {
247     if ((myIsAutomatic || aJustUpdated) &&
248       std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures()) {
249         ModelAPI_ExecState aState = theFeature->data()->execState();
250         if (aFactory->validate(theFeature)) {
251           executeFeature(theFeature);
252         } else {
253           theFeature->eraseResults();
254           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
255         }
256     }
257   } else { // preview is not needed => make state Done
258     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
259       theFeature->data()->execState(ModelAPI_StateDone);
260     }
261   }
262 }
263
264 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
265 {
266   // make updated and redisplay all results
267   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
268   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
269   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
270   for (; aRIter != aResults.cend(); aRIter++) {
271     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
272     aRes->data()->execState(theState);
273     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
274       aRes->data()->setUpdateID(theFeature->data()->updateID());
275     }
276     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
277   }
278   // to redisplay "presentable" feature (for ex. distance constraint)
279   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
280   theFeature->data()->execState(theState);
281 }
282
283 /// Updates the state by the referenced object: if something bad with it, set state for this one
284 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
285 {
286   if (theTarget) {
287     ModelAPI_ExecState aRefState = theTarget->data()->execState();
288     if (aRefState == ModelAPI_StateMustBeUpdated) {
289       if (theCurrent == ModelAPI_StateDone)
290         return ModelAPI_StateMustBeUpdated;
291     } else if (aRefState != ModelAPI_StateDone) {
292       return ModelAPI_StateInvalidArgument;
293     }
294   }
295   return theCurrent;
296 }
297
298 void Model_Update::updateArguments(FeaturePtr theFeature) {
299   // perform this method also for disabled features: to make "not done" state for
300   // featuers referenced to the active and modified features
301
302   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
303
304   ModelAPI_ExecState aState = theFeature->data()->execState();
305   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
306     aState = ModelAPI_StateMustBeUpdated;
307   // check the parameters state
308   // Double
309   std::list<AttributePtr> aDoubles =
310     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
311   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
312   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
313     AttributeDoublePtr aDouble =
314       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
315     if (aDouble.get() && !aDouble->text().empty()) {
316       if (myIsParamUpdated) {
317         ModelAPI_AttributeEvalMessage::send(aDouble, this);
318       }
319       if (aDouble->expressionInvalid()) {
320         aState = ModelAPI_StateInvalidArgument;
321       }
322     }
323   }
324   // Point
325   {
326     std::list<AttributePtr> anAttributes =
327       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
328     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
329     for(; anIter != anAttributes.end(); anIter++) {
330       AttributePointPtr aPointAttribute =
331         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
332       if (aPointAttribute.get()) {
333         if (myIsParamUpdated) {
334           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
335         }
336         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
337           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
338           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
339           aState = ModelAPI_StateInvalidArgument;
340       }
341     }
342   }
343   // Point2D
344   {
345     std::list<AttributePtr> anAttributes =
346       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
347     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
348     for(; anIter != anAttributes.end(); anIter++) {
349       AttributePoint2DPtr aPoint2DAttribute =
350         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
351       if (aPoint2DAttribute.get()) {
352         if (myIsParamUpdated) {
353           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
354         }
355         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
356           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
357           aState = ModelAPI_StateInvalidArgument;
358       }
359     }
360   }
361
362   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
363   //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
364   // before execution update the selection attributes if any
365   list<AttributePtr> aRefs = 
366     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
367   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
368   for (; aRefsIter != aRefs.end(); aRefsIter++) {
369     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
370       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
371     ObjectPtr aContext = aSel->context();
372     // update argument onlt if the referenced object is changed
373     if (aContext.get() && !aContext->isDisabled() && 
374       aContext->data()->updateID() > theFeature->data()->updateID()) {
375         if (aState == ModelAPI_StateDone)
376           aState = ModelAPI_StateMustBeUpdated;
377         if (!aSel->update()) { // this must be done on execution since it may be long operation
378           if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
379             aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
380             aState = ModelAPI_StateInvalidArgument;
381         }
382     }
383   }
384   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
385   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
386     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
387       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
388     for(int a = aSel->size() - 1; a >= 0; a--) {
389       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
390         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
391       if (aSelAttr) {
392         ObjectPtr aContext = aSelAttr->context();
393         // update argument onlt if the referenced object is changed
394         if (aContext.get() && !aContext->isDisabled() &&
395           aContext->data()->updateID() > theFeature->data()->updateID()) {
396             if (aState == ModelAPI_StateDone)
397               aState = ModelAPI_StateMustBeUpdated;
398             if (!aSelAttr->update()) {
399               if (!aFactory->isNotObligatory(
400                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
401                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
402                 aState = ModelAPI_StateInvalidArgument;
403             }
404         }
405       }
406     }
407   }
408   // check all references: if referenced objects are updated, this object also must be updated
409   // also check state of referenced objects: if they are not ready, inherit corresponding state
410   std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefsObj;
411   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
412   aData->referencesToObjects(aRefsObj);
413   std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefsObj.begin();
414   for(; aRef != aRefsObj.end(); aRef++) {
415     std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
416     for(; aRefObj != aRef->second.end(); aRefObj++) {
417       // if reference is null, it may mean that this reference is to other document
418       // the does not supported by RefList: parameters may be recomputed
419       if (!aRefObj->get() && theFeature->firstResult().get() && 
420                theFeature->firstResult()->groupName() == ModelAPI_ResultParameter::group()) {
421           if (aState == ModelAPI_StateDone)
422             aState = ModelAPI_StateMustBeUpdated;
423       } else if (myJustUpdated.find(*aRefObj) != myJustUpdated.end() || 
424              (aRefObj->get() && (*aRefObj)->data()->updateID() > theFeature->data()->updateID())) {
425           if (aState == ModelAPI_StateDone)
426             aState = ModelAPI_StateMustBeUpdated;
427       }
428       aState = stateByReference(*aRefObj, aState);
429     }
430   }
431
432   if (aState != ModelAPI_StateDone)
433     theFeature->data()->execState(aState);
434 }
435
436 void Model_Update::executeFeature(FeaturePtr theFeature)
437 {
438   // execute in try-catch to avoid internal problems of the feature
439   ModelAPI_ExecState aState = ModelAPI_StateDone;
440   theFeature->data()->execState(ModelAPI_StateDone);
441   try {
442     theFeature->execute();
443     myJustUpdated.erase(theFeature);
444     if (theFeature->data()->execState() != ModelAPI_StateDone) {
445       aState = ModelAPI_StateExecFailed;
446     } else {
447       aState = ModelAPI_StateDone;
448       myWaitForFinish.insert(theFeature);
449     }
450   } catch(...) {
451     aState = ModelAPI_StateExecFailed;
452     Events_Error::send(
453       "Feature " + theFeature->getKind() + " has failed during the execution");
454   }
455   if (aState != ModelAPI_StateDone) {
456     theFeature->eraseResults();
457   }
458   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
459   redisplayWithResults(theFeature, aState);
460 }