Salome HOME
Issue #424: Mirror is done wrong
[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->getKind() == "Extrusion") {
116           AttributeSelectionListPtr aBase = aF->selectionList("base");
117           if (aBase.get()) {
118             for(int a = aBase->size() - 1; a >= 0; a--) {
119               ResultPtr aSketchRes = aBase->value(a)->context();
120               if (aSketchRes) {
121                 static Events_ID HIDE_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE);
122                 ModelAPI_EventCreator::get()->sendUpdated(aSketchRes, HIDE_DISP);
123               }
124             }
125           }
126         }
127       }
128     }
129   }
130
131   if (myIsExecuted)
132     return;  // nothing to do: it is executed now
133
134   //Events_LongOp::start(this);
135   myIsExecuted = true;
136   // iterate all documents: features in Root first, then - subs
137   updateInDoc(ModelAPI_Session::get()->moduleDocument());
138
139   myUpdated.clear();
140   // flush to update display
141   static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
142   aLoop->flush(EVENT_DISP);
143   //Events_LongOp::end(this);
144   if (isAutomaticChanged) myIsAutomatic = false;
145
146   if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
147     myJustCreatedOrUpdated.clear();
148     myInitial.clear();
149   }
150
151   myIsExecuted = false;
152 }
153
154 void Model_Update::updateInDoc(std::shared_ptr<ModelAPI_Document> theDoc)
155 {
156   // all features one by one
157   int aNbFeatures = theDoc->size(ModelAPI_Feature::group(), true);
158   for (int aFIndex = 0; aFIndex < aNbFeatures; aFIndex++) {
159     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
160         theDoc->object(ModelAPI_Feature::group(), aFIndex, true));
161     if (aFeature)
162       updateFeature(aFeature);
163   }
164   // all sub-documents one by one
165   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
166   if (aDoc) {
167     const std::set<std::string> aSubs = aDoc->subDocuments(true);
168     for(std::set<std::string>::iterator aSub = aSubs.begin(); aSub != aSubs.end(); aSub++) {
169       DocumentPtr aSubDoc = theDoc->subDocument(*aSub);
170       if (aSubDoc) {
171         updateInDoc(aSubDoc);
172       }
173     }
174   }
175 }
176
177 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
178 {
179   // make updated and redisplay all results
180   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
181   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
182   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
183   for (; aRIter != aResults.cend(); aRIter++) {
184     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
185     aRes->data()->execState(theState);
186     myUpdated[aRes] = true;
187     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
188   }
189   // to redisplay "presentable" feature (for ex. distance constraint)
190   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
191   theFeature->data()->execState(theState);
192 }
193
194 /// Updates the state by the referenced object: if something bad with it, set state for this one
195 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
196 {
197   if (theTarget) {
198     ModelAPI_ExecState aRefState = theTarget->data()->execState();
199     if (aRefState == ModelAPI_StateMustBeUpdated) {
200       return ModelAPI_StateMustBeUpdated;
201     } else if (aRefState != ModelAPI_StateDone) {
202       return ModelAPI_StateInvalidArgument;
203     }
204   }
205   return theCurrent;
206 }
207
208 bool Model_Update::updateFeature(FeaturePtr theFeature)
209 {
210   // check it is already processed
211   if (myUpdated.find(theFeature) != myUpdated.end())
212     return myUpdated[theFeature];
213   // check all features this feature depended on (recursive call of updateFeature)
214   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
215   bool aMustbeUpdated = myInitial.find(theFeature) != myInitial.end();
216   if (theFeature) {  // only real feature contains references to other objects
217     if (theFeature->data()->execState() != ModelAPI_StateDone)
218       aMustbeUpdated = true;
219
220     // composite feature must be executed after sub-features execution
221     CompositeFeaturePtr aComposite = 
222       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
223     if (aComposite) {
224       int aSubsNum = aComposite->numberOfSubs();
225       for(int a = 0; a < aSubsNum; a++) {
226         if (updateFeature(aComposite->subFeature(a)))
227           aMustbeUpdated = true;
228       }
229     }
230     ModelAPI_ExecState aState = ModelAPI_StateDone;
231     // check all references: if referenced objects are updated, this object also must be updated
232     // also check state of referenced objects: if they are not ready, inherit corresponding state
233     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
234     std::shared_ptr<Model_Data> aData = 
235       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
236     aData->referencesToObjects(aRefs);
237     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
238     for(; aRef != aRefs.end(); aRef++) {
239       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
240       for(; aRefObj != aRef->second.end(); aRefObj++) {
241         if (updateObject(*aRefObj)) {
242           aMustbeUpdated = true;
243         }
244         aState = stateByReference(*aRefObj, aState);
245       }
246     }
247
248     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
249     // execute feature if it must be updated
250     if (aMustbeUpdated) {
251       if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
252           !theFeature->isPersistentResult()) {
253         if (aFactory->validate(theFeature)) {
254           if (myIsAutomatic || 
255               (myJustCreatedOrUpdated.find(theFeature) != myJustCreatedOrUpdated.end()) ||
256               !theFeature->isPersistentResult() /* execute quick, not persistent results */) 
257           {
258             if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
259               //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
260               // before execution update the selection attributes if any
261               list<AttributePtr> aRefs = 
262                 theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
263               list<AttributePtr>::iterator aRefsIter = aRefs.begin();
264               for (; aRefsIter != aRefs.end(); aRefsIter++) {
265                 std::shared_ptr<ModelAPI_AttributeSelection> aSel =
266                   std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
267                 if (!aSel->update()) { // this must be done on execution since it may be long operation
268                   if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
269                       aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
270                     aState = ModelAPI_StateInvalidArgument;
271                 }
272               }
273               aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
274               for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
275                 std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
276                   std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
277                 for(int a = aSel->size() - 1; a >= 0; a--) {
278                   std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
279                     std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
280                   if (aSelAttr) {
281                     if (!aSelAttr->update()) {
282                       if (!aFactory->isNotObligatory(
283                             theFeature->getKind(), theFeature->data()->id(aSel)) &&
284                           aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
285                         aState = ModelAPI_StateInvalidArgument;
286                     }
287                   }
288                 }
289               }
290               // for sketch after update of plane (by update of selection attribute)
291               // but before execute, all sub-elements also must be updated (due to the plane changes)
292               if (aComposite) {
293                 int aSubsNum = aComposite->numberOfSubs();
294                 for(int a = 0; a < aSubsNum; a++) {
295                   FeaturePtr aSub = aComposite->subFeature(a);
296                   bool aWasModified = myUpdated[aSub];
297                   myUpdated.erase(myUpdated.find(aSub)); // erase to update for sure (plane may be changed)
298                   myInitial.insert(aSub);
299                   updateFeature(aSub);
300                   myUpdated[aSub] = aWasModified; // restore value
301                 }
302                 // re-execute after update: solver may update the previous values, so, shapes must be
303                 // updated
304                 for(int a = 0; a < aSubsNum; a++) {
305                   if (aComposite->subFeature(a) && aFactory->validate(aComposite->subFeature(a)))
306                     aComposite->subFeature(a)->execute();
307                 }
308               }
309             }
310
311             // execute in try-catch to avoid internal problems of the feature
312             if (aState == ModelAPI_StateDone) {
313               theFeature->data()->execState(ModelAPI_StateDone);
314               try {
315                 theFeature->execute();
316                 if (theFeature->data()->execState() != ModelAPI_StateDone) {
317                   aState = ModelAPI_StateExecFailed;
318                 }
319               } catch(...) {
320                 aState = ModelAPI_StateExecFailed;
321                 Events_Error::send(
322                   "Feature " + theFeature->getKind() + " has failed during the execution");
323               }
324             }
325             if (aState != ModelAPI_StateDone) {
326               theFeature->eraseResults();
327             }
328             redisplayWithResults(theFeature, aState);
329           } else { // must be updatet, but not updated yet
330             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
331             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
332             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
333             for (; aRIter != aResults.cend(); aRIter++) {
334               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
335               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
336             }
337           }
338         } else {
339           theFeature->eraseResults();
340           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
341         }
342       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
343         redisplayWithResults(theFeature, ModelAPI_StateNothing);
344       }
345     } else {
346       // returns also true is results were updated: for sketch that 
347       // refers to sub-features but results of sub-features were changed
348       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
349       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
350       for (; aRIter != aResults.cend(); aRIter++) {
351         if (myInitial.find(*aRIter) != myInitial.end()) {
352           aMustbeUpdated = true;
353           break;
354         }
355       }
356     }
357   }
358   myUpdated[theFeature] = aMustbeUpdated;
359   return aMustbeUpdated;
360 }
361
362 bool Model_Update::updateObject(std::shared_ptr<ModelAPI_Object> theObject, const bool theCyclic)
363 {
364   if (myUpdated.find(theObject) != myUpdated.end())
365     return myUpdated[theObject];  // already processed
366
367   /*
368   if (theCyclic) { // algorithm for update of all features by dependencies tree
369     if (!theObject)
370       return false;
371     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
372     if (aFeature) {  // for feature just call update Feature
373       return updateFeature(aFeature);
374     }
375     // check general object, possible just a result
376     if (myUpdated.find(theObject) != myUpdated.end())
377       return myUpdated[theObject];  // already processed
378     // check the feature of this object must be executed
379     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
380     if (aResult) {
381       FeaturePtr aResFeature = aResult->document()->feature(aResult);
382       if (aResFeature) {
383         return updateFeature(aResFeature);
384       }
385     }
386   }
387   */
388   return myInitial.find(theObject) != myInitial.end();
389 }