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"
29 #include "SMESH_2smeshpy.hxx"
30 #include "SMESH_Comment.hxx"
31 #include "SMESH_Filter_i.hxx"
32 #include "SMESH_Gen_i.hxx"
33 #include "SMESH_MeshEditor_i.hxx"
35 #include <SALOMEDS_wrap.hxx>
37 #include <TColStd_HSequenceOfInteger.hxx>
38 #include <TCollection_AsciiString.hxx>
41 static int MYDEBUG = 0;
43 static int MYDEBUG = 0;
46 static TCollection_AsciiString NotPublishedObjectName()
48 return "__NOT__Published__Object__";
54 size_t TPythonDump::myCounter = 0;
56 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
57 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
58 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
59 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
61 for ( size_t i = 0; i < value.length(); i++)
62 myVals[i] = SMESH_Comment(value[i]);
66 TPythonDump():myVarsCounter(0)
74 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
75 std::string aString = myStream.str();
76 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
77 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
78 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
79 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
80 if(MYDEBUG) MESSAGE(aString);
81 aSMESHGen->UpdateParameters(""); // prevent misuse of already treated variables
86 TPythonDump& //!< to store a variable value
88 operator<<(const TVar& theVarValue)
90 const std::vector< std::string >& varNames = SMESH_Gen_i::GetSMESHGen()->GetLastParameters();
91 if ( theVarValue.myVals.size() != 1 )
94 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
96 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
97 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
99 myStream << theVarValue.myVals[i-1];
100 if ( i < theVarValue.myVals.size() )
108 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
109 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
111 myStream << theVarValue.myVals[0];
119 operator<<(long int theArg){
126 operator<<(int theArg){
133 operator<<(double theArg){
140 operator<<(float theArg){
147 operator<<(const void* theArg){
154 operator<<(const char* theArg){
162 operator<<(const SMESH::ElementType& theArg)
166 case ALL: myStream<<"ALL"; break;
167 case NODE: myStream<<"NODE"; break;
168 case EDGE: myStream<<"EDGE"; break;
169 case FACE: myStream<<"FACE"; break;
170 case VOLUME: myStream<<"VOLUME"; break;
171 case ELEM0D: myStream<<"ELEM0D"; break;
172 case BALL: myStream<<"BALL"; break;
173 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
180 operator<<(const SMESH::GeometryType& theArg)
184 case Geom_POINT: myStream<<"Geom_POINT"; break;
185 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
186 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
187 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
188 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
189 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
190 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
191 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
192 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
193 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
194 case Geom_BALL: myStream<<"Geom_BALL"; break;
195 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
200 template<class TArray>
201 void DumpArray(const TArray& theArray, TPythonDump & theStream)
204 for (int i = 1; i <= theArray.length(); i++) {
205 theStream << theArray[i-1];
206 if ( i < theArray.length() )
213 TPythonDump::operator<<(const SMESH::long_array& theArg)
215 DumpArray( theArg, *this );
220 TPythonDump::operator<<(const SMESH::double_array& theArg)
222 DumpArray( theArg, *this );
227 TPythonDump::operator<<(const SMESH::string_array& theArray)
230 for (int i = 1; i <= theArray.length(); i++) {
231 myStream << "'" << theArray[i-1] << "'";
232 if ( i < theArray.length() )
241 operator<<(SALOMEDS::SObject_ptr aSObject)
243 if ( !aSObject->_is_nil() ) {
244 CORBA::String_var entry = aSObject->GetID();
245 myStream << entry.in();
248 myStream << NotPublishedObjectName();
255 operator<<(CORBA::Object_ptr theArg)
257 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
258 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
259 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
260 if(!aSObject->_is_nil()) {
261 CORBA::String_var id = aSObject->GetID();
263 } else if ( !CORBA::is_nil(theArg)) {
264 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
265 myStream << "smeshObj_" << size_t(theArg);
267 myStream << NotPublishedObjectName();
276 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
278 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
279 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
280 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
281 myStream << "hyp_" << theArg->GetId();
283 *this << CORBA::Object_ptr( theArg );
289 operator<<(SMESH::SMESH_IDSource_ptr theArg)
291 if ( CORBA::is_nil( theArg ) )
292 return *this << "None";
293 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
294 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
295 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
296 if(!aSObject->_is_nil())
298 return *this << aSObject;
300 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
302 return *this << filter;
304 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
306 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
307 SMESH::long_array_var anElementsId = theArg->GetIDs();
308 SMESH::array_of_ElementType_var types = theArg->GetTypes();
309 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
310 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
317 operator<<(SMESH::FilterLibrary_i* theArg)
319 myStream<<"aFilterLibrary"<<theArg;
325 operator<<(SMESH::FilterManager_i* theArg)
327 myStream<<"aFilterManager";
333 operator<<(SMESH::Filter_i* theArg)
335 myStream<<"aFilter"<<theArg;
341 operator<<(SMESH::Functor_i* theArg)
344 FunctorType aFunctorType = theArg->GetFunctorType();
345 switch(aFunctorType){
346 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
347 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
348 case FT_Warping: myStream<< "aWarping"; break;
349 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
350 case FT_Taper: myStream<< "aTaper"; break;
351 case FT_Skew: myStream<< "aSkew"; break;
352 case FT_Area: myStream<< "aArea"; break;
353 case FT_Volume3D: myStream<< "aVolume3D"; break;
354 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
355 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
356 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
357 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
358 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
359 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
360 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
361 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
362 case FT_Length: myStream<< "aLength"; break;
363 case FT_Length2D: myStream<< "aLength2D"; break;
364 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
365 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
366 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
367 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
368 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
369 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
370 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
371 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
372 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
373 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
374 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
375 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
376 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
377 case FT_GroupColor: myStream<< "aGroupColor"; break;
378 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
379 case FT_LessThan: myStream<< "aLessThan"; break;
380 case FT_MoreThan: myStream<< "aMoreThan"; break;
381 case FT_EqualTo: myStream<< "anEqualTo"; break;
382 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
383 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
384 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
386 default: myStream<< "anUndefined"; break;
395 operator<<(SMESH::Measurements_i* theArg)
397 myStream<<"aMeasurements";
402 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
404 myStream << SMESHGenName(); return *this;
407 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
409 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
412 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
414 myStream << theStr; return *this;
418 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
420 switch (theVersion) {
421 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
422 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
423 default: myStream << theVersion;
428 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
430 *this << "SMESH.AxisStruct( "
431 << TVar( theAxis.x ) << ", "
432 << TVar( theAxis.y ) << ", "
433 << TVar( theAxis.z ) << ", "
434 << TVar( theAxis.vx ) << ", "
435 << TVar( theAxis.vy ) << ", "
436 << TVar( theAxis.vz ) << " )";
440 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
442 const SMESH::PointStruct & P = theDir.PS;
443 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
444 << TVar( P.x ) << ", "
445 << TVar( P.y ) << ", "
446 << TVar( P.z ) << " ))";
450 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
452 *this << "SMESH.PointStruct ( "
453 << TVar( P.x ) << ", "
454 << TVar( P.y ) << ", "
455 << TVar( P.z ) << " )";
459 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
461 DumpArray( theList, *this );
464 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
466 DumpArray( *theList, *this );
469 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
471 DumpArray( theList, *this );
475 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
476 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
478 //================================================================================
480 * \brief Return marker of long string literal beginning
481 * \param type - a name of functionality producing the string literal
482 * \retval TCollection_AsciiString - the marker string to be written into
483 * a raw python script
485 //================================================================================
487 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
491 (Standard_Integer) strlen(type) +
496 //================================================================================
498 * \brief Return marker of long string literal end
499 * \retval TCollection_AsciiString - the marker string to be written into
500 * a raw python script
502 //================================================================================
504 TCollection_AsciiString TPythonDump::LongStringEnd()
506 return myLongStringEnd;
509 //================================================================================
511 * \brief Cut out a long string literal from a string
512 * \param theText - text possibly containing string literals
513 * \param theFrom - position in the text to search from
514 * \param theLongString - the retrieved literal
515 * \param theStringType - a name of functionality produced the literal
516 * \retval bool - true if a string literal found
518 * The literal is removed from theText; theFrom points position right after
519 * the removed literal
521 //================================================================================
523 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
525 TCollection_AsciiString & theLongString,
526 TCollection_AsciiString & theStringType)
528 if ( theFrom < 1 || theFrom > theText.Length() )
531 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
532 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
533 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
536 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
540 // find where literal begins
541 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
542 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
543 int typeLen = atoi ( typeLenStr ); // = 7
544 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
545 literalBeg++; // 26 -> 27
548 literalBeg += typeLen + 1; // = 35
549 if ( literalBeg > theText.Length() )
552 // where literal ends (i.e. end marker begins)
553 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
555 literalEnd = theText.Length();
558 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
560 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
562 literalEnd += myLongStringEnd.Length(); // = 79
563 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
564 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
570 //=======================================================================
571 //function : RemoveTabulation
573 //=======================================================================
574 void RemoveTabulation( TCollection_AsciiString& theScript )
576 std::string aString( theScript.ToCString() );
577 std::string::size_type aPos = 0;
578 while( aPos < aString.length() )
580 aPos = aString.find( "\n\t", aPos );
581 if( aPos == std::string::npos )
583 aString.replace( aPos, 2, "\n" );
586 theScript = aString.c_str();
589 //=======================================================================
590 //function : DumpPython
592 //=======================================================================
593 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
594 CORBA::Boolean isPublished,
595 CORBA::Boolean isMultiFile,
596 CORBA::Boolean& isValidScript)
598 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
599 if (CORBA::is_nil(aStudy))
600 return new Engines::TMPFile(0);
602 CORBA::String_var compDataType = ComponentDataType();
603 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
604 if (CORBA::is_nil(aSO))
605 return new Engines::TMPFile(0);
607 // Map study entries to object names
608 Resource_DataMapOfAsciiStringAsciiString aMap;
609 Resource_DataMapOfAsciiStringAsciiString aMapNames;
610 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
612 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
613 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
614 SALOMEDS::SObject_wrap aValue = Itr->Value();
615 CORBA::String_var anID = aValue->GetID();
616 CORBA::String_var aName = aValue->GetName();
617 TCollection_AsciiString aGUIName ( (char*) aName.in() );
618 TCollection_AsciiString anEnrty ( (char*) anID.in() );
619 if (aGUIName.Length() > 0) {
620 aMapNames.Bind( anEnrty, aGUIName );
621 aMap.Bind( anEnrty, aGUIName );
625 // Get trace of restored study
626 //SALOMEDS::SObject_wrap aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
627 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
628 SALOMEDS::GenericAttribute_wrap anAttr =
629 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
631 SALOMEDS::AttributePythonObject_var pyAttr =
632 SALOMEDS::AttributePythonObject::_narrow(anAttr);
633 CORBA::String_var oldValue = pyAttr->GetObject();
634 TCollection_AsciiString aSavedTrace (oldValue.out());
636 // Add trace of API methods calls and replace study entries by names
637 TCollection_AsciiString aScript;
638 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
639 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
641 int aLen = aScript.Length();
642 unsigned char* aBuffer = new unsigned char[aLen+1];
643 strcpy((char*)aBuffer, aScript.ToCString());
645 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
646 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
648 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
649 isValidScript = isValidScript && !hasNotPublishedObjects;
651 return aStreamFile._retn();
654 //=============================================================================
658 //=============================================================================
659 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
661 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
662 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
664 myPythonScripts[theStudyID]->Append(theString);
667 //=============================================================================
669 * RemoveLastFromPythonScript
671 //=============================================================================
672 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
674 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
675 int aLen = myPythonScripts[theStudyID]->Length();
676 myPythonScripts[theStudyID]->Remove(aLen);
680 //=======================================================================
681 //function : SavePython
683 //=======================================================================
684 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
686 // Dump trace of API methods calls
687 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
689 // Check contents of PythonObject attribute
690 CORBA::String_var compDataType = ComponentDataType();
691 SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
692 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
693 SALOMEDS::GenericAttribute_wrap anAttr =
694 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
696 SALOMEDS::AttributePythonObject_var pyAttr =
697 SALOMEDS::AttributePythonObject::_narrow(anAttr);
698 CORBA::String_var oldValue = pyAttr->GetObject();
699 TCollection_AsciiString oldScript (oldValue.out());
701 if (oldScript.Length() > 0) {
703 oldScript += aScript;
708 // Store in PythonObject attribute
709 pyAttr->SetObject(oldScript.ToCString(), 1);
711 // Clean trace of API methods calls
712 CleanPythonTrace(theStudy->StudyId());
719 //=============================================================================
721 * FindEntries: Returns a sequence of start/end positions of entries in the string
723 //=============================================================================
724 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
726 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
727 Standard_Integer aLen = theString.Length();
728 Standard_Boolean isFound = Standard_False;
730 char* arr = (char*) theString.ToCString();
731 Standard_Integer i = 0, j;
736 if ( isdigit( c )) { //Is digit?
738 isFound = Standard_False;
739 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
741 if(c == ':') isFound = Standard_True;
745 int prev = (i < 1) ? 0 : (int)arr[i - 1];
746 // to distinguish from a sketcher command:
747 // last char should be a digit, not ":",
748 // previous char should not be '"'.
749 if (arr[j-2] != ':' && prev != '"') {
750 aSeq->Append(i+1); // +1 because AsciiString starts from 1
764 //================================================================================
766 * \brief Make a string be a valid python name
767 * \param aName - a string to fix
768 * \retval bool - true if aName was not modified
770 //================================================================================
772 bool fixPythonName(TCollection_AsciiString & aName )
774 const TCollection_AsciiString allowedChars =
775 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
776 bool isValidName = true;
777 int nbUnderscore = 0;
778 int p=1; // replace not allowed chars by underscore
779 while (p <= aName.Length() &&
780 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
782 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
783 aName.Remove( p, 1 ); // remove double _ from the start and the end
785 aName.SetValue(p, '_'), nbUnderscore++;
788 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
789 aName.Insert( 1, 'a' );
792 // shorten names like CartesianParameters3D_400_400_400_1000000_1
793 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
794 posted to SALOME Forum */
795 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
797 p = aName.Location( "_", 20, aName.Length());
805 //=============================================================================
809 //=============================================================================
810 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
811 (SALOMEDS::Study_ptr theStudy,
812 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
813 Resource_DataMapOfAsciiStringAsciiString& theNames,
816 bool isHistoricalDump,
818 const TCollection_AsciiString& theSavedTrace)
820 int aStudyID = theStudy->StudyId();
822 TCollection_AsciiString helper; // to comfortably concatenate C strings
823 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
824 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
825 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
827 TCollection_AsciiString aScript;
829 aScript += "def RebuildData(theStudy):";
831 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
832 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
834 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
836 aScript += aSMESHGen + ".SetCurrentStudy(None)";
838 // import python files corresponding to plugins
839 set<string> moduleNameSet;
840 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
841 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
842 string moduleName = hyp_creator->second->GetModuleName();
843 bool newModule = moduleNameSet.insert( moduleName ).second;
845 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
848 // Dump trace of restored study
849 if (theSavedTrace.Length() > 0) {
850 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
851 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
852 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
854 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
855 if ( !isNewVersion ) {
856 TCollection_AsciiString aSavedTrace( theSavedTrace );
857 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
858 int beg, end = aSavedTrace.Length(), from = 1;
859 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
860 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
861 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
862 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
865 from = beg + aSmeshCall.Length();
867 aScript += helper + "\n" + aSavedTrace;
870 // append a saved trace to the script
871 aScript += helper + "\n" + theSavedTrace;
874 // Dump trace of API methods calls
875 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
876 if (aNewLines.Length() > 0) {
877 aScript += helper + "\n" + aNewLines;
880 // Convert IDL API calls into smesh.py API.
881 // Some objects are wrapped with python classes and
882 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
883 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
884 if ( !getenv("NO_2smeshpy_conversion"))
885 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
886 theObjectNames, theStudy, isHistoricalDump );
888 // Replace characters used instead of quote marks to quote notebook variables
891 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
892 aScript.SetValue( pos, '"' );
895 // Find entries to be replaced by names
896 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
897 Standard_Integer aLen = aSeq->Length();
899 if (aLen == 0 && isMultiFile)
902 // Replace entries by the names
903 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
904 TColStd_SequenceOfAsciiString seqRemoved;
905 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
906 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
907 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
909 // Collect names of GEOM objects to exclude same names of SMESH objects
910 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
911 int ign = 0, nbgn = aGeomNames->length();
912 for (; ign < nbgn; ign++) {
913 aName = aGeomNames[ign];
914 theObjectNames.Bind(aName, "1");
917 bool importGeom = false;
918 for (Standard_Integer i = 1; i <= aLen; i += 2) {
919 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
920 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
922 aName = geom->GetDumpName( anEntry.ToCString() );
923 if (aName.IsEmpty()) {
925 if (theObjectNames.IsBound(anEntry)) {
926 // The Object is in Study
927 aName = theObjectNames.Find(anEntry);
928 // check validity of aName
929 bool isValidName = fixPythonName( aName );
930 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
931 // diff objects have same name - make a new name by appending a digit
932 TCollection_AsciiString aName2;
933 Standard_Integer i = 0;
935 aName2 = aName + "_" + ++i;
936 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
941 theObjectNames(anEntry) = aName;
946 aName = aBaseName + (++objectCounter);
947 } while (theObjectNames.IsBound(aName));
948 seqRemoved.Append(aName);
949 mapRemoved.Bind(anEntry, "1");
950 theObjectNames.Bind(anEntry, aName);
952 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
958 anUpdatedScript += aName;
959 aStart = aSeq->Value(i + 1) + 1;
962 // set initial part of aSript
963 TCollection_AsciiString initPart = "import ";
965 initPart += helper + "salome, ";
966 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
967 if ( importGeom && isMultiFile )
969 initPart += ("\n## import GEOM dump file ## \n"
970 "import string, os, sys, re\n"
971 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
972 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
974 anUpdatedScript.Insert ( 1, initPart );
976 // add final part of aScript
977 if (aLen && aSeq->Value(aLen) < aScriptLength)
978 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
980 // Remove removed objects
981 if ( seqRemoved.Length() > 0 ) {
982 anUpdatedScript += "\n\t## some objects were removed";
983 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
985 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
986 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
987 anUpdatedScript += seqRemoved.Value(ir);
988 // for object wrapped by class of smesh.py
989 anEntry = theObjectNames( seqRemoved.Value(ir) );
990 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
991 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
992 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
996 anUpdatedScript += "\n\t## set object names";
997 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
998 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
999 // anUpdatedScript += "\n";
1001 TCollection_AsciiString aGUIName;
1002 Resource_DataMapOfAsciiStringAsciiString mapEntries;
1003 for (Standard_Integer i = 1; i <= aLen; i += 2)
1005 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
1006 aName = geom->GetDumpName( anEntry.ToCString() );
1007 if (aName.IsEmpty() && // Not a GEOM object
1008 theNames.IsBound(anEntry) &&
1009 !mapEntries.IsBound(anEntry) && // Not yet processed
1010 !mapRemoved.IsBound(anEntry)) // Was not removed
1012 aName = theObjectNames.Find(anEntry);
1013 aGUIName = theNames.Find(anEntry);
1014 mapEntries.Bind(anEntry, aName);
1015 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1016 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1017 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1018 anUpdatedScript += helper + ", '" + aGUIName + "')";
1022 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
1023 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
1024 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
1026 // -----------------------------------------------------------------
1027 // store visual properties of displayed objects
1028 // -----------------------------------------------------------------
1032 //Output the script that sets up the visual parameters.
1033 CORBA::String_var compDataType = ComponentDataType();
1034 char* script = theStudy->GetDefaultScript( compDataType.in(), "\t");
1035 if (script && strlen(script) > 0) {
1036 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1037 anUpdatedScript += script;
1038 CORBA::string_free(script);
1043 anUpdatedScript += "\n\tpass";
1044 anUpdatedScript += "\n";
1046 if( !isMultiFile ) // remove unnecessary tabulation
1047 RemoveTabulation( anUpdatedScript );
1049 // -----------------------------------------------------------------
1050 // put string literals describing patterns into separate functions
1051 // -----------------------------------------------------------------
1053 TCollection_AsciiString aLongString, aFunctionType;
1055 set< string > functionNameSet;
1056 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1058 // make a python string literal
1059 aLongString.Prepend(":\n\treturn '''\n");
1060 aLongString += "\n\t'''\n\tpass\n";
1062 TCollection_AsciiString functionName;
1064 // check if the function returning this literal is already defined
1065 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1066 if ( posAlready ) // already defined
1068 // find the function name
1069 int functBeg = posAlready;
1070 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1071 while ( *script != ' ' ) {
1075 functBeg++; // do not take ' '
1076 posAlready--; // do not take ':'
1077 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1079 else // not defined yet
1081 // find a unique function name
1082 fixPythonName( aFunctionType );
1083 Standard_Integer nb = 0;
1084 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1085 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1088 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1091 anUpdatedScript += helper + "\n\n" + funDef;
1096 anUpdatedScript.Insert( 1, funDef);
1097 where += funDef.Length();
1100 anUpdatedScript.InsertBefore( where, functionName ); // call function
1103 aValidScript = true;
1105 return anUpdatedScript;
1108 //=============================================================================
1112 //=============================================================================
1113 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1115 TCollection_AsciiString aScript;
1117 // Dump trace of API methods calls
1118 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1119 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1120 Standard_Integer istr, aLen = aPythonScript->Length();
1121 for (istr = 1; istr <= aLen; istr++) {
1123 aScript += aPythonScript->Value(istr);
1131 //=============================================================================
1135 //=============================================================================
1136 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1138 TCollection_AsciiString aScript;
1140 // Clean trace of API methods calls
1141 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1142 myPythonScripts[theStudyID]->Clear();