Salome HOME
Issue #1062: Parameter value is thrown down in the point selector control
[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 kRebuildEvent = aLoop->eventByName("Rebuild");
44   aLoop->registerListener(this, kRebuildEvent);
45   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
46   aLoop->registerListener(this, kCreatedEvent);
47   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
48   aLoop->registerListener(this, kUpdatedEvent);
49   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
50   aLoop->registerListener(this, kMovedEvent);
51   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
52   aLoop->registerListener(this, kOpFinishEvent);
53   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
54   aLoop->registerListener(this, kOpAbortEvent);
55   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
56   aLoop->registerListener(this, kOpStartEvent);
57   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
58   aLoop->registerListener(this, kStabilityEvent);
59
60   /* not needed now with history line
61   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
62                                    Config_Prop::Boolean, "false");*/
63   myIsAutomatic = true;
64   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
65   myIsParamUpdated = false;
66   myIsFinish = false;
67   myModification = 0;
68   myModificationInStartProcessing = 0;
69 }
70
71 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
72 {
73   static Events_Loop* aLoop = Events_Loop::loop();
74   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
75   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
76   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
77   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
78   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
79   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
80   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
81   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
82   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
83 #ifdef DEB_UPDATE
84   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
85 #endif
86   if (theMessage->eventID() == kStabilityEvent)
87     updateStability(theMessage->sender());
88   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
89     /*bool aPropVal =
90       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
91     if (aPropVal != myIsAutomatic) { // something is changed
92       // myIsAutomatic = aPropVal;
93       if (myIsAutomatic) // higher level of automatization => to rebuild
94         processOperation(false);
95     }*/
96     return;
97   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
98     processOperation(true);
99   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
100              theMessage->eventID() == kMovedEvent) {
101     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
102         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
103     const std::set<ObjectPtr>& anObjs = aMsg->objects();
104     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
105     bool isOnlyResults = true; // check that only results were changed: only redisplay is needed
106     for(; anObjIter != anObjs.cend(); anObjIter++) {
107       if (!std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIter).get()) {
108         isOnlyResults = false;
109       }
110       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
111         myIsParamUpdated = true;
112       }
113       if (myIsExecuted) // modifications from outside are with never IDs to take them into account in the current updates
114         myModification++;
115       // on undo/redo, abort do not update persisten features
116       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
117       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures() ||
118           (anUpdated.get() && !anUpdated->isPersistentResult())) {
119         // created objects are always must be up to date (python box feature)
120         // and updated not in internal uptation chain
121         myUpdated[*anObjIter] = myModification;
122
123         // something is updated during the execution: re-execute it (sketch update by parameters or
124         // Box macro that updates the upper features during the execution)
125         if (myIsExecuted) { 
126           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
127           if (anUpdated.get() &&  anUpdated->data()->isValid())
128             iterateUpdateBreak(anUpdated);
129         }
130 #ifdef DEB_UPDATE
131         if (myIsExecuted) std::cout<<"During execution ";
132         if ((*anObjIter)->data() && (*anObjIter)->data()->isValid()) {
133           std::cout<<"add updated "<<(*anObjIter)->groupName()<<" "
134             <<(*anObjIter)->data()->name()<<std::endl;
135         }
136 #endif
137       }
138
139     }
140     // this event is for solver update, not here, do not react immediately
141     if (!isOnlyResults && !(theMessage->eventID() == kMovedEvent))
142       processOperation(false);
143   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
144       theMessage->eventID() == kOpStartEvent) {
145
146     if (!(theMessage->eventID() == kOpStartEvent)) {
147       myIsFinish = true;
148       processOperation(true, theMessage->eventID() == kOpFinishEvent);
149       myIsFinish = false;
150     }
151     // remove all macros before clearing all created
152     std::set<ObjectPtr>::iterator anUpdatedIter = myWaitForFinish.begin();
153     while(anUpdatedIter != myWaitForFinish.end()) {
154       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
155       if (aFeature.get()) {
156         // remove macro on finish
157         if (aFeature->isMacro()) {
158           aFeature->document()->removeFeature(aFeature);
159           myWaitForFinish.erase(aFeature);
160         }
161         // to avoid the map update problems on "remove"
162         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
163           anUpdatedIter = myWaitForFinish.begin();
164         } else {
165           anUpdatedIter++;
166         }
167       } else {
168         anUpdatedIter++;
169       }
170     }
171     // in the end of transaction everything is updated, so clear the old objects (the only one
172     // place where results are cleared)
173     myIsParamUpdated = false;
174     myUpdated.clear();
175     myModification = 0;
176     myWaitForFinish.clear();
177   }
178 }
179
180 bool Model_Update::iterateUpdate(std::shared_ptr<ModelAPI_CompositeFeature> theFeature)
181 {
182   myProcessIterator.push_back(IterationItem(theFeature));
183   IterationItem& aCurrent = *myProcessIterator.rbegin();
184   // two cycles: parameters must be processed first
185   for(aCurrent.startIteration(true); aCurrent.more(); aCurrent.next()) {
186     if (aCurrent.current()->getKind() == "Parameter")
187       updateFeature(aCurrent.current());
188   }
189   // number of subs can be changed in execution: like fillet
190   for(aCurrent.startIteration(false); aCurrent.more(); aCurrent.next()) {
191     FeaturePtr aSub = aCurrent.current();
192     if (aSub->getKind() != "Parameter")
193       updateFeature(aSub);
194   }
195   // processing is finished, so, remove the iterated
196   bool aResult = !aCurrent.isBreaked(); // iteration is finished correctly, not breaked
197   myProcessIterator.pop_back();
198   return aResult;
199 }
200
201 void Model_Update::iterateUpdateBreak(std::shared_ptr<ModelAPI_Feature> theFeature)
202 {
203   // checking that this feature is before the current iterated one: otherwise break is not needed
204   std::list<IterationItem>::reverse_iterator aProcessed = myProcessIterator.rbegin();
205   for(; aProcessed != myProcessIterator.rend(); aProcessed++) {
206     if (aProcessed->isIterated(theFeature)) {
207       if (aProcessed->isEarlierThanCurrent(theFeature)) {
208         // break all lower level iterators
209         std::list<IterationItem>::reverse_iterator aBreaked = myProcessIterator.rbegin();
210         for(; aBreaked != aProcessed; aBreaked++) {
211           aBreaked->setBreaked();
212         }
213         // for the current breaked, set iteration to this feature precisely
214         aBreaked->setCurrentBefore(theFeature);
215         //myModification++;
216       }
217       // the iterator that contains breaked is found, so, nothing else is needed
218       return;
219     }
220   }
221   // if this feature is not found in the list of the currently iterated, try to break the parent
222   FeaturePtr aParent = ModelAPI_Tools::compositeOwner(theFeature);
223   if (aParent.get())
224     iterateUpdateBreak(aParent);
225 }
226
227 void Model_Update::processOperation(const bool theTotalUpdate, const bool theFinish)
228 {
229   // perform update of everything if needed
230   if (!myIsExecuted) {
231     #ifdef DEB_UPDATE
232       std::cout<<"****** Start processing"<<std::endl;
233     #endif
234     myIsExecuted = true;
235     myModificationInStartProcessing = myModification;
236
237     bool isAutomaticChanged = false;
238
239     if (theTotalUpdate && !myIsAutomatic) { // Apply button now works as "Rebuild"
240       isAutomaticChanged = true;
241       myIsAutomatic = true;
242     }
243     // init iteration from the root document
244     iterateUpdate(CompositeFeaturePtr());
245
246     if (isAutomaticChanged) myIsAutomatic = false;
247     myIsExecuted = false;
248     // flush updates just before "myModification" increment: to distinguish
249     // updates by "execute" produced by this updater and other updates, coming outside,
250     // which are really important for "processEvent" of this updater
251     static Events_Loop* aLoop = Events_Loop::loop();
252     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
253     aLoop->flush(kUpdatedEvent);
254     myModification++;
255
256     // flush to update display
257     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
258     aLoop->flush(EVENT_DISP);
259     #ifdef DEB_UPDATE
260       std::cout<<"****** End processing"<<std::endl;
261     #endif
262   }
263 }
264
265 bool Model_Update::isProcessed(const int theModificationID)
266 {
267   return theModificationID >= myModificationInStartProcessing && 
268          theModificationID <= myModification;
269 }
270
271 void Model_Update::updateFeature(FeaturePtr theFeature)
272 {
273   // check all features this feature depended on (recursive call of updateFeature)
274   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
275
276   if (theFeature->isDisabled()) {
277     // possibly sub-elements are not disabled?
278     CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
279     if (aCompos)
280       iterateUpdate(aCompos);
281     return;
282   }
283
284   // do not execute the composite that contains the current
285   bool isPostponedMain = false;
286   CompositeFeaturePtr aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
287   if (theFeature->getKind() == "ExtrusionSketch" && aMain.get()) {
288     CompositeFeaturePtr aCurrentOwner = 
289       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
290     isPostponedMain = aCurrentOwner.get() && aMain->isSub(aCurrentOwner);
291   }
292
293   #ifdef DEB_UPDATE
294     std::cout<<"Update Feature "<<theFeature->name()<<std::endl;
295   #endif
296   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
297   // If automatice update is not needed and feature attributes were not updated right now,
298   // do not execute it and do not update arguments.
299   if (!myIsAutomatic && 
300        (myUpdated.find(theFeature) == myUpdated.end() || !isProcessed(myUpdated[theFeature]))
301        && !aCompos.get()) {
302     // execute will be performed later, but some features may have not-result 
303     // presentations, so call update for them (like coincidence in the sketcher)
304     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
305     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
306     return;
307   }
308
309   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
310   updateArguments(theFeature);
311
312   // composite feature must be executed after sub-features execution
313   if (aCompos) {
314     if (!iterateUpdate(aCompos))
315       return; // iteration was interrupted, so, interrupt the update of this feature (it will be done later)
316     // reupdate arguments of composite feature: it may be changed during subs execution
317
318     // issue 955: extrusion fuse sketch naming must be updated after the sketch update 
319     // so, comment this: if (theFeature->data()->execState() != ModelAPI_StateMustBeUpdated)
320       updateArguments(theFeature);
321   }
322   // this checking must be after the composite feature sub-elements processing:
323   // composite feature status may depend on it's subelements
324   if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
325     theFeature->eraseResults();
326     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
327     return;
328   }
329
330   // only the currently updated features are executed
331   bool aJustUpdated = myUpdated.find(theFeature) != myUpdated.end();
332   if (aJustUpdated) {
333     // if preview is not needed, the created feature was not updated before, so, myModification is not actual for this
334     if (theFeature->isPreviewNeeded()) {
335       aJustUpdated = isProcessed(myUpdated[theFeature]);
336     }
337   }
338
339   if (myIsAutomatic && theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
340     aJustUpdated = true;
341
342   // On abort, undo or redo execute is not needed: results in document are updated automatically
343   // But redisplay is needed: results are updated, must be also updated in the viewer.
344   if (aJustUpdated && 
345       !std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures()) {
346     if (!theFeature->isPersistentResult()) { // not persistent must be re-executed on abort, etc.
347       ModelAPI_ExecState aState = theFeature->data()->execState();
348       if (aFactory->validate(theFeature)) {
349         executeFeature(theFeature);
350       } else {
351         theFeature->eraseResults();
352         redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
353       }
354     } else {
355       redisplayWithResults(theFeature, ModelAPI_StateNothing);
356       if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) { // it is done (in the tree)
357         theFeature->data()->execState(ModelAPI_StateDone);
358       }
359       // it will be not updated with new modifications: only the currently updated features are updated
360       //if (myUpdated.find(theFeature) != myUpdated.end()) {
361       //  myUpdated.erase(theFeature); // do not update this persistent feature even in the future
362       //}
363     }
364     return;
365   }
366
367   // execute feature if it must be updated
368   if (theFeature->isPreviewNeeded() || myIsFinish) {
369     if (aJustUpdated) {
370       ModelAPI_ExecState aState = theFeature->data()->execState();
371       if (aFactory->validate(theFeature)) {
372         if (!isPostponedMain) {
373           #ifdef DEB_UPDATE
374             std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
375           #endif
376           executeFeature(theFeature);
377         }
378       } else {
379         #ifdef DEB_UPDATE
380           std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
381         #endif
382         theFeature->eraseResults();
383         redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
384       }
385     }
386   } else { // preview is not needed => make state Done
387     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
388       theFeature->data()->execState(ModelAPI_StateDone);
389       if (aJustUpdated) {// store that it must be updated on finish
390         myUpdated[theFeature] = myModification;
391         aFactory->validate(theFeature); // need to be validated to update the "Apply" state if not previewed
392       }
393     }
394   }
395 }
396
397 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
398 {
399   // make updated and redisplay all results
400   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
401
402   std::list<ResultPtr> allResults;
403   ModelAPI_Tools::allResults(theFeature, allResults);
404   std::list<ResultPtr>::iterator aRIter = allResults.begin();
405   for (; aRIter != allResults.cend(); aRIter++) {
406     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
407     if (!aRes->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
408       aRes->data()->execState(theState);
409       if (theState == ModelAPI_StateDone) // feature become "done", so execution changed results
410         myUpdated[aRes] = myModification;
411     }
412     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
413       aRes->data()->setUpdateID(theFeature->data()->updateID());
414     }
415     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
416   }
417   // to redisplay "presentable" feature (for ex. distance constraint)
418   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
419   theFeature->data()->execState(theState);
420   myUpdated[theFeature] = myModification; // feature is also updated to avoid re-updation of it
421 }
422
423 /// Updates the state by the referenced object: if something bad with it, set state for this one
424 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
425 {
426   if (theTarget) {
427     ModelAPI_ExecState aRefState = theTarget->data()->execState();
428     if (aRefState == ModelAPI_StateMustBeUpdated) {
429       if (theCurrent == ModelAPI_StateDone)
430         return ModelAPI_StateMustBeUpdated;
431     } else if (aRefState != ModelAPI_StateDone) {
432       return ModelAPI_StateInvalidArgument;
433     }
434   }
435   return theCurrent;
436 }
437
438 bool Model_Update::isOlder(std::shared_ptr<ModelAPI_Feature> theFeature, 
439                            std::shared_ptr<ModelAPI_Object> theArgument)
440 {
441   int aFeatureID = theFeature->data()->updateID();
442   int anArgID = theArgument->data()->updateID();
443   if (aFeatureID < anArgID)
444     return true;
445   std::map<std::shared_ptr<ModelAPI_Object>, int >::iterator anAIter = myUpdated.find(theArgument);
446   if (anAIter == myUpdated.end())
447     return false;
448   // for the modification IDs compare results: modification ID of feature means only that attributes
449   // of this feature were updated, but if results are obsolete relatively to the referenced results,
450   // the feature must be updated
451   std::list<ResultPtr> aResults;
452   ModelAPI_Tools::allResults(theFeature, aResults);
453   std::list<ResultPtr>::iterator aRIter = aResults.begin();
454   for (; aRIter != aResults.cend(); aRIter++) {
455     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
456     if (!aRes->isDisabled()) {
457       std::map<std::shared_ptr<ModelAPI_Object>, int >::iterator anRIter = myUpdated.find(aRes);
458       if (anRIter == myUpdated.end()) // not updated at all
459         return true;
460       if (anRIter->second < anAIter->second)
461         return true;
462     }
463   }
464   // also check a feature: some have no parameters,
465   // but must be updated anyway (like Coincidence of sketch) to be redisplayed
466   std::map<std::shared_ptr<ModelAPI_Object>, int >::iterator aFIter = myUpdated.find(theFeature);
467   if (aFIter == myUpdated.end())
468     return true; // argument is updated, but feature is not updated at all
469   return aFIter->second < anAIter->second;
470 }
471
472 void Model_Update::updateArguments(FeaturePtr theFeature) {
473   // perform this method also for disabled features: to make "not done" state for
474   // features referenced to the active and modified features
475
476   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
477
478   ModelAPI_ExecState aState = theFeature->data()->execState();
479   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
480     aState = ModelAPI_StateMustBeUpdated;
481   }
482   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
483     aState = ModelAPI_StateMustBeUpdated;
484   // check the parameters state
485   // Double
486   std::list<AttributePtr> aDoubles =
487     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
488   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
489   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
490     AttributeDoublePtr aDouble =
491       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
492     if (aDouble.get() && !aDouble->text().empty()) {
493       if (myIsParamUpdated) {
494         ModelAPI_AttributeEvalMessage::send(aDouble, this);
495       }
496       if (aDouble->expressionInvalid()) {
497         aState = ModelAPI_StateInvalidArgument;
498       }
499     }
500   }
501   // Point
502   {
503     std::list<AttributePtr> anAttributes =
504       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
505     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
506     for(; anIter != anAttributes.end(); anIter++) {
507       AttributePointPtr aPointAttribute =
508         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
509       if (aPointAttribute.get()) {
510         if (myIsParamUpdated) {
511           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
512         }
513         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
514           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
515           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
516           aState = ModelAPI_StateInvalidArgument;
517       }
518     }
519   }
520   // Point2D
521   {
522     std::list<AttributePtr> anAttributes =
523       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
524     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
525     for(; anIter != anAttributes.end(); anIter++) {
526       AttributePoint2DPtr aPoint2DAttribute =
527         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
528       if (aPoint2DAttribute.get()) {
529         if (myIsParamUpdated) {
530           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
531         }
532         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
533           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
534           aState = ModelAPI_StateInvalidArgument;
535       }
536     }
537   }
538
539   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
540   //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
541   // before execution update the selection attributes if any
542   list<AttributePtr> aRefs = 
543     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
544   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
545   for (; aRefsIter != aRefs.end(); aRefsIter++) {
546     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
547       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
548     ObjectPtr aContext = aSel->context();
549     // update argument only if the referenced object is changed
550     if (aContext.get() && !aContext->isDisabled()) {
551       bool isObligatory = !aFactory->isNotObligatory(
552         theFeature->getKind(), theFeature->data()->id(aSel)) &&
553         aFactory->isCase(theFeature, theFeature->data()->id(aSel));
554       if (isOlder(theFeature, aContext)) {
555         if (aState == ModelAPI_StateDone)
556           aState = ModelAPI_StateMustBeUpdated;
557         if (!aSel->update()) { // this must be done on execution since it may be long operation
558           if (isObligatory)
559             aState = ModelAPI_StateInvalidArgument;
560         }
561       } else if (aSel->isInvalid()) { // not needed to update, but invalid (stated previously)
562         if (isObligatory)
563           aState = ModelAPI_StateInvalidArgument;
564       }
565     }
566   }
567   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
568   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
569     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
570       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
571     for(int a = aSel->size() - 1; a >= 0; a--) {
572       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
573         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
574       if (aSelAttr) {
575         ObjectPtr aContext = aSelAttr->context();
576         // update argument onlt if the referenced object is changed
577         if (aContext.get() && !aContext->isDisabled()) {
578           bool isObligatory = !aFactory->isNotObligatory(
579             theFeature->getKind(), theFeature->data()->id(aSel)) &&
580             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
581           if (isOlder(theFeature, aContext)) {
582             if (aState == ModelAPI_StateDone)
583                 aState = ModelAPI_StateMustBeUpdated;
584             if (!aSelAttr->update()) {
585               if (isObligatory)
586                 aState = ModelAPI_StateInvalidArgument;
587             }
588           } else if (aSelAttr->isInvalid()) {
589             if (isObligatory)
590               aState = ModelAPI_StateInvalidArgument;
591           }
592         }
593       }
594     }
595   }
596   // check all references: if referenced objects are updated, this object also must be updated
597   // also check state of referenced objects: if they are not ready, inherit corresponding state
598   std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefsObj;
599   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
600   aData->referencesToObjects(aRefsObj);
601   std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefsObj.begin();
602   for(; aRef != aRefsObj.end(); aRef++) {
603     std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
604     for(; aRefObj != aRef->second.end(); aRefObj++) {
605       // if reference is null, it may mean that this reference is to other document
606       // the does not supported by RefList: parameters may be recomputed
607       if (!aRefObj->get() && theFeature->firstResult().get() && 
608                theFeature->firstResult()->groupName() == ModelAPI_ResultParameter::group()) {
609           if (aState == ModelAPI_StateDone)
610             aState = ModelAPI_StateMustBeUpdated;
611       } else if (aRefObj->get() && isOlder(theFeature, *aRefObj)) {
612         if (aState == ModelAPI_StateDone)
613           aState = ModelAPI_StateMustBeUpdated;
614       }
615       aState = stateByReference(*aRefObj, aState);
616     }
617   }
618   // composites sub-elements
619   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
620   // composite feature must be executed after sub-features execution
621   if (aCompos) {
622     // number of subs can be changed in execution: like fillet
623     int aNumSubs = aCompos->numberOfSubs();
624     for(int a = 0; a < aNumSubs; a++) {
625       FeaturePtr aSub = aCompos->subFeature(a);
626       if (aSub.get() && aState == ModelAPI_StateDone) {
627         if (isOlder(theFeature, aSub)) {
628           aState = ModelAPI_StateMustBeUpdated;
629         }
630         // also check that all results of subs were updated: composite also depends on the results
631         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
632         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aResults.begin();
633         for(; aResIter != aResults.end(); aResIter++) {
634           if (aResIter->get() && (*aResIter)->data()->isValid() && !(*aResIter)->isDisabled() &&
635               isOlder(theFeature, *aResIter)) {
636             aState = ModelAPI_StateMustBeUpdated;
637           }
638         }
639       }
640       if (a == aNumSubs - 1) // in case number of subs is changed, just recheck before end
641         aNumSubs = aCompos->numberOfSubs();
642     }
643   }
644
645
646   if (aState != ModelAPI_StateDone)
647     theFeature->data()->execState(aState);
648 }
649
650 void Model_Update::executeFeature(FeaturePtr theFeature)
651 {
652   // execute in try-catch to avoid internal problems of the feature
653   ModelAPI_ExecState aState = ModelAPI_StateDone;
654   theFeature->data()->execState(ModelAPI_StateDone);
655   try {
656     theFeature->execute();
657     if (theFeature->data()->execState() != ModelAPI_StateDone) {
658       aState = ModelAPI_StateExecFailed;
659     } else {
660       aState = ModelAPI_StateDone;
661       myWaitForFinish.insert(theFeature);
662     }
663   } catch(...) {
664     aState = ModelAPI_StateExecFailed;
665     Events_Error::send(
666       "Feature " + theFeature->getKind() + " has failed during the execution");
667   }
668   if (aState != ModelAPI_StateDone) {
669     theFeature->eraseResults();
670   }
671   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
672   redisplayWithResults(theFeature, aState);
673 }
674
675 void Model_Update::updateStability(void* theSender)
676 {
677   if (theSender) {
678     bool added = false; // object may be was crated
679     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
680     if (aSender && aSender->document()) {
681       FeaturePtr aFeatureSender = 
682         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
683       if (aFeatureSender.get()) {
684         Model_Objects* aDocObjects = 
685           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
686         if (aDocObjects) {
687           //aDocObjects->synchronizeBackRefs();
688           // remove or add all concealment refs from this feature
689           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
690           aSender->data()->referencesToObjects(aRefs);
691           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
692           for(; aRefIt != aRefs.end(); aRefIt++) {
693             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
694             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
695             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
696                // stability is only on results: feature to feature reference mean nested 
697               // features, that will remove nesting references
698               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
699                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
700                 std::shared_ptr<Model_Data> aData = 
701                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
702                 if (aFeatureSender->isStable()) {
703                   aData->addBackReference(aFeatureSender, aRefIt->first);
704                 } else {
705                   aData->removeBackReference(aFeatureSender, aRefIt->first);
706                   added = true; // remove of concealment may be caused creation of some result
707                 }
708               }
709             }
710           }
711         }
712       }
713     }
714     if (added) {
715       static Events_Loop* aLoop = Events_Loop::loop();
716       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
717       aLoop->flush(kEventCreated);
718     }
719   }
720 }
721
722 ///////////////// Updated items iterator ////////////////////////
723 Model_Update::IterationItem::IterationItem(std::shared_ptr<ModelAPI_CompositeFeature> theFeature)
724 {
725   myBreaked = false;
726   myIsVirtual = false;
727   myMain = theFeature;
728   myObjects = NULL;
729   if (!myMain.get() && ModelAPI_Session::get()->hasModuleDocument()) { // no document => nothing to do
730     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
731     myObjects = std::dynamic_pointer_cast<Model_Document>(aRootDoc)->objects();
732   }
733   mySkipNext = false;
734 }
735
736 void Model_Update::IterationItem::next()
737 {
738   if (mySkipNext) { // ignore one next
739     mySkipNext = false;
740     return;
741   }
742   if (!myBreaked) {
743     if (myMain.get()) {
744       myIndex++;
745       int aNumSubs = myMain->numberOfSubs();
746       if (myIndex == aNumSubs)
747         return;
748       // skip sub-objects, that are subs not only for this: sketch elements relatively to Part
749       for(FeaturePtr aSub = myMain->subFeature(myIndex); aSub.get();
750           aSub = myMain->subFeature(myIndex)) {
751         aSub = myMain->subFeature(myIndex);
752         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(aSub);
753         if (!anOwner.get() || anOwner == myMain) {
754           break;
755         }
756         myIndex++;
757         if (myIndex == aNumSubs)
758           break;
759       }
760     } else if (mySub.get()) {
761       while(mySub.get()) {
762         mySub = myObjects->nextFeature(mySub);
763         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(mySub);
764         // skip sub-objects, that are subs not only for this: sketch elements relatively to PartSet
765         if (!anOwner.get()) {
766           break;
767         }
768       }
769     }
770   }
771 }
772
773 bool Model_Update::IterationItem::more()
774 {
775   if (myBreaked)
776     return false;
777   if (myMain.get())
778     return myIndex < myMain->numberOfSubs();
779   return mySub.get() != NULL;
780 }
781
782 FeaturePtr Model_Update::IterationItem::current()
783 {
784   if (myMain.get())
785     return myMain->subFeature(myIndex);
786   return mySub;
787 }
788
789 void Model_Update::IterationItem::setBreaked()
790 {
791   if (!myIsVirtual)
792     myBreaked = true;
793 }
794
795 void Model_Update::IterationItem::startIteration(const bool theVirtual)
796 {
797   myIsVirtual = theVirtual;
798   if (myMain.get()) {
799     myIndex = 0;
800   } else if (myObjects) {
801     mySub = myObjects->firstFeature();
802   }
803 }
804
805 bool Model_Update::IterationItem::isIterated(FeaturePtr theFeature)
806 {
807   if (myMain.get()) {
808     if (myMain->isSub(theFeature)) {
809       CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
810       if (!anOwner.get() || anOwner == myMain)
811         return true;
812     }
813     return false;
814   }
815   // for the root document just check that this feature in this document and it is not sub
816   return myObjects->owner() == theFeature->document() && 
817          !ModelAPI_Tools::compositeOwner(theFeature).get();
818 }
819
820 bool Model_Update::IterationItem::isEarlierThanCurrent(FeaturePtr theFeature)
821 {
822   if (myMain.get()) {
823     for(int a = 0; a < myIndex; a++) {
824       if (myMain->subFeature(a) == theFeature)
825         return true;
826     }
827   } else {
828     return !mySub.get() && !myObjects->isLater(theFeature, mySub);
829   }
830   return false;
831 }
832
833 void Model_Update::IterationItem::setCurrentBefore(FeaturePtr theFeature)
834 {
835   if (myMain.get()) {
836     for(int a = 0; a < myIndex; a++) {
837       if (myMain->subFeature(a) == theFeature) {
838         myIndex = a;
839         break;
840       }
841     }
842   } else {
843     mySub = theFeature;
844   }
845   mySkipNext = true;
846 }