Salome HOME
Fix for the issue #1501
[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     // to update the object browser if something is updated/created during executions
315     static Events_Loop* aLoop = Events_Loop::loop();
316     static const Events_ID kCreatedEvent= aLoop->eventByName(EVENT_OBJECT_CREATED);
317     aLoop->flush(kCreatedEvent);
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   bool isReferencedInvalid = false;
404   // check all features this feature depended on (recursive call of updateFeature)
405   std::set<std::shared_ptr<ModelAPI_Feature> >& aReasons = myModified[theFeature];
406   if (aReasons.find(theFeature) == aReasons.end()) {
407     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aReasonIter = aReasons.begin();
408     for(; aReasonIter != aReasons.end(); aReasonIter++) {
409       if (*aReasonIter != theFeature && (*aReasonIter)->data()->isValid()) {
410         if (processFeature(*aReasonIter))
411           aIsModified = true;
412         if ((*aReasonIter)->data()->execState() == ModelAPI_StateInvalidArgument)
413           isReferencedInvalid = true;
414       }
415     }
416   } else { // check all features this feature depended on because here which one was modified is unknown
417     std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aDeps;
418     theFeature->data()->referencesToObjects(aDeps);
419     std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
420       anAttrsIter = aDeps.begin();
421     for(; anAttrsIter != aDeps.end(); anAttrsIter++) {
422       if (theFeature->attribute(anAttrsIter->first)->isArgument()) {
423         std::list<std::shared_ptr<ModelAPI_Object> >::iterator aDepIter = anAttrsIter->second.begin();
424         for(; aDepIter != anAttrsIter->second.end(); aDepIter++) {
425           FeaturePtr aDepFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(*aDepIter);
426           if (!aDepFeat.get()) { // so, it depends on the result and process the feature owner of it
427             ResultPtr aDepRes = std::dynamic_pointer_cast<ModelAPI_Result>(*aDepIter);
428             if (aDepRes.get()) {
429               aDepFeat = (*aDepIter)->document()->feature(aDepRes);
430             }
431           }
432           if (aDepFeat.get() && aDepFeat->data()->isValid()) {
433             if (processFeature(aDepFeat))
434               aIsModified = true;
435             if (aDepFeat->data()->execState() == ModelAPI_StateInvalidArgument)
436               isReferencedInvalid = true;
437           }
438         }
439       }
440     }
441     if (theFeature->getKind() == "Part") { // part is not depended on its subs directly, but subs must be iterated anyway
442       CompositeFeaturePtr aPart = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
443       int aNum = aPart->numberOfSubs();
444       for(int a = 0; a < aNum; a++) {
445         FeaturePtr aSub = aPart->subFeature(a);
446         if (aSub.get() && aSub->data()->isValid()) {
447           if (processFeature(aSub))
448             aIsModified = true;
449           if (aSub->data()->execState() == ModelAPI_StateInvalidArgument)
450             isReferencedInvalid = true;
451         }
452       }
453     }
454   }
455
456   // do not execute the composite that contains the current
457   bool isPostponedMain = false;
458   CompositeFeaturePtr aCompos = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
459   if (theFeature->getKind() == "ExtrusionSketch" && aCompos.get()) {
460     CompositeFeaturePtr aCurrentOwner = 
461       ModelAPI_Tools::compositeOwner(theFeature->document()->currentFeature(false));
462     isPostponedMain = aCurrentOwner.get() && aCompos->isSub(aCurrentOwner);
463   }
464
465   #ifdef DEB_UPDATE
466     std::cout<<"Update args "<<theFeature->name()<<std::endl;
467   #endif
468   // Update selection and parameters attributes first, before sub-features analysis (sketch plane).
469   updateArguments(theFeature);
470
471   // add this feature to the processed right now to be able remove it from this list on
472   // update signal during this feature execution
473   myModified.erase(theFeature);
474   if (theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
475     theFeature->data()->execState(ModelAPI_StateDone);
476
477   // this checking must be after the composite feature sub-elements processing:
478   // composite feature status may depend on it's subelements
479   if ((theFeature->data()->execState() == ModelAPI_StateInvalidArgument || isReferencedInvalid) && 
480     theFeature->getKind() != "Part") { // don't disable Part because it will make disabled all the features (performance and problems with the current feature)
481   #ifdef DEB_UPDATE
482     std::cout<<"Invalid args "<<theFeature->name()<<std::endl;
483   #endif
484     theFeature->eraseResults();
485     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
486     return true; // so, feature is modified (results are erased)
487   }
488
489   // execute feature if it must be updated
490   ModelAPI_ExecState aState = theFeature->data()->execState();
491   if (aFactory->validate(theFeature)) {
492     if (!isPostponedMain) {
493       executeFeature(theFeature);
494     }
495   } else {
496     #ifdef DEB_UPDATE
497       std::cout<<"Feature is not valid, erase results "<<theFeature->name()<<std::endl;
498     #endif
499     theFeature->eraseResults();
500     redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
501   }
502   return true;
503 }
504
505 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
506 {
507   // make updated and redisplay all results
508   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
509
510   std::list<ResultPtr> allResults;
511   ModelAPI_Tools::allResults(theFeature, allResults);
512   std::list<ResultPtr>::iterator aRIter = allResults.begin();
513   for (; aRIter != allResults.cend(); aRIter++) {
514     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
515     if (!aRes->isDisabled()) {// update state only for enabled results (Placement Result Part may make the original Part Result as invalid)
516       aRes->data()->execState(theState);
517     }
518     if (theFeature->data()->updateID() > aRes->data()->updateID()) {
519       aRes->data()->setUpdateID(theFeature->data()->updateID());
520     }
521     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
522   }
523   // to redisplay "presentable" feature (for ex. distance constraint)
524   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
525   theFeature->data()->execState(theState);
526 }
527
528 /// Updates the state by the referenced object: if something bad with it, set state for this one
529 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
530 {
531   if (theTarget) {
532     ModelAPI_ExecState aRefState = theTarget->data()->execState();
533     if (aRefState == ModelAPI_StateMustBeUpdated) {
534       if (theCurrent == ModelAPI_StateDone)
535         return ModelAPI_StateMustBeUpdated;
536     } else if (aRefState != ModelAPI_StateDone) {
537       return ModelAPI_StateInvalidArgument;
538     }
539   }
540   return theCurrent;
541 }
542
543 void Model_Update::updateArguments(FeaturePtr theFeature) {
544   // perform this method also for disabled features: to make "not done" state for
545   // features referenced to the active and modified features
546
547   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
548
549   ModelAPI_ExecState aState = theFeature->data()->execState();
550   if (aState == ModelAPI_StateExecFailed) { // try again failed feature: issue 577
551     aState = ModelAPI_StateMustBeUpdated;
552   }
553   if (aState == ModelAPI_StateInvalidArgument) // a chance to be corrected
554     aState = ModelAPI_StateMustBeUpdated;
555   // check the parameters state
556   // Integer
557   {
558     std::list<AttributePtr> anAttrinbutes =
559       theFeature->data()->attributes(ModelAPI_AttributeInteger::typeId());
560     std::list<AttributePtr>::iterator anIter = anAttrinbutes.begin();
561     for(; anIter != anAttrinbutes.end(); anIter++) {
562       AttributeIntegerPtr anAttribute =
563         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(*anIter);
564       if (anAttribute.get() && !anAttribute->text().empty()) {
565         if (myIsParamUpdated) {
566           ModelAPI_AttributeEvalMessage::send(anAttribute, this);
567         }
568         if (anAttribute->expressionInvalid()) {
569           aState = ModelAPI_StateInvalidArgument;
570         }
571       }
572     }
573   }
574   // Double
575   {
576     std::list<AttributePtr> aDoubles =
577       theFeature->data()->attributes(ModelAPI_AttributeDouble::typeId());
578     std::list<AttributePtr>::iterator aDoubleIter = aDoubles.begin();
579     for(; aDoubleIter != aDoubles.end(); aDoubleIter++) {
580       AttributeDoublePtr aDouble =
581         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(*aDoubleIter);
582       if (aDouble.get() && !aDouble->text().empty()) {
583         if (myIsParamUpdated) {
584           ModelAPI_AttributeEvalMessage::send(aDouble, this);
585         }
586         if (aDouble->expressionInvalid()) {
587           aState = ModelAPI_StateInvalidArgument;
588         }
589       }
590     }
591   }
592   // Point
593   {
594     std::list<AttributePtr> anAttributes =
595       theFeature->data()->attributes(GeomDataAPI_Point::typeId());
596     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
597     for(; anIter != anAttributes.end(); anIter++) {
598       AttributePointPtr aPointAttribute =
599         std::dynamic_pointer_cast<GeomDataAPI_Point>(*anIter);
600       if (aPointAttribute.get() && (!aPointAttribute->textX().empty() || 
601           !aPointAttribute->textY().empty() || !aPointAttribute->textZ().empty())) {
602         if (myIsParamUpdated) {
603           ModelAPI_AttributeEvalMessage::send(aPointAttribute, this);
604         }
605         if ((!aPointAttribute->textX().empty() && aPointAttribute->expressionInvalid(0)) ||
606           (!aPointAttribute->textY().empty() && aPointAttribute->expressionInvalid(1)) ||
607           (!aPointAttribute->textZ().empty() && aPointAttribute->expressionInvalid(2)))
608           aState = ModelAPI_StateInvalidArgument;
609       }
610     }
611   }
612   // Point2D
613   {
614     std::list<AttributePtr> anAttributes =
615       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
616     std::list<AttributePtr>::iterator anIter = anAttributes.begin();
617     for(; anIter != anAttributes.end(); anIter++) {
618       AttributePoint2DPtr aPoint2DAttribute =
619         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
620       if (aPoint2DAttribute.get()) {
621         if (myIsParamUpdated && (!aPoint2DAttribute->textX().empty() || 
622             !aPoint2DAttribute->textY().empty())) {
623           ModelAPI_AttributeEvalMessage::send(aPoint2DAttribute, this);
624         }
625         if ((!aPoint2DAttribute->textX().empty() && aPoint2DAttribute->expressionInvalid(0)) ||
626           (!aPoint2DAttribute->textY().empty() && aPoint2DAttribute->expressionInvalid(1)))
627           aState = ModelAPI_StateInvalidArgument;
628       }
629     }
630   }
631   // update the selection attributes if any
632   list<AttributePtr> aRefs = 
633     theFeature->data()->attributes(ModelAPI_AttributeSelection::typeId());
634   list<AttributePtr>::iterator aRefsIter = aRefs.begin();
635   for (; aRefsIter != aRefs.end(); aRefsIter++) {
636     std::shared_ptr<ModelAPI_AttributeSelection> aSel =
637       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
638     ObjectPtr aContext = aSel->context();
639     // update argument only if the referenced object is ready to use
640     if (aContext.get() && !aContext->isDisabled()) {
641       if (isReason(theFeature, aContext)) {
642         if (!aSel->update()) { // this must be done on execution since it may be long operation
643           bool isObligatory = !aFactory->isNotObligatory(
644             theFeature->getKind(), theFeature->data()->id(aSel)) &&
645             aFactory->isCase(theFeature, theFeature->data()->id(aSel));
646           if (isObligatory)
647             aState = ModelAPI_StateInvalidArgument;
648         }
649       }
650     } else if (aContext.get()) {
651       // here it may be not obligatory, but if the reference is wrong, it should not be correct
652       bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
653       if (isObligatory)
654         aState = ModelAPI_StateInvalidArgument;
655     }
656   }
657   // update the selection list attributes if any
658   aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
659   for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
660     std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
661       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
662     for(int a = aSel->size() - 1; a >= 0; a--) {
663       std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
664         std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
665       if (aSelAttr) {
666         ObjectPtr aContext = aSelAttr->context();
667         // update argument only if the referenced object is ready to use
668         if (aContext.get() && !aContext->isDisabled()) {
669           if (isReason(theFeature, aContext)) {
670             if (!aSelAttr->update()) {
671               bool isObligatory = !aFactory->isNotObligatory(
672                 theFeature->getKind(), theFeature->data()->id(aSel)) &&
673                 aFactory->isCase(theFeature, theFeature->data()->id(aSel));
674               if (isObligatory)
675                 aState = ModelAPI_StateInvalidArgument;
676             }
677           }
678         } else if (aContext.get()) {
679           // here it may be not obligatory, but if the reference is wrong, it should not be correct
680           bool isObligatory = aFactory->isCase(theFeature, theFeature->data()->id(aSel));
681           if (isObligatory)
682             aState = ModelAPI_StateInvalidArgument;
683         }
684       }
685     }
686   }
687
688   if (aState != ModelAPI_StateDone)
689     theFeature->data()->execState(aState);
690 }
691
692 bool Model_Update::isReason(std::shared_ptr<ModelAPI_Feature>& theFeature, 
693      std::shared_ptr<ModelAPI_Object> theReason) 
694 {
695   std::map<std::shared_ptr<ModelAPI_Feature>, std::set<std::shared_ptr<ModelAPI_Feature> > >
696     ::iterator aReasonsIt = myModified.find(theFeature);
697   if (aReasonsIt == myModified.end())
698     return false; // this case only for not-previewed items update state, nothing is changed in args for it
699   if (aReasonsIt->second.find(theFeature) != aReasonsIt->second.end())
700     return true; // any is reason if it contains itself
701   FeaturePtr aReasFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(theReason);
702   if (!aReasFeat.get()) { // try to get feature of this result
703     ResultPtr aReasRes = std::dynamic_pointer_cast<ModelAPI_Result>(theReason);
704     if (aReasRes.get())
705       aReasFeat = theReason->document()->feature(aReasRes);
706   }
707   return aReasonsIt->second.find(aReasFeat) != aReasonsIt->second.end();
708
709 }
710
711 void Model_Update::executeFeature(FeaturePtr theFeature)
712 {
713 #ifdef DEB_UPDATE
714   std::cout<<"Execute Feature "<<theFeature->name()<<std::endl;
715 #endif
716   // execute in try-catch to avoid internal problems of the feature
717   ModelAPI_ExecState aState = ModelAPI_StateDone;
718   theFeature->data()->execState(ModelAPI_StateDone);
719   try {
720     theFeature->execute();
721     if (theFeature->data()->execState() != ModelAPI_StateDone) {
722       aState = ModelAPI_StateExecFailed;
723     } else {
724       aState = ModelAPI_StateDone;
725     }
726   } catch(...) {
727     aState = ModelAPI_StateExecFailed;
728     Events_Error::send(
729       "Feature " + theFeature->getKind() + " has failed during the execution");
730   }
731   // The macro feature has to be deleted in any case even its execution is failed 
732   myWaitForFinish.insert(theFeature);
733   if (aState != ModelAPI_StateDone) {
734     theFeature->eraseResults();
735   }
736   theFeature->data()->setUpdateID(ModelAPI_Session::get()->transactionID());
737   redisplayWithResults(theFeature, aState);
738 }
739
740 void Model_Update::updateStability(void* theSender)
741 {
742   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
743   if (theSender) {
744     bool added = false; // object may be was crated
745     ModelAPI_Object* aSender = static_cast<ModelAPI_Object*>(theSender);
746     if (aSender && aSender->document()) {
747       FeaturePtr aFeatureSender = 
748         std::dynamic_pointer_cast<ModelAPI_Feature>(aSender->data()->owner());
749       if (aFeatureSender.get()) {
750         Model_Objects* aDocObjects = 
751           std::dynamic_pointer_cast<Model_Document>(aSender->document())->objects();
752         if (aDocObjects) {
753           //aDocObjects->synchronizeBackRefs();
754           // remove or add all concealment refs from this feature
755           std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
756           aSender->data()->referencesToObjects(aRefs);
757           std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefIt = aRefs.begin();
758           for(; aRefIt != aRefs.end(); aRefIt++) {
759             if (!aFactory->isConcealed(aFeatureSender->getKind(), aRefIt->first))
760               continue; // take into account only concealed references (do not remove the sketch constraint and the edge on constraint edit)
761             std::list<ObjectPtr>& aRefFeaturesList = aRefIt->second;
762             std::list<ObjectPtr>::iterator aReferenced = aRefFeaturesList.begin();
763             for(; aReferenced != aRefFeaturesList.end(); aReferenced++) {
764                // stability is only on results: feature to feature reference mean nested 
765               // features, that will remove nesting references
766               if (aReferenced->get() && (*aReferenced)->data()->isValid() && 
767                 (*aReferenced)->groupName() != ModelAPI_Feature::group()) {
768                 std::shared_ptr<Model_Data> aData = 
769                   std::dynamic_pointer_cast<Model_Data>((*aReferenced)->data());
770                 if (aFeatureSender->isStable()) {
771                   aData->addBackReference(aFeatureSender, aRefIt->first);
772                 } else {
773                   aData->removeBackReference(aFeatureSender, aRefIt->first);
774                   added = true; // remove of concealment may be caused creation of some result
775                 }
776               }
777             }
778           }
779         }
780       }
781     }
782     if (added) {
783       static Events_Loop* aLoop = Events_Loop::loop();
784       static Events_ID kEventCreated = aLoop->eventByName(EVENT_OBJECT_CREATED);
785       aLoop->flush(kEventCreated);
786     }
787   }
788 }