1 // Copyright (C) 2007-2019 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, or (at your option) any later version.
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 <Basics_Utils.hxx>
36 #include <SALOMEDS_wrap.hxx>
38 #include <LDOMParser.hxx>
39 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
40 #include <TColStd_HSequenceOfInteger.hxx>
41 #include <TCollection_AsciiString.hxx>
44 static int MYDEBUG = 0;
46 static int MYDEBUG = 0;
49 #include "SMESH_TryCatch.hxx"
54 size_t TPythonDump::myCounter = 0;
55 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
57 TVar::TVar(CORBA::Double value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
58 TVar::TVar(CORBA::Long value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
59 TVar::TVar(CORBA::Short value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
60 TVar::TVar(const SMESH::double_array& value):myVals(value.length()), myIsList(true)
62 for ( size_t i = 0; i < value.length(); i++)
63 myVals[i] = SMESH_Comment(value[i]);
67 TPythonDump():myVarsCounter(0)
75 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
76 std::string aString = myStream.str();
77 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
78 if(!aCollection.IsEmpty())
80 const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
81 if ( !objEntry.empty() )
82 aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
83 aSMESHGen->AddToPythonScript(aCollection);
84 if(MYDEBUG) MESSAGE(aString);
85 // prevent misuse of already treated variables
86 aSMESHGen->UpdateParameters(CORBA::Object_var().in(),"");
91 TPythonDump& //!< store a variable value. Write either a value or '$varID$'
93 operator<<(const TVar& theVarValue)
95 const std::vector< int >& varIDs = SMESH_Gen_i::GetSMESHGen()->GetLastParamIndices();
96 if ( theVarValue.myIsList )
99 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
101 if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
102 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
104 myStream << theVarValue.myVals[i-1];
105 if ( i < theVarValue.myVals.size() )
113 if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
114 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
116 myStream << theVarValue.myVals[0];
124 operator<<(long int theArg){
131 operator<<(int theArg){
138 operator<<(double theArg){
145 operator<<(float theArg){
152 operator<<(const void* theArg){
159 operator<<(const char* theArg){
167 operator<<(const std::string& theArg){
174 operator<<(const SMESH::ElementType& theArg)
178 case ALL: myStream<<"ALL"; break;
179 case NODE: myStream<<"NODE"; break;
180 case EDGE: myStream<<"EDGE"; break;
181 case FACE: myStream<<"FACE"; break;
182 case VOLUME: myStream<<"VOLUME"; break;
183 case ELEM0D: myStream<<"ELEM0D"; break;
184 case BALL: myStream<<"BALL"; break;
185 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
192 operator<<(const SMESH::GeometryType& theArg)
196 case Geom_POINT: myStream<<"Geom_POINT"; break;
197 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
198 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
199 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
200 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
201 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
202 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
203 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
204 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
205 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
206 case Geom_BALL: myStream<<"Geom_BALL"; break;
207 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
213 operator<<(const SMESH::EntityType& theArg)
217 case Entity_0D: myStream<<"Entity_0D"; break;
218 case Entity_Edge: myStream<<"Entity_Edge"; break;
219 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
220 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
221 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
222 case Entity_BiQuad_Triangle: myStream<<"Entity_BiQuad_Triangle"; break;
223 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
224 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
225 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
226 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
227 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
228 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
229 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
230 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
231 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
232 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
233 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
234 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
235 case Entity_Penta: myStream<<"Entity_Penta"; break;
236 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
237 case Entity_BiQuad_Penta: myStream<<"Entity_BiQuad_Penta"; break;
238 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
239 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
240 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
241 case Entity_Ball: myStream<<"Entity_Ball"; break;
242 case Entity_Last: myStream<<"Entity_Last"; break;
243 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
249 TPythonDump::operator<<(const SMESH::long_array& theArg)
251 DumpArray( theArg, *this );
256 TPythonDump::operator<<(const SMESH::double_array& theArg)
258 DumpArray( theArg, *this );
263 TPythonDump::operator<<(const SMESH::nodes_array& theArg)
265 DumpArray( theArg, *this );
270 TPythonDump::operator<<(const SMESH::string_array& theArray)
273 for ( CORBA::ULong i = 1; i <= theArray.length(); i++ ) {
274 myStream << "'" << theArray[i-1] << "'";
275 if ( i < theArray.length() )
284 operator<<(SALOMEDS::SObject_ptr aSObject)
286 if ( !aSObject->_is_nil() ) {
287 CORBA::String_var entry = aSObject->GetID();
288 myStream << entry.in();
291 myStream << theNotPublishedObjectName;
298 operator<<(CORBA::Object_ptr theArg)
300 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
301 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
302 if(!aSObject->_is_nil()) {
303 CORBA::String_var id = aSObject->GetID();
305 } else if ( !CORBA::is_nil(theArg)) {
306 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
307 myStream << "smeshObj_" << size_t(theArg);
309 myStream << theNotPublishedObjectName;
318 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
320 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
321 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
322 myStream << "hyp_" << theArg->GetId();
330 operator<<(SMESH::SMESH_IDSource_ptr theArg)
332 if ( CORBA::is_nil( theArg ) )
333 return *this << "None";
334 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
335 if(!aSObject->_is_nil())
337 return *this << aSObject;
339 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
341 return *this << filter;
343 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
345 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
346 SMESH::long_array_var anElementsId = theArg->GetIDs();
347 SMESH::array_of_ElementType_var types = theArg->GetTypes();
348 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
349 SALOMEDS::SObject_wrap meshSO = SMESH_Gen_i::ObjectToSObject(mesh);
350 if ( meshSO->_is_nil() ) // don't waste memory for dumping not published objects
351 return *this << mesh << ".GetIDSource([], " << type << ")";
353 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
355 return *this << theNotPublishedObjectName;
360 operator<<(SMESH::FilterLibrary_i* theArg)
362 myStream<<"aFilterLibrary"<<theArg;
368 operator<<(SMESH::FilterManager_i* theArg)
370 myStream<<"aFilterManager";
376 operator<<(SMESH::Filter_i* theArg)
378 myStream<<"aFilter"<<theArg;
384 operator<<(SMESH::Functor_i* theArg)
387 FunctorType aFunctorType = theArg->GetFunctorType();
388 switch(aFunctorType) {
389 case FT_AspectRatio: myStream<< "aAspectRatio"; break;
390 case FT_AspectRatio3D: myStream<< "aAspectRatio3D"; break;
391 case FT_Warping: myStream<< "aWarping"; break;
392 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
393 case FT_Taper: myStream<< "aTaper"; break;
394 case FT_Skew: myStream<< "aSkew"; break;
395 case FT_Area: myStream<< "aArea"; break;
396 case FT_Volume3D: myStream<< "aVolume3D"; break;
397 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
398 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
399 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
400 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
401 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
402 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
403 case FT_EqualNodes: myStream<< "aEqualNodes"; break;
404 case FT_EqualEdges: myStream<< "aEqualEdges"; break;
405 case FT_EqualFaces: myStream<< "aEqualFaces"; break;
406 case FT_EqualVolumes: myStream<< "aEqualVolumes"; break;
407 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
408 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
409 case FT_Length: myStream<< "aLength"; break;
410 case FT_Length2D: myStream<< "aLength2D"; break;
411 case FT_Length3D: myStream<< "aLength3D"; break;
412 case FT_Deflection2D: myStream<< "aDeflection2D"; break;
413 case FT_NodeConnectivityNumber:myStream<< "aNodeConnectivityNumber";break;
414 case FT_BelongToMeshGroup: myStream<< "aBelongToMeshGroup"; break;
415 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
416 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
417 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
418 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
419 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
420 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
421 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
422 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
423 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
424 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
425 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
426 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
427 case FT_GroupColor: myStream<< "aGroupColor"; break;
428 case FT_ElemGeomType: myStream<< "aElemGeomType"; break;
429 case FT_EntityType: myStream<< "aEntityType"; break;
430 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
431 case FT_BallDiameter: myStream<< "aBallDiameter"; break;
432 case FT_ConnectedElements: myStream<< "aConnectedElements"; break;
433 case FT_LessThan: myStream<< "aLessThan"; break;
434 case FT_MoreThan: myStream<< "aMoreThan"; break;
435 case FT_EqualTo: myStream<< "aEqualTo"; break;
436 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
437 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
438 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
439 case FT_Undefined: myStream<< "anUndefined"; break;
440 //default: -- commented to have a compilation warning
449 operator<<(SMESH::Measurements_i* theArg)
451 myStream<<"aMeasurements";
455 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
457 myStream << SMESHGenName(); return *this;
460 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
462 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
465 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
467 myStream << theStr; return *this;
470 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
472 *this << "SMESH.AxisStruct( "
473 << TVar( theAxis.x ) << ", "
474 << TVar( theAxis.y ) << ", "
475 << TVar( theAxis.z ) << ", "
476 << TVar( theAxis.vx ) << ", "
477 << TVar( theAxis.vy ) << ", "
478 << TVar( theAxis.vz ) << " )";
482 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
484 const SMESH::PointStruct & P = theDir.PS;
485 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
486 << TVar( P.x ) << ", "
487 << TVar( P.y ) << ", "
488 << TVar( P.z ) << " ))";
492 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
494 *this << "SMESH.PointStruct ( "
495 << TVar( P.x ) << ", "
496 << TVar( P.y ) << ", "
497 << TVar( P.z ) << " )";
501 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
503 DumpArray( theList, *this );
506 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
508 DumpArray( *theList, *this );
511 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGO& theList)
513 DumpArray( theList, *this );
516 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGBO& theList)
518 DumpArray( theList, *this );
521 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
523 DumpArray( theList, *this );
526 TPythonDump& TPythonDump::operator<<(const SMESH::submesh_array& theList)
528 DumpArray( theList, *this );
531 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfHypothesis& theList)
533 DumpArray( theList, *this );
536 TPythonDump& TPythonDump::operator<<(const SMESH::CoincidentFreeBorders& theCFB)
538 // dump CoincidentFreeBorders as a list of lists, each enclosed list
539 // contains node IDs of a group of coincident free borders where
540 // each consequent triple of IDs describe a free border: (n1, n2, nLast)
541 // For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes
542 // two groups of coincident free borders, each group including two borders
545 for ( CORBA::ULong i = 0; i < theCFB.coincidentGroups.length(); ++i )
547 const SMESH::FreeBordersGroup& aGRP = theCFB.coincidentGroups[ i ];
548 if ( i ) myStream << ",";
550 for ( CORBA::ULong iP = 0; iP < aGRP.length(); ++iP )
552 const SMESH::FreeBorderPart& aPART = aGRP[ iP ];
553 if ( 0 <= aPART.border && aPART.border < (CORBA::Long)theCFB.borders.length() )
555 if ( iP ) myStream << ", ";
556 const SMESH::FreeBorder& aBRD = theCFB.borders[ aPART.border ];
557 myStream << aBRD.nodeIDs[ aPART.node1 ] << ",";
558 myStream << aBRD.nodeIDs[ aPART.node2 ] << ",";
559 myStream << aBRD.nodeIDs[ aPART.nodeLast ];
569 const char* TPythonDump::NotPublishedObjectName()
571 return theNotPublishedObjectName;
574 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
575 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
577 //================================================================================
579 * \brief Return marker of long string literal beginning
580 * \param type - a name of functionality producing the string literal
581 * \retval TCollection_AsciiString - the marker string to be written into
582 * a raw python script
584 //================================================================================
586 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
590 (Standard_Integer) strlen(type) +
595 //================================================================================
597 * \brief Return marker of long string literal end
598 * \retval TCollection_AsciiString - the marker string to be written into
599 * a raw python script
601 //================================================================================
603 TCollection_AsciiString TPythonDump::LongStringEnd()
605 return myLongStringEnd;
608 //================================================================================
610 * \brief Cut out a long string literal from a string
611 * \param theText - text possibly containing string literals
612 * \param theFrom - position in the text to search from
613 * \param theLongString - the retrieved literal
614 * \param theStringType - a name of functionality produced the literal
615 * \retval bool - true if a string literal found
617 * The literal is removed from theText; theFrom points position right after
618 * the removed literal
620 //================================================================================
622 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
624 TCollection_AsciiString & theLongString,
625 TCollection_AsciiString & theStringType)
627 if ( theFrom < 1 || theFrom > theText.Length() )
630 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
631 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
632 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
635 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
639 // find where literal begins
640 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
641 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
642 int typeLen = atoi ( typeLenStr ); // = 7
643 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
644 literalBeg++; // 26 -> 27
647 literalBeg += typeLen + 1; // = 35
648 if ( literalBeg > theText.Length() )
651 // where literal ends (i.e. end marker begins)
652 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
654 literalEnd = theText.Length();
657 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
659 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
661 literalEnd += myLongStringEnd.Length(); // = 79
662 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
663 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
668 void printException( const char* text )
671 cout << "Exception in SMESH_Gen_i::DumpPython(): " << text << endl;
675 //=======================================================================
676 //function : RemoveTabulation
678 //=======================================================================
679 void RemoveTabulation( TCollection_AsciiString& theScript )
681 std::string aString( theScript.ToCString() );
682 std::string::size_type aPos = 0;
683 while( aPos < aString.length() )
685 aPos = aString.find( "\n\t", aPos );
686 if( aPos == std::string::npos )
688 aString.replace( aPos, 2, "\n" );
691 theScript = aString.c_str();
695 //=======================================================================
696 //function : DumpPython
698 //=======================================================================
699 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Boolean isPublished,
700 CORBA::Boolean isMultiFile,
701 CORBA::Boolean& isValidScript)
704 Kernel_Utils::Localizer loc;
706 SALOMEDS::Study_var aStudy = getStudyServant();
707 if (CORBA::is_nil(aStudy))
708 return new Engines::TMPFile(0);
710 CORBA::String_var compDataType = ComponentDataType();
711 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
712 if (CORBA::is_nil(aSO))
713 return new Engines::TMPFile(0);
715 // Map study entries to object names
716 Resource_DataMapOfAsciiStringAsciiString aMap;
717 Resource_DataMapOfAsciiStringAsciiString aMapNames;
719 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
720 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
721 SALOMEDS::SObject_wrap aValue = Itr->Value();
722 CORBA::String_var anID = aValue->GetID();
723 CORBA::String_var aName = aValue->GetName();
724 TCollection_AsciiString aGUIName ( (char*) aName.in() );
725 TCollection_AsciiString anEntry ( (char*) anID.in() );
726 if (aGUIName.Length() > 0) {
727 aMapNames.Bind( anEntry, aGUIName );
728 aMap.Bind( anEntry, aGUIName );
732 // Get trace of restored study
733 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
734 SALOMEDS::GenericAttribute_wrap anAttr =
735 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
737 SALOMEDS::AttributePythonObject_var pyAttr =
738 SALOMEDS::AttributePythonObject::_narrow(anAttr);
739 CORBA::String_var oldValue = pyAttr->GetObject();
740 TCollection_AsciiString aSavedTrace (oldValue.in());
742 // Add trace of API methods calls and replace study entries by names
743 TCollection_AsciiString aScript;
744 aScript += DumpPython_impl(aMap, aMapNames, isPublished, isMultiFile,
745 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
747 int aLen = aScript.Length();
748 unsigned char* aBuffer = new unsigned char[aLen+1];
749 strcpy((char*)aBuffer, aScript.ToCString());
751 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
752 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
754 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
755 isValidScript = isValidScript && !hasNotPublishedObjects;
757 return aStreamFile._retn();
760 //=============================================================================
764 //=============================================================================
765 void SMESH_Gen_i::AddToPythonScript (const TCollection_AsciiString& theString)
767 if (myPythonScript.IsNull()) {
768 myPythonScript = new TColStd_HSequenceOfAsciiString;
770 myPythonScript->Append(theString);
773 //=============================================================================
775 * RemoveLastFromPythonScript
777 //=============================================================================
778 void SMESH_Gen_i::RemoveLastFromPythonScript()
780 if (!myPythonScript.IsNull()) {
781 int aLen = myPythonScript->Length();
782 myPythonScript->Remove(aLen);
786 //=======================================================================
787 //function : SavePython
789 //=======================================================================
790 void SMESH_Gen_i::SavePython()
792 // Dump trace of API methods calls
793 TCollection_AsciiString aScript = GetNewPythonLines();
795 // Check contents of PythonObject attribute
796 CORBA::String_var compDataType = ComponentDataType();
797 SALOMEDS::SObject_wrap aSO = getStudyServant()->FindComponent( compDataType.in() );
798 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
799 SALOMEDS::GenericAttribute_wrap anAttr =
800 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
802 SALOMEDS::AttributePythonObject_var pyAttr =
803 SALOMEDS::AttributePythonObject::_narrow(anAttr);
804 CORBA::String_var oldValue = pyAttr->GetObject();
805 TCollection_AsciiString oldScript (oldValue.in());
807 if (oldScript.Length() > 0) {
809 oldScript += aScript;
814 // Store in PythonObject attribute
815 pyAttr->SetObject(oldScript.ToCString(), 1);
817 // Clean trace of API methods calls
825 //=============================================================================
827 * FindEntries: Returns a sequence of start/end positions of entries in the string
829 //=============================================================================
830 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
832 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
833 Standard_Integer aLen = theString.Length();
834 Standard_Boolean isFound = Standard_False;
836 char* arr = (char*) theString.ToCString();
837 Standard_Integer i = 0, j;
842 if ( isdigit( c )) { //Is digit?
844 isFound = Standard_False;
845 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
847 if(c == ':') isFound = Standard_True;
851 int prev = (i < 1) ? 0 : (int)arr[i - 1];
852 // to distinguish from a sketcher command:
853 // last char should be a digit, not ":",
854 // previous char should not be '"'.
855 if (arr[j-2] != ':' && prev != '"') {
856 aSeq->Append(i+1); // +1 because AsciiString starts from 1
870 //================================================================================
872 * \brief Make a string be a valid python name
873 * \param aName - a string to fix
874 * \retval bool - true if aName was not modified
876 //================================================================================
878 bool fixPythonName(TCollection_AsciiString & aName)
880 bool isValidName = true;
881 int nbUnderscore = 0;
883 // replace not allowed chars by underscore
884 const char* name = aName.ToCString();
885 for ( p = 0; name[p]; ++p ) {
886 if ( !isalnum( name[p] ) && name[p] != '_' )
888 if ( p == 0 || p+1 == aName.Length() || name[p-1] == '_')
890 aName.Remove( p+1, 1 ); // remove __ and _ from the start and the end
892 name = aName.ToCString();
896 aName.SetValue( p+1, '_');
902 // aName must not start with a digit
903 if ( aName.IsIntegerValue() ) {
904 aName.Insert( 1, 'a' );
907 // shorten names like CartesianParameters3D_400_400_400_1000000_1
908 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
909 posted to SALOME Forum */
910 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
912 p = aName.Location( "_", 20, aName.Length());
919 //================================================================================
921 * \brief Return Python module names of available plug-ins.
923 //================================================================================
925 std::vector<std::string> getPluginNames()
927 std::vector<std::string> pluginNames;
928 std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
929 LDOMParser xmlParser;
930 for ( size_t i = 0; i < xmlPaths.size(); ++i )
932 bool error = xmlParser.parse( xmlPaths[i].c_str() );
935 TCollection_AsciiString data;
936 INFOS( xmlParser.GetError(data) );
939 // <meshers-group name="Standard Meshers"
940 // resources="StdMeshers"
941 // idl-module="StdMeshers"
942 // server-lib="StdMeshersEngine"
943 // gui-lib="StdMeshersGUI">
944 LDOM_Document xmlDoc = xmlParser.getDocument();
945 LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
946 for ( int i = 0; i < nodeList.getLength(); ++i )
948 LDOM_Node node = nodeList.item( i );
949 LDOM_Element& elem = (LDOM_Element&) node;
950 LDOMString idlModule = elem.getAttribute( "idl-module" );
951 if ( strlen( idlModule.GetString() ) > 0 )
952 pluginNames.push_back( idlModule.GetString() );
959 //================================================================================
961 * \brief Creates a Dump Python script
962 * \param [in,out] theObjectNames - map of an entry to a study and python name
963 * \param [in] theNames - - map of an entry to a study name
964 * \param [in] isPublished - \c true if dump of object publication in study is needed
965 * \param [in] isMultiFile - \c true if dump of each module goes to a separate file
966 * \param [in] isHistoricalDump - \c true if removed object should be dumped
967 * \param [out] aValidScript - returns \c true if the returned script seems valid
968 * \param [in,out] theSavedTrace - the dump stored in the study. It's cleared to
969 * decrease memory usage.
970 * \return TCollection_AsciiString - the result dump script.
972 //================================================================================
974 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
975 (Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
976 Resource_DataMapOfAsciiStringAsciiString& theNames,
979 bool isHistoricalDump,
981 TCollection_AsciiString& theSavedTrace)
985 const TCollection_AsciiString aSmeshpy ( SMESH_2smeshpy::SmeshpyName() );
986 const TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
987 const TCollection_AsciiString anOldGen ( SMESH::TPythonDump::SMESHGenName() );
988 const TCollection_AsciiString helper; // to comfortably append C strings to TCollection_AsciiString
989 const TCollection_AsciiString tab( isMultiFile ? "\t" : "" ), nt = helper + "\n" + tab;
990 TCollection_AsciiString optionalComment;
992 std::list< TCollection_AsciiString > lines; // lines of a script
993 std::list< TCollection_AsciiString >::iterator linesIt;
995 lines.push_back( aSMESHGen + " = smeshBuilder.New()" );
997 optionalComment = "#";
998 lines.push_back( optionalComment + aSMESHGen + ".SetEnablePublish( False ) # Set to False to avoid publish in study if not needed or in some particular situations:" );
999 lines.push_back( " # multiples meshes built in parallel, complex and numerous mesh edition (performance)\n" );
1000 lines.push_back( helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()" );
1001 lines.push_back( helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()" );
1003 // Treat dump trace of restored study
1004 if (theSavedTrace.Length() > 0)
1006 linesIt = --lines.end();
1007 // Split theSavedTrace into lines
1008 int from = 1, end = theSavedTrace.Length(), to;
1009 while ( from < end && ( to = theSavedTrace.Location( "\n", from, end )))
1011 if ( theSavedTrace.ToCString()[from-1] == '\t' )
1014 lines.push_back( theSavedTrace.SubString( from, to - 1 ));
1017 // For the conversion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
1018 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
1019 // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
1021 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
1022 theSavedTrace.Clear();
1023 if ( !isNewVersion )
1025 const TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
1027 for ( ++linesIt; linesIt != lines.end(); ++linesIt )
1029 TCollection_AsciiString& aSavedLine = *linesIt;
1030 end = aSavedLine.Length(), from = 1;
1031 while ( from < end && ( beg = aSavedLine.Location( aSmeshCall, from, end )))
1033 char charBefore = ( beg == 1 ) ? ' ' : aSavedLine.Value( beg - 1 );
1034 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
1035 aSavedLine.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
1036 end += gen.Length();
1038 from = beg + aSmeshCall.Length();
1044 // Add new dump trace of API methods calls to script lines
1045 if (!myPythonScript.IsNull())
1047 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScript;
1048 Standard_Integer istr, aLen = aPythonScript->Length();
1049 for (istr = 1; istr <= aLen; istr++)
1050 lines.push_back( aPythonScript->Value( istr ));
1053 // Convert IDL API calls into smeshBuilder.py API.
1054 // Some objects are wrapped with python classes and
1055 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
1056 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
1057 std::set< TCollection_AsciiString > aRemovedObjIDs;
1058 if ( !getenv("NO_2smeshpy_conversion"))
1059 SMESH_2smeshpy::ConvertScript( lines, anEntry2AccessorMethod,
1060 theObjectNames, aRemovedObjIDs,
1063 bool importGeom = false;
1064 GEOM::GEOM_Gen_ptr geom[2];
1065 for ( int isShaper = 0; isShaper < 2; ++isShaper )
1067 geom[ isShaper ] = GetGeomEngine( isShaper );
1068 if ( CORBA::is_nil( geom[ isShaper ]))
1070 // Add names of GEOM objects to theObjectNames to exclude same names of SMESH objects
1071 GEOM::string_array_var aGeomNames = geom[ isShaper ]->GetAllDumpNames();
1072 for ( CORBA::ULong ign = 0; ign < aGeomNames->length(); ign++) {
1073 TCollection_AsciiString aName = aGeomNames[ign].in();
1074 theObjectNames.Bind(aName, "1");
1078 TCollection_AsciiString anUpdatedScript;
1080 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1081 Resource_DataMapOfAsciiStringAsciiString mapEntries; // names and entries present in anUpdatedScript
1082 Standard_Integer objectCounter = 0;
1083 TCollection_AsciiString anEntry, aName, aGUIName, aBaseName("smeshObj_");
1085 // Treat every script line and add it to anUpdatedScript
1086 for ( linesIt = lines.begin(); linesIt != lines.end(); ++linesIt )
1088 TCollection_AsciiString& aLine = *linesIt;
1089 anUpdatedScript += tab;
1091 //Replace characters used instead of quote marks to quote notebook variables
1093 while (( pos = aLine.Location( 1, SMESH::TVar::Quote(), pos, aLine.Length() )))
1094 aLine.SetValue( pos, '"' );
1096 // Find entries to be replaced by names
1097 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aLine);
1098 const Standard_Integer aSeqLen = aSeq->Length();
1099 Standard_Integer aStart = 1;
1100 for (Standard_Integer i = 1; i <= aSeqLen; i += 2)
1102 if ( aStart < aSeq->Value(i) )
1103 anUpdatedScript += aLine.SubString( aStart, aSeq->Value(i) - 1 ); // line part before i-th entry
1104 anEntry = aLine.SubString( aSeq->Value(i), aSeq->Value(i + 1) );
1105 // is a GEOM object?
1106 CORBA::String_var geomName;
1107 if ( !CORBA::is_nil( geom[0] ))
1108 geomName = geom[0]->GetDumpName( anEntry.ToCString() );
1109 if (( !geomName.in() || !geomName.in()[0] ) && !CORBA::is_nil( geom[1] ))
1110 geomName = geom[1]->GetDumpName( anEntry.ToCString() );
1111 if ( !geomName.in() || !geomName.in()[0] ) {
1112 // is a SMESH object
1113 if ( theObjectNames.IsBound( anEntry )) {
1114 // The Object is in Study
1115 aName = theObjectNames.Find( anEntry );
1116 // check validity of aName
1117 bool isValidName = fixPythonName( aName );
1118 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1119 // diff objects have same name - make a new name by appending a digit
1120 TCollection_AsciiString aName2;
1121 Standard_Integer i = 0;
1123 aName2 = aName + "_" + ++i;
1124 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1126 isValidName = false;
1129 theObjectNames(anEntry) = aName;
1131 if ( aLine.Value(1) != '#' )
1132 mapEntries.Bind(anEntry, aName);
1138 aName = aBaseName + (++objectCounter);
1139 } while (theObjectNames.IsBound(aName));
1141 if ( !aRemovedObjIDs.count( anEntry ) && aLine.Value(1) != '#')
1142 mapRemoved.Bind(anEntry, aName);
1144 theObjectNames.Bind(anEntry, aName);
1146 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1150 aName = geomName.in();
1153 anUpdatedScript += aName;
1154 aStart = aSeq->Value(i + 1) + 1;
1156 } // loop on entries within aLine
1159 anUpdatedScript += aLine;
1160 else if ( aSeq->Value( aSeqLen ) < aLine.Length() )
1161 anUpdatedScript += aLine.SubString( aSeq->Value(aSeqLen) + 1, aLine.Length() );
1163 anUpdatedScript += '\n';
1166 // Make an initial part of aSript
1168 TCollection_AsciiString initPart = "import ";
1170 initPart += "salome, ";
1171 initPart += " SMESH, SALOMEDS\n";
1172 initPart += "from salome.smesh import smeshBuilder\n";
1173 if ( importGeom && isMultiFile )
1175 initPart += ("\n## import GEOM dump file ## \n"
1176 "import string, os, sys, re, inspect\n"
1177 "thisFile = inspect.getfile( inspect.currentframe() )\n"
1178 "thisModule = os.path.splitext( os.path.basename( thisFile ))[0]\n"
1179 "sys.path.insert( 0, os.path.dirname( thisFile ))\n"
1180 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",thisModule)+\" import *\")\n\n");
1182 // import python files corresponding to plugins if they are used in anUpdatedScript
1184 //TCollection_AsciiString importStr;
1185 std::vector<std::string> pluginNames = getPluginNames();
1186 for ( size_t i = 0; i < pluginNames.size(); ++i )
1188 // Convert access to plugin members:
1189 // e.g. StdMeshers.QUAD_REDUCED -> smeshBuilder.QUAD_REDUCED
1190 TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
1191 int iFrom = 1, iPos;
1192 while (( iPos = anUpdatedScript.Location( pluginAccess, iFrom, anUpdatedScript.Length() )))
1194 //anUpdatedScript.Insert( iPos + pluginNames[i].size(), "Builder" );
1195 anUpdatedScript.Remove( iPos, pluginNames[i].size() );
1196 anUpdatedScript.Insert( iPos, "smeshBuilder" );
1197 iFrom = iPos - pluginNames[i].size() + 12;
1199 // if any plugin member is used, import the plugin
1201 // importStr += ( helper + "\n" "from salome." + pluginNames[i].c_str() +
1202 // " import " + pluginNames[i].c_str() +"Builder" );
1204 // if ( !importStr.IsEmpty() )
1205 // initPart += importStr + "\n";
1209 initPart += "def RebuildData():";
1212 anUpdatedScript.Prepend( initPart );
1214 // Make a final part of aScript
1216 // Dump object removal
1217 TCollection_AsciiString removeObjPart;
1218 if ( !mapRemoved.IsEmpty() ) {
1219 removeObjPart += nt + "## some objects were removed";
1220 removeObjPart += nt + "aStudyBuilder = salome.myStudy.NewBuilder()";
1221 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapRemovedIt;
1222 for ( mapRemovedIt.Initialize( mapRemoved ); mapRemovedIt.More(); mapRemovedIt.Next() ) {
1223 aName = mapRemovedIt.Value(); // python name
1224 anEntry = mapRemovedIt.Key();
1225 removeObjPart += nt + "SO = salome.myStudy.FindObjectIOR(salome.myStudy.ConvertObjectToIOR(";
1226 removeObjPart += aName;
1227 // for object wrapped by class of smeshBuilder.py
1228 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1229 removeObjPart += helper + "." + anEntry2AccessorMethod( anEntry );
1230 removeObjPart += helper + "))" + nt + "if SO: aStudyBuilder.RemoveObjectWithChildren(SO)";
1235 TCollection_AsciiString setNamePart;
1236 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapEntriesIt;
1237 for ( mapEntriesIt.Initialize( mapEntries ); mapEntriesIt.More(); mapEntriesIt.Next() )
1239 anEntry = mapEntriesIt.Key();
1240 aName = mapEntriesIt.Value(); // python name
1241 if ( theNames.IsBound( anEntry ))
1243 aGUIName = theNames.Find(anEntry);
1244 aGUIName.RemoveAll('\''); // remove a quote from a name (issue 22360)
1245 setNamePart += nt + aSMESHGen + ".SetName(" + aName;
1246 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1247 setNamePart += helper + "." + anEntry2AccessorMethod( anEntry );
1248 setNamePart += helper + ", '" + aGUIName + "')";
1251 if ( !setNamePart.IsEmpty() )
1253 setNamePart.Insert( 1, nt + "## Set names of Mesh objects" );
1256 // Store visual properties of displayed objects
1258 TCollection_AsciiString visualPropertiesPart;
1261 //Output the script that sets up the visual parameters.
1262 CORBA::String_var compDataType = ComponentDataType();
1263 CORBA::String_var script = getStudyServant()->GetDefaultScript( compDataType.in(), tab.ToCString() );
1264 if ( script.in() && script.in()[0] ) {
1265 visualPropertiesPart += nt + "### Store presentation parameters of displayed objects\n";
1266 visualPropertiesPart += script.in();
1270 anUpdatedScript += removeObjPart + '\n' + setNamePart + '\n' + visualPropertiesPart;
1277 "\nif __name__ == '__main__':"
1278 "\n\tSMESH_RebuildData = RebuildData"
1279 "\n\texec('import '+re.sub('SMESH$','GEOM',thisModule)+' as GEOM_dump')"
1280 "\n\tGEOM_dump.RebuildData()"
1281 "\n\texec('from '+re.sub('SMESH$','GEOM',thisModule)+' import * ')"
1282 "\n\tSMESH_RebuildData()";
1284 anUpdatedScript += "\n";
1286 // no need now as we use 'tab' and 'nt' variables depending on isMultiFile
1287 // if( !isMultiFile ) // remove unnecessary tabulation
1288 // RemoveTabulation( anUpdatedScript );
1290 // -----------------------------------------------------------------
1291 // put string literals describing patterns into separate functions
1292 // -----------------------------------------------------------------
1294 TCollection_AsciiString aLongString, aFunctionType;
1296 std::set< std::string > functionNameSet;
1297 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1299 // make a python string literal
1300 aLongString.Prepend(":\n\treturn '''\n");
1301 aLongString += "\n\t'''\n\tpass\n";
1303 TCollection_AsciiString functionName;
1305 // check if the function returning this literal is already defined
1306 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1307 if ( posAlready ) // already defined
1309 // find the function name
1310 int functBeg = posAlready;
1311 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def function()"
1312 while ( *script != ' ' ) {
1316 functBeg++; // do not take ' '
1317 posAlready--; // do not take ':'
1318 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1320 else // not defined yet
1322 // find a unique function name
1323 fixPythonName( aFunctionType );
1324 Standard_Integer nb = 0;
1325 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1326 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1329 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1332 anUpdatedScript += helper + "\n\n" + funDef;
1337 anUpdatedScript.Insert( 1, funDef);
1338 where += funDef.Length();
1341 anUpdatedScript.InsertBefore( where, functionName ); // call function
1344 aValidScript = true;
1346 return anUpdatedScript;
1348 SMESH_CATCH( SMESH::printException );
1350 aValidScript = false;
1354 //=============================================================================
1358 //=============================================================================
1359 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines()
1361 TCollection_AsciiString aScript;
1363 // Dump trace of API methods calls
1364 if (!myPythonScript.IsNull()) {
1365 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScript;
1366 Standard_Integer istr, aLen = aPythonScript->Length();
1367 for (istr = 1; istr <= aLen; istr++) {
1369 aScript += aPythonScript->Value(istr);
1377 //=============================================================================
1381 //=============================================================================
1382 void SMESH_Gen_i::CleanPythonTrace()
1384 TCollection_AsciiString aScript;
1386 // Clean trace of API methods calls
1387 if (!myPythonScript.IsNull()) {
1388 myPythonScript->Clear();