]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Update.cpp
Salome HOME
Issue #302: correctly abort sketch transaction
[modules/shaper.git] / src / Model / Model_Update.cpp
1 // File:        Model_Update.cxx
2 // Created:     25 Jun 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Update.h>
6 #include <Model_Document.h>
7 #include <Model_Data.h>
8 #include <ModelAPI_Feature.h>
9 #include <ModelAPI_Data.h>
10 #include <ModelAPI_Document.h>
11 #include <ModelAPI_Events.h>
12 #include <ModelAPI_AttributeReference.h>
13 #include <ModelAPI_AttributeRefList.h>
14 #include <ModelAPI_AttributeRefAttr.h>
15 #include <ModelAPI_AttributeSelection.h>
16 #include <ModelAPI_AttributeSelectionList.h>
17 #include <ModelAPI_Result.h>
18 #include <ModelAPI_Validator.h>
19 #include <ModelAPI_CompositeFeature.h>
20 #include <ModelAPI_Session.h>
21 #include <Events_Loop.h>
22 #include <Events_LongOp.h>
23 #include <Events_Error.h>
24 #include <Config_PropManager.h>
25
26 using namespace std;
27
28 Model_Update MY_UPDATER_INSTANCE;  /// the only one instance initialized on load of the library
29
30 Model_Update::Model_Update()
31 {
32   Events_Loop* aLoop = Events_Loop::loop();
33   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
34   aLoop->registerListener(this, kChangedEvent);
35   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
36   aLoop->registerListener(this, kRebuildEvent);
37   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
38   aLoop->registerListener(this, kCreatedEvent);
39   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
40   aLoop->registerListener(this, kUpdatedEvent);
41   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
42   aLoop->registerListener(this, kMovedEvent);
43   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
44   aLoop->registerListener(this, kOpFinishEvent);
45   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
46   aLoop->registerListener(this, kOpAbortEvent);
47   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
48   aLoop->registerListener(this, kOpStartEvent);
49
50   Config_PropManager::registerProp("Model update", "automatic_rebuild", "Rebuild immediately",
51                                    Config_Prop::Bool, "false");
52   isAutomatic = Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
53 }
54
55 void Model_Update::processEvent(const std::shared_ptr<Events_Message>& theMessage)
56 {
57   static Events_Loop* aLoop = Events_Loop::loop();
58   static const Events_ID kChangedEvent = aLoop->eventByName("PreferenceChanged");
59   static const Events_ID kRebuildEvent = aLoop->eventByName("Rebuild");
60   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
61   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
62   static const Events_ID kMovedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
63   static const Events_ID kOpFinishEvent = aLoop->eventByName("FinishOperation");
64   static const Events_ID kOpAbortEvent = aLoop->eventByName("AbortOperation");
65   static const Events_ID kOpStartEvent = aLoop->eventByName("StartOperation");
66   bool isAutomaticChanged = false;
67   if (theMessage->eventID() == kChangedEvent) { // automatic and manual rebuild flag is changed
68     isAutomatic = 
69       Config_PropManager::findProp("Model update", "automatic_rebuild")->value() == "true";
70   } else if (theMessage->eventID() == kRebuildEvent) { // the rebuild command
71     if (isAutomatic == false) {
72       isAutomaticChanged = true;
73       isAutomatic = true;
74     }
75   } else if (theMessage->eventID() == kCreatedEvent || theMessage->eventID() == kUpdatedEvent ||
76     theMessage->eventID() == kMovedEvent) {
77     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
78         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
79     const std::set<ObjectPtr>& anObjs = aMsg->objects();
80     std::set<ObjectPtr>::const_iterator anObjIter = anObjs.cbegin();
81     for(; anObjIter != anObjs.cend(); anObjIter++) {
82       myJustCreatedOrUpdated.insert(*anObjIter);
83     }
84     if (theMessage->eventID() == kMovedEvent)
85       return; // this event is for solver update, not here
86   } else if (theMessage->eventID() == kOpStartEvent) {
87     myJustCreatedOrUpdated.clear();
88     return; // we don't need the update only on operation start (caused problems in PartSet_Listener::processEvent)
89   } else if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
90     if (isAutomatic == false) { // Apply button now works as "Rebuild"
91       isAutomaticChanged = true;
92       isAutomatic = true;
93     }
94     // the hardcode (DBC asked): hide the sketch referenced by extrusion on apply
95     if (theMessage->eventID() == kOpFinishEvent) {
96       std::set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter;
97       for(aFIter = myJustCreatedOrUpdated.begin(); aFIter != myJustCreatedOrUpdated.end(); aFIter++)
98       {
99         FeaturePtr aF = std::dynamic_pointer_cast<ModelAPI_Feature>(*aFIter);
100         if (aF && aF->getKind() == "Extrusion") {
101           if (aF->selection("extrusion_face")) {
102             ResultPtr aSketchRes = aF->selection("extrusion_face")->context();
103             if (aSketchRes) {
104               static Events_ID HIDE_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE);
105               ModelAPI_EventCreator::get()->sendUpdated(aSketchRes, HIDE_DISP);
106             }
107           }
108         }
109       }
110     }
111   }
112
113   if (isExecuted)
114     return;  // nothing to do: it is executed now
115
116   //Events_LongOp::start(this);
117   isExecuted = true;
118   std::list<std::shared_ptr<ModelAPI_Document> > aDocs;
119   std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
120       std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
121   if (aMsg) myInitial = aMsg->objects();
122   else {
123     myInitial.clear();
124     // on change flag all documents must be updated
125     if (isAutomatic) {
126       aDocs = ModelAPI_Session::get()->allOpenedDocuments();
127     }
128   }
129   // collect all documents involved into the update process
130   set<std::shared_ptr<ModelAPI_Object> >::iterator aFIter = myInitial.begin();
131   for (; aFIter != myInitial.end(); aFIter++) {
132     aDocs.push_back((*aFIter)->document());
133   }
134   // iterate all features of features-documents to update them (including hidden)
135   std::set<std::shared_ptr<ModelAPI_Document> > alreadyUsed;
136   list<std::shared_ptr<ModelAPI_Document> >::iterator aDIter = aDocs.begin();
137   for (; aDIter != aDocs.end(); aDIter++) {
138     if (alreadyUsed.find(*aDIter) != alreadyUsed.end())
139       continue;
140     alreadyUsed.insert(*aDIter);
141     int aNbFeatures = (*aDIter)->size(ModelAPI_Feature::group(), true);
142     for (int aFIndex = 0; aFIndex < aNbFeatures; aFIndex++) {
143       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
144           (*aDIter)->object(ModelAPI_Feature::group(), aFIndex, true));
145       if (aFeature)
146         updateFeature(aFeature);
147     }
148   }
149   myUpdated.clear();
150   // flush to update display
151   static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
152   aLoop->flush(EVENT_DISP);
153   //Events_LongOp::end(this);
154   if (isAutomaticChanged) isAutomatic = false;
155
156   if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
157     myJustCreatedOrUpdated.clear();
158   }
159
160   isExecuted = false;
161 }
162
163 void Model_Update::redisplayWithResults(FeaturePtr theFeature, const ModelAPI_ExecState theState) 
164 {
165   // maske updated and redisplay all results
166   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
167   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
168   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
169   for (; aRIter != aResults.cend(); aRIter++) {
170     std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
171     aRes->data()->execState(theState);
172     myUpdated[aRes] = true;
173     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
174   }
175   // to redisplay "presentable" feature (for ex. distance constraint)
176   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
177   theFeature->data()->execState(theState);
178 }
179
180 /// Updates the state by the referenced object: if something bad with it, set state for this one
181 ModelAPI_ExecState stateByReference(ObjectPtr theTarget, const ModelAPI_ExecState theCurrent)
182 {
183   if (theTarget) {
184     ModelAPI_ExecState aRefState = theTarget->data()->execState();
185     if (aRefState == ModelAPI_StateMustBeUpdated) {
186       return ModelAPI_StateMustBeUpdated;
187     } else if (aRefState != ModelAPI_StateDone) {
188       return ModelAPI_StateInvalidArgument;
189     }
190   }
191   return theCurrent;
192 }
193
194 bool Model_Update::updateFeature(FeaturePtr theFeature)
195 {
196   // check it is already processed
197   if (myUpdated.find(theFeature) != myUpdated.end())
198     return myUpdated[theFeature];
199   // check all features this feature depended on (recursive call of updateFeature)
200   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
201   bool aMustbeUpdated = myInitial.find(theFeature) != myInitial.end();
202   if (theFeature) {  // only real feature contains references to other objects
203     if (theFeature->data()->execState() != ModelAPI_StateDone)
204       aMustbeUpdated = true;
205
206     // composite feature must be executed after sub-features execution
207     CompositeFeaturePtr aComposite = 
208       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
209     if (aComposite) {
210       int aSubsNum = aComposite->numberOfSubs();
211       for(int a = 0; a < aSubsNum; a++) {
212         if (updateFeature(aComposite->subFeature(a)))
213           aMustbeUpdated = true;
214       }
215     }
216     ModelAPI_ExecState aState = ModelAPI_StateDone;
217     // check all references: if referenced objects are updated, this object also must be updated
218     // also check state of referenced objects: if they are not ready, inherit corresponding state
219     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
220     std::shared_ptr<Model_Data> aData = 
221       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
222     aData->referencesToObjects(aRefs);
223     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
224     for(; aRef != aRefs.end(); aRef++) {
225       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
226       for(; aRefObj != aRef->second.end(); aRefObj++) {
227         if (updateObject(*aRefObj)) {
228           aMustbeUpdated = true;
229         }
230         aState = stateByReference(*aRefObj, aState);
231       }
232     }
233
234     //std::cout<<"Update feature "<<theFeature->getKind()<<" must be updated = "<<aMustbeUpdated<<std::endl;
235     // execute feature if it must be updated
236     if (aMustbeUpdated) {
237       if (std::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
238           !theFeature->isPersistentResult()) {
239         if (aFactory->validate(theFeature)) {
240           if (isAutomatic || 
241               (myJustCreatedOrUpdated.find(theFeature) != myJustCreatedOrUpdated.end()) ||
242               !theFeature->isPersistentResult() /* execute quick, not persistent results */) 
243           {
244             if (aState == ModelAPI_StateDone) {// all referenced objects are ready to be used
245               //std::cout<<"Execute feature "<<theFeature->getKind()<<std::endl;
246               // before execution update the selection attributes if any
247               list<AttributePtr> aRefs = 
248                 theFeature->data()->attributes(ModelAPI_AttributeSelection::type());
249               list<AttributePtr>::iterator aRefsIter = aRefs.begin();
250               for (; aRefsIter != aRefs.end(); aRefsIter++) {
251                 std::shared_ptr<ModelAPI_AttributeSelection> aSel =
252                   std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
253                 if (!aSel->update()) { // this must be done on execution since it may be long operation
254                   if (!aFactory->isNotObligatory(theFeature->getKind(), theFeature->data()->id(aSel)))
255                     aState = ModelAPI_StateInvalidArgument;
256                 }
257               }
258               aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::type());
259               for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
260                 std::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
261                   std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
262                 for(int a = aSel->size() - 1; a >= 0; a--) {
263                   std::shared_ptr<ModelAPI_AttributeSelection> aSelAttr =
264                     std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(aSel->value(a));
265                   if (aSelAttr) {
266                     if (!aSelAttr->update()) {
267                       if (!aFactory->isNotObligatory(
268                           theFeature->getKind(), theFeature->data()->id(aSel)))
269                         aState = ModelAPI_StateInvalidArgument;
270                     }
271                   }
272                 }
273               }
274               // for sketch after update of plane (by update of selection attribute)
275               // but before execute, all sub-elements also must be updated (due to the plane changes)
276               if (aComposite) {
277                 int aSubsNum = aComposite->numberOfSubs();
278                 for(int a = 0; a < aSubsNum; a++) {
279                   FeaturePtr aSub = aComposite->subFeature(a);
280                   bool aWasModified = myUpdated[aSub];
281                   myUpdated.erase(myUpdated.find(aSub)); // erase to update for sure (plane may be changed)
282                   myInitial.insert(aSub);
283                   updateFeature(aSub);
284                   myUpdated[aSub] = aWasModified; // restore value
285                 }
286                 // re-execute after update: solver may update the previous values, so, shapes must be
287                 // updated
288                 for(int a = 0; a < aSubsNum; a++) {
289                   if (aComposite->subFeature(a) && aFactory->validate(aComposite->subFeature(a)))
290                     aComposite->subFeature(a)->execute();
291                 }
292               }
293             }
294
295             // execute in try-catch to avoid internal problems of the feature
296             if (aState == ModelAPI_StateDone) {
297               theFeature->data()->execState(ModelAPI_StateDone);
298               try {
299                 theFeature->execute();
300                 if (theFeature->data()->execState() != ModelAPI_StateDone) {
301                   aState = ModelAPI_StateExecFailed;
302                 }
303               } catch(...) {
304                 aState = ModelAPI_StateExecFailed;
305                 Events_Error::send(
306                   "Feature " + theFeature->getKind() + " has failed during the execution");
307               }
308             }
309             if (aState != ModelAPI_StateDone) {
310               theFeature->eraseResults();
311             }
312             redisplayWithResults(theFeature, aState);
313           } else { // must be updatet, but not updated yet
314             theFeature->data()->execState(ModelAPI_StateMustBeUpdated);
315             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
316             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
317             for (; aRIter != aResults.cend(); aRIter++) {
318               std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
319               aRes->data()->execState(ModelAPI_StateMustBeUpdated);
320             }
321           }
322         } else {
323           theFeature->eraseResults();
324           redisplayWithResults(theFeature, ModelAPI_StateInvalidArgument); // result also must be updated
325         }
326       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
327         redisplayWithResults(theFeature, ModelAPI_StateNothing);
328       }
329     } else {  // returns also true is results were updated: for sketch that refers to sub-features but results of sub-features were changed
330       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
331       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
332       for (; aRIter != aResults.cend(); aRIter++) {
333         if (myInitial.find(*aRIter) != myInitial.end()) {
334           aMustbeUpdated = true;
335           break;
336         }
337       }
338     }
339   }
340   myUpdated[theFeature] = aMustbeUpdated;
341   return aMustbeUpdated;
342 }
343
344 bool Model_Update::updateObject(std::shared_ptr<ModelAPI_Object> theObject, const bool theCyclic)
345 {
346   if (myUpdated.find(theObject) != myUpdated.end())
347     return myUpdated[theObject];  // already processed
348
349   /*
350   if (theCyclic) { // algorithm for update of all features by dependencies tree
351     if (!theObject)
352       return false;
353     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
354     if (aFeature) {  // for feature just call update Feature
355       return updateFeature(aFeature);
356     }
357     // check general object, possible just a result
358     if (myUpdated.find(theObject) != myUpdated.end())
359       return myUpdated[theObject];  // already processed
360     // check the feature of this object must be executed
361     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
362     if (aResult) {
363       FeaturePtr aResFeature = aResult->document()->feature(aResult);
364       if (aResFeature) {
365         return updateFeature(aResFeature);
366       }
367     }
368   }
369   */
370   return myInitial.find(theObject) != myInitial.end();
371 }