Salome HOME
Issue #1834: Fix length of lines
[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 using namespace std;
35
36 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
37 //#define DEB_UPDATE
38
39 Model_Update::Model_Update()
40 {
41   Events_Loop* aLoop = Events_Loop::loop();
42   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
43   aLoop->registerListener(this, kChangedEvent);
44   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
45   aLoop->registerListener(this, kCreatedEvent);
46   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
47   aLoop->registerListener(this, kUpdatedEvent);
48   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
49   aLoop->registerListener(this, kOpFinishEvent);
50   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
51   aLoop->registerListener(this, kOpAbortEvent);
52   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
53   aLoop->registerListener(this, kOpStartEvent);
54   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
55   aLoop->registerListener(this, kStabilityEvent);
56   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
57   aLoop->registerListener(this, kPreviewBlockedEvent);
58   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
59   aLoop->registerListener(this, kPreviewRequestedEvent);
60   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
61   aLoop->registerListener(this, kReorderEvent);
62   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
63   aLoop->registerListener(this, kUpdatedSel);
64
65   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
66   myIsParamUpdated = false;
67   myIsFinish = false;
68   myIsProcessed = false;
69   myIsPreviewBlocked = false;
70 }
71
72 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
73
74   if (!theFeature->data()->isValid())
75     return false; // delete an extrusion created on the sketch
76
77   bool isNotExecuted = theFeature->isPersistentResult() &&
78     !std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures();
79   if (isNotExecuted) {
80     if (!theReason.get()) // no reason => no construction reason
81       return false;
82     if (myNotPersistentRefs.find(theFeature) == myNotPersistentRefs.end()) {
83       myNotPersistentRefs[theFeature].insert(theReason);
84     } else {
85       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
86       aNewSet.insert(theReason);
87       myNotPersistentRefs[theFeature] = aNewSet;
88     }
89     return false;
90   }
91
92   // update arguments for "apply button" state change
93   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
94     myProcessOnFinish.insert(theFeature);
95 #ifdef DEB_UPDATE
96       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
97 #endif
98     // keeps the currently updated features to avoid infinitive cycling here: where feature on
99     // "updateArguments" sends "updated" (in selection attribute) and goes here again
100     static std::set<FeaturePtr> aCurrentlyUpdated;
101     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
102       aCurrentlyUpdated.insert(theFeature);
103       updateArguments(theFeature);
104       aCurrentlyUpdated.erase(theFeature);
105     }
106     // make it without conditions otherwise the apply button may have a bad state
107     theFeature->data()->execState(ModelAPI_StateDone);
108     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
109      // need to be validated to update the "Apply" state if not previewed
110     aFactory->validate(theFeature);
111
112     // to redisplay split's arguments presentation, even result is not computed
113     if (!theFeature->isPreviewNeeded()) {
114       static Events_Loop* aLoop = Events_Loop::loop();
115       static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
116       ModelAPI_EventCreator::get()->sendUpdated(theFeature, kRedisplayEvent);
117       aLoop->flush(kRedisplayEvent);
118     }
119
120     if (!myIsPreviewBlocked)
121       return true;
122   }
123   if (myModified.find(theFeature) != myModified.end()) {
124     if (theReason.get()) {
125 #ifdef DEB_UPDATE
126       //std::cout<<"*** Add already modified "
127       //   <<theFeature->name()<<" reason "<<theReason->name()<<std::endl;
128 #endif
129       myModified[theFeature].insert(theReason);
130     }
131     return true;
132   }
133   // do not add the disabled, but possibly the sub-elements are not disabled
134   bool aIsDisabled = theFeature->isDisabled();
135   if (!aIsDisabled) {
136     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
137     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated ||
138         theFeature->data()->execState() == ModelAPI_StateInvalidArgument || // issue 1519
139         theFeature->data()->execState() == ModelAPI_StateExecFailed) {
140       // do not forget that in this case all were the reasons
141       aNewSet.insert(theFeature);
142     } else {
143       if (theReason.get())
144         aNewSet.insert(theReason);
145     }
146       myModified[theFeature] = aNewSet;
147 #ifdef DEB_UPDATE
148     if (theReason.get()) {
149       //std::cout<<"*** Add modified "<<theFeature->name()
150       //  <<" reason "<<theReason->name()<<std::endl;
151     } else {
152       //std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
153     }
154 #endif
155   } else { // will be updated during the finish of the operation, or when it becomes enabled
156     if (theFeature->data()->execState() == ModelAPI_StateDone ||
157         theFeature->data()->execState() == ModelAPI_StateExecFailed) // fix issue 1819
158       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
159     else 
160       return true; // do not need iteration deeply if it is already marked as modified or so
161 #ifdef DEB_UPDATE
162     //std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
163 #endif
164   }
165   // clear processed and fill modified recursively
166   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
167   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
168   for(; aRefIter != aRefs.cend(); aRefIter++) {
169     if ((*aRefIter)->isArgument()) {
170       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
171       if (aReferenced.get()) {
172         addModified(aReferenced, theFeature);
173       }
174     }
175   }
176   // proccess also results
177   std::list<ResultPtr> allResults; // list of this feature and results
178   ModelAPI_Tools::allResults(theFeature, allResults);
179   std::list<ResultPtr>::iterator aRes = allResults.begin();
180   for(; aRes != allResults.end(); aRes++) {
181     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*aRes)->data()->refsToMe();
182     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
183     for(; aRefIter != aRefs.cend(); aRefIter++) {
184       if ((*aRefIter)->isArgument()) {
185         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
186         if (aReferenced.get()) {
187           addModified(aReferenced, theFeature);
188         }
189       }
190     }
191   }
192
193   // also add part feature that contains this feature to the modified
194   if (theFeature->document()->kind() != "PartSet") {
195     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
196       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
197     if (aPart.get())
198       addModified(aPart, theFeature);
199   }
200   return true;
201 }
202
203 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
204 {
205   static Events_Loop* aLoop = Events_Loop::loop();
206   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
207   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
208   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
209   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
210   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
211   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
212   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
213   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
214   static const Events_ID kReorderEvent = aLoop->eventByName(EVENT_ORDER_UPDATED);
215   static const Events_ID kRedisplayEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
216   static const Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
217
218 #ifdef DEB_UPDATE
219   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
220 #endif
221   if (theMessage->eventID() == kStabilityEvent) {
222     updateStability(theMessage->sender());
223     return;
224   }
225   if (theMessage->eventID() == kPreviewBlockedEvent) {
226     myIsPreviewBlocked = true;
227     return;
228   }
229   if (theMessage->eventID() == kPreviewRequestedEvent) {
230     if (myIsPreviewBlocked) {
231       myIsPreviewBlocked = false;
232       processFeatures();
233       myIsPreviewBlocked = true;
234     }
235     return;
236   }
237   if (theMessage->eventID() == kUpdatedSel) {
238     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
239         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
240     updateSelection(aMsg->objects());
241   }
242   // creation is added to "update" to avoid recomputation twice: 
243   // on create and immediately after on update
244   if (theMessage->eventID() == kCreatedEvent) {
245     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
246         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
247     const std::set<ObjectPtr>& anObjs = aMsg->objects();
248     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
249     for(; anObjIter != anObjs.cend(); anObjIter++) {
250       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures()) {
251         if ((*anObjIter)->groupName() == ModelAPI_Feature::group()) { 
252           // results creation means enabling, not update
253           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
254         } else {
255           ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kRedisplayEvent);
256         }
257       }
258     }
259     return;
260   }
261   if (theMessage->eventID() == kUpdatedEvent) {
262     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
263         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
264     const std::set<ObjectPtr>& anObjs = aMsg->objects();
265     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
266     bool aSomeModified = false; // check that features not changed: only redisplay is needed
267     for(; anObjIter != anObjs.cend(); anObjIter++) {
268       if (!(*anObjIter)->data()->isValid())
269         continue;
270 #ifdef DEB_UPDATE
271       std::cout<<">>> in event updated "<<(*anObjIter)->groupName()<<
272         " "<<(*anObjIter)->data()->name()<<std::endl;
273 #endif
274       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
275         myIsParamUpdated = true;
276       }
277       // on undo/redo, abort do not update persisten features
278       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
279       if (anUpdated.get()) {
280         if (addModified(anUpdated, FeaturePtr()))
281           aSomeModified = true;
282       } else { 
283         // process the updated result as update of features that refers to this result
284         const std::set<std::shared_ptr<ModelAPI_Attribute> >& 
285           aRefs = (*anObjIter)->data()->refsToMe();
286         std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
287         for(; aRefIter != aRefs.cend(); aRefIter++) {
288           if (!(*aRefIter)->owner()->data()->isValid())
289             continue;
290           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
291           if (anUpdated.get()) {
292             if (addModified(anUpdated, FeaturePtr()))
293               aSomeModified = true;
294           }
295         }
296       }
297     }
298     // this event is for solver update, not here, do not react immediately
299     if (aSomeModified) {
300         processFeatures();
301     }
302   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
303       theMessage->eventID() == kOpStartEvent) {
304     myIsPreviewBlocked = false;
305
306     if (theMessage->eventID() == kOpFinishEvent) {
307       myIsFinish = true;
308       // add features that wait for finish as modified
309       std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aFeature = myProcessOnFinish.begin();
310       for(; aFeature != myProcessOnFinish.end(); aFeature++)
311         if ((*aFeature)->data()->isValid()) // there may be already removed wait for features
312           addModified(*aFeature, FeaturePtr());
313       myIsFinish = false;
314     }
315     // processed features must be only on finish, so clear anyway (to avoid reimport on load)
316     myProcessOnFinish.clear(); 
317
318     if (!(theMessage->eventID() == kOpStartEvent)) {
319       processFeatures(false);
320     }
321     // remove all macros before clearing all created
322     std::set<FeaturePtr>::iterator anUpdatedIter = myWaitForFinish.begin();
323     while(anUpdatedIter != myWaitForFinish.end()) {
324       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
325       if (aFeature.get()) {
326         // remove macro on finish
327         if (aFeature->isMacro()) {
328           aFeature->document()->removeFeature(aFeature);
329           myWaitForFinish.erase(aFeature);
330         }
331         // to avoid the map update problems on "remove"
332         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
333           anUpdatedIter = myWaitForFinish.begin();
334         } else {
335           anUpdatedIter++;
336         }
337       } else {
338         anUpdatedIter++;
339       }
340     }
341     // the redisplay signal should be flushed in order 
342     // to erase the feature presentation in the viewer
343     // if should be done after removeFeature() of document,
344     // by this reason, upper processFeatures() do not perform this flush
345     Events_Loop::loop()->flush(kRedisplayEvent);
346
347     // in the end of transaction everything is updated, so clear the old objects
348     myIsParamUpdated = false;
349     myWaitForFinish.clear();
350   } else if (theMessage->eventID() == kReorderEvent) {
351     std::shared_ptr<ModelAPI_OrderUpdatedMessage> aMsg = 
352       std::dynamic_pointer_cast<ModelAPI_OrderUpdatedMessage>(theMessage);
353     if (aMsg->reordered().get())
354       addModified(aMsg->reordered(), aMsg->reordered()); // to update all attributes
355   }
356 }
357
358 void Model_Update::processFeatures(const bool theFlushRedisplay)
359 {
360    // perform update of everything if it is not performed right now or any preview is blocked
361   if (!myIsProcessed && !myIsPreviewBlocked) {
362     myIsProcessed = true;
363     #ifdef DEB_UPDATE
364       std::cout<<"****** Start processing"<<std::endl;
365     #endif
366
367     while(!myModified.empty()) {
368       processFeature(myModified.begin()->first);
369     }
370     myIsProcessed = false;
371
372     // to update the object browser if something is updated/created during executions
373     static Events_Loop* aLoop = Events_Loop::loop();
374     static const Events_ID kCreatedEvent= aLoop->eventByName(EVENT_OBJECT_CREATED);
375     aLoop->flush(kCreatedEvent);
376     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
377     aLoop->flush(kUpdatedEvent);
378
379     // flush to update display
380     if (theFlushRedisplay) {
381       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
382       aLoop->flush(EVENT_DISP);
383     }
384     #ifdef DEB_UPDATE
385       std::cout<<"****** End processing"<<std::endl;
386     #endif
387     myProcessed.clear();
388   }
389 }
390
391 // collects all the feautres this feature depends on: reasons
392 static void allReasons(FeaturePtr theFeature, std::set<FeaturePtr>& theReasons) {
393   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
394   theFeature->data()->referencesToObjects(aDeps);
395   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
396     anAttrsIter = aDeps.begin();
397   for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
398     if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
399       std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
400       for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
401         FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
402         if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
403           ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
404           if (aDepRes.get()) {
405             aDepFeat = (*aDepIter)->document()->feature(aDepRes);
406           }
407         }
408         if (aDepFeat.get() && aDepFeat->data()->isValid()) {
409           theReasons.insert(aDepFeat);
410         }
411       }
412     }
413   }
414   if (theFeature->getKind() == "Part") {
415     // part is not depended on its subs directly, but subs must be iterated anyway
416     CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
417     int aNum = aPart->numberOfSubs();
418     for(int a = 0; a < aNum; a++) {
419       FeaturePtr aSub = aPart->subFeature(a);
420       if (aSub.get() && aSub->data()->isValid()) {
421         theReasons.insert(aSub);
422       }
423     }
424   }
425 }
426
427 bool Model_Update::processFeature(FeaturePtr theFeature)
428 {
429   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
430
431   if (!theFeature->data()->isValid()) { // deleted feature, just remove from all containers
432     if (myModified.find(theFeature) != myModified.end())
433       myModified.erase(theFeature);
434     return false;
435   }
436
437   if (theFeature->isPersistentResult()) {
438     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
439       return false;
440   }
441
442   if (myProcessed.find(theFeature) == myProcessed.end()) {
443     myProcessed[theFeature] = 0;
444   } else {
445     int aCount = myProcessed[theFeature];
446     if (aCount > 100) { 
447       // too many repetition of processing (in VS it may crash on 330 with stack overflow)
448       Events_InfoMessage("Model_Update",
449         "Feature '%1' is updated in infinitive loop").arg(theFeature->data()->name()).send();
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   list<AttributePtr> aRefs = 
723     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
724   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     list<AttributePtr> aRefs = 
904       (*anObj)->data()->attributes(ModelAPI_AttributeSelection::typeId());
905     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 }