1 // Copyright (C) 2007-2016 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 <SALOMEDS_wrap.hxx>
37 #include <LDOMParser.hxx>
38 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include <TColStd_HSequenceOfInteger.hxx>
40 #include <TCollection_AsciiString.hxx>
43 static int MYDEBUG = 0;
45 static int MYDEBUG = 0;
48 #include "SMESH_TryCatch.hxx"
53 size_t TPythonDump::myCounter = 0;
54 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
56 TVar::TVar(CORBA::Double value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
57 TVar::TVar(CORBA::Long value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
58 TVar::TVar(CORBA::Short value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
59 TVar::TVar(const SMESH::double_array& value):myVals(value.length()), myIsList(true)
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 if(!aCollection.IsEmpty())
79 const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
80 if ( !objEntry.empty() )
81 aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
82 aSMESHGen->AddToPythonScript(aCollection);
83 if(MYDEBUG) MESSAGE(aString);
84 // prevent misuse of already treated variables
85 aSMESHGen->UpdateParameters(CORBA::Object_var().in(),"");
90 TPythonDump& //!< store a variable value. Write either a value or '$varID$'
92 operator<<(const TVar& theVarValue)
94 const std::vector< int >& varIDs = SMESH_Gen_i::GetSMESHGen()->GetLastParamIndices();
95 if ( theVarValue.myIsList )
98 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
100 if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
101 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
103 myStream << theVarValue.myVals[i-1];
104 if ( i < theVarValue.myVals.size() )
112 if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
113 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
115 myStream << theVarValue.myVals[0];
123 operator<<(long int theArg){
130 operator<<(int theArg){
137 operator<<(double theArg){
144 operator<<(float theArg){
151 operator<<(const void* theArg){
158 operator<<(const char* theArg){
166 operator<<(const std::string& theArg){
173 operator<<(const SMESH::ElementType& theArg)
177 case ALL: myStream<<"ALL"; break;
178 case NODE: myStream<<"NODE"; break;
179 case EDGE: myStream<<"EDGE"; break;
180 case FACE: myStream<<"FACE"; break;
181 case VOLUME: myStream<<"VOLUME"; break;
182 case ELEM0D: myStream<<"ELEM0D"; break;
183 case BALL: myStream<<"BALL"; break;
184 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
191 operator<<(const SMESH::GeometryType& theArg)
195 case Geom_POINT: myStream<<"Geom_POINT"; break;
196 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
197 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
198 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
199 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
200 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
201 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
202 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
203 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
204 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
205 case Geom_BALL: myStream<<"Geom_BALL"; break;
206 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
212 operator<<(const SMESH::EntityType& theArg)
216 case Entity_0D: myStream<<"Entity_0D"; break;
217 case Entity_Edge: myStream<<"Entity_Edge"; break;
218 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
219 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
220 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
221 case Entity_BiQuad_Triangle: myStream<<"Entity_BiQuad_Triangle"; break;
222 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
223 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
224 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
225 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
226 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
227 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
228 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
229 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
230 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
231 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
232 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
233 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
234 case Entity_Penta: myStream<<"Entity_Penta"; break;
235 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
236 case Entity_BiQuad_Penta: myStream<<"Entity_BiQuad_Penta"; break;
237 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
238 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
239 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
240 case Entity_Ball: myStream<<"Entity_Ball"; break;
241 case Entity_Last: myStream<<"Entity_Last"; break;
242 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
247 template<class TArray>
248 void DumpArray(const TArray& theArray, TPythonDump & theStream)
250 if ( theArray.length() == 0 )
257 for (CORBA::ULong i = 1; i <= theArray.length(); i++) {
258 theStream << theArray[i-1];
259 if ( i < theArray.length() )
267 TPythonDump::operator<<(const SMESH::long_array& theArg)
269 DumpArray( theArg, *this );
274 TPythonDump::operator<<(const SMESH::double_array& theArg)
276 DumpArray( theArg, *this );
281 TPythonDump::operator<<(const SMESH::nodes_array& theArg)
283 DumpArray( theArg, *this );
288 TPythonDump::operator<<(const SMESH::string_array& theArray)
291 for ( CORBA::ULong i = 1; i <= theArray.length(); i++ ) {
292 myStream << "'" << theArray[i-1] << "'";
293 if ( i < theArray.length() )
302 operator<<(SALOMEDS::SObject_ptr aSObject)
304 if ( !aSObject->_is_nil() ) {
305 CORBA::String_var entry = aSObject->GetID();
306 myStream << entry.in();
309 myStream << theNotPublishedObjectName;
316 operator<<(CORBA::Object_ptr theArg)
318 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
319 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
320 if(!aSObject->_is_nil()) {
321 CORBA::String_var id = aSObject->GetID();
323 } else if ( !CORBA::is_nil(theArg)) {
324 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
325 myStream << "smeshObj_" << size_t(theArg);
327 myStream << theNotPublishedObjectName;
336 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
338 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
339 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
340 myStream << "hyp_" << theArg->GetId();
348 operator<<(SMESH::SMESH_IDSource_ptr theArg)
350 if ( CORBA::is_nil( theArg ) )
351 return *this << "None";
352 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(theArg);
353 if(!aSObject->_is_nil())
355 return *this << aSObject;
357 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
359 return *this << filter;
361 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
363 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
364 SMESH::long_array_var anElementsId = theArg->GetIDs();
365 SMESH::array_of_ElementType_var types = theArg->GetTypes();
366 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
367 SALOMEDS::SObject_wrap meshSO = SMESH_Gen_i::ObjectToSObject(mesh);
368 if ( meshSO->_is_nil() ) // don't waste memory for dumping not published objects
369 return *this << mesh << ".GetIDSource([], " << type << ")";
371 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
373 return *this << theNotPublishedObjectName;
378 operator<<(SMESH::FilterLibrary_i* theArg)
380 myStream<<"aFilterLibrary"<<theArg;
386 operator<<(SMESH::FilterManager_i* theArg)
388 myStream<<"aFilterManager";
394 operator<<(SMESH::Filter_i* theArg)
396 myStream<<"aFilter"<<theArg;
402 operator<<(SMESH::Functor_i* theArg)
405 FunctorType aFunctorType = theArg->GetFunctorType();
406 switch(aFunctorType) {
407 case FT_AspectRatio: myStream<< "aAspectRatio"; break;
408 case FT_AspectRatio3D: myStream<< "aAspectRatio3D"; break;
409 case FT_Warping: myStream<< "aWarping"; break;
410 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
411 case FT_Taper: myStream<< "aTaper"; break;
412 case FT_Skew: myStream<< "aSkew"; break;
413 case FT_Area: myStream<< "aArea"; break;
414 case FT_Volume3D: myStream<< "aVolume3D"; break;
415 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
416 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
417 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
418 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
419 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
420 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
421 case FT_EqualNodes: myStream<< "aEqualNodes"; break;
422 case FT_EqualEdges: myStream<< "aEqualEdges"; break;
423 case FT_EqualFaces: myStream<< "aEqualFaces"; break;
424 case FT_EqualVolumes: myStream<< "aEqualVolumes"; break;
425 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
426 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
427 case FT_Length: myStream<< "aLength"; break;
428 case FT_Length2D: myStream<< "aLength2D"; break;
429 case FT_Deflection2D: myStream<< "aDeflection2D"; break;
430 case FT_NodeConnectivityNumber:myStream<< "aNodeConnectivityNumber";break;
431 case FT_BelongToMeshGroup: myStream<< "aBelongToMeshGroup"; break;
432 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
433 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
434 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
435 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
436 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
437 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
438 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
439 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
440 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
441 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
442 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
443 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
444 case FT_GroupColor: myStream<< "aGroupColor"; break;
445 case FT_ElemGeomType: myStream<< "aElemGeomType"; break;
446 case FT_EntityType: myStream<< "aEntityType"; break;
447 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
448 case FT_BallDiameter: myStream<< "aBallDiameter"; break;
449 case FT_ConnectedElements: myStream<< "aConnectedElements"; break;
450 case FT_LessThan: myStream<< "aLessThan"; break;
451 case FT_MoreThan: myStream<< "aMoreThan"; break;
452 case FT_EqualTo: myStream<< "aEqualTo"; break;
453 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
454 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
455 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
456 case FT_Undefined: myStream<< "anUndefined"; break;
457 //default: -- commented to have a compilation warning
466 operator<<(SMESH::Measurements_i* theArg)
468 myStream<<"aMeasurements";
472 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
474 myStream << SMESHGenName(); return *this;
477 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
479 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
482 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
484 myStream << theStr; return *this;
487 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
489 *this << "SMESH.AxisStruct( "
490 << TVar( theAxis.x ) << ", "
491 << TVar( theAxis.y ) << ", "
492 << TVar( theAxis.z ) << ", "
493 << TVar( theAxis.vx ) << ", "
494 << TVar( theAxis.vy ) << ", "
495 << TVar( theAxis.vz ) << " )";
499 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
501 const SMESH::PointStruct & P = theDir.PS;
502 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
503 << TVar( P.x ) << ", "
504 << TVar( P.y ) << ", "
505 << TVar( P.z ) << " ))";
509 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
511 *this << "SMESH.PointStruct ( "
512 << TVar( P.x ) << ", "
513 << TVar( P.y ) << ", "
514 << TVar( P.z ) << " )";
518 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
520 DumpArray( theList, *this );
523 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
525 DumpArray( *theList, *this );
528 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGO& theList)
530 DumpArray( theList, *this );
533 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGBO& theList)
535 DumpArray( theList, *this );
538 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
540 DumpArray( theList, *this );
543 TPythonDump& TPythonDump::operator<<(const SMESH::submesh_array& theList)
545 DumpArray( theList, *this );
548 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfHypothesis& theList)
550 DumpArray( theList, *this );
553 TPythonDump& TPythonDump::operator<<(const SMESH::CoincidentFreeBorders& theCFB)
555 // dump CoincidentFreeBorders as a list of lists, each enclosed list
556 // contains node IDs of a group of coincident free borders where
557 // each consequent triple of IDs describe a free border: (n1, n2, nLast)
558 // For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes
559 // two groups of coincident free borders, each group including two borders
562 for ( CORBA::ULong i = 0; i < theCFB.coincidentGroups.length(); ++i )
564 const SMESH::FreeBordersGroup& aGRP = theCFB.coincidentGroups[ i ];
565 if ( i ) myStream << ",";
567 for ( CORBA::ULong iP = 0; iP < aGRP.length(); ++iP )
569 const SMESH::FreeBorderPart& aPART = aGRP[ iP ];
570 if ( 0 <= aPART.border && aPART.border < (CORBA::Long)theCFB.borders.length() )
572 if ( iP ) myStream << ", ";
573 const SMESH::FreeBorder& aBRD = theCFB.borders[ aPART.border ];
574 myStream << aBRD.nodeIDs[ aPART.node1 ] << ",";
575 myStream << aBRD.nodeIDs[ aPART.node2 ] << ",";
576 myStream << aBRD.nodeIDs[ aPART.nodeLast ];
586 const char* TPythonDump::NotPublishedObjectName()
588 return theNotPublishedObjectName;
591 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
592 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
594 //================================================================================
596 * \brief Return marker of long string literal beginning
597 * \param type - a name of functionality producing the string literal
598 * \retval TCollection_AsciiString - the marker string to be written into
599 * a raw python script
601 //================================================================================
603 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
607 (Standard_Integer) strlen(type) +
612 //================================================================================
614 * \brief Return marker of long string literal end
615 * \retval TCollection_AsciiString - the marker string to be written into
616 * a raw python script
618 //================================================================================
620 TCollection_AsciiString TPythonDump::LongStringEnd()
622 return myLongStringEnd;
625 //================================================================================
627 * \brief Cut out a long string literal from a string
628 * \param theText - text possibly containing string literals
629 * \param theFrom - position in the text to search from
630 * \param theLongString - the retrieved literal
631 * \param theStringType - a name of functionality produced the literal
632 * \retval bool - true if a string literal found
634 * The literal is removed from theText; theFrom points position right after
635 * the removed literal
637 //================================================================================
639 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
641 TCollection_AsciiString & theLongString,
642 TCollection_AsciiString & theStringType)
644 if ( theFrom < 1 || theFrom > theText.Length() )
647 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
648 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
649 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
652 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
656 // find where literal begins
657 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
658 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
659 int typeLen = atoi ( typeLenStr ); // = 7
660 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
661 literalBeg++; // 26 -> 27
664 literalBeg += typeLen + 1; // = 35
665 if ( literalBeg > theText.Length() )
668 // where literal ends (i.e. end marker begins)
669 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
671 literalEnd = theText.Length();
674 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
676 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
678 literalEnd += myLongStringEnd.Length(); // = 79
679 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
680 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
685 void printException( const char* text )
688 cout << "Exception in SMESH_Gen_i::DumpPython(): " << text << endl;
692 //=======================================================================
693 //function : RemoveTabulation
695 //=======================================================================
696 void RemoveTabulation( TCollection_AsciiString& theScript )
698 std::string aString( theScript.ToCString() );
699 std::string::size_type aPos = 0;
700 while( aPos < aString.length() )
702 aPos = aString.find( "\n\t", aPos );
703 if( aPos == std::string::npos )
705 aString.replace( aPos, 2, "\n" );
708 theScript = aString.c_str();
712 //=======================================================================
713 //function : DumpPython
715 //=======================================================================
716 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Boolean isPublished,
717 CORBA::Boolean isMultiFile,
718 CORBA::Boolean& isValidScript)
720 SALOMEDS::Study_var aStudy = getStudyServant();
721 if (CORBA::is_nil(aStudy))
722 return new Engines::TMPFile(0);
724 CORBA::String_var compDataType = ComponentDataType();
725 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
726 if (CORBA::is_nil(aSO))
727 return new Engines::TMPFile(0);
729 // Map study entries to object names
730 Resource_DataMapOfAsciiStringAsciiString aMap;
731 Resource_DataMapOfAsciiStringAsciiString aMapNames;
733 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
734 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
735 SALOMEDS::SObject_wrap aValue = Itr->Value();
736 CORBA::String_var anID = aValue->GetID();
737 CORBA::String_var aName = aValue->GetName();
738 TCollection_AsciiString aGUIName ( (char*) aName.in() );
739 TCollection_AsciiString anEntry ( (char*) anID.in() );
740 if (aGUIName.Length() > 0) {
741 aMapNames.Bind( anEntry, aGUIName );
742 aMap.Bind( anEntry, aGUIName );
746 // Get trace of restored study
747 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
748 SALOMEDS::GenericAttribute_wrap anAttr =
749 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
751 SALOMEDS::AttributePythonObject_var pyAttr =
752 SALOMEDS::AttributePythonObject::_narrow(anAttr);
753 CORBA::String_var oldValue = pyAttr->GetObject();
754 TCollection_AsciiString aSavedTrace (oldValue.in());
756 // Add trace of API methods calls and replace study entries by names
757 TCollection_AsciiString aScript;
758 aScript += DumpPython_impl(aMap, aMapNames, isPublished, isMultiFile,
759 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
761 int aLen = aScript.Length();
762 unsigned char* aBuffer = new unsigned char[aLen+1];
763 strcpy((char*)aBuffer, aScript.ToCString());
765 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
766 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
768 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
769 isValidScript = isValidScript && !hasNotPublishedObjects;
771 return aStreamFile._retn();
774 //=============================================================================
778 //=============================================================================
779 void SMESH_Gen_i::AddToPythonScript (const TCollection_AsciiString& theString)
781 if (myPythonScript.IsNull()) {
782 myPythonScript = new TColStd_HSequenceOfAsciiString;
784 myPythonScript->Append(theString);
787 //=============================================================================
789 * RemoveLastFromPythonScript
791 //=============================================================================
792 void SMESH_Gen_i::RemoveLastFromPythonScript()
794 if (!myPythonScript.IsNull()) {
795 int aLen = myPythonScript->Length();
796 myPythonScript->Remove(aLen);
800 //=======================================================================
801 //function : SavePython
803 //=======================================================================
804 void SMESH_Gen_i::SavePython()
806 // Dump trace of API methods calls
807 TCollection_AsciiString aScript = GetNewPythonLines();
809 // Check contents of PythonObject attribute
810 CORBA::String_var compDataType = ComponentDataType();
811 SALOMEDS::SObject_wrap aSO = getStudyServant()->FindComponent( compDataType.in() );
812 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
813 SALOMEDS::GenericAttribute_wrap anAttr =
814 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
816 SALOMEDS::AttributePythonObject_var pyAttr =
817 SALOMEDS::AttributePythonObject::_narrow(anAttr);
818 CORBA::String_var oldValue = pyAttr->GetObject();
819 TCollection_AsciiString oldScript (oldValue.in());
821 if (oldScript.Length() > 0) {
823 oldScript += aScript;
828 // Store in PythonObject attribute
829 pyAttr->SetObject(oldScript.ToCString(), 1);
831 // Clean trace of API methods calls
839 //=============================================================================
841 * FindEntries: Returns a sequence of start/end positions of entries in the string
843 //=============================================================================
844 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
846 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
847 Standard_Integer aLen = theString.Length();
848 Standard_Boolean isFound = Standard_False;
850 char* arr = (char*) theString.ToCString();
851 Standard_Integer i = 0, j;
856 if ( isdigit( c )) { //Is digit?
858 isFound = Standard_False;
859 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
861 if(c == ':') isFound = Standard_True;
865 int prev = (i < 1) ? 0 : (int)arr[i - 1];
866 // to distinguish from a sketcher command:
867 // last char should be a digit, not ":",
868 // previous char should not be '"'.
869 if (arr[j-2] != ':' && prev != '"') {
870 aSeq->Append(i+1); // +1 because AsciiString starts from 1
884 //================================================================================
886 * \brief Make a string be a valid python name
887 * \param aName - a string to fix
888 * \retval bool - true if aName was not modified
890 //================================================================================
892 bool fixPythonName(TCollection_AsciiString & aName)
894 bool isValidName = true;
895 int nbUnderscore = 0;
897 // replace not allowed chars by underscore
898 const char* name = aName.ToCString();
899 for ( p = 0; name[p]; ++p ) {
900 if ( !isalnum( name[p] ) && name[p] != '_' )
902 if ( p == 0 || p+1 == aName.Length() || name[p-1] == '_')
904 aName.Remove( p+1, 1 ); // remove __ and _ from the start and the end
906 name = aName.ToCString();
910 aName.SetValue( p+1, '_');
916 // aName must not start with a digit
917 if ( aName.IsIntegerValue() ) {
918 aName.Insert( 1, 'a' );
921 // shorten names like CartesianParameters3D_400_400_400_1000000_1
922 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
923 posted to SALOME Forum */
924 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
926 p = aName.Location( "_", 20, aName.Length());
933 //================================================================================
935 * \brief Return Python module names of available plug-ins.
937 //================================================================================
939 std::vector<std::string> getPluginNames()
941 std::vector<std::string> pluginNames;
942 std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
943 LDOMParser xmlParser;
944 for ( size_t i = 0; i < xmlPaths.size(); ++i )
946 bool error = xmlParser.parse( xmlPaths[i].c_str() );
949 TCollection_AsciiString data;
950 INFOS( xmlParser.GetError(data) );
953 // <meshers-group name="Standard Meshers"
954 // resources="StdMeshers"
955 // idl-module="StdMeshers"
956 // server-lib="StdMeshersEngine"
957 // gui-lib="StdMeshersGUI">
958 LDOM_Document xmlDoc = xmlParser.getDocument();
959 LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
960 for ( int i = 0; i < nodeList.getLength(); ++i )
962 LDOM_Node node = nodeList.item( i );
963 LDOM_Element& elem = (LDOM_Element&) node;
964 LDOMString idlModule = elem.getAttribute( "idl-module" );
965 if ( strlen( idlModule.GetString() ) > 0 )
966 pluginNames.push_back( idlModule.GetString() );
973 //================================================================================
975 * \brief Createa a Dump Python script
976 * \param [in,out] theObjectNames - map of an entry to a study and python name
977 * \param [in] theNames - - map of an entry to a study name
978 * \param [in] isPublished - \c true if dump of object publication in study is needed
979 * \param [in] isMultiFile - \c true if dump of each module goes to a separate file
980 * \param [in] isHistoricalDump - \c true if removed object should be dumped
981 * \param [out] aValidScript - returns \c true if the returned script seems valid
982 * \param [in,out] theSavedTrace - the dump stored in the study. It's cleared to
983 * decrease memory usage.
984 * \return TCollection_AsciiString - the result dump script.
986 //================================================================================
988 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
989 (Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
990 Resource_DataMapOfAsciiStringAsciiString& theNames,
993 bool isHistoricalDump,
995 TCollection_AsciiString& theSavedTrace)
999 const TCollection_AsciiString aSmeshpy ( SMESH_2smeshpy::SmeshpyName() );
1000 const TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
1001 const TCollection_AsciiString anOldGen ( SMESH::TPythonDump::SMESHGenName() );
1002 const TCollection_AsciiString helper; // to comfortably append C strings to TCollection_AsciiString
1003 const TCollection_AsciiString tab( isMultiFile ? "\t" : "" ), nt = helper + "\n" + tab;
1005 std::list< TCollection_AsciiString > lines; // lines of a script
1006 std::list< TCollection_AsciiString >::iterator linesIt;
1008 lines.push_back( aSMESHGen + " = smeshBuilder.New()" );
1010 lines.push_back( aSMESHGen + ".SetEnablePublish( False )" );
1011 lines.push_back( helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()" );
1012 lines.push_back( helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()" );
1014 // Treat dump trace of restored study
1015 if (theSavedTrace.Length() > 0)
1017 linesIt = --lines.end();
1018 // Split theSavedTrace into lines
1019 int from = 1, end = theSavedTrace.Length(), to;
1020 while ( from < end && ( to = theSavedTrace.Location( "\n", from, end )))
1022 if ( theSavedTrace.ToCString()[from-1] == '\t' )
1025 lines.push_back( theSavedTrace.SubString( from, to - 1 ));
1028 // For the conversion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
1029 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
1030 // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
1032 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
1033 theSavedTrace.Clear();
1034 if ( !isNewVersion )
1036 const TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
1038 for ( ++linesIt; linesIt != lines.end(); ++linesIt )
1040 TCollection_AsciiString& aSavedLine = *linesIt;
1041 end = aSavedLine.Length(), from = 1;
1042 while ( from < end && ( beg = aSavedLine.Location( aSmeshCall, from, end )))
1044 char charBefore = ( beg == 1 ) ? ' ' : aSavedLine.Value( beg - 1 );
1045 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
1046 aSavedLine.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
1047 end += gen.Length();
1049 from = beg + aSmeshCall.Length();
1055 // Add new dump trace of API methods calls to script lines
1056 if (!myPythonScript.IsNull())
1058 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScript;
1059 Standard_Integer istr, aLen = aPythonScript->Length();
1060 for (istr = 1; istr <= aLen; istr++)
1061 lines.push_back( aPythonScript->Value( istr ));
1064 // Convert IDL API calls into smeshBuilder.py API.
1065 // Some objects are wrapped with python classes and
1066 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
1067 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
1068 std::set< TCollection_AsciiString > aRemovedObjIDs;
1069 if ( !getenv("NO_2smeshpy_conversion"))
1070 SMESH_2smeshpy::ConvertScript( lines, anEntry2AccessorMethod,
1071 theObjectNames, aRemovedObjIDs,
1074 bool importGeom = false;
1075 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
1077 // Add names of GEOM objects to theObjectNames to exclude same names of SMESH objects
1078 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
1079 int ign = 0, nbgn = aGeomNames->length();
1080 for (; ign < nbgn; ign++) {
1081 TCollection_AsciiString aName = aGeomNames[ign].in();
1082 theObjectNames.Bind(aName, "1");
1086 TCollection_AsciiString anUpdatedScript;
1088 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1089 Resource_DataMapOfAsciiStringAsciiString mapEntries; // names and entries present in anUpdatedScript
1090 Standard_Integer objectCounter = 0;
1091 TCollection_AsciiString anEntry, aName, aGUIName, aBaseName("smeshObj_");
1093 // Treat every script line and add it to anUpdatedScript
1094 for ( linesIt = lines.begin(); linesIt != lines.end(); ++linesIt )
1096 TCollection_AsciiString& aLine = *linesIt;
1097 anUpdatedScript += tab;
1099 //Replace characters used instead of quote marks to quote notebook variables
1101 while (( pos = aLine.Location( 1, SMESH::TVar::Quote(), pos, aLine.Length() )))
1102 aLine.SetValue( pos, '"' );
1104 // Find entries to be replaced by names
1105 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aLine);
1106 const Standard_Integer aSeqLen = aSeq->Length();
1107 Standard_Integer aStart = 1;
1108 for (Standard_Integer i = 1; i <= aSeqLen; i += 2)
1110 if ( aStart < aSeq->Value(i) )
1111 anUpdatedScript += aLine.SubString( aStart, aSeq->Value(i) - 1 ); // line part before i-th entry
1112 anEntry = aLine.SubString( aSeq->Value(i), aSeq->Value(i + 1) );
1113 // is a GEOM object?
1114 CORBA::String_var geomName = geom->GetDumpName( anEntry.ToCString() );
1115 if ( !geomName.in() || !geomName.in()[0] ) {
1116 // is a SMESH object
1117 if ( theObjectNames.IsBound( anEntry )) {
1118 // The Object is in Study
1119 aName = theObjectNames.Find( anEntry );
1120 // check validity of aName
1121 bool isValidName = fixPythonName( aName );
1122 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1123 // diff objects have same name - make a new name by appending a digit
1124 TCollection_AsciiString aName2;
1125 Standard_Integer i = 0;
1127 aName2 = aName + "_" + ++i;
1128 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1130 isValidName = false;
1133 theObjectNames(anEntry) = aName;
1135 if ( aLine.Value(1) != '#' )
1136 mapEntries.Bind(anEntry, aName);
1142 aName = aBaseName + (++objectCounter);
1143 } while (theObjectNames.IsBound(aName));
1145 if ( !aRemovedObjIDs.count( anEntry ) && aLine.Value(1) != '#')
1146 mapRemoved.Bind(anEntry, aName);
1148 theObjectNames.Bind(anEntry, aName);
1150 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1154 aName = geomName.in();
1157 anUpdatedScript += aName;
1158 aStart = aSeq->Value(i + 1) + 1;
1160 } // loop on entries within aLine
1163 anUpdatedScript += aLine;
1164 else if ( aSeq->Value( aSeqLen ) < aLine.Length() )
1165 anUpdatedScript += aLine.SubString( aSeq->Value(aSeqLen) + 1, aLine.Length() );
1167 anUpdatedScript += '\n';
1170 // Make an initial part of aSript
1172 TCollection_AsciiString initPart = "import ";
1174 initPart += "salome, ";
1175 initPart += " SMESH, SALOMEDS\n";
1176 initPart += "from salome.smesh import smeshBuilder\n";
1177 if ( importGeom && isMultiFile )
1179 initPart += ("\n## import GEOM dump file ## \n"
1180 "import string, os, sys, re, inspect\n"
1181 "thisFile = inspect.getfile( inspect.currentframe() )\n"
1182 "thisModule = os.path.splitext( os.path.basename( thisFile ))[0]\n"
1183 "sys.path.insert( 0, os.path.dirname( thisFile ))\n"
1184 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",thisModule)+\" import *\")\n\n");
1186 // import python files corresponding to plugins if they are used in anUpdatedScript
1188 //TCollection_AsciiString importStr;
1189 std::vector<std::string> pluginNames = getPluginNames();
1190 for ( size_t i = 0; i < pluginNames.size(); ++i )
1192 // Convert access to plugin members:
1193 // e.g. StdMeshers.QUAD_REDUCED -> smeshBuilder.QUAD_REDUCED
1194 TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
1195 int iFrom = 1, iPos;
1196 while (( iPos = anUpdatedScript.Location( pluginAccess, iFrom, anUpdatedScript.Length() )))
1198 //anUpdatedScript.Insert( iPos + pluginNames[i].size(), "Builder" );
1199 anUpdatedScript.Remove( iPos, pluginNames[i].size() );
1200 anUpdatedScript.Insert( iPos, "smeshBuilder" );
1201 iFrom = iPos - pluginNames[i].size() + 12;
1203 // if any plugin member is used, import the plugin
1205 // importStr += ( helper + "\n" "from salome." + pluginNames[i].c_str() +
1206 // " import " + pluginNames[i].c_str() +"Builder" );
1208 // if ( !importStr.IsEmpty() )
1209 // initPart += importStr + "\n";
1213 initPart += "def RebuildData():";
1216 anUpdatedScript.Prepend( initPart );
1218 // Make a final part of aScript
1220 // Dump object removal
1221 TCollection_AsciiString removeObjPart;
1222 if ( !mapRemoved.IsEmpty() ) {
1223 removeObjPart += nt + "## some objects were removed";
1224 removeObjPart += nt + "aStudyBuilder = salome.myStudy.NewBuilder()";
1225 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapRemovedIt;
1226 for ( mapRemovedIt.Initialize( mapRemoved ); mapRemovedIt.More(); mapRemovedIt.Next() ) {
1227 aName = mapRemovedIt.Value(); // python name
1228 anEntry = mapRemovedIt.Key();
1229 removeObjPart += nt + "SO = salome.myStudy.FindObjectIOR(salome.myStudy.ConvertObjectToIOR(";
1230 removeObjPart += aName;
1231 // for object wrapped by class of smeshBuilder.py
1232 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1233 removeObjPart += helper + "." + anEntry2AccessorMethod( anEntry );
1234 removeObjPart += helper + "))" + nt + "if SO: aStudyBuilder.RemoveObjectWithChildren(SO)";
1239 TCollection_AsciiString setNamePart;
1240 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapEntriesIt;
1241 for ( mapEntriesIt.Initialize( mapEntries ); mapEntriesIt.More(); mapEntriesIt.Next() )
1243 anEntry = mapEntriesIt.Key();
1244 aName = mapEntriesIt.Value(); // python name
1245 if ( theNames.IsBound( anEntry ))
1247 aGUIName = theNames.Find(anEntry);
1248 aGUIName.RemoveAll('\''); // remove a quote from a name (issue 22360)
1249 setNamePart += nt + aSMESHGen + ".SetName(" + aName;
1250 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1251 setNamePart += helper + "." + anEntry2AccessorMethod( anEntry );
1252 setNamePart += helper + ", '" + aGUIName + "')";
1255 if ( !setNamePart.IsEmpty() )
1257 setNamePart.Insert( 1, nt + "## Set names of Mesh objects" );
1260 // Store visual properties of displayed objects
1262 TCollection_AsciiString visualPropertiesPart;
1265 //Output the script that sets up the visual parameters.
1266 CORBA::String_var compDataType = ComponentDataType();
1267 CORBA::String_var script = getStudyServant()->GetDefaultScript( compDataType.in(), tab.ToCString() );
1268 if ( script.in() && script.in()[0] ) {
1269 visualPropertiesPart += nt + "### Store presentation parameters of displayed objects\n";
1270 visualPropertiesPart += script.in();
1274 anUpdatedScript += removeObjPart + '\n' + setNamePart + '\n' + visualPropertiesPart;
1281 "\nif __name__ == '__main__':"
1282 "\n\tSMESH_RebuildData = RebuildData"
1283 "\n\texec('import '+re.sub('SMESH$','GEOM',thisModule)+' as GEOM_dump')"
1284 "\n\tGEOM_dump.RebuildData()"
1285 "\n\texec('from '+re.sub('SMESH$','GEOM',thisModule)+' import * ')"
1286 "\n\tSMESH_RebuildData()";
1288 anUpdatedScript += "\n";
1290 // no need now as we use 'tab' and 'nt' variables depending on isMultiFile
1291 // if( !isMultiFile ) // remove unnecessary tabulation
1292 // RemoveTabulation( anUpdatedScript );
1294 // -----------------------------------------------------------------
1295 // put string literals describing patterns into separate functions
1296 // -----------------------------------------------------------------
1298 TCollection_AsciiString aLongString, aFunctionType;
1300 std::set< std::string > functionNameSet;
1301 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1303 // make a python string literal
1304 aLongString.Prepend(":\n\treturn '''\n");
1305 aLongString += "\n\t'''\n\tpass\n";
1307 TCollection_AsciiString functionName;
1309 // check if the function returning this literal is already defined
1310 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1311 if ( posAlready ) // already defined
1313 // find the function name
1314 int functBeg = posAlready;
1315 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def function()"
1316 while ( *script != ' ' ) {
1320 functBeg++; // do not take ' '
1321 posAlready--; // do not take ':'
1322 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1324 else // not defined yet
1326 // find a unique function name
1327 fixPythonName( aFunctionType );
1328 Standard_Integer nb = 0;
1329 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1330 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1333 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1336 anUpdatedScript += helper + "\n\n" + funDef;
1341 anUpdatedScript.Insert( 1, funDef);
1342 where += funDef.Length();
1345 anUpdatedScript.InsertBefore( where, functionName ); // call function
1348 aValidScript = true;
1350 return anUpdatedScript;
1352 SMESH_CATCH( SMESH::printException );
1354 aValidScript = false;
1358 //=============================================================================
1362 //=============================================================================
1363 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines()
1365 TCollection_AsciiString aScript;
1367 // Dump trace of API methods calls
1368 if (!myPythonScript.IsNull()) {
1369 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScript;
1370 Standard_Integer istr, aLen = aPythonScript->Length();
1371 for (istr = 1; istr <= aLen; istr++) {
1373 aScript += aPythonScript->Value(istr);
1381 //=============================================================================
1385 //=============================================================================
1386 void SMESH_Gen_i::CleanPythonTrace()
1388 TCollection_AsciiString aScript;
1390 // Clean trace of API methods calls
1391 if (!myPythonScript.IsNull()) {
1392 myPythonScript->Clear();