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