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>
41 static int MYDEBUG = 0;
43 static int MYDEBUG = 0;
49 size_t TPythonDump::myCounter = 0;
50 const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
52 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
53 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
54 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
55 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
57 for ( size_t i = 0; i < value.length(); i++)
58 myVals[i] = SMESH_Comment(value[i]);
62 TPythonDump():myVarsCounter(0)
70 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
71 std::string aString = myStream.str();
72 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
73 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
74 if(!aStudy->_is_nil() && !aCollection.IsEmpty())
76 const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
77 if ( !objEntry.empty() )
78 aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
79 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
80 if(MYDEBUG) MESSAGE(aString);
81 // prevent misuse of already treated variables
82 aSMESHGen->UpdateParameters(CORBA::Object_var().in(),"");
87 TPythonDump& //!< store a variable value. Write either a value or '$varID$'
89 operator<<(const TVar& theVarValue)
91 const std::vector< int >& varIDs = SMESH_Gen_i::GetSMESHGen()->GetLastParamIndices();
92 if ( theVarValue.myVals.size() != 1 )
95 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
97 if ( myVarsCounter < varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
98 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
100 myStream << theVarValue.myVals[i-1];
101 if ( i < theVarValue.myVals.size() )
109 if ( myVarsCounter < varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
110 myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
112 myStream << theVarValue.myVals[0];
120 operator<<(long int theArg){
127 operator<<(int theArg){
134 operator<<(double theArg){
141 operator<<(float theArg){
148 operator<<(const void* theArg){
155 operator<<(const char* theArg){
163 operator<<(const SMESH::ElementType& theArg)
167 case ALL: myStream<<"ALL"; break;
168 case NODE: myStream<<"NODE"; break;
169 case EDGE: myStream<<"EDGE"; break;
170 case FACE: myStream<<"FACE"; break;
171 case VOLUME: myStream<<"VOLUME"; break;
172 case ELEM0D: myStream<<"ELEM0D"; break;
173 case BALL: myStream<<"BALL"; break;
174 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
181 operator<<(const SMESH::GeometryType& theArg)
185 case Geom_POINT: myStream<<"Geom_POINT"; break;
186 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
187 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
188 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
189 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
190 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
191 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
192 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
193 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
194 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
195 case Geom_BALL: myStream<<"Geom_BALL"; break;
196 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
202 operator<<(const SMESH::EntityType& theArg)
206 case Entity_0D: myStream<<"Entity_0D"; break;
207 case Entity_Edge: myStream<<"Entity_Edge"; break;
208 case Entity_Quad_Edge: myStream<<"Entity_Quad_Edge"; break;
209 case Entity_Triangle: myStream<<"Entity_Triangle"; break;
210 case Entity_Quad_Triangle: myStream<<"Entity_Quad_Triangle"; break;
211 case Entity_BiQuad_Triangle: myStream<<"Entity_BiQuad_Triangle"; break;
212 case Entity_Quadrangle: myStream<<"Entity_Quadrangle"; break;
213 case Entity_Quad_Quadrangle: myStream<<"Entity_Quad_Quadrangle"; break;
214 case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
215 case Entity_Polygon: myStream<<"Entity_Polygon"; break;
216 case Entity_Quad_Polygon: myStream<<"Entity_Quad_Polygon"; break;
217 case Entity_Tetra: myStream<<"Entity_Tetra"; break;
218 case Entity_Quad_Tetra: myStream<<"Entity_Quad_Tetra"; break;
219 case Entity_Pyramid: myStream<<"Entity_Pyramid"; break;
220 case Entity_Quad_Pyramid: myStream<<"Entity_Quad_Pyramid"; break;
221 case Entity_Hexa: myStream<<"Entity_Hexa"; break;
222 case Entity_Quad_Hexa: myStream<<"Entity_Quad_Hexa"; break;
223 case Entity_TriQuad_Hexa: myStream<<"Entity_TriQuad_Hexa"; break;
224 case Entity_Penta: myStream<<"Entity_Penta"; break;
225 case Entity_Quad_Penta: myStream<<"Entity_Quad_Penta"; break;
226 case Entity_Hexagonal_Prism: myStream<<"Entity_Hexagonal_Prism"; break;
227 case Entity_Polyhedra: myStream<<"Entity_Polyhedra"; break;
228 case Entity_Quad_Polyhedra: myStream<<"Entity_Quad_Polyhedra"; break;
229 case Entity_Ball: myStream<<"Entity_Ball"; break;
230 case Entity_Last: myStream<<"Entity_Last"; break;
231 default: myStream<<"__UNKNOWN__EntityType: " << theArg;
236 template<class TArray>
237 void DumpArray(const TArray& theArray, TPythonDump & theStream)
240 for (int i = 1; i <= theArray.length(); i++) {
241 theStream << theArray[i-1];
242 if ( i < theArray.length() )
249 TPythonDump::operator<<(const SMESH::long_array& theArg)
251 DumpArray( theArg, *this );
256 TPythonDump::operator<<(const SMESH::double_array& theArg)
258 DumpArray( theArg, *this );
263 TPythonDump::operator<<(const SMESH::string_array& theArray)
266 for (int i = 1; i <= theArray.length(); i++) {
267 myStream << "'" << theArray[i-1] << "'";
268 if ( i < theArray.length() )
277 operator<<(SALOMEDS::SObject_ptr aSObject)
279 if ( !aSObject->_is_nil() ) {
280 CORBA::String_var entry = aSObject->GetID();
281 myStream << entry.in();
284 myStream << theNotPublishedObjectName;
291 operator<<(CORBA::Object_ptr theArg)
293 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
294 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
295 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
296 if(!aSObject->_is_nil()) {
297 CORBA::String_var id = aSObject->GetID();
299 } else if ( !CORBA::is_nil(theArg)) {
300 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
301 myStream << "smeshObj_" << size_t(theArg);
303 myStream << theNotPublishedObjectName;
312 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
314 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
315 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
316 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
317 myStream << "hyp_" << theArg->GetId();
325 operator<<(SMESH::SMESH_IDSource_ptr theArg)
327 if ( CORBA::is_nil( theArg ) )
328 return *this << "None";
329 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
330 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
331 SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
332 if(!aSObject->_is_nil())
334 return *this << aSObject;
336 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
338 return *this << filter;
340 if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
342 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
343 SMESH::long_array_var anElementsId = theArg->GetIDs();
344 SMESH::array_of_ElementType_var types = theArg->GetTypes();
345 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
346 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
348 return *this << theNotPublishedObjectName;
353 operator<<(SMESH::FilterLibrary_i* theArg)
355 myStream<<"aFilterLibrary"<<theArg;
361 operator<<(SMESH::FilterManager_i* theArg)
363 myStream<<"aFilterManager";
369 operator<<(SMESH::Filter_i* theArg)
371 myStream<<"aFilter"<<theArg;
377 operator<<(SMESH::Functor_i* theArg)
380 FunctorType aFunctorType = theArg->GetFunctorType();
381 switch(aFunctorType) {
382 case FT_AspectRatio: myStream<< "aAspectRatio"; break;
383 case FT_AspectRatio3D: myStream<< "aAspectRatio3D"; break;
384 case FT_Warping: myStream<< "aWarping"; break;
385 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
386 case FT_Taper: myStream<< "aTaper"; break;
387 case FT_Skew: myStream<< "aSkew"; break;
388 case FT_Area: myStream<< "aArea"; break;
389 case FT_Volume3D: myStream<< "aVolume3D"; break;
390 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
391 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
392 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
393 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
394 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
395 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
396 case FT_EqualNodes: myStream<< "aEqualNodes"; break;
397 case FT_EqualEdges: myStream<< "aEqualEdges"; break;
398 case FT_EqualFaces: myStream<< "aEqualFaces"; break;
399 case FT_EqualVolumes: myStream<< "aEqualVolumes"; break;
400 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
401 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
402 case FT_Length: myStream<< "aLength"; break;
403 case FT_Length2D: myStream<< "aLength2D"; break;
404 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
405 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
406 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
407 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
408 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
409 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
410 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
411 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
412 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
413 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
414 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
415 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
416 case FT_GroupColor: myStream<< "aGroupColor"; break;
417 case FT_ElemGeomType: myStream<< "aElemGeomType"; break;
418 case FT_EntityType: myStream<< "aEntityType"; break;
419 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
420 case FT_BallDiameter: myStream<< "aBallDiameter"; break;
421 case FT_ConnectedElements: myStream<< "aConnectedElements"; break;
422 case FT_LessThan: myStream<< "aLessThan"; break;
423 case FT_MoreThan: myStream<< "aMoreThan"; break;
424 case FT_EqualTo: myStream<< "aEqualTo"; break;
425 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
426 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
427 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
429 default: myStream<< "anUndefined"; break;
438 operator<<(SMESH::Measurements_i* theArg)
440 myStream<<"aMeasurements";
445 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
447 myStream << SMESHGenName(); return *this;
450 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
452 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
455 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
457 myStream << theStr; return *this;
461 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
463 switch (theVersion) {
464 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
465 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
466 default: myStream << theVersion;
471 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
473 *this << "SMESH.AxisStruct( "
474 << TVar( theAxis.x ) << ", "
475 << TVar( theAxis.y ) << ", "
476 << TVar( theAxis.z ) << ", "
477 << TVar( theAxis.vx ) << ", "
478 << TVar( theAxis.vy ) << ", "
479 << TVar( theAxis.vz ) << " )";
483 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
485 const SMESH::PointStruct & P = theDir.PS;
486 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
487 << TVar( P.x ) << ", "
488 << TVar( P.y ) << ", "
489 << TVar( P.z ) << " ))";
493 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
495 *this << "SMESH.PointStruct ( "
496 << TVar( P.x ) << ", "
497 << TVar( P.y ) << ", "
498 << TVar( P.z ) << " )";
502 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
504 DumpArray( theList, *this );
507 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
509 DumpArray( *theList, *this );
512 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
514 DumpArray( theList, *this );
517 const char* TPythonDump::NotPublishedObjectName()
519 return theNotPublishedObjectName;
522 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
523 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
525 //================================================================================
527 * \brief Return marker of long string literal beginning
528 * \param type - a name of functionality producing the string literal
529 * \retval TCollection_AsciiString - the marker string to be written into
530 * a raw python script
532 //================================================================================
534 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
538 (Standard_Integer) strlen(type) +
543 //================================================================================
545 * \brief Return marker of long string literal end
546 * \retval TCollection_AsciiString - the marker string to be written into
547 * a raw python script
549 //================================================================================
551 TCollection_AsciiString TPythonDump::LongStringEnd()
553 return myLongStringEnd;
556 //================================================================================
558 * \brief Cut out a long string literal from a string
559 * \param theText - text possibly containing string literals
560 * \param theFrom - position in the text to search from
561 * \param theLongString - the retrieved literal
562 * \param theStringType - a name of functionality produced the literal
563 * \retval bool - true if a string literal found
565 * The literal is removed from theText; theFrom points position right after
566 * the removed literal
568 //================================================================================
570 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
572 TCollection_AsciiString & theLongString,
573 TCollection_AsciiString & theStringType)
575 if ( theFrom < 1 || theFrom > theText.Length() )
578 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
579 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
580 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
583 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
587 // find where literal begins
588 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
589 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
590 int typeLen = atoi ( typeLenStr ); // = 7
591 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
592 literalBeg++; // 26 -> 27
595 literalBeg += typeLen + 1; // = 35
596 if ( literalBeg > theText.Length() )
599 // where literal ends (i.e. end marker begins)
600 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
602 literalEnd = theText.Length();
605 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
607 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
609 literalEnd += myLongStringEnd.Length(); // = 79
610 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
611 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
617 //=======================================================================
618 //function : RemoveTabulation
620 //=======================================================================
621 void RemoveTabulation( TCollection_AsciiString& theScript )
623 std::string aString( theScript.ToCString() );
624 std::string::size_type aPos = 0;
625 while( aPos < aString.length() )
627 aPos = aString.find( "\n\t", aPos );
628 if( aPos == std::string::npos )
630 aString.replace( aPos, 2, "\n" );
633 theScript = aString.c_str();
636 //=======================================================================
637 //function : DumpPython
639 //=======================================================================
640 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
641 CORBA::Boolean isPublished,
642 CORBA::Boolean isMultiFile,
643 CORBA::Boolean& isValidScript)
645 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
646 if (CORBA::is_nil(aStudy))
647 return new Engines::TMPFile(0);
649 CORBA::String_var compDataType = ComponentDataType();
650 SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
651 if (CORBA::is_nil(aSO))
652 return new Engines::TMPFile(0);
654 // Map study entries to object names
655 Resource_DataMapOfAsciiStringAsciiString aMap;
656 Resource_DataMapOfAsciiStringAsciiString aMapNames;
657 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
659 SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
660 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
661 SALOMEDS::SObject_wrap aValue = Itr->Value();
662 CORBA::String_var anID = aValue->GetID();
663 CORBA::String_var aName = aValue->GetName();
664 TCollection_AsciiString aGUIName ( (char*) aName.in() );
665 TCollection_AsciiString anEnrty ( (char*) anID.in() );
666 if (aGUIName.Length() > 0) {
667 aMapNames.Bind( anEnrty, aGUIName );
668 aMap.Bind( anEnrty, aGUIName );
672 // Get trace of restored study
673 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
674 SALOMEDS::GenericAttribute_wrap anAttr =
675 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
677 SALOMEDS::AttributePythonObject_var pyAttr =
678 SALOMEDS::AttributePythonObject::_narrow(anAttr);
679 CORBA::String_var oldValue = pyAttr->GetObject();
680 TCollection_AsciiString aSavedTrace (oldValue.in());
682 // Add trace of API methods calls and replace study entries by names
683 TCollection_AsciiString aScript;
684 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
685 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
687 int aLen = aScript.Length();
688 unsigned char* aBuffer = new unsigned char[aLen+1];
689 strcpy((char*)aBuffer, aScript.ToCString());
691 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
692 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
694 bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
695 isValidScript = isValidScript && !hasNotPublishedObjects;
697 return aStreamFile._retn();
700 //=============================================================================
704 //=============================================================================
705 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
707 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
708 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
710 myPythonScripts[theStudyID]->Append(theString);
713 //=============================================================================
715 * RemoveLastFromPythonScript
717 //=============================================================================
718 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
720 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
721 int aLen = myPythonScripts[theStudyID]->Length();
722 myPythonScripts[theStudyID]->Remove(aLen);
726 //=======================================================================
727 //function : SavePython
729 //=======================================================================
730 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
732 // Dump trace of API methods calls
733 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
735 // Check contents of PythonObject attribute
736 CORBA::String_var compDataType = ComponentDataType();
737 SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
738 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
739 SALOMEDS::GenericAttribute_wrap anAttr =
740 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
742 SALOMEDS::AttributePythonObject_var pyAttr =
743 SALOMEDS::AttributePythonObject::_narrow(anAttr);
744 CORBA::String_var oldValue = pyAttr->GetObject();
745 TCollection_AsciiString oldScript (oldValue.in());
747 if (oldScript.Length() > 0) {
749 oldScript += aScript;
754 // Store in PythonObject attribute
755 pyAttr->SetObject(oldScript.ToCString(), 1);
757 // Clean trace of API methods calls
758 CleanPythonTrace(theStudy->StudyId());
765 //=============================================================================
767 * FindEntries: Returns a sequence of start/end positions of entries in the string
769 //=============================================================================
770 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
772 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
773 Standard_Integer aLen = theString.Length();
774 Standard_Boolean isFound = Standard_False;
776 char* arr = (char*) theString.ToCString();
777 Standard_Integer i = 0, j;
782 if ( isdigit( c )) { //Is digit?
784 isFound = Standard_False;
785 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
787 if(c == ':') isFound = Standard_True;
791 int prev = (i < 1) ? 0 : (int)arr[i - 1];
792 // to distinguish from a sketcher command:
793 // last char should be a digit, not ":",
794 // previous char should not be '"'.
795 if (arr[j-2] != ':' && prev != '"') {
796 aSeq->Append(i+1); // +1 because AsciiString starts from 1
810 //================================================================================
812 * \brief Make a string be a valid python name
813 * \param aName - a string to fix
814 * \retval bool - true if aName was not modified
816 //================================================================================
818 bool fixPythonName(TCollection_AsciiString & aName )
820 const TCollection_AsciiString allowedChars =
821 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
822 bool isValidName = true;
823 int nbUnderscore = 0;
824 int p=1; // replace not allowed chars by underscore
825 while (p <= aName.Length() &&
826 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
828 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
829 aName.Remove( p, 1 ); // remove double _ from the start and the end
831 aName.SetValue(p, '_'), nbUnderscore++;
834 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
835 aName.Insert( 1, 'a' );
838 // shorten names like CartesianParameters3D_400_400_400_1000000_1
839 const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
840 posted to SALOME Forum */
841 if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
843 p = aName.Location( "_", 20, aName.Length());
851 //=============================================================================
855 //=============================================================================
856 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
857 (SALOMEDS::Study_ptr theStudy,
858 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
859 Resource_DataMapOfAsciiStringAsciiString& theNames,
862 bool isHistoricalDump,
864 const TCollection_AsciiString& theSavedTrace)
866 int aStudyID = theStudy->StudyId();
868 TCollection_AsciiString helper; // to comfortably concatenate C strings
869 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
870 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
871 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
873 TCollection_AsciiString aScript;
875 aScript += "def RebuildData(theStudy):";
878 aScript += aSMESHGen + " = smeshBuilder.New(theStudy)\n\t";
880 aScript += aSMESHGen + " = smeshBuilder.New(None)\n\t";
881 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
882 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
884 // import python files corresponding to plugins
885 set<string> moduleNameSet;
886 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
887 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
888 string moduleName = hyp_creator->second->GetModuleName();
889 bool newModule = moduleNameSet.insert( moduleName ).second;
891 aScript += helper + "\n\t" + "from salome." + (char*) moduleName.c_str() + " import " + (char*) moduleName.c_str() +"Builder";
894 // Dump trace of restored study
895 if (theSavedTrace.Length() > 0) {
896 // For the convertion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
897 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
898 // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
900 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
901 if ( !isNewVersion ) {
902 TCollection_AsciiString aSavedTrace( theSavedTrace );
903 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
904 int beg, end = aSavedTrace.Length(), from = 1;
905 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
906 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
907 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
908 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
911 from = beg + aSmeshCall.Length();
913 aScript += helper + "\n" + aSavedTrace;
916 // append a saved trace to the script
917 aScript += helper + "\n" + theSavedTrace;
920 // Dump trace of API methods calls
921 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
922 if (aNewLines.Length() > 0) {
923 aScript += helper + "\n" + aNewLines;
926 // Convert IDL API calls into smeshBuilder.py API.
927 // Some objects are wrapped with python classes and
928 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
929 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
930 std::set< TCollection_AsciiString > aRemovedObjIDs;
931 if ( !getenv("NO_2smeshpy_conversion"))
932 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
933 theObjectNames, aRemovedObjIDs,
934 theStudy, isHistoricalDump );
936 // Replace characters used instead of quote marks to quote notebook variables
939 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
940 aScript.SetValue( pos, '"' );
943 // Find entries to be replaced by names
944 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
945 Standard_Integer aLen = aSeq->Length();
947 if (aLen == 0 && isMultiFile)
950 // Replace entries by the names
951 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
952 TColStd_SequenceOfAsciiString seqRemoved;
953 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
954 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
955 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
957 // Collect names of GEOM objects to exclude same names of SMESH objects
958 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
959 int ign = 0, nbgn = aGeomNames->length();
960 for (; ign < nbgn; ign++) {
961 aName = aGeomNames[ign];
962 theObjectNames.Bind(aName, "1");
965 bool importGeom = false;
966 for (Standard_Integer i = 1; i <= aLen; i += 2) {
967 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
968 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
970 aName = geom->GetDumpName( anEntry.ToCString() );
971 if (aName.IsEmpty()) {
973 if (theObjectNames.IsBound(anEntry)) {
974 // The Object is in Study
975 aName = theObjectNames.Find(anEntry);
976 // check validity of aName
977 bool isValidName = fixPythonName( aName );
978 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
979 // diff objects have same name - make a new name by appending a digit
980 TCollection_AsciiString aName2;
981 Standard_Integer i = 0;
983 aName2 = aName + "_" + ++i;
984 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
989 theObjectNames(anEntry) = aName;
994 aName = aBaseName + (++objectCounter);
995 } while (theObjectNames.IsBound(aName));
996 seqRemoved.Append(aName);
997 mapRemoved.Bind(anEntry, "1");
998 theObjectNames.Bind(anEntry, aName);
1000 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1006 anUpdatedScript += aName;
1007 aStart = aSeq->Value(i + 1) + 1;
1010 // set initial part of aSript
1011 TCollection_AsciiString initPart = "import ";
1013 initPart += helper + "salome, ";
1014 initPart += " SMESH, SALOMEDS\n";
1015 initPart += "from salome.smesh import smeshBuilder\n";
1016 if ( importGeom && isMultiFile )
1018 initPart += ("\n## import GEOM dump file ## \n"
1019 "import string, os, sys, re\n"
1020 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
1021 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
1023 anUpdatedScript.Insert ( 1, initPart );
1025 // add final part of aScript
1026 if (aLen && aSeq->Value(aLen) < aScriptLength)
1027 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
1029 // Remove removed objects
1030 if ( seqRemoved.Length() > 0 ) {
1031 anUpdatedScript += "\n\t## some objects were removed";
1032 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
1034 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
1035 if ( aRemovedObjIDs.count( seqRemoved.Value(ir) )) continue;
1036 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1037 anUpdatedScript += seqRemoved.Value(ir);
1038 // for object wrapped by class of smeshBuilder.py
1039 anEntry = theObjectNames( seqRemoved.Value(ir) );
1040 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1041 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1042 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
1046 anUpdatedScript += "\n\t## set object names";
1047 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
1048 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
1049 // anUpdatedScript += "\n";
1051 TCollection_AsciiString aGUIName;
1052 Resource_DataMapOfAsciiStringAsciiString mapEntries;
1053 for (Standard_Integer i = 1; i <= aLen; i += 2)
1055 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
1056 aName = geom->GetDumpName( anEntry.ToCString() );
1057 if (aName.IsEmpty() && // Not a GEOM object
1058 theNames.IsBound(anEntry) &&
1059 !aRemovedObjIDs.count(anEntry) && // a command creating anEntry was erased
1060 !mapEntries.IsBound(anEntry) && // Not yet processed
1061 !mapRemoved.IsBound(anEntry)) // Was not removed
1063 aName = theObjectNames.Find(anEntry);
1064 aGUIName = theNames.Find(anEntry);
1065 mapEntries.Bind(anEntry, aName);
1066 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1067 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1068 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1069 anUpdatedScript += helper + ", '" + aGUIName + "')";
1073 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
1074 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
1075 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
1077 // -----------------------------------------------------------------
1078 // store visual properties of displayed objects
1079 // -----------------------------------------------------------------
1083 //Output the script that sets up the visual parameters.
1084 CORBA::String_var compDataType = ComponentDataType();
1085 char* script = theStudy->GetDefaultScript( compDataType.in(), "\t");
1086 if (script && strlen(script) > 0) {
1087 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1088 anUpdatedScript += script;
1089 CORBA::string_free(script);
1094 anUpdatedScript += "\n\tpass";
1095 anUpdatedScript += "\n";
1097 if( !isMultiFile ) // remove unnecessary tabulation
1098 RemoveTabulation( anUpdatedScript );
1100 // -----------------------------------------------------------------
1101 // put string literals describing patterns into separate functions
1102 // -----------------------------------------------------------------
1104 TCollection_AsciiString aLongString, aFunctionType;
1106 set< string > functionNameSet;
1107 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1109 // make a python string literal
1110 aLongString.Prepend(":\n\treturn '''\n");
1111 aLongString += "\n\t'''\n\tpass\n";
1113 TCollection_AsciiString functionName;
1115 // check if the function returning this literal is already defined
1116 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1117 if ( posAlready ) // already defined
1119 // find the function name
1120 int functBeg = posAlready;
1121 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1122 while ( *script != ' ' ) {
1126 functBeg++; // do not take ' '
1127 posAlready--; // do not take ':'
1128 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1130 else // not defined yet
1132 // find a unique function name
1133 fixPythonName( aFunctionType );
1134 Standard_Integer nb = 0;
1135 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1136 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1139 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1142 anUpdatedScript += helper + "\n\n" + funDef;
1147 anUpdatedScript.Insert( 1, funDef);
1148 where += funDef.Length();
1151 anUpdatedScript.InsertBefore( where, functionName ); // call function
1154 aValidScript = true;
1156 return anUpdatedScript;
1159 //=============================================================================
1163 //=============================================================================
1164 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1166 TCollection_AsciiString aScript;
1168 // Dump trace of API methods calls
1169 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1170 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1171 Standard_Integer istr, aLen = aPythonScript->Length();
1172 for (istr = 1; istr <= aLen; istr++) {
1174 aScript += aPythonScript->Value(istr);
1182 //=============================================================================
1186 //=============================================================================
1187 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1189 TCollection_AsciiString aScript;
1191 // Clean trace of API methods calls
1192 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1193 myPythonScripts[theStudyID]->Clear();