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