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