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