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