Salome HOME
2c32f0467ca08193e9a33f916d8e0796e3e42522
[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::type());
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                       aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
261                     aState = ModelAPI_StateInvalidArgument;
262                 }
263               }
264               aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::type());
265               for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
266                 std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
267                   std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
268                 for(int a = aSel->size() - 1; a >= 0; a--) {
269                   std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
270                     std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
271                   if (aSelAttr) {
272                     if (!aSelAttr->update()) {
273                       if (!aFactory->isNotObligatory(
274                             theFeature->getKind(), theFeature->data()->id(aSel)) &&
275                           aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
276                         aState = ModelAPI_StateInvalidArgument;
277                     }
278                   }
279                 }
280               }
281               // for sketch after update of plane (by update of selection attribute)
282               // but before execute, all sub-elements also must be updated (due to the plane changes)
283               if (aComposite) {
284                 int aSubsNum = aComposite->numberOfSubs();
285                 for(int a = 0; a < aSubsNum; a++) {
286                   FeaturePtr aSub = aComposite->subFeature(a);
287                   bool aWasModified = myUpdated[aSub];
288                   myUpdated.erase(myUpdated.find(aSub)); // erase to update for sure (plane may be changed)
289                   myInitial.insert(aSub);
290                   updateFeature(aSub);
291                   myUpdated[aSub] = aWasModified; // restore value
292                 }
293                 // re-execute after update: solver may update the previous values, so, shapes must be
294                 // updated
295                 for(int a = 0; a < aSubsNum; a++) {
296                   if (aComposite->subFeature(a) && aFactory->validate(aComposite->subFeature(a)))
297                     aComposite->subFeature(a)->execute();
298                 }
299               }
300             }
301
302             // execute in try-catch to avoid internal problems of the feature
303             if (aState == ModelAPI_StateDone) {
304               theFeature->data()->execState(ModelAPI_StateDone);
305               try {
306                 theFeature->execute();
307                 if (theFeature->data()->execState() != ModelAPI_StateDone) {
308                   aState = ModelAPI_StateExecFailed;
309                 }
310               } catch(...) {
311                 aState = ModelAPI_StateExecFailed;
312                 Events_Error::send(
313                   "Feature " + theFeature->getKind() + " has failed during the execution");
314               }
315             }
316             if (aState != ModelAPI_StateDone) {
317               theFeature->eraseResults();
318             }
319             redisplayWithResults(theFeature, aState);
320           } else { // must be updatet, but not updated yet
321             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
322             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
323             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
324             for (; aRIter != aResults.cend(); aRIter++) {
325               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
326               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
327             }
328           }
329         } else {
330           theFeature->eraseResults();
331           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
332         }
333       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
334         redisplayWithResults(theFeature, ModelAPI_StateNothing);
335       }
336     } else {
337       // returns also true is results were updated: for sketch that 
338       // refers to sub-features but results of sub-features were changed
339       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
340       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
341       for (; aRIter != aResults.cend(); aRIter++) {
342         if (myInitial.find(*aRIter) != myInitial.end()) {
343           aMustbeUpdated = true;
344           break;
345         }
346       }
347     }
348   }
349   myUpdated[theFeature] = aMustbeUpdated;
350   return aMustbeUpdated;
351 }
352
353 bool Model_Update::updateObject(std::shared_ptr<ModelAPI_Object> theObject, const bool theCyclic)
354 {
355   if (myUpdated.find(theObject) != myUpdated.end())
356     return myUpdated[theObject];  // already processed
357
358   /*
359   if (theCyclic) { // algorithm for update of all features by dependencies tree
360     if (!theObject)
361       return false;
362     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
363     if (aFeature) {  // for feature just call update Feature
364       return updateFeature(aFeature);
365     }
366     // check general object, possible just a result
367     if (myUpdated.find(theObject) != myUpdated.end())
368       return myUpdated[theObject];  // already processed
369     // check the feature of this object must be executed
370     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
371     if (aResult) {
372       FeaturePtr aResFeature = aResult->document()->feature(aResult);
373       if (aResFeature) {
374         return updateFeature(aResFeature);
375       }
376     }
377   }
378   */
379   return myInitial.find(theObject) != myInitial.end();
380 }