Salome HOME
Fix repeated items
[modules/geom.git] / src / GEOM_I / GEOM_Gen_i.cc
old mode 100644 (file)
new mode 100755 (executable)
index 86fca28..7fa57d2
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -6,7 +6,7 @@
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
-// version 2.1 of the License.
+// version 2.1 of the License, or (at your option) any later version.
 //
 // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -18,8 +18,9 @@
 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
-#ifdef WNT
+#ifdef WIN32
 #pragma warning( disable:4786 )
 #endif
 
 #include "Utils_ExceptHandlers.hxx"
 #include "utilities.h"
 
-#include "GEOM_Object_i.hh"
 #include "GEOM_Object.hxx"
 #include "GEOM_Function.hxx"
 #include "GEOM_ISubShape.hxx"
 #include "GEOM_PythonDump.hxx"
 #include "GEOMImpl_Types.hxx"
 #include "GEOMImpl_CopyDriver.hxx"
+#include "GEOMImpl_IInsertOperations.hxx"
 #include "GEOM_wrap.hxx"
 
 // Cascade headers
 #include <TColStd_HArray1OfInteger.hxx>
 #include <TopAbs_ShapeEnum.hxx>
 #include <TopExp.hxx>
+#include <TopTools_SequenceOfShape.hxx>
 #include <OSD.hxx>
+#include <TDataStd_ChildNodeIterator.hxx>
+#include <TDocStd_Owner.hxx>
+#include <TDataStd_ListIteratorOfListOfExtendedString.hxx>
 
 #include <SALOMEDS_Tool.hxx>
 #include <SALOMEDS_wrap.hxx>
+#include <SALOME_DataContainer_i.hxx>
+#include <Basics_DirUtils.hxx>
 
 #include <set>
 #include <sstream>
 
-#ifdef WNT
+#ifdef WIN32
  #include <windows.h>
  #include <process.h>
 #else
  #include <dlfcn.h>
 #endif
 
-#ifdef WNT
+#ifdef WIN32
  #define LibHandle HMODULE
  #define LoadLib( name ) LoadLibrary( name )
  #define GetProc GetProcAddress
