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