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