Salome HOME
Issue #1305: Make different gray color for selectable and non-selectable items
[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   // Integer
492   {
493     std::list<AttributePtr> anAttrinbutes =
494       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
495     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
496     for(; anIter != anAttrinbutes.end(); anIter++) {
497       AttributeIntegerPtr anAttribute =
498         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
499       if (anAttribute.get() && !anAttribute->text().empty()) {
500         if (myIsParamUpdated) {
501           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
502         }
503         if (anAttribute->expressionInvalid()) {
504           aState = ModelAPI_StateInvalidArgument;
505         }
506       }
507     }
508   }
509   // Double
510   {
511     std::list<AttributePtr> aDoubles =
512       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
513     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
514     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
515       AttributeDoublePtr aDouble =
516         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
517       if (aDouble.get() && !aDouble->text().empty()) {
518         if (myIsParamUpdated) {
519           ModelAPI_AttributeEvalMessage::send(aDouble, this);
520         }
521         if (aDouble->expressionInvalid()) {
522           aState = ModelAPI_StateInvalidArgument;
523         }
524       }
525     }
526   }
527   // Point
528   {
529     std::list<AttributePtr> anAttributes =
530       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
531     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
532     for(; anIter != anAttributes.end(); anIter++) {
533       AttributePointPtr aPointAttribute =
534         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
535       if (aPointAttribute.get()) {
536         if (myIsParamUpdated) {
537           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
538         }
539         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
540           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
541           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
542           aState = ModelAPI_StateInvalidArgument;
543       }
544     }
545   }
546   // Point2D
547   {
548     std::list<AttributePtr> anAttributes =
549       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
550     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
551     for(; anIter != anAttributes.end(); anIter++) {
552       AttributePoint2DPtr aPoint2DAttribute =
553         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
554       if (aPoint2DAttribute.get()) {
555         if (myIsParamUpdated) {
556           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
557         }
558         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
559           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
560           aState = ModelAPI_StateInvalidArgument;
561       }
562     }
563   }
564
565   //if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
566   //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
567   // before execution update the selection attributes if any
568   list<AttributePtr> aRefs = 
569     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
570   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
571   for (; aRefsIter != aRefs.end(); aRefsIter++) {
572     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
573       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
574     ObjectPtr aContext = aSel->context();
575     // update argument only if the referenced object is changed
576     if (aContext.get() && !aContext->isDisabled()) {
577       bool isObligatory = !aFactory->isNotObligatory(
578         theFeature->getKind(), theFeature->data()->id(aSel)) &&
579         aFactory->isCase(theFeature, theFeature->data()->id(aSel));
580       if (isOlder(theFeature, aContext)) {
581         if (aState == ModelAPI_StateDone)
582           aState = ModelAPI_StateMustBeUpdated;
583         if (!aSel->update()) { // this must be done on execution since it may be long operation
584           if (isObligatory)
585             aState = ModelAPI_StateInvalidArgument;
586         }
587       } else if (aSel->isInvalid()) { // not needed to update, but invalid (stated previously)
588         if (isObligatory)
589           aState = ModelAPI_StateInvalidArgument;
590       }
591     }
592   }
593   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
594   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
595     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
596       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
597     for(int a = aSel->size() - 1; a >= 0; a--) {
598       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
599         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
600       if (aSelAttr) {
601         ObjectPtr aContext = aSelAttr->context();
602         // update argument onlt if the referenced object is changed
603         if (aContext.get() && !aContext->isDisabled()) {
604           bool isObligatory = !aFactory->isNotObligatory(
605             theFeature->getKind(), theFeature->data()->id(aSel)) &&
606             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
607           if (isOlder(theFeature, aContext)) {
608             if (aState == ModelAPI_StateDone)
609                 aState = ModelAPI_StateMustBeUpdated;
610             if (!aSelAttr->update()) {
611               if (isObligatory)
612                 aState = ModelAPI_StateInvalidArgument;
613             }
614           } else if (aSelAttr->isInvalid()) {
615             if (isObligatory)
616               aState = ModelAPI_StateInvalidArgument;
617           }
618         }
619       }
620     }
621   }
622   // check all references: if referenced objects are updated, this object also must be updated
623   // also check state of referenced objects: if they are not ready, inherit corresponding state
624   std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefsObj;
625   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
626   aData->referencesToObjects(aRefsObj);
627   std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefsObj.begin();
628   for(; aRef != aRefsObj.end(); aRef++) {
629     std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
630     for(; aRefObj != aRef->second.end(); aRefObj++) {
631       // if reference is null, it may mean that this reference is to other document
632       // the does not supported by RefList: parameters may be recomputed
633       if (!aRefObj->get() && theFeature->firstResult().get() && 
634                theFeature->firstResult()->groupName() == ModelAPI_ResultParameter::group()) {
635           if (aState == ModelAPI_StateDone)
636             aState = ModelAPI_StateMustBeUpdated;
637       } else if (aRefObj->get() && isOlder(theFeature, *aRefObj)) {
638         if (aState == ModelAPI_StateDone)
639           aState = ModelAPI_StateMustBeUpdated;
640       }
641       aState = stateByReference(*aRefObj, aState);
642     }
643   }
644   // composites sub-elements
645   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
646   // composite feature must be executed after sub-features execution
647   if (aCompos) {
648     // number of subs can be changed in execution: like fillet
649     int aNumSubs = aCompos->numberOfSubs();
650     for(int a = 0; a < aNumSubs; a++) {
651       FeaturePtr aSub = aCompos->subFeature(a);
652       if (aSub.get() && aState == ModelAPI_StateDone) {
653         if (isOlder(theFeature, aSub)) {
654           aState = ModelAPI_StateMustBeUpdated;
655         }
656         // also check that all results of subs were updated: composite also depends on the results
657         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
658         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aResults.begin();
659         for(; aResIter != aResults.end(); aResIter++) {
660           if (aResIter->get() && (*aResIter)->data()->isValid() && !(*aResIter)->isDisabled() &&
661               isOlder(theFeature, *aResIter)) {
662             aState = ModelAPI_StateMustBeUpdated;
663           }
664         }
665       }
666       if (a == aNumSubs - 1) // in case number of subs is changed, just recheck before end
667         aNumSubs = aCompos->numberOfSubs();
668     }
669   }
670
671
672   if (aState != ModelAPI_StateDone)
673     theFeature->data()->execState(aState);
674 }
675
676 void Model_Update::executeFeature(FeaturePtr theFeature)
677 {
678   // execute in try-catch to avoid internal problems of the feature
679   ModelAPI_ExecState aState = ModelAPI_StateDone;
680   theFeature->data()->execState(ModelAPI_StateDone);
681   try {
682     theFeature->execute();
683     if (theFeature->data()->execState() != ModelAPI_StateDone) {
684       aState = ModelAPI_StateExecFailed;
685     } else {
686       aState = ModelAPI_StateDone;
687     }
688   } catch(...) {
689     aState = ModelAPI_StateExecFailed;
690     Events_Error::send(
691       "Feature " + theFeature->getKind() + " has failed during the execution");
692   }
693   // The macro feature has to be deleted in any case even its execution is failed 
694   myWaitForFinish.insert(theFeature);
695   if (aState != ModelAPI_StateDone) {
696     theFeature->eraseResults();
697   }
698   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
699   redisplayWithResults(theFeature, aState);
700 }
701
702 void Model_Update::updateStability(void* theSender)
703 {
704   if (theSender) {
705     bool added = false; // object may be was crated
706     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
707     if (aSender && aSender->document()) {
708       FeaturePtr aFeatureSender = 
709         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
710       if (aFeatureSender.get()) {
711         Model_Objects* aDocObjects = 
712           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
713         if (aDocObjects) {
714           //aDocObjects->synchronizeBackRefs();
715           // remove or add all concealment refs from this feature
716           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
717           aSender->data()->referencesToObjects(aRefs);
718           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
719           for(; aRefIt != aRefs.end(); aRefIt++) {
720             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
721             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
722             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
723                // stability is only on results: feature to feature reference mean nested 
724               // features, that will remove nesting references
725               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
726                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
727                 std::shared_ptr<Model_Data> aData = 
728                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
729                 if (aFeatureSender->isStable()) {
730                   aData->addBackReference(aFeatureSender, aRefIt->first);
731                 } else {
732                   aData->removeBackReference(aFeatureSender, aRefIt->first);
733                   added = true; // remove of concealment may be caused creation of some result
734                 }
735               }
736             }
737           }
738         }
739       }
740     }
741     if (added) {
742       static Events_Loop* aLoop = Events_Loop::loop();
743       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
744       aLoop->flush(kEventCreated);
745     }
746   }
747 }
748
749 ///////////////// Updated items iterator ////////////////////////
750 Model_Update::IterationItem::IterationItem(std::shared_ptr<ModelAPI_CompositeFeature> theFeature)
751 {
752   myBreaked = false;
753   myIsVirtual = false;
754   myMain = theFeature;
755   myObjects = NULL;
756   if (!myMain.get() && ModelAPI_Session::get()->hasModuleDocument()) { // no document => nothing to do
757     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
758     myObjects = std::dynamic_pointer_cast<Model_Document>(aRootDoc)->objects();
759   }
760   mySkipNext = false;
761 }
762
763 void Model_Update::IterationItem::next()
764 {
765   if (mySkipNext) { // ignore one next
766     mySkipNext = false;
767     return;
768   }
769   if (!myBreaked) {
770     if (myMain.get()) {
771       myIndex++;
772       int aNumSubs = myMain->numberOfSubs();
773       if (myIndex == aNumSubs)
774         return;
775       // skip sub-objects, that are subs not only for this: sketch elements relatively to Part
776       for(FeaturePtr aSub = myMain->subFeature(myIndex); aSub.get();
777           aSub = myMain->subFeature(myIndex)) {
778         aSub = myMain->subFeature(myIndex);
779         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(aSub);
780         if (!anOwner.get() || anOwner == myMain) {
781           break;
782         }
783         myIndex++;
784         if (myIndex == aNumSubs)
785           break;
786       }
787     } else if (mySub.get()) {
788       while(mySub.get()) {
789         mySub = myObjects->nextFeature(mySub);
790         CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(mySub);
791         // skip sub-objects, that are subs not only for this: sketch elements relatively to PartSet
792         if (!anOwner.get()) {
793           break;
794         }
795       }
796     }
797   }
798 }
799
800 bool Model_Update::IterationItem::more()
801 {
802   if (myBreaked)
803     return false;
804   if (myMain.get())
805     return myIndex < myMain->numberOfSubs();
806   return mySub.get() != NULL;
807 }
808
809 FeaturePtr Model_Update::IterationItem::current()
810 {
811   if (myMain.get())
812     return myMain->subFeature(myIndex);
813   return mySub;
814 }
815
816 void Model_Update::IterationItem::setBreaked()
817 {
818   if (!myIsVirtual)
819     myBreaked = true;
820 }
821
822 void Model_Update::IterationItem::startIteration(const bool theVirtual)
823 {
824   myIsVirtual = theVirtual;
825   if (myMain.get()) {
826     myIndex = 0;
827   } else if (myObjects) {
828     mySub = myObjects->firstFeature();
829   }
830 }
831
832 bool Model_Update::IterationItem::isIterated(FeaturePtr theFeature)
833 {
834   if (myMain.get()) {
835     if (myMain->isSub(theFeature)) {
836       CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
837       if (!anOwner.get() || anOwner == myMain)
838         return true;
839     }
840     return false;
841   }
842   // for the root document just check that this feature in this document and it is not sub
843   return myObjects->owner() == theFeature->document() && 
844          !ModelAPI_Tools::compositeOwner(theFeature).get();
845 }
846
847 bool Model_Update::IterationItem::isEarlierThanCurrent(FeaturePtr theFeature)
848 {
849   if (myMain.get()) {
850     for(int a = 0; a < myIndex; a++) {
851       if (myMain->subFeature(a) == theFeature)
852         return true;
853     }
854   } else {
855     return !mySub.get() && !myObjects->isLater(theFeature, mySub);
856   }
857   return false;
858 }
859
860 void Model_Update::IterationItem::setCurrentBefore(FeaturePtr theFeature)
861 {
862   if (myMain.get()) {
863     for(int a = 0; a < myIndex; a++) {
864       if (myMain->subFeature(a) == theFeature) {
865         myIndex = a;
866         break;
867       }
868     }
869   } else {
870     mySub = theFeature;
871   }
872   mySkipNext = true;
873 }