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