Salome HOME
Task 5.1.7: To be able to export a part to a file and import it into an existing...
[modules/shaper.git] / src / Model / Model_Document.cpp
old mode 100755 (executable)
new mode 100644 (file)
index 99a624a..c69e0c5
@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2017  CEA/DEN, EDF R&D
+// Copyright (C) 2014-2019  CEA/DEN, EDF R&D
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 //
 // You should have received a copy of the GNU Lesser General Public
 // License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
-// See http://www.salome-platform.org/ or
-// email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
 #include <Model_Document.h>
@@ -24,6 +23,7 @@
 #include <Model_Application.h>
 #include <Model_Session.h>
 #include <Model_Events.h>
+#include <Model_Tools.h>
 #include <ModelAPI_ResultPart.h>
 #include <ModelAPI_Validator.h>
 #include <ModelAPI_CompositeFeature.h>
@@ -45,7 +45,6 @@
 #include <TDataStd_AsciiString.hxx>
 #include <TDF_Reference.hxx>
 #include <TDF_ChildIDIterator.hxx>
-#include <TDF_LabelMapHasher.hxx>
 #include <TDF_Delta.hxx>
 #include <TDF_AttributeDelta.hxx>
 #include <TDF_AttributeDeltaList.hxx>
 #include <TNaming_Iterator.hxx>
 #include <TNaming_NamedShape.hxx>
 #include <TNaming_Tool.hxx>
-#include<TNaming_OldShapeIterator.hxx>
+#include <TNaming_OldShapeIterator.hxx>
 #include <TopTools_DataMapOfShapeShape.hxx>
 #include <TopTools_ListOfShape.hxx>
 
 #include <TopExp_Explorer.hxx>
 #include <TopoDS_Shape.hxx>
 
+#include <OSD_Directory.hxx>
 #include <OSD_File.hxx>
 #include <OSD_Path.hxx>
+#include <OSD_Protection.hxx>
 #include <CDF_Session.hxx>
 #include <CDF_Directory.hxx>
+#include <UTL.hxx>
 
 #include <climits>
 #ifndef WIN32
@@ -145,6 +147,7 @@ bool Model_Document::isRoot() const
   return this == Model_Session::get()->moduleDocument().get();
 }
 
+// LCOV_EXCL_START
 /// Makes all modification and generation naming shapes that have old shapes corresponding to
 /// shapes in a root document be equal to this root document
 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
@@ -220,25 +223,23 @@ static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label
     }
   }
 }
+// LCOV_EXCL_STOP
 
-bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
+static bool loadDocument(Handle(Model_Application) theApp,
+                         Handle(TDocStd_Document)& theDoc,
+                         const TCollection_ExtendedString& theFilename)
 {
-  Handle(Model_Application) anApp = Model_Application::getApplication();
-  if (isRoot()) {
-    anApp->setLoadPath(theDirName);
-  }
-  TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
-  PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
-  Handle(TDocStd_Document) aLoaded;
+  PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus)-1;
   try {
-    aStatus = anApp->Open(aPath, aLoaded);
+    aStatus = theApp->Open(theFilename, theDoc);
   } catch (Standard_Failure const& anException) {
     Events_InfoMessage("Model_Document",
         "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
     return false;
   }
-  bool isError = aStatus != PCDM_RS_OK;
-  if (isError) {
+  bool isOk = aStatus == PCDM_RS_OK;
+  if (!isOk) {
+    // LCOV_EXCL_START
     switch (aStatus) {
       case PCDM_RS_UnknownDocument:
         Events_InfoMessage("Model_Document", "Can not open document").send();
@@ -293,10 +294,24 @@ bool Model_Document::load(const char* theDirName, const char* theFileName, Docum
         Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
         break;
     }
+    // LCOV_EXCL_STOP
   }
+  return isOk;
+}
+
+bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
+{
+  Handle(Model_Application) anApp = Model_Application::getApplication();
+  if (isRoot()) {
+    anApp->setLoadPath(theDirName);
+  }
+  TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
+  Handle(TDocStd_Document) aLoaded;
+  bool isOk = loadDocument(anApp, aLoaded, aPath);
+
   std::shared_ptr<Model_Session> aSession =
     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
-  if (!isError) {
+  if (isOk) {
     myDoc = aLoaded;
     myDoc->SetUndoLimit(UNDO_LIMIT);
 
@@ -331,7 +346,97 @@ bool Model_Document::load(const char* theDirName, const char* theFileName, Docum
   } else { // open failed, but new document was created to work with it: inform the model
     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
   }
-  return !isError;
+  return isOk;
+}
+
+bool Model_Document::import(const char* theFileName)
+{
+  Handle(Model_Application) anApp = Model_Application::getApplication();
+  TCollection_ExtendedString aFormat;
+  if (!anApp->Format(theFileName, aFormat))
+    return false;
+
+  Handle(TDocStd_Document) aTempDoc;
+  bool isOk = loadDocument(anApp, aTempDoc, theFileName);
+
+  // copy features from the temporary document to the current
+  Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
+  TDF_LabelList anAllNewFeatures;
+  // Perform the copying twice for correct references:
+  // 1. copy labels hierarchy and fill the relocation table
+  TDF_Label aMain = myDoc->Main();
+  for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
+    TDF_Label aCurrentLab = anIt.Value();
+    Handle(TDataStd_Comment) aFeatureID;
+    TDF_Label aNewFeatuerLab;
+    if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
+      TCollection_AsciiString anID(aFeatureID->Get());
+      FeaturePtr aNewFeature = addFeature(anID.ToCString());
+      std::shared_ptr<Model_Data> aData =
+          std::dynamic_pointer_cast<Model_Data>(aNewFeature->data());
+      aNewFeatuerLab = aData->label().Father();
+      Model_Tools::copyLabels(aCurrentLab, aNewFeatuerLab, aRelocTable);
+    }
+    anAllNewFeatures.Append(aNewFeatuerLab);
+  }
+  // 2. copy attributes
+  TDF_ListIteratorOfLabelList aNewIt(anAllNewFeatures);
+  for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
+    TDF_Label aCurrentLab = anIt.Value();
+    TDF_Label aFeatureLab = aNewIt.Value();
+    if (aFeatureLab.IsNull())
+      anAllNewFeatures.Remove(aNewIt);
+    else {
+      Model_Tools::copyAttrs(aCurrentLab, aFeatureLab, aRelocTable);
+      aNewIt.Next();
+    }
+  }
+
+  myObjs->synchronizeFeatures(anAllNewFeatures, true, false, false, true);
+
+  if (aTempDoc->CanClose() == CDM_CCS_OK)
+    aTempDoc->Close();
+  return isOk;
+}
+
+static bool saveDocument(Handle(Model_Application) theApp,
+                         Handle(TDocStd_Document) theDoc,
+                         const TCollection_ExtendedString& theFilename)
+{
+  PCDM_StoreStatus aStatus;
+  try {
+    // create the directory to save the document
+    OSD_Path aPathToFile = UTL::Path(theFilename);
+    aPathToFile.SetName("");
+    aPathToFile.SetExtension("");
+    OSD_Directory aBaseDir(aPathToFile);
+    if (!aBaseDir.Exists())
+      aBaseDir.Build(OSD_Protection());
+    // save the document
+    aStatus = theApp->SaveAs(theDoc, theFilename);
+  }
+  catch (Standard_Failure const& anException) {
+    Events_InfoMessage("Model_Document",
+      "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
+    return false;
+  }
+  bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
+  if (!isDone) {
+    switch (aStatus) {
+    case PCDM_SS_DriverFailure:
+      Events_InfoMessage("Model_Document",
+        "Can not save document: save driver-library failure").send();
+      break;
+    case PCDM_SS_WriteFailure:
+      Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
+      break;
+    case PCDM_SS_Failure:
+    default:
+      Events_InfoMessage("Model_Document", "Can not save document").send();
+      break;
+    }
+  }
+  return isDone;
 }
 
 bool Model_Document::save(
@@ -362,41 +467,17 @@ bool Model_Document::save(
   Handle(Model_Application) anApp = Model_Application::getApplication();
   if (isRoot()) {
 #ifdef WIN32
-    CreateDirectory((LPTSTR) theDirName, NULL);
+    size_t aDirLen = strlen(theDirName);
+    std::wstring aWStr(aDirLen, L'#');
+    mbstowcs(&aWStr[0], theDirName, aDirLen);
+    CreateDirectory(aWStr.c_str(), NULL);
 #else
     mkdir(theDirName, 0x1ff);
 #endif
   }
   // filename in the dir is id of document inside of the given directory
   TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
-  PCDM_StoreStatus aStatus;
-  try {
-    aStatus = anApp->SaveAs(myDoc, aPath);
-  } catch (Standard_Failure const& anException) {
-    Events_InfoMessage("Model_Document",
-        "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
-    if (aWasCurrent.get()) { // return the current feature to the initial position
-      setCurrentFeature(aWasCurrent, false);
-      aSession->setCheckTransactions(true);
-    }
-    return false;
-  }
-  bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
-  if (!isDone) {
-    switch (aStatus) {
-      case PCDM_SS_DriverFailure:
-        Events_InfoMessage("Model_Document",
-                           "Can not save document: save driver-library failure").send();
-        break;
-      case PCDM_SS_WriteFailure:
-        Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
-        break;
-      case PCDM_SS_Failure:
-      default:
-        Events_InfoMessage("Model_Document", "Can not save document").send();
-        break;
-    }
-  }
+  bool isDone = saveDocument(anApp, myDoc, aPath);
 
   if (aWasCurrent.get()) { // return the current feature to the initial position
     setCurrentFeature(aWasCurrent, false);
@@ -439,6 +520,41 @@ bool Model_Document::save(
   return isDone;
 }
 
+bool Model_Document::save(const char* theFilename,
+                          const std::list<FeaturePtr>& theExportFeatures) const
+{
+  Handle(Model_Application) anApp = Model_Application::getApplication();
+  TCollection_ExtendedString aFormat;
+  if (!anApp->Format(theFilename, aFormat))
+    return false;
+
+  Handle(TDocStd_Document) aTempDoc = new TDocStd_Document(aFormat);
+  TDF_Label aMain = aTempDoc->Main();
+
+  Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
+  std::list<FeaturePtr>::const_iterator anIt = theExportFeatures.begin();
+  // Perform the copying twice for correct references:
+  // 1. copy labels hierarchy and fill the relocation table
+  for (; anIt != theExportFeatures.end(); ++anIt) {
+    TDF_Label aFeatureLab = aMain.NewChild();
+    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
+    Model_Tools::copyLabels(aData->label().Father(), aFeatureLab, aRelocTable);
+  }
+  // 2. copy attributes
+  TDF_ChildIterator aChildIt(aMain);
+  for (anIt = theExportFeatures.begin(); anIt != theExportFeatures.end(); ++anIt) {
+    TDF_Label aFeatureLab = aChildIt.Value();
+    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
+    Model_Tools::copyAttrs(aData->label().Father(), aFeatureLab, aRelocTable);
+    aChildIt.Next();
+  }
+
+  bool isDone = saveDocument(anApp, aTempDoc, theFilename);
+  if (aTempDoc->CanClose() == CDM_CCS_OK)
+    aTempDoc->Close();
+  return isDone;
+}
+
 void Model_Document::close(const bool theForever)
 {
   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
@@ -668,10 +784,10 @@ bool Model_Document::finishOperation()
   }
   myObjs->synchronizeBackRefs();
   Events_Loop* aLoop = Events_Loop::loop();
-  static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
-  static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
-  static const Events_ID kRedispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
-  static const Events_ID kDeletedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED);
+  static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
+  static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
+  static const Events_ID kRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
+  static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
   aLoop->flush(kCreatedEvent);
   aLoop->flush(kUpdatedEvent);
   aLoop->flush(kRedispEvent);
@@ -887,9 +1003,10 @@ void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchron
     myDoc->Undo();
   }
 
+  std::set<int> aSubs;
   if (theWithSubs) {
     // undo for all subs
-    const std::set<int> aSubs = subDocuments();
+    aSubs = subDocuments();
     std::set<int>::iterator aSubIter = aSubs.begin();
     for (; aSubIter != aSubs.end(); aSubIter++) {
       if (!subDoc(*aSubIter)->myObjs)
@@ -902,6 +1019,19 @@ void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchron
     myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
     // update the current features status
     setCurrentFeature(currentFeature(false), false);
+
+    if (theWithSubs) {
+      // undo for all subs
+      const std::set<int> aNewSubs = subDocuments();
+      std::set<int>::iterator aNewSubIter = aNewSubs.begin();
+      for (; aNewSubIter != aNewSubs.end(); aNewSubIter++) {
+        // synchronize only newly appeared documents
+        if (!subDoc(*aNewSubIter)->myObjs || aSubs.find(*aNewSubIter) != aSubs.end())
+          continue;
+        TDF_LabelList anEmptyDeltas;
+        subDoc(*aNewSubIter)->myObjs->synchronizeFeatures(anEmptyDeltas, true, false, true, true);
+      }
+    }
   }
 }
 
@@ -950,7 +1080,8 @@ void Model_Document::redo()
   // update the current features status
   setCurrentFeature(currentFeature(false), false);
 }
-
+// this is used for creation of undo/redo1-list by GUI
+// LCOV_EXCL_START
 std::list<std::string> Model_Document::undoList() const
 {
   std::list<std::string> aResult;
@@ -976,6 +1107,7 @@ std::list<std::string> Model_Document::redoList() const
   }
   return aResult;
 }
+// LCOV_EXCL_STOP
 
 void Model_Document::operationId(const std::string& theId)
 {
@@ -1018,6 +1150,15 @@ FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurre
         }
       }
     }
