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