1 // Copyright (C) 2007-2013 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>
39 #include <LDOMParser.hxx>
42 static int MYDEBUG = 0;
44 static int MYDEBUG = 0;
50 size_t TPythonDump::myCounter = 0;
51 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
53 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
54 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
55 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
56 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
58 for ( size_t i = 0; i < value.length(); i++)
59 myVals[i] = SMESH_Comment(value[i]);
63 TPythonDump():myVarsCounter(0)
71 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
72 std::string aString = myStream.str();
73 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
74 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
75 if(!aStudy->_is_nil() && !aCollection.IsEmpty())
77 const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
78 if ( !objEntry.empty() )
79 aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
80 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
81 if(MYDEBUG) MESSAGE(aString);
82 // prevent misuse of already treated variables
83 aSMESHGen->UpdateParameters(CORBA::Object_var().in(),"");
88 TPythonDump& //!< store a variable value. Write either a value or '$varID$'
90 operator<<(const TVar& theVarValue)
92 const std::vector< int >& varIDs = SMESH_Gen_i::GetSMESHGen()->GetLastParamIndices();
93 if ( theVarValue.myVals.size() != 1 )
96 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
98 if ( myVarsCounter < varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
99 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
101 myStream << theVarValue.myVals[i-1];
102 if ( i < theVarValue.myVals.size() )
110 if ( myVarsCounter < varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
111 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
113 myStream << theVarValue.myVals[0];
121 operator<<(long int theArg){
128 operator<<(int theArg){
135 operator<<(double theArg){
142 operator<<(float theArg){
149 operator<<(const void* theArg){
156 operator<<(const char* theArg){
164 operator<<(const SMESH::ElementType& theArg)
168 case ALL: myStream<<"ALL"; break;
169 case NODE: myStream<<"NODE"; break;
170 case EDGE: myStream<<"EDGE"; break;
171 case FACE: myStream<<"FACE"; break;
172 case VOLUME: myStream<<"VOLUME"; break;
173 case ELEM0D: myStream<<"ELEM0D"; break;
174 case BALL: myStream<<"BALL"; break;
175 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
182 operator<<(const SMESH::GeometryType& theArg)
186 case Geom_POINT: myStream<<"Geom_POINT"; break;
187 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
188 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
189 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
190 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
191 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
192 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
193 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
194 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
195 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
196 case Geom_BALL: myStream<<"Geom_BALL"; break;
197 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
203 operator<<(const SMESH::EntityType& theArg)
207 case Entity_0D: myStream<<"Entity_0D"; break;
208 case Entity_Edge: myStream<<"Entity_Edge"; break;
209 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
210 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
211 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
212 case Entity_BiQuad_Triangle: myStream<<"Entity_BiQuad_Triangle"; break;
213 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
214 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
215 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
216 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
217 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
218 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
219 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
220 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
221 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
222 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
223 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
224 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
225 case Entity_Penta: myStream<<"Entity_Penta"; break;
226 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
227 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
228 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
229 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
230 case Entity_Ball: myStream<<"Entity_Ball"; break;
231 case Entity_Last: myStream<<"Entity_Last"; break;
232 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
237 template<class TArray>
238 void DumpArray(const TArray& theArray, TPythonDump & theStream)
241 for (int i = 1; i <= theArray.length(); i++) {
242 theStream << theArray[i-1];
243 if ( i < theArray.length() )
250 TPythonDump::operator<<(const SMESH::long_array& theArg)
252 DumpArray( theArg, *this );
257 TPythonDump::operator<<(const SMESH::double_array& theArg)
259 DumpArray( theArg, *this );
264 TPythonDump::operator<<(const SMESH::string_array& theArray)
267 for (int i = 1; i <= theArray.length(); i++) {
268 myStream << "'" << theArray[i-1] << "'";
269 if ( i < theArray.length() )
278 operator<<(SALOMEDS::SObject_ptr aSObject)
280 if ( !aSObject->_is_nil() ) {
281 CORBA::String_var entry = aSObject->GetID();
282 myStream << entry.in();
285 myStream << theNotPublishedObjectName;
292 operator<<(CORBA::Object_ptr theArg)
294 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
295 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
296 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
297 if(!aSObject->_is_nil()) {
298 CORBA::String_var id = aSObject->GetID();
300 } else if ( !CORBA::is_nil(theArg)) {
301 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
302 myStream << "smeshObj_" << size_t(theArg);
304 myStream << theNotPublishedObjectName;
313 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
315 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
316 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
317 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
318 myStream << "hyp_" << theArg->GetId();
326 operator<<(SMESH::SMESH_IDSource_ptr theArg)
328 if ( CORBA::is_nil( theArg ) )
329 return *this << "None";
330 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
331 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
332 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
333 if(!aSObject->_is_nil())
335 return *this << aSObject;
337 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
339 return *this << filter;
341 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
343 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
344 SMESH::long_array_var anElementsId = theArg->GetIDs();
345 SMESH::array_of_ElementType_var types = theArg->GetTypes();
346 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
347 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
349 return *this << theNotPublishedObjectName;
354 operator<<(SMESH::FilterLibrary_i* theArg)
356 myStream<<"aFilterLibrary"<<theArg;
362 operator<<(SMESH::FilterManager_i* theArg)
364 myStream<<"aFilterManager";
370 operator<<(SMESH::Filter_i* theArg)
372 myStream<<"aFilter"<<theArg;
378 operator<<(SMESH::Functor_i* theArg)
381 FunctorType aFunctorType = theArg->GetFunctorType();
382 switch(aFunctorType) {
383 case FT_AspectRatio: myStream<< "aAspectRatio"; break;
384 case FT_AspectRatio3D: myStream<< "aAspectRatio3D"; break;
385 case FT_Warping: myStream<< "aWarping"; break;
386 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
387 case FT_Taper: myStream<< "aTaper"; break;
388 case FT_Skew: myStream<< "aSkew"; break;
389 case FT_Area: myStream<< "aArea"; break;
390 case FT_Volume3D: myStream<< "aVolume3D"; break;
391 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
392 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
393 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
394 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
395 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
396 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
397 case FT_EqualNodes: myStream<< "aEqualNodes"; break;
398 case FT_EqualEdges: myStream<< "aEqualEdges"; break;
399 case FT_EqualFaces: myStream<< "aEqualFaces"; break;
400 case FT_EqualVolumes: myStream<< "aEqualVolumes"; break;
401 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
402 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
403 case FT_Length: myStream<< "aLength"; break;
404 case FT_Length2D: myStream<< "aLength2D"; break;
405 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
406 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
407 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
408 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
409 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
410 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
411 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
412 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
413 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
414 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
415 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
416 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
417 case FT_GroupColor: myStream<< "aGroupColor"; break;
418 case FT_ElemGeomType: myStream<< "aElemGeomType"; break;
419 case FT_EntityType: myStream<< "aEntityType"; break;
420 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
421 case FT_BallDiameter: myStream<< "aBallDiameter"; break;
422 case FT_ConnectedElements: myStream<< "aConnectedElements"; break;
423 case FT_LessThan: myStream<< "aLessThan"; break;
424 case FT_MoreThan: myStream<< "aMoreThan"; break;
425 case FT_EqualTo: myStream<< "aEqualTo"; break;
426 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
427 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
428 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
430 default: myStream<< "anUndefined"; break;
439 operator<<(SMESH::Measurements_i* theArg)
441 myStream<<"aMeasurements";
446 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
448 myStream << SMESHGenName(); return *this;
451 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
453 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
456 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
458 myStream << theStr; return *this;
462 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
464 switch (theVersion) {
465 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
466 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
467 default: myStream << theVersion;
472 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
474 *this << "SMESH.AxisStruct( "
475 << TVar( theAxis.x ) << ", "
476 << TVar( theAxis.y ) << ", "
477 << TVar( theAxis.z ) << ", "
478 << TVar( theAxis.vx ) << ", "
479 << TVar( theAxis.vy ) << ", "
480 << TVar( theAxis.vz ) << " )";
484 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
486 const SMESH::PointStruct & P = theDir.PS;
487 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
488 << TVar( P.x ) << ", "
489 << TVar( P.y ) << ", "
490 << TVar( P.z ) << " ))";
494 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
496 *this << "SMESH.PointStruct ( "
497 << TVar( P.x ) << ", "
498 << TVar( P.y ) << ", "
499 << TVar( P.z ) << " )";
503 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
505 DumpArray( theList, *this );
508 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
510 DumpArray( *theList, *this );
513 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
515 DumpArray( theList, *this );
518 const char* TPythonDump::NotPublishedObjectName()
520 return theNotPublishedObjectName;
523 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
524 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
526 //================================================================================
528 * \brief Return marker of long string literal beginning
529 * \param type - a name of functionality producing the string literal
530 * \retval TCollection_AsciiString - the marker string to be written into
531 * a raw python script
533 //================================================================================
535 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
539 (Standard_Integer) strlen(type) +
544 //================================================================================
546 * \brief Return marker of long string literal end
547 * \retval TCollection_AsciiString - the marker string to be written into
548 * a raw python script
550 //================================================================================
552 TCollection_AsciiString TPythonDump::LongStringEnd()
554 return myLongStringEnd;
557 //================================================================================
559 * \brief Cut out a long string literal from a string
560 * \param theText - text possibly containing string literals
561 * \param theFrom - position in the text to search from
562 * \param theLongString - the retrieved literal
563 * \param theStringType - a name of functionality produced the literal
564 * \retval bool - true if a string literal found
566 * The literal is removed from theText; theFrom points position right after
567 * the removed literal
569 //================================================================================
571 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
573 TCollection_AsciiString & theLongString,
574 TCollection_AsciiString & theStringType)
576 if ( theFrom < 1 || theFrom > theText.Length() )
579 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
580 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
581 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
584 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
588 // find where literal begins
589 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
590 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
591 int typeLen = atoi ( typeLenStr ); // = 7
592 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
593 literalBeg++; // 26 -> 27
596 literalBeg += typeLen + 1; // = 35
597 if ( literalBeg > theText.Length() )
600 // where literal ends (i.e. end marker begins)
601 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
603 literalEnd = theText.Length();
606 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
608 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
610 literalEnd += myLongStringEnd.Length(); // = 79
611 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
612 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
618 //=======================================================================
619 //function : RemoveTabulation
621 //=======================================================================
622 void RemoveTabulation( TCollection_AsciiString& theScript )
624 std::string aString( theScript.ToCString() );
625 std::string::size_type aPos = 0;
626 while( aPos < aString.length() )
628 aPos = aString.find( "\n\t", aPos );
629 if( aPos == std::string::npos )
631 aString.replace( aPos, 2, "\n" );
634 theScript = aString.c_str();
637 //=======================================================================
638 //function : DumpPython
640 //=======================================================================
641 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
642 CORBA::Boolean isPublished,
643 CORBA::Boolean isMultiFile,
644 CORBA::Boolean& isValidScript)
646 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
647 if (CORBA::is_nil(aStudy))
648 return new Engines::TMPFile(0);
650 CORBA::String_var compDataType = ComponentDataType();
651 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
652 if (CORBA::is_nil(aSO))
653 return new Engines::TMPFile(0);
655 // Map study entries to object names
656 Resource_DataMapOfAsciiStringAsciiString aMap;
657 Resource_DataMapOfAsciiStringAsciiString aMapNames;
658 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
660 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
661 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
662 SALOMEDS::SObject_wrap aValue = Itr->Value();
663 CORBA::String_var anID = aValue->GetID();
664 CORBA::String_var aName = aValue->GetName();
665 TCollection_AsciiString aGUIName ( (char*) aName.in() );
666 TCollection_AsciiString anEnrty ( (char*) anID.in() );
667 if (aGUIName.Length() > 0) {
668 aMapNames.Bind( anEnrty, aGUIName );
669 aMap.Bind( anEnrty, aGUIName );
673 // Get trace of restored study
674 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
675 SALOMEDS::GenericAttribute_wrap anAttr =
676 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
678 SALOMEDS::AttributePythonObject_var pyAttr =
679 SALOMEDS::AttributePythonObject::_narrow(anAttr);
680 CORBA::String_var oldValue = pyAttr->GetObject();
681 TCollection_AsciiString aSavedTrace (oldValue.in());
683 // Add trace of API methods calls and replace study entries by names
684 TCollection_AsciiString aScript;
685 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
686 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
688 int aLen = aScript.Length();
689 unsigned char* aBuffer = new unsigned char[aLen+1];
690 strcpy((char*)aBuffer, aScript.ToCString());
692 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
693 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
695 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
696 isValidScript = isValidScript && !hasNotPublishedObjects;
698 return aStreamFile._retn();
701 //=============================================================================
705 //=============================================================================
706 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
708 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
709 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
711 myPythonScripts[theStudyID]->Append(theString);
714 //=============================================================================
716 * RemoveLastFromPythonScript
718 //=============================================================================
719 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
721 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
722 int aLen = myPythonScripts[theStudyID]->Length();
723 myPythonScripts[theStudyID]->Remove(aLen);
727 //=======================================================================
728 //function : SavePython
730 //=======================================================================
731 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
733 // Dump trace of API methods calls
734 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
736 // Check contents of PythonObject attribute
737 CORBA::String_var compDataType = ComponentDataType();
738 SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
739 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
740 SALOMEDS::GenericAttribute_wrap anAttr =
741 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
743 SALOMEDS::AttributePythonObject_var pyAttr =
744 SALOMEDS::AttributePythonObject::_narrow(anAttr);
745 CORBA::String_var oldValue = pyAttr->GetObject();
746 TCollection_AsciiString oldScript (oldValue.in());
748 if (oldScript.Length() > 0) {
750 oldScript += aScript;
755 // Store in PythonObject attribute
756 pyAttr->SetObject(oldScript.ToCString(), 1);
758 // Clean trace of API methods calls
759 CleanPythonTrace(theStudy->StudyId());
766 //=============================================================================
768 * FindEntries: Returns a sequence of start/end positions of entries in the string
770 //=============================================================================
771 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
773 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
774 Standard_Integer aLen = theString.Length();
775 Standard_Boolean isFound = Standard_False;
777 char* arr = (char*) theString.ToCString();
778 Standard_Integer i = 0, j;
783 if ( isdigit( c )) { //Is digit?
785 isFound = Standard_False;
786 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
788 if(c == ':') isFound = Standard_True;
792 int prev = (i < 1) ? 0 : (int)arr[i - 1];
793 // to distinguish from a sketcher command:
794 // last char should be a digit, not ":",
795 // previous char should not be '"'.
796 if (arr[j-2] != ':' && prev != '"') {
797 aSeq->Append(i+1); // +1 because AsciiString starts from 1
811 //================================================================================
813 * \brief Make a string be a valid python name
814 * \param aName - a string to fix
815 * \retval bool - true if aName was not modified
817 //================================================================================
819 bool fixPythonName(TCollection_AsciiString & aName )
821 const TCollection_AsciiString allowedChars =
822 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
823 bool isValidName = true;
824 int nbUnderscore = 0;
825 int p=1; // replace not allowed chars by underscore
826 while (p <= aName.Length() &&
827 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
829 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
830 aName.Remove( p, 1 ); // remove double _ from the start and the end
832 aName.SetValue(p, '_'), nbUnderscore++;
835 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
836 aName.Insert( 1, 'a' );
839 // shorten names like CartesianParameters3D_400_400_400_1000000_1
840 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
841 posted to SALOME Forum */
842 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
844 p = aName.Location( "_", 20, aName.Length());
851 //================================================================================
853 * \brief Return Python module names of available plug-ins.
855 //================================================================================
857 std::vector<std::string> getPluginNames()
859 std::vector<std::string> pluginNames;
860 std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
861 LDOMParser xmlParser;
862 for ( size_t i = 0; i < xmlPaths.size(); ++i )
864 bool error = xmlParser.parse( xmlPaths[i].c_str() );
867 TCollection_AsciiString data;
868 INFOS( xmlParser.GetError(data) );
871 // <meshers-group name="Standard Meshers"
872 // resources="StdMeshers"
873 // idl-module="StdMeshers"
874 // server-lib="StdMeshersEngine"
875 // gui-lib="StdMeshersGUI">
876 LDOM_Document xmlDoc = xmlParser.getDocument();
877 LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
878 for ( int i = 0; i < nodeList.getLength(); ++i )
880 LDOM_Node node = nodeList.item( i );
881 LDOM_Element& elem = (LDOM_Element&) node;
882 LDOMString idlModule = elem.getAttribute( "idl-module" );
883 if ( strlen( idlModule.GetString() ) > 0 )
884 pluginNames.push_back( idlModule.GetString() );
891 //=============================================================================
895 //=============================================================================
896 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
897 (SALOMEDS::Study_ptr theStudy,
898 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
899 Resource_DataMapOfAsciiStringAsciiString& theNames,
902 bool isHistoricalDump,
904 const TCollection_AsciiString& theSavedTrace)
906 int aStudyID = theStudy->StudyId();
908 TCollection_AsciiString helper; // to comfortably concatenate C strings
909 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
910 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
911 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
913 TCollection_AsciiString aScript;
915 aScript += "def RebuildData(theStudy):";
919 aScript += aSMESHGen + " = smeshBuilder.New(theStudy)\n\t";
921 aScript += aSMESHGen + " = smeshBuilder.New(None)\n\t";
922 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
923 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
925 // Dump trace of restored study
926 if (theSavedTrace.Length() > 0) {
927 // For the convertion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
928 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
929 // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
931 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
932 if ( !isNewVersion ) {
933 TCollection_AsciiString aSavedTrace( theSavedTrace );
934 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
935 int beg, end = aSavedTrace.Length(), from = 1;
936 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
937 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
938 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
939 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
942 from = beg + aSmeshCall.Length();
944 aScript += helper + "\n" + aSavedTrace;
947 // append a saved trace to the script
948 aScript += helper + "\n" + theSavedTrace;
951 // Dump trace of API methods calls
952 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
953 if (aNewLines.Length() > 0) {
954 aScript += helper + "\n" + aNewLines;
957 // import python files corresponding to plugins if they are used in aScript
959 TCollection_AsciiString importStr;
960 std::vector<std::string> pluginNames = getPluginNames();
961 for ( size_t i = 0; i < pluginNames.size(); ++i )
963 // Convert access to plugin members:
964 // e.g. StdMeshers.QUAD_REDUCED -> StdMeshersBuilder.QUAD_REDUCED
965 TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
967 while (( iPos = aScript.Location( pluginAccess, iFrom, aScript.Length() )))
969 aScript.Insert( iPos + pluginNames[i].size(), "Builder" );
970 iFrom = iPos + pluginNames[i].size() + 8;
972 // if any plugin member is used, import the plugin
974 importStr += ( helper + "\n\t" + "from salome." + (char*) pluginNames[i].c_str() +
975 " import " + (char*) pluginNames[i].c_str() +"Builder" );
977 if ( !importStr.IsEmpty() )
978 aScript.Insert( 1, importStr + "\n\t" );
981 // Convert IDL API calls into smeshBuilder.py API.
982 // Some objects are wrapped with python classes and
983 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
984 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
985 std::set< TCollection_AsciiString > aRemovedObjIDs;
986 if ( !getenv("NO_2smeshpy_conversion"))
987 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
988 theObjectNames, aRemovedObjIDs,
989 theStudy, isHistoricalDump );
991 // Replace characters used instead of quote marks to quote notebook variables
994 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
995 aScript.SetValue( pos, '"' );
998 // Find entries to be replaced by names
999 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
1000 Standard_Integer aLen = aSeq->Length();
1002 if (aLen == 0 && isMultiFile)
1005 // Replace entries by the names
1006 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
1007 TColStd_SequenceOfAsciiString seqRemoved;
1008 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1009 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
1010 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
1012 // Collect names of GEOM objects to exclude same names of SMESH objects
1013 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
1014 int ign = 0, nbgn = aGeomNames->length();
1015 for (; ign < nbgn; ign++) {
1016 aName = aGeomNames[ign];
1017 theObjectNames.Bind(aName, "1");
1020 bool importGeom = false;
1021 for (Standard_Integer i = 1; i <= aLen; i += 2) {
1022 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
1023 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
1024 // is a GEOM object?
1025 aName = geom->GetDumpName( anEntry.ToCString() );
1026 if (aName.IsEmpty()) {
1027 // is a SMESH object
1028 if (theObjectNames.IsBound(anEntry)) {
1029 // The Object is in Study
1030 aName = theObjectNames.Find(anEntry);
1031 // check validity of aName
1032 bool isValidName = fixPythonName( aName );
1033 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1034 // diff objects have same name - make a new name by appending a digit
1035 TCollection_AsciiString aName2;
1036 Standard_Integer i = 0;
1038 aName2 = aName + "_" + ++i;
1039 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1041 isValidName = false;
1044 theObjectNames(anEntry) = aName;
1049 aName = aBaseName + (++objectCounter);
1050 } while (theObjectNames.IsBound(aName));
1051 if ( !aRemovedObjIDs.count( anEntry ))
1052 seqRemoved.Append(aName);
1053 mapRemoved.Bind(anEntry, "1");
1054 theObjectNames.Bind(anEntry, aName);
1056 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1062 anUpdatedScript += aName;
1063 aStart = aSeq->Value(i + 1) + 1;
1066 // set initial part of aSript
1067 TCollection_AsciiString initPart = "import ";
1069 initPart += helper + "salome, ";
1070 initPart += " SMESH, SALOMEDS\n";
1071 initPart += "from salome.smesh import smeshBuilder\n";
1072 if ( importGeom && isMultiFile )
1074 initPart += ("\n## import GEOM dump file ## \n"
1075 "import string, os, sys, re\n"
1076 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
1077 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
1079 anUpdatedScript.Insert ( 1, initPart );
1081 // add final part of aScript
1082 if (aLen && aSeq->Value(aLen) < aScriptLength)
1083 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
1085 // Remove removed objects
1086 if ( seqRemoved.Length() > 0 ) {
1087 anUpdatedScript += "\n\t## some objects were removed";
1088 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
1090 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
1091 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1092 anUpdatedScript += seqRemoved.Value(ir);
1093 // for object wrapped by class of smeshBuilder.py
1094 anEntry = theObjectNames( seqRemoved.Value(ir) );
1095 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1096 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1097 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
1102 TCollection_AsciiString aGUIName, aSetNameScriptPart;
1103 Resource_DataMapOfAsciiStringAsciiString mapEntries;
1104 for (Standard_Integer i = 1; i <= aLen; i += 2)
1106 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
1107 aName = geom->GetDumpName( anEntry.ToCString() );
1108 if (aName.IsEmpty() && // Not a GEOM object
1109 theNames.IsBound(anEntry) &&
1110 !aRemovedObjIDs.count(anEntry) && // A command creating anEntry was erased
1111 !mapEntries.IsBound(anEntry) && // Not yet processed
1112 !mapRemoved.IsBound(anEntry)) // Was not removed
1114 aName = theObjectNames.Find(anEntry);
1115 aGUIName = theNames.Find(anEntry);
1116 mapEntries.Bind(anEntry, aName);
1117 aSetNameScriptPart += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1118 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1119 aSetNameScriptPart += helper + "." + anEntry2AccessorMethod( anEntry );
1120 aSetNameScriptPart += helper + ", '" + aGUIName + "')";
1123 if ( !aSetNameScriptPart.IsEmpty() )
1125 anUpdatedScript += "\n\t## set object names";
1126 anUpdatedScript += aSetNameScriptPart;
1129 // -----------------------------------------------------------------
1130 // store visual properties of displayed objects
1131 // -----------------------------------------------------------------
1135 //Output the script that sets up the visual parameters.
1136 CORBA::String_var compDataType = ComponentDataType();
1137 char* script = theStudy->GetDefaultScript( compDataType.in(), "\t");
1138 if (script && strlen(script) > 0) {
1139 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1140 anUpdatedScript += script;
1141 CORBA::string_free(script);
1146 anUpdatedScript += "\n\tpass";
1147 anUpdatedScript += "\n";
1149 if( !isMultiFile ) // remove unnecessary tabulation
1150 RemoveTabulation( anUpdatedScript );
1152 // -----------------------------------------------------------------
1153 // put string literals describing patterns into separate functions
1154 // -----------------------------------------------------------------
1156 TCollection_AsciiString aLongString, aFunctionType;
1158 set< string > functionNameSet;
1159 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1161 // make a python string literal
1162 aLongString.Prepend(":\n\treturn '''\n");
1163 aLongString += "\n\t'''\n\tpass\n";
1165 TCollection_AsciiString functionName;
1167 // check if the function returning this literal is already defined
1168 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1169 if ( posAlready ) // already defined
1171 // find the function name
1172 int functBeg = posAlready;
1173 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1174 while ( *script != ' ' ) {
1178 functBeg++; // do not take ' '
1179 posAlready--; // do not take ':'
1180 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1182 else // not defined yet
1184 // find a unique function name
1185 fixPythonName( aFunctionType );
1186 Standard_Integer nb = 0;
1187 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1188 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1191 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1194 anUpdatedScript += helper + "\n\n" + funDef;
1199 anUpdatedScript.Insert( 1, funDef);
1200 where += funDef.Length();
1203 anUpdatedScript.InsertBefore( where, functionName ); // call function
1206 aValidScript = true;
1208 return anUpdatedScript;
1211 //=============================================================================
1215 //=============================================================================
1216 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1218 TCollection_AsciiString aScript;
1220 // Dump trace of API methods calls
1221 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1222 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1223 Standard_Integer istr, aLen = aPythonScript->Length();
1224 for (istr = 1; istr <= aLen; istr++) {
1226 aScript += aPythonScript->Value(istr);
1234 //=============================================================================
1238 //=============================================================================
1239 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1241 TCollection_AsciiString aScript;
1243 // Clean trace of API methods calls
1244 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1245 myPythonScripts[theStudyID]->Clear();