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