Salome HOME
4c23c9c30f451d5eac89fb60e20ec27cd7aad041
[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 boost::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     boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
78         boost::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   }
95
96   if (isExecuted)
97     return;  // nothing to do: it is executed now
98
99   //Events_LongOp::start(this);
100   isExecuted = true;
101   std::list<boost::shared_ptr<ModelAPI_Document> > aDocs;
102   boost::shared_ptr<ModelAPI_ObjectUpdatedMessage> aMsg =
103       boost::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
104   if (aMsg) myInitial = aMsg->objects();
105   else {
106     myInitial.clear();
107     // on change flag all documents must be updated
108     if (isAutomatic) {
109       aDocs = ModelAPI_Session::get()->allOpenedDocuments();
110     }
111   }
112   // collect all documents involved into the update process
113   set<boost::shared_ptr<ModelAPI_Object> >::iterator aFIter = myInitial.begin();
114   for (; aFIter != myInitial.end(); aFIter++) {
115     aDocs.push_back((*aFIter)->document());
116   }
117   // iterate all features of features-documents to update them (including hidden)
118   std::set<boost::shared_ptr<ModelAPI_Document> > alreadyUsed;
119   list<boost::shared_ptr<ModelAPI_Document> >::iterator aDIter = aDocs.begin();
120   for (; aDIter != aDocs.end(); aDIter++) {
121     if (alreadyUsed.find(*aDIter) != alreadyUsed.end())
122       continue;
123     alreadyUsed.insert(*aDIter);
124     int aNbFeatures = (*aDIter)->size(ModelAPI_Feature::group(), true);
125     for (int aFIndex = 0; aFIndex < aNbFeatures; aFIndex++) {
126       FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(
127           (*aDIter)->object(ModelAPI_Feature::group(), aFIndex, true));
128       if (aFeature)
129         updateFeature(aFeature);
130     }
131   }
132   myUpdated.clear();
133   // flush to update display
134   static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
135   aLoop->flush(EVENT_DISP);
136   //Events_LongOp::end(this);
137   if (isAutomaticChanged) isAutomatic = false;
138
139   if (theMessage->eventID() == kOpFinishEvent || theMessage->eventID() == kOpAbortEvent) {
140     myJustCreatedOrUpdated.clear();
141   }
142
143   isExecuted = false;
144 }
145
146 void Model_Update::redisplayWithResults(FeaturePtr theFeature) {
147   // maske updated and redisplay all results
148   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
149   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
150   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
151   for (; aRIter != aResults.cend(); aRIter++) {
152     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
153     aRes->data()->mustBeUpdated(false);
154     myUpdated[aRes] = true;
155     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
156   }
157   // to redisplay "presentable" feature (for ex. distance constraint)
158   ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
159   theFeature->data()->mustBeUpdated(false);
160 }
161
162 bool Model_Update::updateFeature(FeaturePtr theFeature)
163 {
164   // check it is already processed
165   if (myUpdated.find(theFeature) != myUpdated.end())
166     return myUpdated[theFeature];
167   // check all features this feature depended on (recursive call of updateFeature)
168   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
169   bool aMustbeUpdated = myInitial.find(theFeature) != myInitial.end();
170   if (theFeature) {  // only real feature contains references to other objects
171     if (theFeature->data()->mustBeUpdated()) aMustbeUpdated = true;
172
173     // composite feature must be executed after sub-features execution
174     CompositeFeaturePtr aComposite = 
175       boost::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
176     if (aComposite) {
177       int aSubsNum = aComposite->numberOfSubs();
178       for(int a = 0; a < aSubsNum; a++) {
179         if (updateFeature(aComposite->subFeature(a)))
180           aMustbeUpdated = true;
181       }
182       if (aMustbeUpdated) {
183         for(int a = 0; a < aSubsNum; a++) {
184           if (aComposite->subFeature(a) && aFactory->validate(aComposite->subFeature(a)))
185             aComposite->subFeature(a)->execute();
186         }
187       }
188     }
189     // check all references: if referenced objects are updated, this object also must be updated
190     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
191     boost::shared_ptr<Model_Data> aData = 
192       boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
193     aData->referencesToObjects(aRefs);
194     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
195     for(; aRef != aRefs.end(); aRef++) {
196       std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
197       for(; aRefObj != aRef->second.end(); aRefObj++) {
198         if (updateObject(*aRefObj)) {
199           aMustbeUpdated = true;
200         }
201       }
202     }
203
204     // execute feature if it must be updated
205     if (aMustbeUpdated) {
206       if (boost::dynamic_pointer_cast<Model_Document>(theFeature->document())->executeFeatures() ||
207           !theFeature->isPersistentResult()) {
208         if (aFactory->validate(theFeature)) {
209           if (isAutomatic || (myJustCreatedOrUpdated.find(theFeature) != myJustCreatedOrUpdated.end()) ||
210             !theFeature->isPersistentResult() /* execute quick, not persistent results */) 
211           {
212             // before execution update the selection attributes if any
213             list<AttributePtr> aRefs = 
214               theFeature->data()->attributes(ModelAPI_AttributeSelection::type());
215             list<AttributePtr>::iterator aRefsIter = aRefs.begin();
216             for (; aRefsIter != aRefs.end(); aRefsIter++) {
217               boost::shared_ptr<ModelAPI_AttributeSelection> aSel =
218                 boost::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRefsIter);
219               aSel->update(); // this must be done on execution since it may be long operation
220             }
221             aRefs = theFeature->data()->attributes(ModelAPI_AttributeSelectionList::type());
222             for (aRefsIter = aRefs.begin(); aRefsIter != aRefs.end(); aRefsIter++) {
223               boost::shared_ptr<ModelAPI_AttributeSelectionList> aSel =
224                 boost::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(*aRefsIter);
225               for(int a = aSel->size() - 1; a >= 0; a--) {
226                   aSel->value(a)->update();
227               }
228             }
229             // execute in try-catch to avoid internal problems of the feature
230             try {
231               theFeature->execute();
232             } catch(...) {
233               Events_Error::send(
234                 "Feature " + theFeature->getKind() + " has failed during the execution");
235               theFeature->eraseResults();
236             }
237             redisplayWithResults(theFeature);
238           } else { // must be updatet, but not updated yet
239             theFeature->data()->mustBeUpdated(true);
240             const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
241             std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
242             for (; aRIter != aResults.cend(); aRIter++) {
243               boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
244               aRes->data()->mustBeUpdated(true);
245             }
246           }
247         } else {
248           theFeature->eraseResults();
249           redisplayWithResults(theFeature); // result also must be updated
250         }
251       } else { // for automatically updated features (on abort, etc) it is necessary to redisplay anyway
252         redisplayWithResults(theFeature);
253       }
254     } else {  // returns also true is results were updated: for sketch that refers to sub-features but results of sub-features were changed
255       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
256       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
257       for (; aRIter != aResults.cend(); aRIter++) {
258         if (myInitial.find(*aRIter) != myInitial.end()) {
259           aMustbeUpdated = true;
260           break;
261         }
262       }
263     }
264   }
265   myUpdated[theFeature] = aMustbeUpdated;
266   return aMustbeUpdated;
267 }
268
269 bool Model_Update::updateObject(boost::shared_ptr<ModelAPI_Object> theObject, const bool theCyclic)
270 {
271   if (myUpdated.find(theObject) != myUpdated.end())
272     return myUpdated[theObject];  // already processed
273
274   /*
275   if (theCyclic) { // algorithm for update of all features by dependencies tree
276     if (!theObject)
277       return false;
278     FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
279     if (aFeature) {  // for feature just call update Feature
280       return updateFeature(aFeature);
281     }
282     // check general object, possible just a result
283     if (myUpdated.find(theObject) != myUpdated.end())
284       return myUpdated[theObject];  // already processed
285     // check the feature of this object must be executed
286     ResultPtr aResult = boost::dynamic_pointer_cast<ModelAPI_Result>(theObject);
287     if (aResult) {
288       FeaturePtr aResFeature = aResult->document()->feature(aResult);
289       if (aResFeature) {
290         return updateFeature(aResFeature);
291       }
292     }
293   }
294   */
295   return myInitial.find(theObject) != myInitial.end();
296 }