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