@@ -106,14 +113,11 @@ GEOM_Gen_i::GEOM_Gen_i(CORBA::ORB_ptr            orb,
   {
     //work around PAL12004, PAL12628
     //OSD::SetSignal( true );
-    bool raiseFPE;
-#ifdef _DEBUG_
-    raiseFPE = true;
-    char* envDisableFPE = getenv("DISABLE_FPE");
-    if (envDisableFPE && atoi(envDisableFPE))
-      raiseFPE = false;
-#else
-    raiseFPE = false;
+    bool raiseFPE = false;
+#if defined(_DEBUG_) | defined(_DEBUG) //the Last for WIN32 default settings
+    char* envEnableFPE = getenv("ENABLE_FPE");
+    if (envEnableFPE && atoi(envEnableFPE))
+      raiseFPE = true;
 #endif
     OSD::SetSignal( raiseFPE );
   }
@@ -238,11 +242,11 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr   theStudy,
   CORBA::String_var aGeomObjIOR = _orb->object_to_string(theObject);
   aResultSO->SetAttrString("AttributeIOR",aGeomObjIOR);
 
-  TCollection_AsciiString anObjectName("Shape_");
+  TCollection_AsciiString anObjectName, aNamePrefix("Shape_");
+  CORBA::Long mytype=aBaseObj->GetType();
 
   // BEGIN: try to find existed name for current shape
-  bool HasName = false;
-  if ( !aShape->_is_nil() )
+  if ( !aShape->_is_nil() && mytype != GEOM_GROUP)
   {
     // recieve current TopoDS shape
     CORBA::String_var entry = aShape->GetEntry();
@@ -261,7 +265,7 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr   theStudy,
     // check all named shapes using iterator
     TDF_ChildIDIterator anIt (aMainLbl, TNaming_NamedShape::GetID(), Standard_True);
 
-    for (; anIt.More() && !HasName; anIt.Next()) {
+    for (; anIt.More() && anObjectName.IsEmpty(); anIt.Next()) {
       Handle(TNaming_NamedShape) anAttr =
         Handle(TNaming_NamedShape)::DownCast(anIt.Value());
       if (anAttr.IsNull()) continue;
@@ -269,47 +273,44 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr   theStudy,
       if (S.IsEqual(TopoSh)) {
         TDF_Label L = anAttr->Label();
         Handle(TDataStd_Name) aName;
-        if (L.FindAttribute(TDataStd_Name::GetID(), aName)) {
+        if (L.FindAttribute(TDataStd_Name::GetID(), aName))
           anObjectName = aName->Get();
-          HasName = true;
-        }
       }
     }
   }
   // END: try to find existed name for current shape
 
-  CORBA::Long mytype=aBaseObj->GetType();
   if ( mytype == GEOM_GROUP ) {
     GEOM::GEOM_IGroupOperations_var anOp = GetIGroupOperations( theStudy->StudyId() );
     switch ( (TopAbs_ShapeEnum)anOp->GetType( aShape )) {
     case TopAbs_VERTEX:
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_PNT" );
-      anObjectName = "Group_Of_Vertices_";
+      aNamePrefix = "Group_Of_Vertices_";
       break;
     case TopAbs_EDGE:
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_EDGE");
-      anObjectName = "Group_Of_Edges_";
+      aNamePrefix = "Group_Of_Edges_";
       break;
     case TopAbs_FACE:
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_FACE");
-      anObjectName = "Group_Of_Faces_";
+      aNamePrefix = "Group_Of_Faces_";
       break;
     case TopAbs_SOLID:
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_SOLID");
-      anObjectName = "Group_Of_Solids_";
+      aNamePrefix = "Group_Of_Solids_";
       break;
     }
   } else if ( mytype == GEOM_MARKER ) {
     aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_LCS");
-    anObjectName = "LocalCS_";
+    aNamePrefix = "LocalCS_";
   } else if ( mytype > ADVANCED_BASE ) {
     char buf[20];
     sprintf( buf, "%d", aBaseObj->GetType() );
     std::string advId = "ICON_OBJBROWSER_ADVANCED_"; advId += buf;
     aResultSO->SetAttrString("AttributePixMap",advId.c_str());
-    anObjectName = "Advanced_";
+    aNamePrefix = "Advanced_";
   } else if ( mytype == GEOM_FIELD ) {
-    anObjectName = "Field_";
+    aNamePrefix = "Field_";
     GEOM::GEOM_Field_var aField = GEOM::GEOM_Field::_narrow(theObject);
     if ( !aField->_is_nil() )
       switch( aField->GetDimension() ) {
@@ -325,38 +326,38 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr   theStudy,
         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_SOLID");
       }
   } else if ( mytype == GEOM_FIELD_STEP ) {
-    anObjectName = "Step_";
+    aNamePrefix = "Step_";
   } else if ( !aShape->_is_nil() ) {
     GEOM::shape_type myshapetype=aShape->GetShapeType();
     if ( myshapetype == GEOM::COMPOUND ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_COMPOUND" );
-      anObjectName = "Compound_";
+      aNamePrefix = "Compound_";
     } else if ( myshapetype == GEOM::COMPSOLID ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_COMPSOLID");
-      anObjectName = "Compsolid_";
+      aNamePrefix = "Compsolid_";
     } else if ( myshapetype == GEOM::SOLID ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_SOLID");
-      anObjectName = "Solid_";
+      aNamePrefix = "Solid_";
     } else if ( myshapetype == GEOM::SHELL ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_SHELL");
-      anObjectName = "Shell_";
+      aNamePrefix = "Shell_";
     } else if ( myshapetype == GEOM::FACE ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FACE");
-      anObjectName = "Face_";
+      aNamePrefix = "Face_";
     } else if ( myshapetype == GEOM::WIRE ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_WIRE");
-      anObjectName = "Wire_";
+      aNamePrefix = "Wire_";
     } else if ( myshapetype == GEOM::EDGE ) {
       aResultSO->SetAttrString("AttributePixMap", "ICON_OBJBROWSER_EDGE");
-      anObjectName = "Edge_";
+      aNamePrefix = "Edge_";
     } else if ( myshapetype == GEOM::VERTEX ) {
       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_VERTEX" );
-      anObjectName = "Vertex_";
+      aNamePrefix = "Vertex_";
     }
   }
-  if (!HasName)
+  if ( anObjectName.IsEmpty() )
   {
-    //if (strlen(theName) == 0) anObjectName += TCollection_AsciiString(aResultSO->Tag());
+    //if (strlen(theName) == 0) aNamePrefix += TCollection_AsciiString(aResultSO->Tag());
     //else anObjectName = TCollection_AsciiString(CORBA::string_dup(theName));
 
     // asv : 11.11.04 Introducing a more sofisticated method of name creation, just as
@@ -366,16 +367,15 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::Study_ptr   theStudy,
     if ( strlen( theName ) == 0 ) { // MOST PROBABLY CALLED FROM BATCHMODE OR SUPERVISOR
       int i = 0;                    // (WITH EMPTY NEW NAME)
       SALOMEDS::SObject_var obj;
-      TCollection_AsciiString aNewObjectName;
       do {
-        aNewObjectName = anObjectName + TCollection_AsciiString(++i);
-        obj = theStudy->FindObject( aNewObjectName.ToCString() );
+        anObjectName = aNamePrefix + TCollection_AsciiString(++i);
+        obj = theStudy->FindObject( anObjectName.ToCString() );
       }
       while ( !obj->_is_nil() );
-      anObjectName = aNewObjectName;
     }
-    else // MOST PROBABLY CALLED FROM GEOM GUI (ALREADY WITH VALID NAME)
+    else // MOST PROBABLY CALLED FROM GEOM GUI (ALREADY WITH VALID NAME)
       anObjectName = theName;
+    }
   }
 
   //Set the study entry as a name of  the published GEOM_Object
@@ -551,7 +551,7 @@ SALOMEDS::TMPFile* GEOM_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
   // OCCT BUG: cannot save a document (in current folder)
   // if directory name is empty
   if (aTmpDir.size() == 0) {
-#ifdef WNT
+#ifdef WIN32
     aTmpDir = ".\\";
 #else
     aTmpDir = "./";
@@ -614,7 +614,7 @@ CORBA::Boolean GEOM_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
   // OCCT BUG: cannot load a document (from current folder)
   // if directory name is empty
   if (aTmpDir.size() == 0) {
-#ifdef WNT
+#ifdef WIN32
     aTmpDir = ".\\";
 #else
     aTmpDir = "./";
@@ -748,6 +748,7 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
   // Find the current Study and StudyBuilder
   SALOMEDS::Study_var aStudy = theObject->GetStudy();
   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
+  SALOMEDS::UseCaseBuilder_var anUseCaseBuilder = aStudy->GetUseCaseBuilder();
   SALOMEDS::SObject_var aNewSO;
   // Retrieve a TopoDS_Shape from byte stream
   TopoDS_Shape aTopology;
@@ -784,6 +785,10 @@ SALOMEDS::SObject_ptr GEOM_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
   anIOR->SetValue(objStr.in());
   anIOR->UnRegister();
 
+  // add object to the use case tree
+  // (to support tree representation customization and drag-n-drop)
+  anUseCaseBuilder->AppendTo( aNewSO->GetFather(), aNewSO );
+
   // Return the created in the Study SObject
   return aNewSO._retn();
 }
@@ -2401,7 +2406,7 @@ GEOM::GEOM_IOperations_ptr GEOM_Gen_i::GetPluginOperations(CORBA::Long theStudyI
      throw ( SALOME::SALOME_Exception )
 {
   std::string aPlatformLibName;
-#ifdef WNT
+#ifdef WIN32
   aPlatformLibName = theLibName;
   aPlatformLibName += ".dll" ;
 #else
@@ -2425,7 +2430,7 @@ GEOM::GEOM_IOperations_ptr GEOM_Gen_i::GetPluginOperations(CORBA::Long theStudyI
       LibHandle libHandle = LoadLib( aPlatformLibName.c_str()/*theLibName*/ );
       if (!libHandle) {
         // report any error, if occured
-#ifndef WNT
+#ifndef WIN32
         const char* anError = dlerror();
         throw(SALOME_Exception(anError));
 #else
@@ -2879,6 +2884,489 @@ void GEOM_Gen_i::Move( const GEOM::object_list& what,
   }
 }
 
+//=================================================================================
+// function : importData
+// purpose  : imports geometrical data file into the GEOM internal data structure
+//=================================================================================
+Engines::ListOfIdentifiers* GEOM_Gen_i::importData(
+  CORBA::Long studyId, Engines::DataContainer_ptr data, const Engines::ListOfOptions& options)
+{
+  CORBA::Object_var aSMObject = name_service->Resolve( "/myStudyManager" );
+  SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow( aSMObject );
+  SALOMEDS::Study_var aStudy = aStudyManager->GetStudyByID( studyId );
+
+  Engines::ListOfIdentifiers_var aResult = new Engines::ListOfIdentifiers;
+  GEOM::GEOM_IInsertOperations_var aInsOp = GetIInsertOperations(aStudy->StudyId());
+  if (aInsOp->_is_nil()) {
+    MESSAGE("No insert operations!");
+    return aResult._retn();
+  }
+
+  // Get a temporary directory to store a file
+  std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
+  std::string aFileName("file");
+  if (aFileName.rfind("/") != std::string::npos) { // remove folders from the name
+    aFileName = aFileName.substr(aFileName.rfind("/") + 1);
+  }
+
+  std::string anExtension(data->extension());
+  aFileName += "." + anExtension;
+  // convert extension to upper case
+  std::transform(anExtension.begin(), anExtension.end(), anExtension.begin(), ::toupper);
+  std::string aFullPath = aTmpDir + aFileName;
+
+  Engines::TMPFile* aFileStream = data->get();
+  const char *aBuffer = (const char*)aFileStream->NP_data();
+#ifdef WIN32
+  std::ofstream aFile(aFullPath.c_str(), std::ios::binary);
+#else
+  std::ofstream aFile(aFullPath.c_str());
+#endif
+  aFile.write(aBuffer, aFileStream->length());
+  aFile.close();
+
+  GEOM::GEOM_Object_var aShapeObj;
+  GEOM::ListOfGO_var aSubShape = new GEOM::ListOfGO;
+  GEOM::ListOfGO_var aGroups = new GEOM::ListOfGO;
+  GEOM::ListOfFields_var aFields = new GEOM::ListOfFields;
+
+  CORBA::Boolean isResultOK = aInsOp->ImportXAO(aFullPath.c_str(), aShapeObj.out(), aSubShape.out(), aGroups.out(), aFields.out());
+
+  if ( isResultOK && !aShapeObj->_is_nil() && aInsOp->IsDone() ) {
+    SALOMEDS::SObject_var aSO = PublishInStudy(aStudy, SALOMEDS::SObject::_nil(), aShapeObj, aShapeObj->GetName());
+    aResult->length(aGroups->length() + 1);
+    aResult[0] = aSO->GetID(); // unioque identifer of the object in GEOM is entry of SObject
+    //Iteration for objects of the group.
+    for (int i = 0; i < aGroups->length(); i++) {
+      SALOMEDS::SObject_var aSOChild = AddInStudy(aStudy, aGroups[i], aGroups[i]->GetName(), aShapeObj);
+      aResult[i+1] = aSOChild->GetID();
+    }
+  }
+  else {
+    if (aShapeObj->_is_nil())
+      MESSAGE("Result of the import operation is incorrect for file "<<aFullPath.c_str());
+    if (!aInsOp->IsDone())
+      MESSAGE("Import operation is not done for file "<<aFullPath.c_str());
+    if (!isResultOK)
+      MESSAGE("ImportXAO operation is failed for file "<<aFullPath.c_str());
+    return aResult._retn();
+  }
+
+  // remove temporary file and directory
+  SALOMEDS::ListOfFileNames aTmpFiles;
+  aTmpFiles.length(1);
+  aTmpFiles[0] = aFileName.c_str();
+  SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir, aTmpFiles, true);
+
+  _impl->DocumentModified(studyId, false);
+  return aResult._retn();
+}
+
+//=================================================================================
+// function : getModifiedData
+// purpose  : exports all geometry of this GEOM module into one BRep file
+//=================================================================================
+Engines::ListOfData* GEOM_Gen_i::getModifiedData(CORBA::Long studyId)
+{
+  Engines::ListOfData_var aResult = new Engines::ListOfData;
+
+  if (!_impl->DocumentModified(studyId)) {
+    MESSAGE("Document is not modified")
+    return aResult._retn();
+  }
+
+  CORBA::Object_var aSMObject = name_service->Resolve("/myStudyManager");
+  SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow( aSMObject );
+  SALOMEDS::Study_var aStudy = aStudyManager->GetStudyByID( studyId );
+  SALOMEDS::SComponent_var aComponent = aStudy->FindComponent("GEOM");
+  if (CORBA::is_nil(aComponent))
+    return aResult._retn();
+  SALOMEDS::ChildIterator_var anIter = aStudy->NewChildIterator(aComponent); // check only published shapes
+
+  GEOM::GEOM_Object_var shapeObj;
+  GEOM::ListOfGO_var groups = new GEOM::ListOfGO;
+  GEOM::ListOfFields_var fields = new GEOM::ListOfFields;
+  std::string anAuthorName = "SIMAN Author";
+  
+  GEOM::GEOM_IShapesOperations_var  aShapesOp = GetIShapesOperations(aStudy->StudyId());
+  GEOM::GEOM_IInsertOperations_var aInsOp = GetIInsertOperations(aStudy->StudyId());
+
+  int aSeqLength = 0; // the sequence length
+  for(; anIter->More(); anIter->Next()) {
+    SALOMEDS::SObject_var aSO = anIter->Value();
+    SALOMEDS::SObject_var aRefSO;
+    // export only not referenced objects, or referenced outside of GEOM
+    if (!aSO->ReferencedObject(aRefSO) || aRefSO->GetFatherComponent()->GetID() != aComponent->GetID()) {
+      CORBA::Object_var anObj = aSO->GetObject();
+      if (!CORBA::is_nil(anObj)) {
+        GEOM::GEOM_Object_var aCORBAMainShape = GEOM::GEOM_Object::_narrow(anObj);
+        if(!aCORBAMainShape->_is_nil()) {
+          CORBA::String_var entry = aCORBAMainShape->GetEntry();
+          Handle(GEOM_Object) aMainShape = Handle(GEOM_Object)::DownCast(_impl->GetObject(studyId, entry));
+
+          GEOM::shape_type aCORBAShapeType = aCORBAMainShape->GetShapeType();
+          if (!aMainShape.IsNull() && !(aCORBAShapeType == GEOM::VERTEX) && !(aCORBAShapeType == GEOM::EDGE)) {
+            aSeqLength++;
+            shapeObj = aCORBAMainShape;
+            if (aShapesOp->_is_nil()) {
+              MESSAGE("No shapes operations!");
+              return aResult._retn();
+            }
+            groups = aShapesOp->GetExistingSubObjects(aCORBAMainShape, true);
+            break;
+          }
+        }
+      }
+    }
+  }
+
+  if (aInsOp->_is_nil()) {
+    MESSAGE("No insert operations!");
+    return aResult._retn();
+  }
+
+  if (aSeqLength > 0) { // Shape is correct, write it to the temporary file
+
+    std::string aFullXaoPath = Kernel_Utils::GetTmpFileName() + ".xao";
+    CORBA::Boolean isResultOK = aInsOp->ExportXAO(shapeObj.in(), groups.in(), fields.in(), anAuthorName.c_str(), aFullXaoPath.c_str());
+
+    aResult->length(1);
+    Engines::DataContainer_var aData = (new Engines_DataContainer_i(
+                    aFullXaoPath.c_str(), "", "", true))->_this();
+    aResult[0] = aData;
+  } else {
+    MESSAGE("No shapes to export");
+  }
+
+  return aResult._retn();
+}
+                                                               
+//=======================================================================
+// function : GetDependencyTree
+// purpose  : Collects dependencies of the given objects from other ones
+//=======================================================================
+SALOMEDS::TMPFile* GEOM_Gen_i::GetDependencyTree( SALOMEDS::Study_ptr theStudy,
+                                                 const GEOM::string_array& theObjectEntries ) {
+  // fill in the tree structure
+  GEOMUtils::TreeModel tree;
+
+  std::string entry;
+  for ( int i = 0; i < theObjectEntries.length(); i++ ) {
+    // process objects one-by-one
+    entry = theObjectEntries[i].in();
+    GEOM::GEOM_BaseObject_var anObj = GetObject( theStudy->StudyId(), entry.c_str() );
+    if ( anObj->_is_nil() )
+      continue;
+    std::map< std::string, std::set<std::string> > passedEntries;
+    GEOMUtils::LevelsList upLevelList;
+    // get objects from which current one depends on recursively
+    getUpwardDependency( anObj, upLevelList, passedEntries );
+    GEOMUtils::LevelsList downLevelList;
+    // get objects that depends on current one recursively
+    getDownwardDependency( anObj, downLevelList, passedEntries );
+    tree.insert( std::pair<std::string, std::pair<GEOMUtils::LevelsList,GEOMUtils::LevelsList> >(entry, std::pair<GEOMUtils::LevelsList,GEOMUtils::LevelsList>( upLevelList, downLevelList ) ) );
+  }
+
+  // translation the tree into string
+  std::string treeStr;
+  GEOMUtils::ConvertTreeToString( tree, treeStr );
+  
+  // put string into stream
+  char* aBuffer = (char*)CORBA::string_dup(treeStr.c_str());
+  int aBufferSize = strlen((char*)aBuffer);
+
+  CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
+
+  SALOMEDS::TMPFile_var aStream = new SALOMEDS::TMPFile(aBufferSize, aBufferSize, anOctetBuf, 1);
+
+  return aStream._retn();
+}
+
+//=======================================================================
+// function : getUpwardDependency
+// purpose  : Collects the entries of objects on that the given one depends
+//=======================================================================
+void GEOM_Gen_i::getUpwardDependency( GEOM::GEOM_BaseObject_ptr gbo, 
+                                     GEOMUtils::LevelsList &upLevelList, 
+                                     std::map< std::string, std::set<std::string> > &passedEntries,
+                                     int level ) {
+  std::string aGboEntry = gbo->GetEntry();
+  GEOMUtils::NodeLinks anEntries;
+  GEOMUtils::LevelInfo aLevelMap;
+  if ( level > 0 ) {
+    if ( level-1 >= upLevelList.size() ) {
+      // create a new map
+      upLevelList.push_back( aLevelMap );
+    } else {
+      // get the existent map
+      aLevelMap = upLevelList.at(level-1);
+      if ( aLevelMap.count( aGboEntry ) > 0 ) {
+       anEntries = aLevelMap[ aGboEntry ];
+      }
+    }
+  }
+  // get objects on that the current one depends
+  GEOM::ListOfGBO_var depList = gbo->GetDependency();
+  std::string aDepEntry;
+  for( int j = 0; j < depList->length(); j++ ) {
+    if ( depList[j]->_is_nil() )
+      continue;
+    aDepEntry = depList[j]->GetEntry();
+    if ( passedEntries.count( aGboEntry ) > 0 && 
+         passedEntries[aGboEntry].count( aDepEntry ) > 0 ) {
+      //avoid checking the passed objects
+      continue;
+    }
+    passedEntries[aGboEntry].insert( aDepEntry );
+    if ( level > 0 ) {
+      anEntries.push_back( aDepEntry );
+    }
+    // get dependencies recursively
+    getUpwardDependency(depList[j], upLevelList, passedEntries, level+1);
+  }
+  if ( level > 0 ) {
+    aLevelMap.insert( std::pair<std::string, GEOMUtils::NodeLinks>(aGboEntry, anEntries) );
+    upLevelList[level-1] = aLevelMap;
+  }
+}
+
+//=======================================================================
+// function : getDownwardDependency
+// purpose  : Collects the entries of objects that depends on the given one
+//=======================================================================
+void GEOM_Gen_i::getDownwardDependency( GEOM::GEOM_BaseObject_ptr gbo, 
+                                       GEOMUtils::LevelsList &downLevelList, 
+                                       std::map< std::string, std::set<std::string> > &passedEntries,
+                                       int level ) {
+  std::string aGboEntry = gbo->GetEntry();
+  Handle(TDocStd_Document) aDoc = GEOM_Engine::GetEngine()->GetDocument(gbo->GetStudyID());
+  Handle(TDataStd_TreeNode) aNode, aRoot;
+  Handle(GEOM_Function) aFunction;
+  if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
+    // go through the whole OCAF tree
+    TDataStd_ChildNodeIterator Itr( aRoot );
+    for (; Itr.More(); Itr.Next()) {
+      aNode = Itr.Value();
+      aFunction = GEOM_Function::GetFunction(aNode->Label());
+      if (aFunction.IsNull()) {
+        continue;
+      }
+      TDF_Label aLabel  = aFunction->GetOwnerEntry();
+      if(aLabel.IsNull()) continue;
+      TCollection_AsciiString anEntry;
+      TDF_Tool::Entry(aLabel, anEntry);
+      GEOM::GEOM_BaseObject_var geomObj = GetObject( gbo->GetStudyID(), anEntry.ToCString() );
+      if( CORBA::is_nil( geomObj ) )
+        continue;
+      // get dependencies for current object in the tree
+      GEOM::ListOfGBO_var depList = geomObj->GetDependency();
+      if( depList->length() == 0 )
+        continue;
+      std::string aGoEntry = geomObj->GetEntry();
+      // go through dependencies of current object to check whether it depends on the given object
+      for( int i = 0; i < depList->length(); i++ ) {
+        if ( depList[i]->_is_nil() )
+          continue;
+        if ( depList[i]->_is_equivalent( gbo ) ) {
+          // yes, the current object depends on the given object
+          if ( passedEntries.count( aGoEntry ) > 0 && 
+               passedEntries[aGoEntry].count( aGboEntry ) > 0 ) {
+            //avoid checking the passed objects
+            continue;
+          }
+          passedEntries[aGoEntry].insert( aGboEntry );
+          GEOMUtils::NodeLinks anEntries;
+          GEOMUtils::LevelInfo aLevelMap;
+          anEntries.push_back( aGboEntry );
+          if ( level >= downLevelList.size() ) {
+            downLevelList.push_back( aLevelMap );
+          } else {
+            aLevelMap = downLevelList.at(level);
+            if ( aLevelMap.count( aGoEntry ) > 0 ) {
+              anEntries = aLevelMap[ aGoEntry ];
+            }
+          }
+          aLevelMap.insert( std::pair<std::string, GEOMUtils::NodeLinks>(aGoEntry, anEntries) );
+          downLevelList[level] = aLevelMap;
+          // get dependencies of the current object recursively
+          getDownwardDependency(geomObj, downLevelList, passedEntries, level+1);
+          break;
+        }
+      }
+    }
+  }
+}
+
+//==============================================================================
+// function : GetEntriesToCleanStudy
+// purpose  : Fills 3 lists that is used to clean study of redundant objects
+//==============================================================================
+void GEOM_Gen_i::GetEntriesToCleanStudy(SALOMEDS::Study_ptr theStudy,
+                                       GEOM::string_array& theSelectedEntries,
+                                       GEOM::string_array& theParentEntries,
+                                       GEOM::string_array& theSubEntries,
+                                       GEOM::string_array& theOtherEntries)
+{
+  std::set<std::string> aSelected, aParents, aChildren, anOthers;
+  for ( int i = 0; i < theSelectedEntries.length(); i++ ) {
+    aSelected.insert( CORBA::string_dup( theSelectedEntries[i] ) );
+  }
+
+  Handle(TDocStd_Document) aDoc = GEOM_Engine::GetEngine()->GetDocument(theStudy->StudyId());
+  Handle(TDataStd_TreeNode) aNode, aRoot;
+  Handle(GEOM_Function) aFunction;
+  if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
+    // go through the whole OCAF tree
+    TDF_Label aLabel;
+    std::string anEntry;
+    TCollection_AsciiString anAsciiEntry;
+    TDataStd_ChildNodeIterator Itr( aRoot );
+    for (; Itr.More(); Itr.Next()) {
+      aNode = Itr.Value();
+      aFunction = GEOM_Function::GetFunction(aNode->Label());
+      if (aFunction.IsNull()) {
+        continue;
+      }
+      aLabel = aFunction->GetOwnerEntry();
+      if(aLabel.IsNull())
+        continue;
+      TDF_Tool::Entry(aLabel, anAsciiEntry);
+      anEntry = anAsciiEntry.ToCString();
+      GEOM::GEOM_BaseObject_var geomObj = GetObject( theStudy->StudyId(), anEntry.c_str() );
+      if( CORBA::is_nil( geomObj ) )
+        continue;
+
+      if ( aSelected.count( anEntry ) > 0 &&
+           aParents.count( anEntry ) == 0 ) {
+        getParentDependencies( geomObj, aSelected, aParents, aChildren, anOthers );
+      } else if ( aParents.count( anEntry ) == 0 && 
+                  aChildren.count( anEntry ) == 0 ) {
+        anOthers.insert( geomObj->GetEntry() );
+      }
+    }
+
+    std::set<std::string>::iterator it;
+    std::set<std::string>::iterator foundIt;
+    TCollection_AsciiString stringIOR;
+    GEOM::GEOM_Object_var geomObj;
+
+    // filling list of sub-objects
+    for ( it = aSelected.begin(); it != aSelected.end(); ++it ) {
+      Handle(GEOM_BaseObject) handle_object = _impl->GetObject( theStudy->StudyId(), (*it).c_str(), false);
+      if ( handle_object.IsNull() )
+        continue;
+
+      Handle(GEOM_Function) aShapeFun = handle_object->GetFunction(1);
+      if ( aShapeFun.IsNull() || !aShapeFun->HasSubShapeReferences() )
+        continue;
+
+      const TDataStd_ListOfExtendedString& aListEntries = aShapeFun->GetSubShapeReferences();
+      if ( aListEntries.IsEmpty() )
+        continue;
+
+      TDataStd_ListIteratorOfListOfExtendedString anIt (aListEntries);
+      for ( ; anIt.More(); anIt.Next() ) {
+        TCollection_ExtendedString aSubEntry = anIt.Value();
+        Standard_Integer aStrLen = aSubEntry.LengthOfCString();
+        char* aSubEntryStr = new char[aStrLen+1];
+        aSubEntry.ToUTF8CString( aSubEntryStr );
+        foundIt = aParents.find( aSubEntryStr );
+        if ( foundIt == aParents.end() ) { // add to sub-objects if it is not in parents list
+          aChildren.insert( aSubEntryStr );
+          foundIt = anOthers.find( aSubEntryStr );
+          if ( foundIt != anOthers.end() )
+            anOthers.erase( foundIt );
+        }
+      }
+    }
+
+    // if some selected object is not a main shape,
+    // we move it's main shapes into 'selected' list, 
+    // because they could not be modified anyhow.
+    std::set<std::string> aToBeInSelected;
+    for ( it = aSelected.begin(); it != aSelected.end(); ++it ) {
+      Handle(GEOM_BaseObject) handle_object = _impl->GetObject( theStudy->StudyId(), (*it).c_str(), false);
+      if ( handle_object.IsNull() )
+        continue;
+
+      stringIOR = handle_object->GetIOR();
+      if ( !stringIOR.Length() > 1 )
+        continue;
+
+      geomObj = GetIORFromString( stringIOR.ToCString() );
+      while ( !geomObj->IsMainShape() ) {
+        geomObj = geomObj->GetMainShape();
+        anEntry = geomObj->GetEntry();
+
+        foundIt = aParents.find( anEntry );
+        if ( foundIt != aParents.end() )
+          aParents.erase( foundIt );
+
+        foundIt = aChildren.find( anEntry );
+        if ( foundIt != aChildren.end() )
+          aChildren.erase( foundIt );
+
+        foundIt = anOthers.find( anEntry );
+        if ( foundIt != anOthers.end() )
+          anOthers.erase( foundIt );
+
+        aToBeInSelected.insert( anEntry );
+      }
+    }
+    aSelected.insert( aToBeInSelected.begin(), aToBeInSelected.end() );
+
+    // fill the CORBA arrays with values from sets
+    int i;
+    theSelectedEntries.length( aSelected.size() );
+    for ( i = 0, it = aSelected.begin(); it != aSelected.end(); ++it, i++ )
+      theSelectedEntries[i]  = CORBA::string_dup( (*it).c_str() );
+    theParentEntries.length( aParents.size() );
+    for ( i = 0, it = aParents.begin(); it != aParents.end(); ++it, i++ )
+      theParentEntries[i]  = CORBA::string_dup( (*it).c_str() );
+    theSubEntries.length( aChildren.size() );
+    for ( i = 0, it = aChildren.begin(); it != aChildren.end(); ++it, i++ )
+      theSubEntries[i]  = CORBA::string_dup( (*it).c_str() );
+    theOtherEntries.length( anOthers.size() );
+    for ( i = 0, it = anOthers.begin(); it != anOthers.end(); ++it, i++ )
+      theOtherEntries[i]  = CORBA::string_dup( (*it).c_str() );
+  }
+}
+
+void GEOM_Gen_i::getParentDependencies(GEOM::GEOM_BaseObject_ptr geomObj,
+                                      std::set<std::string>& aSelected,
+                                      std::set<std::string>& aParents,
+                                      std::set<std::string>& aChildren,
+                                      std::set<std::string>& anOthers)
+{
+  std::string anEntry = geomObj->GetEntry();
+  if ( aSelected.count( anEntry ) == 0 ) {
+    aParents.insert( anEntry );
+    std::set<std::string>::iterator it;
+    it = aChildren.find( anEntry );
+    if ( it != aChildren.end() )
+      aChildren.erase( it );
+    it = anOthers.find( anEntry );
+    if ( it != anOthers.end() )
+      anOthers.erase( it );
+  }
+  // get dependencies for current object in the tree
+  GEOM::ListOfGBO_var depList = geomObj->GetDependency();
+  if( depList->length() == 0 )
+    return;
+  // go through dependencies of current object to check whether it depends on the given object
+  std::string aDepEntry;
+  for( int i = 0; i < depList->length(); i++ ) {
+    aDepEntry = depList[i]->GetEntry();
+    if ( depList[i]->_is_nil() ||
+        aDepEntry == anEntry ||             // skip self-depending
+        aSelected.count( aDepEntry ) > 0 || // skip selected objects
+        aParents.count( aDepEntry ) > 0     // skip already processed objects
+        )
+      continue;
+    getParentDependencies( depList[i], aSelected, aParents, aChildren, anOthers );
+  }
+}
+
 //=====================================================================================
 // EXPORTED METHODS
 //=====================================================================================