1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Session.cxx
4 // Created: 20 Mar 2014
5 // Author: Mikhail PONIKAROV
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>
27 #include <TDF_CopyTool.hxx>
28 #include <TDF_DataSet.hxx>
29 #include <TDF_RelocationTable.hxx>
30 #include <TDF_ClosureTool.hxx>
34 static Model_Session* myImpl = new Model_Session();
36 // t oredirect all calls to the root document
37 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
39 bool Model_Session::load(const char* theFileName)
41 bool aRes = ROOT_DOC->load(theFileName, ROOT_DOC);
45 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
47 return ROOT_DOC->save(theFileName, theResults);
50 void Model_Session::closeAll()
52 Model_Application::getApplication()->deleteAllDocuments();
55 void Model_Session::startOperation(const std::string& theId, const bool theAttachedToNested)
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);
71 void Model_Session::finishOperation()
73 setCheckTransactions(false);
74 ROOT_DOC->finishOperation();
75 if (myOperationAttachedToNext) { // twice, with nested
76 ROOT_DOC->finishOperation();
77 myOperationAttachedToNext = false;
79 setCheckTransactions(true);
82 void Model_Session::abortOperation()
84 setCheckTransactions(false);
85 ROOT_DOC->abortOperation();
86 if (myOperationAttachedToNext) { // twice, with nested
87 ROOT_DOC->abortOperation();
88 myOperationAttachedToNext = false;
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;
102 bool Model_Session::isOperation()
104 return ROOT_DOC->isOperation();
107 bool Model_Session::isModified()
109 return ROOT_DOC->isModified();
112 bool Model_Session::canUndo()
114 return ROOT_DOC->canUndo();
117 void Model_Session::undo()
119 setCheckTransactions(false);
121 setCheckTransactions(true);
124 bool Model_Session::canRedo()
126 return ROOT_DOC->canRedo();
129 void Model_Session::redo()
131 setCheckTransactions(false);
133 setCheckTransactions(true);
136 //! Returns stack of performed operations
137 std::list<std::string> Model_Session::undoList()
139 return ROOT_DOC->undoList();
141 //! Returns stack of rolled back operations
142 std::list<std::string> Model_Session::redoList()
144 return ROOT_DOC->redoList();
147 FeaturePtr Model_Session::createFeature(string theFeatureID, Model_Document* theDocOwner)
149 if (this != myImpl) {
150 return myImpl->createFeature(theFeatureID, theDocOwner);
153 // load all information about plugins, features and attributes
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()) {
160 string("Feature '") + theFeatureID + "' can be created only in document '"
161 + aPlugin.second + "' by the XML definition");
164 myCurrentPluginName = aPlugin.first;
165 if (myPluginObjs.find(myCurrentPluginName) == myPluginObjs.end()) {
166 // load plugin library if not yet done
167 Config_ModuleReader::loadPlugin(myCurrentPluginName);
169 if (myPluginObjs.find(myCurrentPluginName) != myPluginObjs.end()) {
170 FeaturePtr aCreated = myPluginObjs[myCurrentPluginName]->createFeature(theFeatureID);
173 string("Can not initialize feature '") + theFeatureID + "' in plugin '"
174 + myCurrentPluginName + "'");
178 Events_Error::send(string("Can not load plugin '") + myCurrentPluginName + "'");
181 Events_Error::send(string("Feature '") + theFeatureID + "' not found in any plugin");
184 return FeaturePtr(); // return nothing
187 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
189 bool aFirstCall = !Model_Application::getApplication()->hasDocument("root");
191 // creation of the root document is always outside of the transaction, so, avoid checking it
192 setCheckTransactions(false);
194 std::shared_ptr<ModelAPI_Document> aDoc = std::shared_ptr<ModelAPI_Document>(
195 Model_Application::getApplication()->getDocument("root"));
197 // creation of the root document is always outside of the transaction, so, avoid checking it
198 setCheckTransactions(true);
203 std::shared_ptr<ModelAPI_Document> Model_Session::document(std::string theDocID)
205 return std::shared_ptr<ModelAPI_Document>(
206 Model_Application::getApplication()->getDocument(theDocID));
209 bool Model_Session::hasModuleDocument()
211 return Model_Application::getApplication()->hasDocument("root");
214 bool Model_Session::hasDocument(std::string theDocID)
216 return Model_Application::getApplication()->hasDocument(theDocID);
219 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
221 if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
222 myCurrentDoc = moduleDocument();
226 /// makes the last feature in the document as the current
227 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
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
233 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
236 aMain = ModelAPI_Tools::compositeOwner(aLast);
239 theDoc->setCurrentFeature(aLast, false);
243 void Model_Session::setActiveDocument(
244 std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
246 if (myCurrentDoc != theDoc) {
247 if (myCurrentDoc.get())
248 myCurrentDoc->setActive(false);
250 theDoc->setActive(true);
252 std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
253 myCurrentDoc = theDoc;
254 if (theDoc.get() && theSendSignal) {
255 // this must be before the synchronisation call because features in PartSet lower than this
256 // part feature must be disabled and don't recomputed anymore (issue 1156,
257 // translation feature is failed on activation of Part 2)
258 if (isOperation()) { // do it only in transaction, not on opening of document
259 DocumentPtr aRoot = moduleDocument();
260 if (myCurrentDoc != aRoot) {
261 FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
262 if (aPartFeat.get()) {
263 aRoot->setCurrentFeature(aPartFeat, false);
267 // syncronize the document: it may be just opened or opened but removed before
268 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
270 bool aWasChecked = myCheckTransactions;
271 setCheckTransactions(false);
272 TDF_LabelList anEmptyUpdated;
273 aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true);
275 setCheckTransactions(true);
277 static std::shared_ptr<Events_Message> aMsg(
278 new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
279 Events_Loop::loop()->send(aMsg);
281 // make the current state correct and synchronised in the module and sub-documents
282 if (isOperation()) { // do it only in transaction, not on opening of document
283 if (myCurrentDoc == moduleDocument()) {
284 // make the current feature the latest in root, in previous root current become also last
285 makeCurrentLast(aPrevious);
286 makeCurrentLast(myCurrentDoc);
288 // make the current feature the latest in sub, root current feature becomes this sub
289 makeCurrentLast(myCurrentDoc);
295 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
297 list<std::shared_ptr<ModelAPI_Document> > aResult;
298 aResult.push_back(moduleDocument());
299 // add subs recursively
300 list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
301 for(; aDoc != aResult.end(); aDoc++) {
302 DocumentPtr anAPIDoc = *aDoc;
303 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
305 const std::set<std::string> aSubs = aDoc->subDocuments(true);
306 std::set<std::string>::const_iterator aSubIter = aSubs.cbegin();
307 for(; aSubIter != aSubs.cend(); aSubIter++) {
308 if (!Model_Application::getApplication()->isLoadByDemand(*aSubIter)) {
309 aResult.push_back(Model_Application::getApplication()->getDocument(*aSubIter));
317 bool Model_Session::isLoadByDemand(const std::string theDocID)
319 return Model_Application::getApplication()->isLoadByDemand(theDocID);
322 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
323 std::shared_ptr<ModelAPI_Document> theSource, std::string theID)
325 // create a new document
326 std::shared_ptr<Model_Document> aNew = std::dynamic_pointer_cast<Model_Document>(
327 Model_Application::getApplication()->getDocument(theID));
328 // make a copy of all labels
329 TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
331 TDF_Label aTargetRoot = aNew->document()->Main().Father();
332 Handle(TDF_DataSet) aDS = new TDF_DataSet;
333 aDS->AddLabel(aSourceRoot);
334 TDF_ClosureTool::Closure(aDS);
335 Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable;
336 aRT->SetRelocation(aSourceRoot, aTargetRoot);
337 TDF_CopyTool::Copy(aDS, aRT);
339 TDF_LabelList anEmptyUpdated;
340 aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true);
344 Model_Session::Model_Session()
346 myPluginsInfoLoaded = false;
347 myCheckTransactions = true;
348 myOperationAttachedToNext = false;
349 ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
350 // register the configuration reading listener
351 Events_Loop* aLoop = Events_Loop::loop();
352 static const Events_ID kFeatureEvent =
353 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
354 aLoop->registerListener(this, kFeatureEvent);
355 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
356 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
357 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
358 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
361 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
363 static const Events_ID kFeatureEvent =
364 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
365 static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
366 if (theMessage->eventID() == kFeatureEvent) {
367 const std::shared_ptr<Config_FeatureMessage> aMsg =
368 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
370 // process the plugin info, load plugin
371 if (myPlugins.find(aMsg->id()) == myPlugins.end()) {
372 myPlugins[aMsg->id()] = std::pair<std::string, std::string>(
373 aMsg->pluginLibrary(), aMsg->documentKind());
376 const std::shared_ptr<Config_AttributeMessage> aMsgAttr =
377 std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
379 if (!aMsgAttr->isObligatory()) {
380 validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
382 if(aMsgAttr->isConcealment()) {
383 validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
385 if (!aMsgAttr->caseId().empty()) {
386 validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(),
387 aMsgAttr->switchId(), aMsgAttr->caseId());
391 // plugins information was started to load, so, it will be loaded
392 myPluginsInfoLoaded = true;
393 } else if (theMessage->eventID() == kValidatorEvent) {
394 std::shared_ptr<Config_ValidatorMessage> aMsg =
395 std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
397 if (aMsg->attributeId().empty()) { // feature validator
398 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
399 } else { // attribute validator
400 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
404 } else { // create/update/delete
405 if (myCheckTransactions && !isOperation())
406 Events_Error::send("Modification of data structure outside of the transaction");
407 // if part is deleted, make the root as the current document (on undo of Parts creations)
408 static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
409 if (theMessage->eventID() == kDeletedEvent) {
410 std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
411 std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
413 aDeleted->groups().find(ModelAPI_ResultPart::group()) != aDeleted->groups().end())
415 // check that the current feature of the session is still the active Part (even disabled)
417 FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
418 if (aCurrentPart.get()) {
419 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
420 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
421 for(; !aFound && aRes != aResList.end(); aRes++) {
422 ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
423 if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
429 if (!aFound) { // if not, the part was removed, so activate the module document
430 setActiveDocument(moduleDocument());
437 void Model_Session::LoadPluginsInfo()
439 if (myPluginsInfoLoaded) // nothing to do
442 // Read plugins information from XML files
443 Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
444 aModuleReader.readAll();
445 std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
446 std::set<std::string>::iterator it = aFiles.begin();
447 for ( ; it != aFiles.end(); it++ ) {
448 Config_ValidatorReader aValidatorReader (*it);
449 aValidatorReader.readAll();
454 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
456 myPluginObjs[myCurrentPluginName] = thePlugin;
457 static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
458 ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD);
459 Events_Loop::loop()->flush(EVENT_LOAD);
460 // If the plugin has an ability to process GUI events, register it
461 Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
463 Events_Loop* aLoop = Events_Loop::loop();
464 static Events_ID aStateRequestEventId =
465 Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
466 aLoop->registerListener(aListener, aStateRequestEventId);
470 ModelAPI_ValidatorsFactory* Model_Session::validators()
472 static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
476 int Model_Session::transactionID()
478 return ROOT_DOC->transactionID();