1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include <Model_Session.h>
22 #include <ModelAPI_Feature.h>
23 #include <ModelAPI_Plugin.h>
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <Model_Objects.h>
27 #include <Model_Application.h>
28 #include <Model_Events.h>
29 #include <Model_Validator.h>
30 #include <ModelAPI_Events.h>
31 #include <Events_Loop.h>
32 #include <Events_InfoMessage.h>
33 #include <Config_FeatureMessage.h>
34 #include <Config_AttributeMessage.h>
35 #include <Config_ValidatorMessage.h>
36 #include <Config_ModuleReader.h>
37 #include <Config_ValidatorReader.h>
38 #include <Config_PluginMessage.h>
40 #include <ModelAPI_CompositeFeature.h>
41 #include <ModelAPI_ResultPart.h>
42 #include <ModelAPI_Tools.h>
44 #include <TDF_ChildIDIterator.hxx>
45 #include <TDF_CopyTool.hxx>
46 #include <TDF_DataSet.hxx>
47 #include <TDF_RelocationTable.hxx>
48 #include <TDF_ClosureTool.hxx>
50 #include <TNaming_Builder.hxx>
51 #include <TNaming_Iterator.hxx>
52 #include <TNaming_NamedShape.hxx>
54 #include <TopoDS_Shape.hxx>
56 static Model_Session* myImpl = new Model_Session();
58 // t oredirect all calls to the root document
59 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
61 bool Model_Session::load(const char* theFileName)
63 bool aRes = ROOT_DOC->load(theFileName, "root", ROOT_DOC);
67 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
69 return ROOT_DOC->save(theFileName, "root", theResults);
72 void Model_Session::closeAll()
74 Model_Application::getApplication()->deleteAllDocuments();
77 void Model_Session::startOperation(const std::string& theId, const bool theAttachedToNested)
79 myOperationAttachedToNext = theAttachedToNested;
80 ROOT_DOC->startOperation();
81 ROOT_DOC->operationId(theId);
82 static std::shared_ptr<Events_Message> aStartedMsg
83 (new Events_Message(Events_Loop::eventByName("StartOperation")));
84 Events_Loop::loop()->send(aStartedMsg);
85 // remove all useless documents that has been closed: on start of operation undo/redo is cleared
86 // MPV: this code is dangerous now because it may close the document that is activated right now
87 // but not in the list of the opened documents yet (create, delete, undo, activate Part)
88 // later this must be updated by correct usage of uniques IDs of documents, not names of results
89 //std::list<std::shared_ptr<ModelAPI_Document> > aUsedDocs = allOpenedDocuments();
90 //Model_Application::getApplication()->removeUselessDocuments(aUsedDocs);
93 void Model_Session::finishOperation()
95 setCheckTransactions(false);
96 ROOT_DOC->finishOperation();
97 if (myOperationAttachedToNext) { // twice, with nested
98 ROOT_DOC->finishOperation();
99 myOperationAttachedToNext = false;
101 setCheckTransactions(true);
104 void Model_Session::abortOperation()
106 setCheckTransactions(false);
107 ROOT_DOC->abortOperation();
108 if (myOperationAttachedToNext) { // twice, with nested
109 ROOT_DOC->abortOperation();
110 myOperationAttachedToNext = false;
112 setCheckTransactions(true);
113 // here the update mechanism may work after abort, so, supress the warnings about
114 // modifications outside of the transactions
115 bool aWasCheck = myCheckTransactions;
116 myCheckTransactions = false;
117 static std::shared_ptr<Events_Message> anAbortMsg
118 (new Events_Message(Events_Loop::eventByName("AbortOperation")));
119 Events_Loop::loop()->send(anAbortMsg);
120 myCheckTransactions = true;
121 myCheckTransactions = aWasCheck;
124 bool Model_Session::isOperation()
126 return ROOT_DOC->isOperation();
129 bool Model_Session::isModified()
131 return ROOT_DOC->isModified();
134 bool Model_Session::canUndo()
136 return ROOT_DOC->canUndo();
139 void Model_Session::undo()
141 setCheckTransactions(false);
143 setCheckTransactions(true);
146 bool Model_Session::canRedo()
148 return ROOT_DOC->canRedo();
151 void Model_Session::redo()
153 setCheckTransactions(false);
155 setCheckTransactions(true);
158 //! Returns stack of performed operations
159 std::list<std::string> Model_Session::undoList()
161 return ROOT_DOC->undoList();
163 //! Returns stack of rolled back operations
164 std::list<std::string> Model_Session::redoList()
166 return ROOT_DOC->redoList();
169 ModelAPI_Plugin* Model_Session::getPlugin(const std::string& thePluginName)
171 if (myPluginObjs.find(thePluginName) == myPluginObjs.end()) {
172 // before load the used plugins
173 if (myUsePlugins.find(thePluginName) != myUsePlugins.end()) {
174 std::string aUse = myUsePlugins[thePluginName];
175 std::stringstream aUseStream(aUse);
176 std::string aPluginName;
177 while (std::getline(aUseStream, aPluginName, ',')) {
178 if (myPluginObjs.find(aPluginName) == myPluginObjs.end())
179 getPlugin(aPluginName);
182 // load plugin library if not yet done
183 Config_ModuleReader::loadPlugin(thePluginName);
185 if (myPluginObjs.find(thePluginName) == myPluginObjs.end()) {
186 Events_InfoMessage("Model_Session", "Can not load plugin '%1'").arg(thePluginName).send();
189 return myPluginObjs[thePluginName];
192 FeaturePtr Model_Session::createFeature(std::string theFeatureID, Model_Document* theDocOwner)
194 if (this != myImpl) {
195 return myImpl->createFeature(theFeatureID, theDocOwner);
198 // load all information about plugins, features and attributes
201 if (myPlugins.find(theFeatureID) != myPlugins.end()) {
202 std::pair<std::string, std::string>& aPlugin = myPlugins[theFeatureID]; // plugin and doc kind
203 if (!aPlugin.second.empty() && aPlugin.second != theDocOwner->kind()) {
204 Events_InfoMessage("Model_Session",
205 "Feature '%1' can be created only in document '%2' by the XML definition")
206 .arg(theFeatureID).arg(aPlugin.second).send();
209 ModelAPI_Plugin* aPluginObj = getPlugin(aPlugin.first);
211 FeaturePtr aCreated = aPluginObj->createFeature(theFeatureID);
213 Events_InfoMessage("Model_Session", "Can not initialize feature '%1' in plugin '%2'")
214 .arg(theFeatureID).arg(aPlugin.first).send();
218 Events_InfoMessage("Model_Session", "Can not load plugin '%1'").arg(aPlugin.first).send();
221 Events_InfoMessage("Model_Session",
222 "Feature '%1' not found in any plugin").arg(theFeatureID).send();
225 return FeaturePtr(); // return nothing
228 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
230 Handle(Model_Application) anApp = Model_Application::getApplication();
231 bool aFirstCall = !anApp->hasRoot();
233 // to be sure that plugins are loaded,
234 // even before the first "createFeature" call (in unit tests)
237 // creation of the root document is always outside of the transaction, so, avoid checking it
238 setCheckTransactions(false);
239 anApp->createDocument(0); // 0 is a root ID
240 // creation of the root document is always outside of the transaction, so, avoid checking it
241 setCheckTransactions(true);
243 return anApp->rootDocument();
246 std::shared_ptr<ModelAPI_Document> Model_Session::document(int theDocID)
248 return std::shared_ptr<ModelAPI_Document>(
249 Model_Application::getApplication()->document(theDocID));
252 bool Model_Session::hasModuleDocument()
254 return Model_Application::getApplication()->hasRoot();
257 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
259 if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id()))
260 myCurrentDoc = moduleDocument();
264 /// makes the last feature in the document as the current
265 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
267 FeaturePtr aLast = std::dynamic_pointer_cast<Model_Document>(theDoc)->lastFeature();
268 // if last is nested into something else, make this something else as last:
269 // otherwise it will look like edition of sub-element, so, the main will be disabled
271 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
274 aMain = ModelAPI_Tools::compositeOwner(aLast);
277 theDoc->setCurrentFeature(aLast, false);
281 void Model_Session::setActiveDocument(
282 std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
284 if (myCurrentDoc != theDoc) {
285 if (myCurrentDoc.get())
286 myCurrentDoc->setActive(false);
288 theDoc->setActive(true);
290 std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
291 myCurrentDoc = theDoc;
292 if (theDoc.get() && theSendSignal) {
293 // this must be before the synchronisation call because features in PartSet lower than this
294 // part feature must be disabled and don't recomputed anymore (issue 1156,
295 // translation feature is failed on activation of Part 2)
296 if (isOperation()) { // do it only in transaction, not on opening of document
297 DocumentPtr aRoot = moduleDocument();
298 if (myCurrentDoc != aRoot) {
299 FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
300 if (aPartFeat.get()) {
301 aRoot->setCurrentFeature(aPartFeat, false);
305 // syncronize the document: it may be just opened or opened but removed before
306 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
308 bool aWasChecked = myCheckTransactions;
309 setCheckTransactions(false);
310 TDF_LabelList anEmptyUpdated;
311 aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true, false, true);
313 setCheckTransactions(true);
315 static std::shared_ptr<Events_Message> aMsg(
316 new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
317 Events_Loop::loop()->send(aMsg);
319 // make the current state correct and synchronised in the module and sub-documents
320 if (isOperation()) { // do it only in transaction, not on opening of document
321 if (myCurrentDoc == moduleDocument()) {
322 // make the current feature the latest in root, in previous root current become also last
323 makeCurrentLast(aPrevious);
324 makeCurrentLast(myCurrentDoc);
326 // make the current feature the latest in sub, root current feature becomes this sub
327 makeCurrentLast(myCurrentDoc);
333 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
335 std::list<std::shared_ptr<ModelAPI_Document> > aResult;
336 aResult.push_back(moduleDocument());
337 // add subs recursively
338 std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDoc = aResult.begin();
339 for(; aDoc != aResult.end(); aDoc++) {
340 DocumentPtr anAPIDoc = *aDoc;
341 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
343 const std::set<int> aSubs = aDoc->subDocuments();
344 std::set<int>::const_iterator aSubIter = aSubs.cbegin();
345 for(; aSubIter != aSubs.cend(); aSubIter++) {
346 aResult.push_back(Model_Application::getApplication()->document(*aSubIter));
353 bool Model_Session::isLoadByDemand(const std::string theDocID, const int theDocIndex)
355 return Model_Application::getApplication()->isLoadByDemand(theDocID, theDocIndex);
358 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
359 std::shared_ptr<ModelAPI_Document> theSource, const int theDestID)
361 std::shared_ptr<Model_Document> aNew = Model_Application::getApplication()->document(theDestID);
362 // make a copy of all labels
363 TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
365 TDF_Label aTargetRoot = aNew->document()->Main().Father();
366 Handle(TDF_DataSet) aDS = new TDF_DataSet;
367 aDS->AddLabel(aSourceRoot);
368 TDF_ClosureTool::Closure(aDS);
369 Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable(Standard_True);
370 aRT->SetRelocation(aSourceRoot, aTargetRoot);
371 TDF_CopyTool::Copy(aDS, aRT);
373 // TODO: remove after fix in OCCT.
374 // All named shapes are stored in reversed order, so to fix this we reverse them back.
375 for(TDF_ChildIDIterator aChildIter(aTargetRoot, TNaming_NamedShape::GetID(), true);
378 Handle(TNaming_NamedShape) aNamedShape =
379 Handle(TNaming_NamedShape)::DownCast(aChildIter.Value());
380 if (aNamedShape.IsNull()) {
384 TopoDS_Shape aShape = aNamedShape->Get();
385 if(aShape.IsNull() || aShape.ShapeType() != TopAbs_COMPOUND) {
389 TNaming_Evolution anEvol = aNamedShape->Evolution();
390 std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
391 for(TNaming_Iterator anIter(aNamedShape); anIter.More(); anIter.Next()) {
392 aShapePairs.push_back(
393 std::pair<TopoDS_Shape, TopoDS_Shape>(anIter.OldShape(), anIter.NewShape()));
396 // Add in reverse order.
397 TDF_Label aLabel = aNamedShape->Label();
398 TNaming_Builder aBuilder(aLabel);
399 for(std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter =
401 aPairsIter != aShapePairs.end();
403 if (anEvol == TNaming_GENERATED) {
404 aBuilder.Generated(aPairsIter->first, aPairsIter->second);
405 } else if (anEvol == TNaming_MODIFY) {
406 aBuilder.Modify(aPairsIter->first, aPairsIter->second);
407 } else if (anEvol == TNaming_DELETE) {
408 aBuilder.Delete(aPairsIter->first);
409 } else if (anEvol == TNaming_PRIMITIVE) {
410 aBuilder.Generated(aPairsIter->second);
411 } else if (anEvol == TNaming_SELECTED) {
412 aBuilder.Select(aPairsIter->second, aPairsIter->first);
417 TDF_LabelList anEmptyUpdated;
418 aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true, true);
422 Model_Session::Model_Session()
424 myPluginsInfoLoaded = false;
425 myCheckTransactions = true;
426 myOperationAttachedToNext = false;
427 myIsAutoUpdateBlocked = false;
428 ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
429 // register the configuration reading listener
430 Events_Loop* aLoop = Events_Loop::loop();
431 static const Events_ID kFeatureEvent =
432 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
433 aLoop->registerListener(this, kFeatureEvent);
434 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
435 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
436 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
437 aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
438 aLoop->registerListener(this, Events_Loop::eventByName(Config_PluginMessage::EVENT_ID()));
441 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
443 static const Events_ID kFeatureEvent =
444 Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
445 static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
446 static const Events_ID kPluginEvent = Events_Loop::eventByName(Config_PluginMessage::EVENT_ID());
447 if (theMessage->eventID() == kFeatureEvent) {
448 const std::shared_ptr<Config_FeatureMessage> aMsg =
449 std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
452 // process the plugin info, load plugin
453 if (myPlugins.find(aMsg->id()) == myPlugins.end()) {
454 myPlugins[aMsg->id()] = std::pair<std::string, std::string>(
455 aMsg->pluginLibrary(), aMsg->documentKind());
458 const std::shared_ptr<Config_AttributeMessage> aMsgAttr =
459 std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
462 if (!aMsgAttr->isObligatory()) {
463 validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
465 if(aMsgAttr->isConcealment()) {
466 validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
468 if(aMsgAttr->isMainArgument()) {
469 validators()->registerMainArgument(aMsgAttr->featureId(), aMsgAttr->attributeId());
471 const std::list<std::pair<std::string, std::string> >& aCases = aMsgAttr->getCases();
472 if (!aCases.empty()) {
473 validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(), aCases);
477 // plugins information was started to load, so, it will be loaded
478 myPluginsInfoLoaded = true;
479 } else if (theMessage->eventID() == kValidatorEvent) {
480 std::shared_ptr<Config_ValidatorMessage> aMsg =
481 std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
483 if (aMsg->attributeId().empty()) { // feature validator
484 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
485 } else { // attribute validator
486 validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
490 } else if (theMessage->eventID() == kPluginEvent) { // plugin is started to load
491 std::shared_ptr<Config_PluginMessage> aMsg =
492 std::dynamic_pointer_cast<Config_PluginMessage>(theMessage);
494 myCurrentPluginName = aMsg->pluginId();
495 if (!aMsg->uses().empty()) {
496 myUsePlugins[myCurrentPluginName] = aMsg->uses();
499 } else { // create/update/delete
500 if (myCheckTransactions && !isOperation())
501 Events_InfoMessage("Model_Session",
502 "Modification of data structure outside of the transaction").send();
503 // if part is deleted, make the root as the current document (on undo of Parts creations)
504 static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
505 if (theMessage->eventID() == kDeletedEvent) {
506 std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
507 std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
509 std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator
510 aGIter = aDeleted->groups().cbegin();
511 for (; aGIter != aDeleted->groups().cend(); aGIter++) {
512 if (aGIter->second == ModelAPI_ResultPart::group())
515 if (aGIter != aDeleted->groups().cend())
517 // check that the current feature of the session is still the active Part (even disabled)
519 FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
520 if (aCurrentPart.get()) {
521 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
522 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
523 for(; !aFound && aRes != aResList.end(); aRes++) {
524 ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
525 if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
531 if (!aFound) { // if not, the part was removed, so activate the module document
532 if (myCurrentDoc.get())
533 setActiveDocument(moduleDocument());
540 void Model_Session::LoadPluginsInfo()
542 if (myPluginsInfoLoaded) // nothing to do
544 // Read plugins information from XML files
545 Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
546 aModuleReader.readAll();
547 std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
548 std::set<std::string>::iterator it = aFiles.begin();
549 for ( ; it != aFiles.end(); it++ ) {
550 Config_ValidatorReader aValidatorReader (*it);
551 aValidatorReader.readAll();
556 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
558 myPluginObjs[myCurrentPluginName] = thePlugin;
559 static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
560 ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD, false);
561 // If the plugin has an ability to process GUI events, register it
562 Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
564 Events_Loop* aLoop = Events_Loop::loop();
565 static Events_ID aStateRequestEventId =
566 Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
567 aLoop->registerListener(aListener, aStateRequestEventId);
571 ModelAPI_ValidatorsFactory* Model_Session::validators()
573 static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
577 int Model_Session::transactionID()
579 return ROOT_DOC->transactionID();
582 void Model_Session::blockAutoUpdate(const bool theBlock)
584 if (myIsAutoUpdateBlocked != theBlock) {
585 myIsAutoUpdateBlocked = theBlock;
586 static Events_Loop* aLoop = Events_Loop::loop();
588 static const Events_ID kAutoOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
589 std::shared_ptr<Events_Message> aMsg(new Events_Message(kAutoOff));
592 static const Events_ID kAutoOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
593 std::shared_ptr<Events_Message> aMsg(new Events_Message(kAutoOn));