]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Update.cpp
Salome HOME
Merge branch 'Dev_1.5.0' of salome:modules/shaper into Dev_1.5.0
[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   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
402   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
403   for (; aRIter != aResults.cend(); aRIter++) {
404     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
405     if (!aRes->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
406       aRes->data()->execState(theState);
407       if (theState == ModelAPI_StateDone) // feature become "done", so execution changed results
408         myUpdated[aRes] = myModification;
409     }
410     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
411       aRes->data()->setUpdateID(theFeature->data()->updateID());
412     }
413     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
414     // iterate sub-bodies of compsolid
415     ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aRes);
416     if (aComp.get()) {
417       int aNumSub = aComp->numberOfSubs();
418       for(int a = 0; a < aNumSub; a++) {
419         ResultPtr aSub = aComp->subResult(a);
420         if (!aSub->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
421           aSub->data()->execState(theState);
422           if (theState == ModelAPI_StateDone) // feature become "done", so execution changed results
423             myUpdated[aSub] = myModification;
424         }
425         if (theFeature->data()->updateID() > aSub->data()->updateID()) {
426           aSub->data()->setUpdateID(theFeature->data()->updateID());
427         }
428         ModelAPI_EventCreator::get()->sendUpdated(aSub, EVENT_DISP);
429       }
430     }
431   }
432   // to redisplay "presentable" feature (for ex. distance constraint)
433   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
434   theFeature->data()->execState(theState);
435 }
436
437 /// Updates the state by the referenced object: if something bad with it, set state for this one
438 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
439 {
440   if (theTarget) {
441     ModelAPI_ExecState aRefState = theTarget->data()->execState();
442     if (aRefState == ModelAPI_StateMustBeUpdated) {
443       if (theCurrent == ModelAPI_StateDone)
444         return ModelAPI_StateMustBeUpdated;
445     } else if (aRefState != ModelAPI_StateDone) {
446       return ModelAPI_StateInvalidArgument;
447     }
448   }
449   return theCurrent;
450 }
451
452 bool Model_Update::isOlder(std::shared_ptr<ModelAPI_Feature> theFeature, 
453                            std::shared_ptr<ModelAPI_Object> theArgument)
454 {
455   int aFeatureID = theFeature->data()->updateID();
456   int anArgID = theArgument->data()->updateID();
457   if (aFeatureID < anArgID)
458     return true;
459   std::map<std::shared_ptr<ModelAPI_Object>, int >::iterator anAIter = myUpdated.find(theArgument);
460   if (anAIter == myUpdated.end())
461     return false;
462   std::map<std::shared_ptr<ModelAPI_Object>, int >::iterator aFIter = myUpdated.find(theFeature);
463   if (aFIter == myUpdated.end())
464     return true; // argument is updated, but feature is not updated at all
465   return aFIter->second < anAIter->second;
466 }
467
468 void Model_Update::updateArguments(FeaturePtr theFeature) {
469   // perform this method also for disabled features: to make "not done" state for
470   // features referenced to the active and modified features
471
472   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
473
474   ModelAPI_ExecState aState = theFeature->data()->execState();
475   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
476     aState = ModelAPI_StateMustBeUpdated;
477   }
478   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
479     aState = ModelAPI_StateMustBeUpdated;
480   // check the parameters state
481   // Double
482   std::list<AttributePtr> aDoubles =
483     theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
484   std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
485   for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
486     AttributeDoublePtr aDouble =
487       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
488     if (aDouble.get() && !aDouble->text().empty()) {
489       if (myIsParamUpdated) {
490         ModelAPI_AttributeEvalMessage::send(aDouble, this);
491       }
492       if (aDouble->expressionInvalid()) {
493         aState = ModelAPI_StateInvalidArgument;
494       }
495     }
496   }
497   // Point
498   {
499     std::list<AttributePtr> anAttributes =
500       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
501     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
502     for(; anIter != anAttributes.end(); anIter++) {
503       AttributePointPtr aPointAttribute =
504         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
505       if (aPointAttribute.get()) {
506         if (myIsParamUpdated) {
507           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
508         }
509         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
510           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
511           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
512           aState = ModelAPI_StateInvalidArgument;
513       }
514     }
515   }
516   // Point2D
517   {
518     std::list<AttributePtr> anAttributes =
519       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
520     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
521     for(; anIter != anAttributes.end(); anIter++) {
522       AttributePoint2DPtr aPoint2DAttribute =
523         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
524       if (aPoint2DAttribute.get()) {
525         if (myIsParamUpdated) {
526           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
527         }
528         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
529           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
530           aState = ModelAPI_StateInvalidArgument;
531       }
532     }
533   }
534
535   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
536   //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
537   // before execution update the selection attributes if any
538   list<AttributePtr> aRefs = 
539     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
540   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
541   for (; aRefsIter != aRefs.end(); aRefsIter++) {
542     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
543       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
544     ObjectPtr aContext = aSel->context();
545     // update argument only if the referenced object is changed
546     if (aContext.get() && !aContext->isDisabled()) {
547       bool isObligatory = !aFactory->isNotObligatory(
548         theFeature->getKind(), theFeature->data()->id(aSel)) &&
549         aFactory->isCase(theFeature, theFeature->data()->id(aSel));
550       if (isOlder(theFeature, aContext)) {
551         if (aState == ModelAPI_StateDone)
552           aState = ModelAPI_StateMustBeUpdated;
553         if (!aSel->update()) { // this must be done on execution since it may be long operation
554           if (isObligatory)
555             aState = ModelAPI_StateInvalidArgument;
556         }
557       } else if (aSel->isInvalid()) { // not needed to update, but invalid (stated previously)
558         if (isObligatory)
559           aState = ModelAPI_StateInvalidArgument;
560       }
561     }
562   }
563   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
564   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
565     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
566       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
567     for(int a = aSel->size() - 1; a >= 0; a--) {
568       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
569         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
570       if (aSelAttr) {
571         ObjectPtr aContext = aSelAttr->context();
572         // update argument onlt if the referenced object is changed
573         if (aContext.get() && !aContext->isDisabled()) {
574           bool isObligatory = !aFactory->isNotObligatory(
575             theFeature->getKind(), theFeature->data()->id(aSel)) &&
576             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
577           if (isOlder(theFeature, aContext)) {
578             if (aState == ModelAPI_StateDone)
579                 aState = ModelAPI_StateMustBeUpdated;
580             if (!aSelAttr->update()) {
581               if (isObligatory)
582                 aState = ModelAPI_StateInvalidArgument;
583             }
584           } else if (aSelAttr->isInvalid()) {
585             if (isObligatory)
586               aState = ModelAPI_StateInvalidArgument;
587           }
588         }
589       }
590     }
591   }
592   // check all references: if referenced objects are updated, this object also must be updated
593   // also check state of referenced objects: if they are not ready, inherit corresponding state
594   std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefsObj;
595   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
596   aData->referencesToObjects(aRefsObj);
597   std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefsObj.begin();
598   for(; aRef != aRefsObj.end(); aRef++) {
599     std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
600     for(; aRefObj != aRef->second.end(); aRefObj++) {
601       // if reference is null, it may mean that this reference is to other document
602       // the does not supported by RefList: parameters may be recomputed
603       if (!aRefObj->get() && theFeature->firstResult().get() && 
604                theFeature->firstResult()->groupName() == ModelAPI_ResultParameter::group()) {
605           if (aState == ModelAPI_StateDone)
606             aState = ModelAPI_StateMustBeUpdated;
607       } else if (aRefObj->get() && isOlder(theFeature, *aRefObj)) {
608         if (aState == ModelAPI_StateDone)
609           aState = ModelAPI_StateMustBeUpdated;
610       }
611       aState = stateByReference(*aRefObj, aState);
612     }
613   }
614   // composites sub-elements
615   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
616   // composite feature must be executed after sub-features execution
617   if (aCompos) {
618     // number of subs can be changed in execution: like fillet
619     int aNumSubs = aCompos->numberOfSubs();
620     for(int a = 0; a < aNumSubs; a++) {
621       FeaturePtr aSub = aCompos->subFeature(a);
622       if (aSub.get() && aState == ModelAPI_StateDone) {
623         if (isOlder(theFeature, aSub)) {
624           aState = ModelAPI_StateMustBeUpdated;
625         }
626         // also check that all results of subs were updated: composite also depends on the results
627         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
628         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aResults.begin();
629         for(; aResIter != aResults.end(); aResIter++) {
630           if (aResIter->get() && (*aResIter)->data()->isValid() && !(*aResIter)->isDisabled() &&
631               isOlder(theFeature, *aResIter)) {
632             aState = ModelAPI_StateMustBeUpdated;
633           }
634         }
635       }
636       if (a == aNumSubs - 1) // in case number of subs is changed, just recheck before end
637         aNumSubs = aCompos->numberOfSubs();
638     }
639   }
640
641
642   if (aState != ModelAPI_StateDone)
643     theFeature->data()->execState(aState);
644 }
645
646 void Model_Update::executeFeature(FeaturePtr theFeature)
647 {
648   // execute in try-catch to avoid internal problems of the feature
649   ModelAPI_ExecState aState = ModelAPI_StateDone;
650   theFeature->data()->execState(ModelAPI_StateDone);
651   try {
652     theFeature->execute();
653     if (theFeature->data()->execState() != ModelAPI_StateDone) {
654       aState = ModelAPI_StateExecFailed;
655     } else {
656       aState = ModelAPI_StateDone;
657       myWaitForFinish.insert(theFeature);
658     }
659   } catch(...) {
660     aState = ModelAPI_StateExecFailed;
661     Events_Error::send(
662       "Feature " + theFeature->getKind() + " has failed during the execution");
663   }
664   if (aState != ModelAPI_StateDone) {
665     theFeature->eraseResults();
666   }
667   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
668   redisplayWithResults(theFeature, aState);
669 }
670
671 void Model_Update::updateStability(void* theSender)
672 {
673   if (theSender) {
674     bool added = false; // object may be was crated
675     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
676     if (aSender && aSender->document()) {
677       FeaturePtr aFeatureSender = 
678         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
679       if (aFeatureSender.get()) {
680         Model_Objects* aDocObjects = 
681           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
682         if (aDocObjects) {
683           //aDocObjects->synchronizeBackRefs();
684           // remove or add all concealment refs from this feature
685           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
686           aSender->data()->referencesToObjects(aRefs);
687           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
688           for(; aRefIt != aRefs.end(); aRefIt++) {
689             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
690             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
691             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
692                // stability is only on results: feature to feature reference mean nested 
693               // features, that will remove nesting references
694               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
695                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
696                 std::shared_ptr<Model_Data> aData = 
697                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
698                 if (aFeatureSender->isStable()) {
699                   aData->addBackReference(aFeatureSender, aRefIt->first);
700                 } else {
701                   aData->removeBackReference(aFeatureSender, aRefIt->first);
702                   added = true; // remove of concealment may be caused creation of some result
703                 }
704               }
705             }
706           }
707         }
708       }
709     }
710     if (added) {
711       static Events_Loop* aLoop = Events_Loop::loop();
712       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
713       aLoop->flush(kEventCreated);
714     }
715   }
716 }
717
718 ///////////////// Updated items iterator ////////////////////////
719 Model_Update::IterationItem::IterationItem(std::shared_ptr<ModelAPI_CompositeFeature> theFeature)
720 {
721   myBreaked = false;
722   myIsVirtual = false;
723   myMain = theFeature;
724   myObjects = NULL;
725   if (!myMain.get() && ModelAPI_Session::get()->hasModuleDocument()) { // no document => nothing to do
726     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
727     myObjects = std::dynamic_pointer_cast<Model_Document>(aRootDoc)->objects();
728   }
729   mySkipNext = false;
730 }
731
732 void Model_Update::IterationItem::next()
733 {
734   if (mySkipNext) { // ignore one next
735     mySkipNext = false;
736     return;
737   }
738   if (!myBreaked) {
739     if (myMain.get()) {
740       myIndex++;
741       int aNumSubs = myMain->numberOfSubs();
742       if (myIndex == aNumSubs)
743         return;
744       // skip sub-objects, that are subs not only for this: sketch elements relatively to Part
745       for(FeaturePtr aSub = myMain->subFeature(myIndex); aSub.get();
746           aSub = myMain->subFeature(myIndex)) {
747         aSub = myMain->subFeature(myIndex);
748         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(aSub);
749         if (!anOwner.get() || anOwner == myMain) {
750           break;
751         }
752         myIndex++;
753         if (myIndex == aNumSubs)
754           break;
755       }
756     } else if (mySub.get()) {
757       while(mySub.get()) {
758         mySub = myObjects->nextFeature(mySub);
759         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(mySub);
760         // skip sub-objects, that are subs not only for this: sketch elements relatively to PartSet
761         if (!anOwner.get()) {
762           break;
763         }
764       }
765     }
766   }
767 }
768
769 bool Model_Update::IterationItem::more()
770 {
771   if (myBreaked)
772     return false;
773   if (myMain.get())
774     return myIndex < myMain->numberOfSubs();
775   return mySub.get() != NULL;
776 }
777
778 FeaturePtr Model_Update::IterationItem::current()
779 {
780   if (myMain.get())
781     return myMain->subFeature(myIndex);
782   return mySub;
783 }
784
785 void Model_Update::IterationItem::setBreaked()
786 {
787   if (!myIsVirtual)
788     myBreaked = true;
789 }
790
791 void Model_Update::IterationItem::startIteration(const bool theVirtual)
792 {
793   myIsVirtual = theVirtual;
794   if (myMain.get()) {
795     myIndex = 0;
796   } else if (myObjects) {
797     mySub = myObjects->firstFeature();
798   }
799 }
800
801 bool Model_Update::IterationItem::isIterated(FeaturePtr theFeature)
802 {
803   if (myMain.get()) {
804     if (myMain->isSub(theFeature)) {
805       CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
806       if (!anOwner.get() || anOwner == myMain)
807         return true;
808     }
809     return false;
810   }
811   // for the root document just check that this feature in this document and it is not sub
812   return myObjects->owner() == theFeature->document() && 
813          !ModelAPI_Tools::compositeOwner(theFeature).get();
814 }
815
816 bool Model_Update::IterationItem::isEarlierThanCurrent(FeaturePtr theFeature)
817 {
818   if (myMain.get()) {
819     for(int a = 0; a < myIndex; a++) {
820       if (myMain->subFeature(a) == theFeature)
821         return true;
822     }
823   } else {
824     return !mySub.get() && !myObjects->isLater(theFeature, mySub);
825   }
826   return false;
827 }
828
829 void Model_Update::IterationItem::setCurrentBefore(FeaturePtr theFeature)
830 {
831   if (myMain.get()) {
832     for(int a = 0; a < myIndex; a++) {
833       if (myMain->subFeature(a) == theFeature) {
834         myIndex = a;
835         break;
836       }
837     }
838   } else {
839     mySub = theFeature;
840   }
841   mySkipNext = true;
842 }