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