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