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