Salome HOME
Fix for the issue #1480 : make documentation targets near to SALOME common rules
[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 kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
44   aLoop->registerListener(this, kCreatedEvent);
45   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
46   aLoop->registerListener(this, kUpdatedEvent);
47   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
48   aLoop->registerListener(this, kOpFinishEvent);
49   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
50   aLoop->registerListener(this, kOpAbortEvent);
51   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
52   aLoop->registerListener(this, kOpStartEvent);
53   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
54   aLoop->registerListener(this, kStabilityEvent);
55   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
56   aLoop->registerListener(this, kPreviewBlockedEvent);
57   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
58   aLoop->registerListener(this, kPreviewRequestedEvent);
59
60   //  Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
61   myIsParamUpdated = false;
62   myIsFinish = false;
63   myIsProcessed = false;
64   myIsPreviewBlocked = false;
65 }
66
67 bool Model_Update::addModified(FeaturePtr theFeature, FeaturePtr theReason) {
68
69   if (!theFeature->data()->isValid())
70     return false; // delete an extrusion created on the sketch
71
72   if (theFeature->isPersistentResult()) {
73     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
74       return false;
75   }
76
77   // update arguments for "apply button" state change
78   if ((!theFeature->isPreviewNeeded() && !myIsFinish) || myIsPreviewBlocked) {
79     myProcessOnFinish.insert(theFeature);
80 #ifdef DEB_UPDATE
81       std::cout<<"*** Add process on finish "<<theFeature->name()<<std::endl;
82 #endif
83     // keeps the currently updated features to avoid infinitive cycling here: where feature on
84     // "updateArguments" sends "updated" (in selection attribute) and goes here again
85     static std::set<FeaturePtr> aCurrentlyUpdated;
86     if (aCurrentlyUpdated.find(theFeature) == aCurrentlyUpdated.end()) {
87       aCurrentlyUpdated.insert(theFeature);
88       updateArguments(theFeature);
89       aCurrentlyUpdated.erase(theFeature);
90     }
91     // make it without conditions otherwise the apply button may have a bad state
92     theFeature->data()->execState(ModelAPI_StateDone);
93     static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
94     aFactory->validate(theFeature); // need to be validated to update the "Apply" state if not previewed
95
96     if (!myIsPreviewBlocked)
97       return true;
98   }
99   if (myModified.find(theFeature) != myModified.end()) {
100     if (theReason.get()) {
101 #ifdef DEB_UPDATE
102       std::cout<<"*** Add already modified "<<theFeature->name()<<std::endl;
103 #endif
104       myModified[theFeature].insert(theReason);
105     }
106     return true;
107   }
108   // do not add the disabled, but possibly the sub-elements are not disabled
109   bool aIsDisabled = theFeature->isDisabled();
110   if (!aIsDisabled) {
111     std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
112     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
113       // do not forget that in this case all were the reasons
114       aNewSet.insert(theFeature);
115     } else {
116       if (theReason.get())
117         aNewSet.insert(theReason);
118     }
119     myModified[theFeature] = aNewSet;
120 #ifdef DEB_UPDATE
121     std::cout<<"*** Add modified "<<theFeature->name()<<std::endl;
122 #endif
123   } else { // will be updated during the finish of the operation, or when it becomes enabled
124     if (theFeature->data()->execState() == ModelAPI_StateDone)
125       theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
126     else 
127       return true; // do not need iteration deeply if it is already marked as modified or so
128 #ifdef DEB_UPDATE
129     std::cout<<"*** Set modified state "<<theFeature->name()<<std::endl;
130 #endif
131   }
132   // clear processed and fill modified recursively
133   const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
134   std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
135   for(; aRefIter != aRefs.cend(); aRefIter++) {
136     if ((*aRefIter)->isArgument()) {
137       FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
138       if (aReferenced.get()) {
139         addModified(aReferenced, theFeature);
140       }
141     }
142   }
143   // proccess also results
144   std::list<ResultPtr> allResults; // list of this feature and results
145   ModelAPI_Tools::allResults(theFeature, allResults);
146   std::list<ResultPtr>::iterator aRes = allResults.begin();
147   for(; aRes != allResults.end(); aRes++) {
148     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*aRes)->data()->refsToMe();
149     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
150     for(; aRefIter != aRefs.cend(); aRefIter++) {
151       if ((*aRefIter)->isArgument()) {
152         FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
153         if (aReferenced.get()) {
154           addModified(aReferenced, theFeature);
155         }
156       }
157     }
158   }
159
160   // also add part feature that contains this feature to the modified
161   if (theFeature->document()->kind() != "PartSet") {
162     FeaturePtr aPart = ModelAPI_Tools::findPartFeature(
163       ModelAPI_Session::get()->moduleDocument(), theFeature->document());
164     if (aPart.get())
165       addModified(aPart, theFeature);
166   }
167   return true;
168 }
169
170 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
171 {
172   static Events_Loop* aLoop = Events_Loop::loop();
173   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
174   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
175   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
176   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
177   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
178   static const Events_ID kStabilityEvent = aLoop->eventByName(EVENT_STABILITY_CHANGED);
179   static const Events_ID kPreviewBlockedEvent = aLoop->eventByName(EVENT_PREVIEW_BLOCKED);
180   static const Events_ID kPreviewRequestedEvent = aLoop->eventByName(EVENT_PREVIEW_REQUESTED);
181
182 #ifdef DEB_UPDATE
183   std::cout<<"****** Event "<<theMessage->eventID().eventText()<<std::endl;
184 #endif
185   if (theMessage->eventID() == kStabilityEvent) {
186     updateStability(theMessage->sender());
187     return;
188   }
189   if (theMessage->eventID() == kPreviewBlockedEvent) {
190     myIsPreviewBlocked = true;
191     return;
192   }
193   if (theMessage->eventID() == kPreviewRequestedEvent) {
194     if (myIsPreviewBlocked) {
195       myIsPreviewBlocked = false;
196       processFeatures();
197       myIsPreviewBlocked = true;
198     }
199     return;
200   }
201   // creation is added to "update" to avoid recomputation twice: on create and immediately after on update
202   if (theMessage->eventID() == kCreatedEvent) {
203     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
204         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
205     const std::set<ObjectPtr>& anObjs = aMsg->objects();
206     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
207     for(; anObjIter != anObjs.cend(); anObjIter++) {
208       if (std::dynamic_pointer_cast<Model_Document>((*anObjIter)->document())->executeFeatures())
209         ModelAPI_EventCreator::get()->sendUpdated(*anObjIter, kUpdatedEvent);
210     }
211     return;
212   }
213   if (theMessage->eventID() == kUpdatedEvent) {
214     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
215         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
216     const std::set<ObjectPtr>& anObjs = aMsg->objects();
217     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
218     bool aSomeModified = false; // check that features not changed: only redisplay is needed
219     for(; anObjIter != anObjs.cend(); anObjIter++) {
220       if (!(*anObjIter)->data()->isValid())
221         continue;
222 #ifdef DEB_UPDATE
223       std::cout<<">>> in event updated "<<(*anObjIter)->data()->name()<<std::endl;
224 #endif
225       if ((*anObjIter)->groupName() == ModelAPI_ResultParameter::group()) {
226         myIsParamUpdated = true;
227       }
228       // on undo/redo, abort do not update persisten features
229       FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
230       if (anUpdated.get()) {
231         if (addModified(anUpdated, FeaturePtr()))
232           aSomeModified = true;
233       } else { // process the updated result as update of features that refers to this result
234         const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = (*anObjIter)->data()->refsToMe();
235         std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.cbegin();
236         for(; aRefIter != aRefs.cend(); aRefIter++) {
237           if (!(*aRefIter)->owner()->data()->isValid())
238             continue;
239           FeaturePtr anUpdated = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIter)->owner());
240           if (anUpdated.get()) {
241             if (addModified(anUpdated, FeaturePtr()))
242               aSomeModified = true;
243           }
244         }
245       }
246     }
247     // this event is for solver update, not here, do not react immediately
248     if (aSomeModified) {
249         processFeatures();
250     }
251   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent ||
252       theMessage->eventID() == kOpStartEvent) {
253     myIsPreviewBlocked = false;
254
255     if (theMessage->eventID() == kOpFinishEvent) {
256       myIsFinish = true;
257       // add features that wait for finish as modified
258       std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aFeature = myProcessOnFinish.begin();
259       for(; aFeature != myProcessOnFinish.end(); aFeature++)
260         if ((*aFeature)->data()->isValid()) // there may be already removed wait for features
261           addModified(*aFeature, FeaturePtr());
262       myIsFinish = false;
263     }
264     myProcessOnFinish.clear(); // processed features must be only on finish, so clear anyway (to avoid reimport on load)
265
266     if (!(theMessage->eventID() == kOpStartEvent)) {
267       processFeatures(false);
268     }
269     // remove all macros before clearing all created
270     std::set<FeaturePtr>::iterator anUpdatedIter = myWaitForFinish.begin();
271     while(anUpdatedIter != myWaitForFinish.end()) {
272       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anUpdatedIter);
273       if (aFeature.get()) {
274         // remove macro on finish
275         if (aFeature->isMacro()) {
276           aFeature->document()->removeFeature(aFeature);
277           myWaitForFinish.erase(aFeature);
278         }
279         // to avoid the map update problems on "remove"
280         if (myWaitForFinish.find(aFeature) == myWaitForFinish.end()) {
281           anUpdatedIter = myWaitForFinish.begin();
282         } else {
283           anUpdatedIter++;
284         }
285       } else {
286         anUpdatedIter++;
287       }
288     }
289     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
290     // if should be done after removeFeature() of document,
291     // by this reason, upper processFeatures() do not perform this flush
292     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
293
294     // in the end of transaction everything is updated, so clear the old objects
295     myIsParamUpdated = false;
296     myWaitForFinish.clear();
297   }
298 }
299
300 void Model_Update::processFeatures(const bool theFlushRedisplay)
301 {
302    // perform update of everything if it is not performed right now or any preview is blocked
303   if (!myIsProcessed && !myIsPreviewBlocked) {
304     myIsProcessed = true;
305     #ifdef DEB_UPDATE
306       std::cout<<"****** Start processing"<<std::endl;
307     #endif
308
309     while(!myModified.empty()) {
310       processFeature(myModified.begin()->first);
311     }
312     myIsProcessed = false;
313
314     // flush updates just before "myModification" increment: to distinguish
315     // updates by "execute" produced by this updater and other updates, coming outside,
316     // which are really important for "processEvent" of this updater
317     static Events_Loop* aLoop = Events_Loop::loop();
318     static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
319     aLoop->flush(kUpdatedEvent);
320
321     // flush to update display
322     if (theFlushRedisplay) {
323       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
324       aLoop->flush(EVENT_DISP);
325     }
326     #ifdef DEB_UPDATE
327       std::cout<<"****** End processing"<<std::endl;
328     #endif
329     myProcessed.clear();
330   }
331 }
332
333 bool Model_Update::processFeature(FeaturePtr theFeature)
334 {
335   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
336
337   if (!theFeature->data()->isValid()) { // deleted feature, just remove from all containers
338     if (myModified.find(theFeature) != myModified.end())
339       myModified.erase(theFeature);
340     return false;
341   }
342
343   if (theFeature->isPersistentResult()) {
344     if (!std::dynamic_pointer_cast<Model_Document>((theFeature)->document())->executeFeatures())
345       return false;
346   }
347
348   if (myProcessed.find(theFeature) == myProcessed.end()) {
349     myProcessed[theFeature] = 0;
350   } else {
351     int aCount = myProcessed[theFeature];
352     if (aCount > 100) { // too many repetition of processing (in VS it may crash on 330 with stack overflow)
353       Events_Error::send(
354         "Feature '" + theFeature->data()->name() + "' is updated in infinitive loop");
355       return false;
356     }
357     myProcessed[theFeature] = aCount + 1;
358   }
359
360   // check this feature is not yet checked or processed
361   bool aIsModified = myModified.find(theFeature) != myModified.end();
362   if (!aIsModified && myIsFinish) { // get info about the modification for features without preview
363     if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated) {
364       aIsModified = true;
365       std::set<std::shared_ptr<ModelAPI_Feature> > aNewSet;
366       aNewSet.insert(theFeature); // contains itself, so, we don't know which was the reason and the reason is any
367       myModified[theFeature] = aNewSet;
368     }
369   }
370
371 #ifdef DEB_UPDATE
372     std::cout<<"* Process feature "<<theFeature->name()<<std::endl;
373 #endif
374
375   // update the sketch plane before the sketch sub-elements are recomputed
376   // (otherwise sketch will update plane, modify subs, after executed, but with old subs edges)
377   if (aIsModified && theFeature->getKind() == "Sketch") {
378 #ifdef DEB_UPDATE
379     std::cout<<"****** Update sketch args "<<theFeature->name()<<std::endl;
380 #endif
381     AttributeSelectionPtr anExtSel = theFeature->selection("External");
382     if (anExtSel.get()) {
383       ResultPtr aContext = anExtSel->context();
384       if (aContext.get() && aContext->document().get()) {
385         FeaturePtr anExtBase = aContext->document()->feature(aContext);
386         if (anExtBase.get()) {
387           processFeature(anExtBase);
388         }
389       }
390     }
391     updateArguments(theFeature);
392   }
393
394   if (!aIsModified) { // no modification is needed
395     return false;
396   }
397
398   // evaluate parameter before the sub-elements update: it updates dependencies on evaluation (#1085)
399   if (theFeature->getKind() == "Parameter") {
400     theFeature->execute();
401   }
402
403   // check all features this feature depended on (recursive call of updateFeature)
404   std::set<std::shared_ptr<ModelAPI_Feature> >& aReasons = myModified[theFeature];
405   if (aReasons.find(theFeature) == aReasons.end()) {
406     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aReasonIter = aReasons.begin();
407     for(; aReasonIter != aReasons.end(); aReasonIter++) {
408       if (*aReasonIter != theFeature && processFeature(*aReasonIter)) {
409         aIsModified = true;
410       }
411     }
412   } else { // check all features this feature depended on because here which one was modified is unknown
413     std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
414     theFeature->data()->referencesToObjects(aDeps);
415     std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
416       anAttrsIter = aDeps.begin();
417     for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
418       if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
419         std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
420         for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
421           FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
422           if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
423             ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
424             if (aDepRes.get()) {
425               aDepFeat = (*aDepIter)->document()->feature(aDepRes);
426             }
427           }
428           if (aDepFeat.get()) {
429             if (processFeature(aDepFeat))
430               aIsModified = true;
431           }
432         }
433       }
434     }
435     if (theFeature->getKind() == "Part") { // part is not depended on its subs directly, but subs must be iterated anyway
436       CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
437       int aNum = aPart->numberOfSubs();
438       for(int a = 0; a < aNum; a++) {
439         FeaturePtr aSub = aPart->subFeature(a);
440         if (aSub.get()) {
441           if (processFeature(aSub))
442             aIsModified = true;
443         }
444       }
445     }
446   }
447
448   // do not execute the composite that contains the current
449   bool isPostponedMain = false;
450   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
451   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
452     CompositeFeaturePtr aCurrentOwner = 
453       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
454     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
455   }
456
457   #ifdef DEB_UPDATE
458     std::cout<<"Update args "<<theFeature->name()<<std::endl;
459   #endif
460   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
461   updateArguments(theFeature);
462
463   // add this feature to the processed right now to be able remove it from this list on
464   // update signal during this feature execution
465   myModified.erase(theFeature);
466   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
467     theFeature->data()->execState(ModelAPI_StateDone);
468
469   // this checking must be after the composite feature sub-elements processing:
470   // composite feature status may depend on it's subelements
471   if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
472   #ifdef DEB_UPDATE
473     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
474   #endif
475     theFeature->eraseResults();
476     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
477     return true; // so, feature is modified (results are erased)
478   }
479
480   // execute feature if it must be updated
481   ModelAPI_ExecState aState = theFeature->data()->execState();
482   if (aFactory->validate(theFeature)) {
483     if (!isPostponedMain) {
484       executeFeature(theFeature);
485     }
486   } else {
487     #ifdef DEB_UPDATE
488       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
489     #endif
490     theFeature->eraseResults();
491     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
492   }
493   return true;
494 }
495
496 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
497 {
498   // make updated and redisplay all results
499   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
500
501   std::list<ResultPtr> allResults;
502   ModelAPI_Tools::allResults(theFeature, allResults);
503   std::list<ResultPtr>::iterator aRIter = allResults.begin();
504   for (; aRIter != allResults.cend(); aRIter++) {
505     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
506     if (!aRes->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
507       aRes->data()->execState(theState);
508     }
509     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
510       aRes->data()->setUpdateID(theFeature->data()->updateID());
511     }
512     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
513   }
514   // to redisplay "presentable" feature (for ex. distance constraint)
515   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
516   theFeature->data()->execState(theState);
517 }
518
519 /// Updates the state by the referenced object: if something bad with it, set state for this one
520 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
521 {
522   if (theTarget) {
523     ModelAPI_ExecState aRefState = theTarget->data()->execState();
524     if (aRefState == ModelAPI_StateMustBeUpdated) {
525       if (theCurrent == ModelAPI_StateDone)
526         return ModelAPI_StateMustBeUpdated;
527     } else if (aRefState != ModelAPI_StateDone) {
528       return ModelAPI_StateInvalidArgument;
529     }
530   }
531   return theCurrent;
532 }
533
534 void Model_Update::updateArguments(FeaturePtr theFeature) {
535   // perform this method also for disabled features: to make "not done" state for
536   // features referenced to the active and modified features
537
538   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
539
540   ModelAPI_ExecState aState = theFeature->data()->execState();
541   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
542     aState = ModelAPI_StateMustBeUpdated;
543   }
544   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
545     aState = ModelAPI_StateMustBeUpdated;
546   // check the parameters state
547   // Integer
548   {
549     std::list<AttributePtr> anAttrinbutes =
550       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
551     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
552     for(; anIter != anAttrinbutes.end(); anIter++) {
553       AttributeIntegerPtr anAttribute =
554         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
555       if (anAttribute.get() && !anAttribute->text().empty()) {
556         if (myIsParamUpdated) {
557           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
558         }
559         if (anAttribute->expressionInvalid()) {
560           aState = ModelAPI_StateInvalidArgument;
561         }
562       }
563     }
564   }
565   // Double
566   {
567     std::list<AttributePtr> aDoubles =
568       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
569     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
570     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
571       AttributeDoublePtr aDouble =
572         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
573       if (aDouble.get() && !aDouble->text().empty()) {
574         if (myIsParamUpdated) {
575           ModelAPI_AttributeEvalMessage::send(aDouble, this);
576         }
577         if (aDouble->expressionInvalid()) {
578           aState = ModelAPI_StateInvalidArgument;
579         }
580       }
581     }
582   }
583   // Point
584   {
585     std::list<AttributePtr> anAttributes =
586       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
587     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
588     for(; anIter != anAttributes.end(); anIter++) {
589       AttributePointPtr aPointAttribute =
590         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
591       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() || 
592           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
593         if (myIsParamUpdated) {
594           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
595         }
596         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
597           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
598           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
599           aState = ModelAPI_StateInvalidArgument;
600       }
601     }
602   }
603   // Point2D
604   {
605     std::list<AttributePtr> anAttributes =
606       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
607     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
608     for(; anIter != anAttributes.end(); anIter++) {
609       AttributePoint2DPtr aPoint2DAttribute =
610         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
611       if (aPoint2DAttribute.get()) {
612         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() || 
613             !aPoint2DAttribute->textY().empty())) {
614           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
615         }
616         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
617           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
618           aState = ModelAPI_StateInvalidArgument;
619       }
620     }
621   }
622   // update the selection attributes if any
623   list<AttributePtr> aRefs = 
624     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
625   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
626   for (; aRefsIter != aRefs.end(); aRefsIter++) {
627     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
628       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
629     ObjectPtr aContext = aSel->context();
630     // update argument only if the referenced object is ready to use
631     if (aContext.get() && !aContext->isDisabled()) {
632       if (isReason(theFeature, aContext)) {
633         if (!aSel->update()) { // this must be done on execution since it may be long operation
634           bool isObligatory = !aFactory->isNotObligatory(
635             theFeature->getKind(), theFeature->data()->id(aSel)) &&
636             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
637           if (isObligatory)
638             aState = ModelAPI_StateInvalidArgument;
639         }
640       }
641     } else if (aContext.get()) {
642       // here it may be not obligatory, but if the reference is wrong, it should not be correct
643       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
644       if (isObligatory)
645         aState = ModelAPI_StateInvalidArgument;
646     }
647   }
648   // update the selection list attributes if any
649   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
650   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
651     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
652       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
653     for(int a = aSel->size() - 1; a >= 0; a--) {
654       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
655         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
656       if (aSelAttr) {
657         ObjectPtr aContext = aSelAttr->context();
658         // update argument only if the referenced object is ready to use
659         if (aContext.get() && !aContext->isDisabled()) {
660           if (isReason(theFeature, aContext)) {
661             if (!aSelAttr->update()) {
662               bool isObligatory = !aFactory->isNotObligatory(
663                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
664                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
665               if (isObligatory)
666                 aState = ModelAPI_StateInvalidArgument;
667             }
668           }
669         } else if (aContext.get()) {
670           // here it may be not obligatory, but if the reference is wrong, it should not be correct
671           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
672           if (isObligatory)
673             aState = ModelAPI_StateInvalidArgument;
674         }
675       }
676     }
677   }
678
679   if (aState != ModelAPI_StateDone)
680     theFeature->data()->execState(aState);
681 }
682
683 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature, 
684      std::shared_ptr<ModelAPI_Object> theReason) 
685 {
686   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
687     ::iterator aReasonsIt = myModified.find(theFeature);
688   if (aReasonsIt == myModified.end())
689     return false; // this case only for not-previewed items update state, nothing is changed in args for it
690   if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
691     return true; // any is reason if it contains itself
692   FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
693   if (!aReasFeat.get()) { // try to get feature of this result
694     ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
695     if (aReasRes.get())
696       aReasFeat = theReason->document()->feature(aReasRes);
697   }
698   return aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end();
699
700 }
701
702 void Model_Update::executeFeature(FeaturePtr theFeature)
703 {
704 #ifdef DEB_UPDATE
705   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
706 #endif
707   // execute in try-catch to avoid internal problems of the feature
708   ModelAPI_ExecState aState = ModelAPI_StateDone;
709   theFeature->data()->execState(ModelAPI_StateDone);
710   try {
711     theFeature->execute();
712     if (theFeature->data()->execState() != ModelAPI_StateDone) {
713       aState = ModelAPI_StateExecFailed;
714     } else {
715       aState = ModelAPI_StateDone;
716     }
717   } catch(...) {
718     aState = ModelAPI_StateExecFailed;
719     Events_Error::send(
720       "Feature " + theFeature->getKind() + " has failed during the execution");
721   }
722   // The macro feature has to be deleted in any case even its execution is failed 
723   myWaitForFinish.insert(theFeature);
724   if (aState != ModelAPI_StateDone) {
725     theFeature->eraseResults();
726   }
727   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
728   redisplayWithResults(theFeature, aState);
729 }
730
731 void Model_Update::updateStability(void* theSender)
732 {
733   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
734   if (theSender) {
735     bool added = false; // object may be was crated
736     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
737     if (aSender && aSender->document()) {
738       FeaturePtr aFeatureSender = 
739         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
740       if (aFeatureSender.get()) {
741         Model_Objects* aDocObjects = 
742           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
743         if (aDocObjects) {
744           //aDocObjects->synchronizeBackRefs();
745           // remove or add all concealment refs from this feature
746           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
747           aSender->data()->referencesToObjects(aRefs);
748           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
749           for(; aRefIt != aRefs.end(); aRefIt++) {
750             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
751               continue; // take into account only concealed references (do not remove the sketch constraint and the edge on constraint edit)
752             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
753             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
754             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
755                // stability is only on results: feature to feature reference mean nested 
756               // features, that will remove nesting references
757               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
758                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
759                 std::shared_ptr<Model_Data> aData = 
760                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
761                 if (aFeatureSender->isStable()) {
762                   aData->addBackReference(aFeatureSender, aRefIt->first);
763                 } else {
764                   aData->removeBackReference(aFeatureSender, aRefIt->first);
765                   added = true; // remove of concealment may be caused creation of some result
766                 }
767               }
768             }
769           }
770         }
771       }
772     }
773     if (added) {
774       static Events_Loop* aLoop = Events_Loop::loop();
775       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
776       aLoop->flush(kEventCreated);
777     }
778   }
779 }