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;
49 size_t TPythonDump::myCounter = 0;
50 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
52 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
53 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
54 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
55 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
57 for ( size_t i = 0; i < value.length(); i++)
58 myVals[i] = SMESH_Comment(value[i]);
62 TPythonDump():myVarsCounter(0)
70 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
71 std::string aString = myStream.str();
72 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
73 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
74 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
75 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
76 if(MYDEBUG) MESSAGE(aString);
77 aSMESHGen->UpdateParameters(""); // prevent misuse of already treated variables
82 TPythonDump& //!< to store a variable value
84 operator<<(const TVar& theVarValue)
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 case BALL: myStream<<"BALL"; break;
169 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
176 operator<<(const SMESH::GeometryType& theArg)
180 case Geom_POINT: myStream<<"Geom_POINT"; break;
181 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
182 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
183 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
184 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
185 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
186 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
187 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
188 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
189 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
190 case Geom_BALL: myStream<<"Geom_BALL"; break;
191 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
197 operator<<(const SMESH::EntityType& theArg)
201 case Entity_0D: myStream<<"Entity_0D"; break;
202 case Entity_Edge: myStream<<"Entity_Edge"; break;
203 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
204 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
205 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
206 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
207 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
208 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
209 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
210 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
211 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
212 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
213 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
214 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
215 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
216 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
217 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
218 case Entity_Penta: myStream<<"Entity_Penta"; break;
219 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
220 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
221 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
222 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
223 case Entity_Ball: myStream<<"Entity_Ball"; break;
224 case Entity_Last: myStream<<"Entity_Last"; break;
225 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
230 template<class TArray>
231 void DumpArray(const TArray& theArray, TPythonDump & theStream)
234 for (int i = 1; i <= theArray.length(); i++) {
235 theStream << theArray[i-1];
236 if ( i < theArray.length() )
243 TPythonDump::operator<<(const SMESH::long_array& theArg)
245 DumpArray( theArg, *this );
250 TPythonDump::operator<<(const SMESH::double_array& theArg)
252 DumpArray( theArg, *this );
257 TPythonDump::operator<<(const SMESH::string_array& theArray)
260 for (int i = 1; i <= theArray.length(); i++) {
261 myStream << "'" << theArray[i-1] << "'";
262 if ( i < theArray.length() )
271 operator<<(SALOMEDS::SObject_ptr aSObject)
273 if ( !aSObject->_is_nil() ) {
274 CORBA::String_var entry = aSObject->GetID();
275 myStream << entry.in();
278 myStream << theNotPublishedObjectName;
285 operator<<(CORBA::Object_ptr theArg)
287 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
288 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
289 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
290 if(!aSObject->_is_nil()) {
291 CORBA::String_var id = aSObject->GetID();
293 } else if ( !CORBA::is_nil(theArg)) {
294 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
295 myStream << "smeshObj_" << size_t(theArg);
297 myStream << theNotPublishedObjectName;
306 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
308 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
309 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
310 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
311 myStream << "hyp_" << theArg->GetId();
313 *this << CORBA::Object_ptr( theArg );
319 operator<<(SMESH::SMESH_IDSource_ptr theArg)
321 if ( CORBA::is_nil( theArg ) )
322 return *this << "None";
323 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
324 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
325 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
326 if(!aSObject->_is_nil())
328 return *this << aSObject;
330 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
332 return *this << filter;
334 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
336 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
337 SMESH::long_array_var anElementsId = theArg->GetIDs();
338 SMESH::array_of_ElementType_var types = theArg->GetTypes();
339 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
340 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
342 return *this << theNotPublishedObjectName;
347 operator<<(SMESH::FilterLibrary_i* theArg)
349 myStream<<"aFilterLibrary"<<theArg;
355 operator<<(SMESH::FilterManager_i* theArg)
357 myStream<<"aFilterManager";
363 operator<<(SMESH::Filter_i* theArg)
365 myStream<<"aFilter"<<theArg;
371 operator<<(SMESH::Functor_i* theArg)
374 FunctorType aFunctorType = theArg->GetFunctorType();
375 switch(aFunctorType){
376 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
377 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
378 case FT_Warping: myStream<< "aWarping"; break;
379 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
380 case FT_Taper: myStream<< "aTaper"; break;
381 case FT_Skew: myStream<< "aSkew"; break;
382 case FT_Area: myStream<< "aArea"; break;
383 case FT_Volume3D: myStream<< "aVolume3D"; break;
384 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
385 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
386 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
387 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
388 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
389 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
390 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
391 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
392 case FT_Length: myStream<< "aLength"; break;
393 case FT_Length2D: myStream<< "aLength2D"; break;
394 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
395 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
396 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
397 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
398 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
399 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
400 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
401 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
402 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
403 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
404 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
405 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
406 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
407 case FT_GroupColor: myStream<< "aGroupColor"; break;
408 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
409 case FT_LessThan: myStream<< "aLessThan"; break;
410 case FT_MoreThan: myStream<< "aMoreThan"; break;
411 case FT_EqualTo: myStream<< "anEqualTo"; break;
412 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
413 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
414 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
416 default: myStream<< "anUndefined"; break;
425 operator<<(SMESH::Measurements_i* theArg)
427 myStream<<"aMeasurements";
432 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
434 myStream << SMESHGenName(); return *this;
437 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
439 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
442 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
444 myStream << theStr; return *this;
448 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
450 switch (theVersion) {
451 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
452 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
453 default: myStream << theVersion;
458 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
460 *this << "SMESH.AxisStruct( "
461 << TVar( theAxis.x ) << ", "
462 << TVar( theAxis.y ) << ", "
463 << TVar( theAxis.z ) << ", "
464 << TVar( theAxis.vx ) << ", "
465 << TVar( theAxis.vy ) << ", "
466 << TVar( theAxis.vz ) << " )";
470 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
472 const SMESH::PointStruct & P = theDir.PS;
473 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
474 << TVar( P.x ) << ", "
475 << TVar( P.y ) << ", "
476 << TVar( P.z ) << " ))";
480 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
482 *this << "SMESH.PointStruct ( "
483 << TVar( P.x ) << ", "
484 << TVar( P.y ) << ", "
485 << TVar( P.z ) << " )";
489 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
491 DumpArray( theList, *this );
494 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
496 DumpArray( *theList, *this );
499 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
501 DumpArray( theList, *this );
504 const char* TPythonDump::NotPublishedObjectName()
506 return theNotPublishedObjectName;
509 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
510 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
512 //================================================================================
514 * \brief Return marker of long string literal beginning
515 * \param type - a name of functionality producing the string literal
516 * \retval TCollection_AsciiString - the marker string to be written into
517 * a raw python script
519 //================================================================================
521 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
525 (Standard_Integer) strlen(type) +
530 //================================================================================
532 * \brief Return marker of long string literal end
533 * \retval TCollection_AsciiString - the marker string to be written into
534 * a raw python script
536 //================================================================================
538 TCollection_AsciiString TPythonDump::LongStringEnd()
540 return myLongStringEnd;
543 //================================================================================
545 * \brief Cut out a long string literal from a string
546 * \param theText - text possibly containing string literals
547 * \param theFrom - position in the text to search from
548 * \param theLongString - the retrieved literal
549 * \param theStringType - a name of functionality produced the literal
550 * \retval bool - true if a string literal found
552 * The literal is removed from theText; theFrom points position right after
553 * the removed literal
555 //================================================================================
557 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
559 TCollection_AsciiString & theLongString,
560 TCollection_AsciiString & theStringType)
562 if ( theFrom < 1 || theFrom > theText.Length() )
565 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
566 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
567 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
570 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
574 // find where literal begins
575 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
576 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
577 int typeLen = atoi ( typeLenStr ); // = 7
578 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
579 literalBeg++; // 26 -> 27
582 literalBeg += typeLen + 1; // = 35
583 if ( literalBeg > theText.Length() )
586 // where literal ends (i.e. end marker begins)
587 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
589 literalEnd = theText.Length();
592 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
594 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
596 literalEnd += myLongStringEnd.Length(); // = 79
597 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
598 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
604 //=======================================================================
605 //function : RemoveTabulation
607 //=======================================================================
608 void RemoveTabulation( TCollection_AsciiString& theScript )
610 std::string aString( theScript.ToCString() );
611 std::string::size_type aPos = 0;
612 while( aPos < aString.length() )
614 aPos = aString.find( "\n\t", aPos );
615 if( aPos == std::string::npos )
617 aString.replace( aPos, 2, "\n" );
620 theScript = aString.c_str();
623 //=======================================================================
624 //function : DumpPython
626 //=======================================================================
627 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
628 CORBA::Boolean isPublished,
629 CORBA::Boolean isMultiFile,
630 CORBA::Boolean& isValidScript)
632 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
633 if (CORBA::is_nil(aStudy))
634 return new Engines::TMPFile(0);
636 CORBA::String_var compDataType = ComponentDataType();
637 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
638 if (CORBA::is_nil(aSO))
639 return new Engines::TMPFile(0);
641 // Map study entries to object names
642 Resource_DataMapOfAsciiStringAsciiString aMap;
643 Resource_DataMapOfAsciiStringAsciiString aMapNames;
644 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
646 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
647 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
648 SALOMEDS::SObject_wrap aValue = Itr->Value();
649 CORBA::String_var anID = aValue->GetID();
650 CORBA::String_var aName = aValue->GetName();
651 TCollection_AsciiString aGUIName ( (char*) aName.in() );
652 TCollection_AsciiString anEnrty ( (char*) anID.in() );
653 if (aGUIName.Length() > 0) {
654 aMapNames.Bind( anEnrty, aGUIName );
655 aMap.Bind( anEnrty, aGUIName );
659 // Get trace of restored study
660 //SALOMEDS::SObject_wrap aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
661 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
662 SALOMEDS::GenericAttribute_wrap anAttr =
663 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
665 SALOMEDS::AttributePythonObject_var pyAttr =
666 SALOMEDS::AttributePythonObject::_narrow(anAttr);
667 CORBA::String_var oldValue = pyAttr->GetObject();
668 TCollection_AsciiString aSavedTrace (oldValue.in());
670 // Add trace of API methods calls and replace study entries by names
671 TCollection_AsciiString aScript;
672 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
673 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
675 int aLen = aScript.Length();
676 unsigned char* aBuffer = new unsigned char[aLen+1];
677 strcpy((char*)aBuffer, aScript.ToCString());
679 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
680 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
682 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
683 isValidScript = isValidScript && !hasNotPublishedObjects;
685 return aStreamFile._retn();
688 //=============================================================================
692 //=============================================================================
693 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
695 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
696 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
698 myPythonScripts[theStudyID]->Append(theString);
701 //=============================================================================
703 * RemoveLastFromPythonScript
705 //=============================================================================
706 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
708 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
709 int aLen = myPythonScripts[theStudyID]->Length();
710 myPythonScripts[theStudyID]->Remove(aLen);
714 //=======================================================================
715 //function : SavePython
717 //=======================================================================
718 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
720 // Dump trace of API methods calls
721 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
723 // Check contents of PythonObject attribute
724 CORBA::String_var compDataType = ComponentDataType();
725 SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
726 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
727 SALOMEDS::GenericAttribute_wrap anAttr =
728 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
730 SALOMEDS::AttributePythonObject_var pyAttr =
731 SALOMEDS::AttributePythonObject::_narrow(anAttr);
732 CORBA::String_var oldValue = pyAttr->GetObject();
733 TCollection_AsciiString oldScript (oldValue.in());
735 if (oldScript.Length() > 0) {
737 oldScript += aScript;
742 // Store in PythonObject attribute
743 pyAttr->SetObject(oldScript.ToCString(), 1);
745 // Clean trace of API methods calls
746 CleanPythonTrace(theStudy->StudyId());
753 //=============================================================================
755 * FindEntries: Returns a sequence of start/end positions of entries in the string
757 //=============================================================================
758 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
760 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
761 Standard_Integer aLen = theString.Length();
762 Standard_Boolean isFound = Standard_False;
764 char* arr = (char*) theString.ToCString();
765 Standard_Integer i = 0, j;
770 if ( isdigit( c )) { //Is digit?
772 isFound = Standard_False;
773 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
775 if(c == ':') isFound = Standard_True;
779 int prev = (i < 1) ? 0 : (int)arr[i - 1];
780 // to distinguish from a sketcher command:
781 // last char should be a digit, not ":",
782 // previous char should not be '"'.
783 if (arr[j-2] != ':' && prev != '"') {
784 aSeq->Append(i+1); // +1 because AsciiString starts from 1
798 //================================================================================
800 * \brief Make a string be a valid python name
801 * \param aName - a string to fix
802 * \retval bool - true if aName was not modified
804 //================================================================================
806 bool fixPythonName(TCollection_AsciiString & aName )
808 const TCollection_AsciiString allowedChars =
809 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
810 bool isValidName = true;
811 int nbUnderscore = 0;
812 int p=1; // replace not allowed chars by underscore
813 while (p <= aName.Length() &&
814 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
816 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
817 aName.Remove( p, 1 ); // remove double _ from the start and the end
819 aName.SetValue(p, '_'), nbUnderscore++;
822 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
823 aName.Insert( 1, 'a' );
826 // shorten names like CartesianParameters3D_400_400_400_1000000_1
827 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
828 posted to SALOME Forum */
829 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
831 p = aName.Location( "_", 20, aName.Length());
839 //=============================================================================
843 //=============================================================================
844 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
845 (SALOMEDS::Study_ptr theStudy,
846 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
847 Resource_DataMapOfAsciiStringAsciiString& theNames,
850 bool isHistoricalDump,
852 const TCollection_AsciiString& theSavedTrace)
854 int aStudyID = theStudy->StudyId();
856 TCollection_AsciiString helper; // to comfortably concatenate C strings
857 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
858 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
859 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
861 TCollection_AsciiString aScript;
863 aScript += "def RebuildData(theStudy):";
865 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
866 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
868 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
870 aScript += aSMESHGen + ".SetCurrentStudy(None)";
872 // import python files corresponding to plugins
873 set<string> moduleNameSet;
874 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
875 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
876 string moduleName = hyp_creator->second->GetModuleName();
877 bool newModule = moduleNameSet.insert( moduleName ).second;
879 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
882 // Dump trace of restored study
883 if (theSavedTrace.Length() > 0) {
884 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
885 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
886 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
888 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
889 if ( !isNewVersion ) {
890 TCollection_AsciiString aSavedTrace( theSavedTrace );
891 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
892 int beg, end = aSavedTrace.Length(), from = 1;
893 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
894 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
895 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
896 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
899 from = beg + aSmeshCall.Length();
901 aScript += helper + "\n" + aSavedTrace;
904 // append a saved trace to the script
905 aScript += helper + "\n" + theSavedTrace;
908 // Dump trace of API methods calls
909 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
910 if (aNewLines.Length() > 0) {
911 aScript += helper + "\n" + aNewLines;
914 // Convert IDL API calls into smesh.py API.
915 // Some objects are wrapped with python classes and
916 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
917 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
918 if ( !getenv("NO_2smeshpy_conversion"))
919 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
920 theObjectNames, theStudy, isHistoricalDump );
922 // Replace characters used instead of quote marks to quote notebook variables
925 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
926 aScript.SetValue( pos, '"' );
929 // Find entries to be replaced by names
930 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
931 Standard_Integer aLen = aSeq->Length();
933 if (aLen == 0 && isMultiFile)
936 // Replace entries by the names
937 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
938 TColStd_SequenceOfAsciiString seqRemoved;
939 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
940 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
941 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
943 // Collect names of GEOM objects to exclude same names of SMESH objects
944 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
945 int ign = 0, nbgn = aGeomNames->length();
946 for (; ign < nbgn; ign++) {
947 aName = aGeomNames[ign];
948 theObjectNames.Bind(aName, "1");
951 bool importGeom = false;
952 for (Standard_Integer i = 1; i <= aLen; i += 2) {
953 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
954 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
956 aName = geom->GetDumpName( anEntry.ToCString() );
957 if (aName.IsEmpty()) {
959 if (theObjectNames.IsBound(anEntry)) {
960 // The Object is in Study
961 aName = theObjectNames.Find(anEntry);
962 // check validity of aName
963 bool isValidName = fixPythonName( aName );
964 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
965 // diff objects have same name - make a new name by appending a digit
966 TCollection_AsciiString aName2;
967 Standard_Integer i = 0;
969 aName2 = aName + "_" + ++i;
970 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
975 theObjectNames(anEntry) = aName;
980 aName = aBaseName + (++objectCounter);
981 } while (theObjectNames.IsBound(aName));
982 seqRemoved.Append(aName);
983 mapRemoved.Bind(anEntry, "1");
984 theObjectNames.Bind(anEntry, aName);
986 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
992 anUpdatedScript += aName;
993 aStart = aSeq->Value(i + 1) + 1;
996 // set initial part of aSript
997 TCollection_AsciiString initPart = "import ";
999 initPart += helper + "salome, ";
1000 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
1001 if ( importGeom && isMultiFile )
1003 initPart += ("\n## import GEOM dump file ## \n"
1004 "import string, os, sys, re\n"
1005 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
1006 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
1008 anUpdatedScript.Insert ( 1, initPart );
1010 // add final part of aScript
1011 if (aLen && aSeq->Value(aLen) < aScriptLength)
1012 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
1014 // Remove removed objects
1015 if ( seqRemoved.Length() > 0 ) {
1016 anUpdatedScript += "\n\t## some objects were removed";
1017 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
1019 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
1020 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1021 anUpdatedScript += seqRemoved.Value(ir);
1022 // for object wrapped by class of smesh.py
1023 anEntry = theObjectNames( seqRemoved.Value(ir) );
1024 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1025 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1026 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
1030 anUpdatedScript += "\n\t## set object names";
1031 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
1032 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
1033 // anUpdatedScript += "\n";
1035 TCollection_AsciiString aGUIName;
1036 Resource_DataMapOfAsciiStringAsciiString mapEntries;
1037 for (Standard_Integer i = 1; i <= aLen; i += 2)
1039 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
1040 aName = geom->GetDumpName( anEntry.ToCString() );
1041 if (aName.IsEmpty() && // Not a GEOM object
1042 theNames.IsBound(anEntry) &&
1043 !mapEntries.IsBound(anEntry) && // Not yet processed
1044 !mapRemoved.IsBound(anEntry)) // Was not removed
1046 aName = theObjectNames.Find(anEntry);
1047 aGUIName = theNames.Find(anEntry);
1048 mapEntries.Bind(anEntry, aName);
1049 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1050 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1051 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1052 anUpdatedScript += helper + ", '" + aGUIName + "')";
1056 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
1057 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
1058 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
1060 // -----------------------------------------------------------------
1061 // store visual properties of displayed objects
1062 // -----------------------------------------------------------------
1066 //Output the script that sets up the visual parameters.
1067 CORBA::String_var compDataType = ComponentDataType();
1068 char* script = theStudy->GetDefaultScript( compDataType.in(), "\t");
1069 if (script && strlen(script) > 0) {
1070 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1071 anUpdatedScript += script;
1072 CORBA::string_free(script);
1077 anUpdatedScript += "\n\tpass";
1078 anUpdatedScript += "\n";
1080 if( !isMultiFile ) // remove unnecessary tabulation
1081 RemoveTabulation( anUpdatedScript );
1083 // -----------------------------------------------------------------
1084 // put string literals describing patterns into separate functions
1085 // -----------------------------------------------------------------
1087 TCollection_AsciiString aLongString, aFunctionType;
1089 set< string > functionNameSet;
1090 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1092 // make a python string literal
1093 aLongString.Prepend(":\n\treturn '''\n");
1094 aLongString += "\n\t'''\n\tpass\n";
1096 TCollection_AsciiString functionName;
1098 // check if the function returning this literal is already defined
1099 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1100 if ( posAlready ) // already defined
1102 // find the function name
1103 int functBeg = posAlready;
1104 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1105 while ( *script != ' ' ) {
1109 functBeg++; // do not take ' '
1110 posAlready--; // do not take ':'
1111 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1113 else // not defined yet
1115 // find a unique function name
1116 fixPythonName( aFunctionType );
1117 Standard_Integer nb = 0;
1118 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1119 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1122 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1125 anUpdatedScript += helper + "\n\n" + funDef;
1130 anUpdatedScript.Insert( 1, funDef);
1131 where += funDef.Length();
1134 anUpdatedScript.InsertBefore( where, functionName ); // call function
1137 aValidScript = true;
1139 return anUpdatedScript;
1142 //=============================================================================
1146 //=============================================================================
1147 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1149 TCollection_AsciiString aScript;
1151 // Dump trace of API methods calls
1152 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1153 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1154 Standard_Integer istr, aLen = aPythonScript->Length();
1155 for (istr = 1; istr <= aLen; istr++) {
1157 aScript += aPythonScript->Value(istr);
1165 //=============================================================================
1169 //=============================================================================
1170 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1172 TCollection_AsciiString aScript;
1174 // Clean trace of API methods calls
1175 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1176 myPythonScripts[theStudyID]->Clear();