Salome HOME
Copyright update 2021
[modules/shaper.git] / src / Model / Model_Document.cpp
index 216acecd7a7a3e73fdaf670cf1cb24e95f3f3e27..94903c205b044a660676fc5b2cc9ae43219adca8 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2019  CEA/DEN, EDF R&D
+// Copyright (C) 2014-2021  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
@@ -34,6 +34,8 @@
 #include <Events_InfoMessage.h>
 #include <GeomAPI_Tools.h>
 
+#include <Locale_Convert.h>
+
 #include <TDataStd_Integer.hxx>
 #include <TDataStd_Comment.hxx>
 #include <TDF_ChildIDIterator.hxx>
 #include <OSD_File.hxx>
 #include <OSD_Path.hxx>
 #include <OSD_Protection.hxx>
+
+#ifdef TINSPECTOR
 #include <CDF_Session.hxx>
 #include <CDF_Directory.hxx>
+#endif
+
 #include <UTL.hxx>
 
 #include <climits>
@@ -104,8 +110,11 @@ static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
 
 Model_Document::Model_Document(const int theID, const std::string theKind)
-    : myID(theID), myKind(theKind), myIsActive(false), myIsSetCurrentFeature(false),
-      myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
+    : myID(theID),
+      myKind(theKind),
+      myDoc(new TDocStd_Document("BinOcaf")),  // binary OCAF format
+      myIsActive(false),
+      myIsSetCurrentFeature(false)
 {
 #ifdef TINSPECTOR
   CDF_Session::CurrentSession()->Directory()->Add(myDoc);
@@ -123,6 +132,15 @@ Model_Document::Model_Document(const int theID, const std::string theKind)
   myDoc->CommitCommand();
 }
 