+    // #2861,3029: if the parameter is added, add it after parameters existing in the list
+    if (aCurrent.get() &&
+      (aFeature->getKind() == "Parameter" || aFeature->getKind() == "ParametersMgr")) {
+      int anIndex = kUNDEFINED_FEATURE_INDEX;
+      for(FeaturePtr aNextFeat = myObjs->nextFeature(aCurrent, anIndex);
+        aNextFeat.get() && aNextFeat->getKind() == "Parameter";
+        aNextFeat = myObjs->nextFeature(aCurrent, anIndex))
+        aCurrent = aNextFeat;
+    }
     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
     if (!aFeature->isAction()) {  // do not add action to the data model
       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
@@ -1030,7 +1171,6 @@ FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurre
   return aFeature;
 }
 
-
 void Model_Document::refsToFeature(FeaturePtr theFeature,
   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
 {
@@ -1041,7 +1181,7 @@ void Model_Document::removeFeature(FeaturePtr theFeature)
 {
   myObjs->removeFeature(theFeature);
   // fix for #2723: send signal that part is updated
-  if (!isRoot()) {
+  if (!isRoot() && isOperation()) {
     std::shared_ptr<Model_Document> aRoot =
       std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
     std::list<ResultPtr> allParts;
@@ -1069,7 +1209,6 @@ static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
   return isSub(theMain, aParent);
 }
 
-
 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
 {
   bool aCurrentUp = theMoved == currentFeature(false);
@@ -1230,6 +1369,18 @@ void Model_Document::setCurrentFeature(
       }
     }
   }
+  if (theVisible) { // make RemoveResults feature be active even it is performed after the current
+    int anIndex = kUNDEFINED_FEATURE_INDEX;
+    FeaturePtr aNext =
+      theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
+    for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
+      if (aNext->isInHistory()) {
+        break; // next in history is not needed
+      } else if (aNext->getKind() == "RemoveResults"){
+        theCurrent = aNext;
+      }
+    }
+  }
   if (theCurrent.get()) {
     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
     if (!aData.get() || !aData->isValid()) {
@@ -1435,16 +1586,6 @@ std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
   return myObjs->feature(theResult);
 }
 
-Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
-{
-  return TDF_LabelMapHasher::HashCode(theLab, theUpper);
-
-}
-Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
-{
-  return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
-}
-
 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
   TDF_Label aCurrentLab = theLab;
   while(aCurrentLab.Depth() > 3)
@@ -1465,7 +1606,6 @@ ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
   return ResultPtr(); // not found
 }
 
-
 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
 {
   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
@@ -1521,7 +1661,7 @@ void Model_Document::changeNamingName(const std::string theOldName,
           Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
           std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
           if (aName.find(theOldName) == 0) { // started from parent name
-            std::string aNewSubName = theNewName + aName.substr(theNewName.size());
+            std::string aNewSubName = theNewName + aName.substr(theOldName.size());
             changeNamingName(aName, aNewSubName, aSubName->Label());
             aSubName->Set(aNewSubName.c_str());
           }
@@ -1759,11 +1899,6 @@ void Model_Document::incrementTransactionID()
   int aNewVal = transactionID() + 1;
   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
 }
-void Model_Document::decrementTransactionID()
-{
-  int aNewVal = transactionID() - 1;
-  TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
-}
 
 TDF_Label Model_Document::extConstructionsLabel() const
 {
@@ -1785,11 +1920,6 @@ std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theI
   return myObjs->internalFeature(theIndex);
 }
 
-std::shared_ptr<ModelAPI_Feature> Model_Document::featureById(const int theId)
-{
-  return myObjs->featureById(theId);
-}
-
 void Model_Document::synchronizeTransactions()
 {
   Model_Document* aRoot =
@@ -2009,6 +2139,8 @@ bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
   return myObjs->isLater(theLater, theCurrent);
 }
 
+// Object Browser nodes states
+// LCOV_EXCL_START
 void Model_Document::storeNodesState(const std::list<bool>& theStates)
 {
   TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
@@ -2034,6 +2166,7 @@ void Model_Document::restoreNodesState(std::list<bool>& theStates) const
     }
   }
 }
+// LCOV_EXCL_STOP
 
 void Model_Document::eraseAllFeatures()
 {
@@ -2041,6 +2174,16 @@ void Model_Document::eraseAllFeatures()
     myObjs->eraseAllFeatures();
 }
 
+std::shared_ptr<ModelAPI_Feature> Model_Document::nextFeature(
+  std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse) const
+{
+  if (theCurrent.get() && myObjs) {
+    int anIndex = kUNDEFINED_FEATURE_INDEX;
+    return myObjs->nextFeature(theCurrent, anIndex, theReverse);
+  }
+  return FeaturePtr(); // nothing by default
+}
+
 void Model_Document::setExecuteFeatures(const bool theFlag)
 {
   myExecuteFeatures = theFlag;