1 // Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_DumpPython.cxx
23 // Created : Thu Mar 24 17:17:59 2005
24 // Author : Julia DOROVSKIKH
27 #include "SMESH_PythonDump.hxx"
28 #include "SMESH_Gen_i.hxx"
29 #include "SMESH_Filter_i.hxx"
30 #include "SMESH_MeshEditor_i.hxx"
31 #include "SMESH_2smeshpy.hxx"
33 #include <TColStd_HSequenceOfInteger.hxx>
34 #include <TCollection_AsciiString.hxx>
35 #include <SMESH_Comment.hxx>
39 static int MYDEBUG = 0;
41 static int MYDEBUG = 0;
44 static TCollection_AsciiString NotPublishedObjectName()
46 return "__NOT__Published__Object__";
52 size_t TPythonDump::myCounter = 0;
63 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
64 std::string aString = myStream.str();
65 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
66 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
67 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
68 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
69 if(MYDEBUG) MESSAGE(aString);
76 operator<<(long int theArg){
83 operator<<(int theArg){
90 operator<<(double theArg){
97 operator<<(float theArg){
104 operator<<(const void* theArg){
111 operator<<(const char* theArg){
119 operator<<(const SMESH::ElementType& theArg)
123 case ALL: myStream<<"ALL";break;
124 case NODE: myStream<<"NODE";break;
125 case EDGE: myStream<<"EDGE";break;
126 case FACE: myStream<<"FACE";break;
127 case VOLUME:myStream<<"VOLUME";break;
128 case ELEM0D:myStream<<"ELEM0D";break;
129 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
136 operator<<(const SMESH::GeometryType& theArg)
140 case Geom_POINT: myStream<<"Geom_POINT"; break;
141 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
142 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
143 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
144 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
145 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
146 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
147 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
148 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
149 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
150 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
155 template<class TArray>
156 void DumpArray(const TArray& theArray, TPythonDump & theStream)
159 for (int i = 1; i <= theArray.length(); i++) {
160 theStream << theArray[i-1];
161 if ( i < theArray.length() )
168 TPythonDump::operator<<(const SMESH::long_array& theArg)
170 DumpArray( theArg, *this );
175 TPythonDump::operator<<(const SMESH::double_array& theArg)
177 DumpArray( theArg, *this );
182 TPythonDump::operator<<(const SMESH::string_array& theArray)
185 for (int i = 1; i <= theArray.length(); i++) {
186 myStream << "'" << theArray[i-1] << "'";
187 if ( i < theArray.length() )
196 operator<<(SALOMEDS::SObject_ptr aSObject)
198 if ( !aSObject->_is_nil() )
199 myStream << aSObject->GetID();
201 myStream << NotPublishedObjectName();
207 operator<<(CORBA::Object_ptr theArg)
209 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
210 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
211 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
212 if(!aSObject->_is_nil()) {
213 CORBA::String_var id = aSObject->GetID();
215 } else if ( !CORBA::is_nil(theArg)) {
216 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
217 myStream << "smeshObj_" << size_t(theArg);
219 myStream << NotPublishedObjectName();
228 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
230 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
231 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
232 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
233 myStream << "hyp_" << theArg->GetId();
235 *this << CORBA::Object_ptr( theArg );
241 operator<<(SMESH::SMESH_IDSource_ptr theArg)
243 if ( CORBA::is_nil( theArg ) )
244 return *this << "None";
245 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
246 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
247 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
248 if(!aSObject->_is_nil())
249 return *this << aSObject;
250 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
251 return *this << filter;
252 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
253 if ( !theArg->_is_equivalent( mesh ))
255 SMESH::long_array_var anElementsId = theArg->GetIDs();
256 SMESH::array_of_ElementType_var types = theArg->GetTypes();
257 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
258 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
265 operator<<(SMESH::FilterLibrary_i* theArg)
267 myStream<<"aFilterLibrary"<<theArg;
273 operator<<(SMESH::FilterManager_i* theArg)
275 myStream<<"aFilterManager";
281 operator<<(SMESH::Filter_i* theArg)
283 myStream<<"aFilter"<<theArg;
289 operator<<(SMESH::Functor_i* theArg)
292 FunctorType aFunctorType = theArg->GetFunctorType();
293 switch(aFunctorType){
294 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
295 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
296 case FT_Warping: myStream<< "aWarping"; break;
297 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
298 case FT_Taper: myStream<< "aTaper"; break;
299 case FT_Skew: myStream<< "aSkew"; break;
300 case FT_Area: myStream<< "aArea"; break;
301 case FT_Volume3D: myStream<< "aVolume3D"; break;
302 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
303 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
304 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
305 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
306 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
307 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
308 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
309 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
310 case FT_Length: myStream<< "aLength"; break;
311 case FT_Length2D: myStream<< "aLength2D"; break;
312 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
313 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
314 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
315 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
316 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
317 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
318 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
319 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
320 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
321 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
322 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
323 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
324 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
325 case FT_GroupColor: myStream<< "aGroupColor"; break;
326 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
327 case FT_LessThan: myStream<< "aLessThan"; break;
328 case FT_MoreThan: myStream<< "aMoreThan"; break;
329 case FT_EqualTo: myStream<< "anEqualTo"; break;
330 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
331 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
332 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
334 default: myStream<< "anUndefined"; break;
343 operator<<(SMESH::Measurements_i* theArg)
345 myStream<<"aMeasurements";
350 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
352 myStream << SMESHGenName(); return *this;
355 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
357 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
360 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
362 myStream << theStr; return *this;
366 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
368 switch (theVersion) {
369 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
370 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
371 default: myStream << theVersion;
376 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
378 myStream << "SMESH.AxisStruct( "
382 << theAxis.vx << ", "
383 << theAxis.vy << ", "
384 << theAxis.vz << " )";
388 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
390 const SMESH::PointStruct & P = theDir.PS;
391 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
398 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
400 DumpArray( theList, *this );
403 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
405 DumpArray( *theList, *this );
408 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
410 DumpArray( theList, *this );
414 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
415 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
417 //================================================================================
419 * \brief Return marker of long string literal beginning
420 * \param type - a name of functionality producing the string literal
421 * \retval TCollection_AsciiString - the marker string to be written into
422 * a raw python script
424 //================================================================================
426 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
430 (Standard_Integer) strlen(type) +
435 //================================================================================
437 * \brief Return marker of long string literal end
438 * \retval TCollection_AsciiString - the marker string to be written into
439 * a raw python script
441 //================================================================================
443 TCollection_AsciiString TPythonDump::LongStringEnd()
445 return myLongStringEnd;
448 //================================================================================
450 * \brief Cut out a long string literal from a string
451 * \param theText - text possibly containing string literals
452 * \param theFrom - position in the text to search from
453 * \param theLongString - the retrieved literal
454 * \param theStringType - a name of functionality produced the literal
455 * \retval bool - true if a string literal found
457 * The literal is removed from theText; theFrom points position right after
458 * the removed literal
460 //================================================================================
462 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
464 TCollection_AsciiString & theLongString,
465 TCollection_AsciiString & theStringType)
467 if ( theFrom < 1 || theFrom > theText.Length() )
470 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
471 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
472 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
475 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
479 // find where literal begins
480 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
481 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
482 int typeLen = atoi ( typeLenStr ); // = 7
483 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
484 literalBeg++; // 26 -> 27
487 literalBeg += typeLen + 1; // = 35
488 if ( literalBeg > theText.Length() )
491 // where literal ends (i.e. end marker begins)
492 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
494 literalEnd = theText.Length();
497 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
499 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
501 literalEnd += myLongStringEnd.Length(); // = 79
502 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
503 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
509 //=======================================================================
510 //function : RemoveTabulation
512 //=======================================================================
513 void RemoveTabulation( TCollection_AsciiString& theScript )
515 std::string aString( theScript.ToCString() );
516 std::string::size_type aPos = 0;
517 while( aPos < aString.length() )
519 aPos = aString.find( "\n\t", aPos );
520 if( aPos == std::string::npos )
522 aString.replace( aPos, 2, "\n" );
525 theScript = aString.c_str();
528 //=======================================================================
529 //function : DumpPython
531 //=======================================================================
532 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
533 CORBA::Boolean isPublished,
534 CORBA::Boolean isMultiFile,
535 CORBA::Boolean& isValidScript)
537 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
538 if (CORBA::is_nil(aStudy))
539 return new Engines::TMPFile(0);
541 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
542 if (CORBA::is_nil(aSO))
543 return new Engines::TMPFile(0);
545 // Map study entries to object names
546 Resource_DataMapOfAsciiStringAsciiString aMap;
547 Resource_DataMapOfAsciiStringAsciiString aMapNames;
548 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
550 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
551 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
552 SALOMEDS::SObject_var aValue = Itr->Value();
553 CORBA::String_var anID = aValue->GetID();
554 CORBA::String_var aName = aValue->GetName();
555 TCollection_AsciiString aGUIName ( (char*) aName.in() );
556 TCollection_AsciiString anEnrty ( (char*) anID.in() );
557 if (aGUIName.Length() > 0) {
558 aMapNames.Bind( anEnrty, aGUIName );
559 aMap.Bind( anEnrty, aGUIName );
563 // Get trace of restored study
564 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
565 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
566 SALOMEDS::GenericAttribute_var anAttr =
567 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
569 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
570 TCollection_AsciiString aSavedTrace (oldValue);
572 // Add trace of API methods calls and replace study entries by names
573 TCollection_AsciiString aScript;
574 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
575 isPublished, isMultiFile, isValidScript, aSavedTrace);
577 int aLen = aScript.Length();
578 unsigned char* aBuffer = new unsigned char[aLen+1];
579 strcpy((char*)aBuffer, aScript.ToCString());
581 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
582 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
584 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
585 isValidScript = isValidScript && !hasNotPublishedObjects;
587 return aStreamFile._retn();
590 //=============================================================================
594 //=============================================================================
595 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
597 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
598 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
600 myPythonScripts[theStudyID]->Append(theString);
603 //=============================================================================
605 * RemoveLastFromPythonScript
607 //=============================================================================
608 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
610 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
611 int aLen = myPythonScripts[theStudyID]->Length();
612 myPythonScripts[theStudyID]->Remove(aLen);
616 //=======================================================================
617 //function : SavePython
619 //=======================================================================
620 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
622 // Dump trace of API methods calls
623 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
625 // Check contents of PythonObject attribute
626 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
627 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
628 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
629 SALOMEDS::GenericAttribute_var anAttr =
630 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
632 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
633 TCollection_AsciiString oldScript (oldValue);
635 if (oldScript.Length() > 0) {
637 oldScript += aScript;
642 // Store in PythonObject attribute
643 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
645 // Clean trace of API methods calls
646 CleanPythonTrace(theStudy->StudyId());
653 //=============================================================================
655 * FindEntries: Returns a sequence of start/end positions of entries in the string
657 //=============================================================================
658 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
660 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
661 Standard_Integer aLen = theString.Length();
662 Standard_Boolean isFound = Standard_False;
664 char* arr = (char*) theString.ToCString();
665 Standard_Integer i = 0, j;
670 if ( isdigit( c )) { //Is digit?
672 isFound = Standard_False;
673 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
675 if(c == ':') isFound = Standard_True;
679 int prev = (i < 1) ? 0 : (int)arr[i - 1];
680 // to distinguish from a sketcher command:
681 // last char should be a digit, not ":",
682 // previous char should not be '"'.
683 if (arr[j-2] != ':' && prev != '"') {
684 aSeq->Append(i+1); // +1 because AsciiString starts from 1
698 //================================================================================
700 * \brief Make a string be a valid python name
701 * \param aName - a string to fix
702 * \retval bool - true if aName was not modified
704 //================================================================================
706 bool fixPythonName(TCollection_AsciiString & aName )
708 const TCollection_AsciiString allowedChars =
709 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
710 bool isValidName = true;
711 int nbUnderscore = 0;
712 int p=1; // replace not allowed chars by underscore
713 while (p <= aName.Length() &&
714 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
716 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
717 aName.Remove( p, 1 ); // remove double _ and from the start and the end
719 aName.SetValue(p, '_'), nbUnderscore++;
722 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
723 aName.Insert( 1, 'a' );
726 // shorten names like CartesianParameters3D_400_400_400_1000000_1
727 if ( aName.Length() > 20 && nbUnderscore > 2 )
729 p = aName.Location( "_", 20, aName.Length());
737 //=============================================================================
741 //=============================================================================
742 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
743 (SALOMEDS::Study_ptr theStudy,
744 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
745 Resource_DataMapOfAsciiStringAsciiString& theNames,
749 const TCollection_AsciiString& theSavedTrace)
751 int aStudyID = theStudy->StudyId();
753 TCollection_AsciiString helper; // to comfortably concatenate C strings
754 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
755 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
756 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
758 TCollection_AsciiString aScript;
760 aScript += "def RebuildData(theStudy):";
762 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
763 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
765 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
767 aScript += aSMESHGen + ".SetCurrentStudy(None)";
769 // import python files corresponding to plugins
770 set<string> moduleNameSet;
771 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
772 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
773 string moduleName = hyp_creator->second->GetModuleName();
774 bool newModule = moduleNameSet.insert( moduleName ).second;
776 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
779 // Dump trace of restored study
780 if (theSavedTrace.Length() > 0) {
781 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
782 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
783 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
785 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
786 if ( !isNewVersion ) {
787 TCollection_AsciiString aSavedTrace( theSavedTrace );
788 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
789 int beg, end = aSavedTrace.Length(), from = 1;
790 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
791 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
792 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
793 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
796 from = beg + aSmeshCall.Length();
798 aScript += helper + "\n" + aSavedTrace;
801 // append a saved trace to the script
802 aScript += helper + "\n" + theSavedTrace;
805 // Dump trace of API methods calls
806 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
807 if (aNewLines.Length() > 0) {
808 aScript += helper + "\n" + aNewLines;
811 // Convert IDL API calls into smesh.py API.
812 // Some objects are wrapped with python classes and
813 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
814 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
815 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod, theObjectNames );
817 // Find entries to be replaced by names
818 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
819 Standard_Integer aLen = aSeq->Length();
824 // Replace entries by the names
825 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
826 TColStd_SequenceOfAsciiString seqRemoved;
827 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
828 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
829 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
831 // Collect names of GEOM objects to exclude same names for SMESH objects
832 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
833 int ign = 0, nbgn = aGeomNames->length();
834 for (; ign < nbgn; ign++) {
835 aName = aGeomNames[ign];
836 theObjectNames.Bind(aName, "1");
839 bool importGeom = false;
840 for (Standard_Integer i = 1; i <= aLen; i += 2) {
841 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
842 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
844 aName = geom->GetDumpName( anEntry.ToCString() );
845 if (aName.IsEmpty()) {
847 if (theObjectNames.IsBound(anEntry)) {
848 // The Object is in Study
849 aName = theObjectNames.Find(anEntry);
850 // check validity of aName
851 bool isValidName = fixPythonName( aName );
852 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
853 // diff objects have same name - make a new name by appending a digit
854 TCollection_AsciiString aName2;
855 Standard_Integer i = 0;
857 aName2 = aName + "_" + ++i;
858 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
863 theObjectNames(anEntry) = aName;
868 aName = aBaseName + (++objectCounter);
869 } while (theObjectNames.IsBound(aName));
870 seqRemoved.Append(aName);
871 mapRemoved.Bind(anEntry, "1");
872 theObjectNames.Bind(anEntry, aName);
874 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
880 anUpdatedScript += aName;
881 aStart = aSeq->Value(i + 1) + 1;
884 // set initial part of aSript
885 TCollection_AsciiString initPart = "import ";
887 initPart += helper + "salome, ";
888 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
889 if ( importGeom && isMultiFile )
891 initPart += ("\n## import GEOM dump file ## \n"
892 "import string, os, sys, re\n"
893 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
894 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
896 anUpdatedScript.Insert ( 1, initPart );
898 // add final part of aScript
899 if (aSeq->Value(aLen) < aScriptLength)
900 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
902 // Remove removed objects
903 if ( seqRemoved.Length() > 0 ) {
904 anUpdatedScript += "\n\t## some objects were removed";
905 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
907 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
908 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
909 anUpdatedScript += seqRemoved.Value(ir);
910 // for object wrapped by class of smesh.py
911 anEntry = theObjectNames( seqRemoved.Value(ir) );
912 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
913 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
914 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
918 anUpdatedScript += "\n\t## set object names";
919 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
920 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
921 // anUpdatedScript += "\n";
923 TCollection_AsciiString aGUIName;
924 Resource_DataMapOfAsciiStringAsciiString mapEntries;
925 for (Standard_Integer i = 1; i <= aLen; i += 2)
927 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
928 aName = geom->GetDumpName( anEntry.ToCString() );
929 if (aName.IsEmpty() && // Not a GEOM object
930 theNames.IsBound(anEntry) &&
931 !mapEntries.IsBound(anEntry) && // Not yet processed
932 !mapRemoved.IsBound(anEntry)) // Was not removed
934 aName = theObjectNames.Find(anEntry);
935 aGUIName = theNames.Find(anEntry);
936 mapEntries.Bind(anEntry, aName);
937 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
938 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
939 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
940 anUpdatedScript += helper + ", '" + aGUIName + "')";
944 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
945 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
946 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
948 // -----------------------------------------------------------------
949 // store visual properties of displayed objects
950 // -----------------------------------------------------------------
954 //Output the script that sets up the visual parameters.
955 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
956 if (script && strlen(script) > 0) {
957 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
958 anUpdatedScript += script;
959 CORBA::string_free(script);
964 anUpdatedScript += "\n\tpass";
965 anUpdatedScript += "\n";
967 if( !isMultiFile ) // remove unnecessary tabulation
968 RemoveTabulation( anUpdatedScript );
970 // -----------------------------------------------------------------
971 // put string literals describing patterns into separate functions
972 // -----------------------------------------------------------------
974 TCollection_AsciiString aLongString, aFunctionType;
976 set< string > functionNameSet;
977 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
979 // make a python string literal
980 aLongString.Prepend(":\n\treturn '''\n");
981 aLongString += "\n\t'''\n\tpass\n";
983 TCollection_AsciiString functionName;
985 // check if the function returning this literal is already defined
986 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
987 if ( posAlready ) // already defined
989 // find the function name
990 int functBeg = posAlready;
991 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
992 while ( *script != ' ' ) {
996 functBeg++; // do not take ' '
997 posAlready--; // do not take ':'
998 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1000 else // not defined yet
1002 // find a unique function name
1003 fixPythonName( aFunctionType );
1004 Standard_Integer nb = 0;
1005 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1006 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1009 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1012 anUpdatedScript += helper + "\n\n" + funDef;
1017 anUpdatedScript.Insert( 1, funDef);
1018 where += funDef.Length();
1021 anUpdatedScript.InsertBefore( where, functionName ); // call function
1024 aValidScript = true;
1026 return anUpdatedScript;
1029 //=============================================================================
1033 //=============================================================================
1034 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1036 TCollection_AsciiString aScript;
1038 // Dump trace of API methods calls
1039 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1040 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1041 Standard_Integer istr, aLen = aPythonScript->Length();
1042 for (istr = 1; istr <= aLen; istr++) {
1044 aScript += aPythonScript->Value(istr);
1052 //=============================================================================
1056 //=============================================================================
1057 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1059 TCollection_AsciiString aScript;
1061 // Clean trace of API methods calls
1062 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1063 myPythonScripts[theStudyID]->Clear();