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