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