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