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