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