Salome HOME
Issue #2612 : Re-calculate model after modification of parameters
[modules/shaper.git] / src / Model / Model_Update.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Update.h>
22 #include <Model_Document.h>
23 #include <Model_Data.h>
24 #include <Model_Objects.h>
25 #include <Model_AttributeSelection.h>
26 #include <ModelAPI_Feature.h>
27 #include <ModelAPI_Data.h>
28 #include <ModelAPI_Document.h>
29 #include <ModelAPI_Events.h>
30 #include <ModelAPI_AttributeReference.h>
31 #include <ModelAPI_AttributeRefList.h>
32 #include <ModelAPI_AttributeRefAttr.h>
33 #include <ModelAPI_AttributeSelection.h>
34 #include <ModelAPI_AttributeSelectionList.h>
35 #include <ModelAPI_Result.h>
36 #include <ModelAPI_ResultPart.h>
37 #include <ModelAPI_Validator.h>
38 #include <ModelAPI_CompositeFeature.h>
39 #include <ModelAPI_Session.h>
40 #include <ModelAPI_Tools.h>
41 #include <ModelAPI_ResultBody.h>
42 #include <ModelAPI_ResultPart.h>
43 #include <GeomAPI_Shape.h>
44 #include <GeomDataAPI_Point.h>
45 #include <GeomDataAPI_Point2D.h>
46 #include <Events_Loop.h>
47 #include <Events_LongOp.h>
48 #include <Events_InfoMessage.h>
49 #include <Config_PropManager.h>
50
51 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
52 //#define DEB_UPDATE
53
54 Model_Update::Model_Update()
55 {
56   Events_Loop* aLoop = Events_Loop::loop();
57   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
58   aLoop->registerListener(this, kChangedEvent);
59   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
60   aLoop->registerListener(this, kCreatedEvent);
61   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
62   aLoop->registerListener(this, kUpdatedEvent);
63   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
64   aLoop->registerListener(this, kOpFinishEvent);
65   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
66   aLoop->registerListener(this, kOpAbortEvent);
67   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
68   aLoop->registerListener(this, kOpStartEvent);
69   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
70   aLoop->registerListener(this, kStabilityEvent);
71   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
72   aLoop->registerListener(this, kPreviewBlockedEvent);
73   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
74   aLoop->registerListener(this, kPreviewRequestedEvent);
75   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
76   aLoop->registerListener(this, kReorderEvent);
77   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
78   aLoop->registerListener(this, kUpdatedSel);
79   static const Events_ID kAutomaticOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
80   aLoop->registerListener(this, kAutomaticOff);
81   static const Events_ID kAutomaticOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
82   aLoop->registerListener(this, kAutomaticOn);
83
84   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
85   myIsParamUpdated = false;
86   myIsFinish = false;
87   myIsProcessed = false;
88   myIsPreviewBlocked = false;
89   myUpdateBlocked = false;
90 }
91
92 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
93
94   if (!theFeature->data()->isValid())
95     return false; // delete an extrusion created on the sketch
96
97
98   bool isNotExecuted = theFeature->isPersistentResult() &&
99     !std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures();
100   if (isNotExecuted) {
101     redisplayWithResults(theFeature, ModelAPI_StateNothing, false); // redisplay even not executed
102     if (!theReason.get()) // no reason => no construction reason
103       return false;
104     if (myNotPersistentRefs.find(theFeature) == myNotPersistentRefs.end()) {
105       myNotPersistentRefs[theFeature].insert(theReason);
106     } else {
107       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
108       aNewSet.insert(theReason);
109       myNotPersistentRefs[theFeature] = aNewSet;
110     }
111     return false;
112   }
113
114   // update arguments for "apply button" state change
115   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
116     if (theReason.get())
117       myProcessOnFinish[theFeature].insert(theReason);
118     else if (myProcessOnFinish.find(theFeature) == myProcessOnFinish.end())
119       myProcessOnFinish[theFeature] = std::set<std::shared_ptr<ModelAPI_Feature> >();
120 #ifdef DEB_UPDATE
121       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
122 #endif
123     // keeps the currently updated features to avoid infinitive cycling here: where feature on
124     // "updateArguments" sends "updated" (in selection attribute) and goes here again
125     static std::set<FeaturePtr> aCurrentlyUpdated;
126     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
127       aCurrentlyUpdated.insert(theFeature);
128       updateArguments(theFeature);
129       aCurrentlyUpdated.erase(theFeature);
130     }
131     // make it without conditions otherwise the apply button may have a bad state
132     theFeature->data()->execState(ModelAPI_StateDone);
133     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
134      // need to be validated to update the "Apply" state if not previewed
135     aFactory->validate(theFeature);
136
137     // to redisplay split's arguments presentation, even result is not computed
138     if (!theFeature->isPreviewNeeded()) {
139       static Events_Loop* aLoop = Events_Loop::loop();
140       static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
141       ModelAPI_EventCreator::get()->sendUpdated(theFeature, kRedisplayEvent);
142       aLoop->flush(kRedisplayEvent);
143     }
144
145     if (!myIsPreviewBlocked)
146       return true;
147   }
148   if (myModified.find(theFeature) != myModified.end()) {
149     if (theReason.get()) {
150 #ifdef DEB_UPDATE
151       //std::cout<<"*** Add already modified "
152       //   <<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
153 #endif
154       myModified[theFeature].insert(theReason);
155     }
156     return true;
157   }
158   // do not add the disabled, but possibly the sub-elements are not disabled
159   bool aIsDisabled = theFeature->isDisabled();
160   if (!aIsDisabled) {
161     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
162     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated ||
163         theFeature->data()->execState() == ModelAPI_StateInvalidArgument || // issue 1519
164         theFeature->data()->execState() == ModelAPI_StateExecFailed) {
165       // do not forget that in this case all were the reasons
166       aNewSet.insert(theFeature);
167     } else {
168       if (theReason.get())
169         aNewSet.insert(theReason);
170     }
171     myModified[theFeature] = aNewSet;
172 #ifdef DEB_UPDATE
173     if (theReason.get()) {
174       //std::cout<<"*** Add modified "<<theFeature->name()
175       //  <<" reason "<<theReason->name()<<std::endl;
176     } else {
177       //std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
178     }
179 #endif
180   } else { // will be updated during the finish of the operation, or when it becomes enabled
181     if (theFeature->data()->execState() == ModelAPI_StateDone ||
182         theFeature->data()->execState() == ModelAPI_StateExecFailed) // fix issue 1819
183       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
184     else
185       return true; // do not need iteration deeply if it is already marked as modified or so
186 #ifdef DEB_UPDATE
187     //std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
188 #endif
189   }
190   // clear processed and fill modified recursively
191   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
192   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
193   for(; aRefIter != aRefs.cend(); aRefIter++) {
194     if ((*aRefIter)->isArgument()) {
195       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
196       if (aReferenced.get()) {
197         addModified(aReferenced, theFeature);
198       }
199     }
200   }
201   // proccess also results
202   std::list<ResultPtr> allResults; // list of this feature and results
203   ModelAPI_Tools::allResults(theFeature, allResults);
204   std::list<ResultPtr>::iterator aRes = allResults.begin();
205   for(; aRes != allResults.end(); aRes++) {
206     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*aRes)->data()->refsToMe();
207     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
208     for(; aRefIter != aRefs.cend(); aRefIter++) {
209       if ((*aRefIter)->isArgument()) {
210         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
211         if (aReferenced.get()) {
212           addModified(aReferenced, theFeature);
213         }
214       }
215     }
216   }
217
218   // also add part feature that contains this feature to the modified
219   if (theFeature->document()->kind() != "PartSet") {
220     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
221       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
222     if (aPart.get())
223       addModified(aPart, theFeature);
224   }
225   return true;
226 }
227
228 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
229 {
230   static Events_Loop* aLoop = Events_Loop::loop();
231   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
232   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
233   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
234   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
235   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
236   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
237   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
238   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
239   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
240   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
241   static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
242   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
243   static const Events_ID kAutomaticOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
244   static const Events_ID kAutomaticOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
245
246 #ifdef DEB_UPDATE
247   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
248 #endif
249   if (theMessage->eventID() == kStabilityEvent) {
250     updateStability(theMessage->sender());
251     return;
252   }
253   if (theMessage->eventID() == kPreviewBlockedEvent) {
254     myIsPreviewBlocked = true;
255     return;
256   }
257   if (theMessage->eventID() == kPreviewRequestedEvent) {
258     if (myIsPreviewBlocked) {
259       bool anUpdateState = myUpdateBlocked;
260       myUpdateBlocked = false;
261       myIsPreviewBlocked = false;
262       processFeatures();
263       myIsPreviewBlocked = true;
264       myUpdateBlocked = anUpdateState;
265     }
266     return;
267   }
268   if (theMessage->eventID() == kAutomaticOff) {
269     myUpdateBlocked = true;
270     return;
271   }
272   if (theMessage->eventID() == kAutomaticOn) {
273     myUpdateBlocked = false; // then process all modified features, even if preview is blocked
274     bool aPreviewBlockedState = myIsPreviewBlocked; // to update the selected arguments
275     myIsPreviewBlocked = false;
276     // iterate everything and add efatures in state "MustBeUpdated" into modified
277     std::list<std::shared_ptr<ModelAPI_Document> > allDocs =
278       ModelAPI_Session::get()->allOpenedDocuments();
279     std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = allDocs.begin();
280     for(; aDoc != allDocs.end(); aDoc++) {
281       std::list<std::shared_ptr<ModelAPI_Feature> > allFeats = (*aDoc)->allFeatures();
282       std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFeat = allFeats.begin();
283       for(; aFeat != allFeats.end(); aFeat++) {
284         if ((*aFeat)->data()->isValid() &&
285             (*aFeat)->data()->execState() == ModelAPI_StateMustBeUpdated) {
286           addModified(*aFeat, FeaturePtr());
287         }
288       }
289     }
290     processFeatures();
291     myIsPreviewBlocked = myIsPreviewBlocked;
292     return;
293   }
294   if (theMessage->eventID() == kUpdatedSel) {
295     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
296         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
297     updateSelection(aMsg->objects());
298   }
299   // creation is added to "update" to avoid recomputation twice:
300   // on create and immediately after on update
301   if (theMessage->eventID() == kCreatedEvent) {
302     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
303         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
304     const std::set<ObjectPtr>& anObjs = aMsg->objects();
305     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
306     for(; anObjIter != anObjs.cend(); anObjIter++) {
307       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
308         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) {
309           // results creation means enabling, not update
310           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
311         } else {
312           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kRedisplayEvent);
313         }
314       }
315     }
316     return;
317   }
318   if (theMessage->eventID() == kUpdatedEvent) {
319     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
320         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
321     const std::set<ObjectPtr>& anObjs = aMsg->objects();
322     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
323     bool aSomeModified = false; // check that features not changed: only redisplay is needed
324     for(; anObjIter != anObjs.cend(); anObjIter++) {
325       if (!(*anObjIter)->data()->isValid())
326         continue;
327 #ifdef DEB_UPDATE
328       std::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<
329         " "<<(*anObjIter)->data()->name()<<std::endl;
330 #endif
331       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
332         myIsParamUpdated = true;
333       }
334       // on undo/redo, abort do not update persisten features
335       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
336       if (anUpdated.get()) {
337         if (addModified(anUpdated, FeaturePtr()))
338           aSomeModified = true;
339         if (myUpdateBlocked) { // execute this feature anyway to show the current result
340           /*if (!anUpdated->isStable() && anUpdated->results().size() && (
341               anUpdated->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
342               anUpdated->firstResult()->groupName() == ModelAPI_ResultPart::group())) {
343             if (aFactory->validate(anUpdated)) {
344               executeFeature(anUpdated);
345               redisplayWithResults(anUpdated, ModelAPI_StateNothing, false);
346               static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
347               aLoop->flush(EVENT_DISP);
348             }
349           }*/
350         }
351       } else {
352         // process the updated result as update of features that refers to this result
353         const std::set<std::shared_ptr<ModelAPI_Attribute> >&
354           aRefs = (*anObjIter)->data()->refsToMe();
355         std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
356         FeaturePtr aReason;
357         ResultPtr aReasonResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter);
358         if (aReasonResult.get())
359           aReason = (*anObjIter)->document()->feature(aReasonResult);
360         for(; aRefIter != aRefs.cend(); aRefIter++) {
361           if (!(*aRefIter)->owner()->data()->isValid())
362             continue;
363           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
364           if (anUpdated.get()) {
365             if (addModified(anUpdated, aReason))
366               aSomeModified = true;
367           }
368         }
369       }
370     }
371     // this event is for solver update, not here, do not react immediately
372     if (aSomeModified) {
373         processFeatures();
374     }
375   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
376       theMessage->eventID() == kOpStartEvent) {
377     myIsPreviewBlocked = false;
378
379     if (theMessage->eventID() == kOpFinishEvent) {// if update is blocked, skip
380       myIsFinish = true;
381       // add features that wait for finish as modified
382       std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >::
383         iterator aFeature = myProcessOnFinish.begin();
384       for(; aFeature != myProcessOnFinish.end(); aFeature++) {
385         if (aFeature->first->data()->isValid()) {// there may be already removed while wait
386           if (aFeature->second.empty()) {
387             addModified(aFeature->first, FeaturePtr());
388             continue;
389           }
390           std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aReasons;
391           for(aReasons = aFeature->second.begin(); aReasons != aFeature->second.end(); aReasons++){
392             addModified(aFeature->first, *aReasons);
393           }
394         }
395       }
396       myIsFinish = false;
397     }
398     // processed features must be only on finish, so clear anyway (to avoid reimport on load)
399     myProcessOnFinish.clear();
400
401     // #2156: current must be sketch, left after the macro execution
402     DocumentPtr anActiveDoc = ModelAPI_Session::get()->activeDocument();
403     FeaturePtr aCurrent;
404     if (anActiveDoc.get())
405       aCurrent = anActiveDoc->currentFeature(false);
406
407     if (!(theMessage->eventID() == kOpStartEvent)) {
408       processFeatures(false);
409     }
410
411     if (anActiveDoc.get() && aCurrent.get() && aCurrent->data()->isValid()) {
412       if (anActiveDoc->currentFeature(false) != aCurrent)
413         anActiveDoc->setCurrentFeature(aCurrent, false); // #2156 make the current feature back
414     }
415
416     // remove all macros before clearing all created
417     std::set<FeaturePtr>::iterator anUpdatedIter = myWaitForFinish.begin();
418     while(anUpdatedIter != myWaitForFinish.end()) {
419       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
420       if (aFeature.get()) {
421         // remove macro on finish
422         if (aFeature->isMacro()) {
423           aFeature->document()->removeFeature(aFeature);
424           myWaitForFinish.erase(aFeature);
425         }
426         // to avoid the map update problems on "remove"
427         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
428           anUpdatedIter = myWaitForFinish.begin();
429         } else {
430           anUpdatedIter++;
431         }
432       } else {
433         anUpdatedIter++;
434       }
435     }
436     // the redisplay signal should be flushed in order
437     // to erase the feature presentation in the viewer
438     // if should be done after removeFeature() of document,
439     // by this reason, upper processFeatures() do not perform this flush
440     Events_Loop::loop()->flush(kRedisplayEvent);
441
442     // in the end of transaction everything is updated, so clear the old objects
443     myIsParamUpdated = false;
444     myWaitForFinish.clear();
445   } else if (theMessage->eventID() == kReorderEvent) {
446     std::shared_ptr<ModelAPI_OrderUpdatedMessage> aMsg =
447       std::dynamic_pointer_cast<ModelAPI_OrderUpdatedMessage>(theMessage);
448     if (aMsg->reordered().get())
449       addModified(aMsg->reordered(), aMsg->reordered()); // to update all attributes
450   }
451 }
452
453 void Model_Update::processFeatures(const bool theFlushRedisplay)
454 {
455    // perform update of everything if it is not performed right now or any preview is blocked
456   if (!myIsProcessed && !myIsPreviewBlocked) {
457     myIsProcessed = true;
458     #ifdef DEB_UPDATE
459       std::cout<<"****** Start processing"<<std::endl;
460     #endif
461
462     while(!myModified.empty()) {
463       processFeature(myModified.begin()->first);
464     }
465     myIsProcessed = false;
466
467     // to update the object browser if something is updated/created during executions
468     static Events_Loop* aLoop = Events_Loop::loop();
469     static const Events_ID kCreatedEvent= aLoop->eventByName(EVENT_OBJECT_CREATED);
470     aLoop->flush(kCreatedEvent);
471     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
472     aLoop->flush(kUpdatedEvent);
473
474     // flush to update display
475     if (theFlushRedisplay) {
476       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
477       aLoop->flush(EVENT_DISP);
478     }
479     #ifdef DEB_UPDATE
480       std::cout<<"****** End processing"<<std::endl;
481     #endif
482     myProcessed.clear();
483   }
484 }
485
486 // collects all the feautres this feature depends on: reasons
487 static void allReasons(FeaturePtr theFeature, std::set<FeaturePtr>& theReasons) {
488   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
489   theFeature->data()->referencesToObjects(aDeps);
490   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
491     anAttrsIter = aDeps.begin();
492   for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
493     if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
494       std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
495       for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
496         FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
497         if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
498           ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
499           if (aDepRes.get()) {
500             aDepFeat = (*aDepIter)->document()->feature(aDepRes);
501           }
502         }
503         if (aDepFeat.get() && aDepFeat->data()->isValid()) {
504           theReasons.insert(aDepFeat);
505         }
506       }
507     }
508   }
509   if (theFeature->getKind() == "Part") {
510     // part is not depended on its subs directly, but subs must be iterated anyway
511     CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
512     int aNum = aPart->numberOfSubs();
513     for(int a = 0; a < aNum; a++) {
514       FeaturePtr aSub = aPart->subFeature(a);
515       if (aSub.get() && aSub->data()->isValid()) {
516         theReasons.insert(aSub);
517       }
518     }
519   }
520 }
521
522 bool Model_Update::processFeature(FeaturePtr theFeature)
523 {
524   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
525
526   if (!theFeature->data()->isValid()) { // deleted feature, just remove from all containers
527     if (myModified.find(theFeature) != myModified.end())
528       myModified.erase(theFeature);
529     return false;
530   }
531
532   if (theFeature->isPersistentResult()) {
533     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
534       return false;
535   }
536
537   if (myProcessed.find(theFeature) == myProcessed.end()) {
538     myProcessed[theFeature] = 0;
539   } else {
540     int aCount = myProcessed[theFeature];
541     if (aCount > 100) {
542       // too many repetition of processing (in VS it may crash on 330 with stack overflow)
543       Events_InfoMessage("Model_Update",
544         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
545       // to stop iteration
546       myModified.clear();
547       return false;
548     }
549     myProcessed[theFeature] = aCount + 1;
550   }
551
552   // check this feature is not yet checked or processed
553   bool aIsModified = myModified.find(theFeature) != myModified.end();
554   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
555     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
556       aIsModified = true;
557       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
558       // contains itself, so, we don't know which was the reason and the reason is any
559       aNewSet.insert(theFeature);
560       myModified[theFeature] = aNewSet;
561     }
562   }
563
564 #ifdef DEB_UPDATE
565     std::cout<<"* Process feature "<<theFeature->name()<<std::endl;
566 #endif
567
568   // update the sketch plane before the sketch sub-elements are recomputed
569   // (otherwise sketch will update plane, modify subs, after executed, but with old subs edges)
570   if (aIsModified && theFeature->getKind() == "Sketch") {
571 #ifdef DEB_UPDATE
572     std::cout<<"****** Update sketch args "<<theFeature->name()<<std::endl;
573 #endif
574     AttributeSelectionPtr anExtSel = theFeature->selection("External");
575     if (anExtSel.get()) {
576       ResultPtr aContext = anExtSel->context();
577       if (aContext.get() && aContext->document().get()) {
578         FeaturePtr anExtBase = aContext->document()->feature(aContext);
579         if (anExtBase.get()) {
580           processFeature(anExtBase);
581         }
582       }
583     }
584     std::shared_ptr<GeomAPI_Shape> aShapeBefore = anExtSel->value();
585     if (!aShapeBefore.get() && anExtSel->context()) aShapeBefore = anExtSel->context()->shape();
586     updateArguments(theFeature);
587     std::shared_ptr<GeomAPI_Shape> aShapeAfter = anExtSel->value();
588     if (!aShapeAfter.get() && anExtSel->context()) aShapeAfter = anExtSel->context()->shape();
589     // if selected plane is changed, try to re-take external references of all subs of the sketch
590     if (aShapeBefore.get() && !aShapeBefore->isEqual(aShapeAfter)) {
591       std::set<FeaturePtr> aWholeR;
592       allReasons(theFeature, aWholeR);
593       std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
594       for(; aRIter != aWholeR.end(); aRIter++) {
595         if ((*aRIter)->data()->selection("External"))
596           (*aRIter)->attributeChanged("External");
597       }
598     }
599   }
600
601   if (!aIsModified) { // no modification is needed
602     return false;
603   }
604
605   // evaluate parameter before the sub-elements update:
606   // it updates dependencies on evaluation (#1085)
607   if (theFeature->getKind() == "Parameter") {
608     theFeature->execute();
609   }
610
611   bool isReferencedInvalid = false;
612   // check all features this feature depended on (recursive call of updateFeature)
613   std::set<FeaturePtr>& aReasons = myModified[theFeature];
614   bool allSubsUsed = aReasons.find(theFeature) != aReasons.end();
615   if (allSubsUsed) {
616     // add all subs in aReasons and temporary remove "theFeature" to avoid processing itself
617     allReasons(theFeature, aReasons);
618     aReasons.erase(theFeature);
619   }
620   // take reasons one by one (they may be added during the feature process
621   // (circle by the radius of sketch)
622   std::set<FeaturePtr> aProcessedReasons;
623   while(!aReasons.empty()) {
624     FeaturePtr aReason = *(aReasons.begin());
625 #ifdef DEB_UPDATE
626     //cout<<theFeature->name()<<" process next reason "<<aReason->name()<<endl;
627 #endif
628     if (aReason != theFeature && (aReason)->data()->isValid()) {
629       if (processFeature(aReason))
630         aIsModified = true;
631       // check validity of aReason once again because it may be removed by dependent feature
632       // (e.g. by SketchPlugin_IntersectionPoint)
633       if (!aReason->data()->isValid() ||
634           aReason->data()->execState() == ModelAPI_StateInvalidArgument)
635         isReferencedInvalid = true;
636     }
637     // searching for the next not used reason
638     aProcessedReasons.insert(aReason);
639     aReasons.erase(aReason);
640   }
641   // restore the modified reasons: they will be used in the update of arguments
642   if (allSubsUsed) { // restore theFeature in this set
643     aProcessedReasons.insert(theFeature);
644   }
645   myModified[theFeature] = aProcessedReasons;
646
647   // do not execute the composite that contains the current
648   bool isPostponedMain = false;
649   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
650   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
651     CompositeFeaturePtr aCurrentOwner =
652       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
653     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
654   } else if (theFeature->getKind() == "Sketch" &&
655     std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures()) {
656     // send event that sketch is prepared to be recomputed
657     static Events_ID anID = Events_Loop::eventByName("SketchPrepared");
658     std::shared_ptr<Events_Message> aMsg(new Events_Message(anID, this));
659     Events_Loop* aLoop = Events_Loop::loop();
660     // in case it is finish operation, flush for the sketch other events (#2450)
661     aLoop->flush(aLoop->eventByName(EVENT_OBJECT_UPDATED));
662     aLoop->send(aMsg);
663     // check that sub-elements of sketch are updated => sketch must be re-processed
664     std::set<FeaturePtr> aWholeR;
665     allReasons(theFeature, aWholeR);
666     std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
667     for(; aRIter != aWholeR.end(); aRIter++) {
668       if (myModified.find(*aRIter) != myModified.end()) {
669         processFeature(theFeature);
670         return true;
671       }
672     }
673   }
674
675 #ifdef DEB_UPDATE
676   std::cout<<"Update args "<<theFeature->name()<<std::endl;
677 #endif
678   // TestImport.py : after arguments are updated, theFeature may be removed
679   if (!theFeature->data()->isValid())
680     return false;
681   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
682   updateArguments(theFeature);
683
684   // add this feature to the processed right now to be able remove it from this list on
685   // update signal during this feature execution
686   myModified.erase(theFeature);
687   if (myNotPersistentRefs.find(theFeature) != myNotPersistentRefs.end())
688     myNotPersistentRefs.erase(theFeature);
689   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
690     theFeature->data()->execState(ModelAPI_StateDone);
691
692   // this checking must be after the composite feature sub-elements processing:
693   // composite feature status may depend on it's subelements
694   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) &&
695     theFeature->getKind() != "Part") {
696       // don't disable Part because it will make disabled all the features
697       // (performance and problems with the current feature)
698   #ifdef DEB_UPDATE
699     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
700   #endif
701     theFeature->eraseResults(false);
702     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
703     return true; // so, feature is modified (results are erased)
704   }
705
706   // execute feature if it must be updated
707   ModelAPI_ExecState aState = theFeature->data()->execState();
708   if (aFactory->validate(theFeature)) {
709     if (!isPostponedMain) {
710       bool aDoExecute = true;
711       if (myUpdateBlocked) {
712         if (!theFeature->isStable()) {
713           aDoExecute = true;
714         } else if (theFeature->results().size()) { // execute only not-results features
715           aDoExecute = !(theFeature->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
716                          theFeature->firstResult()->groupName() == ModelAPI_ResultPart::group());
717         } else {
718           aDoExecute = aState != ModelAPI_StateInvalidArgument;
719         }
720       }
721       if (aDoExecute) {
722         executeFeature(theFeature);
723       } else {
724         // store information that this feature must be executed later
725         theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
726       }
727     }
728   } else {
729     #ifdef DEB_UPDATE
730       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
731     #endif
732     theFeature->eraseResults(false);
733     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
734   }
735   return true;
736 }
737
738 void Model_Update::redisplayWithResults(
739   FeaturePtr theFeature, const ModelAPI_ExecState theState, bool theUpdateState)
740 {
741   // make updated and redisplay all results
742   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
743
744   std::list<ResultPtr> allResults;
745   ModelAPI_Tools::allResults(theFeature, allResults);
746   std::list<ResultPtr>::iterator aRIter = allResults.begin();
747   for (; aRIter != allResults.cend(); aRIter++) {
748     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
749     if (!aRes->isDisabled()) {
750       // update state only for enabled results
751       // (Placement Result Part may make the original Part Result as invalid)
752       if (theUpdateState)
753         aRes->data()->execState(theState);
754     }
755     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
756       aRes->data()->setUpdateID(theFeature->data()->updateID());
757     }
758     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
759   }
760   // to redisplay "presentable" feature (for ex. distance constraint)
761   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
762   if (theUpdateState)
763     theFeature->data()->execState(theState);
764 }
765
766 /// Updates the state by the referenced object: if something bad with it, set state for this one
767 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
768 {
769   if (theTarget) {
770     ModelAPI_ExecState aRefState = theTarget->data()->execState();
771     if (aRefState == ModelAPI_StateMustBeUpdated) {
772       if (theCurrent == ModelAPI_StateDone)
773         return ModelAPI_StateMustBeUpdated;
774     } else if (aRefState != ModelAPI_StateDone) {
775       return ModelAPI_StateInvalidArgument;
776     }
777   }
778   return theCurrent;
779 }
780
781 void Model_Update::updateArguments(FeaturePtr theFeature) {
782   // perform this method also for disabled features: to make "not done" state for
783   // features referenced to the active and modified features
784   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
785
786   ModelAPI_ExecState aState = theFeature->data()->execState();
787   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
788     aState = ModelAPI_StateMustBeUpdated;
789   }
790   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
791     aState = ModelAPI_StateMustBeUpdated;
792   // check the parameters state
793   // Integer
794   {
795     std::list<AttributePtr> anAttrinbutes =
796       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
797     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
798     for(; anIter != anAttrinbutes.end(); anIter++) {
799       AttributeIntegerPtr anAttribute =
800         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
801       if (anAttribute.get() && !anAttribute->text().empty()) {
802         if (myIsParamUpdated) {
803           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
804         }
805         if (anAttribute->expressionInvalid()) {
806           aState = ModelAPI_StateInvalidArgument;
807         }
808       }
809     }
810   }
811   // Double
812   {
813     std::list<AttributePtr> aDoubles =
814       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
815     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
816     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
817       AttributeDoublePtr aDouble =
818         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
819       if (aDouble.get() && !aDouble->text().empty()) {
820         if (myIsParamUpdated) {
821           ModelAPI_AttributeEvalMessage::send(aDouble, this);
822         }
823         if (aDouble->expressionInvalid()) {
824           aState = ModelAPI_StateInvalidArgument;
825         }
826       }
827     }
828   }
829   // Point
830   {
831     std::list<AttributePtr> anAttributes =
832       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
833     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
834     for(; anIter != anAttributes.end(); anIter++) {
835       AttributePointPtr aPointAttribute =
836         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
837       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() ||
838           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
839         if (myIsParamUpdated) {
840           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
841         }
842         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
843           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
844           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
845           aState = ModelAPI_StateInvalidArgument;
846       }
847     }
848   }
849   // Point2D
850   {
851     std::list<AttributePtr> anAttributes =
852       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
853     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
854     for(; anIter != anAttributes.end(); anIter++) {
855       AttributePoint2DPtr aPoint2DAttribute =
856         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
857       if (aPoint2DAttribute.get()) {
858         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() ||
859             !aPoint2DAttribute->textY().empty())) {
860           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
861         }
862         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
863           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
864           aState = ModelAPI_StateInvalidArgument;
865       }
866     }
867   }
868   // update the selection attributes if any
869   std::list<AttributePtr> aRefs =
870     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
871   std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
872   for (; aRefsIter != aRefs.end(); aRefsIter++) {
873     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
874       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
875     ObjectPtr aContext = aSel->context();
876     // update argument only if the referenced object is ready to use
877     if (aContext.get() && !aContext->isDisabled()) {
878       if (isReason(theFeature, aContext)) {
879         if (!aSel->update()) { // this must be done on execution since it may be long operation
880           bool isObligatory = !aFactory->isNotObligatory(
881             theFeature->getKind(), theFeature->data()->id(aSel)) &&
882             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
883           if (isObligatory)
884             aState = ModelAPI_StateInvalidArgument;
885         }
886       }
887     } else if (aContext.get()) {
888       // here it may be not obligatory, but if the reference is wrong, it should not be correct
889       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
890       if (isObligatory)
891         aState = ModelAPI_StateInvalidArgument;
892     }
893   }
894   // update the selection list attributes if any
895   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
896   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
897     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
898       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
899     for(int a = aSel->size() - 1; a >= 0; a--) {
900       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
901         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
902       if (aSelAttr) {
903         ObjectPtr aContext = aSelAttr->context();
904         // update argument only if the referenced object is ready to use
905         if (aContext.get() && !aContext->isDisabled() && !aSelAttr->isInvalid()) {
906           if (isReason(theFeature, aContext)) {
907             if (!aSelAttr->update()) {
908               bool isObligatory = !aFactory->isNotObligatory(
909                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
910                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
911               if (isObligatory)
912                 aState = ModelAPI_StateInvalidArgument;
913             }
914           }
915         } else if (aContext.get() || aSelAttr->isInvalid()) {
916           // here it may be not obligatory, but if the reference is wrong, it should not be correct
917           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
918           if (isObligatory)
919             aState = ModelAPI_StateInvalidArgument;
920         }
921       }
922     }
923   }
924
925   if (aState != ModelAPI_StateDone)
926     theFeature->data()->execState(aState);
927 }
928
929 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
930      std::shared_ptr<ModelAPI_Object> theReason)
931 {
932   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
933     ::iterator aReasonsIt = myModified.find(theFeature);
934   if (aReasonsIt != myModified.end()) {
935     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
936       return true; // any is reason if it contains itself
937     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
938     if (!aReasFeat.get()) { // try to get feature of this result
939       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
940       if (aReasRes.get())
941         aReasFeat = theReason->document()->feature(aReasRes);
942     }
943     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
944       return true;
945   }
946   // another try: postponed modification by not-persistences
947   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
948     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
949   if (aNotPersist != myNotPersistentRefs.end()) {
950     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
951     if (!aReasFeat.get()) { // try to get feature of this result
952       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
953       if (aReasRes.get())
954         aReasFeat = theReason->document()->feature(aReasRes);
955     }
956     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
957       return true;
958   }
959
960   // this case only for not-previewed items update state, nothing is changed in args for it
961   return false;
962 }
963
964 void Model_Update::executeFeature(FeaturePtr theFeature)
965 {
966 #ifdef DEB_UPDATE
967   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
968 #endif
969   // execute in try-catch to avoid internal problems of the feature
970   ModelAPI_ExecState aState = ModelAPI_StateDone;
971   theFeature->data()->execState(ModelAPI_StateDone);
972   try {
973     theFeature->execute();
974     if (theFeature->data()->execState() != ModelAPI_StateDone) {
975       aState = ModelAPI_StateExecFailed;
976     } else {
977       aState = ModelAPI_StateDone;
978     }
979   } catch(...) {
980     aState = ModelAPI_StateExecFailed;
981     Events_InfoMessage("Model_Update",
982       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
983   }
984   // The macro feature has to be deleted in any case even its execution is failed
985   myWaitForFinish.insert(theFeature);
986   if (aState != ModelAPI_StateDone) {
987     theFeature->eraseResults(false);
988   }
989   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
990   redisplayWithResults(theFeature, aState);
991 }
992
993 void Model_Update::updateStability(void* theSender)
994 {
995   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
996   if (theSender) {
997     bool added = false; // object may be was crated
998     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
999     if (aSender && aSender->document()) {
1000       FeaturePtr aFeatureSender =
1001         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1002       if (aFeatureSender.get()) {
1003         Model_Objects* aDocObjects =
1004           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1005         if (aDocObjects) {
1006           //aDocObjects->synchronizeBackRefs();
1007           // remove or add all concealment refs from this feature
1008           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1009           aSender->data()->referencesToObjects(aRefs);
1010           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1011             aRefIt = aRefs.begin();
1012           for(; aRefIt != aRefs.end(); aRefIt++) {
1013             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1014               // take into account only concealed references
1015               // (do not remove the sketch constraint and the edge on constraint edit)
1016               continue;
1017             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1018             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1019             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1020                // stability is only on results: feature to feature reference mean nested
1021               // features, that will remove nesting references
1022               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1023                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1024                 std::shared_ptr<Model_Data> aData =
1025                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1026                 if (aFeatureSender->isStable()) {
1027                   aData->addBackReference(aFeatureSender, aRefIt->first);
1028                 } else {
1029                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1030                   added = true; // remove of concealment may be caused creation of some result
1031                 }
1032               }
1033             }
1034           }
1035         }
1036       }
1037     }
1038     if (added) {
1039       static Events_Loop* aLoop = Events_Loop::loop();
1040       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1041       aLoop->flush(kEventCreated);
1042     }
1043   }
1044 }
1045
1046 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1047 {
1048   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1049   for(; anObj != theObjects.end(); anObj++) {
1050     std::list<AttributePtr> aRefs =
1051       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1052     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1053     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1054       std::shared_ptr<Model_AttributeSelection> aSel =
1055         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1056       aSel->updateInHistory();
1057     }
1058     // update the selection list attributes if any
1059     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1060     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1061       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1062         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1063       for(int a = aSel->size() - 1; a >= 0; a--) {
1064         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1065           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1066         if (aSelAttr.get())
1067           aSelAttr->updateInHistory();
1068       }
1069     }
1070   }
1071 }