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