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