Salome HOME
Merge branch 'master' into cgt/devCEA
[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_InfoMessage.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
25 #include <ModelAPI_CompositeFeature.h>
26 #include <ModelAPI_ResultPart.h>
27 #include <ModelAPI_Tools.h>
28
29 #include <TDF_CopyTool.hxx>
30 #include <TDF_DataSet.hxx>
31 #include <TDF_RelocationTable.hxx>
32 #include <TDF_ClosureTool.hxx>
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", 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, "root", 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(std::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_InfoMessage("Model_Session",
160           "Feature '%1' can be created only in document '%2' by the XML definition")
161           .arg(theFeatureID).arg(aPlugin.second).send();
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_InfoMessage("Model_Session",
173             "Can not initialize feature '%1' in plugin '%2'")
174             .arg(theFeatureID).arg(myCurrentPluginName).send();
175       }
176       return aCreated;
177     } else {
178       Events_InfoMessage("Model_Session",
179         "Can not load plugin '%1'").arg(myCurrentPluginName).send();
180     }
181   } else {
182     Events_InfoMessage("Model_Session",
183       "Feature '%1' not found in any plugin").arg(theFeatureID).send();
184   }
185
186   return FeaturePtr();  // return nothing
187 }
188
189 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
190 {
191   Handle(Model_Application) anApp = Model_Application::getApplication();
192   bool aFirstCall = !anApp->hasRoot();
193   if (aFirstCall) {
194     // to be sure that plugins are loaded,
195     // even before the first "createFeature" call (in unit tests)
196
197     LoadPluginsInfo();
198     // creation of the root document is always outside of the transaction, so, avoid checking it
199     setCheckTransactions(false);
200     anApp->createDocument(0); // 0 is a root ID
201     // creation of the root document is always outside of the transaction, so, avoid checking it
202     setCheckTransactions(true);
203   }
204   return anApp->rootDocument();
205 }
206
207 std::shared_ptr<ModelAPI_Document> Model_Session::document(int theDocID)
208 {
209   return std::shared_ptr<ModelAPI_Document>(
210       Model_Application::getApplication()->document(theDocID));
211 }
212
213 bool Model_Session::hasModuleDocument()
214 {
215   return Model_Application::getApplication()->hasRoot();
216 }
217
218 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
219 {
220   if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
221     myCurrentDoc = moduleDocument();
222   return myCurrentDoc;
223 }
224
225 /// makes the last feature in the document as the current
226 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
227   if (theDoc.get()) {
228     FeaturePtr aLast = std::dynamic_pointer_cast<Model_Document>(theDoc)->lastFeature();
229     // if last is nested into something else, make this something else as last:
230     // otherwise it will look like edition of sub-element, so, the main will be disabled
231     if (aLast.get()) {
232       CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
233       while(aMain.get()) {
234         aLast = aMain;
235         aMain = ModelAPI_Tools::compositeOwner(aLast);
236       }
237     }
238     theDoc->setCurrentFeature(aLast, false);
239   }
240 }
241
242 void Model_Session::setActiveDocument(
243   std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
244 {
245   if (myCurrentDoc != theDoc) {
246     if (myCurrentDoc.get())
247       myCurrentDoc->setActive(false);
248     if (theDoc.get())
249       theDoc->setActive(true);
250
251     std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
252     myCurrentDoc = theDoc;
253     if (theDoc.get() && theSendSignal) {
254       // this must be before the synchronisation call because features in PartSet lower than this
255       // part feature must be disabled and don't recomputed anymore (issue 1156,
256       // translation feature is failed on activation of Part 2)
257       if (isOperation()) { // do it only in transaction, not on opening of document
258         DocumentPtr aRoot = moduleDocument();
259         if (myCurrentDoc != aRoot) {
260           FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
261           if (aPartFeat.get()) {
262             aRoot->setCurrentFeature(aPartFeat, false);
263           }
264         }
265       }
266       // syncronize the document: it may be just opened or opened but removed before
267       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
268       if (aDoc.get()) {
269         bool aWasChecked = myCheckTransactions;
270         setCheckTransactions(false);
271         TDF_LabelList anEmptyUpdated;
272         aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true, false, true);
273         if (aWasChecked)
274             setCheckTransactions(true);
275       }
276       static std::shared_ptr<Events_Message> aMsg(
277           new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
278       Events_Loop::loop()->send(aMsg);
279     }
280     // make the current state correct and synchronised in the module and sub-documents
281     if (isOperation()) { // do it only in transaction, not on opening of document
282       if (myCurrentDoc == moduleDocument()) {
283         // make the current feature the latest in root, in previous root current become also last
284         makeCurrentLast(aPrevious);
285         makeCurrentLast(myCurrentDoc);
286       } else {
287         // make the current feature the latest in sub, root current feature becomes this sub
288         makeCurrentLast(myCurrentDoc);
289       }
290     }
291   }
292 }
293
294 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
295 {
296   std::list<std::shared_ptr<ModelAPI_Document> > aResult;
297   aResult.push_back(moduleDocument());
298   // add subs recursively
299   std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
300   for(; aDoc != aResult.end(); aDoc++) {
301     DocumentPtr anAPIDoc = *aDoc;
302     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
303     if (aDoc) {
304       const std::set<int> aSubs = aDoc->subDocuments();
305       std::set<int>::const_iterator aSubIter = aSubs.cbegin();
306       for(; aSubIter != aSubs.cend(); aSubIter++) {
307         aResult.push_back(Model_Application::getApplication()->document(*aSubIter));
308       }
309     }
310   }
311   return aResult;
312 }
313
314 bool Model_Session::isLoadByDemand(const std::string theDocID)
315 {
316   return Model_Application::getApplication()->isLoadByDemand(theDocID);
317 }
318
319 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
320     std::shared_ptr<ModelAPI_Document> theSource, const int theDestID)
321 {
322   std::shared_ptr<Model_Document> aNew = Model_Application::getApplication()->document(theDestID);
323   // make a copy of all labels
324   TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
325       .Father();
326   TDF_Label aTargetRoot = aNew->document()->Main().Father();
327   Handle(TDF_DataSet) aDS = new TDF_DataSet;
328   aDS->AddLabel(aSourceRoot);
329   TDF_ClosureTool::Closure(aDS);
330   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable(Standard_True);
331   aRT->SetRelocation(aSourceRoot, aTargetRoot);
332   TDF_CopyTool::Copy(aDS, aRT);
333
334   TDF_LabelList anEmptyUpdated;
335   aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true, true);
336   return aNew;
337 }
338
339 Model_Session::Model_Session()
340 {
341   myPluginsInfoLoaded = false;
342   myCheckTransactions = true;
343   myOperationAttachedToNext = false;
344   ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
345   // register the configuration reading listener
346   Events_Loop* aLoop = Events_Loop::loop();
347   static const Events_ID kFeatureEvent =
348     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
349   aLoop->registerListener(this, kFeatureEvent);
350   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
351   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
352   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
353   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
354 }
355
356 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
357 {
358   static const Events_ID kFeatureEvent =
359     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
360   static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
361   if (theMessage->eventID() == kFeatureEvent) {
362     const std::shared_ptr<Config_FeatureMessage> aMsg =
363       std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
364     if (aMsg) {
365
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
376         if (!aMsgAttr->isObligatory()) {
377           validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
378         }
379         if(aMsgAttr->isConcealment()) {
380           validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
381         }
382         const std::list<std::pair<std::string, std::string> >& aCases = aMsgAttr->getCases();
383         if (!aCases.empty()) {
384           validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(), aCases);
385         }
386       }
387     }
388     // plugins information was started to load, so, it will be loaded
389     myPluginsInfoLoaded = true;
390   } else if (theMessage->eventID() == kValidatorEvent) {
391     std::shared_ptr<Config_ValidatorMessage> aMsg =
392       std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
393     if (aMsg) {
394       if (aMsg->attributeId().empty()) {  // feature validator
395         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
396       } else {  // attribute validator
397         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
398                                       aMsg->parameters());
399       }
400     }
401   } else {  // create/update/delete
402     if (myCheckTransactions && !isOperation())
403       Events_InfoMessage("Model_Session",
404         "Modification of data structure outside of the transaction").send();
405     // if part is deleted, make the root as the current document (on undo of Parts creations)
406     static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
407     if (theMessage->eventID() == kDeletedEvent) {
408       std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
409         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
410       if (aDeleted &&
411           aDeleted->groups().find(ModelAPI_ResultPart::group()) != aDeleted->groups().end())
412       {
413          // check that the current feature of the session is still the active Part (even disabled)
414         bool aFound = false;
415         FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
416         if (aCurrentPart.get()) {
417           const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
418           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
419           for(; !aFound && aRes != aResList.end(); aRes++) {
420             ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
421             if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
422               aFound = true;
423
424             }
425           }
426         }
427         if (!aFound) { // if not, the part was removed, so activate the module document
428           if (myCurrentDoc.get())
429             setActiveDocument(moduleDocument());
430         }
431       }
432     }
433   }
434 }
435
436 void Model_Session::LoadPluginsInfo()
437 {
438   if (myPluginsInfoLoaded)  // nothing to do
439     return;
440   // Read plugins information from XML files
441   Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
442   aModuleReader.readAll();
443   std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
444   std::set<std::string>::iterator it = aFiles.begin();
445   for ( ; it != aFiles.end(); it++ ) {
446     Config_ValidatorReader aValidatorReader (*it);
447     aValidatorReader.readAll();
448   };
449
450 }
451
452 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
453 {
454   myPluginObjs[myCurrentPluginName] = thePlugin;
455   static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
456   ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD);
457   Events_Loop::loop()->flush(EVENT_LOAD);
458   // If the plugin has an ability to process GUI events, register it
459   Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
460   if (aListener) {
461     Events_Loop* aLoop = Events_Loop::loop();
462     static Events_ID aStateRequestEventId =
463         Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
464     aLoop->registerListener(aListener, aStateRequestEventId);
465   }
466 }
467
468 ModelAPI_ValidatorsFactory* Model_Session::validators()
469 {
470   static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
471   return aFactory;
472 }
473
474 int Model_Session::transactionID()
475 {
476   return ROOT_DOC->transactionID();
477 }