Salome HOME
Fix for the problem of referencing to the attributes by pointers in messages. It...
[modules/shaper.git] / src / Model / Model_Update.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Update.h>
21 #include <Model_Document.h>
22 #include <Model_Data.h>
23 #include <Model_Objects.h>
24 #include <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   // check this feature is not yet checked or processed
539   bool aIsModified = myModified.find(theFeature) != myModified.end();
540   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
541     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
542       aIsModified = true;
543       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
544       // contains itself, so, we don't know which was the reason and the reason is any
545       aNewSet.insert(theFeature);
546       myModified[theFeature] = aNewSet;
547     }
548   }
549
550   if (myProcessed.find(theFeature) == myProcessed.end()) {
551     myProcessed[theFeature] = 0;
552   } else if (aIsModified) {
553     int aCount = myProcessed[theFeature];
554     if (aCount > 100) {
555       // too many repetition of processing (in VS it may crash on 330 with stack overflow)
556       Events_InfoMessage("Model_Update",
557         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
558       // to stop iteration
559       myModified.clear();
560       return false;
561     }
562     myProcessed[theFeature] = aCount + 1;
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     // #19071 : avoid sending of update event in cycle
915     bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
916     // list to keep the shared pointers while update is blocked (in messages raw poiters are used)
917     std::list<AttributeSelectionPtr> anAttrList;
918     for(int a = aSel->size() - 1; a >= 0; a--) {
919       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
920         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
921       if (aSelAttr) {
922         ObjectPtr aContext = aSelAttr->context();
923         // update argument only if the referenced object is ready to use
924         if (aContext.get() && !aContext->isDisabled()) {
925           if (isReason(theFeature, aContext)) {
926             anAttrList.push_back(aSelAttr);
927             if (!aSelAttr->update()) {
928               bool isObligatory = !aFactory->isNotObligatory(
929                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
930                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
931               if (isObligatory)
932                 aState = ModelAPI_StateInvalidArgument;
933             }
934           }
935         } else if (aContext.get()) {
936           // here it may be not obligatory, but if the reference is wrong, it should not be correct
937           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
938           if (isObligatory)
939             aState = ModelAPI_StateInvalidArgument;
940         }
941       }
942     }
943     if (!aWasBlocked)
944       theFeature->data()->blockSendAttributeUpdated(false);
945   }
946
947   if (aState != ModelAPI_StateDone)
948     theFeature->data()->execState(aState);
949 }
950
951 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature,
952      std::shared_ptr<ModelAPI_Object> theReason)
953 {
954   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
955     ::iterator aReasonsIt = myModified.find(theFeature);
956   if (aReasonsIt != myModified.end()) {
957     if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
958       return true; // any is reason if it contains itself
959     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
960     if (!aReasFeat.get()) { // try to get feature of this result
961       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
962       if (aReasRes.get())
963         aReasFeat = theReason->document()->feature(aReasRes);
964     }
965     if (aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end())
966       return true;
967   }
968   // another try: postponed modification by not-persistences
969   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
970     ::iterator aNotPersist = myNotPersistentRefs.find(theFeature);
971   if (aNotPersist != myNotPersistentRefs.end()) {
972     FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
973     if (!aReasFeat.get()) { // try to get feature of this result
974       ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
975       if (aReasRes.get())
976         aReasFeat = theReason->document()->feature(aReasRes);
977     }
978     if (aNotPersist->second.find(aReasFeat) != aNotPersist->second.end())
979       return true;
980   }
981
982   // this case only for not-previewed items update state, nothing is changed in args for it
983   return false;
984 }
985
986 void Model_Update::executeFeature(FeaturePtr theFeature)
987 {
988 #ifdef DEB_UPDATE
989   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
990 #endif
991   // execute in try-catch to avoid internal problems of the feature
992   ModelAPI_ExecState aState = ModelAPI_StateDone;
993   theFeature->data()->execState(ModelAPI_StateDone);
994   try {
995     theFeature->execute();
996     if (theFeature->data()->execState() != ModelAPI_StateDone) {
997       aState = ModelAPI_StateExecFailed;
998     } else {
999       aState = ModelAPI_StateDone;
1000     }
1001   } catch(...) {
1002     aState = ModelAPI_StateExecFailed;
1003     Events_InfoMessage("Model_Update",
1004       "Feature %1 has failed during the execution").arg(theFeature->getKind()).send();
1005   }
1006   // The macro feature has to be deleted in any case even its execution is failed
1007   myWaitForFinish.insert(theFeature);
1008   if (aState != ModelAPI_StateDone) {
1009     theFeature->eraseResults(false);
1010   }
1011   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
1012   redisplayWithResults(theFeature, aState);
1013 }
1014
1015 // it is called on GUI edit of feature start
1016 // LCOV_EXCL_START
1017 void Model_Update::updateStability(void* theSender)
1018 {
1019   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1020   if (theSender) {
1021     bool added = false; // object may be was crated
1022     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
1023     if (aSender && aSender->document()) {
1024       FeaturePtr aFeatureSender =
1025         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
1026       if (aFeatureSender.get()) {
1027         Model_Objects* aDocObjects =
1028           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
1029         if (aDocObjects) {
1030           //aDocObjects->synchronizeBackRefs();
1031           // remove or add all concealment refs from this feature
1032           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1033           aSender->data()->referencesToObjects(aRefs);
1034           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator
1035             aRefIt = aRefs.begin();
1036           for(; aRefIt != aRefs.end(); aRefIt++) {
1037             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
1038               // take into account only concealed references
1039               // (do not remove the sketch constraint and the edge on constraint edit)
1040               continue;
1041             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
1042             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
1043             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
1044                // stability is only on results: feature to feature reference mean nested
1045               // features, that will remove nesting references
1046               if (aReferenced->get() && (*aReferenced)->data()->isValid() &&
1047                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
1048                 std::shared_ptr<Model_Data> aData =
1049                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
1050                 if (aFeatureSender->isStable()) {
1051                   aData->addBackReference(aFeatureSender, aRefIt->first);
1052                 } else {
1053                   aData->removeBackReference(aFeatureSender, aRefIt->first);
1054                   added = true; // remove of concealment may be caused creation of some result
1055                 }
1056               }
1057             }
1058           }
1059         }
1060       }
1061     }
1062     if (added) {
1063       static Events_Loop* aLoop = Events_Loop::loop();
1064       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
1065       aLoop->flush(kEventCreated);
1066     }
1067   }
1068 }
1069 // LCOV_EXCL_STOP
1070
1071 void Model_Update::updateSelection(const std::set<std::shared_ptr<ModelAPI_Object> >& theObjects)
1072 {
1073   std::set<std::shared_ptr<ModelAPI_Object> >::iterator anObj = theObjects.begin();
1074   for(; anObj != theObjects.end(); anObj++) {
1075     std::list<AttributePtr> aRefs =
1076       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
1077     std::list<AttributePtr>::iterator aRefsIter = aRefs.begin();
1078     for (; aRefsIter != aRefs.end(); aRefsIter++) {
1079       std::shared_ptr<Model_AttributeSelection> aSel =
1080         std::dynamic_pointer_cast<Model_AttributeSelection>(*aRefsIter);
1081       bool aRemove = false;
1082       aSel->updateInHistory(aRemove);
1083     }
1084     // update the selection list attributes if any
1085     aRefs = (*anObj)->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1086     for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
1087       std::set<int> aRemoveSet;
1088       std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
1089         std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
1090       for(int a = aSel->size() - 1; a >= 0; a--) {
1091         std::shared_ptr<Model_AttributeSelection> aSelAttr =
1092           std::dynamic_pointer_cast<Model_AttributeSelection>(aSel->value(a));
1093         if (aSelAttr.get()) {
1094           bool theRemove = false;
1095           aSelAttr->updateInHistory(theRemove);
1096           if (theRemove) {
1097             aRemoveSet.insert(a);
1098           }
1099         }
1100       }
1101       aSel->remove(aRemoveSet);
1102     }
1103   }
1104 }