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