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