1 // Copyright (C) 2007-2012 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;
47 size_t TPythonDump::myCounter = 0;
48 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
50 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
51 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
52 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
53 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
55 for ( size_t i = 0; i < value.length(); i++)
56 myVals[i] = SMESH_Comment(value[i]);
60 TPythonDump():myVarsCounter(0)
68 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
69 std::string aString = myStream.str();
70 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
71 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
72 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
73 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
74 if(MYDEBUG) MESSAGE(aString);
75 aSMESHGen->UpdateParameters(""); // prevent misuse of already treated variables
80 TPythonDump& //!< to store a variable value
82 operator<<(const TVar& theVarValue)
84 if ( theVarValue.myVals.empty() ) return *this;
86 const std::vector< std::string >& varNames = SMESH_Gen_i::GetSMESHGen()->GetLastParameters();
87 if ( theVarValue.myVals.size() > 1 )
90 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
92 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
93 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
95 myStream << theVarValue.myVals[i-1];
96 if ( i < theVarValue.myVals.size() )
104 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
105 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
107 myStream << theVarValue.myVals[0];
115 operator<<(long int theArg){
122 operator<<(int theArg){
129 operator<<(double theArg){
136 operator<<(float theArg){
143 operator<<(const void* theArg){
150 operator<<(const char* theArg){
158 operator<<(const SMESH::ElementType& theArg)
162 case ALL: myStream<<"ALL";break;
163 case NODE: myStream<<"NODE";break;
164 case EDGE: myStream<<"EDGE";break;
165 case FACE: myStream<<"FACE";break;
166 case VOLUME:myStream<<"VOLUME";break;
167 case ELEM0D:myStream<<"ELEM0D";break;
168 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
175 operator<<(const SMESH::GeometryType& theArg)
179 case Geom_POINT: myStream<<"Geom_POINT"; break;
180 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
181 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
182 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
183 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
184 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
185 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
186 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
187 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
188 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
189 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
194 template<class TArray>
195 void DumpArray(const TArray& theArray, TPythonDump & theStream)
198 for (int i = 1; i <= theArray.length(); i++) {
199 theStream << theArray[i-1];
200 if ( i < theArray.length() )
207 TPythonDump::operator<<(const SMESH::long_array& theArg)
209 DumpArray( theArg, *this );
214 TPythonDump::operator<<(const SMESH::double_array& theArg)
216 DumpArray( theArg, *this );
221 TPythonDump::operator<<(const SMESH::string_array& theArray)
224 for (int i = 1; i <= theArray.length(); i++) {
225 myStream << "'" << theArray[i-1] << "'";
226 if ( i < theArray.length() )
235 operator<<(SALOMEDS::SObject_ptr aSObject)
237 if ( !aSObject->_is_nil() ) {
\r
238 CORBA::String_var entry = aSObject->GetID();
\r
239 myStream << entry.in();
\r
242 myStream << theNotPublishedObjectName;
\r
249 operator<<(CORBA::Object_ptr theArg)
251 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
252 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
253 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
254 if(!aSObject->_is_nil()) {
255 CORBA::String_var id = aSObject->GetID();
257 } else if ( !CORBA::is_nil(theArg)) {
258 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
259 myStream << "smeshObj_" << size_t(theArg);
261 myStream << theNotPublishedObjectName;
270 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
272 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
273 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
274 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
275 myStream << "hyp_" << theArg->GetId();
277 *this << CORBA::Object_ptr( theArg );
283 operator<<(SMESH::SMESH_IDSource_ptr theArg)
285 if ( CORBA::is_nil( theArg ) )
286 return *this << "None";
287 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
288 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
289 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
290 if(!aSObject->_is_nil())
291 return *this << aSObject;
292 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
293 return *this << filter;
294 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
295 if ( !theArg->_is_equivalent( mesh ))
297 SMESH::long_array_var anElementsId = theArg->GetIDs();
298 SMESH::array_of_ElementType_var types = theArg->GetTypes();
299 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
300 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
302 return *this << theNotPublishedObjectName;
307 operator<<(SMESH::FilterLibrary_i* theArg)
309 myStream<<"aFilterLibrary"<<theArg;
315 operator<<(SMESH::FilterManager_i* theArg)
317 myStream<<"aFilterManager";
323 operator<<(SMESH::Filter_i* theArg)
325 myStream<<"aFilter"<<theArg;
331 operator<<(SMESH::Functor_i* theArg)
334 FunctorType aFunctorType = theArg->GetFunctorType();
335 switch(aFunctorType){
336 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
337 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
338 case FT_Warping: myStream<< "aWarping"; break;
339 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
340 case FT_Taper: myStream<< "aTaper"; break;
341 case FT_Skew: myStream<< "aSkew"; break;
342 case FT_Area: myStream<< "aArea"; break;
343 case FT_Volume3D: myStream<< "aVolume3D"; break;
344 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
345 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
346 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
347 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
348 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
349 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
350 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
351 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
352 case FT_Length: myStream<< "aLength"; break;
353 case FT_Length2D: myStream<< "aLength2D"; break;
354 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
355 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
356 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
357 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
358 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
359 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
360 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
361 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
362 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
363 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
364 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
365 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
366 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
367 case FT_GroupColor: myStream<< "aGroupColor"; break;
368 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
369 case FT_LessThan: myStream<< "aLessThan"; break;
370 case FT_MoreThan: myStream<< "aMoreThan"; break;
371 case FT_EqualTo: myStream<< "anEqualTo"; break;
372 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
373 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
374 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
376 default: myStream<< "anUndefined"; break;
385 operator<<(SMESH::Measurements_i* theArg)
387 myStream<<"aMeasurements";
392 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
394 myStream << SMESHGenName(); return *this;
397 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
399 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
402 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
404 myStream << theStr; return *this;
408 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
410 switch (theVersion) {
411 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
412 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
413 default: myStream << theVersion;
418 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
420 *this << "SMESH.AxisStruct( "
421 << TVar( theAxis.x ) << ", "
422 << TVar( theAxis.y ) << ", "
423 << TVar( theAxis.z ) << ", "
424 << TVar( theAxis.vx ) << ", "
425 << TVar( theAxis.vy ) << ", "
426 << TVar( theAxis.vz ) << " )";
430 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
432 const SMESH::PointStruct & P = theDir.PS;
433 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
434 << TVar( P.x ) << ", "
435 << TVar( P.y ) << ", "
436 << TVar( P.z ) << " ))";
440 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
442 *this << "SMESH.PointStruct ( "
443 << TVar( P.x ) << ", "
444 << TVar( P.y ) << ", "
445 << TVar( P.z ) << " )";
449 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
451 DumpArray( theList, *this );
454 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
456 DumpArray( *theList, *this );
459 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
461 DumpArray( theList, *this );
464 const char* TPythonDump::NotPublishedObjectName()
\r
466 return theNotPublishedObjectName;
\r
469 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
470 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
472 //================================================================================
474 * \brief Return marker of long string literal beginning
475 * \param type - a name of functionality producing the string literal
476 * \retval TCollection_AsciiString - the marker string to be written into
477 * a raw python script
479 //================================================================================
481 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
485 (Standard_Integer) strlen(type) +
490 //================================================================================
492 * \brief Return marker of long string literal end
493 * \retval TCollection_AsciiString - the marker string to be written into
494 * a raw python script
496 //================================================================================
498 TCollection_AsciiString TPythonDump::LongStringEnd()
500 return myLongStringEnd;
503 //================================================================================
505 * \brief Cut out a long string literal from a string
506 * \param theText - text possibly containing string literals
507 * \param theFrom - position in the text to search from
508 * \param theLongString - the retrieved literal
509 * \param theStringType - a name of functionality produced the literal
510 * \retval bool - true if a string literal found
512 * The literal is removed from theText; theFrom points position right after
513 * the removed literal
515 //================================================================================
517 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
519 TCollection_AsciiString & theLongString,
520 TCollection_AsciiString & theStringType)
522 if ( theFrom < 1 || theFrom > theText.Length() )
525 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
526 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
527 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
530 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
534 // find where literal begins
535 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
536 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
537 int typeLen = atoi ( typeLenStr ); // = 7
538 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
539 literalBeg++; // 26 -> 27
542 literalBeg += typeLen + 1; // = 35
543 if ( literalBeg > theText.Length() )
546 // where literal ends (i.e. end marker begins)
547 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
549 literalEnd = theText.Length();
552 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
554 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
556 literalEnd += myLongStringEnd.Length(); // = 79
557 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
558 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
564 //=======================================================================
565 //function : RemoveTabulation
567 //=======================================================================
568 void RemoveTabulation( TCollection_AsciiString& theScript )
570 std::string aString( theScript.ToCString() );
571 std::string::size_type aPos = 0;
572 while( aPos < aString.length() )
574 aPos = aString.find( "\n\t", aPos );
575 if( aPos == std::string::npos )
577 aString.replace( aPos, 2, "\n" );
580 theScript = aString.c_str();
583 //=======================================================================
584 //function : DumpPython
586 //=======================================================================
587 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
588 CORBA::Boolean isPublished,
589 CORBA::Boolean isMultiFile,
590 CORBA::Boolean& isValidScript)
592 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
593 if (CORBA::is_nil(aStudy))
594 return new Engines::TMPFile(0);
596 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
597 if (CORBA::is_nil(aSO))
598 return new Engines::TMPFile(0);
600 // Map study entries to object names
601 Resource_DataMapOfAsciiStringAsciiString aMap;
602 Resource_DataMapOfAsciiStringAsciiString aMapNames;
603 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
605 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
606 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
607 SALOMEDS::SObject_var aValue = Itr->Value();
608 CORBA::String_var anID = aValue->GetID();
609 CORBA::String_var aName = aValue->GetName();
610 TCollection_AsciiString aGUIName ( (char*) aName.in() );
611 TCollection_AsciiString anEnrty ( (char*) anID.in() );
612 if (aGUIName.Length() > 0) {
613 aMapNames.Bind( anEnrty, aGUIName );
614 aMap.Bind( anEnrty, aGUIName );
618 // Get trace of restored study
619 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
620 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
621 SALOMEDS::GenericAttribute_var anAttr =
622 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
624 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
625 TCollection_AsciiString aSavedTrace (oldValue);
627 // Add trace of API methods calls and replace study entries by names
628 TCollection_AsciiString aScript;
629 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
630 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
632 int aLen = aScript.Length();
633 unsigned char* aBuffer = new unsigned char[aLen+1];
634 strcpy((char*)aBuffer, aScript.ToCString());
636 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
637 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
639 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
640 isValidScript = isValidScript && !hasNotPublishedObjects;
642 return aStreamFile._retn();
645 //=============================================================================
649 //=============================================================================
650 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
652 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
653 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
655 myPythonScripts[theStudyID]->Append(theString);
658 //=============================================================================
660 * RemoveLastFromPythonScript
662 //=============================================================================
663 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
665 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
666 int aLen = myPythonScripts[theStudyID]->Length();
667 myPythonScripts[theStudyID]->Remove(aLen);
671 //=======================================================================
672 //function : SavePython
674 //=======================================================================
675 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
677 // Dump trace of API methods calls
678 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
680 // Check contents of PythonObject attribute
681 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
682 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
683 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
684 SALOMEDS::GenericAttribute_var anAttr =
685 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
687 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
688 TCollection_AsciiString oldScript (oldValue);
690 if (oldScript.Length() > 0) {
692 oldScript += aScript;
697 // Store in PythonObject attribute
698 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
700 // Clean trace of API methods calls
701 CleanPythonTrace(theStudy->StudyId());
708 //=============================================================================
710 * FindEntries: Returns a sequence of start/end positions of entries in the string
712 //=============================================================================
713 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
715 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
716 Standard_Integer aLen = theString.Length();
717 Standard_Boolean isFound = Standard_False;
719 char* arr = (char*) theString.ToCString();
720 Standard_Integer i = 0, j;
725 if ( isdigit( c )) { //Is digit?
727 isFound = Standard_False;
728 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
730 if(c == ':') isFound = Standard_True;
734 int prev = (i < 1) ? 0 : (int)arr[i - 1];
735 // to distinguish from a sketcher command:
736 // last char should be a digit, not ":",
737 // previous char should not be '"'.
738 if (arr[j-2] != ':' && prev != '"') {
739 aSeq->Append(i+1); // +1 because AsciiString starts from 1
753 //================================================================================
755 * \brief Make a string be a valid python name
756 * \param aName - a string to fix
757 * \retval bool - true if aName was not modified
759 //================================================================================
761 bool fixPythonName(TCollection_AsciiString & aName )
763 const TCollection_AsciiString allowedChars =
764 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
765 bool isValidName = true;
766 int nbUnderscore = 0;
767 int p=1; // replace not allowed chars by underscore
768 while (p <= aName.Length() &&
769 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
771 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
772 aName.Remove( p, 1 ); // remove double _ from the start and the end
774 aName.SetValue(p, '_'), nbUnderscore++;
777 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
778 aName.Insert( 1, 'a' );
781 // shorten names like CartesianParameters3D_400_400_400_1000000_1
782 if ( aName.Length() > 20 && nbUnderscore > 2 )
784 p = aName.Location( "_", 20, aName.Length());
792 //=============================================================================
796 //=============================================================================
797 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
798 (SALOMEDS::Study_ptr theStudy,
799 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
800 Resource_DataMapOfAsciiStringAsciiString& theNames,
803 bool isHistoricalDump,
805 const TCollection_AsciiString& theSavedTrace)
807 int aStudyID = theStudy->StudyId();
809 TCollection_AsciiString helper; // to comfortably concatenate C strings
810 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
811 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
812 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
814 TCollection_AsciiString aScript;
816 aScript += "def RebuildData(theStudy):";
818 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
819 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
821 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
823 aScript += aSMESHGen + ".SetCurrentStudy(None)";
825 // import python files corresponding to plugins
826 set<string> moduleNameSet;
827 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
828 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
829 string moduleName = hyp_creator->second->GetModuleName();
830 bool newModule = moduleNameSet.insert( moduleName ).second;
832 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
835 // Dump trace of restored study
836 if (theSavedTrace.Length() > 0) {
837 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
838 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
839 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
841 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
842 if ( !isNewVersion ) {
843 TCollection_AsciiString aSavedTrace( theSavedTrace );
844 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
845 int beg, end = aSavedTrace.Length(), from = 1;
846 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
847 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
848 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
849 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
852 from = beg + aSmeshCall.Length();
854 aScript += helper + "\n" + aSavedTrace;
857 // append a saved trace to the script
858 aScript += helper + "\n" + theSavedTrace;
861 // Dump trace of API methods calls
862 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
863 if (aNewLines.Length() > 0) {
864 aScript += helper + "\n" + aNewLines;
867 // Convert IDL API calls into smesh.py API.
868 // Some objects are wrapped with python classes and
869 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
870 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
871 std::set< TCollection_AsciiString > aRemovedObjIDs;
872 if ( !getenv("NO_2smeshpy_conversion"))
873 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
\r
874 theObjectNames, aRemovedObjIDs,
\r
875 theStudy, isHistoricalDump );
877 // Replace characters used instead of quote marks to quote notebook variables
880 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
881 aScript.SetValue( pos, '"' );
884 // Find entries to be replaced by names
885 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
886 Standard_Integer aLen = aSeq->Length();
888 if (aLen == 0 && isMultiFile)
891 // Replace entries by the names
892 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
893 TColStd_SequenceOfAsciiString seqRemoved;
894 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
895 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
896 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
898 // Collect names of GEOM objects to exclude same names of SMESH objects
899 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
900 int ign = 0, nbgn = aGeomNames->length();
901 for (; ign < nbgn; ign++) {
902 aName = aGeomNames[ign];
903 theObjectNames.Bind(aName, "1");
906 bool importGeom = false;
907 for (Standard_Integer i = 1; i <= aLen; i += 2) {
908 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
909 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
911 aName = geom->GetDumpName( anEntry.ToCString() );
912 if (aName.IsEmpty()) {
914 if (theObjectNames.IsBound(anEntry)) {
915 // The Object is in Study
916 aName = theObjectNames.Find(anEntry);
917 // check validity of aName
918 bool isValidName = fixPythonName( aName );
919 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
920 // diff objects have same name - make a new name by appending a digit
921 TCollection_AsciiString aName2;
922 Standard_Integer i = 0;
924 aName2 = aName + "_" + ++i;
925 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
930 theObjectNames(anEntry) = aName;
935 aName = aBaseName + (++objectCounter);
936 } while (theObjectNames.IsBound(aName));
937 if ( !aRemovedObjIDs.count( anEntry ))
938 seqRemoved.Append(aName);
939 mapRemoved.Bind(anEntry, "1");
940 theObjectNames.Bind(anEntry, aName);
942 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
948 anUpdatedScript += aName;
949 aStart = aSeq->Value(i + 1) + 1;
952 // set initial part of aSript
953 TCollection_AsciiString initPart = "import ";
955 initPart += helper + "salome, ";
956 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
957 if ( importGeom && isMultiFile )
959 initPart += ("\n## import GEOM dump file ## \n"
960 "import string, os, sys, re\n"
961 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
962 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
964 anUpdatedScript.Insert ( 1, initPart );
966 // add final part of aScript
967 if (aLen && aSeq->Value(aLen) < aScriptLength)
968 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
970 // Remove removed objects
971 if ( seqRemoved.Length() > 0 ) {
972 anUpdatedScript += "\n\t## some objects were removed";
973 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
975 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
976 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
977 anUpdatedScript += seqRemoved.Value(ir);
978 // for object wrapped by class of smesh.py
979 anEntry = theObjectNames( seqRemoved.Value(ir) );
980 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
981 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
982 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
987 TCollection_AsciiString aGUIName, aSetNameScriptPart;
988 Resource_DataMapOfAsciiStringAsciiString mapEntries;
989 for (Standard_Integer i = 1; i <= aLen; i += 2)
991 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
992 aName = geom->GetDumpName( anEntry.ToCString() );
993 if (aName.IsEmpty() && // Not a GEOM object
994 theNames.IsBound(anEntry) &&
995 !aRemovedObjIDs.count(anEntry) && // a command creating anEntry was erased
996 !mapEntries.IsBound(anEntry) && // Not yet processed
997 !mapRemoved.IsBound(anEntry)) // Was not removed
999 aName = theObjectNames.Find(anEntry);
1000 aGUIName = theNames.Find(anEntry);
1001 mapEntries.Bind(anEntry, aName);
1002 aSetNameScriptPart += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1003 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1004 aSetNameScriptPart += helper + "." + anEntry2AccessorMethod( anEntry );
1005 aSetNameScriptPart += helper + ", '" + aGUIName + "')";
1008 if ( !aSetNameScriptPart.IsEmpty() )
\r
1010 anUpdatedScript += "\n\t## set object names";
\r
1011 anUpdatedScript += aSetNameScriptPart;
\r
1014 // -----------------------------------------------------------------
1015 // store visual properties of displayed objects
1016 // -----------------------------------------------------------------
1020 //Output the script that sets up the visual parameters.
1021 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
1022 if (script && strlen(script) > 0) {
1023 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1024 anUpdatedScript += script;
1025 CORBA::string_free(script);
1030 anUpdatedScript += "\n\tpass";
1031 anUpdatedScript += "\n";
1033 if( !isMultiFile ) // remove unnecessary tabulation
1034 RemoveTabulation( anUpdatedScript );
1036 // -----------------------------------------------------------------
1037 // put string literals describing patterns into separate functions
1038 // -----------------------------------------------------------------
1040 TCollection_AsciiString aLongString, aFunctionType;
1042 set< string > functionNameSet;
1043 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1045 // make a python string literal
1046 aLongString.Prepend(":\n\treturn '''\n");
1047 aLongString += "\n\t'''\n\tpass\n";
1049 TCollection_AsciiString functionName;
1051 // check if the function returning this literal is already defined
1052 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1053 if ( posAlready ) // already defined
1055 // find the function name
1056 int functBeg = posAlready;
1057 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1058 while ( *script != ' ' ) {
1062 functBeg++; // do not take ' '
1063 posAlready--; // do not take ':'
1064 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1066 else // not defined yet
1068 // find a unique function name
1069 fixPythonName( aFunctionType );
1070 Standard_Integer nb = 0;
1071 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1072 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1075 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1078 anUpdatedScript += helper + "\n\n" + funDef;
1083 anUpdatedScript.Insert( 1, funDef);
1084 where += funDef.Length();
1087 anUpdatedScript.InsertBefore( where, functionName ); // call function
1090 aValidScript = true;
1092 return anUpdatedScript;
1095 //=============================================================================
1099 //=============================================================================
1100 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1102 TCollection_AsciiString aScript;
1104 // Dump trace of API methods calls
1105 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1106 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1107 Standard_Integer istr, aLen = aPythonScript->Length();
1108 for (istr = 1; istr <= aLen; istr++) {
1110 aScript += aPythonScript->Value(istr);
1118 //=============================================================================
1122 //=============================================================================
1123 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1125 TCollection_AsciiString aScript;
1127 // Clean trace of API methods calls
1128 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1129 myPythonScripts[theStudyID]->Clear();