Salome HOME
Dump Python extension.
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
index 2475cce34c953459e64ac8556087ffd52a0e5f31..73b3154143554b2e4f6cd8d3a6b50ed4aa3a14f9 100644 (file)
@@ -49,6 +49,7 @@
 #include <TColStd_MapOfTransient.hxx>
 #include <TColStd_HSequenceOfInteger.hxx>
 
+
 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
 
 #include <Standard_Failure.hxx>
 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
 
+#define COMMA ','
+#define O_BRACKET '('
+#define C_BRACKET ')'
+
+#ifdef _DEBUG_
+static int MYDEBUG = 0;
+#else
+static int MYDEBUG = 0;
+#endif
+
 static GEOM_Engine* TheEngine = NULL;
 
 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
@@ -84,10 +95,19 @@ static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
 
 void ProcessFunction(Handle(GEOM_Function)& theFunction, 
                     TCollection_AsciiString& theScript,
+                     Resource_DataMapOfAsciiStringAsciiString& theVariableNames,
+                     TColStd_HSequenceOfAsciiString& theStudyVariables,
                     TColStd_MapOfTransient& theProcessed);
 
+void ReplaceVariables(TCollection_AsciiString& theCommand, 
+                      Resource_DataMapOfAsciiStringAsciiString& theVariableNames,
+                      TColStd_HSequenceOfAsciiString& theStudyVariables);
+
+
+
 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
 
+
 //=============================================================================
 /*!
  *  GetEngine
@@ -116,6 +136,25 @@ GEOM_Engine::GEOM_Engine()
   _UndoLimit = 10;
 }
 
+/*!
+ *  Destructor
+ */
+GEOM_Engine::~GEOM_Engine()
+{ 
+  GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
+  for(; It.More(); It.Next()) 
+    {
+      RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
+    }
+
+  //Close all documents not closed
+  for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
+    Close(anItr.Key());
+
+  _mapIDDocument.Clear();
+  _objects.Clear();
+}
+
 //=============================================================================
 /*!
  *  GetDocument
@@ -176,18 +215,33 @@ Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
 //=============================================================================
 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
 {
-    Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
-    Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
+  Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
+  Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
 
-    TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
-    Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
+  // NPAL18604: use existing label to decrease memory usage,
+  //            if this label has been freed (object deleted)
+  bool useExisting = false;
+  TDF_Label aChild;
+  if (!_lastCleared.IsNull()) {
+    if (_lastCleared.Root() == aDoc->Main().Root()) {
+      useExisting = true;
+      aChild = _lastCleared;
+      _lastCleared.Nullify();
+    }
+  }
+  if (!useExisting) {
+    // create new label
+    aChild = TDF_TagSource::NewChild(aDoc->Main());
+  }
 
-    //Put an object in the map of created objects
-    TCollection_AsciiString anID = BuildIDFromObject(anObject);
-    if(_objects.IsBound(anID)) _objects.UnBind(anID);
-    _objects.Bind(anID, anObject);
+  Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
 
-    return anObject;
+  //Put an object in the map of created objects
+  TCollection_AsciiString anID = BuildIDFromObject(anObject);
+  if(_objects.IsBound(anID)) _objects.UnBind(anID);
+  _objects.Bind(anID, anObject);
+
+  return anObject;
 }
 
 //=============================================================================
@@ -204,7 +258,21 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
 
-  TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
+  // NPAL18604: use existing label to decrease memory usage,
+  //            if this label has been freed (object deleted)
+  bool useExisting = false;
+  TDF_Label aChild;
+  if (!_lastCleared.IsNull()) {
+    if (_lastCleared.Root() == aDoc->Main().Root()) {
+      useExisting = true;
+      aChild = _lastCleared;
+      _lastCleared.Nullify();
+    }
+  }
+  if (!useExisting) {
+    // create new label
+    aChild = TDF_TagSource::NewChild(aDoc->Main());
+  }
 
   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
@@ -258,22 +326,23 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
 //=============================================================================
 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
 {
-  if(!theObject) return false;
+  if (!theObject) return false;
 
   //Remove an object from the map of available objects
   TCollection_AsciiString anID = BuildIDFromObject(theObject);
-  if(_objects.IsBound(anID)) _objects.UnBind(anID);
+  if (_objects.IsBound(anID)) _objects.UnBind(anID);
 
   int nb = theObject->GetNbFunctions();
   Handle(TDataStd_TreeNode) aNode;
-  for(int i = 1; i<=nb; i++) {
+  for (int i = 1; i<=nb; i++) {
     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
-    if(aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode)) 
+    if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode)) 
       aNode->Remove();
   }
 
   TDF_Label aLabel = theObject->GetEntry();
   aLabel.ForgetAllAttributes(Standard_True);
+  _lastCleared = aLabel;
 
   theObject.Nullify();
 
@@ -344,20 +413,22 @@ bool GEOM_Engine::Load(int theDocID, char* theFileName)
 //=============================================================================
 void GEOM_Engine::Close(int theDocID)
 {
-  if(_mapIDDocument.IsBound(theDocID)) {
+  if (_mapIDDocument.IsBound(theDocID)) {
     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
 
     //Remove all GEOM Objects associated to the given document
     TColStd_SequenceOfAsciiString aSeq;
-    GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
-    for(; It.More(); It.Next()) {
-      TCollection_AsciiString anObjID(It.Key());
+    GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
+    for (; It.More(); It.Next()) {
+      TCollection_AsciiString anObjID (It.Key());
       Standard_Integer anID = ExtractDocID(anObjID);
-      if(theDocID == anID) aSeq.Append(It.Key());
+      if (theDocID == anID) aSeq.Append(It.Key());
     }
-    for(Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
+    for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
+
+    _lastCleared.Nullify();
 
-   _mapIDDocument.UnBind(theDocID);
+    _mapIDDocument.UnBind(theDocID);
     _OCAFApp->Close(aDoc);
     aDoc.Nullify();
   }
@@ -368,37 +439,40 @@ void GEOM_Engine::Close(int theDocID)
  *  DumpPython
  */
 //=============================================================================
-TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID, 
+TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
                                                Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
-                                               bool isPublished, 
+                                               Resource_DataMapOfAsciiStringAsciiString& theVariableNames,
+                                                TColStd_HSequenceOfAsciiString& theStudyVariables,
+                                               bool isPublished,
                                                bool& aValidScript)
 {
   TCollection_AsciiString aScript;
   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
-  
-  if(aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
+
+  if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
+
   aScript = "import geompy\n";
-  aScript += "import math\n\n";
+  aScript += "import math\n";
+  aScript += "import SALOMEDS\n\n";
   aScript += "def RebuildData(theStudy):";
   aScript += "\n\tgeompy.init_geom(theStudy)";
-  
+
   Standard_Integer posToInertGlobalVars = aScript.Length() + 1;
 
   Handle(TDataStd_TreeNode) aNode, aRoot;
   Handle(GEOM_Function) aFunction;
   TColStd_MapOfTransient aMap;
 
-  if(aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
+  if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
     TDataStd_ChildNodeIterator Itr(aRoot);
-    for(; Itr.More(); Itr.Next()) {
+    for (; Itr.More(); Itr.Next()) {
       aNode = Itr.Value();
       aFunction = GEOM_Function::GetFunction(aNode->Label());
-      if(aFunction.IsNull()) {
-       cout << "Null function !!!!" << endl;
+      if (aFunction.IsNull()) {
+       MESSAGE ( "Null function !!!!" );
        continue;
       }
-      ProcessFunction(aFunction, aScript, aMap);
+      ProcessFunction(aFunction, aScript, theVariableNames, theStudyVariables ,aMap);
     }
   }
 
@@ -430,12 +504,12 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
   //Replace entries by the names
   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
-  if(aLen == 0) anUpdatedScript = aScript;
+  if (aLen == 0) anUpdatedScript = aScript;
 
-  for(Standard_Integer i = 1; i <= aLen; i+=2) {
+  for (Standard_Integer i = 1; i <= aLen; i+=2) {
     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
-    if(theObjectNames.IsBound(anEntry)) {
+    if (theObjectNames.IsBound(anEntry)) {
       aName = theObjectNames.Find(anEntry);
       // check validity of aName
       bool isValidName = true;
@@ -478,12 +552,47 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
   }
 
   //Add final part of the script
-  if(aLen && aSeq->Value(aLen) < aScriptLength)  anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
+  if (aLen && aSeq->Value(aLen) < aScriptLength)
+    anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
+
+  // ouv : NPAL12872
+  for (anEntryToNameIt.Initialize( theObjectNames );
+       anEntryToNameIt.More();
+       anEntryToNameIt.Next())
+  {
+    const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
+    const TCollection_AsciiString& aName = anEntryToNameIt.Value();
+
+    TDF_Label L;
+    TDF_Tool::Label( aDoc->GetData(), aEntry, L );
+    if ( L.IsNull() )
+      continue;
+
+    Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
+    if ( obj.IsNull() )
+      continue;
+
+    bool anAutoColor = obj->GetAutoColor();
+    if ( anAutoColor )
+    {
+      TCollection_AsciiString aCommand( "\n\t" );
+      aCommand += aName + ".SetAutoColor(1)";
+      anUpdatedScript += aCommand.ToCString();
+    }
+
+    SALOMEDS::Color aColor = obj->GetColor();
+    if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
+    {
+      TCollection_AsciiString aCommand( "\n\t" );
+      aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
+      anUpdatedScript += aCommand.ToCString();
+    }
+  }
+
   // Make script to publish in study
   if ( isPublished )
   {
-    map< int, string > anEntryToCommandMap; // sort publishing commands by object entry
+    std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
     for (anEntryToNameIt.Initialize( theObjectNames );
          anEntryToNameIt.More();
          anEntryToNameIt.Next())
@@ -516,17 +625,18 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
       // bind a command to the last digit of the entry
       int tag =
         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
-      anEntryToCommandMap.insert( make_pair( tag, aCommand.ToCString() ));
+      anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
     }
 
     // add publishing commands to the script
-    map< int, string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
+    std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
     }
   }
 
-  anUpdatedScript += "\n\tpass\n";
+  //anUpdatedScript += "\n\tpass\n";
+  anUpdatedScript += "\n";
   aValidScript = true;
 
   // fill _studyEntry2NameMap and build globalVars
@@ -547,7 +657,7 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
     globalVars.Insert( 1, "\n\tglobal " );
     anUpdatedScript.Insert( posToInertGlobalVars, globalVars );
   }
-  
+
   return anUpdatedScript;
 }
 
@@ -587,6 +697,8 @@ Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
 //===========================================================================
 void ProcessFunction(Handle(GEOM_Function)& theFunction, 
                     TCollection_AsciiString& theScript,
+                     Resource_DataMapOfAsciiStringAsciiString& theVariableNames,
+                     TColStd_HSequenceOfAsciiString& theStudyVariables,
                     TColStd_MapOfTransient& theProcessed)
 {
   if(theFunction.IsNull() || theProcessed.Contains(theFunction)) return;
@@ -610,8 +722,11 @@ void ProcessFunction(Handle(GEOM_Function)& theFunction,
   //Check if its internal function which doesn't requires dumping
   if(aDescr == "None") return;
 
+  //Replace parameter by notebook variables
+  ReplaceVariables(aDescr,theVariableNames,theStudyVariables);
   theScript += "\n\t";
   theScript += aDescr;
+
  
   theProcessed.Add(theFunction);
   return;
@@ -628,7 +743,7 @@ Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theStrin
   Standard_Integer aLen = theString.Length();
   Standard_Boolean isFound = Standard_False;
 
-  char* arr = theString.ToCString();
+  const char* arr = theString.ToCString();
   Standard_Integer i = 0, j;
 
   while(i < aLen) {
@@ -653,3 +768,144 @@ Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theStrin
 
   return aSeq;
 }
+
+//=============================================================================
+/*!
+ *  ReplaceVariables: Replace parameters of the function by variales from 
+ *                    Notebook if need
+ */
+//=============================================================================
+void ReplaceVariables(TCollection_AsciiString& theCommand, 
+                      Resource_DataMapOfAsciiStringAsciiString& theVariableNames,
+                      TColStd_HSequenceOfAsciiString& theStudyVariables)
+{
+  //Get Entry of the result object
+  TCollection_AsciiString anEntry = theCommand.Token("=",1);
+
+  //Remove white spaces
+  anEntry.RightAdjust();
+  anEntry.LeftAdjust();
+  if(MYDEBUG)
+    cout<<"Result entry : '" <<anEntry<<"'"<<endl;
+    
+  //Find variables used for object construction
+  TCollection_AsciiString aVariables;
+  if(theVariableNames.IsBound(anEntry)) 
+    aVariables = theVariableNames.Find(anEntry);
+
+  if(aVariables.IsEmpty()) {
+    if(MYDEBUG)
+      cout<<"Valiables list empty!!!"<<endl;
+    return;
+  }
+
+  if(MYDEBUG)
+    cout<<"Variables : '" <<aVariables<<"'"<<endl;
+
+  //Calculate number of variables, that mast be replaced
+  Standard_Integer aNbReplacedParams = 1,aPos;
+  TColStd_HSequenceOfInteger aPositions;
+  while(aPos = aVariables.Location(aNbReplacedParams,':',1,aVariables.Length())) {
+    aPositions.Append(aPos);
+    aNbReplacedParams++;
+  }
+
+  if(MYDEBUG)
+    cout<<"Number of replaced variables : " <<aNbReplacedParams<<endl;
+
+  if(MYDEBUG)
+    {
+      for(Standard_Integer i = 1;i<=aPositions.Length();i++)
+        cout<<"Positions ["<<i<<"] = "<<aPositions.Value(i)<<endl;
+    }
+
+  //Calculate total number of parameter
+  Standard_Integer aTotalNbParams = 1;
+  while(theCommand.Location(aTotalNbParams,COMMA,1,theCommand.Length()))
+    aTotalNbParams++;
+
+
+  if(MYDEBUG)
+    cout<<"Total Number of parameters : " <<aTotalNbParams<<endl;
+
+  //Get Variables names 
+  TColStd_SequenceOfAsciiString aVarSeq;
+  TCollection_AsciiString aVar;
+  Standard_Integer i = 1;
+  while(i <= aNbReplacedParams){
+    
+    if(i == 1)
+      aVar = (aPositions.Value(i) == 1) ? TCollection_AsciiString() : aVariables.SubString(1, aPositions.Value(i)-1);
+    else if(i == aNbReplacedParams) {
+      Standard_Integer aLen = aVariables.Length();
+      Standard_Integer aPos = aPositions.Value(i-1);
+      aVar = (aPos == aLen) ? TCollection_AsciiString() : aVariables.SubString(aPos+1, aLen);
+    }
+    else {
+      Standard_Integer aPrevPos = aPositions.Value(i-1);
+      Standard_Integer aCurrentPos = aPositions.Value(i);
+      aVar = (aCurrentPos - aPrevPos == 1) ? TCollection_AsciiString() : aVariables.SubString(aPrevPos+1, aCurrentPos-1);
+    }
+    if(MYDEBUG)
+      cout<<"Variable ["<<i<<"] = '"<<aVar<<"'"<<endl;
+    
+    //Add current varibale
+    aVarSeq.Append(aVar);
+    i++;
+  }
+
+  //Replace parameters by variables
+  Standard_Integer aStartPos = 0;
+  Standard_Integer aEndPos = 0;
+  Standard_Integer iVar = 1;
+  for(Standard_Integer i=1;i <= aTotalNbParams;i++) {
+        
+    //Replace first parameter (bettwen '(' character and first ',' character)
+    if(i == 1) 
+      {
+        aStartPos = theCommand.Location(O_BRACKET, 1, theCommand.Length()) + 1;
+        aEndPos = theCommand.Location(COMMA, 1, theCommand.Length());
+      }
+    //Replace last parameter (bettwen ',' character and ')' character)
+    else if(i == aVarSeq.Length())
+      {
+        aStartPos = theCommand.Location(i-1, COMMA, 1, theCommand.Length()) + 2;
+        aEndPos = theCommand.Location(C_BRACKET, 1, theCommand.Length());
+      }
+    //Replace other parameters (bettwen two ',' characters)
+    else if(i != 1 && i != aVarSeq.Length())
+      {
+        aStartPos = theCommand.Location(i-1, COMMA, 1, theCommand.Length()) + 2;
+        aEndPos = theCommand.Location(i, COMMA, 1, theCommand.Length());
+      }
+
+    aVar = aVarSeq.Value(iVar);
+    
+    //If parameter is entry, skip it
+    aVar.RightAdjust();
+    aVar.LeftAdjust();
+    if(theVariableNames.IsBound(aVar))
+      continue;
+
+      
+    if(aVar.IsEmpty()) {
+      iVar++;
+      continue;
+    }
+
+    bool isVar = false;
+    for(Standard_Integer i = 1; i <= theStudyVariables.Length();i++)
+      if(theStudyVariables.Value(i).IsEqual(aVar)) {
+        isVar = true;
+        break;
+      }
+    if(isVar) {
+      aVar.InsertBefore(1,"\"");
+      aVar.InsertAfter(aVar.Length(),"\"");
+    }
+
+    theCommand.Remove(aStartPos, aEndPos - aStartPos);
+    theCommand.Insert(aStartPos,aVar);    
+    iVar++;
+  }
+}