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