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