Salome HOME
Resolve batch runtime errors on debian squeeze
[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_Validator.h>
21 #include <ModelAPI_CompositeFeature.h>
22 #include <ModelAPI_Session.h>
23 #include <Events_Loop.h>
24 #include <Events_LongOp.h>
25 #include <Events_Error.h>
26 #include <Config_PropManager.h>
27
28 using namespace std;
29
30 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
31
32 Model_Update::Model_Update()
33 {
34   Events_Loop* aLoop = Events_Loop::loop();
35   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
36   aLoop->registerListener(this, kChangedEvent);
37   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
38   aLoop->registerListener(this, kRebuildEvent);
39   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
40   aLoop->registerListener(this, kCreatedEvent);
41   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
42   aLoop->registerListener(this, kUpdatedEvent);
43   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
44   aLoop->registerListener(this, kMovedEvent);
45   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
46   aLoop->registerListener(this, kOpFinishEvent);
47   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
48   aLoop->registerListener(this, kOpAbortEvent);
49   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
50   aLoop->registerListener(this, kOpStartEvent);
51
52   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
53                                    Config_Prop::Bool, "false");
54   isAutomatic = Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
55 }
56
57 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
58 {
59   static Events_Loop* aLoop = Events_Loop::loop();
60   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
61   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
62   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
63   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
64   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
65   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
66   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
67   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
68   bool isAutomaticChanged = false;
69   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
70     isAutomatic = 
71       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
72   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
73     if (isAutomatic == false) {
74       isAutomaticChanged = true;
75       isAutomatic = true;
76     }
77   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
78     theMessage->eventID() == kMovedEvent) {
79     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
80         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
81     const std::set<ObjectPtr>& anObjs = aMsg->objects();
82     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
83     for(; anObjIter != anObjs.cend(); anObjIter++) {
84       myJustCreatedOrUpdated.insert(*anObjIter);
85       // TODO(mpv): check the next line. Came into dev 0.6.1 from BR_PYTHON_PLUGIN
86       // (*anObjIter)->data()->mustBeUpdated(true); // object must be updated because it was changed
87     }
88     if (theMessage->eventID() == kMovedEvent)
89       return; // this event is for solver update, not here
90   } else if (theMessage->eventID() == kOpStartEvent) {
91     myJustCreatedOrUpdated.clear();
92     return; // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
93   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
94     if (isAutomatic == false) { // Apply button now works as "Rebuild"
95       isAutomaticChanged = true;
96       isAutomatic = true;
97     }
98     // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
99     if (theMessage->eventID() == kOpFinishEvent) {
100       std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
101       for(aFIter = myJustCreatedOrUpdated.begin(); aFIter != myJustCreatedOrUpdated.end(); aFIter++)
102       {
103         FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
104         if (aF && aF->getKind() == "Extrusion") {
105           if (aF->selection("extrusion_face")) {
106             ResultPtr aSketchRes = aF->selection("extrusion_face")->context();
107             if (aSketchRes) {
108               static Events_ID HIDE_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE);
109               ModelAPI_EventCreator::get()->sendUpdated(aSketchRes, HIDE_DISP);
110             }
111           }
112         }
113       }
114     }
115   }
116
117   if (isExecuted)
118     return;  // nothing to do: it is executed now
119
120   //Events_LongOp::start(this);
121   isExecuted = true;
122   std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
123       std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
124   if (aMsg) myInitial = aMsg->objects();
125   else {
126     myInitial.clear();
127   }
128   // iterate all documents: features in Root first, then - subs
129   updateInDoc(ModelAPI_Session::get()->moduleDocument());
130
131   myUpdated.clear();
132   // flush to update display
133   static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
134   aLoop->flush(EVENT_DISP);
135   //Events_LongOp::end(this);
136   if (isAutomaticChanged) isAutomatic = false;
137
138   if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
139     myJustCreatedOrUpdated.clear();
140   }
141
142   isExecuted = false;
143 }
144
145 void Model_Update::updateInDoc(std::shared_ptr<ModelAPI_Document> theDoc)
146 {
147   // all features one by one
148   int aNbFeatures = theDoc->size(ModelAPI_Feature::group(), true);
149   for (int aFIndex = 0; aFIndex < aNbFeatures; aFIndex++) {
150     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
151         theDoc->object(ModelAPI_Feature::group(), aFIndex, true));
152     if (aFeature)
153       updateFeature(aFeature);
154   }
155   // all sub-documents one by one
156   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
157   if (aDoc) {
158     const std::set<std::string> aSubs = aDoc->subDocuments(true);
159     for(std::set<std::string>::iterator aSub = aSubs.begin(); aSub != aSubs.end(); aSub++) {
160       DocumentPtr aSubDoc = theDoc->subDocument(*aSub);
161       if (aSubDoc) {
162         updateInDoc(aSubDoc);
163       }
164     }
165   }
166 }
167
168 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
169 {
170   // make updated and redisplay all results
171   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
172   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
173   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
174   for (; aRIter != aResults.cend(); aRIter++) {
175     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
176     aRes->data()->execState(theState);
177     myUpdated[aRes] = true;
178     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
179   }
180   // to redisplay "presentable" feature (for ex. distance constraint)
181   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
182   theFeature->data()->execState(theState);
183 }
184
185 /// Updates the state by the referenced object: if something bad with it, set state for this one
186 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
187 {
188   if (theTarget) {
189     ModelAPI_ExecState aRefState = theTarget->data()->execState();
190     if (aRefState == ModelAPI_StateMustBeUpdated) {
191       return ModelAPI_StateMustBeUpdated;
192     } else if (aRefState != ModelAPI_StateDone) {
193       return ModelAPI_StateInvalidArgument;
194     }
195   }
196   return theCurrent;
197 }
198
199 bool Model_Update::updateFeature(FeaturePtr theFeature)
200 {
201   // check it is already processed
202   if (myUpdated.find(theFeature) != myUpdated.end())
203     return myUpdated[theFeature];
204   // check all features this feature depended on (recursive call of updateFeature)
205   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
206   bool aMustbeUpdated = myInitial.find(theFeature) != myInitial.end();
207   if (theFeature) {  // only real feature contains references to other objects
208     if (theFeature->data()->execState() != ModelAPI_StateDone)
209       aMustbeUpdated = true;
210
211     // composite feature must be executed after sub-features execution
212     CompositeFeaturePtr aComposite = 
213       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
214     if (aComposite) {
215       int aSubsNum = aComposite->numberOfSubs();
216       for(int a = 0; a < aSubsNum; a++) {
217         if (updateFeature(aComposite->subFeature(a)))
218           aMustbeUpdated = true;
219       }
220     }
221     ModelAPI_ExecState aState = ModelAPI_StateDone;
222     // check all references: if referenced objects are updated, this object also must be updated
223     // also check state of referenced objects: if they are not ready, inherit corresponding state
224     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
225     std::shared_ptr<Model_Data> aData = 
226       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
227     aData->referencesToObjects(aRefs);
228     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
229     for(; aRef != aRefs.end(); aRef++) {
230       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
231       for(; aRefObj != aRef->second.end(); aRefObj++) {
232         if (updateObject(*aRefObj)) {
233           aMustbeUpdated = true;
234         }
235         aState = stateByReference(*aRefObj, aState);
236       }
237     }
238
239     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
240     // execute feature if it must be updated
241     if (aMustbeUpdated) {
242       if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
243           !theFeature->isPersistentResult()) {
244         if (aFactory->validate(theFeature)) {
245           if (isAutomatic || 
246               (myJustCreatedOrUpdated.find(theFeature) != myJustCreatedOrUpdated.end()) ||
247               !theFeature->isPersistentResult() /* execute quick, not persistent results */) 
248           {
249             if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
250               //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
251               // before execution update the selection attributes if any
252               list<AttributePtr> aRefs = 
253                 theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
254               list<AttributePtr>::iterator aRefsIter = aRefs.begin();
255               for (; aRefsIter != aRefs.end(); aRefsIter++) {
256                 std::shared_ptr<ModelAPI_AttributeSelection> aSel =
257                   std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
258                 if (!aSel->update()) { // this must be done on execution since it may be long operation
259                   if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)))
260                     aState = ModelAPI_StateInvalidArgument;
261                 }
262               }
263               aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
264               for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
265                 std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
266                   std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
267                 for(int a = aSel->size() - 1; a >= 0; a--) {
268                   std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
269                     std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
270                   if (aSelAttr) {
271                     if (!aSelAttr->update()) {
272                       if (!aFactory->isNotObligatory(
273                           theFeature->getKind(), theFeature->data()->id(aSel)))
274                         aState = ModelAPI_StateInvalidArgument;
275                     }
276                   }
277                 }
278               }
279               // for sketch after update of plane (by update of selection attribute)
280               // but before execute, all sub-elements also must be updated (due to the plane changes)
281               if (aComposite) {
282                 int aSubsNum = aComposite->numberOfSubs();
283                 for(int a = 0; a < aSubsNum; a++) {
284                   FeaturePtr aSub = aComposite->subFeature(a);
285                   bool aWasModified = myUpdated[aSub];
286                   myUpdated.erase(myUpdated.find(aSub)); // erase to update for sure (plane may be changed)
287                   myInitial.insert(aSub);
288                   updateFeature(aSub);
289                   myUpdated[aSub] = aWasModified; // restore value
290                 }
291                 // re-execute after update: solver may update the previous values, so, shapes must be
292                 // updated
293                 for(int a = 0; a < aSubsNum; a++) {
294                   if (aComposite->subFeature(a) && aFactory->validate(aComposite->subFeature(a)))
295                     aComposite->subFeature(a)->execute();
296                 }
297               }
298             }
299
300             // execute in try-catch to avoid internal problems of the feature
301             if (aState == ModelAPI_StateDone) {
302               theFeature->data()->execState(ModelAPI_StateDone);
303               try {
304                 theFeature->execute();
305                 if (theFeature->data()->execState() != ModelAPI_StateDone) {
306                   aState = ModelAPI_StateExecFailed;
307                 }
308               } catch(...) {
309                 aState = ModelAPI_StateExecFailed;
310                 Events_Error::send(
311                   "Feature " + theFeature->getKind() + " has failed during the execution");
312               }
313             }
314             if (aState != ModelAPI_StateDone) {
315               theFeature->eraseResults();
316             }
317             redisplayWithResults(theFeature, aState);
318           } else { // must be updatet, but not updated yet
319             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
320             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
321             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
322             for (; aRIter != aResults.cend(); aRIter++) {
323               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
324               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
325             }
326           }
327         } else {
328           theFeature->eraseResults();
329           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
330         }
331       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
332         redisplayWithResults(theFeature, ModelAPI_StateNothing);
333       }
334     } else {
335       // returns also true is results were updated: for sketch that 
336       // refers to sub-features but results of sub-features were changed
337       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
338       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
339       for (; aRIter != aResults.cend(); aRIter++) {
340         if (myInitial.find(*aRIter) != myInitial.end()) {
341           aMustbeUpdated = true;
342           break;
343         }
344       }
345     }
346   }
347   myUpdated[theFeature] = aMustbeUpdated;
348   return aMustbeUpdated;
349 }
350
351 bool Model_Update::updateObject(std::shared_ptr<ModelAPI_Object> theObject, const bool theCyclic)
352 {
353   if (myUpdated.find(theObject) != myUpdated.end())
354     return myUpdated[theObject];  // already processed
355
356   /*
357   if (theCyclic) { // algorithm for update of all features by dependencies tree
358     if (!theObject)
359       return false;
360     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
361     if (aFeature) {  // for feature just call update Feature
362       return updateFeature(aFeature);
363     }
364     // check general object, possible just a result
365     if (myUpdated.find(theObject) != myUpdated.end())
366       return myUpdated[theObject];  // already processed
367     // check the feature of this object must be executed
368     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
369     if (aResult) {
370       FeaturePtr aResFeature = aResult->document()->feature(aResult);
371       if (aResFeature) {
372         return updateFeature(aResFeature);
373       }
374     }
375   }
376   */
377   return myInitial.find(theObject) != myInitial.end();
378 }