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