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