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