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