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