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