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