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