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