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