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