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