Salome HOME
Optimization in the frames of issue #1668
[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 <ModelAPI_ResultConstruction.h>
44 #include <GeomAPI_Shape.h>
45 #include <GeomDataAPI_Point.h>
46 #include <GeomDataAPI_Dir.h>
47 #include <GeomDataAPI_Point2D.h>
48 #include <Events_Loop.h>
49 #include <Events_LongOp.h>
50 #include <Events_InfoMessage.h>
51 #include <Config_PropManager.h>
52
53 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
54 //#define DEB_UPDATE
55
56 Model_Update::Model_Update()
57 {
58   Events_Loop* aLoop = Events_Loop::loop();
59   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
60   aLoop->registerListener(this, kChangedEvent);
61   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
62   aLoop->registerListener(this, kCreatedEvent);
63   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
64   aLoop->registerListener(this, kUpdatedEvent);
65   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
66   aLoop->registerListener(this, kOpFinishEvent);
67   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
68   aLoop->registerListener(this, kOpAbortEvent);
69   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
70   aLoop->registerListener(this, kOpStartEvent);
71   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
72   aLoop->registerListener(this, kStabilityEvent);
73   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
74   aLoop->registerListener(this, kPreviewBlockedEvent);
75   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
76   aLoop->registerListener(this, kPreviewRequestedEvent);
77   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
78   aLoop->registerListener(this, kReorderEvent);
79   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
80   aLoop->registerListener(this, kUpdatedSel);
81   static const Events_ID kAutoRecomp = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
82   aLoop->registerListener(this, kAutoRecomp);
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   // process 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
244 #ifdef DEB_UPDATE
245   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
246 #endif
247   // check the automatic update flag on any event
248   bool aNewAutomaticState = ModelAPI_Session::get()->isAutoUpdateBlocked();
249   if (myUpdateBlocked != aNewAutomaticState) {
250     myUpdateBlocked = aNewAutomaticState;
251     if (!myUpdateBlocked) { // process all modified features, even if preview is blocked
252       bool aPreviewBlockedState = myIsPreviewBlocked; // to update the selected arguments
253       myIsPreviewBlocked = false;
254       // iterate everything and add features in state "MustBeUpdated" into modified
255       std::list<std::shared_ptr<ModelAPI_Document> > allDocs =
256         ModelAPI_Session::get()->allOpenedDocuments();
257       std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = allDocs.begin();
258       for(; aDoc != allDocs.end(); aDoc++) {
259         std::list<std::shared_ptr<ModelAPI_Feature> > allFeats = (*aDoc)->allFeatures();
260         std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFeat = allFeats.begin();
261         for(; aFeat != allFeats.end(); aFeat++) {
262           if ((*aFeat)->data()->isValid() &&
263             (*aFeat)->data()->execState() == ModelAPI_StateMustBeUpdated) {
264             addModified(*aFeat, FeaturePtr());
265           }
266         }
267       }
268       processFeatures();
269       myIsPreviewBlocked = myIsPreviewBlocked;
270     }
271   }
272
273   if (theMessage->eventID() == kStabilityEvent) {
274     updateStability(theMessage->sender());
275     return;
276   }
277   if (theMessage->eventID() == kPreviewBlockedEvent) {
278     myIsPreviewBlocked = true;
279     return;
280   }
281   if (theMessage->eventID() == kPreviewRequestedEvent) {
282     if (myIsPreviewBlocked) {
283       bool anUpdateState = myUpdateBlocked;
284       myUpdateBlocked = false;
285       myIsPreviewBlocked = false;
286       processFeatures();
287       myIsPreviewBlocked = true;
288       myUpdateBlocked = anUpdateState;
289     }
290     return;
291   }
292   if (theMessage->eventID() == kUpdatedSel) {
293     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
294         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
295     updateSelection(aMsg->objects());
296   }
297   // creation is added to "update" to avoid recomputation twice:
298   // on create and immediately after on update
299   if (theMessage->eventID() == kCreatedEvent) {
300     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
301         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
302     const std::set<ObjectPtr>& anObjs = aMsg->objects();
303     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
304     std::list<ObjectPtr> aFeatures, aResults;
305     for(; anObjIter != anObjs.cend(); anObjIter++) {
306       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
307         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) {
308           // results creation means enabling, not update
309           aFeatures.push_back(*anObjIter);
310         } else {
311           aResults.push_back(*anObjIter);
312         }
313       }
314     }
315     ModelAPI_EventCreator::get()->sendUpdated(aFeatures, kUpdatedEvent);
316     ModelAPI_EventCreator::get()->sendUpdated(aResults, kRedisplayEvent);
317     return;
318   }
319   if (theMessage->eventID() == kUpdatedEvent) {
320     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
321         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
322     const std::set<ObjectPtr>& anObjs = aMsg->objects();
323     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
324     bool aSomeModified = false; // check that features not changed: only redisplay is needed
325     for(; anObjIter != anObjs.cend(); anObjIter++) {
326       if (!(*anObjIter)->data()->isValid())
327         continue;
328 #ifdef DEB_UPDATE
329       std::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<
330         " "<<(*anObjIter)->data()->name()<<std::endl;
331 #endif
332       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
333         myIsParamUpdated = true;
334       }
335       // on undo/redo, abort do not update persistent features
336       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
337       if (anUpdated.get()) {
338         if (addModified(anUpdated, FeaturePtr()))
339           aSomeModified = true;
340         if (myUpdateBlocked) { // execute this feature anyway to show the current result
341           /*if (!anUpdated->isStable() && anUpdated->results().size() && (
342               anUpdated->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
343               anUpdated->firstResult()->groupName() == ModelAPI_ResultPart::group())) {
344             if (aFactory->validate(anUpdated)) {
345               executeFeature(anUpdated);
346               redisplayWithResults(anUpdated, ModelAPI_StateNothing, false);
347               static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
348               aLoop->flush(EVENT_DISP);
349             }
350           }*/
351         }
352       } else {
353         // process the updated result as update of features that refers to this result
354         const std::set<std::shared_ptr<ModelAPI_Attribute> >&
355           aRefs = (*anObjIter)->data()->refsToMe();
356         std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
357         FeaturePtr aReason;
358         ResultPtr aReasonResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter);
359         if (aReasonResult.get())
360           aReason = (*anObjIter)->document()->feature(aReasonResult);
361         for(; aRefIter != aRefs.cend(); aRefIter++) {
362           if (!(*aRefIter)->owner()->data()->isValid())
363             continue;
364           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
365           if (anUpdated.get()) {
366             if (addModified(anUpdated, aReason))
367               aSomeModified = true;
368           }
369         }
370       }
371     }
372     // this event is for solver update, not here, do not react immediately
373     if (aSomeModified) {
374         processFeatures();
375     }
376   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
377       theMessage->eventID() == kOpStartEvent) {
378     myIsPreviewBlocked = false;
379
380     if (theMessage->eventID() == kOpFinishEvent) {// if update is blocked, skip
381       myIsFinish = true;
382       // add features that wait for finish as modified
383       std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >::
384         iterator aFeature = myProcessOnFinish.begin();
385       for(; aFeature != myProcessOnFinish.end(); aFeature++) {
386         if (aFeature->first->data()->isValid()) {// there may be already removed while wait
387           if (aFeature->second.empty()) {
388             addModified(aFeature->first, FeaturePtr());
389             continue;
390           }
391           std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aReasons;
392           for(aReasons = aFeature->second.begin(); aReasons != aFeature->second.end(); aReasons++){
393             addModified(aFeature->first, *aReasons);
394           }
395         }
396       }
397       myIsFinish = false;
398     }
399     // processed features must be only on finish, so clear anyway (to avoid re-import on load)
400     myProcessOnFinish.clear();
401
402     // #2156: current must be sketch, left after the macro execution
403     DocumentPtr anActiveDoc = ModelAPI_Session::get()->activeDocument();
404     FeaturePtr aCurrent;
405     if (anActiveDoc.get())
406       aCurrent = anActiveDoc->currentFeature(false);
407
408     if (!(theMessage->eventID() == kOpStartEvent)) {
409       processFeatures(false);
410     }
411
412     if (anActiveDoc.get() && aCurrent.get() && aCurrent->data()->isValid()) {
413       if (anActiveDoc->currentFeature(false) != aCurrent &&
414           ModelAPI_Tools::compositeOwner(anActiveDoc->currentFeature(false)) == aCurrent)
415         anActiveDoc->setCurrentFeature(aCurrent, false); // #2156 make the current feature back
416     }
417
418     // remove all macros before clearing all created
419     std::set<FeaturePtr>::iterator anUpdatedIter = myWaitForFinish.begin();
420     while(anUpdatedIter != myWaitForFinish.end()) {
421       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
422       if (aFeature.get()) {
423         // remove macro on finish
424         if (aFeature->isMacro()) {
425           aFeature->document()->removeFeature(aFeature);
426           myWaitForFinish.erase(aFeature);
427         }
428         // to avoid the map update problems on "remove"
429         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
430           anUpdatedIter = myWaitForFinish.begin();
431         } else {
432           anUpdatedIter++;
433         }
434       } else {
435         anUpdatedIter++;
436       }
437     }
438     // the redisplay signal should be flushed in order
439     // to erase the feature presentation in the viewer
440     // if should be done after removeFeature() of document,
441     // by this reason, upper processFeatures() do not perform this flush
442     Events_Loop::loop()->flush(kRedisplayEvent);
443
444     // in the end of transaction everything is updated, so clear the old objects
445     myIsParamUpdated = false;
446     myWaitForFinish.clear();
447   } else if (theMessage->eventID() == kReorderEvent) {
448     std::shared_ptr<ModelAPI_OrderUpdatedMessage> aMsg =
449       std::dynamic_pointer_cast<ModelAPI_OrderUpdatedMessage>(theMessage);
450     if (aMsg->reordered().get())
451       addModified(aMsg->reordered(), aMsg->reordered()); // to update all attributes
452   }
453 }
454
455 void Model_Update::processFeatures(const bool theFlushRedisplay)
456 {
457    // perform update of everything if it is not performed right now or any preview is blocked
458   if (!myIsProcessed && !myIsPreviewBlocked) {
459     myIsProcessed = true;
460     #ifdef DEB_UPDATE
461       std::cout<<"****** Start processing"<<std::endl;
462     #endif
463
464     while(!myModified.empty()) {
465       processFeature(myModified.begin()->first);
466     }
467     myIsProcessed = false;
468
469     // to update the object browser if something is updated/created during executions
470     static Events_Loop* aLoop = Events_Loop::loop();
471     static const Events_ID kCreatedEvent= aLoop->eventByName(EVENT_OBJECT_CREATED);
472     aLoop->flush(kCreatedEvent);
473     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
474     aLoop->flush(kUpdatedEvent);
475
476     // flush to update display
477     if (theFlushRedisplay) {
478       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
479       aLoop->flush(EVENT_DISP);
480     }
481     #ifdef DEB_UPDATE
482       std::cout<<"****** End processing"<<std::endl;
483     #endif
484     myProcessed.clear();
485   }
486 }
487
488 // collects all the features this feature depends on: reasons
489 static void allReasons(FeaturePtr theFeature, std::set<FeaturePtr>& theReasons) {
490   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
491   theFeature->data()->referencesToObjects(aDeps);
492   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
493     anAttrsIter = aDeps.begin();
494   for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
495     if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
496       std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
497       for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
498         FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
499         if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
500           ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
501           if (aDepRes.get()) {
502             aDepFeat = (*aDepIter)->document()->feature(aDepRes);
503           }
504         }
505         if (aDepFeat.get() && aDepFeat->data()->isValid()) {
506           theReasons.insert(aDepFeat);
507         }
508       }
509     }
510   }
511   if (theFeature->getKind() == "Part") {
512     // part is not depended on its subs directly, but subs must be iterated anyway
513     CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
514     int aNum = aPart->numberOfSubs();
515     for(int a = 0; a < aNum; a++) {
516       FeaturePtr aSub = aPart->subFeature(a);
517       if (aSub.get() && aSub->data()->isValid()) {
518         theReasons.insert(aSub);
519       }
520     }
521   }
522 }
523
524 bool Model_Update::processFeature(FeaturePtr theFeature)
525 {
526   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
527
528   if (!theFeature->data()->isValid()) { // deleted feature, just remove from all containers
529     if (myModified.find(theFeature) != myModified.end())
530       myModified.erase(theFeature);
531     return false;
532   }
533
534   if (theFeature->isPersistentResult()) {
535     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
536       return false;
537   }
538
539   if (myProcessed.find(theFeature) == myProcessed.end()) {
540     myProcessed[theFeature] = 0;
541   } else {
542     int aCount = myProcessed[theFeature];
543     if (aCount > 100) {
544       // too many repetition of processing (in VS it may crash on 330 with stack overflow)
545       Events_InfoMessage("Model_Update",
546         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
547       // to stop iteration
548       myModified.clear();
549       return false;
550     }
551     myProcessed[theFeature] = aCount + 1;
552   }
553
554   // check this feature is not yet checked or processed
555   bool aIsModified = myModified.find(theFeature) != myModified.end();
556   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
557     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
558       aIsModified = true;
559       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
560       // contains itself, so, we don't know which was the reason and the reason is any
561       aNewSet.insert(theFeature);
562       myModified[theFeature] = aNewSet;
563     }
564   }
565
566 #ifdef DEB_UPDATE
567     std::cout<<"* Process feature "<<theFeature->name()<<std::endl;
568 #endif
569
570   // update the sketch plane before the sketch sub-elements are recomputed
571   // (otherwise sketch will update plane, modify subs, after executed, but with old subs edges)
572     if (aIsModified && theFeature->getKind() == "Sketch") {
573 #ifdef DEB_UPDATE
574       std::cout << "****** Update sketch args " << theFeature->name() << std::endl;
575 #endif
576       AttributeSelectionPtr anExtSel = theFeature->selection("External");
577       if (anExtSel.get()) {
578         ResultPtr aContext = anExtSel->context();
579         if (aContext.get() && aContext->document().get()) {
580           FeaturePtr anExtBase = aContext->document()->feature(aContext);
581           if (anExtBase.get()) {
582             processFeature(anExtBase);
583           }
584           std::shared_ptr<GeomDataAPI_Point> anOrigin =
585             std::dynamic_pointer_cast<GeomDataAPI_Point>(theFeature->attribute("Origin"));
586           double anOX = anOrigin->x(), anOY = anOrigin->y(), anOZ = anOrigin->z();
587           std::shared_ptr<GeomDataAPI_Dir> aDir =
588             std::dynamic_pointer_cast<GeomDataAPI_Dir>(theFeature->attribute("DirX"));
589           double aDX = aDir->x(), aDY = aDir->y(), aDZ = aDir->z();
590           std::shared_ptr<GeomDataAPI_Dir> aNorm =
591             std::dynamic_pointer_cast<GeomDataAPI_Dir>(theFeature->attribute("Norm"));
592           double aNX = aNorm->x(), aNY = aNorm->y(), aNZ = aNorm->z();
593           // update sketch plane
594           updateArguments(theFeature);
595           theFeature->attributeChanged("External"); // to recompute origin, direction and normal
596           // check it is updated, so all must be changed
597           if (anOrigin->x() != anOX || anOrigin->y() != anOY || anOrigin->z() != anOZ ||
598               aDir->x() != aDX || aDir->y() != aDY || aDir->z() != aDZ ||
599               aNorm->x() != aNX || aNorm->y() != aNY || aNorm->z() != aNZ)
600           {
601             std::set<FeaturePtr> aWholeR;
602             allReasons(theFeature, aWholeR);
603             std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
604             for (; aRIter != aWholeR.end(); aRIter++) {
605               if ((*aRIter)->data()->selection("External").get())
606                 (*aRIter)->attributeChanged("External");
607             }
608           }
609         }
610       }
611     }
612
613   if (!aIsModified) { // no modification is needed
614     return false;
615   }
616
617   // evaluate parameter before the sub-elements update:
618   // it updates dependencies on evaluation (#1085)
619   if (theFeature->getKind() == "Parameter") {
620     theFeature->execute();
621   }
622
623   bool isReferencedInvalid = false;
624   // check all features this feature depended on (recursive call of updateFeature)
625   std::set<FeaturePtr>& aReasons = myModified[theFeature];
626   bool allSubsUsed = aReasons.find(theFeature) != aReasons.end();
627   if (allSubsUsed) {
628     // add all subs in aReasons and temporary remove "theFeature" to avoid processing itself
629     allReasons(theFeature, aReasons);
630     aReasons.erase(theFeature);
631   }
632   // take reasons one by one (they may be added during the feature process
633   // (circle by the radius of sketch)
634   std::set<FeaturePtr> aProcessedReasons;
635   while(!aReasons.empty()) {
636     FeaturePtr aReason = *(aReasons.begin());
637 #ifdef DEB_UPDATE
638     //cout<<theFeature->name()<<" process next reason "<<aReason->name()<<endl;
639 #endif
640     if (aReason != theFeature && (aReason)->data()->isValid()) {
641       if (processFeature(aReason))
642         aIsModified = true;
643       // check validity of aReason once again because it may be removed by dependent feature
644       // (e.g. by SketchPlugin_IntersectionPoint)
645       if (!aReason->data()->isValid() ||
646           aReason->data()->execState() == ModelAPI_StateInvalidArgument)
647         isReferencedInvalid = true;
648     }
649     // searching for the next not used reason
650     aProcessedReasons.insert(aReason);
651     aReasons.erase(aReason);
652   }
653   // restore the modified reasons: they will be used in the update of arguments
654   if (allSubsUsed) { // restore theFeature in this set
655     aProcessedReasons.insert(theFeature);
656   }
657   myModified[theFeature] = aProcessedReasons;
658
659   // do not execute the composite that contains the current
660   bool isPostponedMain = false;
661   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
662   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
663     CompositeFeaturePtr aCurrentOwner =
664       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
665     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
666   } else if (theFeature->getKind() == "Sketch" &&
667     std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures()) {
668     // send event that sketch is prepared to be recomputed
669     static Events_ID anID = Events_Loop::eventByName("SketchPrepared");
670     std::shared_ptr<Events_Message> aMsg(new Events_Message(anID, this));
671     Events_Loop* aLoop = Events_Loop::loop();
672     // in case it is finish operation, flush for the sketch other events (#2450)
673     aLoop->flush(aLoop->eventByName(EVENT_OBJECT_UPDATED));
674     aLoop->send(aMsg);
675     // check that sub-elements of sketch are updated => sketch must be re-processed
676     std::set<FeaturePtr> aWholeR;
677     allReasons(theFeature, aWholeR);
678     std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
679     for(; aRIter != aWholeR.end(); aRIter++) {
680       if (myModified.find(*aRIter) != myModified.end()) {
681         processFeature(theFeature);
682         return true;
683       }
684     }
685   }
686
687 #ifdef DEB_UPDATE
688   std::cout<<"Update args "<<theFeature->name()<<std::endl;
689 #endif
690   // TestImport.py : after arguments are updated, theFeature may be removed
691   if (!theFeature->data()->isValid())
692     return false;
693   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
694   updateArguments(theFeature);
695
696   // add this feature to the processed right now to be able remove it from this list on
697   // update signal during this feature execution
698   myModified.erase(theFeature);
699   if (myNotPersistentRefs.find(theFeature) != myNotPersistentRefs.end())
700     myNotPersistentRefs.erase(theFeature);
701   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
702     theFeature->data()->execState(ModelAPI_StateDone);
703
704   // this checking must be after the composite feature sub-elements processing:
705   // composite feature status may depend on it's sub-elements
706   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) &&
707     theFeature->getKind() != "Part") {
708       // don't disable Part because it will make disabled all the features
709       // (performance and problems with the current feature)
710   #ifdef DEB_UPDATE
711     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
712   #endif
713     theFeature->eraseResults(false);
714     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
715     return true; // so, feature is modified (results are erased)
716   }
717
718   // execute feature if it must be updated
719   ModelAPI_ExecState aState = theFeature->data()->execState();
720   if (aFactory->validate(theFeature)) {
721     if (!isPostponedMain) {
722       bool aDoExecute = true;
723       if (myUpdateBlocked) {
724         if (!theFeature->isStable()) {
725           aDoExecute = true;
726         } else if (theFeature->results().size()) { // execute only not-results features
727           aDoExecute = !(theFeature->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
728             theFeature->firstResult()->groupName() == ModelAPI_ResultPart::group() ||
729             theFeature->getKind() == "Sketch");
730         } else {
731           aDoExecute = aState != ModelAPI_StateInvalidArgument;
732         }
733       }
734       if (aDoExecute) {
735         executeFeature(theFeature);
736       } else {
737         // store information that this feature must be executed later
738         theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
739       }
740     }
741   } else {
742     #ifdef DEB_UPDATE
743       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
744     #endif
745     theFeature->eraseResults(false);
746     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
747   }
748   return true;
749 }
750
751 void Model_Update::redisplayWithResults(
752   FeaturePtr theFeature, const ModelAPI_ExecState theState, bool theUpdateState)
753 {
754   // make updated and redisplay all results
755   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
756
757   std::list<ResultPtr> allResults;
758   ModelAPI_Tools::allResults(theFeature, allResults);
759   std::list<ResultPtr>::iterator aRIter = allResults.begin();
760   for (; aRIter != allResults.cend(); aRIter++) {
761     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
762     if (!aRes->isDisabled()) {
763       // update state only for enabled results
764       // (Placement Result Part may make the original Part Result as invalid)
765       if (theUpdateState)
766         aRes->data()->execState(theState);
767     }
768     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
769       aRes->data()->setUpdateID(theFeature->data()->updateID());
770     }
771     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
772   }
773   // to redisplay "presentable" feature (for ex. distance constraint)
774   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
775   if (theUpdateState)
776     theFeature->data()->execState(theState);
777 }
778
779 /// Updates the state by the referenced object: if something bad with it, set state for this one
780 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
781 {
782   if (theTarget) {
783     ModelAPI_ExecState aRefState = theTarget->data()->execState();
784     if (aRefState == ModelAPI_StateMustBeUpdated) {
785       if (theCurrent == ModelAPI_StateDone)
786         return ModelAPI_StateMustBeUpdated;
787     } else if (aRefState != ModelAPI_StateDone) {
788       return ModelAPI_StateInvalidArgument;
789     }
790   }
791   return theCurrent;
792 }
793
794 void Model_Update::updateArguments(FeaturePtr theFeature) {
795   // perform this method also for disabled features: to make "not done" state for
796   // features referenced to the active and modified features
797   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
798
799   ModelAPI_ExecState aState = theFeature->data()->execState();
800   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
801     aState = ModelAPI_StateMustBeUpdated;
802   }
803   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
804     aState = ModelAPI_StateMustBeUpdated;
805   // check the parameters state
806   // Integer
807   {
808     std::list<AttributePtr> anAttrinbutes =
809       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
810     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
811     for(; anIter != anAttrinbutes.end(); anIter++) {
812       AttributeIntegerPtr anAttribute =
813         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
814       if (anAttribute.get() && !anAttribute->text().empty()) {
815         if (myIsParamUpdated) {
816           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
817         }
818         if (anAttribute->expressionInvalid()) {
819           aState = ModelAPI_StateInvalidArgument;
820         }
821       }
822     }
823   }
824   // Double
825   {
826     std::list<AttributePtr> aDoubles =
827       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
828     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
829     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
830       AttributeDoublePtr aDouble =
831         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
832       if (aDouble.get() && !aDouble->text().empty()) {
833         if (myIsParamUpdated) {
834           ModelAPI_AttributeEvalMessage::send(aDouble, this);
835         }
836         if (aDouble->expressionInvalid()) {
837           aState = ModelAPI_StateInvalidArgument;
838         }
839       }
840     }
841   }
842   // Point
843   {
844     std::list<AttributePtr> anAttributes =
845       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
846     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
847     for(; anIter != anAttributes.end(); anIter++) {
848       AttributePointPtr aPointAttribute =
849         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
850       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() ||
851           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
852         if (myIsParamUpdated) {
853           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
854         }
855         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
856           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
857           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
858           aState = ModelAPI_StateInvalidArgument;
859       }
860     }
861   }
862   // Point2D
863   {
864     std::list<AttributePtr> anAttributes =
865       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
866     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
867     for(; anIter != anAttributes.end(); anIter++) {
868       AttributePoint2DPtr aPoint2DAttribute =
869         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
870       if (aPoint2DAttribute.get()) {
871         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() ||
872             !aPoint2DAttribute->textY().empty())) {
873           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
874         }
875         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
876           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
877           aState = ModelAPI_StateInvalidArgument;
878       }
879     }
880   }
881   // update the selection attributes if any
882   std::list<AttributePtr> aRefs =
883     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
884   std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
885   for (; aRefsIter != aRefs.end(); aRefsIter++) {
886     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
887       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
888     ObjectPtr aContext = aSel->context();
889     // update argument only if the referenced object is ready to use
890     if (aContext.get() && !aContext->isDisabled()) {
891       if (isReason(theFeature, aContext)) {
892         if (!aSel->update()) { // this must be done on execution since it may be long operation
893           bool isObligatory = !aFactory->isNotObligatory(
894             theFeature->getKind(), theFeature->data()->id(aSel)) &&
895             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
896           if (isObligatory)
897             aState = ModelAPI_StateInvalidArgument;
898         }
899       }
900     } else if (aContext.get()) {
901       // here it may be not obligatory, but if the reference is wrong, it should not be correct
902       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
903       if (isObligatory)
904         aState = ModelAPI_StateInvalidArgument;
905     }
906   }
907   // update the selection list attributes if any
908   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
909   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
910     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
911       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
912     for(int a = aSel->size() - 1; a >= 0; a--) {
913       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
914         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
915       if (aSelAttr) {
916         ObjectPtr aContext = aSelAttr->context();
917         // update argument only if the referenced object is ready to use
918         if (aContext.get() && !aContext->isDisabled()) {
919           if (isReason(theFeature, aContext)) {
920             if (!aSelAttr->update()) {
921               bool isObligatory = !aFactory->isNotObligatory(
922                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
923                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
924               if (isObligatory)
925                 aState = ModelAPI_StateInvalidArgument;
926             }
927           }
928         } else if (aContext.get()) {
929           // here it may be not obligatory, but if the reference is wrong, it should not be correct
930           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
931           if (isObligatory)
932             aState = ModelAPI_StateInvalidArgument;
933         }
934       }
935     }
936   }
937
938   if (aState != ModelAPI_StateDone)
939     theFeature->data()->execState(aState);
940 }
941
942 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
943      std::shared_ptr<ModelAPI_Object> theReason)
944 {
945   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
946     ::iterator aReasonsIt = myModified.find(theFeature);
947   if (aReasonsIt != myModified.end()) {
948     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
949       return true; // any is reason if it contains itself
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 (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
957       return true;
958   }
959   // another try: postponed modification by not-persistences
960   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
961     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
962   if (aNotPersist != myNotPersistentRefs.end()) {
963     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
964     if (!aReasFeat.get()) { // try to get feature of this result
965       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
966       if (aReasRes.get())
967         aReasFeat = theReason->document()->feature(aReasRes);
968     }
969     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
970       return true;
971   }
972
973   // this case only for not-previewed items update state, nothing is changed in args for it
974   return false;
975 }
976
977 void Model_Update::executeFeature(FeaturePtr theFeature)
978 {
979 #ifdef DEB_UPDATE
980   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
981 #endif
982   // execute in try-catch to avoid internal problems of the feature
983   ModelAPI_ExecState aState = ModelAPI_StateDone;
984   theFeature->data()->execState(ModelAPI_StateDone);
985   try {
986     theFeature->execute();
987     if (theFeature->data()->execState() != ModelAPI_StateDone) {
988       aState = ModelAPI_StateExecFailed;
989     } else {
990       aState = ModelAPI_StateDone;
991     }
992   } catch(...) {
993     aState = ModelAPI_StateExecFailed;
994     Events_InfoMessage("Model_Update",
995       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
996   }
997   // The macro feature has to be deleted in any case even its execution is failed
998   myWaitForFinish.insert(theFeature);
999   if (aState != ModelAPI_StateDone) {
1000     theFeature->eraseResults(false);
1001   }
1002   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
1003   redisplayWithResults(theFeature, aState);
1004 }
1005
1006 // it is called on GUI edit of feature start
1007 // LCOV_EXCL_START
1008 void Model_Update::updateStability(void* theSender)
1009 {
1010   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1011   if (theSender) {
1012     bool added = false; // object may be was crated
1013     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
1014     if (aSender && aSender->document()) {
1015       FeaturePtr aFeatureSender =
1016         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1017       if (aFeatureSender.get()) {
1018         Model_Objects* aDocObjects =
1019           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1020         if (aDocObjects) {
1021           //aDocObjects->synchronizeBackRefs();
1022           // remove or add all concealment refs from this feature
1023           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1024           aSender->data()->referencesToObjects(aRefs);
1025           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1026             aRefIt = aRefs.begin();
1027           for(; aRefIt != aRefs.end(); aRefIt++) {
1028             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1029               // take into account only concealed references
1030               // (do not remove the sketch constraint and the edge on constraint edit)
1031               continue;
1032             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1033             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1034             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1035                // stability is only on results: feature to feature reference mean nested
1036               // features, that will remove nesting references
1037               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1038                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1039                 std::shared_ptr<Model_Data> aData =
1040                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1041                 if (aFeatureSender->isStable()) {
1042                   aData->addBackReference(aFeatureSender, aRefIt->first);
1043                 } else {
1044                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1045                   added = true; // remove of concealment may be caused creation of some result
1046                 }
1047               }
1048             }
1049           }
1050         }
1051       }
1052     }
1053     if (added) {
1054       static Events_Loop* aLoop = Events_Loop::loop();
1055       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1056       aLoop->flush(kEventCreated);
1057     }
1058   }
1059 }
1060 // LCOV_EXCL_STOP
1061
1062 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1063 {
1064   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1065   for(; anObj != theObjects.end(); anObj++) {
1066     std::list<AttributePtr> aRefs =
1067       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1068     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1069     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1070       std::shared_ptr<Model_AttributeSelection> aSel =
1071         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1072       aSel->updateInHistory();
1073     }
1074     // update the selection list attributes if any
1075     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1076     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1077       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1078         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1079       for(int a = aSel->size() - 1; a >= 0; a--) {
1080         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1081           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1082         if (aSelAttr.get())
1083           aSelAttr->updateInHistory();
1084       }
1085     }
1086   }
1087 }