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