Back to index

salome-geom  6.5.0
GEOM_Engine.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00004 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00005 //
00006 // This library is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 2.1 of the License.
00010 //
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 // Lesser General Public License for more details.
00015 //
00016 // You should have received a copy of the GNU Lesser General Public
00017 // License along with this library; if not, write to the Free Software
00018 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00019 //
00020 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00021 //
00022 
00023 #ifdef WNT
00024 #pragma warning( disable:4786 )
00025 #endif
00026 
00027 #include "GEOM_Engine.hxx"
00028 
00029 #include "GEOM_Solver.hxx"
00030 #include "GEOM_Function.hxx"
00031 #include "GEOM_ISubShape.hxx"
00032 #include "GEOM_SubShapeDriver.hxx"
00033 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
00034 #include "GEOM_PythonDump.hxx"
00035 
00036 #include <Basics_OCCTVersion.hxx>
00037 
00038 #include "utilities.h"
00039 
00040 #include <Basics_Utils.hxx>
00041 
00042 #include <TDF_Tool.hxx>
00043 #include <TDF_Data.hxx>
00044 #include <TDF_Reference.hxx>
00045 #include <TDF_LabelSequence.hxx>
00046 #include <TDataStd_Integer.hxx>
00047 #include <TDataStd_ChildNodeIterator.hxx>
00048 #include <TFunction_Driver.hxx>
00049 #include <TFunction_DriverTable.hxx>
00050 #include <TDataStd_ByteArray.hxx>
00051 #include <TDataStd_UAttribute.hxx>
00052 #include <TDF_ChildIterator.hxx>
00053 #include <TDataStd_Comment.hxx>
00054 
00055 #include <TopExp.hxx>
00056 #include <TopTools_IndexedMapOfShape.hxx>
00057 
00058 #include <TCollection_AsciiString.hxx>
00059 #include <TCollection_ExtendedString.hxx>
00060 #include <TColStd_SequenceOfAsciiString.hxx>
00061 #include <TColStd_MapOfTransient.hxx>
00062 #include <TColStd_HSequenceOfInteger.hxx>
00063 
00064 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00065 #include <TColStd_HArray1OfByte.hxx>
00066 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
00067 #else
00068 #include <TDataStd_HArray1OfByte.hxx>
00069 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
00070 #endif
00071 
00072 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
00073 
00074 #include <set>
00075 
00076 #include <Standard_Failure.hxx>
00077 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
00078 
00079 #define COMMA ','
00080 #define O_BRACKET '('
00081 #define C_BRACKET ')'
00082 #define O_SQR_BRACKET '['
00083 #define C_SQR_BRACKET ']'
00084 #define PY_NULL "None"
00085 
00086 #ifdef _DEBUG_
00087 static int MYDEBUG = 0;
00088 #else
00089 static int MYDEBUG = 0;
00090 #endif
00091 
00092 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
00093 typedef std::map< TCollection_AsciiString, TObjectData >             TSting2ObjDataMap;
00094 typedef std::map< TCollection_AsciiString, TObjectData* >            TSting2ObjDataPtrMap;
00095 
00096 static GEOM_Engine* TheEngine = NULL;
00097 
00098 
00099 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
00100 {
00101   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
00102   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
00103   anID+=(TCollection_AsciiString("_")+anEntry);
00104   return anID;
00105 }
00106 
00107 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
00108 {
00109   TCollection_AsciiString anID(theDocID);
00110   anID+=(TCollection_AsciiString("_")+theEntry);
00111   return anID;
00112 }
00113 
00114 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
00115 {
00116   TCollection_AsciiString aDocID = theID.Token("_");
00117   if(aDocID.Length() < 1) return -1;
00118   return aDocID.IntegerValue();
00119 }
00120 
00121 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
00122                      TCollection_AsciiString&           theScript,
00123                      TCollection_AsciiString&           theAfterScript,
00124                      const TVariablesList&              theVariables,
00125                      const bool                         theIsPublished,
00126                      TDF_LabelMap&                      theProcessed,
00127                      std::set<TCollection_AsciiString>& theIgnoreObjs,
00128                      bool&                              theIsDumpCollected);
00129 
00130 void ReplaceVariables(TCollection_AsciiString& theCommand,
00131                       const TVariablesList&    theVariables);
00132 
00133 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
00134 
00135 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
00136                             TSting2ObjDataMap&                        aEntry2ObjData,
00137                             const bool                                theIsPublished,
00138                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
00139                             Standard_Integer&                         objectCounter,
00140                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
00141 
00142 void AddObjectColors (int                      theDocID,
00143                       TCollection_AsciiString& theScript,
00144                       const TSting2ObjDataMap& theEntry2ObjData);
00145 
00146 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
00147 
00148 void PublishObject (TObjectData&                              theObjectData,
00149                     TSting2ObjDataMap&                        theEntry2ObjData,
00150                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
00151                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
00152                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
00153                     std::set<TCollection_AsciiString>&        theMapOfPublished);
00154 
00155 namespace
00156 {
00157   //================================================================================
00161   //================================================================================
00162 
00163   void healPyName( TCollection_AsciiString&                  pyName,
00164                    const TCollection_AsciiString&            anEntry,
00165                    Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
00166   {
00167     const TCollection_AsciiString allowedChars
00168       ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
00169 
00170     if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
00171       pyName.Insert( 1, 'a' );
00172     }
00173     int p, p2=1; // replace not allowed chars
00174     while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
00175       pyName.SetValue(p, '_');
00176       p2=p;
00177     }
00178     if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
00179     {  // diff objects have same name - make a new name by appending a digit
00180       TCollection_AsciiString aName2;
00181       Standard_Integer i = 0;
00182       do {
00183         aName2 = pyName + "_" + ++i;
00184       } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
00185       pyName = aName2;
00186     }
00187   }
00188 }
00189 
00190 //=======================================================================
00191 //function : GetTextureGUID
00192 //purpose  :
00193 //=======================================================================
00194 const Standard_GUID& GEOM_Engine::GetTextureGUID()
00195 {
00196   static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
00197   return anID;
00198 }
00199 
00200 //=============================================================================
00204 //=============================================================================
00205 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
00206 
00207 //=============================================================================
00211 //=============================================================================
00212 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
00213 
00214 //=============================================================================
00218 //=============================================================================
00219 GEOM_Engine::GEOM_Engine()
00220 {
00221   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
00222 
00223   _OCAFApp = new GEOM_Application();
00224   _UndoLimit = 10;
00225 }
00226 
00230 GEOM_Engine::~GEOM_Engine()
00231 {
00232   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
00233   std::list< Handle(GEOM_Object) > objs;
00234   for(; It.More(); It.Next())
00235     objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
00236   std::list< Handle(GEOM_Object) >::iterator objit;
00237   for(objit = objs.begin(); objit != objs.end(); ++objit)
00238     RemoveObject(*objit);
00239 
00240   //Close all documents not closed
00241 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00242   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
00243 #else
00244   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
00245 #endif
00246   for (; anItr.More(); anItr.Next())
00247     Close(anItr.Key());
00248 
00249   _mapIDDocument.Clear();
00250   _objects.Clear();
00251 }
00252 
00253 //=============================================================================
00257 //=============================================================================
00258 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
00259 {
00260   Handle(TDocStd_Document) aDoc;
00261   if(_mapIDDocument.IsBound(theDocID)) {
00262     aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
00263   }
00264   else if (force) {
00265     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
00266     aDoc->SetUndoLimit(_UndoLimit);
00267     _mapIDDocument.Bind(theDocID, aDoc);
00268     TDataStd_Integer::Set(aDoc->Main(), theDocID);
00269   }
00270   return aDoc;
00271 }
00272 
00273 //=============================================================================
00277 //=============================================================================
00278 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
00279 {
00280   if (theDocument.IsNull()) return -1;
00281 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00282   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
00283 #else
00284   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
00285 #endif
00286   for (; anItr.More(); anItr.Next())
00287     if (anItr.Value() == theDocument) return anItr.Key();
00288 
00289   return -1;
00290 }
00291 
00292 //=============================================================================
00296 //=============================================================================
00297 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry, bool force)
00298 {
00299   Handle(GEOM_Object) anObject;
00300 
00301   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
00302 
00303   if (_objects.IsBound(anID)) {
00304     anObject = Handle(GEOM_Object)::DownCast(_objects(anID));
00305   }
00306   else if (force) {
00307     Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
00308     if ( !aDoc.IsNull()) {
00309       TDF_Label aLabel;
00310       TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
00311       anObject = new GEOM_Object(aLabel);
00312       _objects.Bind(anID, anObject);
00313     }
00314   }
00315 
00316   return anObject;
00317 }
00318 
00319 //=============================================================================
00323 //=============================================================================
00324 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
00325 {
00326   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
00327   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
00328 
00329   // NPAL18604: use existing label to decrease memory usage,
00330   //            if this label has been freed (object deleted)
00331   bool useExisting = false;
00332   TDF_Label aChild;
00333   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
00334     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
00335     if (!aFreeLabels.empty()) {
00336       useExisting = true;
00337       aChild = aFreeLabels.front();
00338       aFreeLabels.pop_front();
00339     }
00340   }
00341   if (!useExisting) {
00342     // create new label
00343     aChild = TDF_TagSource::NewChild(aDoc->Main());
00344   }
00345 
00346   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
00347 
00348   //Put an object in the map of created objects
00349   TCollection_AsciiString anID = BuildIDFromObject(anObject);
00350   if(_objects.IsBound(anID)) _objects.UnBind(anID);
00351   _objects.Bind(anID, anObject);
00352 
00353   return anObject;
00354 }
00355 
00356 //=============================================================================
00360 //=============================================================================
00361 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
00362                                              Handle(TColStd_HArray1OfInteger) theIndices,
00363                                              bool isStandaloneOperation)
00364 {
00365   if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
00366 
00367   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
00368   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
00369 
00370   // NPAL18604: use existing label to decrease memory usage,
00371   //            if this label has been freed (object deleted)
00372   bool useExisting = false;
00373   TDF_Label aChild;
00374   int aDocID = theMainShape->GetDocID();
00375   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
00376     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
00377     if (!aFreeLabels.empty()) {
00378       useExisting = true;
00379       aChild = aFreeLabels.front();
00380       aFreeLabels.pop_front();
00381     }
00382   }
00383   if (!useExisting) {
00384     // create new label
00385     aChild = TDF_TagSource::NewChild(aDoc->Main());
00386   }
00387 
00388   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
00389   Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
00390   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
00391 
00392   GEOM_ISubShape aSSI (aFunction);
00393   aSSI.SetMainShape(aMainShape);
00394   aSSI.SetIndices(theIndices);
00395 
00396   try {
00397 #if OCC_VERSION_LARGE > 0x06010000
00398     OCC_CATCH_SIGNALS;
00399 #endif
00400     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
00401     if (!aSolver.ComputeFunction(aFunction)) {
00402       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
00403       return NULL;
00404     }
00405   }
00406   catch (Standard_Failure) {
00407     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
00408     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
00409     return NULL;
00410   }
00411 
00412   // Put an object in the map of created objects
00413   TCollection_AsciiString anID = BuildIDFromObject(anObject);
00414   if (_objects.IsBound(anID)) _objects.UnBind(anID);
00415   _objects.Bind(anID, anObject);
00416 
00417   // Put this sub-shape in the list of sub-shapes of theMainShape
00418   aMainShape->AddSubShapeReference(aFunction);
00419 
00420   GEOM::TPythonDump pd (aFunction);
00421 
00422   if (isStandaloneOperation) {
00423     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
00424     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
00425     for (; i <= up - 1; i++) {
00426       pd << theIndices->Value(i) << ", ";
00427     }
00428     pd << theIndices->Value(up) << "])";
00429   }
00430   else
00431     pd << "None";
00432 
00433   return anObject;
00434 }
00435 
00436 //=============================================================================
00440 //=============================================================================
00441 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
00442 {
00443   if (theObject.IsNull()) return false;
00444 
00445   int aDocID = theObject->GetDocID();
00446   if(!_mapIDDocument.IsBound(aDocID))
00447     return false;  // document is closed...
00448 
00449   //Remove an object from the map of available objects
00450   TCollection_AsciiString anID = BuildIDFromObject(theObject);
00451   if (_objects.IsBound(anID)) _objects.UnBind(anID);
00452 
00453   // If sub-shape, remove it from the list of sub-shapes of its main shape
00454   if (!theObject->IsMainShape()) {
00455     Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
00456     GEOM_ISubShape aSSI (aFunction);
00457     Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
00458     //If main shape is not null, then remove
00459     if(!aMainShape.IsNull())
00460       aMainShape->RemoveSubShapeReference(aFunction);
00461   }
00462 
00463   int nb = theObject->GetNbFunctions();
00464   Handle(TDataStd_TreeNode) aNode;
00465   for (int i = 1; i <= nb; i++) {
00466     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
00467     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
00468       aNode->Remove();
00469   }
00470 
00471   TDF_Label aLabel = theObject->GetEntry();
00472   aLabel.ForgetAllAttributes(Standard_True);
00473 
00474   // Remember the label to reuse it then
00475   std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
00476   aFreeLabels.push_back(aLabel);
00477 
00478   theObject.Nullify();
00479 
00480   return true;
00481 }
00482 
00483 //=============================================================================
00487 //=============================================================================
00488 void GEOM_Engine::Undo(int theDocID)
00489 {
00490   GetDocument(theDocID)->Undo();
00491 }
00492 
00493 //=============================================================================
00497 //=============================================================================
00498 void GEOM_Engine::Redo(int theDocID)
00499 {
00500   GetDocument(theDocID)->Redo();
00501 }
00502 
00503 //=============================================================================
00507 //=============================================================================
00508 bool GEOM_Engine::Save(int theDocID, char* theFileName)
00509 {
00510   if(!_mapIDDocument.IsBound(theDocID)) return false;
00511   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
00512 
00513   _OCAFApp->SaveAs(aDoc, theFileName);
00514 
00515   return true;
00516 }
00517 
00518 //=============================================================================
00522 //=============================================================================
00523 bool GEOM_Engine::Load(int theDocID, char* theFileName)
00524 {
00525   Handle(TDocStd_Document) aDoc;
00526 #if OCC_VERSION_LARGE > 0x06050100 // For OCCT6.5.2 and higher
00527   if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
00528 #else
00529   if (_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
00530 #endif
00531     return false;
00532   }
00533 
00534   aDoc->SetUndoLimit(_UndoLimit);
00535 
00536   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
00537   _mapIDDocument.Bind(theDocID, aDoc);
00538 
00539   TDataStd_Integer::Set(aDoc->Main(), theDocID);
00540 
00541   return true;
00542 }
00543 
00544 //=============================================================================
00548 //=============================================================================
00549 void GEOM_Engine::Close(int theDocID)
00550 {
00551   if (_mapIDDocument.IsBound(theDocID)) {
00552     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
00553 
00554     //Remove all GEOM Objects associated to the given document
00555     TColStd_SequenceOfAsciiString aSeq;
00556     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
00557     for (; It.More(); It.Next()) {
00558       TCollection_AsciiString anObjID (It.Key());
00559       Standard_Integer anID = ExtractDocID(anObjID);
00560       if (theDocID == anID) aSeq.Append(It.Key());
00561     }
00562     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
00563 
00564     // Forget free labels for this document
00565     TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
00566     if (anIt != _freeLabels.end()) {
00567       _freeLabels.erase(anIt);
00568     }
00569 
00570     _mapIDDocument.UnBind(theDocID);
00571     _OCAFApp->Close(aDoc);
00572     aDoc.Nullify();
00573   }
00574 }
00575 
00576 //=============================================================================
00580 //=============================================================================
00581 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
00582                                                 std::vector<TObjectData>& theObjectData,
00583                                                 TVariablesList theVariables,
00584                                                 bool isPublished,
00585                                                 bool isMultiFile, 
00586                                                 bool& aValidScript)
00587 {
00588   // Set "C" numeric locale to save numbers correctly
00589   Kernel_Utils::Localizer loc;
00590 
00591   TCollection_AsciiString aScript;
00592   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
00593 
00594   if (aDoc.IsNull())
00595   {
00596     TCollection_AsciiString anEmptyScript;
00597     if( isMultiFile )
00598       anEmptyScript = "def RebuildData(theStudy): pass\n";
00599     return anEmptyScript;
00600   }
00601 
00602   aScript  = "import GEOM\n";
00603   aScript += "import geompy\n";
00604   aScript += "import math\n";
00605   aScript += "import SALOMEDS\n\n";
00606   if( isMultiFile )
00607     aScript += "def RebuildData(theStudy):";
00608 
00609   aScript += "\n\tgeompy.init_geom(theStudy)\n";
00610 
00611   AddTextures(theDocID, aScript);
00612 
00613   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
00614 
00615   // a map containing copies of TObjectData from theObjectData
00616   TSting2ObjDataMap    aEntry2ObjData;
00617   // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
00618   // occures when several StudyEntries correspond to one Entry
00619   TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
00620 
00621   //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
00622   for (unsigned i = 0; i < theObjectData.size(); ++i )
00623   {
00624     TObjectData& data = theObjectData[i];
00625     // look for an object by entry
00626     TDF_Label L;
00627     TDF_Tool::Label( aDoc->GetData(), data._entry, L );
00628     if ( L.IsNull() ) continue;
00629     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
00630     // fill maps
00631     if ( !obj.IsNull() ) {
00632       TSting2ObjDataMap::iterator ent2Data =
00633         aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
00634 
00635       if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
00636         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
00637       else
00638         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
00639     }
00640   }
00641 
00642   // collect objects entries to be published
00643   TColStd_SequenceOfAsciiString aObjListToPublish;
00644 
00645   // iterates on functions till critical (that requiers publication of objects)
00646   Handle(TDataStd_TreeNode) aNode, aRoot;
00647   Handle(GEOM_Function) aFunction;
00648   TDF_LabelMap aCheckedFuncMap;
00649   std::set< TCollection_AsciiString > anIgnoreObjMap;
00650 
00651   TCollection_AsciiString aFuncScript;
00652 
00653   // Mantis issue 0020768
00654   Standard_Integer objectCounter = 0;
00655   Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
00656 
00657   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
00658     TDataStd_ChildNodeIterator Itr(aRoot);
00659     for (; Itr.More(); Itr.Next()) {
00660       aNode = Itr.Value();
00661       aFunction = GEOM_Function::GetFunction(aNode->Label());
00662       if (aFunction.IsNull()) {
00663         MESSAGE ( "Null function !!!!" );
00664         continue;
00665       }
00666       bool isDumpCollected = false;
00667       TCollection_AsciiString aCurScript, anAfterScript;
00668       if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
00669                            isPublished, aCheckedFuncMap, anIgnoreObjMap,
00670                            isDumpCollected ))
00671         continue;
00672       // add function description before dump
00673       if (!aCurScript.IsEmpty())
00674         aFuncScript += aCurScript;
00675       if (isDumpCollected ) {
00676         // Replace entries by the names
00677         ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
00678                                aObjListToPublish, objectCounter, aNameToEntry );
00679 
00680         // publish collected objects
00681         std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
00682         int i = 1, n = aObjListToPublish.Length();
00683         for ( ; i <= n; i++ )
00684         {
00685           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
00686           PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
00687                          aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
00688         }
00689         // add publishing commands to the script
00690         std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
00691         for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
00692           aFuncScript += anEntryToCmd->second;
00693 
00694         // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
00695         //  because they will be published during command execution
00696         int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
00697         if ( indx == -1 )
00698           indx = anAfterScript.Search( "RestoreSubShapes" );
00699         if ( indx != -1 ) {
00700           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
00701           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
00702           i = 1, n = aSeq->Length();
00703           for ( ; i <= n; i+=2) {
00704             TCollection_AsciiString anEntry =
00705               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
00706             anIgnoreObjMap.insert(anEntry.ToCString());
00707           }
00708         }
00709 
00710         aObjListToPublish.Clear();
00711         aScript += aFuncScript;
00712         aFuncScript.Clear();
00713       }
00714       aFuncScript += anAfterScript;
00715     }
00716   }
00717 
00718   // Replace entries by the names
00719   aObjListToPublish.Clear();
00720   ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
00721                          objectCounter, aNameToEntry );
00722 
00723   aScript += aFuncScript;
00724 
00725   // ouv : NPAL12872
00726   AddObjectColors( theDocID, aScript, aEntry2ObjData );
00727 
00728   // Make script to publish in study
00729   TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
00730   if ( isPublished )
00731   {
00732     std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
00733 
00734     for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
00735          aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
00736          ++aStEntry2ObjDataPtrIt)
00737     {
00738       TObjectData* data = aStEntry2ObjDataPtrIt->second;
00739       if ( anIgnoreObjMap.count( data->_entry ))
00740         continue; // should not be dumped
00741       PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
00742                      aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
00743     }
00744     // add publishing commands to the script
00745     std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
00746     for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
00747       aScript += anEntryToCmd->second;
00748   }
00749 
00750   //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
00751   //Add unpublish command if need
00752   TCollection_AsciiString unpublishCmd("\n");
00753   if(isMultiFile)
00754     unpublishCmd += "\t";
00755   unpublishCmd += "geompy.hideInStudy(";
00756   
00757   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
00758        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
00759        ++aStEntry2ObjDataPtrIt)
00760     {
00761       TObjectData* data = aStEntry2ObjDataPtrIt->second;      
00762       if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
00763        aScript +=  unpublishCmd + data->_pyName + ")";
00764       }
00765     }    
00766   
00767   //aScript += "\n\tpass\n";
00768   aScript += "\n";
00769   aValidScript = true;
00770 
00771   // fill _studyEntry2NameMap and build globalVars
00772   TCollection_AsciiString globalVars;
00773   _studyEntry2NameMap.Clear();
00774   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
00775        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
00776        ++aStEntry2ObjDataPtrIt)
00777   {
00778     const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
00779     const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
00780     _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
00781     if ( !globalVars.IsEmpty() )
00782       globalVars += ", ";
00783     globalVars += data->_pyName;
00784   }
00785   if ( isMultiFile && !globalVars.IsEmpty() ) {
00786     globalVars.Insert( 1, "\n\tglobal " );
00787     aScript.Insert( posToInsertGlobalVars, globalVars );
00788   }
00789 
00790   return aScript;
00791 }
00792 
00793 //=======================================================================
00794 //function : GetDumpName
00795 //purpose  :
00796 //=======================================================================
00797 
00798 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
00799 {
00800   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
00801     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
00802 
00803   return NULL;
00804 }
00805 
00806 //=======================================================================
00807 //function : GetAllDumpNames
00808 //purpose  :
00809 //=======================================================================
00810 
00811 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
00812 {
00813   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
00814 
00815   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
00816   for (; it.More(); it.Next()) {
00817     aRetSeq->Append(it.Value());
00818   }
00819 
00820   return aRetSeq;
00821 }
00822 
00823 #define TEXTURE_LABEL_ID       1
00824 #define TEXTURE_LABEL_FILE     2
00825 #define TEXTURE_LABEL_WIDTH    3
00826 #define TEXTURE_LABEL_HEIGHT   4
00827 #define TEXTURE_LABEL_DATA     5
00828 
00829 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
00830 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00831                             const Handle(TColStd_HArray1OfByte)& theTexture,
00832 #else
00833                             const Handle(TDataStd_HArray1OfByte)& theTexture,
00834 #endif
00835                             const TCollection_AsciiString& theFileName)
00836 {
00837   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
00838   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
00839 
00840   // NPAL18604: use existing label to decrease memory usage,
00841   //            if this label has been freed (object deleted)
00842   bool useExisting = false;
00843   TDF_Label aChild;
00844   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
00845     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
00846     if (!aFreeLabels.empty()) {
00847       useExisting = true;
00848       aChild = aFreeLabels.front();
00849       aFreeLabels.pop_front();
00850     }
00851   }
00852   if (!useExisting) {
00853     // create new label
00854     aChild = TDF_TagSource::NewChild(aDoc->Main());
00855   }
00856 
00857   aChild.ForgetAllAttributes(Standard_True);
00858   Handle(TDataStd_TreeNode) node;
00859   if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
00860     node = TDataStd_TreeNode::Set(aChild);
00861   TDataStd_UAttribute::Set(aChild, GetTextureGUID());
00862 
00863   static int aTextureID = 0;
00864 
00865   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID),     ++aTextureID);
00866   TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE),   theFileName);
00867   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH),  theWidth);
00868   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
00869 
00870   Handle(TDataStd_ByteArray) anAttr =
00871     TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
00872                             theTexture.IsNull() ? 0 : theTexture->Lower(),
00873                             theTexture.IsNull() ? 0 : theTexture->Upper());
00874   anAttr->ChangeArray(theTexture);
00875 
00876   return aTextureID;
00877 }
00878 
00879 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00880 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
00881 #else
00882 Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
00883 #endif
00884                                                       int& theWidth, int& theHeight,
00885                                                       TCollection_AsciiString& theFileName)
00886 {
00887 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00888   Handle(TColStd_HArray1OfByte) anArray;
00889 #else
00890   Handle(TDataStd_HArray1OfByte) anArray;
00891 #endif
00892   theWidth = theHeight = 0;
00893 
00894   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
00895 
00896   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
00897   bool found = false;
00898   for (; anIterator.More() && !found; anIterator.Next()) {
00899     TDF_Label aTextureLabel = anIterator.Value();
00900     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
00901       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
00902       Handle(TDataStd_Integer) anIdAttr;
00903       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
00904          anIdAttr->Get() == theTextureID) {
00905         TDF_Label aFileLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_FILE,    Standard_False);
00906         TDF_Label aWidthLabel  = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH,   Standard_False);
00907         TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT,  Standard_False);
00908         TDF_Label aDataLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_DATA,    Standard_False);
00909         Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
00910         Handle(TDataStd_ByteArray) aTextureAttr;
00911         Handle(TDataStd_Comment) aFileAttr;
00912         if (!aWidthLabel.IsNull()  && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(),  aWidthAttr) &&
00913             !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
00914             !aDataLabel.IsNull()   && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
00915           theWidth = aWidthAttr->Get();
00916           theHeight = aHeightAttr->Get();
00917           anArray = aTextureAttr->InternalArray();
00918         }
00919         if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
00920           theFileName = aFileAttr->Get();
00921         found = true;
00922       }
00923     }
00924   }
00925   return anArray;
00926 }
00927 
00928 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
00929 {
00930   std::list<int> id_list;
00931 
00932   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
00933 
00934   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
00935   for (; anIterator.More(); anIterator.Next()) {
00936     TDF_Label aTextureLabel = anIterator.Value();
00937     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
00938       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
00939       Handle(TDataStd_Integer) anIdAttr;
00940       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
00941         id_list.push_back((int)anIdAttr->Get());
00942     }
00943   }
00944   return id_list;
00945 }
00946 
00947 //===========================================================================
00948 //                     Internal functions
00949 //===========================================================================
00950 
00951 //=============================================================================
00955 //=============================================================================
00956 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
00957                      TCollection_AsciiString&           theScript,
00958                      TCollection_AsciiString&           theAfterScript,
00959                      const TVariablesList&              theVariables,
00960                      const bool                         theIsPublished,
00961                      TDF_LabelMap&                      theProcessed,
00962                      std::set<TCollection_AsciiString>& theIgnoreObjs,
00963                      bool&                              theIsDumpCollected)
00964 {
00965   theIsDumpCollected = false;
00966   if (theFunction.IsNull()) return false;
00967 
00968   if (theProcessed.Contains(theFunction->GetEntry())) return false;
00969 
00970   // pass functions, that depends on nonexisting ones
00971   bool doNotProcess = false;
00972   TDF_LabelSequence aSeq;
00973   theFunction->GetDependency(aSeq);
00974   Standard_Integer aLen = aSeq.Length();
00975   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
00976     TDF_Label aRefLabel = aSeq.Value(i);
00977     Handle(TDF_Reference) aRef;
00978     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
00979       doNotProcess = true;
00980     }
00981     else {
00982       if (aRef.IsNull() || aRef->Get().IsNull()) {
00983         doNotProcess = true;
00984       }
00985       else {
00986         Handle(TDataStd_TreeNode) aT;
00987         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
00988           doNotProcess = true;
00989         }
00990         else {
00991           TDF_Label aDepLabel = aT->Label();
00992           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
00993 
00994           if (aFunction.IsNull()) doNotProcess = true;
00995           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
00996         }
00997       }
00998     }
00999   }
01000 
01001   if (doNotProcess) {
01002     TCollection_AsciiString anObjEntry;
01003     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
01004     theIgnoreObjs.insert(anObjEntry);
01005     return false;
01006   }
01007   theProcessed.Add(theFunction->GetEntry());
01008 
01009   TCollection_AsciiString aDescr = theFunction->GetDescription();
01010   if(aDescr.Length() == 0) return false;
01011 
01012   //Check if its internal function which doesn't requires dumping
01013   if(aDescr == "None") return false;
01014 
01015   // 0020001 PTv, check for critical functions, which require dump of objects
01016   if (theIsPublished)
01017   {
01018     // currently, there is only one function "RestoreGivenSubShapes",
01019     // later this check could be replaced by iterations on list of such functions
01020     if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
01021       theIsDumpCollected = true;
01022     else if (aDescr.Search( "RestoreSubShapes" ) != -1)
01023       theIsDumpCollected = true;
01024   }
01025 
01026   //Replace parameter by notebook variables
01027   ReplaceVariables(aDescr,theVariables);
01028   if ( theIsDumpCollected ) {
01029     int i = 1;
01030     bool isBefore = true;
01031     TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
01032     while (!aSubStr.IsEmpty()) {
01033       if (isBefore &&
01034           aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
01035           aSubStr.Search( "RestoreSubShapes" ) == -1)
01036         theScript += TCollection_AsciiString("\n\t") + aSubStr;
01037       else
01038         theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
01039       aSubStr = aDescr.Token("\n\t", i++);
01040     }
01041   }
01042   else {
01043     theScript += "\n\t";
01044     theScript += aDescr;
01045   }
01046   return true;
01047 }
01048 
01049 //=============================================================================
01053 //=============================================================================
01054 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
01055 {
01056   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
01057   Standard_Integer aLen = theString.Length();
01058   Standard_Boolean isFound = Standard_False;
01059 
01060   const char* arr = theString.ToCString();
01061   Standard_Integer i = 0, j;
01062 
01063   while(i < aLen) {
01064     int c = (int)arr[i];
01065     j = i+1;
01066     if(c >= 48 && c <= 57) { //Is digit?
01067 
01068       isFound = Standard_False;
01069       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
01070         c = (int)arr[j++];
01071         if(c == 58) isFound = Standard_True;
01072       }
01073 
01074       if(isFound && arr[j-2] != 58) { // last char should be a diggit
01075         aSeq->Append(i+1); // +1 because AsciiString starts from 1
01076         aSeq->Append(j-1);
01077       }
01078     }
01079 
01080     i = j;
01081   }
01082 
01083   return aSeq;
01084 }
01085 
01086 //=============================================================================
01091 //=============================================================================
01092 void ReplaceVariables(TCollection_AsciiString& theCommand,
01093                       const TVariablesList&    theVariables)
01094 {
01095   if (MYDEBUG)
01096     cout<<"Command : "<<theCommand<<endl;
01097 
01098   if (MYDEBUG) {
01099     cout<<"All Entries:"<<endl;
01100     TVariablesList::const_iterator it = theVariables.begin();
01101     for(;it != theVariables.end();it++)
01102       cout<<"\t'"<<(*it).first<<"'"<<endl;
01103   }
01104 
01105   //Additional case - multi-row commands
01106   int aCommandIndex = 1;
01107   while( aCommandIndex < 10 ) { // tmp check
01108     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
01109     if( aCommand.Length() == 0 )
01110       break;
01111 
01112     if (MYDEBUG)
01113       cout<<"Sub-command : "<<aCommand<<endl;
01114 
01115     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
01116     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
01117 
01118     //Get Entry of the result object
01119     TCollection_AsciiString anEntry;
01120     if( aCommand.Search("=") != -1 ) // command returns an object
01121       anEntry = aCommand.Token("=",1);
01122     else { // command modifies the object
01123       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
01124         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
01125           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
01126     }
01127     //Remove white spaces
01128     anEntry.RightAdjust();
01129     anEntry.LeftAdjust();
01130     if(MYDEBUG)
01131       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
01132 
01133     if ( anEntry.IsEmpty() ) {
01134       aCommandIndex++;
01135       continue;
01136     }
01137 
01138     //Check if result is list of entries - enough to get the first entry in this case
01139     int aNbEntries = 1;
01140     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
01141       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
01142         aNbEntries++;
01143       TCollection_AsciiString aSeparator(COMMA);
01144       anEntry = anEntry.Token(aSeparator.ToCString(),1);
01145       anEntry.Remove( 1, 1 );
01146       anEntry.RightAdjust();
01147       anEntry.LeftAdjust();
01148       if(MYDEBUG)
01149         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
01150     }
01151 
01152     //Find variables used for object construction
01153     ObjectStates* aStates = 0;
01154     TVariablesList::const_iterator it = theVariables.find(anEntry);
01155     if( it != theVariables.end() )
01156       aStates = (*it).second;
01157 
01158     if(!aStates) {
01159       if(MYDEBUG)
01160         cout<<"Valiables list empty!!!"<<endl;
01161       aCommandIndex++;
01162       continue;
01163     }
01164 
01165     TState aVariables = aStates->GetCurrectState();
01166 
01167     if(MYDEBUG) {
01168       cout<<"Variables from SObject:"<<endl;
01169       for (int i = 0; i < aVariables.size();i++)
01170         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
01171     }
01172 
01173     //Calculate total number of parameters
01174     Standard_Integer aTotalNbParams = 1;
01175     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
01176       aTotalNbParams++;
01177 
01178     if(MYDEBUG)
01179       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
01180 
01181     Standard_Integer aFirstParam = aNbEntries;
01182 
01183     //Replace parameters by variables
01184     Standard_Integer aStartPos = 0;
01185     Standard_Integer aEndPos = 0;
01186     int iVar = 0;
01187     TCollection_AsciiString aVar, aReplacedVar;
01188     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
01189       //Replace first parameter (bettwen '(' character and first ',' character)
01190       if(i == aFirstParam)
01191       {
01192         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
01193         if(aTotalNbParams - aNbEntries > 0 )
01194           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
01195         else
01196           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
01197       }
01198       //Replace last parameter (bettwen ',' character and ')' character)
01199       else if(i == aTotalNbParams)
01200       {
01201         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
01202         aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
01203       }
01204       //Replace other parameters (bettwen two ',' characters)
01205       else if(i != aFirstParam && i != aTotalNbParams )
01206       {
01207         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
01208         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
01209       }
01210 
01211       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
01212         aStartPos++;
01213       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
01214         aEndPos--;
01215       if ( aStartPos == aEndPos )
01216         continue; // PAL20889: for "[]"
01217 
01218       if(MYDEBUG)
01219         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
01220 
01221       aVar = aCommand.SubString(aStartPos, aEndPos-1);
01222       aVar.RightAdjust();
01223       aVar.LeftAdjust();
01224 
01225       if(MYDEBUG)
01226         cout<<"Variable: '"<< aVar <<"'"<<endl;
01227 
01228       // specific case for sketcher
01229       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
01230         Standard_Integer aNbSections = 1;
01231         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
01232           aNbSections++;
01233         aNbSections--;
01234 
01235         int aStartSectionPos = 0, aEndSectionPos = 0;
01236         TCollection_AsciiString aSection, aReplacedSection;
01237         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
01238           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
01239           if( aSectionIndex != aNbSections )
01240             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
01241           else
01242             aEndSectionPos = aVar.Length();
01243 
01244           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
01245           if(MYDEBUG)
01246             cout<<"aSection: "<<aSection<<endl;
01247 
01248           Standard_Integer aNbParams = 1;
01249           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
01250             aNbParams++;
01251           aNbParams--;
01252 
01253           int aStartParamPos = 0, aEndParamPos = 0;
01254           TCollection_AsciiString aParameter, aReplacedParameter;
01255           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
01256             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
01257             if( aParamIndex != aNbParams )
01258               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
01259             else
01260               aEndParamPos = aSection.Length() + 1;
01261 
01262             if(MYDEBUG)
01263               cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
01264 
01265            if ( aStartParamPos == aEndParamPos)
01266              continue;
01267 
01268             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
01269             if(MYDEBUG)
01270               cout<<"aParameter: "<<aParameter<<endl;
01271 
01272             if(iVar >= aVariables.size())
01273               continue;
01274 
01275             aReplacedParameter = aVariables[iVar].myVariable;
01276             if(aReplacedParameter.IsEmpty()) {
01277               iVar++;
01278               continue;
01279             }
01280 
01281             if(aVariables[iVar].isVariable) {
01282               aReplacedParameter.InsertBefore(1,"'");
01283               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
01284             }
01285 
01286             if(MYDEBUG)
01287               cout<<"aSection before : "<<aSection<<endl;
01288             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
01289             aSection.Insert(aStartParamPos, aReplacedParameter);
01290             if(MYDEBUG)
01291               cout<<"aSection after  : "<<aSection<<endl<<endl;
01292             iVar++;
01293           }
01294           if(MYDEBUG)
01295             cout<<"aVar before : "<<aVar<<endl;
01296           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
01297           aVar.Insert(aStartSectionPos, aSection);
01298           if(MYDEBUG)
01299             cout<<"aVar after  : "<<aVar<<endl<<endl;
01300         }
01301 
01302         if(MYDEBUG)
01303           cout<<"aCommand before : "<<aCommand<<endl;
01304         aCommand.Remove(aStartPos, aEndPos - aStartPos);
01305         aCommand.Insert(aStartPos, aVar);
01306         if(MYDEBUG)
01307           cout<<"aCommand after  : "<<aCommand<<endl;
01308 
01309         break;
01310       } // end of specific case for sketcher
01311 
01312       //If parameter is entry or 'None', skip it
01313       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
01314         continue;
01315 
01316       if(iVar >= aVariables.size())
01317         continue;
01318 
01319       aReplacedVar = aVariables[iVar].myVariable;
01320       if(aReplacedVar.IsEmpty()) {
01321         iVar++;
01322         continue;
01323       }
01324 
01325       if(aVariables[iVar].isVariable) {
01326         aReplacedVar.InsertBefore(1,"\"");
01327         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
01328       }
01329 
01330       aCommand.Remove(aStartPos, aEndPos - aStartPos);
01331       aCommand.Insert(aStartPos, aReplacedVar);
01332       iVar++;
01333     }
01334 
01335     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
01336     theCommand.Insert(aStartCommandPos, aCommand);
01337 
01338     aCommandIndex++;
01339 
01340     aStates->IncrementState();
01341   }
01342 
01343   if (MYDEBUG)
01344     cout<<"Command : "<<theCommand<<endl;
01345 }
01346 
01347 //=============================================================================
01351 //=============================================================================
01352 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
01353                             TSting2ObjDataMap&                        aEntry2ObjData,
01354                             const bool                                theIsPublished,
01355                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
01356                             Standard_Integer&                         objectCounter,
01357                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
01358 {
01359   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
01360   Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
01361 
01362   //Replace entries by the names
01363   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
01364     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
01365   if (aLen == 0) anUpdatedScript = theScript;
01366 
01367   for (Standard_Integer i = 1; i <= aLen; i+=2) {
01368     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
01369     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
01370     theObjListToPublish.Append( anEntry );
01371     
01372     TObjectData& data = aEntry2ObjData[ anEntry ];
01373     if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
01374       if ( !data._name.IsEmpty() ) { // published object
01375         data._pyName = data._name;
01376         healPyName( data._pyName, anEntry, aNameToEntry);
01377       }
01378       else {
01379         do {
01380           data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
01381         } while(aNameToEntry.IsBound(data._pyName));
01382       }
01383     }
01384     
01385     aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
01386     
01387     anUpdatedScript += data._pyName;
01388     aStart = aSeq->Value(i+1) + 1;
01389   }
01390   
01391   //Add final part of the script
01392   if (aLen && aSeq->Value(aLen) < aScriptLength)
01393     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
01394   
01395   theScript = anUpdatedScript;
01396 }
01397 
01398 //=============================================================================
01402 //=============================================================================
01403 void AddObjectColors (int                      theDocID,
01404                       TCollection_AsciiString& theScript,
01405                       const TSting2ObjDataMap& theEntry2ObjData)
01406 {
01407   GEOM_Engine* engine = GEOM_Engine::GetEngine();
01408   Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
01409 
01410   TSting2ObjDataMap::const_iterator anEntryToNameIt;
01411   for (anEntryToNameIt = theEntry2ObjData.begin();
01412        anEntryToNameIt!= theEntry2ObjData.end();
01413        ++anEntryToNameIt)
01414   {
01415     const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
01416     const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
01417 
01418     TDF_Label L;
01419     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
01420     if ( L.IsNull() )
01421       continue;
01422 
01423     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
01424     if ( obj.IsNull() )
01425       continue;
01426 
01427     bool anAutoColor = obj->GetAutoColor();
01428     if ( anAutoColor )
01429     {
01430       TCollection_AsciiString aCommand( "\n\t" );
01431       aCommand += aName + ".SetAutoColor(1)";
01432       theScript += aCommand.ToCString();
01433     }
01434 
01435     GEOM_Object::Color aColor = obj->GetColor();
01436     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
01437     {
01438       TCollection_AsciiString aCommand( "\n\t" );
01439       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
01440       theScript += aCommand.ToCString();
01441     }
01442 
01443     Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
01444     if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
01445       TCollection_AsciiString aCommand( "\n\t" );
01446       aCommand += aName + ".SetMarkerStd(";
01447       switch (aMarkerType) {
01448       case Aspect_TOM_POINT:   aCommand += "GEOM.MT_POINT";   break;
01449       case Aspect_TOM_PLUS:    aCommand += "GEOM.MT_PLUS";    break;
01450       case Aspect_TOM_STAR:    aCommand += "GEOM.MT_STAR";    break;
01451       case Aspect_TOM_O:       aCommand += "GEOM.MT_O";       break;
01452       case Aspect_TOM_X:       aCommand += "GEOM.MT_X";       break;
01453       case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
01454       case Aspect_TOM_O_PLUS:  aCommand += "GEOM.MT_O_PLUS";  break;
01455       case Aspect_TOM_O_STAR:  aCommand += "GEOM.MT_O_STAR";  break;
01456       case Aspect_TOM_O_X:     aCommand += "GEOM.MT_O_X";     break;
01457       case Aspect_TOM_BALL:    aCommand += "GEOM.MT_BALL";    break;
01458       case Aspect_TOM_RING1:   aCommand += "GEOM.MT_RING1";   break;
01459       case Aspect_TOM_RING2:   aCommand += "GEOM.MT_RING2";   break;
01460       case Aspect_TOM_RING3:   aCommand += "GEOM.MT_RING3";   break;
01461       default:                 aCommand += "GEOM.MT_NONE";    break; // just for completeness, should not get here
01462       }
01463       aCommand += ", ";
01464       int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
01465       switch (aSize) {
01466       case  1: aCommand += "GEOM.MS_10";   break;
01467       case  2: aCommand += "GEOM.MS_15";   break;
01468       case  3: aCommand += "GEOM.MS_20";   break;
01469       case  4: aCommand += "GEOM.MS_25";   break;
01470       case  5: aCommand += "GEOM.MS_30";   break;
01471       case  6: aCommand += "GEOM.MS_35";   break;
01472       case  7: aCommand += "GEOM.MS_40";   break;
01473       case  8: aCommand += "GEOM.MS_45";   break;
01474       case  9: aCommand += "GEOM.MS_50";   break;
01475       case 10: aCommand += "GEOM.MS_55";   break;
01476       case 11: aCommand += "GEOM.MS_60";   break;
01477       case 12: aCommand += "GEOM.MS_65";   break;
01478       case 13: aCommand += "GEOM.MS_70";   break;
01479       default: aCommand += "GEOM.MS_NONE"; break;
01480       }
01481       aCommand += ")";
01482       theScript += aCommand.ToCString();
01483     }
01484     else if (aMarkerType == Aspect_TOM_USERDEFINED) {
01485       int aMarkerTextureID = obj->GetMarkerTexture();
01486       if (aMarkerTextureID >= 0) {
01487         TCollection_AsciiString aCommand( "\n\t" );
01488         aCommand += aName + ".SetMarkerTexture(texture_map[";
01489         aCommand += aMarkerTextureID;
01490         aCommand += "])";
01491         theScript += aCommand.ToCString();
01492       }
01493     }
01494   }
01495 }
01496 
01497 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
01498 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
01499 #else
01500 static TCollection_AsciiString pack_data (const Handle(TDataStd_HArray1OfByte)& aData)
01501 #endif
01502 {
01503   TCollection_AsciiString stream;
01504   if (!aData.IsNull()) {
01505     for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
01506       Standard_Byte byte = aData->Value(i);
01507       TCollection_AsciiString strByte = "";
01508       for (int j = 0; j < 8; j++)
01509         strByte.Prepend((byte & (1<<j)) ? "1" : "0");
01510       stream += strByte;
01511     }
01512   }
01513   return stream;
01514 }
01515 
01516 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
01517 {
01518   GEOM_Engine* engine = GEOM_Engine::GetEngine();
01519   std::list<int> allTextures = engine->getAllTextures(theDocID);
01520   std::list<int>::const_iterator it;
01521 
01522   if (allTextures.size() > 0) {
01523     theScript += "\n\ttexture_map = {}\n";
01524 
01525     for (it = allTextures.begin(); it != allTextures.end(); ++it) {
01526       if (*it <= 0) continue;
01527       Standard_Integer aWidth, aHeight;
01528       TCollection_AsciiString aFileName;
01529 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
01530       Handle(TColStd_HArray1OfByte) aTexture =
01531 #else
01532       Handle(TDataStd_HArray1OfByte) aTexture =
01533 #endif
01534         engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
01535       if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
01536         TCollection_AsciiString aCommand = "\n\t";
01537         aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
01538         if (aFileName != "" ) {
01539           aCommand += "geompy.LoadTexture(\"";
01540           aCommand += aFileName.ToCString();
01541           aCommand += "\")";
01542         }
01543         else {
01544           aCommand += "geompy.AddTexture(";
01545           aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
01546           aCommand += pack_data(aTexture);
01547           aCommand += "\")";
01548         }
01549         theScript += aCommand;
01550       }
01551     }
01552     theScript += "\n";
01553   }
01554 }
01555 
01556 //=============================================================================
01560 //=============================================================================
01561 void PublishObject (TObjectData&                              theObjectData,
01562                     TSting2ObjDataMap&                        theEntry2ObjData,
01563                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
01564                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
01565                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
01566                     std::set< TCollection_AsciiString>&       theIgnoreMap)
01567 {
01568   if ( theObjectData._studyEntry.IsEmpty() )
01569     return; // was not published
01570   if ( theIgnoreMap.count( theObjectData._entry ) )
01571     return; // not to publish
01572 
01573   TCollection_AsciiString aCommand("\n\tgeompy.");
01574 
01575   // find a father entry
01576   TObjectData* aFatherData = 0;
01577   TCollection_AsciiString aFatherStudyEntry =
01578     theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
01579   TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
01580     theStEntry2ObjDataPtr.find( aFatherStudyEntry );
01581   if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
01582     aFatherData = stEntry2DataPtr->second;
01583 
01584   const int geomObjDepth = 3;
01585 
01586   // treat multiply published object
01587   if ( theObjectData._pyName.IsEmpty() )
01588   {
01589     TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
01590     if ( data0._pyName.IsEmpty() ) return; // something wrong
01591 
01592     theObjectData._pyName = theObjectData._name;
01593     healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
01594 
01595     TCollection_AsciiString aCreationCommand("\n\t");
01596     aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
01597 
01598     // store aCreationCommand before publishing commands
01599     int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
01600     theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
01601   }
01602 
01603   // make a command
01604   if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
01605     aCommand += "addToStudyInFather( ";
01606     aCommand += aFatherData->_pyName + ", ";
01607   }
01608   else {
01609     aCommand += "addToStudy( ";
01610   }
01611   aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
01612 
01613   // bind a command to the study entry
01614   int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
01615   theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
01616 
01617   theObjectData._studyEntry.Clear(); // not to publish any more
01618 }
01619 
01620 //================================================================================
01624 //================================================================================
01625 ObjectStates::ObjectStates()
01626 {
01627   _dumpstate = 0;
01628 }
01629 
01630 //================================================================================
01634 //================================================================================
01635 ObjectStates::~ObjectStates()
01636 {
01637 }
01638 
01639 //================================================================================
01644 //================================================================================
01645 TState ObjectStates::GetCurrectState() const
01646 {
01647   if(_states.size() > _dumpstate)
01648     return _states[_dumpstate];
01649   return TState();
01650 }
01651 
01652 //================================================================================
01657 //================================================================================
01658 void ObjectStates::AddState(const TState &theState)
01659 {
01660   _states.push_back(theState);
01661 }
01662 
01663 //================================================================================
01667 //================================================================================
01668 void ObjectStates::IncrementState()
01669 {
01670   _dumpstate++;
01671 }