]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Update.cpp
Salome HOME
Make features history working. Optimization of features and results management and...
[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 <Model_Objects.h>
11 #include <ModelAPI_Feature.h>
12 #include <ModelAPI_Data.h>
13 #include <ModelAPI_Document.h>
14 #include <ModelAPI_Events.h>
15 #include <ModelAPI_AttributeReference.h>
16 #include <ModelAPI_AttributeRefList.h>
17 #include <ModelAPI_AttributeRefAttr.h>
18 #include <ModelAPI_AttributeSelection.h>
19 #include <ModelAPI_AttributeSelectionList.h>
20 #include <ModelAPI_Result.h>
21 #include <ModelAPI_ResultPart.h>
22 #include <ModelAPI_Validator.h>
23 #include <ModelAPI_CompositeFeature.h>
24 #include <ModelAPI_Session.h>
25 #include <ModelAPI_Tools.h>
26 #include <Events_Loop.h>
27 #include <Events_LongOp.h>
28 #include <Events_Error.h>
29 #include <Config_PropManager.h>
30
31 using namespace std;
32
33 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
34
35 Model_Update::Model_Update()
36 {
37   Events_Loop* aLoop = Events_Loop::loop();
38   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
39   aLoop->registerListener(this, kChangedEvent);
40   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
41   aLoop->registerListener(this, kRebuildEvent);
42   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
43   aLoop->registerListener(this, kCreatedEvent);
44   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
45   aLoop->registerListener(this, kUpdatedEvent);
46   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
47   aLoop->registerListener(this, kMovedEvent);
48   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
49   aLoop->registerListener(this, kOpFinishEvent);
50   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
51   aLoop->registerListener(this, kOpAbortEvent);
52   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
53   aLoop->registerListener(this, kOpStartEvent);
54
55   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
56                                    Config_Prop::Boolean, "false");
57   myIsAutomatic =
58     Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
59 }
60
61 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
62 {
63   static Events_Loop* aLoop = Events_Loop::loop();
64   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
65   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
66   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
67   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
68   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
69   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
70   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
71   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
72   bool isOperationChanged = false;
73   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
74     bool aPropVal =
75       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
76     if (aPropVal != myIsAutomatic) { // something is changed
77       myIsAutomatic = aPropVal;
78       if (myIsAutomatic) // higher level of automatization => to rebuild
79         processOperation(false);
80     }
81   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
82     processOperation(true);
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       // created objects are always must be up to date (python box feature)
91       // and updated not in internal uptation chain
92       if (theMessage->eventID() == kCreatedEvent) {
93         myJustCreated.insert(*anObjIter);
94       } else if (myJustCreated.find(*anObjIter) == myJustCreated.end()) { // moved and updated
95         myJustUpdated.insert(*anObjIter);
96       }
97     }
98      // this event is for solver update, not here, do not react immideately
99     if (!(theMessage->eventID() == kMovedEvent))
100       processOperation(false);
101   } else if (theMessage->eventID() == kOpStartEvent) {
102     // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
103     isOperationChanged = true;
104   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
105     processOperation(true);
106     isOperationChanged = true;
107   }
108   if (isOperationChanged) {
109     // remove all macros before clearing all created
110     std::set<ObjectPtr>::iterator aCreatedIter = myJustCreated.begin();
111     for(; aCreatedIter != myJustCreated.end(); aCreatedIter++) {
112       FeaturePtr aFeature = 
113         std::dynamic_pointer_cast<ModelAPI_Feature>(*aCreatedIter);
114       if (aFeature.get() && aFeature->isMacro()) {
115         aFeature->document()->removeFeature(aFeature);
116       }
117     }
118     myJustCreated.clear();
119     myJustUpdated.clear();
120   }
121 }
122
123 void Model_Update::processOperation(const bool theTotalUpdate)
124 {
125   // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
126   std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
127   for(aFIter = myJustCreated.begin(); aFIter != myJustCreated.end(); aFIter++)
128   {
129     FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
130     if (aF && aF->data().get() && aF->getKind() == "Extrusion") {
131       AttributeSelectionListPtr aBase = aF->selectionList("base");
132       if (aBase.get()) {
133         for(int a = aBase->size() - 1; a >= 0; a--) {
134           ResultPtr aSketchRes = aBase->value(a)->context();
135           if (aSketchRes) {
136             static Events_ID HIDE_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE);
137             ModelAPI_EventCreator::get()->sendUpdated(aSketchRes, HIDE_DISP);
138           }
139         }
140       }
141     }
142   }
143   // perform update of everything if needed
144   if (!myIsExecuted) {
145     myIsExecuted = true;
146
147     bool isAutomaticChanged = false;
148
149     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
150       isAutomaticChanged = true;
151       myIsAutomatic = true;
152     }
153
154     updateInDoc(ModelAPI_Session::get()->moduleDocument());
155
156     if (isAutomaticChanged) myIsAutomatic = false;
157     myIsExecuted = false;
158
159     // flush to update display
160     static Events_Loop* aLoop = Events_Loop::loop();
161     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
162     aLoop->flush(EVENT_DISP);
163   }
164 }
165
166 void Model_Update::updateInDoc(std::shared_ptr<ModelAPI_Document> theDoc)
167 {
168   std::set<FeaturePtr> alreadyProcessed; // features that are processed before others
169   // all features one by one
170   Model_Objects* anObjs = std::dynamic_pointer_cast<Model_Document>(theDoc)->objects();
171   if (!anObjs) return;
172   FeaturePtr aFeatureIter = anObjs->firstFeature();
173   for (; aFeatureIter.get(); aFeatureIter = anObjs->nextFeature(aFeatureIter)) {
174     if (aFeatureIter && alreadyProcessed.find(aFeatureIter) == alreadyProcessed.end()) {
175       // update selection and parameters attributes first, before sub-features analysis (sketch plane)
176       updateArguments(aFeatureIter);
177       // composite feature must be executed after sub-features execution
178       CompositeFeaturePtr aComposite = 
179         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeatureIter);
180       if (aComposite) {
181         // number of subs can be changed in execution: like fillet
182         for(int a = 0; a < aComposite->numberOfSubs(); a++) {
183           FeaturePtr aSub = aComposite->subFeature(a);
184           updateFeature(aSub);
185           alreadyProcessed.insert(aSub);
186         }
187       }
188
189       updateFeature(aFeatureIter);
190       // update the document results recursively
191       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeatureIter->results();
192       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
193       for (; aRIter != aResults.cend(); aRIter++) {
194         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
195         if (aPart.get()) {
196           if (!aPart->isDisabled() && aPart->isActivated()) {
197             updateInDoc(aPart->partDoc());
198           }
199         }
200       }
201     }
202   }
203 }
204
205 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
206 {
207   // make updated and redisplay all results
208   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
209   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
210   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
211   for (; aRIter != aResults.cend(); aRIter++) {
212     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
213     aRes->data()->execState(theState);
214     myJustUpdated.insert(aRes);
215     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
216   }
217   // to redisplay "presentable" feature (for ex. distance constraint)
218   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
219   theFeature->data()->execState(theState);
220 }
221
222 /// Updates the state by the referenced object: if something bad with it, set state for this one
223 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
224 {
225   if (theTarget) {
226     ModelAPI_ExecState aRefState = theTarget->data()->execState();
227     if (aRefState == ModelAPI_StateMustBeUpdated) {
228       return ModelAPI_StateMustBeUpdated;
229     } else if (aRefState != ModelAPI_StateDone) {
230       return ModelAPI_StateInvalidArgument;
231     }
232   }
233   return theCurrent;
234 }
235
236 void Model_Update::updateArguments(FeaturePtr theFeature) {
237   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
238
239   if (theFeature->isDisabled()) // nothing to do with disabled feature
240     return;
241   bool aJustUpdated = false;
242   ModelAPI_ExecState aState = ModelAPI_StateDone;
243   // check the parameters: values can be changed
244   std::list<AttributePtr> aDoubles = 
245     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId()); 
246   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
247   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
248     AttributeDoublePtr aDouble = 
249       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
250     if (aDouble.get() && !aDouble->text().empty()) {
251       double aNewVal;
252       if (ModelAPI_Tools::findVariable(aDouble->text(), aNewVal)) {
253         if (aNewVal != aDouble->value()) {
254           aDouble->setValue(aNewVal);
255           aJustUpdated = true;
256         }
257       } else {
258         aState = ModelAPI_StateInvalidArgument;
259       }
260     }
261   }
262
263   if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
264     //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
265     // before execution update the selection attributes if any
266     list<AttributePtr> aRefs = 
267       theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
268     list<AttributePtr>::iterator aRefsIter = aRefs.begin();
269     for (; aRefsIter != aRefs.end(); aRefsIter++) {
270       std::shared_ptr<ModelAPI_AttributeSelection> aSel =
271         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
272       if (!aSel->update()) { // this must be done on execution since it may be long operation
273         if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
274             aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
275           aState = ModelAPI_StateInvalidArgument;
276       }
277     }
278     aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
279     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
280       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
281         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
282       for(int a = aSel->size() - 1; a >= 0; a--) {
283         std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
284           std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
285         if (aSelAttr) {
286           if (!aSelAttr->update()) {
287             if (!aFactory->isNotObligatory(
288                   theFeature->getKind(), theFeature->data()->id(aSel)) &&
289                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
290               aState = ModelAPI_StateInvalidArgument;
291           }
292         }
293       }
294     }
295   }
296   if (aJustUpdated && myJustCreated.find(theFeature) == myJustCreated.end())
297   myJustUpdated.insert(theFeature);
298   if (aState != ModelAPI_StateDone)
299     theFeature->data()->execState(aState);
300 }
301
302 void Model_Update::updateFeature(FeaturePtr theFeature)
303 {
304   // check all features this feature depended on (recursive call of updateFeature)
305   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
306
307   if (theFeature->isDisabled()) // nothing to do with disabled feature
308     return;
309   bool aJustUpdated = false;
310
311   if (theFeature) {
312     if (theFeature->data()->execState() != ModelAPI_StateDone)
313       aJustUpdated = true;
314
315     ModelAPI_ExecState aState = ModelAPI_StateDone;
316
317     // check all references: if referenced objects are updated, this object also must be updated
318     // also check state of referenced objects: if they are not ready, inherit corresponding state
319     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
320     std::shared_ptr<Model_Data> aData = 
321       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
322     aData->referencesToObjects(aRefs);
323     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
324     for(; aRef != aRefs.end(); aRef++) {
325       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
326       for(; aRefObj != aRef->second.end(); aRefObj++) {
327         if (myJustCreated.find(*aRefObj) != myJustCreated.end() ||
328             myJustUpdated.find(*aRefObj) != myJustUpdated.end()) {
329           aJustUpdated = true;
330         }
331         aState = stateByReference(*aRefObj, aState);
332       }
333     }
334
335     // some arguments were changed, so, this feature must be updated
336     if (myJustCreated.find(theFeature) != myJustCreated.end()) {
337       aJustUpdated = true;
338     } else {
339       if (aJustUpdated) {
340         if (myJustUpdated.find(theFeature) == myJustUpdated.end())
341           myJustUpdated.insert(theFeature);
342       } else {
343         aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
344       }
345     }
346     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
347     // execute feature if it must be updated
348     if (aJustUpdated) {
349       if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
350           !theFeature->isPersistentResult()) {
351         if (aFactory->validate(theFeature)) {
352           if (myIsAutomatic || 
353               (myJustCreated.find(theFeature) != myJustCreated.end() ||
354               !theFeature->isPersistentResult() /* execute quick, not persistent results */))
355           {
356             // execute in try-catch to avoid internal problems of the feature
357             if (aState == ModelAPI_StateDone || aState == ModelAPI_StateMustBeUpdated) {
358               theFeature->data()->execState(ModelAPI_StateDone);
359               try {
360                 theFeature->execute();
361                 if (theFeature->data()->execState() != ModelAPI_StateDone) {
362                   aState = ModelAPI_StateExecFailed;
363                 } else {
364                   aState = ModelAPI_StateDone;
365                 }
366               } catch(...) {
367                 aState = ModelAPI_StateExecFailed;
368                 Events_Error::send(
369                   "Feature " + theFeature->getKind() + " has failed during the execution");
370               }
371             }
372             if (aState != ModelAPI_StateDone) {
373               theFeature->eraseResults();
374             }
375             redisplayWithResults(theFeature, aState);
376           } else { // must be updatet, but not updated yet
377             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
378             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
379             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
380             for (; aRIter != aResults.cend(); aRIter++) {
381               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
382               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
383             }
384           }
385         } else {
386           theFeature->eraseResults();
387           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
388         }
389       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
390         redisplayWithResults(theFeature, ModelAPI_StateNothing);
391       }
392     }
393   }
394 }