Salome HOME
Fix for import/export features
[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_Error.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 using namespace std;
33
34 static Model_Session* myImpl = new Model_Session();
35
36 // t oredirect all calls to the root document
37 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
38
39 bool Model_Session::load(const char* theFileName)
40 {
41   bool aRes = ROOT_DOC->load(theFileName, ROOT_DOC);
42   return aRes;
43 }
44
45 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
46 {
47   return ROOT_DOC->save(theFileName, theResults);
48 }
49
50 void Model_Session::closeAll()
51 {
52   Model_Application::getApplication()->deleteAllDocuments();
53 }
54
55 void Model_Session::startOperation(const std::string& theId)
56 {
57   ROOT_DOC->startOperation();
58   ROOT_DOC->operationId(theId);
59   static std::shared_ptr<Events_Message> aStartedMsg
60     (new Events_Message(Events_Loop::eventByName("StartOperation")));
61   Events_Loop::loop()->send(aStartedMsg);
62   // remove all useless documents that has been closed: on start of operation undo/redo is cleared
63   std::list<std::shared_ptr<ModelAPI_Document> > aUsedDocs = allOpenedDocuments();
64   Model_Application::getApplication()->removeUselessDocuments(aUsedDocs);
65 }
66
67 void Model_Session::finishOperation()
68 {
69   setCheckTransactions(false);
70   ROOT_DOC->finishOperation();
71   setCheckTransactions(true);
72 }
73
74 void Model_Session::abortOperation()
75 {
76   setCheckTransactions(false);
77   ROOT_DOC->abortOperation();
78   setCheckTransactions(true);
79   // here the update mechanism may work after abort, so, supress the warnings about
80   // modifications outside of the transactions
81   bool aWasCheck = myCheckTransactions;
82   myCheckTransactions = false;
83   static std::shared_ptr<Events_Message> anAbortMsg
84     (new Events_Message(Events_Loop::eventByName("AbortOperation")));
85   Events_Loop::loop()->send(anAbortMsg);
86   myCheckTransactions = true;
87   myCheckTransactions = aWasCheck;
88 }
89
90 bool Model_Session::isOperation()
91 {
92   return ROOT_DOC->isOperation();
93 }
94
95 bool Model_Session::isModified()
96 {
97   return ROOT_DOC->isModified();
98 }
99
100 bool Model_Session::canUndo()
101 {
102   return ROOT_DOC->canUndo();
103 }
104
105 void Model_Session::undo()
106 {
107   setCheckTransactions(false);
108   ROOT_DOC->undo();
109   setCheckTransactions(true);
110 }
111
112 bool Model_Session::canRedo()
113 {
114   return ROOT_DOC->canRedo();
115 }
116
117 void Model_Session::redo()
118 {
119   setCheckTransactions(false);
120   ROOT_DOC->redo();
121   setCheckTransactions(true);
122 }
123
124 //! Returns stack of performed operations
125 std::list<std::string> Model_Session::undoList()
126 {
127   return ROOT_DOC->undoList();
128 }
129 //! Returns stack of rolled back operations
130 std::list<std::string> Model_Session::redoList()
131 {
132   return ROOT_DOC->redoList();
133 }
134
135 FeaturePtr Model_Session::createFeature(string theFeatureID, Model_Document* theDocOwner)
136 {
137   if (this != myImpl) {
138     return myImpl->createFeature(theFeatureID, theDocOwner);
139   }
140
141   // load all information about plugins, features and attributes
142   LoadPluginsInfo();
143
144   if (myPlugins.find(theFeatureID) != myPlugins.end()) {
145     std::pair<std::string, std::string>& aPlugin = myPlugins[theFeatureID]; // plugin and doc kind
146     if (!aPlugin.second.empty() && aPlugin.second != theDocOwner->kind()) {
147       Events_Error::send(
148           string("Feature '") + theFeatureID + "' can be created only in document '"
149               + aPlugin.second + "' by the XML definition");
150       return FeaturePtr();
151     }
152     myCurrentPluginName = aPlugin.first;
153     if (myPluginObjs.find(myCurrentPluginName) == myPluginObjs.end()) {
154       // load plugin library if not yet done
155       Config_ModuleReader::loadPlugin(myCurrentPluginName);
156     }
157     if (myPluginObjs.find(myCurrentPluginName) != myPluginObjs.end()) {
158       FeaturePtr aCreated = myPluginObjs[myCurrentPluginName]->createFeature(theFeatureID);
159       if (!aCreated) {
160         Events_Error::send(
161             string("Can not initialize feature '") + theFeatureID + "' in plugin '"
162                 + myCurrentPluginName + "'");
163       }
164       return aCreated;
165     } else {
166       Events_Error::send(string("Can not load plugin '") + myCurrentPluginName + "'");
167     }
168   } else {
169     Events_Error::send(string("Feature '") + theFeatureID + "' not found in any plugin");
170   }
171
172   return FeaturePtr();  // return nothing
173 }
174
175 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
176 {
177   bool aFirstCall = !Model_Application::getApplication()->hasDocument("root");
178   if (aFirstCall) {
179     // creation of the root document is always outside of the transaction, so, avoid checking it
180     setCheckTransactions(false);
181   }
182   std::shared_ptr<ModelAPI_Document> aDoc = std::shared_ptr<ModelAPI_Document>(
183       Model_Application::getApplication()->getDocument("root"));
184   if (aFirstCall) {
185     // creation of the root document is always outside of the transaction, so, avoid checking it
186     setCheckTransactions(true);
187   }
188   return aDoc;
189 }
190
191 std::shared_ptr<ModelAPI_Document> Model_Session::document(std::string theDocID)
192 {
193   return std::shared_ptr<ModelAPI_Document>(
194       Model_Application::getApplication()->getDocument(theDocID));
195 }
196
197 bool Model_Session::hasModuleDocument()
198 {
199   return Model_Application::getApplication()->hasDocument("root");
200 }
201
202 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
203 {
204   if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
205     myCurrentDoc = moduleDocument();
206   return myCurrentDoc;
207 }
208
209 /// makes the last feature in the document as the current
210 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
211   if (theDoc.get()) {
212     FeaturePtr aLastFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theDoc->object(
213       ModelAPI_Feature::group(), theDoc->size(ModelAPI_Feature::group()) - 1));
214     theDoc->setCurrentFeature(aLastFeature, false);
215   }
216 }
217
218 void Model_Session::setActiveDocument(
219   std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
220 {
221   if (myCurrentDoc != theDoc) {
222     if (myCurrentDoc.get())
223       myCurrentDoc->setActive(false);
224     if (theDoc.get())
225       theDoc->setActive(true);
226
227     std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
228     myCurrentDoc = theDoc;
229     if (theDoc.get() && theSendSignal) {
230       // syncronize the document: it may be just opened or opened but removed before
231       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
232       if (aDoc.get()) {
233         bool aWasChecked = myCheckTransactions;
234         setCheckTransactions(false);
235         aDoc->objects()->synchronizeFeatures(false, true, true);
236         if (aWasChecked)
237             setCheckTransactions(true);
238       }
239       static std::shared_ptr<Events_Message> aMsg(
240           new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
241       Events_Loop::loop()->send(aMsg);
242     }
243     // make the current state correct and synchronised in the module and sub-documents
244     if (isOperation()) { // do it only in transaction, not on opening of document
245       if (myCurrentDoc == moduleDocument()) {
246         // make the current feature the latest in root, in previous root current become also last
247         makeCurrentLast(aPrevious);
248         makeCurrentLast(myCurrentDoc);
249       } else {
250         // make the current feature the latest in sub, root current feature becomes this sub
251         makeCurrentLast(myCurrentDoc);
252         DocumentPtr aRoot = moduleDocument();
253         ResultPtr aPartRes = ModelAPI_Tools::findPartResult(aRoot, myCurrentDoc);
254         if (aPartRes.get()) {
255           FeaturePtr aPartFeat = aRoot->feature(aPartRes);
256           if (aPartFeat.get()) {
257             aRoot->setCurrentFeature(aPartFeat, false);
258           }
259         }
260       }
261     }
262   }
263 }
264
265 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
266 {
267   list<std::shared_ptr<ModelAPI_Document> > aResult;
268   aResult.push_back(moduleDocument());
269   // add subs recursively
270   list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
271   for(; aDoc != aResult.end(); aDoc++) {
272     DocumentPtr anAPIDoc = *aDoc;
273     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
274     if (aDoc) {
275       const std::set<std::string> aSubs = aDoc->subDocuments(true);
276       std::set<std::string>::const_iterator aSubIter = aSubs.cbegin();
277       for(; aSubIter != aSubs.cend(); aSubIter++) {
278         if (!Model_Application::getApplication()->isLoadByDemand(*aSubIter)) {
279           aResult.push_back(Model_Application::getApplication()->getDocument(*aSubIter));
280         }
281       }
282     }
283   }
284   return aResult;
285 }
286
287 bool Model_Session::isLoadByDemand(const std::string theDocID)
288 {
289   return Model_Application::getApplication()->isLoadByDemand(theDocID);
290 }
291
292 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
293     std::shared_ptr<ModelAPI_Document> theSource, std::string theID)
294 {
295   // create a new document
296   std::shared_ptr<Model_Document> aNew = std::dynamic_pointer_cast<Model_Document>(
297       Model_Application::getApplication()->getDocument(theID));
298   // make a copy of all labels
299   TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
300       .Father();
301   TDF_Label aTargetRoot = aNew->document()->Main().Father();
302   Handle(TDF_DataSet) aDS = new TDF_DataSet;
303   aDS->AddLabel(aSourceRoot);
304   TDF_ClosureTool::Closure(aDS);
305   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable;
306   aRT->SetRelocation(aSourceRoot, aTargetRoot);
307   TDF_CopyTool::Copy(aDS, aRT);
308
309   aNew->objects()->synchronizeFeatures(false, true, true);
310   return aNew;
311 }
312
313 Model_Session::Model_Session()
314 {
315   myPluginsInfoLoaded = false;
316   myCheckTransactions = true;
317   ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
318   // register the configuration reading listener
319   Events_Loop* aLoop = Events_Loop::loop();
320   static const Events_ID kFeatureEvent = 
321     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
322   aLoop->registerListener(this, kFeatureEvent);
323   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
324   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
325   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
326   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
327 }
328
329 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
330 {
331   static const Events_ID kFeatureEvent = 
332     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
333   static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
334   if (theMessage->eventID() == kFeatureEvent) {
335     const std::shared_ptr<Config_FeatureMessage> aMsg = 
336       std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
337     if (aMsg) {
338       // proccess the plugin info, load plugin
339       if (myPlugins.find(aMsg->id()) == myPlugins.end()) {
340         myPlugins[aMsg->id()] = std::pair<std::string, std::string>(
341           aMsg->pluginLibrary(), aMsg->documentKind());
342       }
343     } else {
344       const std::shared_ptr<Config_AttributeMessage> aMsgAttr = 
345         std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
346       if (aMsgAttr) {
347         if (!aMsgAttr->isObligatory()) {
348           validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
349         }
350         if(aMsgAttr->isConcealment()) {
351           validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
352         }
353         if (!aMsgAttr->caseId().empty()) {
354           validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(),
355             aMsgAttr->switchId(), aMsgAttr->caseId());
356         }
357       }
358     }
359     // plugins information was started to load, so, it will be loaded
360     myPluginsInfoLoaded = true;
361   } else if (theMessage->eventID() == kValidatorEvent) {
362     std::shared_ptr<Config_ValidatorMessage> aMsg = 
363       std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
364     if (aMsg) {
365       if (aMsg->attributeId().empty()) {  // feature validator
366         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
367       } else {  // attribute validator
368         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
369                                       aMsg->parameters());
370       }
371     }
372   } else {  // create/update/delete
373     if (myCheckTransactions && !isOperation())
374       Events_Error::send("Modification of data structure outside of the transaction");
375     // if part is deleted, make the root as the current document (on undo of Parts creations)
376     static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
377     if (theMessage->eventID() == kDeletedEvent) {
378       std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
379         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
380       if (aDeleted && 
381           aDeleted->groups().find(ModelAPI_ResultPart::group()) != aDeleted->groups().end() &&
382           !ModelAPI_Tools::findPartResult(moduleDocument(), activeDocument()).get()) // another part may be disabled
383       {
384         setActiveDocument(moduleDocument());
385       }
386     }
387   }
388 }
389
390 void Model_Session::LoadPluginsInfo()
391 {
392   if (myPluginsInfoLoaded)  // nothing to do
393     return;
394
395   // Read plugins information from XML files
396   Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
397   aModuleReader.readAll();
398   std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
399   std::set<std::string>::iterator it = aFiles.begin();
400   for ( ; it != aFiles.end(); it++ ) {
401     Config_ValidatorReader aValidatorReader (*it);
402     aValidatorReader.readAll();
403   };
404
405 }
406
407 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
408 {
409   myPluginObjs[myCurrentPluginName] = thePlugin;
410   static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
411   ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD);
412   Events_Loop::loop()->flush(EVENT_LOAD);
413   // If the plugin has an ability to process GUI events, register it
414   Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
415   if (aListener) {
416     Events_Loop* aLoop = Events_Loop::loop();
417     static Events_ID aStateRequestEventId =
418         Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
419     aLoop->registerListener(aListener, aStateRequestEventId);
420   }
421 }
422
423 ModelAPI_ValidatorsFactory* Model_Session::validators()
424 {
425   static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
426   return aFactory;
427 }
428
429 int Model_Session::transactionID()
430 {
431   return ROOT_DOC->transactionID();
432 }