Salome HOME
First implementation of the sketch drawer: helper for creation of sketch on imported...
[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 <GeomAPI_Shape.h>
44 #include <GeomDataAPI_Point.h>
45 #include <GeomDataAPI_Point2D.h>
46 #include <Events_Loop.h>
47 #include <Events_LongOp.h>
48 #include <Events_InfoMessage.h>
49 #include <Config_PropManager.h>
50
51 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
52 //#define DEB_UPDATE
53
54 Model_Update::Model_Update()
55 {
56   Events_Loop* aLoop = Events_Loop::loop();
57   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
58   aLoop->registerListener(this, kChangedEvent);
59   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
60   aLoop->registerListener(this, kCreatedEvent);
61   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
62   aLoop->registerListener(this, kUpdatedEvent);
63   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
64   aLoop->registerListener(this, kOpFinishEvent);
65   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
66   aLoop->registerListener(this, kOpAbortEvent);
67   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
68   aLoop->registerListener(this, kOpStartEvent);
69   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
70   aLoop->registerListener(this, kStabilityEvent);
71   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
72   aLoop->registerListener(this, kPreviewBlockedEvent);
73   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
74   aLoop->registerListener(this, kPreviewRequestedEvent);
75   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
76   aLoop->registerListener(this, kReorderEvent);
77   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
78   aLoop->registerListener(this, kUpdatedSel);
79   static const Events_ID kAutomaticOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
80   aLoop->registerListener(this, kAutomaticOff);
81   static const Events_ID kAutomaticOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
82   aLoop->registerListener(this, kAutomaticOn);
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   static const Events_ID kAutomaticOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
244   static const Events_ID kAutomaticOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
245
246 #ifdef DEB_UPDATE
247   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
248 #endif
249   // check the automatic update flag on any event
250   bool aNewAutomaticState = ModelAPI_Session::get()->isAutoUpdateBlocked();
251   if (myUpdateBlocked != aNewAutomaticState) {
252     myUpdateBlocked = aNewAutomaticState;
253     if (!myUpdateBlocked) { // process all modified features, even if preview is blocked
254       bool aPreviewBlockedState = myIsPreviewBlocked; // to update the selected arguments
255       myIsPreviewBlocked = false;
256       // iterate everything and add features in state "MustBeUpdated" into modified
257       std::list<std::shared_ptr<ModelAPI_Document> > allDocs =
258         ModelAPI_Session::get()->allOpenedDocuments();
259       std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = allDocs.begin();
260       for(; aDoc != allDocs.end(); aDoc++) {
261         std::list<std::shared_ptr<ModelAPI_Feature> > allFeats = (*aDoc)->allFeatures();
262         std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFeat = allFeats.begin();
263         for(; aFeat != allFeats.end(); aFeat++) {
264           if ((*aFeat)->data()->isValid() &&
265             (*aFeat)->data()->execState() == ModelAPI_StateMustBeUpdated) {
266             addModified(*aFeat, FeaturePtr());
267           }
268         }
269       }
270       processFeatures();
271       myIsPreviewBlocked = myIsPreviewBlocked;
272     }
273   }
274
275   if (theMessage->eventID() == kStabilityEvent) {
276     updateStability(theMessage->sender());
277     return;
278   }
279   if (theMessage->eventID() == kPreviewBlockedEvent) {
280     myIsPreviewBlocked = true;
281     return;
282   }
283   if (theMessage->eventID() == kPreviewRequestedEvent) {
284     if (myIsPreviewBlocked) {
285       bool anUpdateState = myUpdateBlocked;
286       myUpdateBlocked = false;
287       myIsPreviewBlocked = false;
288       processFeatures();
289       myIsPreviewBlocked = true;
290       myUpdateBlocked = anUpdateState;
291     }
292     return;
293   }
294   if (theMessage->eventID() == kUpdatedSel) {
295     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
296         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
297     updateSelection(aMsg->objects());
298   }
299   // creation is added to "update" to avoid recomputation twice:
300   // on create and immediately after on update
301   if (theMessage->eventID() == kCreatedEvent) {
302     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
303         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
304     const std::set<ObjectPtr>& anObjs = aMsg->objects();
305     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
306     for(; anObjIter != anObjs.cend(); anObjIter++) {
307       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
308         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) {
309           // results creation means enabling, not update
310           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
311         } else {
312           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kRedisplayEvent);
313         }
314       }
315     }
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;
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       }
584     }
585     std::shared_ptr<GeomAPI_Shape> aShapeBefore = anExtSel->value();
586     if (!aShapeBefore.get() && anExtSel->context()) aShapeBefore = anExtSel->context()->shape();
587     updateArguments(theFeature);
588     std::shared_ptr<GeomAPI_Shape> aShapeAfter = anExtSel->value();
589     if (!aShapeAfter.get() && anExtSel->context()) aShapeAfter = anExtSel->context()->shape();
590     // if selected plane is changed, try to re-take external references of all subs of the sketch
591     if (aShapeBefore.get() && !aShapeBefore->isEqual(aShapeAfter)) {
592       std::set<FeaturePtr> aWholeR;
593       allReasons(theFeature, aWholeR);
594       std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
595       for(; aRIter != aWholeR.end(); aRIter++) {
596         if ((*aRIter)->data()->selection("External"))
597           (*aRIter)->attributeChanged("External");
598       }
599     }
600   }
601
602   if (!aIsModified) { // no modification is needed
603     return false;
604   }
605
606   // evaluate parameter before the sub-elements update:
607   // it updates dependencies on evaluation (#1085)
608   if (theFeature->getKind() == "Parameter") {
609     theFeature->execute();
610   }
611
612   bool isReferencedInvalid = false;
613   // check all features this feature depended on (recursive call of updateFeature)
614   std::set<FeaturePtr>& aReasons = myModified[theFeature];
615   bool allSubsUsed = aReasons.find(theFeature) != aReasons.end();
616   if (allSubsUsed) {
617     // add all subs in aReasons and temporary remove "theFeature" to avoid processing itself
618     allReasons(theFeature, aReasons);
619     aReasons.erase(theFeature);
620   }
621   // take reasons one by one (they may be added during the feature process
622   // (circle by the radius of sketch)
623   std::set<FeaturePtr> aProcessedReasons;
624   while(!aReasons.empty()) {
625     FeaturePtr aReason = *(aReasons.begin());
626 #ifdef DEB_UPDATE
627     //cout<<theFeature->name()<<" process next reason "<<aReason->name()<<endl;
628 #endif
629     if (aReason != theFeature && (aReason)->data()->isValid()) {
630       if (processFeature(aReason))
631         aIsModified = true;
632       // check validity of aReason once again because it may be removed by dependent feature
633       // (e.g. by SketchPlugin_IntersectionPoint)
634       if (!aReason->data()->isValid() ||
635           aReason->data()->execState() == ModelAPI_StateInvalidArgument)
636         isReferencedInvalid = true;
637     }
638     // searching for the next not used reason
639     aProcessedReasons.insert(aReason);
640     aReasons.erase(aReason);
641   }
642   // restore the modified reasons: they will be used in the update of arguments
643   if (allSubsUsed) { // restore theFeature in this set
644     aProcessedReasons.insert(theFeature);
645   }
646   myModified[theFeature] = aProcessedReasons;
647
648   // do not execute the composite that contains the current
649   bool isPostponedMain = false;
650   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
651   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
652     CompositeFeaturePtr aCurrentOwner =
653       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
654     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
655   } else if (theFeature->getKind() == "Sketch" &&
656     std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures()) {
657     // send event that sketch is prepared to be recomputed
658     static Events_ID anID = Events_Loop::eventByName("SketchPrepared");
659     std::shared_ptr<Events_Message> aMsg(new Events_Message(anID, this));
660     Events_Loop* aLoop = Events_Loop::loop();
661     // in case it is finish operation, flush for the sketch other events (#2450)
662     aLoop->flush(aLoop->eventByName(EVENT_OBJECT_UPDATED));
663     aLoop->send(aMsg);
664     // check that sub-elements of sketch are updated => sketch must be re-processed
665     std::set<FeaturePtr> aWholeR;
666     allReasons(theFeature, aWholeR);
667     std::set<FeaturePtr>::iterator aRIter = aWholeR.begin();
668     for(; aRIter != aWholeR.end(); aRIter++) {
669       if (myModified.find(*aRIter) != myModified.end()) {
670         processFeature(theFeature);
671         return true;
672       }
673     }
674   }
675
676 #ifdef DEB_UPDATE
677   std::cout<<"Update args "<<theFeature->name()<<std::endl;
678 #endif
679   // TestImport.py : after arguments are updated, theFeature may be removed
680   if (!theFeature->data()->isValid())
681     return false;
682   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
683   updateArguments(theFeature);
684
685   // add this feature to the processed right now to be able remove it from this list on
686   // update signal during this feature execution
687   myModified.erase(theFeature);
688   if (myNotPersistentRefs.find(theFeature) != myNotPersistentRefs.end())
689     myNotPersistentRefs.erase(theFeature);
690   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
691     theFeature->data()->execState(ModelAPI_StateDone);
692
693   // this checking must be after the composite feature sub-elements processing:
694   // composite feature status may depend on it's sub-elements
695   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) &&
696     theFeature->getKind() != "Part") {
697       // don't disable Part because it will make disabled all the features
698       // (performance and problems with the current feature)
699   #ifdef DEB_UPDATE
700     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
701   #endif
702     theFeature->eraseResults(false);
703     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
704     return true; // so, feature is modified (results are erased)
705   }
706
707   // execute feature if it must be updated
708   ModelAPI_ExecState aState = theFeature->data()->execState();
709   if (aFactory->validate(theFeature)) {
710     if (!isPostponedMain) {
711       bool aDoExecute = true;
712       if (myUpdateBlocked) {
713         if (!theFeature->isStable()) {
714           aDoExecute = true;
715         } else if (theFeature->results().size()) { // execute only not-results features
716           aDoExecute = !(theFeature->firstResult()->groupName() == ModelAPI_ResultBody::group() ||
717                          theFeature->firstResult()->groupName() == ModelAPI_ResultPart::group());
718         } else {
719           aDoExecute = aState != ModelAPI_StateInvalidArgument;
720         }
721       }
722       if (aDoExecute) {
723         executeFeature(theFeature);
724       } else {
725         // store information that this feature must be executed later
726         theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
727       }
728     }
729   } else {
730     #ifdef DEB_UPDATE
731       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
732     #endif
733     theFeature->eraseResults(false);
734     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
735   }
736   return true;
737 }
738
739 void Model_Update::redisplayWithResults(
740   FeaturePtr theFeature, const ModelAPI_ExecState theState, bool theUpdateState)
741 {
742   // make updated and redisplay all results
743   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
744
745   std::list<ResultPtr> allResults;
746   ModelAPI_Tools::allResults(theFeature, allResults);
747   std::list<ResultPtr>::iterator aRIter = allResults.begin();
748   for (; aRIter != allResults.cend(); aRIter++) {
749     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
750     if (!aRes->isDisabled()) {
751       // update state only for enabled results
752       // (Placement Result Part may make the original Part Result as invalid)
753       if (theUpdateState)
754         aRes->data()->execState(theState);
755     }
756     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
757       aRes->data()->setUpdateID(theFeature->data()->updateID());
758     }
759     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
760   }
761   // to redisplay "presentable" feature (for ex. distance constraint)
762   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
763   if (theUpdateState)
764     theFeature->data()->execState(theState);
765 }
766
767 /// Updates the state by the referenced object: if something bad with it, set state for this one
768 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
769 {
770   if (theTarget) {
771     ModelAPI_ExecState aRefState = theTarget->data()->execState();
772     if (aRefState == ModelAPI_StateMustBeUpdated) {
773       if (theCurrent == ModelAPI_StateDone)
774         return ModelAPI_StateMustBeUpdated;
775     } else if (aRefState != ModelAPI_StateDone) {
776       return ModelAPI_StateInvalidArgument;
777     }
778   }
779   return theCurrent;
780 }
781
782 void Model_Update::updateArguments(FeaturePtr theFeature) {
783   // perform this method also for disabled features: to make "not done" state for
784   // features referenced to the active and modified features
785   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
786
787   ModelAPI_ExecState aState = theFeature->data()->execState();
788   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
789     aState = ModelAPI_StateMustBeUpdated;
790   }
791   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
792     aState = ModelAPI_StateMustBeUpdated;
793   // check the parameters state
794   // Integer
795   {
796     std::list<AttributePtr> anAttrinbutes =
797       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
798     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
799     for(; anIter != anAttrinbutes.end(); anIter++) {
800       AttributeIntegerPtr anAttribute =
801         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
802       if (anAttribute.get() && !anAttribute->text().empty()) {
803         if (myIsParamUpdated) {
804           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
805         }
806         if (anAttribute->expressionInvalid()) {
807           aState = ModelAPI_StateInvalidArgument;
808         }
809       }
810     }
811   }
812   // Double
813   {
814     std::list<AttributePtr> aDoubles =
815       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
816     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
817     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
818       AttributeDoublePtr aDouble =
819         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
820       if (aDouble.get() && !aDouble->text().empty()) {
821         if (myIsParamUpdated) {
822           ModelAPI_AttributeEvalMessage::send(aDouble, this);
823         }
824         if (aDouble->expressionInvalid()) {
825           aState = ModelAPI_StateInvalidArgument;
826         }
827       }
828     }
829   }
830   // Point
831   {
832     std::list<AttributePtr> anAttributes =
833       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
834     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
835     for(; anIter != anAttributes.end(); anIter++) {
836       AttributePointPtr aPointAttribute =
837         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
838       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() ||
839           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
840         if (myIsParamUpdated) {
841           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
842         }
843         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
844           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
845           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
846           aState = ModelAPI_StateInvalidArgument;
847       }
848     }
849   }
850   // Point2D
851   {
852     std::list<AttributePtr> anAttributes =
853       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
854     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
855     for(; anIter != anAttributes.end(); anIter++) {
856       AttributePoint2DPtr aPoint2DAttribute =
857         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
858       if (aPoint2DAttribute.get()) {
859         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() ||
860             !aPoint2DAttribute->textY().empty())) {
861           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
862         }
863         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
864           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
865           aState = ModelAPI_StateInvalidArgument;
866       }
867     }
868   }
869   // update the selection attributes if any
870   std::list<AttributePtr> aRefs =
871     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
872   std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
873   for (; aRefsIter != aRefs.end(); aRefsIter++) {
874     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
875       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
876     ObjectPtr aContext = aSel->context();
877     // update argument only if the referenced object is ready to use
878     if (aContext.get() && !aContext->isDisabled()) {
879       if (isReason(theFeature, aContext)) {
880         if (!aSel->update()) { // this must be done on execution since it may be long operation
881           bool isObligatory = !aFactory->isNotObligatory(
882             theFeature->getKind(), theFeature->data()->id(aSel)) &&
883             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
884           if (isObligatory)
885             aState = ModelAPI_StateInvalidArgument;
886         }
887       }
888     } else if (aContext.get()) {
889       // here it may be not obligatory, but if the reference is wrong, it should not be correct
890       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
891       if (isObligatory)
892         aState = ModelAPI_StateInvalidArgument;
893     }
894   }
895   // update the selection list attributes if any
896   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
897   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
898     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
899       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
900     for(int a = aSel->size() - 1; a >= 0; a--) {
901       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
902         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
903       if (aSelAttr) {
904         ObjectPtr aContext = aSelAttr->context();
905         // update argument only if the referenced object is ready to use
906         if (aContext.get() && !aContext->isDisabled() && !aSelAttr->isInvalid()) {
907           if (isReason(theFeature, aContext)) {
908             if (!aSelAttr->update()) {
909               bool isObligatory = !aFactory->isNotObligatory(
910                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
911                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
912               if (isObligatory)
913                 aState = ModelAPI_StateInvalidArgument;
914             }
915           }
916         } else if (aContext.get() || aSelAttr->isInvalid()) {
917           // here it may be not obligatory, but if the reference is wrong, it should not be correct
918           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
919           if (isObligatory)
920             aState = ModelAPI_StateInvalidArgument;
921         }
922       }
923     }
924   }
925
926   if (aState != ModelAPI_StateDone)
927     theFeature->data()->execState(aState);
928 }
929
930 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
931      std::shared_ptr<ModelAPI_Object> theReason)
932 {
933   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
934     ::iterator aReasonsIt = myModified.find(theFeature);
935   if (aReasonsIt != myModified.end()) {
936     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
937       return true; // any is reason if it contains itself
938     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
939     if (!aReasFeat.get()) { // try to get feature of this result
940       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
941       if (aReasRes.get())
942         aReasFeat = theReason->document()->feature(aReasRes);
943     }
944     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
945       return true;
946   }
947   // another try: postponed modification by not-persistences
948   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
949     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
950   if (aNotPersist != myNotPersistentRefs.end()) {
951     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
952     if (!aReasFeat.get()) { // try to get feature of this result
953       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
954       if (aReasRes.get())
955         aReasFeat = theReason->document()->feature(aReasRes);
956     }
957     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
958       return true;
959   }
960
961   // this case only for not-previewed items update state, nothing is changed in args for it
962   return false;
963 }
964
965 void Model_Update::executeFeature(FeaturePtr theFeature)
966 {
967 #ifdef DEB_UPDATE
968   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
969 #endif
970   // execute in try-catch to avoid internal problems of the feature
971   ModelAPI_ExecState aState = ModelAPI_StateDone;
972   theFeature->data()->execState(ModelAPI_StateDone);
973   try {
974     theFeature->execute();
975     if (theFeature->data()->execState() != ModelAPI_StateDone) {
976       aState = ModelAPI_StateExecFailed;
977     } else {
978       aState = ModelAPI_StateDone;
979     }
980   } catch(...) {
981     aState = ModelAPI_StateExecFailed;
982     Events_InfoMessage("Model_Update",
983       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
984   }
985   // The macro feature has to be deleted in any case even its execution is failed
986   myWaitForFinish.insert(theFeature);
987   if (aState != ModelAPI_StateDone) {
988     theFeature->eraseResults(false);
989   }
990   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
991   redisplayWithResults(theFeature, aState);
992 }
993
994 void Model_Update::updateStability(void* theSender)
995 {
996   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
997   if (theSender) {
998     bool added = false; // object may be was crated
999     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
1000     if (aSender && aSender->document()) {
1001       FeaturePtr aFeatureSender =
1002         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1003       if (aFeatureSender.get()) {
1004         Model_Objects* aDocObjects =
1005           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1006         if (aDocObjects) {
1007           //aDocObjects->synchronizeBackRefs();
1008           // remove or add all concealment refs from this feature
1009           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1010           aSender->data()->referencesToObjects(aRefs);
1011           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1012             aRefIt = aRefs.begin();
1013           for(; aRefIt != aRefs.end(); aRefIt++) {
1014             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1015               // take into account only concealed references
1016               // (do not remove the sketch constraint and the edge on constraint edit)
1017               continue;
1018             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1019             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1020             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1021                // stability is only on results: feature to feature reference mean nested
1022               // features, that will remove nesting references
1023               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1024                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1025                 std::shared_ptr<Model_Data> aData =
1026                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1027                 if (aFeatureSender->isStable()) {
1028                   aData->addBackReference(aFeatureSender, aRefIt->first);
1029                 } else {
1030                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1031                   added = true; // remove of concealment may be caused creation of some result
1032                 }
1033               }
1034             }
1035           }
1036         }
1037       }
1038     }
1039     if (added) {
1040       static Events_Loop* aLoop = Events_Loop::loop();
1041       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1042       aLoop->flush(kEventCreated);
1043     }
1044   }
1045 }
1046
1047 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1048 {
1049   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1050   for(; anObj != theObjects.end(); anObj++) {
1051     std::list<AttributePtr> aRefs =
1052       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1053     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1054     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1055       std::shared_ptr<Model_AttributeSelection> aSel =
1056         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1057       aSel->updateInHistory();
1058     }
1059     // update the selection list attributes if any
1060     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1061     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1062       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1063         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1064       for(int a = aSel->size() - 1; a >= 0; a--) {
1065         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1066           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1067         if (aSelAttr.get())
1068           aSelAttr->updateInHistory();
1069       }
1070     }
1071   }
1072 }