]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Update.cpp
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->data()->isValid()) // this may be on close of the document
195       continue;
196     if (aFeatureIter && alreadyProcessed.find(aFeatureIter) == alreadyProcessed.end()) {
197       // update selection and parameters attributes first, before sub-features analysis (sketch plane)
198       updateArguments(aFeatureIter);
199       // composite feature must be executed after sub-features execution
200       CompositeFeaturePtr aComposite = 
201         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeatureIter);
202       if (aComposite) {
203         // number of subs can be changed in execution: like fillet
204         for(int a = 0; a < aComposite->numberOfSubs(); a++) {
205           FeaturePtr aSub = aComposite->subFeature(a);
206           updateArguments(aSub);
207           updateFeature(aSub);
208           alreadyProcessed.insert(aSub);
209         }
210       }
211
212       updateFeature(aFeatureIter);
213       // update the document results recursively
214       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeatureIter->results();
215       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
216       for (; aRIter != aResults.cend(); aRIter++) {
217         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
218         if (aPart.get()) {
219           if (!aPart->isDisabled() && aPart->isActivated()) {
220             updateInDoc(aPart->partDoc());
221           }
222         }
223       }
224     }
225   }
226 }
227
228 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
229 {
230   // make updated and redisplay all results
231   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
232   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
233   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
234   for (; aRIter != aResults.cend(); aRIter++) {
235     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
236     aRes->data()->execState(theState);
237     myJustUpdated.insert(aRes);
238     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
239   }
240   // to redisplay "presentable" feature (for ex. distance constraint)
241   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
242   theFeature->data()->execState(theState);
243 }
244
245 /// Updates the state by the referenced object: if something bad with it, set state for this one
246 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
247 {
248   if (theTarget) {
249     ModelAPI_ExecState aRefState = theTarget->data()->execState();
250     if (aRefState == ModelAPI_StateMustBeUpdated) {
251       return ModelAPI_StateMustBeUpdated;
252     } else if (aRefState != ModelAPI_StateDone) {
253       return ModelAPI_StateInvalidArgument;
254     }
255   }
256   return theCurrent;
257 }
258
259 void Model_Update::updateArguments(FeaturePtr theFeature) {
260   // perform this method also for disabled features: to make "not done" state for
261   // featuers referenced to the active and modified features
262
263   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
264
265   bool aJustUpdated = false;
266   ModelAPI_ExecState aState = theFeature->data()->execState();
267   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
268     aState = ModelAPI_StateMustBeUpdated;
269   // check the parameters state
270   // Double
271   std::list<AttributePtr> aDoubles =
272     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
273   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
274   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
275     AttributeDoublePtr aDouble =
276       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
277     if (aDouble.get() && !aDouble->text().empty()) {
278       if (aDouble->expressionInvalid()) {
279         aState = ModelAPI_StateInvalidArgument;
280       }
281     }
282   }
283   // Point
284   {
285     std::list<AttributePtr> anAttributes =
286       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
287     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
288     for(; anIter != anAttributes.end(); anIter++) {
289       AttributePointPtr aPointAttribute =
290         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
291       if (aPointAttribute.get()) {
292         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
293             (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
294             (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
295           aState = ModelAPI_StateInvalidArgument;
296       }
297     }
298   }
299   // Point2D
300   {
301     std::list<AttributePtr> anAttributes =
302       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
303     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
304     for(; anIter != anAttributes.end(); anIter++) {
305       AttributePoint2DPtr aPoint2DAttribute =
306         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
307       if (aPoint2DAttribute.get()) {
308         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
309             (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
310           aState = ModelAPI_StateInvalidArgument;
311       }
312     }
313   }
314
315   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
316     //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
317     // before execution update the selection attributes if any
318     list<AttributePtr> aRefs = 
319       theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
320     list<AttributePtr>::iterator aRefsIter = aRefs.begin();
321     for (; aRefsIter != aRefs.end(); aRefsIter++) {
322       std::shared_ptr<ModelAPI_AttributeSelection> aSel =
323         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
324       ObjectPtr aContext = aSel->context();
325       // update argument onlt if the referenced object is changed
326       if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
327         if (aState == ModelAPI_StateDone)
328           aState = ModelAPI_StateMustBeUpdated;
329         if (!aSel->update()) { // this must be done on execution since it may be long operation
330           if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)) &&
331               aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
332             aState = ModelAPI_StateInvalidArgument;
333         }
334       }
335     }
336     aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
337     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
338       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
339         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
340       for(int a = aSel->size() - 1; a >= 0; a--) {
341         std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
342           std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
343         if (aSelAttr) {
344           ObjectPtr aContext = aSelAttr->context();
345           // update argument onlt if the referenced object is changed
346           if (aContext.get() && isUpdated(aContext) && !aContext->isDisabled()) {
347             if (aState == ModelAPI_StateDone)
348               aState = ModelAPI_StateMustBeUpdated;
349             if (!aSelAttr->update()) {
350               if (!aFactory->isNotObligatory(
351                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
352                 aFactory->isCase(theFeature, theFeature->data()->id(aSel)))
353                 aState = ModelAPI_StateInvalidArgument;
354             }
355           }
356         }
357       }
358     }
359   //}
360   if (aJustUpdated && myJustCreated.find(theFeature) == myJustCreated.end())
361   myJustUpdated.insert(theFeature);
362   if (aState != ModelAPI_StateDone)
363     theFeature->data()->execState(aState);
364 }
365
366 void Model_Update::updateFeature(FeaturePtr theFeature)
367 {
368   // check all features this feature depended on (recursive call of updateFeature)
369   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
370
371   if (theFeature->isDisabled() ||  // nothing to do with disabled feature
372       theFeature->data()->execState() == ModelAPI_StateInvalidArgument)
373     return;
374   bool aJustUpdated = false;
375
376   if (theFeature) {
377     if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
378       aJustUpdated = true;
379
380     ModelAPI_ExecState aState = ModelAPI_StateDone;
381
382     // check all references: if referenced objects are updated, this object also must be updated
383     // also check state of referenced objects: if they are not ready, inherit corresponding state
384     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
385     std::shared_ptr<Model_Data> aData = 
386       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
387     aData->referencesToObjects(aRefs);
388     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
389     for(; aRef != aRefs.end(); aRef++) {
390       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
391       for(; aRefObj != aRef->second.end(); aRefObj++) {
392         if (myJustCreated.find(*aRefObj) != myJustCreated.end() ||
393             myJustUpdated.find(*aRefObj) != myJustUpdated.end()) {
394           aJustUpdated = true;
395         }
396         aState = stateByReference(*aRefObj, aState);
397       }
398     }
399
400     // some arguments were changed, so, this feature must be updated
401     if (myJustCreated.find(theFeature) != myJustCreated.end()) {
402       aJustUpdated = true;
403     } else {
404       if (aJustUpdated) {
405         if (myJustUpdated.find(theFeature) == myJustUpdated.end())
406           myJustUpdated.insert(theFeature);
407       } else {
408         aJustUpdated = myJustUpdated.find(theFeature) != myJustUpdated.end();
409       }
410     }
411     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
412     // execute feature if it must be updated
413     if (aJustUpdated) {
414       if (theFeature->isPreviewNeeded()) {
415         if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
416             !theFeature->isPersistentResult()) {
417           if (aFactory->validate(theFeature)) {
418             FeaturePtr aCurrent = theFeature->document()->currentFeature(false);
419             if (myIsAutomatic || !theFeature->isPersistentResult() /* execute quick, not persistent results */
420                 || (isUpdated(theFeature) && 
421                      (theFeature == aCurrent || 
422                       (aCurrent.get() && aCurrent->isMacro())))) // currently edited
423             {
424               if (aState == ModelAPI_StateDone || aState == ModelAPI_StateMustBeUpdated) {
425                 executeFeature(theFeature);
426               }
427             } else { // must be updatet, but not updated yet
428               theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
429               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
430               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
431               for (; aRIter != aResults.cend(); aRIter++) {
432                 std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
433                 aRes->data()->execState(ModelAPI_StateMustBeUpdated);
434               }
435             }
436           } else {
437             theFeature->eraseResults();
438             redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
439           }
440         } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
441           redisplayWithResults(theFeature, ModelAPI_StateNothing);
442         }
443       } else { // preview is not needed => make state Done
444         if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
445           theFeature->data()->execState(ModelAPI_StateDone);
446       }
447     }
448   }
449 }
450
451 void Model_Update::executeFeature(FeaturePtr theFeature)
452 {
453   // execute in try-catch to avoid internal problems of the feature
454   ModelAPI_ExecState aState = ModelAPI_StateDone;
455   theFeature->data()->execState(ModelAPI_StateDone);
456   try {
457     theFeature->execute();
458     if (theFeature->data()->execState() != ModelAPI_StateDone) {
459       aState = ModelAPI_StateExecFailed;
460     } else {
461       aState = ModelAPI_StateDone;
462     }
463   } catch(...) {
464     aState = ModelAPI_StateExecFailed;
465     Events_Error::send(
466       "Feature " + theFeature->getKind() + " has failed during the execution");
467   }
468   if (aState != ModelAPI_StateDone) {
469     theFeature->eraseResults();
470   }
471   redisplayWithResults(theFeature, aState);
472 }
473
474 bool Model_Update::isUpdated(const ObjectPtr& theObj)
475 {
476   return myJustCreated.find(theObj) != myJustCreated.end() ||
477          myJustUpdated.find(theObj) != myJustUpdated.end();
478 }