Salome HOME
Multiple fixes (issue #1757 , issue #1799 , issue #1842 , etc):
[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 <Model_AttributeSelection.h>
12 #include <ModelAPI_Feature.h>
13 #include <ModelAPI_Data.h>
14 #include <ModelAPI_Document.h>
15 #include <ModelAPI_Events.h>
16 #include <ModelAPI_AttributeReference.h>
17 #include <ModelAPI_AttributeRefList.h>
18 #include <ModelAPI_AttributeRefAttr.h>
19 #include <ModelAPI_AttributeSelection.h>
20 #include <ModelAPI_AttributeSelectionList.h>
21 #include <ModelAPI_Result.h>
22 #include <ModelAPI_ResultPart.h>
23 #include <ModelAPI_Validator.h>
24 #include <ModelAPI_CompositeFeature.h>
25 #include <ModelAPI_Session.h>
26 #include <ModelAPI_Tools.h>
27 #include <GeomDataAPI_Point.h>
28 #include <GeomDataAPI_Point2D.h>
29 #include <Events_Loop.h>
30 #include <Events_LongOp.h>
31 #include <Events_InfoMessage.h>
32 #include <Config_PropManager.h>
33
34 using namespace std;
35
36 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
37 //#define DEB_UPDATE
38
39 Model_Update::Model_Update()
40 {
41   Events_Loop* aLoop = Events_Loop::loop();
42   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
43   aLoop->registerListener(this, kChangedEvent);
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 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   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
55   aLoop->registerListener(this, kStabilityEvent);
56   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
57   aLoop->registerListener(this, kPreviewBlockedEvent);
58   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
59   aLoop->registerListener(this, kPreviewRequestedEvent);
60   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
61   aLoop->registerListener(this, kReorderEvent);
62   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
63   aLoop->registerListener(this, kUpdatedSel);
64
65   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
66   myIsParamUpdated = false;
67   myIsFinish = false;
68   myIsProcessed = false;
69   myIsPreviewBlocked = false;
70 }
71
72 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
73
74   if (!theFeature->data()->isValid())
75     return false; // delete an extrusion created on the sketch
76
77   bool isNotExecuted = theFeature->isPersistentResult() &&
78     !std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures();
79   if (isNotExecuted) {
80     if (!theReason.get()) // no reason => no construction reason
81       return false;
82     if (myNotPersistentRefs.find(theFeature) == myNotPersistentRefs.end()) {
83       myNotPersistentRefs[theFeature].insert(theReason);
84     } else {
85       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
86       aNewSet.insert(theReason);
87       myNotPersistentRefs[theFeature] = aNewSet;
88     }
89     return false;
90   }
91
92   // update arguments for "apply button" state change
93   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
94     myProcessOnFinish.insert(theFeature);
95 #ifdef DEB_UPDATE
96       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
97 #endif
98     // keeps the currently updated features to avoid infinitive cycling here: where feature on
99     // "updateArguments" sends "updated" (in selection attribute) and goes here again
100     static std::set<FeaturePtr> aCurrentlyUpdated;
101     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
102       aCurrentlyUpdated.insert(theFeature);
103       updateArguments(theFeature);
104       aCurrentlyUpdated.erase(theFeature);
105     }
106     // make it without conditions otherwise the apply button may have a bad state
107     theFeature->data()->execState(ModelAPI_StateDone);
108     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
109     aFactory->validate(theFeature); // need to be validated to update the "Apply" state if not previewed
110
111     // to redisplay split's arguments presentation, even result is not computed
112     if (!theFeature->isPreviewNeeded()) {
113       static Events_Loop* aLoop = Events_Loop::loop();
114       static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
115       ModelAPI_EventCreator::get()->sendUpdated(theFeature, kRedisplayEvent);
116       aLoop->flush(kRedisplayEvent);
117     }
118
119     if (!myIsPreviewBlocked)
120       return true;
121   }
122   if (myModified.find(theFeature) != myModified.end()) {
123     if (theReason.get()) {
124 #ifdef DEB_UPDATE
125       //std::cout<<"*** Add already modified "<<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
126 #endif
127       myModified[theFeature].insert(theReason);
128     }
129     return true;
130   }
131   // do not add the disabled, but possibly the sub-elements are not disabled
132   bool aIsDisabled = theFeature->isDisabled();
133   if (!aIsDisabled) {
134     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
135     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated ||
136         theFeature->data()->execState() == ModelAPI_StateInvalidArgument || // issue 1519
137         theFeature->data()->execState() == ModelAPI_StateExecFailed) {
138       // do not forget that in this case all were the reasons
139       aNewSet.insert(theFeature);
140     } else {
141       if (theReason.get())
142         aNewSet.insert(theReason);
143     }
144       myModified[theFeature] = aNewSet;
145 #ifdef DEB_UPDATE
146     if (theReason.get()) {
147       //std::cout<<"*** Add modified "<<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
148     } else {
149       //std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
150     }
151 #endif
152   } else { // will be updated during the finish of the operation, or when it becomes enabled
153     if (theFeature->data()->execState() == ModelAPI_StateDone ||
154         theFeature->data()->execState() == ModelAPI_StateExecFailed) // fix issue 1819
155       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
156     else 
157       return true; // do not need iteration deeply if it is already marked as modified or so
158 #ifdef DEB_UPDATE
159     //std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
160 #endif
161   }
162   // clear processed and fill modified recursively
163   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
164   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
165   for(; aRefIter != aRefs.cend(); aRefIter++) {
166     if ((*aRefIter)->isArgument()) {
167       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
168       if (aReferenced.get()) {
169         addModified(aReferenced, theFeature);
170       }
171     }
172   }
173   // proccess also results
174   std::list<ResultPtr> allResults; // list of this feature and results
175   ModelAPI_Tools::allResults(theFeature, allResults);
176   std::list<ResultPtr>::iterator aRes = allResults.begin();
177   for(; aRes != allResults.end(); aRes++) {
178     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*aRes)->data()->refsToMe();
179     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
180     for(; aRefIter != aRefs.cend(); aRefIter++) {
181       if ((*aRefIter)->isArgument()) {
182         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
183         if (aReferenced.get()) {
184           addModified(aReferenced, theFeature);
185         }
186       }
187     }
188   }
189
190   // also add part feature that contains this feature to the modified
191   if (theFeature->document()->kind() != "PartSet") {
192     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
193       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
194     if (aPart.get())
195       addModified(aPart, theFeature);
196   }
197   return true;
198 }
199
200 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
201 {
202   static Events_Loop* aLoop = Events_Loop::loop();
203   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
204   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
205   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
206   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
207   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
208   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
209   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
210   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
211   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
212   static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
213   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
214
215 #ifdef DEB_UPDATE
216   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
217 #endif
218   if (theMessage->eventID() == kStabilityEvent) {
219     updateStability(theMessage->sender());
220     return;
221   }
222   if (theMessage->eventID() == kPreviewBlockedEvent) {
223     myIsPreviewBlocked = true;
224     return;
225   }
226   if (theMessage->eventID() == kPreviewRequestedEvent) {
227     if (myIsPreviewBlocked) {
228       myIsPreviewBlocked = false;
229       processFeatures();
230       myIsPreviewBlocked = true;
231     }
232     return;
233   }
234   if (theMessage->eventID() == kUpdatedSel) {
235     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
236         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
237     updateSelection(aMsg->objects());
238   }
239   // creation is added to "update" to avoid recomputation twice: on create and immediately after on update
240   if (theMessage->eventID() == kCreatedEvent) {
241     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
242         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
243     const std::set<ObjectPtr>& anObjs = aMsg->objects();
244     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
245     for(; anObjIter != anObjs.cend(); anObjIter++) {
246       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
247         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) { // results creation means enabling, not update
248           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
249         } else {
250           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kRedisplayEvent);
251         }
252       }
253     }
254     return;
255   }
256   if (theMessage->eventID() == kUpdatedEvent) {
257     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
258         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
259     const std::set<ObjectPtr>& anObjs = aMsg->objects();
260     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
261     bool aSomeModified = false; // check that features not changed: only redisplay is needed
262     for(; anObjIter != anObjs.cend(); anObjIter++) {
263       if (!(*anObjIter)->data()->isValid())
264         continue;
265 #ifdef DEB_UPDATE
266       std::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<" "<<(*anObjIter)->data()->name()<<std::endl;
267 #endif
268       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
269         myIsParamUpdated = true;
270       }
271       // on undo/redo, abort do not update persisten features
272       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
273       if (anUpdated.get()) {
274         if (addModified(anUpdated, FeaturePtr()))
275           aSomeModified = true;
276       } else { // process the updated result as update of features that refers to this result
277         const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*anObjIter)->data()->refsToMe();
278         std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
279         for(; aRefIter != aRefs.cend(); aRefIter++) {
280           if (!(*aRefIter)->owner()->data()->isValid())
281             continue;
282           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
283           if (anUpdated.get()) {
284             if (addModified(anUpdated, FeaturePtr()))
285               aSomeModified = true;
286           }
287         }
288       }
289     }
290     // this event is for solver update, not here, do not react immediately
291     if (aSomeModified) {
292         processFeatures();
293     }
294   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
295       theMessage->eventID() == kOpStartEvent) {
296     myIsPreviewBlocked = false;
297
298     if (theMessage->eventID() == kOpFinishEvent) {
299       myIsFinish = true;
300       // add features that wait for finish as modified
301       std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aFeature = myProcessOnFinish.begin();
302       for(; aFeature != myProcessOnFinish.end(); aFeature++)
303         if ((*aFeature)->data()->isValid()) // there may be already removed wait for features
304           addModified(*aFeature, FeaturePtr());
305       myIsFinish = false;
306     }
307     myProcessOnFinish.clear(); // processed features must be only on finish, so clear anyway (to avoid reimport on load)
308
309     if (!(theMessage->eventID() == kOpStartEvent)) {
310       processFeatures(false);
311     }
312     // remove all macros before clearing all created
313     std::set<FeaturePtr>::iterator anUpdatedIter = myWaitForFinish.begin();
314     while(anUpdatedIter != myWaitForFinish.end()) {
315       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
316       if (aFeature.get()) {
317         // remove macro on finish
318         if (aFeature->isMacro()) {
319           aFeature->document()->removeFeature(aFeature);
320           myWaitForFinish.erase(aFeature);
321         }
322         // to avoid the map update problems on "remove"
323         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
324           anUpdatedIter = myWaitForFinish.begin();
325         } else {
326           anUpdatedIter++;
327         }
328       } else {
329         anUpdatedIter++;
330       }
331     }
332     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
333     // if should be done after removeFeature() of document,
334     // by this reason, upper processFeatures() do not perform this flush
335     Events_Loop::loop()->flush(kRedisplayEvent);
336
337     // in the end of transaction everything is updated, so clear the old objects
338     myIsParamUpdated = false;
339     myWaitForFinish.clear();
340   } else if (theMessage->eventID() == kReorderEvent) {
341     std::shared_ptr<ModelAPI_OrderUpdatedMessage> aMsg = 
342       std::dynamic_pointer_cast<ModelAPI_OrderUpdatedMessage>(theMessage);
343     if (aMsg->reordered().get())
344       addModified(aMsg->reordered(), aMsg->reordered()); // to update all attributes
345   }
346 }
347
348 void Model_Update::processFeatures(const bool theFlushRedisplay)
349 {
350    // perform update of everything if it is not performed right now or any preview is blocked
351   if (!myIsProcessed && !myIsPreviewBlocked) {
352     myIsProcessed = true;
353     #ifdef DEB_UPDATE
354       std::cout<<"****** Start processing"<<std::endl;
355     #endif
356
357     while(!myModified.empty()) {
358       processFeature(myModified.begin()->first);
359     }
360     myIsProcessed = false;
361
362     // to update the object browser if something is updated/created during executions
363     static Events_Loop* aLoop = Events_Loop::loop();
364     static const Events_ID kCreatedEvent= aLoop->eventByName(EVENT_OBJECT_CREATED);
365     aLoop->flush(kCreatedEvent);
366     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
367     aLoop->flush(kUpdatedEvent);
368
369     // flush to update display
370     if (theFlushRedisplay) {
371       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
372       aLoop->flush(EVENT_DISP);
373     }
374     #ifdef DEB_UPDATE
375       std::cout<<"****** End processing"<<std::endl;
376     #endif
377     myProcessed.clear();
378   }
379 }
380
381 // collects all the feautres this feature depends on: reasons
382 static void allReasons(FeaturePtr theFeature, std::set<FeaturePtr>& theReasons) {
383   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
384   theFeature->data()->referencesToObjects(aDeps);
385   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
386     anAttrsIter = aDeps.begin();
387   for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
388     if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
389       std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
390       for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
391         FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
392         if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
393           ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
394           if (aDepRes.get()) {
395             aDepFeat = (*aDepIter)->document()->feature(aDepRes);
396           }
397         }
398         if (aDepFeat.get() && aDepFeat->data()->isValid()) {
399           theReasons.insert(aDepFeat);
400         }
401       }
402     }
403   }
404   if (theFeature->getKind() == "Part") { // part is not depended on its subs directly, but subs must be iterated anyway
405     CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
406     int aNum = aPart->numberOfSubs();
407     for(int a = 0; a < aNum; a++) {
408       FeaturePtr aSub = aPart->subFeature(a);
409       if (aSub.get() && aSub->data()->isValid()) {
410         theReasons.insert(aSub);
411       }
412     }
413   }
414 }
415
416 bool Model_Update::processFeature(FeaturePtr theFeature)
417 {
418   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
419
420   if (!theFeature->data()->isValid()) { // deleted feature, just remove from all containers
421     if (myModified.find(theFeature) != myModified.end())
422       myModified.erase(theFeature);
423     return false;
424   }
425
426   if (theFeature->isPersistentResult()) {
427     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
428       return false;
429   }
430
431   if (myProcessed.find(theFeature) == myProcessed.end()) {
432     myProcessed[theFeature] = 0;
433   } else {
434     int aCount = myProcessed[theFeature];
435     if (aCount > 100) { // too many repetition of processing (in VS it may crash on 330 with stack overflow)
436       Events_InfoMessage("Model_Update",
437         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
438       return false;
439     }
440     myProcessed[theFeature] = aCount + 1;
441   }
442
443   // check this feature is not yet checked or processed
444   bool aIsModified = myModified.find(theFeature) != myModified.end();
445   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
446     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
447       aIsModified = true;
448       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
449       aNewSet.insert(theFeature); // contains itself, so, we don't know which was the reason and the reason is any
450       myModified[theFeature] = aNewSet;
451     }
452   }
453
454 #ifdef DEB_UPDATE
455     std::cout<<"* Process feature "<<theFeature->name()<<std::endl;
456 #endif
457
458   // update the sketch plane before the sketch sub-elements are recomputed
459   // (otherwise sketch will update plane, modify subs, after executed, but with old subs edges)
460   if (aIsModified && theFeature->getKind() == "Sketch") {
461 #ifdef DEB_UPDATE
462     std::cout<<"****** Update sketch args "<<theFeature->name()<<std::endl;
463 #endif
464     AttributeSelectionPtr anExtSel = theFeature->selection("External");
465     if (anExtSel.get()) {
466       ResultPtr aContext = anExtSel->context();
467       if (aContext.get() && aContext->document().get()) {
468         FeaturePtr anExtBase = aContext->document()->feature(aContext);
469         if (anExtBase.get()) {
470           processFeature(anExtBase);
471         }
472       }
473     }
474     updateArguments(theFeature);
475     // send event that sketch is prepared to be recomputed
476     static Events_ID anID = Events_Loop::eventByName("SketchPrepared");
477     std::shared_ptr<Events_Message> aMsg(new Events_Message(anID, this));
478     Events_Loop::loop()->send(aMsg);
479   }
480
481   if (!aIsModified) { // no modification is needed
482     return false;
483   }
484
485   // evaluate parameter before the sub-elements update: it updates dependencies on evaluation (#1085)
486   if (theFeature->getKind() == "Parameter") {
487     theFeature->execute();
488   }
489
490   bool isReferencedInvalid = false;
491   // check all features this feature depended on (recursive call of updateFeature)
492   std::set<FeaturePtr>& aReasons = myModified[theFeature];
493   bool allSubsUsed = aReasons.find(theFeature) != aReasons.end();
494   if (allSubsUsed) { // add all subs in aReasons and temporary remove "theFeature" to avoid processing itself
495     allReasons(theFeature, aReasons);
496     aReasons.erase(theFeature);
497   }
498   // take reasons one by one (they may be added during the feature process (circle by the radius of sketch)
499   std::set<FeaturePtr> aProcessedReasons;
500   while(!aReasons.empty()) {
501     FeaturePtr aReason = *(aReasons.begin());
502 #ifdef DEB_UPDATE
503     //cout<<theFeature->name()<<" process next reason "<<aReason->name()<<endl;
504 #endif
505     if (aReason != theFeature && (aReason)->data()->isValid()) {
506       if (processFeature(aReason))
507         aIsModified = true;
508       if (aReason->data()->execState() == ModelAPI_StateInvalidArgument)
509         isReferencedInvalid = true;
510     }
511     // searching for the next not used reason
512     aProcessedReasons.insert(aReason);
513     aReasons.erase(aReason);
514   }
515   // restore the modified reasons: they will be used in the update of arguments
516   if (allSubsUsed) { // restore theFeature in this set
517     aProcessedReasons.insert(theFeature);
518   }
519   myModified[theFeature] = aProcessedReasons;
520
521   // do not execute the composite that contains the current
522   bool isPostponedMain = false;
523   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
524   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
525     CompositeFeaturePtr aCurrentOwner = 
526       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
527     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
528   }
529
530 #ifdef DEB_UPDATE
531   std::cout<<"Update args "<<theFeature->name()<<std::endl;
532 #endif
533   // TestImport.py : after arguments are updated, theFeature may be removed
534   if (!theFeature->data()->isValid())
535     return false;
536   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
537   updateArguments(theFeature);
538
539   // add this feature to the processed right now to be able remove it from this list on
540   // update signal during this feature execution
541   myModified.erase(theFeature);
542   if (myNotPersistentRefs.find(theFeature) != myNotPersistentRefs.end())
543     myNotPersistentRefs.erase(theFeature);
544   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
545     theFeature->data()->execState(ModelAPI_StateDone);
546
547   // this checking must be after the composite feature sub-elements processing:
548   // composite feature status may depend on it's subelements
549   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) && 
550     theFeature->getKind() != "Part") { // don't disable Part because it will make disabled all the features (performance and problems with the current feature)
551   #ifdef DEB_UPDATE
552     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
553   #endif
554     theFeature->eraseResults();
555     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
556     return true; // so, feature is modified (results are erased)
557   }
558
559   // execute feature if it must be updated
560   ModelAPI_ExecState aState = theFeature->data()->execState();
561   if (aFactory->validate(theFeature)) {
562     if (!isPostponedMain) {
563       executeFeature(theFeature);
564     }
565   } else {
566     #ifdef DEB_UPDATE
567       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
568     #endif
569     theFeature->eraseResults();
570     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
571   }
572   return true;
573 }
574
575 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
576 {
577   // make updated and redisplay all results
578   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
579
580   std::list<ResultPtr> allResults;
581   ModelAPI_Tools::allResults(theFeature, allResults);
582   std::list<ResultPtr>::iterator aRIter = allResults.begin();
583   for (; aRIter != allResults.cend(); aRIter++) {
584     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
585     if (!aRes->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
586       aRes->data()->execState(theState);
587     }
588     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
589       aRes->data()->setUpdateID(theFeature->data()->updateID());
590     }
591     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
592   }
593   // to redisplay "presentable" feature (for ex. distance constraint)
594   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
595   theFeature->data()->execState(theState);
596 }
597
598 /// Updates the state by the referenced object: if something bad with it, set state for this one
599 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
600 {
601   if (theTarget) {
602     ModelAPI_ExecState aRefState = theTarget->data()->execState();
603     if (aRefState == ModelAPI_StateMustBeUpdated) {
604       if (theCurrent == ModelAPI_StateDone)
605         return ModelAPI_StateMustBeUpdated;
606     } else if (aRefState != ModelAPI_StateDone) {
607       return ModelAPI_StateInvalidArgument;
608     }
609   }
610   return theCurrent;
611 }
612
613 void Model_Update::updateArguments(FeaturePtr theFeature) {
614   // perform this method also for disabled features: to make "not done" state for
615   // features referenced to the active and modified features
616
617   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
618
619   ModelAPI_ExecState aState = theFeature->data()->execState();
620   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
621     aState = ModelAPI_StateMustBeUpdated;
622   }
623   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
624     aState = ModelAPI_StateMustBeUpdated;
625   // check the parameters state
626   // Integer
627   {
628     std::list<AttributePtr> anAttrinbutes =
629       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
630     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
631     for(; anIter != anAttrinbutes.end(); anIter++) {
632       AttributeIntegerPtr anAttribute =
633         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
634       if (anAttribute.get() && !anAttribute->text().empty()) {
635         if (myIsParamUpdated) {
636           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
637         }
638         if (anAttribute->expressionInvalid()) {
639           aState = ModelAPI_StateInvalidArgument;
640         }
641       }
642     }
643   }
644   // Double
645   {
646     std::list<AttributePtr> aDoubles =
647       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
648     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
649     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
650       AttributeDoublePtr aDouble =
651         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
652       if (aDouble.get() && !aDouble->text().empty()) {
653         if (myIsParamUpdated) {
654           ModelAPI_AttributeEvalMessage::send(aDouble, this);
655         }
656         if (aDouble->expressionInvalid()) {
657           aState = ModelAPI_StateInvalidArgument;
658         }
659       }
660     }
661   }
662   // Point
663   {
664     std::list<AttributePtr> anAttributes =
665       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
666     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
667     for(; anIter != anAttributes.end(); anIter++) {
668       AttributePointPtr aPointAttribute =
669         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
670       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() || 
671           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
672         if (myIsParamUpdated) {
673           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
674         }
675         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
676           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
677           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
678           aState = ModelAPI_StateInvalidArgument;
679       }
680     }
681   }
682   // Point2D
683   {
684     std::list<AttributePtr> anAttributes =
685       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
686     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
687     for(; anIter != anAttributes.end(); anIter++) {
688       AttributePoint2DPtr aPoint2DAttribute =
689         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
690       if (aPoint2DAttribute.get()) {
691         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() || 
692             !aPoint2DAttribute->textY().empty())) {
693           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
694         }
695         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
696           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
697           aState = ModelAPI_StateInvalidArgument;
698       }
699     }
700   }
701   // update the selection attributes if any
702   list<AttributePtr> aRefs = 
703     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
704   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
705   for (; aRefsIter != aRefs.end(); aRefsIter++) {
706     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
707       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
708     ObjectPtr aContext = aSel->context();
709     // update argument only if the referenced object is ready to use
710     if (aContext.get() && !aContext->isDisabled()) {
711       if (isReason(theFeature, aContext)) {
712         if (!aSel->update()) { // this must be done on execution since it may be long operation
713           bool isObligatory = !aFactory->isNotObligatory(
714             theFeature->getKind(), theFeature->data()->id(aSel)) &&
715             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
716           if (isObligatory)
717             aState = ModelAPI_StateInvalidArgument;
718         }
719       }
720     } else if (aContext.get()) {
721       // here it may be not obligatory, but if the reference is wrong, it should not be correct
722       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
723       if (isObligatory)
724         aState = ModelAPI_StateInvalidArgument;
725     }
726   }
727   // update the selection list attributes if any
728   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
729   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
730     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
731       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
732     for(int a = aSel->size() - 1; a >= 0; a--) {
733       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
734         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
735       if (aSelAttr) {
736         ObjectPtr aContext = aSelAttr->context();
737         // update argument only if the referenced object is ready to use
738         if (aContext.get() && !aContext->isDisabled()) {
739           if (isReason(theFeature, aContext)) {
740             if (!aSelAttr->update()) {
741               bool isObligatory = !aFactory->isNotObligatory(
742                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
743                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
744               if (isObligatory)
745                 aState = ModelAPI_StateInvalidArgument;
746             }
747           }
748         } else if (aContext.get()) {
749           // here it may be not obligatory, but if the reference is wrong, it should not be correct
750           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
751           if (isObligatory)
752             aState = ModelAPI_StateInvalidArgument;
753         }
754       }
755     }
756   }
757
758   if (aState != ModelAPI_StateDone)
759     theFeature->data()->execState(aState);
760 }
761
762 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature, 
763      std::shared_ptr<ModelAPI_Object> theReason) 
764 {
765   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
766     ::iterator aReasonsIt = myModified.find(theFeature);
767   if (aReasonsIt != myModified.end()) {
768     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
769       return true; // any is reason if it contains itself
770     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
771     if (!aReasFeat.get()) { // try to get feature of this result
772       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
773       if (aReasRes.get())
774         aReasFeat = theReason->document()->feature(aReasRes);
775     }
776     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
777       return true;
778   }
779   // another try: postponed modification by not-persistences
780   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
781     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
782   if (aNotPersist != myNotPersistentRefs.end()) {
783     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
784     if (!aReasFeat.get()) { // try to get feature of this result
785       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
786       if (aReasRes.get())
787         aReasFeat = theReason->document()->feature(aReasRes);
788     }
789     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
790       return true;
791   }
792
793   return false; // this case only for not-previewed items update state, nothing is changed in args for it
794 }
795
796 void Model_Update::executeFeature(FeaturePtr theFeature)
797 {
798 #ifdef DEB_UPDATE
799   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
800 #endif
801   // execute in try-catch to avoid internal problems of the feature
802   ModelAPI_ExecState aState = ModelAPI_StateDone;
803   theFeature->data()->execState(ModelAPI_StateDone);
804   try {
805     theFeature->execute();
806     if (theFeature->data()->execState() != ModelAPI_StateDone) {
807       aState = ModelAPI_StateExecFailed;
808     } else {
809       aState = ModelAPI_StateDone;
810     }
811   } catch(...) {
812     aState = ModelAPI_StateExecFailed;
813     Events_InfoMessage("Model_Update",
814       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
815   }
816   // The macro feature has to be deleted in any case even its execution is failed 
817   myWaitForFinish.insert(theFeature);
818   if (aState != ModelAPI_StateDone) {
819     theFeature->eraseResults();
820   }
821   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
822   redisplayWithResults(theFeature, aState);
823 }
824
825 void Model_Update::updateStability(void* theSender)
826 {
827   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
828   if (theSender) {
829     bool added = false; // object may be was crated
830     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
831     if (aSender && aSender->document()) {
832       FeaturePtr aFeatureSender = 
833         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
834       if (aFeatureSender.get()) {
835         Model_Objects* aDocObjects = 
836           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
837         if (aDocObjects) {
838           //aDocObjects->synchronizeBackRefs();
839           // remove or add all concealment refs from this feature
840           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
841           aSender->data()->referencesToObjects(aRefs);
842           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
843           for(; aRefIt != aRefs.end(); aRefIt++) {
844             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
845               continue; // take into account only concealed references (do not remove the sketch constraint and the edge on constraint edit)
846             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
847             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
848             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
849                // stability is only on results: feature to feature reference mean nested 
850               // features, that will remove nesting references
851               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
852                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
853                 std::shared_ptr<Model_Data> aData = 
854                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
855                 if (aFeatureSender->isStable()) {
856                   aData->addBackReference(aFeatureSender, aRefIt->first);
857                 } else {
858                   aData->removeBackReference(aFeatureSender, aRefIt->first);
859                   added = true; // remove of concealment may be caused creation of some result
860                 }
861               }
862             }
863           }
864         }
865       }
866     }
867     if (added) {
868       static Events_Loop* aLoop = Events_Loop::loop();
869       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
870       aLoop->flush(kEventCreated);
871     }
872   }
873 }
874
875 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
876 {
877   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
878   for(; anObj != theObjects.end(); anObj++) {
879     list<AttributePtr> aRefs = 
880       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
881     list<AttributePtr>::iterator aRefsIter = aRefs.begin();
882     for (; aRefsIter != aRefs.end(); aRefsIter++) {
883       std::shared_ptr<Model_AttributeSelection> aSel =
884         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
885       aSel->updateInHistory();
886     }
887     // update the selection list attributes if any
888     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
889     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
890       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
891         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
892       for(int a = aSel->size() - 1; a >= 0; a--) {
893         std::shared_ptr<Model_AttributeSelection> aSelAttr =
894           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
895         if (aSelAttr.get())
896           aSelAttr->updateInHistory();
897       }
898     }
899   }
900 }