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