Salome HOME
Fix for the #19720 : Wrong part position after reloading hdf. If the part is hidden...
[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 <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 Model_Update::Model_Update()
56 {
57   Events_Loop* aLoop = Events_Loop::loop();
58   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
59   aLoop->registerListener(this, kChangedEvent);
60   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
61   aLoop->registerListener(this, kCreatedEvent);
62   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
63   aLoop->registerListener(this, kUpdatedEvent);
64   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
65   aLoop->registerListener(this, kOpFinishEvent);
66   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
67   aLoop->registerListener(this, kOpAbortEvent);
68   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
69   aLoop->registerListener(this, kOpStartEvent);
70   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
71   aLoop->registerListener(this, kStabilityEvent);
72   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
73   aLoop->registerListener(this, kPreviewBlockedEvent);
74   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
75   aLoop->registerListener(this, kPreviewRequestedEvent);
76   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
77   aLoop->registerListener(this, kReorderEvent);
78   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
79   aLoop->registerListener(this, kUpdatedSel);
80   static const Events_ID kAutoRecomp = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
81   aLoop->registerListener(this, kAutoRecomp);
82
83   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
84   myIsParamUpdated = false;
85   myIsFinish = false;
86   myIsProcessed = false;
87   myIsPreviewBlocked = false;
88   myUpdateBlocked = false;
89 }
90
91 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
92
93   if (!theFeature->data()->isValid())
94     return false; // delete an extrusion created on the sketch
95
96
97   bool isNotExecuted = theFeature->isPersistentResult() &&
98     !std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures();
99   if (isNotExecuted) {
100     redisplayWithResults(theFeature, ModelAPI_StateNothing, false); // redisplay even not executed
101     if (!theReason.get()) // no reason => no construction reason
102       return false;
103     if (myNotPersistentRefs.find(theFeature) == myNotPersistentRefs.end()) {
104       myNotPersistentRefs[theFeature].insert(theReason);
105     } else {
106       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
107       aNewSet.insert(theReason);
108       myNotPersistentRefs[theFeature] = aNewSet;
109     }
110     return false;
111   }
112
113   // update arguments for "apply button" state change
114   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
115     if (theReason.get())
116       myProcessOnFinish[theFeature].insert(theReason);
117     else if (myProcessOnFinish.find(theFeature) == myProcessOnFinish.end())
118       myProcessOnFinish[theFeature] = std::set<std::shared_ptr<ModelAPI_Feature> >();
119 #ifdef DEB_UPDATE
120       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
121 #endif
122     // keeps the currently updated features to avoid infinitive cycling here: where feature on
123     // "updateArguments" sends "updated" (in selection attribute) and goes here again
124     static std::set<FeaturePtr> aCurrentlyUpdated;
125     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
126       aCurrentlyUpdated.insert(theFeature);
127       updateArguments(theFeature);
128       aCurrentlyUpdated.erase(theFeature);
129     }
130     // make it without conditions otherwise the apply button may have a bad state
131     theFeature->data()->execState(ModelAPI_StateDone);
132     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
133      // need to be validated to update the "Apply" state if not previewed
134     aFactory->validate(theFeature);
135
136     // to redisplay split's arguments presentation, even result is not computed
137     if (!theFeature->isPreviewNeeded()) {
138       static Events_Loop* aLoop = Events_Loop::loop();
139       static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
140       ModelAPI_EventCreator::get()->sendUpdated(theFeature, kRedisplayEvent);
141       aLoop->flush(kRedisplayEvent);
142     }
143
144     if (!myIsPreviewBlocked)
145       return true;
146   }
147   if (myModified.find(theFeature) != myModified.end()) {
148     if (theReason.get()) {
149 #ifdef DEB_UPDATE
150       //std::cout<<"*** Add already modified "
151       //   <<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
152 #endif
153       myModified[theFeature].insert(theReason);
154     }
155     return true;
156   }
157   // do not add the disabled, but possibly the sub-elements are not disabled
158   bool aIsDisabled = theFeature->isDisabled();
159   if (!aIsDisabled) {
160     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
161     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated ||
162         theFeature->data()->execState() == ModelAPI_StateInvalidArgument || // issue 1519
163         theFeature->data()->execState() == ModelAPI_StateExecFailed) {
164       // do not forget that in this case all were the reasons
165       aNewSet.insert(theFeature);
166     } else {
167       if (theReason.get())
168         aNewSet.insert(theReason);
169     }
170     myModified[theFeature] = aNewSet;
171 #ifdef DEB_UPDATE
172     if (theReason.get()) {
173       //std::cout<<"*** Add modified "<<theFeature->name()
174       //  <<" reason "<<theReason->name()<<std::endl;
175     } else {
176       //std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
177     }
178 #endif
179   } else { // will be updated during the finish of the operation, or when it becomes enabled
180     if (theFeature->data()->execState() == ModelAPI_StateDone ||
181         theFeature->data()->execState() == ModelAPI_StateExecFailed) // fix issue 1819
182       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
183     else
184       return true; // do not need iteration deeply if it is already marked as modified or so
185 #ifdef DEB_UPDATE
186     //std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
187 #endif
188   }
189   // clear processed and fill modified recursively
190   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
191   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
192   for(; aRefIter != aRefs.cend(); aRefIter++) {
193     if ((*aRefIter)->isArgument()) {
194       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
195       if (aReferenced.get()) {
196         addModified(aReferenced, theFeature);
197       }
198     }
199   }
200   // process also results
201   std::list<ResultPtr> allResults; // list of this feature and results
202   ModelAPI_Tools::allResults(theFeature, allResults);
203   std::list<ResultPtr>::iterator aRes = allResults.begin();
204   for(; aRes != allResults.end(); aRes++) {
205     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aResRefs = (*aRes)->data()->refsToMe();
206     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRIter = aResRefs.cbegin();
207     for(; aRIter != aResRefs.cend(); aRIter++) {
208       if ((*aRIter)->isArgument()) {
209         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRIter)->owner());
210         if (aReferenced.get()) {
211           addModified(aReferenced, theFeature);
212         }
213       }
214     }
215   }
216
217   // also add part feature that contains this feature to the modified
218   if (theFeature->document()->kind() != "PartSet") {
219     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
220       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
221     if (aPart.get())
222       addModified(aPart, theFeature);
223   }
224   return true;
225 }
226
227 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
228 {
229   static Events_Loop* aLoop = Events_Loop::loop();
230   //static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
231   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
232   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
233   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
234   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
235   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
236   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
237   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
238   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
239   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
240   static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
241   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
242
243 #ifdef DEB_UPDATE
244   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
245 #endif
246   // check the automatic update flag on any event
247   bool aNewAutomaticState = ModelAPI_Session::get()->isAutoUpdateBlocked();
248   if (myUpdateBlocked != aNewAutomaticState) {
249     myUpdateBlocked = aNewAutomaticState;
250     if (!myUpdateBlocked) { // process all modified features, even if preview is blocked
251       bool aPreviewBlockedState = myIsPreviewBlocked; // to update the selected arguments
252       myIsPreviewBlocked = false;
253       // iterate everything and add features in state "MustBeUpdated" into modified
254       std::list<std::shared_ptr<ModelAPI_Document> > allDocs =
255         ModelAPI_Session::get()->allOpenedDocuments();
256       std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = allDocs.begin();
257       for(; aDoc != allDocs.end(); aDoc++) {
258         std::list<std::shared_ptr<ModelAPI_Feature> > allFeats = (*aDoc)->allFeatures();
259         std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFeat = allFeats.begin();
260         for(; aFeat != allFeats.end(); aFeat++) {
261           if ((*aFeat)->data()->isValid() &&
262             (*aFeat)->data()->execState() == ModelAPI_StateMustBeUpdated) {
263             addModified(*aFeat, FeaturePtr());
264           }
265         }
266       }
267       processFeatures();
268       myIsPreviewBlocked = aPreviewBlockedState;
269     }
270   }
271
272   if (theMessage->eventID() == kStabilityEvent) {
273     updateStability(theMessage->sender());
274     return;
275   }
276   if (theMessage->eventID() == kPreviewBlockedEvent) {
277     myIsPreviewBlocked = true;
278     return;
279   }
280   if (theMessage->eventID() == kPreviewRequestedEvent) {
281     if (myIsPreviewBlocked) {
282       bool anUpdateState = myUpdateBlocked;
283       myUpdateBlocked = false;
284       myIsPreviewBlocked = false;
285       processFeatures();
286       myIsPreviewBlocked = true;
287       myUpdateBlocked = anUpdateState;
288     }
289     return;
290   }
291   if (theMessage->eventID() == kUpdatedSel) {
292     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
293         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
294     updateSelection(aMsg->objects());
295   }
296   // creation is added to "update" to avoid recomputation twice:
297   // on create and immediately after on update
298   if (theMessage->eventID() == kCreatedEvent) {
299     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
300         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
301     const std::set<ObjectPtr>& anObjs = aMsg->objects();
302     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
303     std::list<ObjectPtr> aFeatures, aResults;
304     for(; anObjIter != anObjs.cend(); anObjIter++) {
305       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
306         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) {
307           // results creation means enabling, not update
308           aFeatures.push_back(*anObjIter);
309         } else {
310           aResults.push_back(*anObjIter);
311           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*anObjIter);
312           if (aPart.get() && aPart->data().get() && aPart->data()->isValid()) {
313             aPart->shape(); // to update the shape on creation of the result
314           }
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::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<
333         " "<<(*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           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::cout<<"* 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::cout << "****** 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::cout<<"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::cout<<"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::cout<<"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     } else if (theFeature->getKind() == "Sketch" && aSel->id() == "External" &&
912                aSel->isInitialized()) {
913       // #19703 : if sketch plane was selected, but after context disappears, it must become invalid
914       aSel->update();
915       if (aSel->isInvalid()) {
916           aState = ModelAPI_StateInvalidArgument;
917       }
918     }
919   }
920   // update the selection list attributes if any
921   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
922   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
923     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
924       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
925     // #19071 : avoid sending of update event in cycle
926     bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
927     // list to keep the shared pointers while update is blocked (in messages raw poiters are used)
928     std::list<AttributeSelectionPtr> anAttrList;
929     for(int a = aSel->size() - 1; a >= 0; a--) {
930       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
931         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
932       if (aSelAttr) {
933         ObjectPtr aContext = aSelAttr->context();
934         // update argument only if the referenced object is ready to use
935         if (aContext.get() && !aContext->isDisabled()) {
936           if (isReason(theFeature, aContext)) {
937             anAttrList.push_back(aSelAttr);
938             if (!aSelAttr->update()) {
939               bool isObligatory = !aFactory->isNotObligatory(
940                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
941                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
942               if (isObligatory)
943                 aState = ModelAPI_StateInvalidArgument;
944             }
945           }
946         } else if (aContext.get()) {
947           // here it may be not obligatory, but if the reference is wrong, it should not be correct
948           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
949           if (isObligatory)
950             aState = ModelAPI_StateInvalidArgument;
951         }
952       }
953     }
954     if (!aWasBlocked)
955       theFeature->data()->blockSendAttributeUpdated(false);
956   }
957
958   if (aState != ModelAPI_StateDone)
959     theFeature->data()->execState(aState);
960 }
961
962 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
963      std::shared_ptr<ModelAPI_Object> theReason)
964 {
965   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
966     ::iterator aReasonsIt = myModified.find(theFeature);
967   if (aReasonsIt != myModified.end()) {
968     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
969       return true; // any is reason if it contains itself
970     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
971     if (!aReasFeat.get()) { // try to get feature of this result
972       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
973       if (aReasRes.get())
974         aReasFeat = theReason->document()->feature(aReasRes);
975     }
976     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
977       return true;
978   }
979   // another try: postponed modification by not-persistences
980   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
981     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
982   if (aNotPersist != myNotPersistentRefs.end()) {
983     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
984     if (!aReasFeat.get()) { // try to get feature of this result
985       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
986       if (aReasRes.get())
987         aReasFeat = theReason->document()->feature(aReasRes);
988     }
989     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
990       return true;
991   }
992
993   // this case only for not-previewed items update state, nothing is changed in args for it
994   return false;
995 }
996
997 void Model_Update::executeFeature(FeaturePtr theFeature)
998 {
999 #ifdef DEB_UPDATE
1000   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
1001 #endif
1002   // execute in try-catch to avoid internal problems of the feature
1003   ModelAPI_ExecState aState = ModelAPI_StateDone;
1004   theFeature->data()->execState(ModelAPI_StateDone);
1005   try {
1006     theFeature->execute();
1007     if (theFeature->data()->execState() != ModelAPI_StateDone) {
1008       aState = ModelAPI_StateExecFailed;
1009     } else {
1010       aState = ModelAPI_StateDone;
1011     }
1012   } catch(...) {
1013     aState = ModelAPI_StateExecFailed;
1014     Events_InfoMessage("Model_Update",
1015       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
1016   }
1017   // The macro feature has to be deleted in any case even its execution is failed
1018   myWaitForFinish.insert(theFeature);
1019   if (aState != ModelAPI_StateDone) {
1020     theFeature->eraseResults(false);
1021   }
1022   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
1023   redisplayWithResults(theFeature, aState);
1024 }
1025
1026 // it is called on GUI edit of feature start
1027 // LCOV_EXCL_START
1028 void Model_Update::updateStability(void* theSender)
1029 {
1030   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1031   if (theSender) {
1032     bool added = false; // object may be was crated
1033     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
1034     if (aSender && aSender->document()) {
1035       FeaturePtr aFeatureSender =
1036         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1037       if (aFeatureSender.get()) {
1038         Model_Objects* aDocObjects =
1039           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1040         if (aDocObjects) {
1041           //aDocObjects->synchronizeBackRefs();
1042           // remove or add all concealment refs from this feature
1043           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1044           aSender->data()->referencesToObjects(aRefs);
1045           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1046             aRefIt = aRefs.begin();
1047           for(; aRefIt != aRefs.end(); aRefIt++) {
1048             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1049               // take into account only concealed references
1050               // (do not remove the sketch constraint and the edge on constraint edit)
1051               continue;
1052             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1053             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1054             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1055                // stability is only on results: feature to feature reference mean nested
1056               // features, that will remove nesting references
1057               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1058                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1059                 std::shared_ptr<Model_Data> aData =
1060                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1061                 if (aFeatureSender->isStable()) {
1062                   aData->addBackReference(aFeatureSender, aRefIt->first);
1063                 } else {
1064                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1065                   added = true; // remove of concealment may be caused creation of some result
1066                 }
1067               }
1068             }
1069           }
1070         }
1071       }
1072     }
1073     if (added) {
1074       static Events_Loop* aLoop = Events_Loop::loop();
1075       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1076       aLoop->flush(kEventCreated);
1077     }
1078   }
1079 }
1080 // LCOV_EXCL_STOP
1081
1082 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1083 {
1084   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1085   for(; anObj != theObjects.end(); anObj++) {
1086     std::list<AttributePtr> aRefs =
1087       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1088     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1089     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1090       std::shared_ptr<Model_AttributeSelection> aSel =
1091         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1092       bool aRemove = false;
1093       aSel->updateInHistory(aRemove);
1094     }
1095     // update the selection list attributes if any
1096     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1097     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1098       std::set<int> aRemoveSet;
1099       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1100         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1101       for(int a = aSel->size() - 1; a >= 0; a--) {
1102         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1103           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1104         if (aSelAttr.get()) {
1105           bool theRemove = false;
1106           aSelAttr->updateInHistory(theRemove);
1107           if (theRemove) {
1108             aRemoveSet.insert(a);
1109           }
1110         }
1111       }
1112       aSel->remove(aRemoveSet);
1113     }
1114   }
1115 }