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_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 #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>
36 static Model_Session* myImpl = new Model_Session();
38 // t oredirect all calls to the root document
39 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
41 bool Model_Session::load(const char* theFileName)
43 bool aRes = ROOT_DOC->load(theFileName, "root", ROOT_DOC);
47 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
49 return ROOT_DOC->save(theFileName, "root", theResults);
52 void Model_Session::closeAll()
54 Model_Application::getApplication()->deleteAllDocuments();
57 void Model_Session::startOperation(const std::string& theId, const bool theAttachedToNested)
59 myOperationAttachedToNext = theAttachedToNested;
60 ROOT_DOC->startOperation();
61 ROOT_DOC->operationId(theId);
62 static std::shared_ptr<Events_Message> aStartedMsg
63 (new Events_Message(Events_Loop::eventByName("StartOperation")));
64 Events_Loop::loop()->send(aStartedMsg);
65 // remove all useless documents that has been closed: on start of operation undo/redo is cleared
66 // MPV: this code is dangerous now because it may close the document that is activated right now
67 // but not in the list of the opened documents yet (create, delete, undo, activate Part)
68 // later this must be updated by correct usage of uniques IDs of documents, not names of results
69 //std::list<std::shared_ptr<ModelAPI_Document> > aUsedDocs = allOpenedDocuments();
70 //Model_Application::getApplication()->removeUselessDocuments(aUsedDocs);
73 void Model_Session::finishOperation()
75 setCheckTransactions(false);
76 ROOT_DOC->finishOperation();
77 if (myOperationAttachedToNext) { // twice, with nested
78 ROOT_DOC->finishOperation();
79 myOperationAttachedToNext = false;
81 setCheckTransactions(true);
84 void Model_Session::abortOperation()
86 setCheckTransactions(false);
87 ROOT_DOC->abortOperation();
88 if (myOperationAttachedToNext) { // twice, with nested
89 ROOT_DOC->abortOperation();
90 myOperationAttachedToNext = false;
92 setCheckTransactions(true);
93 // here the update mechanism may work after abort, so, supress the warnings about
94 // modifications outside of the transactions
95 bool aWasCheck = myCheckTransactions;
96 myCheckTransactions = false;
97 static std::shared_ptr<Events_Message> anAbortMsg
98 (new Events_Message(Events_Loop::eventByName("AbortOperation")));
99 Events_Loop::loop()->send(anAbortMsg);
100 myCheckTransactions = true;
101 myCheckTransactions = aWasCheck;
104 bool Model_Session::isOperation()
106 return ROOT_DOC->isOperation();
109 bool Model_Session::isModified()
111 return ROOT_DOC->isModified();
114 bool Model_Session::canUndo()
116 return ROOT_DOC->canUndo();
119 void Model_Session::undo()
121 setCheckTransactions(false);
123 setCheckTransactions(true);
126 bool Model_Session::canRedo()
128 return ROOT_DOC->canRedo();
131 void Model_Session::redo()
133 setCheckTransactions(false);
135 setCheckTransactions(true);
138 //! Returns stack of performed operations
139 std::list<std::string> Model_Session::undoList()
141 return ROOT_DOC->undoList();
143 //! Returns stack of rolled back operations
144 std::list<std::string> Model_Session::redoList()
146 return ROOT_DOC->redoList();
149 FeaturePtr Model_Session::createFeature(string theFeatureID, Model_Document* theDocOwner)
151 if (this != myImpl) {
152 return myImpl->createFeature(theFeatureID, theDocOwner);
155 // load all information about plugins, features and attributes
158 if (myPlugins.find(theFeatureID) != myPlugins.end()) {
159 std::pair<std::string, std::string>& aPlugin = myPlugins[theFeatureID]; // plugin and doc kind
160 if (!aPlugin.second.empty() && aPlugin.second != theDocOwner->kind()) {
161 Events_InfoMessage("Model_Session",
162 "Feature '%1' can be created only in document '%2' by the XML definition")
163 .arg(theFeatureID).arg(aPlugin.second).send();
166 myCurrentPluginName = aPlugin.first;
167 if (myPluginObjs.find(myCurrentPluginName) == myPluginObjs.end()) {
168 // load plugin library if not yet done
169 Config_ModuleReader::loadPlugin(myCurrentPluginName);
171 if (myPluginObjs.find(myCurrentPluginName) != myPluginObjs.end()) {
172 FeaturePtr aCreated = myPluginObjs[myCurrentPluginName]->createFeature(theFeatureID);
174 Events_InfoMessage("Model_Session",
175 "Can not initialize feature '%1' in plugin '%2'")
176 .arg(theFeatureID).arg(myCurrentPluginName).send();
180 Events_InfoMessage("Model_Session","Can not load plugin '%1'").arg(myCurrentPluginName).send();
183 Events_InfoMessage("Model_Session","Feature '%1' not found in any plugin").arg(theFeatureID).send();
186 return FeaturePtr(); // return nothing
189 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
191 Handle(Model_Application) anApp = Model_Application::getApplication();
192 bool aFirstCall = !anApp->hasRoot();
194 // to be sure that plugins are loaded, even before the first "createFeature" call (in unit tests)
196 // creation of the root document is always outside of the transaction, so, avoid checking it
197 setCheckTransactions(false);
198 anApp->createDocument(0); // 0 is a root ID
199 // creation of the root document is always outside of the transaction, so, avoid checking it
200 setCheckTransactions(true);
202 return anApp->rootDocument();
205 std::shared_ptr<ModelAPI_Document> Model_Session::document(int theDocID)
207 return std::shared_ptr<ModelAPI_Document>(
208 Model_Application::getApplication()->document(theDocID));
211 bool Model_Session::hasModuleDocument()
213 return Model_Application::getApplication()->hasRoot();
216 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
218 if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
219 myCurrentDoc = moduleDocument();
223 /// makes the last feature in the document as the current
224 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
226 FeaturePtr aLast = std::dynamic_pointer_cast<Model_Document>(theDoc)->lastFeature();
227 // if last is nested into something else, make this something else as last:
228 // otherwise it will look like edition of sub-element, so, the main will be disabled
230 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
233 aMain = ModelAPI_Tools::compositeOwner(aLast);
236 theDoc->setCurrentFeature(aLast, false);
240 void Model_Session::setActiveDocument(
241 std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
243 if (myCurrentDoc != theDoc) {
244 if (myCurrentDoc.get())
245 myCurrentDoc->setActive(false);
247 theDoc->setActive(true);
249 std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
250 myCurrentDoc = theDoc;
251 if (theDoc.get() && theSendSignal) {
252 // this must be before the synchronisation call because features in PartSet lower than this
253 // part feature must be disabled and don't recomputed anymore (issue 1156,
254 // translation feature is failed on activation of Part 2)
255 if (isOperation()) { // do it only in transaction, not on opening of document
256 DocumentPtr aRoot = moduleDocument();
257 if (myCurrentDoc != aRoot) {
258 FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
259 if (aPartFeat.get()) {
260 aRoot->setCurrentFeature(aPartFeat, false);
264 // syncronize the document: it may be just opened or opened but removed before
265 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
267 bool aWasChecked = myCheckTransactions;
268 setCheckTransactions(false);
269 TDF_LabelList anEmptyUpdated;
270 aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true);
272 setCheckTransactions(true);
274 static std::shared_ptr<Events_Message> aMsg(
275 new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
276 Events_Loop::loop()->send(aMsg);
278 // make the current state correct and synchronised in the module and sub-documents
279 if (isOperation()) { // do it only in transaction, not on opening of document
280 if (myCurrentDoc == moduleDocument()) {
281 // make the current feature the latest in root, in previous root current become also last
282 makeCurrentLast(aPrevious);
283 makeCurrentLast(myCurrentDoc);
285 // make the current feature the latest in sub, root current feature becomes this sub
286 makeCurrentLast(myCurrentDoc);
292 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
294 list<std::shared_ptr<ModelAPI_Document> > aResult;
295 aResult.push_back(moduleDocument());
296 // add subs recursively
297 list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
298 for(; aDoc != aResult.end(); aDoc++) {
299 DocumentPtr anAPIDoc = *aDoc;
300 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
302 const std::set<int> aSubs = aDoc->subDocuments();
303 std::set<int>::const_iterator aSubIter = aSubs.cbegin();
304 for(; aSubIter != aSubs.cend(); aSubIter++) {
305 aResult.push_back(Model_Application::getApplication()->document(*aSubIter));
312 bool Model_Session::isLoadByDemand(const std::string theDocID)
314 return Model_Application::getApplication()->isLoadByDemand(theDocID);
317 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
318 std::shared_ptr<ModelAPI_Document> theSource, const int theDestID)
320 std::shared_ptr<Model_Document> aNew = Model_Application::getApplication()->document(theDestID);
321 // make a copy of all labels
322 TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
324 TDF_Label aTargetRoot = aNew->document()->Main().Father();
325 Handle(TDF_DataSet) aDS = new TDF_DataSet;
326 aDS->AddLabel(aSourceRoot);
327 TDF_ClosureTool::Closure(aDS);
328 Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable;
329 aRT->SetRelocation(aSourceRoot, aTargetRoot);
330 TDF_CopyTool::Copy(aDS, aRT);
332 TDF_LabelList anEmptyUpdated;
333 aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true);
337 Model_Session::Model_Session()
339 myPluginsInfoLoaded = false;
340 myCheckTransactions = true;
341 myOperationAttachedToNext = false;
342 ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
343 // register the configuration reading listener
344 Events_Loop* aLoop = Events_Loop::loop();
345 static const Events_ID kFeatureEvent =
346 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
347 aLoop->registerListener(this, kFeatureEvent);
348 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
349 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
350 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
351 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
354 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
356 static const Events_ID kFeatureEvent =
357 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
358 static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
359 if (theMessage->eventID() == kFeatureEvent) {
360 const std::shared_ptr<Config_FeatureMessage> aMsg =
361 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
364 // std::cout << "Feature: " << aMsg->id() << std::endl;
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());
372 const std::shared_ptr<Config_AttributeMessage> aMsgAttr =
373 std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
376 // std::cout << "Feature: " << aMsgAttr->featureId()
377 // << ", Attribute: " << aMsgAttr->attributeId() << std::endl;
379 if (!aMsgAttr->isObligatory()) {
380 validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
382 std::cout << "F: " << aMsgAttr->featureId()
383 << ", V: Model_FeatureValidator"
384 << ", A: " << aMsgAttr->attributeId()
387 if(aMsgAttr->isConcealment()) {
388 validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
390 if (!aMsgAttr->caseId().empty()) {
391 validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(),
392 aMsgAttr->switchId(), aMsgAttr->caseId());
396 // plugins information was started to load, so, it will be loaded
397 myPluginsInfoLoaded = true;
398 } else if (theMessage->eventID() == kValidatorEvent) {
400 static bool done = false;
402 std::set<std::string> aPlugins;
403 for (auto it = myPlugins.begin(); it != myPlugins.end(); ++it) {
404 std::string aPluginName = it->second.first;
405 aPlugins.insert(aPluginName);
408 for (auto it = aPlugins.begin(); it != aPlugins.end(); ++it) {
409 myCurrentPluginName = *it;
410 Config_ModuleReader::loadPlugin(*it);
416 std::shared_ptr<Config_ValidatorMessage> aMsg =
417 std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
419 if (aMsg->attributeId().empty()) { // feature validator
421 std::cout << "F: " << aMsg->featureId()
422 << ", V: " << aMsg->validatorId() << std::endl;
424 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
425 } else { // attribute validator
427 std::cout << "F: " << aMsg->featureId()
428 << ", A: " << aMsg->attributeId()
429 << ", V: " << aMsg->validatorId() << std::endl;
431 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
435 } else { // create/update/delete
436 if (myCheckTransactions && !isOperation())
437 Events_InfoMessage("Model_Session", "Modification of data structure outside of the transaction").send();
438 // if part is deleted, make the root as the current document (on undo of Parts creations)
439 static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
440 if (theMessage->eventID() == kDeletedEvent) {
441 std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
442 std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
444 aDeleted->groups().find(ModelAPI_ResultPart::group()) != aDeleted->groups().end())
446 // check that the current feature of the session is still the active Part (even disabled)
448 FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
449 if (aCurrentPart.get()) {
450 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
451 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
452 for(; !aFound && aRes != aResList.end(); aRes++) {
453 ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
454 if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
460 if (!aFound) { // if not, the part was removed, so activate the module document
461 setActiveDocument(moduleDocument());
468 void Model_Session::LoadPluginsInfo()
470 if (myPluginsInfoLoaded) // nothing to do
473 // Read plugins information from XML files
474 Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
475 aModuleReader.readAll();
476 std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
477 std::set<std::string>::iterator it = aFiles.begin();
478 for ( ; it != aFiles.end(); it++ ) {
479 Config_ValidatorReader aValidatorReader (*it);
480 aValidatorReader.readAll();
485 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
487 myPluginObjs[myCurrentPluginName] = thePlugin;
488 static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
489 ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD);
490 Events_Loop::loop()->flush(EVENT_LOAD);
491 // If the plugin has an ability to process GUI events, register it
492 Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
494 Events_Loop* aLoop = Events_Loop::loop();
495 static Events_ID aStateRequestEventId =
496 Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
497 aLoop->registerListener(aListener, aStateRequestEventId);
501 ModelAPI_ValidatorsFactory* Model_Session::validators()
503 static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
507 int Model_Session::transactionID()
509 return ROOT_DOC->transactionID();