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