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