+Model_Document::~Model_Document()
+{
+  if (!myDoc.IsNull())
+  {
+    myDoc->ClearUndos();
+    myDoc->ClearRedos();
+  }
+}
+
 void Model_Document::setThis(DocumentPtr theDoc)
 {
   myObjs->setOwner(theDoc);
@@ -312,6 +330,8 @@ bool Model_Document::load(const char* theDirName, const char* theFileName, Docum
   std::shared_ptr<Model_Session> aSession =
     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
   if (isOk) {
+    // keep handle to avoid destruction of the document until myObjs works on it
+    Handle(TDocStd_Document) anOldDoc = myDoc;
     myDoc = aLoaded;
     myDoc->SetUndoLimit(UNDO_LIMIT);
 
@@ -320,6 +340,9 @@ bool Model_Document::load(const char* theDirName, const char* theFileName, Docum
     aSession->setCheckTransactions(false);
     if (myObjs)
       delete myObjs;
+    anOldDoc->ClearRedos();
+    anOldDoc->ClearUndos();
+    anOldDoc.Nullify();
     myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
     myObjs->setOwner(theThis);
     // update the current features status
@@ -349,9 +372,9 @@ bool Model_Document::load(const char* theDirName, const char* theFileName, Docum
   return isOk;
 }
 
-bool Model_Document::import(const char* theFileName,
-                            std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
-                            bool theCheckBefore)
+bool Model_Document::importPart(const char* theFileName,
+                                std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
+                                bool theCheckOnly)
 {
   Handle(Model_Application) anApp = Model_Application::getApplication();
   TCollection_ExtendedString aFormat;
@@ -361,7 +384,7 @@ bool Model_Document::import(const char* theFileName,
   Handle(TDocStd_Document) aTempDoc;
   bool isOk = loadDocument(anApp, aTempDoc, theFileName);
 
-  if (isOk && theCheckBefore) {
+  if (isOk && theCheckOnly) {
     // verify all features are applicable for the current document type (e.g. PartSet)
     std::shared_ptr<Model_Session> aSession =
         std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
@@ -380,13 +403,16 @@ bool Model_Document::import(const char* theFileName,
     }
   }
 
-  if (isOk) {
+  if (isOk && !theCheckOnly) {
     // copy features from the temporary document to the current
     Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable();
+    // add to relocation table source root label to the destination label because
+    // sometimes there could be a reference to root (issue 3267 on import part
+    // with sketch with removed features)
+    aRelocTable->SetRelocation(aTempDoc->Main().Root(), myDoc->Main().Root());
     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;
@@ -437,7 +463,7 @@ static bool saveDocument(Handle(Model_Application) theApp,
     aPathToFile.SetName("");
     aPathToFile.SetExtension("");
     OSD_Directory aBaseDir(aPathToFile);
-    if (!aBaseDir.Exists())
+    if (aPathToFile.TrekLength() != 0 && !aBaseDir.Exists())
       aBaseDir.Build(OSD_Protection());
     // save the document
     aStatus = theApp->SaveAs(theDoc, theFilename);
@@ -522,12 +548,12 @@ bool Model_Document::save(
       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
       if (!aPart->isActivated()) {
         // copy not-activated document that is not in the memory
-        std::string aDocName = aPart->data()->name();
+        std::string aDocName = Locale::Convert::toString(aPart->data()->name());
         if (!aDocName.empty()) {
           // just copy file
           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
-          OSD_Path aPath(aSubPath);
-          OSD_File aFile(aPath);
+          OSD_Path aCopyPath(aSubPath);
+          OSD_File aFile(aCopyPath);
           if (aFile.Exists()) {
             TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
             OSD_Path aDestination(aDestinationDir);
@@ -539,8 +565,9 @@ bool Model_Document::save(
           }
         }
       } else { // simply save opened document
+        std::string aDocName = Locale::Convert::toString(aPart->data()->name());
         isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
-          save(theDirName, aPart->data()->name().c_str(), theResults);
+          save(theDirName, aDocName.c_str(), theResults);
       }
     }
   }
@@ -762,7 +789,7 @@ static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
   aDelta = theDoc->GetUndos().Last();
   TDF_LabelList aDeltaList;
   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
-  for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
+  if (!aDeltaList.IsEmpty()) {
     return false;
   }
   // add also label of the modified attributes
@@ -990,7 +1017,7 @@ bool Model_Document::isOperation() const
 bool Model_Document::isModified()
 {
   // is modified if at least one operation was committed and not undone
-  return myTransactions.size() != myTransactionSave || isOperation();
+  return (int)myTransactions.size() != myTransactionSave || isOperation();
 }
 
 bool Model_Document::canUndo()
@@ -1148,6 +1175,8 @@ FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurre
 {
   std::shared_ptr<Model_Session> aSession =
     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
+  if (!aSession->hasModuleDocument() || !myObjs)
+    return FeaturePtr(); // this may be on close of the document
   FeaturePtr aFeature = aSession->createFeature(theID, this);
   if (!aFeature)
     return aFeature;
@@ -1239,7 +1268,7 @@ static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
   return isSub(theMain, aParent);
 }
 
-void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
+void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis, const bool theSplit)
 {
   bool aCurrentUp = theMoved == currentFeature(false);
   if (aCurrentUp) {
@@ -1263,13 +1292,26 @@ void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
     } while (aSub.get());
   }
 
+  AttributeSelectionListPtr aMovedList;
+  if (theMoved->getKind() == "Group") {
+    aMovedList = theMoved->selectionList("group_list");
+    if (aMovedList.get())
+      aMovedList->setMakeCopy(true);
+  }
   myObjs->moveFeature(theMoved, anAfterThisSub);
+
+  if (theSplit) { // split the group into sub-features
+    theMoved->customAction("split");
+  }
+
   if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
     setCurrentFeature(currentFeature(false), false);
   } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
     // must be after move to make enabled all features which are before theMoved
     setCurrentFeature(theMoved, true);
   }
+  if (aMovedList.get())
+    aMovedList->setMakeCopy(false);
 }
 
 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
@@ -1314,7 +1356,7 @@ ObjectPtr Model_Document::object(const std::string& theGroupID,
 }
 
 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
-    const std::string& theGroupID, const std::string& theName)
+    const std::string& theGroupID, const std::wstring& theName)
 {
   return myObjs->objectByName(theGroupID, theName);
 }
@@ -1492,6 +1534,9 @@ void Model_Document::setCurrentFeature(
   myIsSetCurrentFeature = false;
   // unblock  the flush signals and up them after this
   aLoop->activateFlushes(isActive);
+
+  static Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
+  aLoop->flush(kUpdatedSel);
 }
 
 void Model_Document::setCurrentFeatureUp()
@@ -1636,9 +1681,9 @@ ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
   return ResultPtr(); // not found
 }
 
-void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
+void Model_Document::addNamingName(const TDF_Label theLabel, std::wstring theName)
 {
-  std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
+  std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
 
   if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
     // to keep correct order in spite of history line management
@@ -1670,11 +1715,11 @@ void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName
   myNamingNames[theName].push_back(theLabel);
 }
 
-void Model_Document::changeNamingName(const std::string theOldName,
-                                      const std::string theNewName,
+void Model_Document::changeNamingName(const std::wstring theOldName,
+                                      const std::wstring theNewName,
                                       const TDF_Label& theLabel)
 {
-  std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
+  std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
   if (aFind != myNamingNames.end()) {
     std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
     for(; aLabIter != aFind->second.end(); aLabIter++) {
@@ -1689,9 +1734,9 @@ void Model_Document::changeNamingName(const std::string theOldName,
         TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
         for(; aChild.More(); aChild.Next()) {
           Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
-          std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
+          std::wstring aName = Locale::Convert::toWString(aSubName->Get().ToExtString());
           if (aName.find(theOldName) == 0) { // started from parent name
-            std::string aNewSubName = theNewName + aName.substr(theOldName.size());
+            std::wstring aNewSubName = theNewName + aName.substr(theOldName.size());
             changeNamingName(aName, aNewSubName, aSubName->Label());
             aSubName->Set(aNewSubName.c_str());
           }
@@ -1702,9 +1747,55 @@ void Model_Document::changeNamingName(const std::string theOldName,
   }
 }
 
-TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theContext)
+// returns true if names consist of the same sub-elements but with different order.
+// Sub-elements are separated by "-" symbol. First part must be "Face", second at the same place.
+static bool IsExchangedName(const TCollection_ExtendedString& theName1,
+                            const TCollection_ExtendedString& theName2)
 {
-  std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
+  static const TCollection_ExtendedString aSepStr("-");
+  static const Standard_ExtString aSep = aSepStr.ToExtString();
+  static const TCollection_ExtendedString aWireTail("_wire");
+  if (theName1.Token(aSep, 1) != "Face" || theName2.Token(aSep, 1) != "Face")
+    return false;
+  if (theName1.Token(aSep, 2) != theName2.Token(aSep, 2))
+    return false;
+  // Collect Map of the sub-elements of the first name
+  NCollection_Map<TCollection_ExtendedString> aSubsMap;
+  TCollection_ExtendedString aWireSuffix;
+  int a = 3;
+  for (; true ; a++) {
+    TCollection_ExtendedString aToken = theName1.Token(aSep, a);
+    if (aToken.IsEmpty())
+      break;
+    int aTailPos = aToken.Search(aWireTail);
+    if (aTailPos > 0) {
+      aWireSuffix = aToken.Split(aTailPos - 1);
+    }
+    aSubsMap.Add(aToken);
+  }
+  // check all subs in the second name are in the map
+  for (int a2 = 3; true; a2++) {
+    TCollection_ExtendedString aToken = theName2.Token(aSep, a2);
+    if (aToken.IsEmpty()) {
+      if (a2 != a) // number of sub-elements is not equal
+        return false;
+      break;
+    }
+    int aTailPos = aToken.Search(aWireTail);
+    if (aTailPos > 0) {
+      TCollection_ExtendedString aSuffix = aToken.Split(aTailPos - 1);
+      if (aWireSuffix != aSuffix)
+        return false;
+    }
+    if (!aSubsMap.Contains(aToken))
+      return false;
+  }
+  return true;
+}
+
+TDF_Label Model_Document::findNamingName(std::wstring theName, ResultPtr theContext)
+{
+  std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
   if (aFind != myNamingNames.end()) {
       std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
       for(; aLabIter != aFind->second.rend(); aLabIter++) {
@@ -1717,9 +1808,9 @@ TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theConte
       return *(aFind->second.rbegin()); // no more variants, so, return the last
   }
   // not found exact name, try to find by sub-components
-  std::string::size_type aSlash = theName.rfind('/');
-  if (aSlash != std::string::npos) {
-    std::string anObjName = theName.substr(0, aSlash);
+  std::wstring::size_type aSlash = theName.rfind(L'/');
+  if (aSlash != std::wstring::npos) {
+    std::wstring anObjName = theName.substr(0, aSlash);
     aFind = myNamingNames.find(anObjName);
     if (aFind != myNamingNames.end()) {
       TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
@@ -1733,13 +1824,19 @@ TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theConte
         }
         // copy aSubName to avoid incorrect further processing after its suffix cutting
         TCollection_ExtendedString aSubNameCopy(aSubName);
+        TDF_Label aFaceLabelWithExchangedSubs; // check also exchanged sub-elements of the name
         // searching sub-labels with this name
         TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
         for(; aNamesIter.More(); aNamesIter.Next()) {
           Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
           if (aName->Get() == aSubNameCopy)
             return aName->Label();
+          if (aName->Get().Length() == aSubNameCopy.Length() &&
+              IsExchangedName(aName->Get(),  aSubNameCopy))
+            aFaceLabelWithExchangedSubs = aName->Label();
         }
+        if (!aFaceLabelWithExchangedSubs.IsNull())
+          return aFaceLabelWithExchangedSubs;
         // If not found child label with the exact sub-name, then try to find compound with
         // such sub-name without suffix.
         Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
@@ -1809,7 +1906,7 @@ bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
 int Model_Document::numberOfNameInHistory(
   const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
 {
-  std::map<std::string, std::list<TDF_Label> >::iterator aFind =
+  std::map<std::wstring, std::list<TDF_Label> >::iterator aFind =
     myNamingNames.find(theNameObject->data()->name());
   if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
     return 1; // no need to specify the name by additional identifiers
@@ -1847,10 +1944,10 @@ int Model_Document::numberOfNameInHistory(
 }
 
 ResultPtr Model_Document::findByName(
-  std::string& theName, std::string& theSubShapeName, bool& theUniqueContext)
+  std::wstring& theName, std::wstring& theSubShapeName, bool& theUniqueContext)
 {
   int aNumInHistory = 0;
-  std::string aName = theName;
+  std::wstring aName = theName;
   ResultPtr aRes = myObjs->findByName(aName);
   theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
   while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
@@ -1859,8 +1956,8 @@ ResultPtr Model_Document::findByName(
     aRes = myObjs->findByName(aName);
   }
   if (aNumInHistory) {
-    std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
-    if (aFind != myNamingNames.end() && aFind->second.size() > aNumInHistory) {
+    std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
+    if (aFind != myNamingNames.end() && (int)aFind->second.size() > aNumInHistory) {
       std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
       for(; aNumInHistory != 0; aNumInHistory--)
         aLibIt++;
@@ -2004,7 +2101,7 @@ AttributeSelectionListPtr Model_Document::selectionInPartFeature()
     aData->setObject(mySelectionFeature);
     mySelectionFeature->setDoc(myObjs->owner());
     mySelectionFeature->setData(aData);
-    std::string aName = id() + "_Part";
+    std::wstring aName = id() + L"_Part";
     mySelectionFeature->data()->setName(aName);
     mySelectionFeature->setDoc(myObjs->owner());
     mySelectionFeature->initAttributes();
@@ -2230,6 +2327,8 @@ void Model_Document::appendTransactionToPrevious()
 {
   Transaction anAppended =  myTransactions.back();
   myTransactions.pop_back();
+  if (!myNestedNum.empty())
+    (*myNestedNum.rbegin())--;
   if (!myTransactions.empty()) { // if it is empty, just forget the appended
     myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
   }