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