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