Salome HOME
Merge branch 'Dev_1.2.0' of newgeom:newgeom into Dev_1.2.0
[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 <GeomDataAPI_Point.h>
27 #include <GeomDataAPI_Point2D.h>
28 #include <Events_Loop.h>
29 #include <Events_LongOp.h>
30 #include <Events_Error.h>
31 #include <Config_PropManager.h>
32
33 using namespace std;
34
35 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
36
37 Model_Update::Model_Update()
38 {
39   Events_Loop* aLoop = Events_Loop::loop();
40   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
41   aLoop->registerListener(this, kChangedEvent);
42   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
43   aLoop->registerListener(this, kRebuildEvent);
44   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
45   aLoop->registerListener(this, kCreatedEvent);
46   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
47   aLoop->registerListener(this, kUpdatedEvent);
48   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
49   aLoop->registerListener(this, kMovedEvent);
50   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
51   aLoop->registerListener(this, kOpFinishEvent);
52   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
53   aLoop->registerListener(this, kOpAbortEvent);
54   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
55   aLoop->registerListener(this, kOpStartEvent);
56
57   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
58                                    Config_Prop::Boolean, "false");
59   myIsAutomatic =
60     Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
61 }
62
63 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
64 {
65   static Events_Loop* aLoop = Events_Loop::loop();
66   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
67   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
68   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
69   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
70   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
71   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
72   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
73   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
74   bool isOperationChanged = false;
75   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
76     bool aPropVal =
77       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
78     if (aPropVal != myIsAutomatic) { // something is changed
79       myIsAutomatic = aPropVal;
80       if (myIsAutomatic) // higher level of automatization => to rebuild
81         processOperation(false);
82     }
83   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
84     processOperation(true);
85   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
86              theMessage->eventID() == kMovedEvent) {
87     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
88         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
89     const std::set<ObjectPtr>& anObjs = aMsg->objects();
90     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
91     bool isOnlyResults = true; // check that only results were changed: only redisplay is needed
92     for(; anObjIter != anObjs.cend(); anObjIter++) {
93       if (!std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter).get()) {
94         isOnlyResults = false;
95       }
96       // created objects are always must be up to date (python box feature)
97       // and updated not in internal uptation chain
98       if (theMessage->eventID() == kCreatedEvent) {
99         myJustCreated.insert(*anObjIter);
100       } else if (myJustCreated.find(*anObjIter) == myJustCreated.end()) { // moved and updated
101         myJustUpdated.insert(*anObjIter);
102       }
103     }
104      // this event is for solver update, not here, do not react immideately
105     if (!isOnlyResults && !(theMessage->eventID() == kMovedEvent))
106       processOperation(false);
107   } else if (theMessage->eventID() == kOpStartEvent) {
108     // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
109     isOperationChanged = true;
110   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
111     processOperation(true, theMessage->eventID() == kOpFinishEvent);
112     isOperationChanged = true;
113   }
114   if (isOperationChanged) {
115     // remove all macros before clearing all created and execute all not-previewed
116     std::set<ObjectPtr>::iterator aCreatedIter = myJustCreated.begin();
117     std::set<ObjectPtr>::iterator anUpdatedIter = myJustUpdated.begin();
118     for(; aCreatedIter != myJustCreated.end() || anUpdatedIter != myJustUpdated.end();
119       aCreatedIter == myJustCreated.end() ? anUpdatedIter++ : aCreatedIter++) {
120       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*
121         (aCreatedIter == myJustCreated.end() ? anUpdatedIter : aCreatedIter));
122       if (aFeature.get()) {
123         // execute not-previewed feature on "apply"
124         if (!aFeature->isPreviewNeeded() && (myJustCreated.find(aFeature) != myJustCreated.end() ||
125           myJustUpdated.find(aFeature) != myJustUpdated.end())) {
126           static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
127           if (aFactory->validate(aFeature)) {
128             executeFeature(aFeature);
129           }
130         }
131         // remove macro on apply
132         if (aFeature->isMacro()) {
133           aFeature->document()->removeFeature(aFeature);
134         }
135       }
136     }
137     myJustCreated.clear();
138     myJustUpdated.clear();
139   }
140 }
141
142 void Model_Update::processOperation(const bool theTotalUpdate, const bool theFinish)
143 {
144   if (theFinish) {
145     // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
146     std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
147     for(aFIter = myJustCreated.begin(); aFIter != myJustCreated.end(); aFIter++)
148     {
149       FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
150       if (aF && aF->data()->isValid() && aF->getKind() == "Extrusion") {
151         AttributeSelectionListPtr aBase = aF->selectionList("base");
152         if (aBase.get()) {
153           for(int a = aBase->size() - 1; a >= 0; a--) {
154             ResultPtr aSketchRes = aBase->value(a)->context();
155             if (aSketchRes) {
156               aSketchRes->setDisplayed(false);
157             }
158           }
159         }
160       }
161     }
162   }
163   // perform update of everything if needed
164   if (!myIsExecuted) {
165     myIsExecuted = true;
166
167     bool isAutomaticChanged = false;
168
169     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
170       isAutomaticChanged = true;
171       myIsAutomatic = true;
172     }
173
174     updateInDoc(ModelAPI_Session::get()->moduleDocument());
175
176     if (isAutomaticChanged) myIsAutomatic = false;
177     myIsExecuted = false;
178
179     // flush to update display
180     static Events_Loop* aLoop = Events_Loop::loop();
181     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
182     aLoop->flush(EVENT_DISP);
183   }
184 }
185
186 void Model_Update::updateInDoc(std::shared_ptr<ModelAPI_Document> theDoc)
187 {
188   std::set<FeaturePtr> alreadyProcessed; // features that are processed before others
189   // all features one by one
190   Model_Objects* anObjs = std::dynamic_pointer_cast<Model_Document>(theDoc)->objects();
191   if (!anObjs) return;
192   FeaturePtr aFeatureIter = anObjs->firstFeature();
193   for (; aFeatureIter.get(); aFeatureIter = anObjs->nextFeature(aFeatureIter)) {
194     if (aFeatureIter && alreadyProcessed.find(aFeatureIter) == alreadyProcessed.end()) {
195       // update selection and parameters attributes first, before sub-features analysis (sketch plane)
196       updateArguments(aFeatureIter);
197       // composite feature must be executed after sub-features execution
198       CompositeFeaturePtr aComposite = 
199         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeatureIter);
200       if (aComposite) {
201         // number of subs can be changed in execution: like fillet
202         for(int a = 0; a < aComposite->numberOfSubs(); a++) {
203           FeaturePtr aSub = aComposite->subFeature(a);
204           updateArguments(aSub);
205           updateFeature(aSub);
206           alreadyProcessed.insert(aSub);
207         }
208       }
209
210       updateFeature(aFeatureIter);
211       // update the document results recursively
212       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeatureIter->results();
213       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
214       for (; aRIter != aResults.cend(); aRIter++) {
215         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
216         if (aPart.get()) {
217           if (!aPart->isDisabled() && aPart->isActivated()) {
218             updateInDoc(aPart->partDoc());
219           }
220         }
221       }
222     }
223   }
224 }
225
226 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
227 {
228   // make updated and redisplay all results
229   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
230   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
231   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
232   for (; aRIter != aResults.cend(); aRIter++) {
233     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
234     aRes->data()->execState(theState);
235     myJustUpdated.insert(aRes);
236     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
237   }
238   // to redisplay "presentable" feature (for ex. distance constraint)
239   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
240   theFeature->data()->execState(theState);
241 }
242
243 /// Updates the state by the referenced object: if something bad with it, set state for this one
244 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
245 {
246   if (theTarget) {
247     ModelAPI_ExecState aRefState = theTarget->data()->execState();
248     if (aRefState == ModelAPI_StateMustBeUpdated) {
249       return ModelAPI_StateMustBeUpdated;
250     } else if (aRefState != ModelAPI_StateDone) {
251       return ModelAPI_StateInvalidArgument;
252     }
253   }
254   return theCurrent;
255 }
256
257 void Model_Update::updateArguments(FeaturePtr theFeature) {
258   // perform this method also for disabled features: to make "not done" state for
259   // featuers referenced to the active and modified features
260
261   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
262
263   bool aJustUpdated = false;
264   ModelAPI_ExecState aState = theFeature->data()->execState();
265   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
266     aState = ModelAPI_StateMustBeUpdated;
267   // check the parameters state
268   // Double
269   std::list<AttributePtr> aDoubles =
270     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
271   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
272   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
273     AttributeDoublePtr aDouble =
274       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
275     if (aDouble.get() && !aDouble->text().empty()) {
276       if (aDouble->expressionInvalid()) {
277         aState = ModelAPI_StateInvalidArgument;
278       }
279     }
280   }
281   // Point
282   {
283     std::list<AttributePtr> anAttributes =
284       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
285     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
286     for(; anIter != anAttributes.end(); anIter++) {
287       AttributePointPtr aPointAttribute =
288         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
289       if (aPointAttribute.get()) {
290         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
291             (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
292             (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
293           aState = ModelAPI_StateInvalidArgument;
294       }
295     }
296   }
297   // Point2D
298   {
299     std::list<AttributePtr> anAttributes =
300       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
301     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
302     for(; anIter != anAttributes.end(); anIter++) {
303       AttributePoint2DPtr aPoint2DAttribute =
304         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
305       if (aPoint2DAttribute.get()) {
306         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
307             (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
308           aState = ModelAPI_StateInvalidArgument;
309       }
310     }
311   }
312
313   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
314     //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
315     // before execution update the selection attributes if any
316     list<AttributePtr> aRefs = 
317       theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
318     list<AttributePtr>::iterator aRefsIter = aRefs.begin();
319     for (; aRefsIter != aRefs.end(); aRefsIter++) {
320       std::shared_ptr<ModelAPI_AttributeSelection> aSel =
321         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
322       ObjectPtr aContext = aSel->context();
323       // update argument onlt if the referenced object is changed
324       if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
325         if (aState == ModelAPI_StateDone)
326           aState = ModelAPI_StateMustBeUpdated;
327         if (!aSel->update()) { // this must be done on execution since it may be long operation
328           if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
329               aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
330             aState = ModelAPI_StateInvalidArgument;
331         }
332       }
333     }
334     aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
335     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
336       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
337         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
338       for(int a = aSel->size() - 1; a >= 0; a--) {
339         std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
340           std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
341         if (aSelAttr) {
342           ObjectPtr aContext = aSelAttr->context();
343           // update argument onlt if the referenced object is changed
344           if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
345             if (aState == ModelAPI_StateDone)
346               aState = ModelAPI_StateMustBeUpdated;
347             if (!aSelAttr->update()) {
348               if (!aFactory->isNotObligatory(
349                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
350                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
351                 aState = ModelAPI_StateInvalidArgument;
352             }
353           }
354         }
355       }
356     }
357   //}
358   if (aJustUpdated && myJustCreated.find(theFeature) == myJustCreated.end())
359   myJustUpdated.insert(theFeature);
360   if (aState != ModelAPI_StateDone)
361     theFeature->data()->execState(aState);
362 }
363
364 void Model_Update::updateFeature(FeaturePtr theFeature)
365 {
366   // check all features this feature depended on (recursive call of updateFeature)
367   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
368
369   if (theFeature->isDisabled() ||  // nothing to do with disabled feature
370       theFeature->data()->execState() == ModelAPI_StateInvalidArgument)
371     return;
372   bool aJustUpdated = false;
373
374   if (theFeature) {
375     if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
376       aJustUpdated = true;
377
378     ModelAPI_ExecState aState = ModelAPI_StateDone;
379
380     // check all references: if referenced objects are updated, this object also must be updated
381     // also check state of referenced objects: if they are not ready, inherit corresponding state
382     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
383     std::shared_ptr<Model_Data> aData = 
384       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
385     aData->referencesToObjects(aRefs);
386     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
387     for(; aRef != aRefs.end(); aRef++) {
388       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
389       for(; aRefObj != aRef->second.end(); aRefObj++) {
390         if (myJustCreated.find(*aRefObj) != myJustCreated.end() ||
391             myJustUpdated.find(*aRefObj) != myJustUpdated.end()) {
392           aJustUpdated = true;
393         }
394         aState = stateByReference(*aRefObj, aState);
395       }
396     }
397
398     // some arguments were changed, so, this feature must be updated
399     if (myJustCreated.find(theFeature) != myJustCreated.end()) {
400       aJustUpdated = true;
401     } else {
402       if (aJustUpdated) {
403         if (myJustUpdated.find(theFeature) == myJustUpdated.end())
404           myJustUpdated.insert(theFeature);
405       } else {
406         aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
407       }
408     }
409     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
410     // execute feature if it must be updated
411     if (aJustUpdated) {
412       if (theFeature->isPreviewNeeded()) {
413         if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
414             !theFeature->isPersistentResult()) {
415           if (aFactory->validate(theFeature)) {
416             FeaturePtr aCurrent = theFeature->document()->currentFeature(false);
417             if (myIsAutomatic || !theFeature->isPersistentResult() /* execute quick, not persistent results */
418                 || (isUpdated(theFeature) && 
419                      (theFeature == aCurrent || 
420                       (aCurrent.get() && aCurrent->isMacro())))) // currently edited
421             {
422               if (aState == ModelAPI_StateDone || aState == ModelAPI_StateMustBeUpdated) {
423                 executeFeature(theFeature);
424               }
425             } else { // must be updatet, but not updated yet
426               theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
427               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
428               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
429               for (; aRIter != aResults.cend(); aRIter++) {
430                 std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
431                 aRes->data()->execState(ModelAPI_StateMustBeUpdated);
432               }
433             }
434           } else {
435             theFeature->eraseResults();
436             redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
437           }
438         } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
439           redisplayWithResults(theFeature, ModelAPI_StateNothing);
440         }
441       } else { // preview is not needed => make state Done
442         if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
443           theFeature->data()->execState(ModelAPI_StateDone);
444       }
445     }
446   }
447 }
448
449 void Model_Update::executeFeature(FeaturePtr theFeature)
450 {
451   // execute in try-catch to avoid internal problems of the feature
452   ModelAPI_ExecState aState = ModelAPI_StateDone;
453   theFeature->data()->execState(ModelAPI_StateDone);
454   try {
455     theFeature->execute();
456     if (theFeature->data()->execState() != ModelAPI_StateDone) {
457       aState = ModelAPI_StateExecFailed;
458     } else {
459       aState = ModelAPI_StateDone;
460     }
461   } catch(...) {
462     aState = ModelAPI_StateExecFailed;
463     Events_Error::send(
464       "Feature " + theFeature->getKind() + " has failed during the execution");
465   }
466   if (aState != ModelAPI_StateDone) {
467     theFeature->eraseResults();
468   }
469   redisplayWithResults(theFeature, aState);
470 }
471
472 bool Model_Update::isUpdated(const ObjectPtr& theObj)
473 {
474   return myJustCreated.find(theObj) != myJustCreated.end() ||
475          myJustUpdated.find(theObj) != myJustUpdated.end();
476 }