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