Salome HOME
Fix for the problem that on undo/redo of feature creation (in this particular case...
[modules/shaper.git] / src / Model / Model_Session.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Session.cxx
4 // Created:     20 Mar 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Session.h>
8 #include <ModelAPI_Feature.h>
9 #include <ModelAPI_Plugin.h>
10 #include <Model_Data.h>
11 #include <Model_Document.h>
12 #include <Model_Objects.h>
13 #include <Model_Application.h>
14 #include <Model_Events.h>
15 #include <Model_Validator.h>
16 #include <ModelAPI_Events.h>
17 #include <Events_Loop.h>
18 #include <Events_InfoMessage.h>
19 #include <Config_FeatureMessage.h>
20 #include <Config_AttributeMessage.h>
21 #include <Config_ValidatorMessage.h>
22 #include <Config_ModuleReader.h>
23 #include <Config_ValidatorReader.h>
24 #include <ModelAPI_ResultPart.h>
25 #include <ModelAPI_Tools.h>
26
27 #include <TDF_CopyTool.hxx>
28 #include <TDF_DataSet.hxx>
29 #include <TDF_RelocationTable.hxx>
30 #include <TDF_ClosureTool.hxx>
31
32 static Model_Session* myImpl = new Model_Session();
33
34 // t oredirect all calls to the root document
35 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
36
37 bool Model_Session::load(const char* theFileName)
38 {
39   bool aRes = ROOT_DOC->load(theFileName, "root", ROOT_DOC);
40   return aRes;
41 }
42
43 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
44 {
45   return ROOT_DOC->save(theFileName, "root", theResults);
46 }
47
48 void Model_Session::closeAll()
49 {
50   Model_Application::getApplication()->deleteAllDocuments();
51 }
52
53 void Model_Session::startOperation(const std::string& theId, const bool theAttachedToNested)
54 {
55   myOperationAttachedToNext = theAttachedToNested;
56   ROOT_DOC->startOperation();
57   ROOT_DOC->operationId(theId);
58   static std::shared_ptr<Events_Message> aStartedMsg
59     (new Events_Message(Events_Loop::eventByName("StartOperation")));
60   Events_Loop::loop()->send(aStartedMsg);
61   // remove all useless documents that has been closed: on start of operation undo/redo is cleared
62   // MPV: this code is dangerous now because it may close the document that is activated right now
63   // but not in the list of the opened documents yet (create, delete, undo, activate Part)
64   // later this must be updated by correct usage of uniques IDs of documents, not names of results
65   //std::list<std::shared_ptr<ModelAPI_Document> > aUsedDocs = allOpenedDocuments();
66   //Model_Application::getApplication()->removeUselessDocuments(aUsedDocs);
67 }
68
69 void Model_Session::finishOperation()
70 {
71   setCheckTransactions(false);
72   ROOT_DOC->finishOperation();
73   if (myOperationAttachedToNext) { // twice, with nested
74     ROOT_DOC->finishOperation();
75     myOperationAttachedToNext = false;
76   }
77   setCheckTransactions(true);
78 }
79
80 void Model_Session::abortOperation()
81 {
82   setCheckTransactions(false);
83   ROOT_DOC->abortOperation();
84   if (myOperationAttachedToNext) { // twice, with nested
85     ROOT_DOC->abortOperation();
86     myOperationAttachedToNext = false;
87   }
88   setCheckTransactions(true);
89   // here the update mechanism may work after abort, so, supress the warnings about
90   // modifications outside of the transactions
91   bool aWasCheck = myCheckTransactions;
92   myCheckTransactions = false;
93   static std::shared_ptr<Events_Message> anAbortMsg
94     (new Events_Message(Events_Loop::eventByName("AbortOperation")));
95   Events_Loop::loop()->send(anAbortMsg);
96   myCheckTransactions = true;
97   myCheckTransactions = aWasCheck;
98 }
99
100 bool Model_Session::isOperation()
101 {
102   return ROOT_DOC->isOperation();
103 }
104
105 bool Model_Session::isModified()
106 {
107   return ROOT_DOC->isModified();
108 }
109
110 bool Model_Session::canUndo()
111 {
112   return ROOT_DOC->canUndo();
113 }
114
115 void Model_Session::undo()
116 {
117   setCheckTransactions(false);
118   ROOT_DOC->undo();
119   setCheckTransactions(true);
120 }
121
122 bool Model_Session::canRedo()
123 {
124   return ROOT_DOC->canRedo();
125 }
126
127 void Model_Session::redo()
128 {
129   setCheckTransactions(false);
130   ROOT_DOC->redo();
131   setCheckTransactions(true);
132 }
133
134 //! Returns stack of performed operations
135 std::list<std::string> Model_Session::undoList()
136 {
137   return ROOT_DOC->undoList();
138 }
139 //! Returns stack of rolled back operations
140 std::list<std::string> Model_Session::redoList()
141 {
142   return ROOT_DOC->redoList();
143 }
144
145 FeaturePtr Model_Session::createFeature(std::string theFeatureID, Model_Document* theDocOwner)
146 {
147   if (this != myImpl) {
148     return myImpl->createFeature(theFeatureID, theDocOwner);
149   }
150
151   // load all information about plugins, features and attributes
152   LoadPluginsInfo();
153
154   if (myPlugins.find(theFeatureID) != myPlugins.end()) {
155     std::pair<std::string, std::string>& aPlugin = myPlugins[theFeatureID]; // plugin and doc kind
156     if (!aPlugin.second.empty() && aPlugin.second != theDocOwner->kind()) {
157       Events_InfoMessage("Model_Session",
158           "Feature '%1' can be created only in document '%2' by the XML definition")
159           .arg(theFeatureID).arg(aPlugin.second).send();
160       return FeaturePtr();
161     }
162     myCurrentPluginName = aPlugin.first;
163     if (myPluginObjs.find(myCurrentPluginName) == myPluginObjs.end()) {
164       // load plugin library if not yet done
165       Config_ModuleReader::loadPlugin(myCurrentPluginName);
166     }
167     if (myPluginObjs.find(myCurrentPluginName) != myPluginObjs.end()) {
168       FeaturePtr aCreated = myPluginObjs[myCurrentPluginName]->createFeature(theFeatureID);
169       if (!aCreated) {
170         Events_InfoMessage("Model_Session",
171             "Can not initialize feature '%1' in plugin '%2'")
172             .arg(theFeatureID).arg(myCurrentPluginName).send();
173       }
174       return aCreated;
175     } else {
176       Events_InfoMessage("Model_Session",
177         "Can not load plugin '%1'").arg(myCurrentPluginName).send();
178     }
179   } else {
180     Events_InfoMessage("Model_Session",
181       "Feature '%1' not found in any plugin").arg(theFeatureID).send();
182   }
183
184   return FeaturePtr();  // return nothing
185 }
186
187 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
188 {
189   Handle(Model_Application) anApp = Model_Application::getApplication();
190   bool aFirstCall = !anApp->hasRoot();
191   if (aFirstCall) {
192     // to be sure that plugins are loaded,
193     // even before the first "createFeature" call (in unit tests)
194     LoadPluginsInfo();
195     // creation of the root document is always outside of the transaction, so, avoid checking it
196     setCheckTransactions(false);
197     anApp->createDocument(0); // 0 is a root ID
198     // creation of the root document is always outside of the transaction, so, avoid checking it
199     setCheckTransactions(true);
200   }
201   return anApp->rootDocument();
202 }
203
204 std::shared_ptr<ModelAPI_Document> Model_Session::document(int theDocID)
205 {
206   return std::shared_ptr<ModelAPI_Document>(
207       Model_Application::getApplication()->document(theDocID));
208 }
209
210 bool Model_Session::hasModuleDocument()
211 {
212   return Model_Application::getApplication()->hasRoot();
213 }
214
215 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
216 {
217   if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
218     myCurrentDoc = moduleDocument();
219   return myCurrentDoc;
220 }
221
222 /// makes the last feature in the document as the current
223 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
224   if (theDoc.get()) {
225     FeaturePtr aLast = std::dynamic_pointer_cast<Model_Document>(theDoc)->lastFeature();
226     // if last is nested into something else, make this something else as last:
227     // otherwise it will look like edition of sub-element, so, the main will be disabled
228     if (aLast.get()) {
229       CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
230       while(aMain.get()) {
231         aLast = aMain;
232         aMain = ModelAPI_Tools::compositeOwner(aLast);
233       }
234     }
235     theDoc->setCurrentFeature(aLast, false);
236   }
237 }
238
239 void Model_Session::setActiveDocument(
240   std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
241 {
242   if (myCurrentDoc != theDoc) {
243     if (myCurrentDoc.get())
244       myCurrentDoc->setActive(false);
245     if (theDoc.get())
246       theDoc->setActive(true);
247
248     std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
249     myCurrentDoc = theDoc;
250     if (theDoc.get() && theSendSignal) {
251       // this must be before the synchronisation call because features in PartSet lower than this
252       // part feature must be disabled and don't recomputed anymore (issue 1156,
253       // translation feature is failed on activation of Part 2)
254       if (isOperation()) { // do it only in transaction, not on opening of document
255         DocumentPtr aRoot = moduleDocument();
256         if (myCurrentDoc != aRoot) {
257           FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
258           if (aPartFeat.get()) {
259             aRoot->setCurrentFeature(aPartFeat, false);
260           }
261         }
262       }
263       // syncronize the document: it may be just opened or opened but removed before
264       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
265       if (aDoc.get()) {
266         bool aWasChecked = myCheckTransactions;
267         setCheckTransactions(false);
268         TDF_LabelList anEmptyUpdated;
269         aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true, false, true);
270         if (aWasChecked)
271             setCheckTransactions(true);
272       }
273       static std::shared_ptr<Events_Message> aMsg(
274           new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
275       Events_Loop::loop()->send(aMsg);
276     }
277     // make the current state correct and synchronised in the module and sub-documents
278     if (isOperation()) { // do it only in transaction, not on opening of document
279       if (myCurrentDoc == moduleDocument()) {
280         // make the current feature the latest in root, in previous root current become also last
281         makeCurrentLast(aPrevious);
282         makeCurrentLast(myCurrentDoc);
283       } else {
284         // make the current feature the latest in sub, root current feature becomes this sub
285         makeCurrentLast(myCurrentDoc);
286       }
287     }
288   }
289 }
290
291 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
292 {
293   std::list<std::shared_ptr<ModelAPI_Document> > aResult;
294   aResult.push_back(moduleDocument());
295   // add subs recursively
296   std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
297   for(; aDoc != aResult.end(); aDoc++) {
298     DocumentPtr anAPIDoc = *aDoc;
299     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
300     if (aDoc) {
301       const std::set<int> aSubs = aDoc->subDocuments();
302       std::set<int>::const_iterator aSubIter = aSubs.cbegin();
303       for(; aSubIter != aSubs.cend(); aSubIter++) {
304         aResult.push_back(Model_Application::getApplication()->document(*aSubIter));
305       }
306     }
307   }
308   return aResult;
309 }
310
311 bool Model_Session::isLoadByDemand(const std::string theDocID)
312 {
313   return Model_Application::getApplication()->isLoadByDemand(theDocID);
314 }
315
316 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
317     std::shared_ptr<ModelAPI_Document> theSource, const int theDestID)
318 {
319   std::shared_ptr<Model_Document> aNew = Model_Application::getApplication()->document(theDestID);
320   // make a copy of all labels
321   TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
322       .Father();
323   TDF_Label aTargetRoot = aNew->document()->Main().Father();
324   Handle(TDF_DataSet) aDS = new TDF_DataSet;
325   aDS->AddLabel(aSourceRoot);
326   TDF_ClosureTool::Closure(aDS);
327   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable(Standard_True);
328   aRT->SetRelocation(aSourceRoot, aTargetRoot);
329   TDF_CopyTool::Copy(aDS, aRT);
330
331   TDF_LabelList anEmptyUpdated;
332   aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true, true);
333   return aNew;
334 }
335
336 Model_Session::Model_Session()
337 {
338   myPluginsInfoLoaded = false;
339   myCheckTransactions = true;
340   myOperationAttachedToNext = false;
341   ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
342   // register the configuration reading listener
343   Events_Loop* aLoop = Events_Loop::loop();
344   static const Events_ID kFeatureEvent =
345     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
346   aLoop->registerListener(this, kFeatureEvent);
347   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
348   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
349   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
350   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
351 }
352
353 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
354 {
355   static const Events_ID kFeatureEvent =
356     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
357   static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
358   if (theMessage->eventID() == kFeatureEvent) {
359     const std::shared_ptr<Config_FeatureMessage> aMsg =
360       std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
361     if (aMsg) {
362
363       // process the plugin info, load plugin
364       if (myPlugins.find(aMsg->id()) == myPlugins.end()) {
365         myPlugins[aMsg->id()] = std::pair<std::string, std::string>(
366           aMsg->pluginLibrary(), aMsg->documentKind());
367       }
368     } else {
369       const std::shared_ptr<Config_AttributeMessage> aMsgAttr =
370         std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
371       if (aMsgAttr) {
372
373         if (!aMsgAttr->isObligatory()) {
374           validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
375         }
376         if(aMsgAttr->isConcealment()) {
377           validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
378         }
379         const std::list<std::pair<std::string, std::string> >& aCases = aMsgAttr->getCases();
380         if (!aCases.empty()) {
381           validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(), aCases);
382         }
383       }
384     }
385     // plugins information was started to load, so, it will be loaded
386     myPluginsInfoLoaded = true;
387   } else if (theMessage->eventID() == kValidatorEvent) {
388     std::shared_ptr<Config_ValidatorMessage> aMsg =
389       std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
390     if (aMsg) {
391       if (aMsg->attributeId().empty()) {  // feature validator
392         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
393       } else {  // attribute validator
394         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
395                                       aMsg->parameters());
396       }
397     }
398   } else {  // create/update/delete
399     if (myCheckTransactions && !isOperation())
400       Events_InfoMessage("Model_Session",
401         "Modification of data structure outside of the transaction").send();
402     // if part is deleted, make the root as the current document (on undo of Parts creations)
403     static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
404     if (theMessage->eventID() == kDeletedEvent) {
405       std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
406         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
407       if (aDeleted &&
408           aDeleted->groups().find(ModelAPI_ResultPart::group()) != aDeleted->groups().end())
409       {
410          // check that the current feature of the session is still the active Part (even disabled)
411         bool aFound = false;
412         FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
413         if (aCurrentPart.get()) {
414           const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
415           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
416           for(; !aFound && aRes != aResList.end(); aRes++) {
417             ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
418             if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
419               aFound = true;
420
421             }
422           }
423         }
424         if (!aFound) { // if not, the part was removed, so activate the module document
425           if (myCurrentDoc.get())
426             setActiveDocument(moduleDocument());
427         }
428       }
429     }
430   }
431 }
432
433 void Model_Session::LoadPluginsInfo()
434 {
435   if (myPluginsInfoLoaded)  // nothing to do
436     return;
437
438   // Read plugins information from XML files
439   Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
440   aModuleReader.readAll();
441   std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
442   std::set<std::string>::iterator it = aFiles.begin();
443   for ( ; it != aFiles.end(); it++ ) {
444     Config_ValidatorReader aValidatorReader (*it);
445     aValidatorReader.readAll();
446   };
447
448 }
449
450 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
451 {
452   myPluginObjs[myCurrentPluginName] = thePlugin;
453   static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
454   ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD);
455   Events_Loop::loop()->flush(EVENT_LOAD);
456   // If the plugin has an ability to process GUI events, register it
457   Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
458   if (aListener) {
459     Events_Loop* aLoop = Events_Loop::loop();
460     static Events_ID aStateRequestEventId =
461         Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
462     aLoop->registerListener(aListener, aStateRequestEventId);
463   }
464 }
465
466 ModelAPI_ValidatorsFactory* Model_Session::validators()
467 {
468   static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
469   return aFactory;
470 }
471
472 int Model_Session::transactionID()
473 {
474   return ROOT_DOC->transactionID();
475 }