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