Salome HOME
Fix the problem of the sketch plane update
[modules/shaper.git] / src / Model / Model_Update.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Update.h>
22 #include <Model_Document.h>
23 #include <Model_Data.h>
24 #include <Model_Objects.h>
25 #include <Model_AttributeSelection.h>
26 #include <ModelAPI_Feature.h>
27 #include <ModelAPI_Data.h>
28 #include <ModelAPI_Document.h>
29 #include <ModelAPI_Events.h>
30 #include <ModelAPI_AttributeReference.h>
31 #include <ModelAPI_AttributeRefList.h>
32 #include <ModelAPI_AttributeRefAttr.h>
33 #include <ModelAPI_AttributeSelection.h>
34 #include <ModelAPI_AttributeSelectionList.h>
35 #include <ModelAPI_Result.h>
36 #include <ModelAPI_ResultPart.h>
37 #include <ModelAPI_Validator.h>
38 #include <ModelAPI_CompositeFeature.h>
39 #include <ModelAPI_Session.h>
40 #include <ModelAPI_Tools.h>
41 #include <ModelAPI_ResultBody.h>
42 #include <ModelAPI_ResultPart.h>
43 #include <ModelAPI_ResultConstruction.h>
44 #include <GeomAPI_Shape.h>
45 #include <GeomDataAPI_Point.h>
46 #include <GeomDataAPI_Dir.h>
47 #include <GeomDataAPI_Point2D.h>
48 #include <Events_Loop.h>
49 #include <Events_LongOp.h>
50 #include <Events_InfoMessage.h>
51 #include <Config_PropManager.h>
52
53 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
54 //#define DEB_UPDATE
55
56 Model_Update::Model_Update()
57 {
58   Events_Loop* aLoop = Events_Loop::loop();
59   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
60   aLoop->registerListener(this, kChangedEvent);
61   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
62   aLoop->registerListener(this, kCreatedEvent);
63   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
64   aLoop->registerListener(this, kUpdatedEvent);
65   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
66   aLoop->registerListener(this, kOpFinishEvent);
67   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
68   aLoop->registerListener(this, kOpAbortEvent);
69   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
70   aLoop->registerListener(this, kOpStartEvent);
71   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
72   aLoop->registerListener(this, kStabilityEvent);
73   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
74   aLoop->registerListener(this, kPreviewBlockedEvent);
75   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
76   aLoop->registerListener(this, kPreviewRequestedEvent);
77   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
78   aLoop->registerListener(this, kReorderEvent);
79   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
80   aLoop->registerListener(this, kUpdatedSel);
81   static const Events_ID kAutoRecomp = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
82   aLoop->registerListener(this, kAutoRecomp);
83
84   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
85   myIsParamUpdated = false;
86   myIsFinish = false;
87   myIsProcessed = false;
88   myIsPreviewBlocked = false;
89   myUpdateBlocked = false;
90 }
91
92 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
93
94   if (!theFeature->data()->isValid())
95     return false; // delete an extrusion created on the sketch
96
97
98   bool isNotExecuted = theFeature->isPersistentResult() &&
99     !std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures();
100   if (isNotExecuted) {
101     redisplayWithResults(theFeature, ModelAPI_StateNothing, false); // redisplay even not executed
102     if (!theReason.get()) // no reason => no construction reason
103       return false;
104     if (myNotPersistentRefs.find(theFeature) == myNotPersistentRefs.end()) {
105       myNotPersistentRefs[theFeature].insert(theReason);
106     } else {
107       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
108       aNewSet.insert(theReason);
109       myNotPersistentRefs[theFeature] = aNewSet;
110     }
111     return false;
112   }
113
114   // update arguments for "apply button" state change
115   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
116     if (theReason.get())
117       myProcessOnFinish[theFeature].insert(theReason);
118     else if (myProcessOnFinish.find(theFeature) == myProcessOnFinish.end())
119       myProcessOnFinish[theFeature] = std::set<std::shared_ptr<ModelAPI_Feature> >();
120 #ifdef DEB_UPDATE
121       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
122 #endif
123     // keeps the currently updated features to avoid infinitive cycling here: where feature on
124     // "updateArguments" sends "updated" (in selection attribute) and goes here again
125     static std::set<FeaturePtr> aCurrentlyUpdated;
126     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
127       aCurrentlyUpdated.insert(theFeature);
128       updateArguments(theFeature);
129       aCurrentlyUpdated.erase(theFeature);
130     }
131     // make it without conditions otherwise the apply button may have a bad state
132     theFeature->data()->execState(ModelAPI_StateDone);
133     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
134      // need to be validated to update the "Apply" state if not previewed
135     aFactory->validate(theFeature);
136
137     // to redisplay split's arguments presentation, even result is not computed
138     if (!theFeature->isPreviewNeeded()) {
139       static Events_Loop* aLoop = Events_Loop::loop();
140       static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
141       ModelAPI_EventCreator::get()->sendUpdated(theFeature, kRedisplayEvent);
142       aLoop->flush(kRedisplayEvent);
143     }
144
145     if (!myIsPreviewBlocked)
146       return true;
147   }
148   if (myModified.find(theFeature) != myModified.end()) {
149     if (theReason.get()) {
150 #ifdef DEB_UPDATE
151       //std::cout<<"*** Add already modified "
152       //   <<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
153 #endif
154       myModified[theFeature].insert(theReason);
155     }
156     return true;
157   }
158   // do not add the disabled, but possibly the sub-elements are not disabled
159   bool aIsDisabled = theFeature->isDisabled();
160   if (!aIsDisabled) {
161     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
162     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated ||
163         theFeature->data()->execState() == ModelAPI_StateInvalidArgument || // issue 1519
164         theFeature->data()->execState() == ModelAPI_StateExecFailed) {
165       // do not forget that in this case all were the reasons
166       aNewSet.insert(theFeature);
167     } else {
168       if (theReason.get())
169         aNewSet.insert(theReason);
170     }
171     myModified[theFeature] = aNewSet;
172 #ifdef DEB_UPDATE
173     if (theReason.get()) {
174       //std::cout<<"*** Add modified "<<theFeature->name()
175       //  <<" reason "<<theReason->name()<<std::endl;
176     } else {
177       //std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
178     }
179 #endif
180   } else { // will be updated during the finish of the operation, or when it becomes enabled
181     if (theFeature->data()->execState() == ModelAPI_StateDone ||
182         theFeature->data()->execState() == ModelAPI_StateExecFailed) // fix issue 1819
183       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
184     else
185       return true; // do not need iteration deeply if it is already marked as modified or so
186 #ifdef DEB_UPDATE
187     //std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
188 #endif
189   }
190   // clear processed and fill modified recursively
191   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
192   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
193   for(; aRefIter != aRefs.cend(); aRefIter++) {
194     if ((*aRefIter)->isArgument()) {
195       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
196       if (aReferenced.get()) {
197         addModified(aReferenced, theFeature);
198       }
199     }
200   }
201   // process also results
202   std::list<ResultPtr> allResults; // list of this feature and results
203   ModelAPI_Tools::allResults(theFeature, allResults);
204   std::list<ResultPtr>::iterator aRes = allResults.begin();
205   for(; aRes != allResults.end(); aRes++) {
206     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*aRes)->data()->refsToMe();
207     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
208     for(; aRefIter != aRefs.cend(); aRefIter++) {
209       if ((*aRefIter)->isArgument()) {
210         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
211         if (aReferenced.get()) {
212           addModified(aReferenced, theFeature);
213         }
214       }
215     }
216   }
217
218   // also add part feature that contains this feature to the modified
219   if (theFeature->document()->kind() != "PartSet") {
220     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
221       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
222     if (aPart.get())
223       addModified(aPart, theFeature);
224   }
225   return true;
226 }
227
228 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
229 {
230   static Events_Loop* aLoop = Events_Loop::loop();
231   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
232   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
233   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
234   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
235   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
236   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
237   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
238   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
239   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
240   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
241   static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
242   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
243
244 #ifdef DEB_UPDATE
245   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
246 #endif
247   // check the automatic update flag on any event
248   bool aNewAutomaticState = ModelAPI_Session::get()->isAutoUpdateBlocked();
249   if (myUpdateBlocked != aNewAutomaticState) {
250     myUpdateBlocked = aNewAutomaticState;
251     if (!myUpdateBlocked) { // process all modified features, even if preview is blocked
252       bool aPreviewBlockedState = myIsPreviewBlocked; // to update the selected arguments
253       myIsPreviewBlocked = false;
254       // iterate everything and add features in state "MustBeUpdated" into modified
255       std::list<std::shared_ptr<ModelAPI_Document> > allDocs =
256         ModelAPI_Session::get()->allOpenedDocuments();
257       std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = allDocs.begin();
258       for(; aDoc != allDocs.end(); aDoc++) {
259         std::list<std::shared_ptr<ModelAPI_Feature> > allFeats = (*aDoc)->allFeatures();
260         std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFeat = allFeats.begin();
261         for(; aFeat != allFeats.end(); aFeat++) {
262           if ((*aFeat)->data()->isValid() &&
263             (*aFeat)->data()->execState() == ModelAPI_StateMustBeUpdated) {
264             addModified(*aFeat, FeaturePtr());
265           }
266         }
267       }
268       processFeatures();
269       myIsPreviewBlocked = myIsPreviewBlocked;
270     }
271   }
272
273   if (theMessage->eventID() == kStabilityEvent) {
274     updateStability(theMessage->sender());
275     return;
276   }
277   if (theMessage->eventID() == kPreviewBlockedEvent) {
278     myIsPreviewBlocked = true;
279     return;
280   }
281   if (theMessage->eventID() == kPreviewRequestedEvent) {
282     if (myIsPreviewBlocked) {
283       bool anUpdateState = myUpdateBlocked;
284       myUpdateBlocked = false;
285       myIsPreviewBlocked = false;
286       processFeatures();
287       myIsPreviewBlocked = true;
288       myUpdateBlocked = anUpdateState;
289     }
290     return;
291   }
292   if (theMessage->eventID() == kUpdatedSel) {
293     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
294         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
295     updateSelection(aMsg->objects());
296   }
297   // creation is added to "update" to avoid recomputation twice:
298   // on create and immediately after on update
299   if (theMessage->eventID() == kCreatedEvent) {
300     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
301         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
302     const std::set<ObjectPtr>& anObjs = aMsg->objects();
303     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
304     for(; anObjIter != anObjs.cend(); anObjIter++) {
305       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
306         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) {
307           // results creation means enabling, not update
308           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
309         } else {
310           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kRedisplayEvent);
311         }
312       }
313     }
314     return;
315   }
316   if (theMessage->eventID() == kUpdatedEvent) {
317     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
318         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
319     const std::set<ObjectPtr>& anObjs = aMsg->objects();
320     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
321     bool aSomeModified = false; // check that features not changed: only redisplay is needed
322     for(; anObjIter != anObjs.cend(); anObjIter++) {
323       if (!(*anObjIter)->data()->isValid())
324         continue;
325 #ifdef DEB_UPDATE
326       std::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<
327         " "<<(*anObjIter)->data()->name()<<std::endl;
328 #endif
329       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
330         myIsParamUpdated = true;
331       }
332       // on undo/redo, abort do not update persistent features
333       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
334       if (anUpdated.get()) {
335         if (addModified(anUpdated, FeaturePtr()))
336           aSomeModified = true;
337         if (myUpdateBlocked) { // execute this feature anyway to show the current result
338           /*if (!anUpdated->isStable() && anUpdated->results().size() && (
339               anUpdated->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
340               anUpdated->firstResult()->groupName() == ModelAPI_ResultPart::group())) {
341             if (aFactory->validate(anUpdated)) {
342               executeFeature(anUpdated);
343               redisplayWithResults(anUpdated, ModelAPI_StateNothing, false);
344               static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
345               aLoop->flush(EVENT_DISP);
346             }
347           }*/
348         }
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           FeaturePtr 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;
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   if (myProcessed.find(theFeature) == myProcessed.end()) {
537     myProcessed[theFeature] = 0;
538   } else {
539     int aCount = myProcessed[theFeature];
540     if (aCount > 100) {
541       // too many repetition of processing (in VS it may crash on 330 with stack overflow)
542       Events_InfoMessage("Model_Update",
543         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
544       // to stop iteration
545       myModified.clear();
546       return false;
547     }
548     myProcessed[theFeature] = aCount + 1;
549   }
550
551   // check this feature is not yet checked or processed
552   bool aIsModified = myModified.find(theFeature) != myModified.end();
553   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
554     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
555       aIsModified = true;
556       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
557       // contains itself, so, we don't know which was the reason and the reason is any
558       aNewSet.insert(theFeature);
559       myModified[theFeature] = aNewSet;
560     }
561   }
562
563 #ifdef DEB_UPDATE
564     std::cout<<"* 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::cout << "****** 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     aReasons.erase(aReason);
649   }
650   // restore the modified reasons: they will be used in the update of arguments
651   if (allSubsUsed) { // restore theFeature in this set
652     aProcessedReasons.insert(theFeature);
653   }
654   myModified[theFeature] = aProcessedReasons;
655
656   // do not execute the composite that contains the current
657   bool isPostponedMain = false;
658   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
659   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
660     CompositeFeaturePtr aCurrentOwner =
661       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
662     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
663   } else if (theFeature->getKind() == "Sketch" &&
664     std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures()) {
665     // send event that sketch is prepared to be recomputed
666     static Events_ID anID = Events_Loop::eventByName("SketchPrepared");
667     std::shared_ptr<Events_Message> aMsg(new Events_Message(anID, this));
668     Events_Loop* aLoop = Events_Loop::loop();
669     // in case it is finish operation, flush for the sketch other events (#2450)
670     aLoop->flush(aLoop->eventByName(EVENT_OBJECT_UPDATED));
671     aLoop->send(aMsg);
672     // check that sub-elements of sketch are updated => sketch must be re-processed
673     std::set<FeaturePtr> aWholeR;
674     allReasons(theFeature, aWholeR);
675     std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
676     for(; aRIter != aWholeR.end(); aRIter++) {
677       if (myModified.find(*aRIter) != myModified.end()) {
678         processFeature(theFeature);
679         return true;
680       }
681     }
682   }
683
684 #ifdef DEB_UPDATE
685   std::cout<<"Update args "<<theFeature->name()<<std::endl;
686 #endif
687   // TestImport.py : after arguments are updated, theFeature may be removed
688   if (!theFeature->data()->isValid())
689     return false;
690   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
691   updateArguments(theFeature);
692
693   // add this feature to the processed right now to be able remove it from this list on
694   // update signal during this feature execution
695   myModified.erase(theFeature);
696   if (myNotPersistentRefs.find(theFeature) != myNotPersistentRefs.end())
697     myNotPersistentRefs.erase(theFeature);
698   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
699     theFeature->data()->execState(ModelAPI_StateDone);
700
701   // this checking must be after the composite feature sub-elements processing:
702   // composite feature status may depend on it's sub-elements
703   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) &&
704     theFeature->getKind() != "Part") {
705       // don't disable Part because it will make disabled all the features
706       // (performance and problems with the current feature)
707   #ifdef DEB_UPDATE
708     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
709   #endif
710     theFeature->eraseResults(false);
711     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
712     return true; // so, feature is modified (results are erased)
713   }
714
715   // execute feature if it must be updated
716   ModelAPI_ExecState aState = theFeature->data()->execState();
717   if (aFactory->validate(theFeature)) {
718     if (!isPostponedMain) {
719       bool aDoExecute = true;
720       if (myUpdateBlocked) {
721         if (!theFeature->isStable()) {
722           aDoExecute = true;
723         } else if (theFeature->results().size()) { // execute only not-results features
724           aDoExecute = !(theFeature->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
725             theFeature->firstResult()->groupName() == ModelAPI_ResultPart::group() ||
726             theFeature->getKind() == "Sketch");
727         } else {
728           aDoExecute = aState != ModelAPI_StateInvalidArgument;
729         }
730       }
731       if (aDoExecute) {
732         executeFeature(theFeature);
733       } else {
734         // store information that this feature must be executed later
735         theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
736       }
737     }
738   } else {
739     #ifdef DEB_UPDATE
740       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
741     #endif
742     theFeature->eraseResults(false);
743     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
744   }
745   return true;
746 }
747
748 void Model_Update::redisplayWithResults(
749   FeaturePtr theFeature, const ModelAPI_ExecState theState, bool theUpdateState)
750 {
751   // make updated and redisplay all results
752   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
753
754   std::list<ResultPtr> allResults;
755   ModelAPI_Tools::allResults(theFeature, allResults);
756   std::list<ResultPtr>::iterator aRIter = allResults.begin();
757   for (; aRIter != allResults.cend(); aRIter++) {
758     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
759     if (!aRes->isDisabled()) {
760       // update state only for enabled results
761       // (Placement Result Part may make the original Part Result as invalid)
762       if (theUpdateState)
763         aRes->data()->execState(theState);
764     }
765     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
766       aRes->data()->setUpdateID(theFeature->data()->updateID());
767     }
768     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
769   }
770   // to redisplay "presentable" feature (for ex. distance constraint)
771   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
772   if (theUpdateState)
773     theFeature->data()->execState(theState);
774 }
775
776 /// Updates the state by the referenced object: if something bad with it, set state for this one
777 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
778 {
779   if (theTarget) {
780     ModelAPI_ExecState aRefState = theTarget->data()->execState();
781     if (aRefState == ModelAPI_StateMustBeUpdated) {
782       if (theCurrent == ModelAPI_StateDone)
783         return ModelAPI_StateMustBeUpdated;
784     } else if (aRefState != ModelAPI_StateDone) {
785       return ModelAPI_StateInvalidArgument;
786     }
787   }
788   return theCurrent;
789 }
790
791 void Model_Update::updateArguments(FeaturePtr theFeature) {
792   // perform this method also for disabled features: to make "not done" state for
793   // features referenced to the active and modified features
794   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
795
796   ModelAPI_ExecState aState = theFeature->data()->execState();
797   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
798     aState = ModelAPI_StateMustBeUpdated;
799   }
800   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
801     aState = ModelAPI_StateMustBeUpdated;
802   // check the parameters state
803   // Integer
804   {
805     std::list<AttributePtr> anAttrinbutes =
806       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
807     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
808     for(; anIter != anAttrinbutes.end(); anIter++) {
809       AttributeIntegerPtr anAttribute =
810         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
811       if (anAttribute.get() && !anAttribute->text().empty()) {
812         if (myIsParamUpdated) {
813           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
814         }
815         if (anAttribute->expressionInvalid()) {
816           aState = ModelAPI_StateInvalidArgument;
817         }
818       }
819     }
820   }
821   // Double
822   {
823     std::list<AttributePtr> aDoubles =
824       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
825     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
826     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
827       AttributeDoublePtr aDouble =
828         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
829       if (aDouble.get() && !aDouble->text().empty()) {
830         if (myIsParamUpdated) {
831           ModelAPI_AttributeEvalMessage::send(aDouble, this);
832         }
833         if (aDouble->expressionInvalid()) {
834           aState = ModelAPI_StateInvalidArgument;
835         }
836       }
837     }
838   }
839   // Point
840   {
841     std::list<AttributePtr> anAttributes =
842       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
843     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
844     for(; anIter != anAttributes.end(); anIter++) {
845       AttributePointPtr aPointAttribute =
846         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
847       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() ||
848           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
849         if (myIsParamUpdated) {
850           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
851         }
852         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
853           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
854           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
855           aState = ModelAPI_StateInvalidArgument;
856       }
857     }
858   }
859   // Point2D
860   {
861     std::list<AttributePtr> anAttributes =
862       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
863     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
864     for(; anIter != anAttributes.end(); anIter++) {
865       AttributePoint2DPtr aPoint2DAttribute =
866         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
867       if (aPoint2DAttribute.get()) {
868         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() ||
869             !aPoint2DAttribute->textY().empty())) {
870           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
871         }
872         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
873           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
874           aState = ModelAPI_StateInvalidArgument;
875       }
876     }
877   }
878   // update the selection attributes if any
879   std::list<AttributePtr> aRefs =
880     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
881   std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
882   for (; aRefsIter != aRefs.end(); aRefsIter++) {
883     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
884       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
885     ObjectPtr aContext = aSel->context();
886     // update argument only if the referenced object is ready to use
887     if (aContext.get() && !aContext->isDisabled()) {
888       if (isReason(theFeature, aContext)) {
889         if (!aSel->update()) { // this must be done on execution since it may be long operation
890           bool isObligatory = !aFactory->isNotObligatory(
891             theFeature->getKind(), theFeature->data()->id(aSel)) &&
892             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
893           if (isObligatory)
894             aState = ModelAPI_StateInvalidArgument;
895         }
896       }
897     } else if (aContext.get()) {
898       // here it may be not obligatory, but if the reference is wrong, it should not be correct
899       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
900       if (isObligatory)
901         aState = ModelAPI_StateInvalidArgument;
902     }
903   }
904   // update the selection list attributes if any
905   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
906   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
907     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
908       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
909     for(int a = aSel->size() - 1; a >= 0; a--) {
910       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
911         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
912       if (aSelAttr) {
913         ObjectPtr aContext = aSelAttr->context();
914         // update argument only if the referenced object is ready to use
915         if (aContext.get() && !aContext->isDisabled() && !aSelAttr->isInvalid()) {
916           if (isReason(theFeature, aContext)) {
917             if (!aSelAttr->update()) {
918               bool isObligatory = !aFactory->isNotObligatory(
919                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
920                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
921               if (isObligatory)
922                 aState = ModelAPI_StateInvalidArgument;
923             }
924           }
925         } else if (aContext.get() || aSelAttr->isInvalid()) {
926           // here it may be not obligatory, but if the reference is wrong, it should not be correct
927           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
928           if (isObligatory)
929             aState = ModelAPI_StateInvalidArgument;
930         }
931       }
932     }
933   }
934
935   if (aState != ModelAPI_StateDone)
936     theFeature->data()->execState(aState);
937 }
938
939 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
940      std::shared_ptr<ModelAPI_Object> theReason)
941 {
942   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
943     ::iterator aReasonsIt = myModified.find(theFeature);
944   if (aReasonsIt != myModified.end()) {
945     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
946       return true; // any is reason if it contains itself
947     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
948     if (!aReasFeat.get()) { // try to get feature of this result
949       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
950       if (aReasRes.get())
951         aReasFeat = theReason->document()->feature(aReasRes);
952     }
953     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
954       return true;
955   }
956   // another try: postponed modification by not-persistences
957   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
958     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
959   if (aNotPersist != myNotPersistentRefs.end()) {
960     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
961     if (!aReasFeat.get()) { // try to get feature of this result
962       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
963       if (aReasRes.get())
964         aReasFeat = theReason->document()->feature(aReasRes);
965     }
966     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
967       return true;
968   }
969
970   // this case only for not-previewed items update state, nothing is changed in args for it
971   return false;
972 }
973
974 void Model_Update::executeFeature(FeaturePtr theFeature)
975 {
976 #ifdef DEB_UPDATE
977   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
978 #endif
979   // execute in try-catch to avoid internal problems of the feature
980   ModelAPI_ExecState aState = ModelAPI_StateDone;
981   theFeature->data()->execState(ModelAPI_StateDone);
982   try {
983     theFeature->execute();
984     if (theFeature->data()->execState() != ModelAPI_StateDone) {
985       aState = ModelAPI_StateExecFailed;
986     } else {
987       aState = ModelAPI_StateDone;
988     }
989   } catch(...) {
990     aState = ModelAPI_StateExecFailed;
991     Events_InfoMessage("Model_Update",
992       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
993   }
994   // The macro feature has to be deleted in any case even its execution is failed
995   myWaitForFinish.insert(theFeature);
996   if (aState != ModelAPI_StateDone) {
997     theFeature->eraseResults(false);
998   }
999   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
1000   redisplayWithResults(theFeature, aState);
1001 }
1002
1003 // it is called on GUI edit of feature start
1004 // LCOV_EXCL_START
1005 void Model_Update::updateStability(void* theSender)
1006 {
1007   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1008   if (theSender) {
1009     bool added = false; // object may be was crated
1010     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
1011     if (aSender && aSender->document()) {
1012       FeaturePtr aFeatureSender =
1013         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1014       if (aFeatureSender.get()) {
1015         Model_Objects* aDocObjects =
1016           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1017         if (aDocObjects) {
1018           //aDocObjects->synchronizeBackRefs();
1019           // remove or add all concealment refs from this feature
1020           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1021           aSender->data()->referencesToObjects(aRefs);
1022           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1023             aRefIt = aRefs.begin();
1024           for(; aRefIt != aRefs.end(); aRefIt++) {
1025             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1026               // take into account only concealed references
1027               // (do not remove the sketch constraint and the edge on constraint edit)
1028               continue;
1029             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1030             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1031             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1032                // stability is only on results: feature to feature reference mean nested
1033               // features, that will remove nesting references
1034               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1035                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1036                 std::shared_ptr<Model_Data> aData =
1037                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1038                 if (aFeatureSender->isStable()) {
1039                   aData->addBackReference(aFeatureSender, aRefIt->first);
1040                 } else {
1041                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1042                   added = true; // remove of concealment may be caused creation of some result
1043                 }
1044               }
1045             }
1046           }
1047         }
1048       }
1049     }
1050     if (added) {
1051       static Events_Loop* aLoop = Events_Loop::loop();
1052       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1053       aLoop->flush(kEventCreated);
1054     }
1055   }
1056 }
1057 // LCOV_EXCL_STOP
1058
1059 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1060 {
1061   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1062   for(; anObj != theObjects.end(); anObj++) {
1063     std::list<AttributePtr> aRefs =
1064       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1065     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1066     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1067       std::shared_ptr<Model_AttributeSelection> aSel =
1068         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1069       aSel->updateInHistory();
1070     }
1071     // update the selection list attributes if any
1072     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1073     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1074       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1075         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1076       for(int a = aSel->size() - 1; a >= 0; a--) {
1077         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1078           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1079         if (aSelAttr.get())
1080           aSelAttr->updateInHistory();
1081       }
1082     }
1083   }
1084 }