1 // Copyright (C) 2007-2014 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) { myVals[0] = SMESH_Comment(value); }
57 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
58 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
59 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
61 for ( size_t i = 0; i < value.length(); i++)
62 myVals[i] = SMESH_Comment(value[i]);
66 TPythonDump():myVarsCounter(0)
74 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
75 std::string aString = myStream.str();
76 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
77 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
78 if(!aStudy->_is_nil() && !aCollection.IsEmpty())
80 const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
81 if ( !objEntry.empty() )
82 aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
83 aSMESHGen->AddToPythonScript(aStudy->StudyId(),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.myVals.size() != 1 )
99 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
101 if ( myVarsCounter < 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 < 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 SMESH::ElementType& theArg)
171 case ALL: myStream<<"ALL"; break;
172 case NODE: myStream<<"NODE"; break;
173 case EDGE: myStream<<"EDGE"; break;
174 case FACE: myStream<<"FACE"; break;
175 case VOLUME: myStream<<"VOLUME"; break;
176 case ELEM0D: myStream<<"ELEM0D"; break;
177 case BALL: myStream<<"BALL"; break;
178 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
185 operator<<(const SMESH::GeometryType& theArg)
189 case Geom_POINT: myStream<<"Geom_POINT"; break;
190 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
191 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
192 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
193 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
194 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
195 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
196 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
197 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
198 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
199 case Geom_BALL: myStream<<"Geom_BALL"; break;
200 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
206 operator<<(const SMESH::EntityType& theArg)
210 case Entity_0D: myStream<<"Entity_0D"; break;
211 case Entity_Edge: myStream<<"Entity_Edge"; break;
212 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
213 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
214 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
215 case Entity_BiQuad_Triangle: myStream<<"Entity_BiQuad_Triangle"; break;
216 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
217 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
218 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
219 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
220 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
221 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
222 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
223 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
224 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
225 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
226 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
227 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
228 case Entity_Penta: myStream<<"Entity_Penta"; break;
229 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
230 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
231 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
232 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
233 case Entity_Ball: myStream<<"Entity_Ball"; break;
234 case Entity_Last: myStream<<"Entity_Last"; break;
235 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
240 template<class TArray>
241 void DumpArray(const TArray& theArray, TPythonDump & theStream)
243 if ( theArray.length() == 0 )
250 for (int i = 1; i <= theArray.length(); i++) {
251 theStream << theArray[i-1];
252 if ( i < theArray.length() )
260 TPythonDump::operator<<(const SMESH::long_array& theArg)
262 DumpArray( theArg, *this );
267 TPythonDump::operator<<(const SMESH::double_array& theArg)
269 DumpArray( theArg, *this );
274 TPythonDump::operator<<(const SMESH::nodes_array& theArg)
276 DumpArray( theArg, *this );
281 TPythonDump::operator<<(const SMESH::string_array& theArray)
284 for (int i = 1; i <= theArray.length(); i++) {
285 myStream << "'" << theArray[i-1] << "'";
286 if ( i < theArray.length() )
295 operator<<(SALOMEDS::SObject_ptr aSObject)
297 if ( !aSObject->_is_nil() ) {
298 CORBA::String_var entry = aSObject->GetID();
299 myStream << entry.in();
302 myStream << theNotPublishedObjectName;
309 operator<<(CORBA::Object_ptr theArg)
311 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
312 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
313 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
314 if(!aSObject->_is_nil()) {
315 CORBA::String_var id = aSObject->GetID();
317 } else if ( !CORBA::is_nil(theArg)) {
318 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
319 myStream << "smeshObj_" << size_t(theArg);
321 myStream << theNotPublishedObjectName;
330 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
332 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
333 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
334 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
335 myStream << "hyp_" << theArg->GetId();
343 operator<<(SMESH::SMESH_IDSource_ptr theArg)
345 if ( CORBA::is_nil( theArg ) )
346 return *this << "None";
347 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
348 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
349 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
350 if(!aSObject->_is_nil())
352 return *this << aSObject;
354 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
356 return *this << filter;
358 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
360 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
361 SMESH::long_array_var anElementsId = theArg->GetIDs();
362 SMESH::array_of_ElementType_var types = theArg->GetTypes();
363 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
364 SALOMEDS::SObject_wrap meshSO = SMESH_Gen_i::ObjectToSObject(aStudy,mesh);
365 if ( meshSO->_is_nil() ) // don't waste memory for dumping not published objects
366 return *this << mesh << ".GetIDSource([], " << type << ")";
368 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
370 return *this << theNotPublishedObjectName;
375 operator<<(SMESH::FilterLibrary_i* theArg)
377 myStream<<"aFilterLibrary"<<theArg;
383 operator<<(SMESH::FilterManager_i* theArg)
385 myStream<<"aFilterManager";
391 operator<<(SMESH::Filter_i* theArg)
393 myStream<<"aFilter"<<theArg;
399 operator<<(SMESH::Functor_i* theArg)
402 FunctorType aFunctorType = theArg->GetFunctorType();
403 switch(aFunctorType) {
404 case FT_AspectRatio: myStream<< "aAspectRatio"; break;
405 case FT_AspectRatio3D: myStream<< "aAspectRatio3D"; break;
406 case FT_Warping: myStream<< "aWarping"; break;
407 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
408 case FT_Taper: myStream<< "aTaper"; break;
409 case FT_Skew: myStream<< "aSkew"; break;
410 case FT_Area: myStream<< "aArea"; break;
411 case FT_Volume3D: myStream<< "aVolume3D"; break;
412 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
413 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
414 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
415 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
416 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
417 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
418 case FT_EqualNodes: myStream<< "aEqualNodes"; break;
419 case FT_EqualEdges: myStream<< "aEqualEdges"; break;
420 case FT_EqualFaces: myStream<< "aEqualFaces"; break;
421 case FT_EqualVolumes: myStream<< "aEqualVolumes"; break;
422 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
423 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
424 case FT_Length: myStream<< "aLength"; break;
425 case FT_Length2D: myStream<< "aLength2D"; break;
426 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
427 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
428 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
429 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
430 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
431 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
432 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
433 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
434 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
435 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
436 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
437 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
438 case FT_GroupColor: myStream<< "aGroupColor"; break;
439 case FT_ElemGeomType: myStream<< "aElemGeomType"; break;
440 case FT_EntityType: myStream<< "aEntityType"; break;
441 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
442 case FT_BallDiameter: myStream<< "aBallDiameter"; break;
443 case FT_ConnectedElements: myStream<< "aConnectedElements"; break;
444 case FT_LessThan: myStream<< "aLessThan"; break;
445 case FT_MoreThan: myStream<< "aMoreThan"; break;
446 case FT_EqualTo: myStream<< "aEqualTo"; break;
447 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
448 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
449 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
451 default: myStream<< "anUndefined"; break;
460 operator<<(SMESH::Measurements_i* theArg)
462 myStream<<"aMeasurements";
467 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
469 myStream << SMESHGenName(); return *this;
472 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
474 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
477 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
479 myStream << theStr; return *this;
483 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
485 switch (theVersion) {
486 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
487 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
488 default: myStream << theVersion;
493 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
495 *this << "SMESH.AxisStruct( "
496 << TVar( theAxis.x ) << ", "
497 << TVar( theAxis.y ) << ", "
498 << TVar( theAxis.z ) << ", "
499 << TVar( theAxis.vx ) << ", "
500 << TVar( theAxis.vy ) << ", "
501 << TVar( theAxis.vz ) << " )";
505 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
507 const SMESH::PointStruct & P = theDir.PS;
508 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
509 << TVar( P.x ) << ", "
510 << TVar( P.y ) << ", "
511 << TVar( P.z ) << " ))";
515 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
517 *this << "SMESH.PointStruct ( "
518 << TVar( P.x ) << ", "
519 << TVar( P.y ) << ", "
520 << TVar( P.z ) << " )";
524 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
526 DumpArray( theList, *this );
529 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
531 DumpArray( *theList, *this );
534 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGO& theList)
536 DumpArray( theList, *this );
539 TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGBO& theList)
541 DumpArray( theList, *this );
544 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
546 DumpArray( theList, *this );
549 const char* TPythonDump::NotPublishedObjectName()
551 return theNotPublishedObjectName;
554 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
555 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
557 //================================================================================
559 * \brief Return marker of long string literal beginning
560 * \param type - a name of functionality producing the string literal
561 * \retval TCollection_AsciiString - the marker string to be written into
562 * a raw python script
564 //================================================================================
566 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
570 (Standard_Integer) strlen(type) +
575 //================================================================================
577 * \brief Return marker of long string literal end
578 * \retval TCollection_AsciiString - the marker string to be written into
579 * a raw python script
581 //================================================================================
583 TCollection_AsciiString TPythonDump::LongStringEnd()
585 return myLongStringEnd;
588 //================================================================================
590 * \brief Cut out a long string literal from a string
591 * \param theText - text possibly containing string literals
592 * \param theFrom - position in the text to search from
593 * \param theLongString - the retrieved literal
594 * \param theStringType - a name of functionality produced the literal
595 * \retval bool - true if a string literal found
597 * The literal is removed from theText; theFrom points position right after
598 * the removed literal
600 //================================================================================
602 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
604 TCollection_AsciiString & theLongString,
605 TCollection_AsciiString & theStringType)
607 if ( theFrom < 1 || theFrom > theText.Length() )
610 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
611 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
612 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
615 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
619 // find where literal begins
620 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
621 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
622 int typeLen = atoi ( typeLenStr ); // = 7
623 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
624 literalBeg++; // 26 -> 27
627 literalBeg += typeLen + 1; // = 35
628 if ( literalBeg > theText.Length() )
631 // where literal ends (i.e. end marker begins)
632 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
634 literalEnd = theText.Length();
637 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
639 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
641 literalEnd += myLongStringEnd.Length(); // = 79
642 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
643 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
648 void printException( const char* text )
651 cout << "Exception in SMESH_Gen_i::DumpPython(): " << text << endl;
656 //=======================================================================
657 //function : RemoveTabulation
659 //=======================================================================
660 void RemoveTabulation( TCollection_AsciiString& theScript )
662 std::string aString( theScript.ToCString() );
663 std::string::size_type aPos = 0;
664 while( aPos < aString.length() )
666 aPos = aString.find( "\n\t", aPos );
667 if( aPos == std::string::npos )
669 aString.replace( aPos, 2, "\n" );
672 theScript = aString.c_str();
675 //=======================================================================
676 //function : DumpPython
678 //=======================================================================
679 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
680 CORBA::Boolean isPublished,
681 CORBA::Boolean isMultiFile,
682 CORBA::Boolean& isValidScript)
684 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
685 if (CORBA::is_nil(aStudy))
686 return new Engines::TMPFile(0);
688 CORBA::String_var compDataType = ComponentDataType();
689 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
690 if (CORBA::is_nil(aSO))
691 return new Engines::TMPFile(0);
693 // Map study entries to object names
694 Resource_DataMapOfAsciiStringAsciiString aMap;
695 Resource_DataMapOfAsciiStringAsciiString aMapNames;
697 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
698 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
699 SALOMEDS::SObject_wrap aValue = Itr->Value();
700 CORBA::String_var anID = aValue->GetID();
701 CORBA::String_var aName = aValue->GetName();
702 TCollection_AsciiString aGUIName ( (char*) aName.in() );
703 TCollection_AsciiString anEntry ( (char*) anID.in() );
704 if (aGUIName.Length() > 0) {
705 aMapNames.Bind( anEntry, aGUIName );
706 aMap.Bind( anEntry, aGUIName );
710 // Get trace of restored study
711 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
712 SALOMEDS::GenericAttribute_wrap anAttr =
713 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
715 SALOMEDS::AttributePythonObject_var pyAttr =
716 SALOMEDS::AttributePythonObject::_narrow(anAttr);
717 CORBA::String_var oldValue = pyAttr->GetObject();
718 TCollection_AsciiString aSavedTrace (oldValue.in());
720 // Add trace of API methods calls and replace study entries by names
721 TCollection_AsciiString aScript;
722 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
723 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
725 int aLen = aScript.Length();
726 unsigned char* aBuffer = new unsigned char[aLen+1];
727 strcpy((char*)aBuffer, aScript.ToCString());
729 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
730 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
732 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
733 isValidScript = isValidScript && !hasNotPublishedObjects;
735 return aStreamFile._retn();
738 //=============================================================================
742 //=============================================================================
743 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
745 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
746 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
748 myPythonScripts[theStudyID]->Append(theString);
751 //=============================================================================
753 * RemoveLastFromPythonScript
755 //=============================================================================
756 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
758 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
759 int aLen = myPythonScripts[theStudyID]->Length();
760 myPythonScripts[theStudyID]->Remove(aLen);
764 //=======================================================================
765 //function : SavePython
767 //=======================================================================
768 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
770 // Dump trace of API methods calls
771 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
773 // Check contents of PythonObject attribute
774 CORBA::String_var compDataType = ComponentDataType();
775 SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
776 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
777 SALOMEDS::GenericAttribute_wrap anAttr =
778 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
780 SALOMEDS::AttributePythonObject_var pyAttr =
781 SALOMEDS::AttributePythonObject::_narrow(anAttr);
782 CORBA::String_var oldValue = pyAttr->GetObject();
783 TCollection_AsciiString oldScript (oldValue.in());
785 if (oldScript.Length() > 0) {
787 oldScript += aScript;
792 // Store in PythonObject attribute
793 pyAttr->SetObject(oldScript.ToCString(), 1);
795 // Clean trace of API methods calls
796 CleanPythonTrace(theStudy->StudyId());
803 //=============================================================================
805 * FindEntries: Returns a sequence of start/end positions of entries in the string
807 //=============================================================================
808 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
810 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
811 Standard_Integer aLen = theString.Length();
812 Standard_Boolean isFound = Standard_False;
814 char* arr = (char*) theString.ToCString();
815 Standard_Integer i = 0, j;
820 if ( isdigit( c )) { //Is digit?
822 isFound = Standard_False;
823 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
825 if(c == ':') isFound = Standard_True;
829 int prev = (i < 1) ? 0 : (int)arr[i - 1];
830 // to distinguish from a sketcher command:
831 // last char should be a digit, not ":",
832 // previous char should not be '"'.
833 if (arr[j-2] != ':' && prev != '"') {
834 aSeq->Append(i+1); // +1 because AsciiString starts from 1
848 //================================================================================
850 * \brief Make a string be a valid python name
851 * \param aName - a string to fix
852 * \retval bool - true if aName was not modified
854 //================================================================================
856 bool fixPythonName(TCollection_AsciiString & aName)
858 bool isValidName = true;
859 int nbUnderscore = 0;
861 // replace not allowed chars by underscore
862 const char* name = aName.ToCString();
863 for ( p = 0; name[p]; ++p ) {
864 if ( !isalnum( name[p] ) && name[p] != '_' )
866 if ( p == 0 || p+1 == aName.Length() || name[p-1] == '_')
868 aName.Remove( p+1, 1 ); // remove __ and _ from the start and the end
870 name = aName.ToCString();
874 aName.SetValue( p+1, '_');
880 // aName must not start with a digit
881 if ( aName.IsIntegerValue() ) {
882 aName.Insert( 1, 'a' );
885 // shorten names like CartesianParameters3D_400_400_400_1000000_1
886 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
887 posted to SALOME Forum */
888 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
890 p = aName.Location( "_", 20, aName.Length());
897 //================================================================================
899 * \brief Return Python module names of available plug-ins.
901 //================================================================================
903 std::vector<std::string> getPluginNames()
905 std::vector<std::string> pluginNames;
906 std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
907 LDOMParser xmlParser;
908 for ( size_t i = 0; i < xmlPaths.size(); ++i )
910 bool error = xmlParser.parse( xmlPaths[i].c_str() );
913 TCollection_AsciiString data;
914 INFOS( xmlParser.GetError(data) );
917 // <meshers-group name="Standard Meshers"
918 // resources="StdMeshers"
919 // idl-module="StdMeshers"
920 // server-lib="StdMeshersEngine"
921 // gui-lib="StdMeshersGUI">
922 LDOM_Document xmlDoc = xmlParser.getDocument();
923 LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
924 for ( int i = 0; i < nodeList.getLength(); ++i )
926 LDOM_Node node = nodeList.item( i );
927 LDOM_Element& elem = (LDOM_Element&) node;
928 LDOMString idlModule = elem.getAttribute( "idl-module" );
929 if ( strlen( idlModule.GetString() ) > 0 )
930 pluginNames.push_back( idlModule.GetString() );
937 //================================================================================
939 * \brief Createa a Dump Python script
940 * \param [in] theStudy - the study to dump
941 * \param [in,out] theObjectNames - map of an entry to a study and python name
942 * \param [in] theNames - - map of an entry to a study name
943 * \param [in] isPublished - \c true if dump of object publication in study is needed
944 * \param [in] isMultiFile - \c true if dump of each module goes to a separate file
945 * \param [in] isHistoricalDump - \c true if removed object should be dumped
946 * \param [out] aValidScript - returns \c true if the returned script seems valid
947 * \param [in,out] theSavedTrace - the dump stored in the study. It's cleared to
948 * decrease memory usage.
949 * \return TCollection_AsciiString - the result dump script.
951 //================================================================================
953 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
954 (SALOMEDS::Study_ptr theStudy,
955 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
956 Resource_DataMapOfAsciiStringAsciiString& theNames,
959 bool isHistoricalDump,
961 TCollection_AsciiString& theSavedTrace)
964 const int aStudyID = theStudy->StudyId();
966 const TCollection_AsciiString aSmeshpy ( SMESH_2smeshpy::SmeshpyName() );
967 const TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
968 const TCollection_AsciiString anOldGen ( SMESH::TPythonDump::SMESHGenName() );
969 const TCollection_AsciiString helper; // to comfortably append C strings to TCollection_AsciiString
970 const TCollection_AsciiString tab( isMultiFile ? "\t" : "" ), nt = helper + "\n" + tab;
972 std::list< TCollection_AsciiString > lines; // lines of a script
973 std::list< TCollection_AsciiString >::iterator linesIt;
976 lines.push_back( aSMESHGen + " = smeshBuilder.New(theStudy)" );
978 lines.push_back( aSMESHGen + " = smeshBuilder.New(None)" );
979 lines.push_back( helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()" );
980 lines.push_back( helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()" );
982 // Treat dump trace of restored study
983 if (theSavedTrace.Length() > 0)
985 linesIt = --lines.end();
986 // Split theSavedTrace into lines
987 int from = 1, end = theSavedTrace.Length(), to;
988 while ( from < end && ( to = theSavedTrace.Location( "\n", from, end )))
990 if ( theSavedTrace.ToCString()[from-1] == '\t' )
993 lines.push_back( theSavedTrace.SubString( from, to - 1 ));
996 // For the convertion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
997 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
998 // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
1000 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
1001 theSavedTrace.Clear();
1002 if ( !isNewVersion )
1004 const TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
1006 for ( ++linesIt; linesIt != lines.end(); ++linesIt )
1008 TCollection_AsciiString& aSavedLine = *linesIt;
1009 end = aSavedLine.Length(), from = 1;
1010 while ( from < end && ( beg = aSavedLine.Location( aSmeshCall, from, end )))
1012 char charBefore = ( beg == 1 ) ? ' ' : aSavedLine.Value( beg - 1 );
1013 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
1014 aSavedLine.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
1015 end += gen.Length();
1017 from = beg + aSmeshCall.Length();
1023 // Add new dump trace of API methods calls to script lines
1024 if (myPythonScripts.find( aStudyID ) != myPythonScripts.end())
1026 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[ aStudyID ];
1027 Standard_Integer istr, aLen = aPythonScript->Length();
1028 for (istr = 1; istr <= aLen; istr++)
1029 lines.push_back( aPythonScript->Value( istr ));
1032 // Convert IDL API calls into smeshBuilder.py API.
1033 // Some objects are wrapped with python classes and
1034 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
1035 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
1036 std::set< TCollection_AsciiString > aRemovedObjIDs;
1037 if ( !getenv("NO_2smeshpy_conversion"))
1038 SMESH_2smeshpy::ConvertScript( lines, anEntry2AccessorMethod,
1039 theObjectNames, aRemovedObjIDs,
1040 theStudy, isHistoricalDump );
1042 bool importGeom = false;
1043 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
1045 // Add names of GEOM objects to theObjectNames to exclude same names of SMESH objects
1046 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
1047 int ign = 0, nbgn = aGeomNames->length();
1048 for (; ign < nbgn; ign++) {
1049 TCollection_AsciiString aName = aGeomNames[ign].in();
1050 theObjectNames.Bind(aName, "1");
1054 TCollection_AsciiString anUpdatedScript;
1056 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1057 Resource_DataMapOfAsciiStringAsciiString mapEntries; // names and entries present in anUpdatedScript
1058 Standard_Integer objectCounter = 0;
1059 TCollection_AsciiString anEntry, aName, aGUIName, aBaseName("smeshObj_");
1061 // Treat every script line and add it to anUpdatedScript
1062 for ( linesIt = lines.begin(); linesIt != lines.end(); ++linesIt )
1064 TCollection_AsciiString& aLine = *linesIt;
1065 anUpdatedScript += tab;
1067 //Replace characters used instead of quote marks to quote notebook variables
1069 while (( pos = aLine.Location( 1, SMESH::TVar::Quote(), pos, aLine.Length() )))
1070 aLine.SetValue( pos, '"' );
1072 // Find entries to be replaced by names
1073 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aLine);
1074 const Standard_Integer aSeqLen = aSeq->Length();
1075 Standard_Integer aStart = 1;
1076 for (Standard_Integer i = 1; i <= aSeqLen; i += 2)
1078 if ( aStart < aSeq->Value(i) )
1079 anUpdatedScript += aLine.SubString( aStart, aSeq->Value(i) - 1 ); // line part before i-th entry
1080 anEntry = aLine.SubString( aSeq->Value(i), aSeq->Value(i + 1) );
1081 // is a GEOM object?
1082 CORBA::String_var geomName = geom->GetDumpName( anEntry.ToCString() );
1083 if ( !geomName.in() || !geomName.in()[0] ) {
1084 // is a SMESH object
1085 if ( theObjectNames.IsBound( anEntry )) {
1086 // The Object is in Study
1087 aName = theObjectNames.Find( anEntry );
1088 // check validity of aName
1089 bool isValidName = fixPythonName( aName );
1090 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1091 // diff objects have same name - make a new name by appending a digit
1092 TCollection_AsciiString aName2;
1093 Standard_Integer i = 0;
1095 aName2 = aName + "_" + ++i;
1096 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1098 isValidName = false;
1101 theObjectNames(anEntry) = aName;
1103 if ( aLine.Value(1) != '#' )
1104 mapEntries.Bind(anEntry, aName);
1110 aName = aBaseName + (++objectCounter);
1111 } while (theObjectNames.IsBound(aName));
1113 if ( !aRemovedObjIDs.count( anEntry ) && aLine.Value(1) != '#')
1114 mapRemoved.Bind(anEntry, aName);
1116 theObjectNames.Bind(anEntry, aName);
1118 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1122 aName = geomName.in();
1125 anUpdatedScript += aName;
1126 aStart = aSeq->Value(i + 1) + 1;
1128 } // loop on entries within aLine
1131 anUpdatedScript += aLine;
1132 else if ( aSeq->Value( aSeqLen ) < aLine.Length() )
1133 anUpdatedScript += aLine.SubString( aSeq->Value(aSeqLen) + 1, aLine.Length() );
1135 anUpdatedScript += '\n';
1138 // Make an initial part of aSript
1140 TCollection_AsciiString initPart = "import ";
1142 initPart += "salome, ";
1143 initPart += " SMESH, SALOMEDS\n";
1144 initPart += "from salome.smesh import smeshBuilder\n";
1145 if ( importGeom && isMultiFile )
1147 initPart += ("\n## import GEOM dump file ## \n"
1148 "import string, os, sys, re\n"
1149 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
1150 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
1152 // import python files corresponding to plugins if they are used in anUpdatedScript
1154 TCollection_AsciiString importStr;
1155 std::vector<std::string> pluginNames = getPluginNames();
1156 for ( size_t i = 0; i < pluginNames.size(); ++i )
1158 // Convert access to plugin members:
1159 // e.g. StdMeshers.QUAD_REDUCED -> StdMeshersBuilder.QUAD_REDUCED
1160 TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
1161 int iFrom = 1, iPos;
1162 while (( iPos = anUpdatedScript.Location( pluginAccess, iFrom, anUpdatedScript.Length() )))
1164 anUpdatedScript.Insert( iPos + pluginNames[i].size(), "Builder" );
1165 iFrom = iPos + pluginNames[i].size() + 8;
1167 // if any plugin member is used, import the plugin
1169 importStr += ( helper + "\n" "from salome." + pluginNames[i].c_str() +
1170 " import " + pluginNames[i].c_str() +"Builder" );
1172 if ( !importStr.IsEmpty() )
1173 initPart += importStr + "\n";
1177 initPart += "def RebuildData(theStudy):";
1180 anUpdatedScript.Prepend( initPart );
1182 // Make a final part of aScript
1184 // Dump object removal
1185 TCollection_AsciiString removeObjPart;
1186 if ( !mapRemoved.IsEmpty() ) {
1187 removeObjPart += nt + "## some objects were removed";
1188 removeObjPart += nt + "aStudyBuilder = theStudy.NewBuilder()";
1189 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapRemovedIt;
1190 for ( mapRemovedIt.Initialize( mapRemoved ); mapRemovedIt.More(); mapRemovedIt.Next() ) {
1191 aName = mapRemovedIt.Value(); // python name
1192 anEntry = mapRemovedIt.Key();
1193 removeObjPart += nt + "SO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1194 removeObjPart += aName;
1195 // for object wrapped by class of smeshBuilder.py
1196 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1197 removeObjPart += helper + "." + anEntry2AccessorMethod( anEntry );
1198 removeObjPart += helper + "))" + nt + "if SO: aStudyBuilder.RemoveObjectWithChildren(SO)";
1203 TCollection_AsciiString setNamePart;
1204 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapEntriesIt;
1205 for ( mapEntriesIt.Initialize( mapEntries ); mapEntriesIt.More(); mapEntriesIt.Next() )
1207 anEntry = mapEntriesIt.Key();
1208 aName = mapEntriesIt.Value(); // python name
1209 if ( theNames.IsBound( anEntry ))
1211 aGUIName = theNames.Find(anEntry);
1212 setNamePart += nt + aSMESHGen + ".SetName(" + aName;
1213 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1214 setNamePart += helper + "." + anEntry2AccessorMethod( anEntry );
1215 setNamePart += helper + ", '" + aGUIName + "')";
1218 if ( !setNamePart.IsEmpty() )
1220 setNamePart.Insert( 1, nt + "## Set names of Mesh objects" );
1223 // Store visual properties of displayed objects
1225 TCollection_AsciiString visualPropertiesPart;
1228 //Output the script that sets up the visual parameters.
1229 CORBA::String_var compDataType = ComponentDataType();
1230 CORBA::String_var script = theStudy->GetDefaultScript( compDataType.in(), tab.ToCString() );
1231 if ( script.in() && script.in()[0] ) {
1232 visualPropertiesPart += nt + "### Store presentation parameters of displayed objects\n";
1233 visualPropertiesPart += script.in();
1237 anUpdatedScript += removeObjPart + '\n' + setNamePart + '\n' + visualPropertiesPart;
1240 anUpdatedScript += "\n\tpass";
1241 anUpdatedScript += "\n";
1243 // no need now as we use 'tab' and 'nt' variables depending on isMultiFile
1244 // if( !isMultiFile ) // remove unnecessary tabulation
1245 // RemoveTabulation( anUpdatedScript );
1247 // -----------------------------------------------------------------
1248 // put string literals describing patterns into separate functions
1249 // -----------------------------------------------------------------
1251 TCollection_AsciiString aLongString, aFunctionType;
1253 set< string > functionNameSet;
1254 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1256 // make a python string literal
1257 aLongString.Prepend(":\n\treturn '''\n");
1258 aLongString += "\n\t'''\n\tpass\n";
1260 TCollection_AsciiString functionName;
1262 // check if the function returning this literal is already defined
1263 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1264 if ( posAlready ) // already defined
1266 // find the function name
1267 int functBeg = posAlready;
1268 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1269 while ( *script != ' ' ) {
1273 functBeg++; // do not take ' '
1274 posAlready--; // do not take ':'
1275 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1277 else // not defined yet
1279 // find a unique function name
1280 fixPythonName( aFunctionType );
1281 Standard_Integer nb = 0;
1282 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1283 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1286 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1289 anUpdatedScript += helper + "\n\n" + funDef;
1294 anUpdatedScript.Insert( 1, funDef);
1295 where += funDef.Length();
1298 anUpdatedScript.InsertBefore( where, functionName ); // call function
1301 aValidScript = true;
1303 return anUpdatedScript;
1305 SMESH_CATCH( SMESH::printException );
1307 aValidScript = false;
1311 //=============================================================================
1315 //=============================================================================
1316 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1318 TCollection_AsciiString aScript;
1320 // Dump trace of API methods calls
1321 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1322 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1323 Standard_Integer istr, aLen = aPythonScript->Length();
1324 for (istr = 1; istr <= aLen; istr++) {
1326 aScript += aPythonScript->Value(istr);
1334 //=============================================================================
1338 //=============================================================================
1339 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1341 TCollection_AsciiString aScript;
1343 // Clean trace of API methods calls
1344 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1345 myPythonScripts[theStudyID]->Clear();