1 // Copyright (C) 2007-2012 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"
28 #include "SMESH_Gen_i.hxx"
29 #include "SMESH_Filter_i.hxx"
30 #include "SMESH_MeshEditor_i.hxx"
31 #include "SMESH_2smeshpy.hxx"
33 #include <TColStd_HSequenceOfInteger.hxx>
34 #include <TCollection_AsciiString.hxx>
35 #include <SMESH_Comment.hxx>
39 static int MYDEBUG = 0;
41 static int MYDEBUG = 0;
44 static TCollection_AsciiString NotPublishedObjectName()
46 return "__NOT__Published__Object__";
52 size_t TPythonDump::myCounter = 0;
54 TVar::TVar(CORBA::Double value):myVals(1) { myVals[0] = SMESH_Comment(value); }
55 TVar::TVar(CORBA::Long value):myVals(1) { myVals[0] = SMESH_Comment(value); }
56 TVar::TVar(CORBA::Short value):myVals(1) { myVals[0] = SMESH_Comment(value); }
57 TVar::TVar(const SMESH::double_array& value):myVals(value.length())
59 for ( size_t i = 0; i < value.length(); i++)
60 myVals[i] = SMESH_Comment(value[i]);
64 TPythonDump():myVarsCounter(0)
72 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
73 std::string aString = myStream.str();
74 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
75 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
76 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
77 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
78 if(MYDEBUG) MESSAGE(aString);
79 aSMESHGen->UpdateParameters(""); // prevent misuse of already treated variables
84 TPythonDump& //!< to store a variable value
86 operator<<(const TVar& theVarValue)
88 const std::vector< std::string >& varNames = SMESH_Gen_i::GetSMESHGen()->GetLastParameters();
89 if ( theVarValue.myVals.size() != 1 )
92 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
94 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
95 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
97 myStream << theVarValue.myVals[i-1];
98 if ( i < theVarValue.myVals.size() )
106 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
107 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
109 myStream << theVarValue.myVals[0];
117 operator<<(long int theArg){
124 operator<<(int theArg){
131 operator<<(double theArg){
138 operator<<(float theArg){
145 operator<<(const void* theArg){
152 operator<<(const char* theArg){
160 operator<<(const SMESH::ElementType& theArg)
164 case ALL: myStream<<"ALL"; break;
165 case NODE: myStream<<"NODE"; break;
166 case EDGE: myStream<<"EDGE"; break;
167 case FACE: myStream<<"FACE"; break;
168 case VOLUME: myStream<<"VOLUME"; break;
169 case ELEM0D: myStream<<"ELEM0D"; break;
170 case BALL: myStream<<"BALL"; break;
171 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
178 operator<<(const SMESH::GeometryType& theArg)
182 case Geom_POINT: myStream<<"Geom_POINT"; break;
183 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
184 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
185 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
186 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
187 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
188 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
189 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
190 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
191 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
192 case Geom_BALL: myStream<<"Geom_BALL"; break;
193 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
198 template<class TArray>
199 void DumpArray(const TArray& theArray, TPythonDump & theStream)
202 for (int i = 1; i <= theArray.length(); i++) {
203 theStream << theArray[i-1];
204 if ( i < theArray.length() )
211 TPythonDump::operator<<(const SMESH::long_array& theArg)
213 DumpArray( theArg, *this );
218 TPythonDump::operator<<(const SMESH::double_array& theArg)
220 DumpArray( theArg, *this );
225 TPythonDump::operator<<(const SMESH::string_array& theArray)
228 for (int i = 1; i <= theArray.length(); i++) {
229 myStream << "'" << theArray[i-1] << "'";
230 if ( i < theArray.length() )
239 operator<<(SALOMEDS::SObject_ptr aSObject)
241 if ( !aSObject->_is_nil() )
242 myStream << aSObject->GetID();
244 myStream << NotPublishedObjectName();
250 operator<<(CORBA::Object_ptr theArg)
252 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
253 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
254 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
255 if(!aSObject->_is_nil()) {
256 CORBA::String_var id = aSObject->GetID();
258 } else if ( !CORBA::is_nil(theArg)) {
259 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
260 myStream << "smeshObj_" << size_t(theArg);
262 myStream << NotPublishedObjectName();
271 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
273 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
274 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
275 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
276 myStream << "hyp_" << theArg->GetId();
278 *this << CORBA::Object_ptr( theArg );
284 operator<<(SMESH::SMESH_IDSource_ptr theArg)
286 if ( CORBA::is_nil( theArg ) )
287 return *this << "None";
288 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
289 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
290 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
291 if(!aSObject->_is_nil())
292 return *this << aSObject;
293 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
294 return *this << filter;
295 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
296 if ( !theArg->_is_equivalent( mesh ))
298 SMESH::long_array_var anElementsId = theArg->GetIDs();
299 SMESH::array_of_ElementType_var types = theArg->GetTypes();
300 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
301 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
308 operator<<(SMESH::FilterLibrary_i* theArg)
310 myStream<<"aFilterLibrary"<<theArg;
316 operator<<(SMESH::FilterManager_i* theArg)
318 myStream<<"aFilterManager";
324 operator<<(SMESH::Filter_i* theArg)
326 myStream<<"aFilter"<<theArg;
332 operator<<(SMESH::Functor_i* theArg)
335 FunctorType aFunctorType = theArg->GetFunctorType();
336 switch(aFunctorType){
337 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
338 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
339 case FT_Warping: myStream<< "aWarping"; break;
340 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
341 case FT_Taper: myStream<< "aTaper"; break;
342 case FT_Skew: myStream<< "aSkew"; break;
343 case FT_Area: myStream<< "aArea"; break;
344 case FT_Volume3D: myStream<< "aVolume3D"; break;
345 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
346 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
347 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
348 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
349 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
350 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
351 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
352 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
353 case FT_Length: myStream<< "aLength"; break;
354 case FT_Length2D: myStream<< "aLength2D"; break;
355 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
356 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
357 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
358 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
359 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
360 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
361 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
362 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
363 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
364 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
365 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
366 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
367 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
368 case FT_GroupColor: myStream<< "aGroupColor"; break;
369 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
370 case FT_LessThan: myStream<< "aLessThan"; break;
371 case FT_MoreThan: myStream<< "aMoreThan"; break;
372 case FT_EqualTo: myStream<< "anEqualTo"; break;
373 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
374 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
375 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
377 default: myStream<< "anUndefined"; break;
386 operator<<(SMESH::Measurements_i* theArg)
388 myStream<<"aMeasurements";
393 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
395 myStream << SMESHGenName(); return *this;
398 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
400 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
403 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
405 myStream << theStr; return *this;
409 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
411 switch (theVersion) {
412 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
413 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
414 default: myStream << theVersion;
419 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
421 *this << "SMESH.AxisStruct( "
422 << TVar( theAxis.x ) << ", "
423 << TVar( theAxis.y ) << ", "
424 << TVar( theAxis.z ) << ", "
425 << TVar( theAxis.vx ) << ", "
426 << TVar( theAxis.vy ) << ", "
427 << TVar( theAxis.vz ) << " )";
431 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
433 const SMESH::PointStruct & P = theDir.PS;
434 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
435 << TVar( P.x ) << ", "
436 << TVar( P.y ) << ", "
437 << TVar( P.z ) << " ))";
441 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
443 *this << "SMESH.PointStruct ( "
444 << TVar( P.x ) << ", "
445 << TVar( P.y ) << ", "
446 << TVar( P.z ) << " )";
450 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
452 DumpArray( theList, *this );
455 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
457 DumpArray( *theList, *this );
460 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
462 DumpArray( theList, *this );
466 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
467 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
469 //================================================================================
471 * \brief Return marker of long string literal beginning
472 * \param type - a name of functionality producing the string literal
473 * \retval TCollection_AsciiString - the marker string to be written into
474 * a raw python script
476 //================================================================================
478 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
482 (Standard_Integer) strlen(type) +
487 //================================================================================
489 * \brief Return marker of long string literal end
490 * \retval TCollection_AsciiString - the marker string to be written into
491 * a raw python script
493 //================================================================================
495 TCollection_AsciiString TPythonDump::LongStringEnd()
497 return myLongStringEnd;
500 //================================================================================
502 * \brief Cut out a long string literal from a string
503 * \param theText - text possibly containing string literals
504 * \param theFrom - position in the text to search from
505 * \param theLongString - the retrieved literal
506 * \param theStringType - a name of functionality produced the literal
507 * \retval bool - true if a string literal found
509 * The literal is removed from theText; theFrom points position right after
510 * the removed literal
512 //================================================================================
514 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
516 TCollection_AsciiString & theLongString,
517 TCollection_AsciiString & theStringType)
519 if ( theFrom < 1 || theFrom > theText.Length() )
522 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
523 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
524 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
527 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
531 // find where literal begins
532 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
533 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
534 int typeLen = atoi ( typeLenStr ); // = 7
535 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
536 literalBeg++; // 26 -> 27
539 literalBeg += typeLen + 1; // = 35
540 if ( literalBeg > theText.Length() )
543 // where literal ends (i.e. end marker begins)
544 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
546 literalEnd = theText.Length();
549 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
551 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
553 literalEnd += myLongStringEnd.Length(); // = 79
554 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
555 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
561 //=======================================================================
562 //function : RemoveTabulation
564 //=======================================================================
565 void RemoveTabulation( TCollection_AsciiString& theScript )
567 std::string aString( theScript.ToCString() );
568 std::string::size_type aPos = 0;
569 while( aPos < aString.length() )
571 aPos = aString.find( "\n\t", aPos );
572 if( aPos == std::string::npos )
574 aString.replace( aPos, 2, "\n" );
577 theScript = aString.c_str();
580 //=======================================================================
581 //function : DumpPython
583 //=======================================================================
584 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
585 CORBA::Boolean isPublished,
586 CORBA::Boolean isMultiFile,
587 CORBA::Boolean& isValidScript)
589 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
590 if (CORBA::is_nil(aStudy))
591 return new Engines::TMPFile(0);
593 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
594 if (CORBA::is_nil(aSO))
595 return new Engines::TMPFile(0);
597 // Map study entries to object names
598 Resource_DataMapOfAsciiStringAsciiString aMap;
599 Resource_DataMapOfAsciiStringAsciiString aMapNames;
600 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
602 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
603 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
604 SALOMEDS::SObject_var aValue = Itr->Value();
605 CORBA::String_var anID = aValue->GetID();
606 CORBA::String_var aName = aValue->GetName();
607 TCollection_AsciiString aGUIName ( (char*) aName.in() );
608 TCollection_AsciiString anEnrty ( (char*) anID.in() );
609 if (aGUIName.Length() > 0) {
610 aMapNames.Bind( anEnrty, aGUIName );
611 aMap.Bind( anEnrty, aGUIName );
615 // Get trace of restored study
616 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
617 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
618 SALOMEDS::GenericAttribute_var anAttr =
619 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
621 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
622 TCollection_AsciiString aSavedTrace (oldValue);
624 // Add trace of API methods calls and replace study entries by names
625 TCollection_AsciiString aScript;
626 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
627 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
629 int aLen = aScript.Length();
630 unsigned char* aBuffer = new unsigned char[aLen+1];
631 strcpy((char*)aBuffer, aScript.ToCString());
633 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
634 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
636 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
637 isValidScript = isValidScript && !hasNotPublishedObjects;
639 return aStreamFile._retn();
642 //=============================================================================
646 //=============================================================================
647 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
649 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
650 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
652 myPythonScripts[theStudyID]->Append(theString);
655 //=============================================================================
657 * RemoveLastFromPythonScript
659 //=============================================================================
660 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
662 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
663 int aLen = myPythonScripts[theStudyID]->Length();
664 myPythonScripts[theStudyID]->Remove(aLen);
668 //=======================================================================
669 //function : SavePython
671 //=======================================================================
672 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
674 // Dump trace of API methods calls
675 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
677 // Check contents of PythonObject attribute
678 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
679 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
680 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
681 SALOMEDS::GenericAttribute_var anAttr =
682 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
684 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
685 TCollection_AsciiString oldScript (oldValue);
687 if (oldScript.Length() > 0) {
689 oldScript += aScript;
694 // Store in PythonObject attribute
695 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
697 // Clean trace of API methods calls
698 CleanPythonTrace(theStudy->StudyId());
705 //=============================================================================
707 * FindEntries: Returns a sequence of start/end positions of entries in the string
709 //=============================================================================
710 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
712 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
713 Standard_Integer aLen = theString.Length();
714 Standard_Boolean isFound = Standard_False;
716 char* arr = (char*) theString.ToCString();
717 Standard_Integer i = 0, j;
722 if ( isdigit( c )) { //Is digit?
724 isFound = Standard_False;
725 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
727 if(c == ':') isFound = Standard_True;
731 int prev = (i < 1) ? 0 : (int)arr[i - 1];
732 // to distinguish from a sketcher command:
733 // last char should be a digit, not ":",
734 // previous char should not be '"'.
735 if (arr[j-2] != ':' && prev != '"') {
736 aSeq->Append(i+1); // +1 because AsciiString starts from 1
750 //================================================================================
752 * \brief Make a string be a valid python name
753 * \param aName - a string to fix
754 * \retval bool - true if aName was not modified
756 //================================================================================
758 bool fixPythonName(TCollection_AsciiString & aName )
760 const TCollection_AsciiString allowedChars =
761 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
762 bool isValidName = true;
763 int nbUnderscore = 0;
764 int p=1; // replace not allowed chars by underscore
765 while (p <= aName.Length() &&
766 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
768 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
769 aName.Remove( p, 1 ); // remove double _ from the start and the end
771 aName.SetValue(p, '_'), nbUnderscore++;
774 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
775 aName.Insert( 1, 'a' );
778 // shorten names like CartesianParameters3D_400_400_400_1000000_1
779 if ( aName.Length() > 20 && nbUnderscore > 2 )
781 p = aName.Location( "_", 20, aName.Length());
789 //=============================================================================
793 //=============================================================================
794 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
795 (SALOMEDS::Study_ptr theStudy,
796 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
797 Resource_DataMapOfAsciiStringAsciiString& theNames,
800 bool isHistoricalDump,
802 const TCollection_AsciiString& theSavedTrace)
804 int aStudyID = theStudy->StudyId();
806 TCollection_AsciiString helper; // to comfortably concatenate C strings
807 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
808 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
809 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
811 TCollection_AsciiString aScript;
813 aScript += "def RebuildData(theStudy):";
815 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
816 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
818 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
820 aScript += aSMESHGen + ".SetCurrentStudy(None)";
822 // import python files corresponding to plugins
823 set<string> moduleNameSet;
824 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
825 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
826 string moduleName = hyp_creator->second->GetModuleName();
827 bool newModule = moduleNameSet.insert( moduleName ).second;
829 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
832 // Dump trace of restored study
833 if (theSavedTrace.Length() > 0) {
834 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
835 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
836 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
838 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
839 if ( !isNewVersion ) {
840 TCollection_AsciiString aSavedTrace( theSavedTrace );
841 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
842 int beg, end = aSavedTrace.Length(), from = 1;
843 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
844 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
845 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
846 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
849 from = beg + aSmeshCall.Length();
851 aScript += helper + "\n" + aSavedTrace;
854 // append a saved trace to the script
855 aScript += helper + "\n" + theSavedTrace;
858 // Dump trace of API methods calls
859 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
860 if (aNewLines.Length() > 0) {
861 aScript += helper + "\n" + aNewLines;
864 // Convert IDL API calls into smesh.py API.
865 // Some objects are wrapped with python classes and
866 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
867 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
868 if ( !getenv("NO_2smeshpy_conversion"))
869 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
870 theObjectNames, theStudy, isHistoricalDump );
872 // Replace characters used instead of quote marks to quote notebook variables
875 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
876 aScript.SetValue( pos, '"' );
879 // Find entries to be replaced by names
880 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
881 Standard_Integer aLen = aSeq->Length();
883 if (aLen == 0 && isMultiFile)
886 // Replace entries by the names
887 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
888 TColStd_SequenceOfAsciiString seqRemoved;
889 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
890 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
891 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
893 // Collect names of GEOM objects to exclude same names of SMESH objects
894 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
895 int ign = 0, nbgn = aGeomNames->length();
896 for (; ign < nbgn; ign++) {
897 aName = aGeomNames[ign];
898 theObjectNames.Bind(aName, "1");
901 bool importGeom = false;
902 for (Standard_Integer i = 1; i <= aLen; i += 2) {
903 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
904 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
906 aName = geom->GetDumpName( anEntry.ToCString() );
907 if (aName.IsEmpty()) {
909 if (theObjectNames.IsBound(anEntry)) {
910 // The Object is in Study
911 aName = theObjectNames.Find(anEntry);
912 // check validity of aName
913 bool isValidName = fixPythonName( aName );
914 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
915 // diff objects have same name - make a new name by appending a digit
916 TCollection_AsciiString aName2;
917 Standard_Integer i = 0;
919 aName2 = aName + "_" + ++i;
920 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
925 theObjectNames(anEntry) = aName;
930 aName = aBaseName + (++objectCounter);
931 } while (theObjectNames.IsBound(aName));
932 seqRemoved.Append(aName);
933 mapRemoved.Bind(anEntry, "1");
934 theObjectNames.Bind(anEntry, aName);
936 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
942 anUpdatedScript += aName;
943 aStart = aSeq->Value(i + 1) + 1;
946 // set initial part of aSript
947 TCollection_AsciiString initPart = "import ";
949 initPart += helper + "salome, ";
950 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
951 if ( importGeom && isMultiFile )
953 initPart += ("\n## import GEOM dump file ## \n"
954 "import string, os, sys, re\n"
955 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
956 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
958 anUpdatedScript.Insert ( 1, initPart );
960 // add final part of aScript
961 if (aLen && aSeq->Value(aLen) < aScriptLength)
962 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
964 // Remove removed objects
965 if ( seqRemoved.Length() > 0 ) {
966 anUpdatedScript += "\n\t## some objects were removed";
967 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
969 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
970 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
971 anUpdatedScript += seqRemoved.Value(ir);
972 // for object wrapped by class of smesh.py
973 anEntry = theObjectNames( seqRemoved.Value(ir) );
974 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
975 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
976 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
980 anUpdatedScript += "\n\t## set object names";
981 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
982 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
983 // anUpdatedScript += "\n";
985 TCollection_AsciiString aGUIName;
986 Resource_DataMapOfAsciiStringAsciiString mapEntries;
987 for (Standard_Integer i = 1; i <= aLen; i += 2)
989 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
990 aName = geom->GetDumpName( anEntry.ToCString() );
991 if (aName.IsEmpty() && // Not a GEOM object
992 theNames.IsBound(anEntry) &&
993 !mapEntries.IsBound(anEntry) && // Not yet processed
994 !mapRemoved.IsBound(anEntry)) // Was not removed
996 aName = theObjectNames.Find(anEntry);
997 aGUIName = theNames.Find(anEntry);
998 mapEntries.Bind(anEntry, aName);
999 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1000 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1001 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1002 anUpdatedScript += helper + ", '" + aGUIName + "')";
1006 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
1007 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
1008 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
1010 // -----------------------------------------------------------------
1011 // store visual properties of displayed objects
1012 // -----------------------------------------------------------------
1016 //Output the script that sets up the visual parameters.
1017 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
1018 if (script && strlen(script) > 0) {
1019 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1020 anUpdatedScript += script;
1021 CORBA::string_free(script);
1026 anUpdatedScript += "\n\tpass";
1027 anUpdatedScript += "\n";
1029 if( !isMultiFile ) // remove unnecessary tabulation
1030 RemoveTabulation( anUpdatedScript );
1032 // -----------------------------------------------------------------
1033 // put string literals describing patterns into separate functions
1034 // -----------------------------------------------------------------
1036 TCollection_AsciiString aLongString, aFunctionType;
1038 set< string > functionNameSet;
1039 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1041 // make a python string literal
1042 aLongString.Prepend(":\n\treturn '''\n");
1043 aLongString += "\n\t'''\n\tpass\n";
1045 TCollection_AsciiString functionName;
1047 // check if the function returning this literal is already defined
1048 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1049 if ( posAlready ) // already defined
1051 // find the function name
1052 int functBeg = posAlready;
1053 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1054 while ( *script != ' ' ) {
1058 functBeg++; // do not take ' '
1059 posAlready--; // do not take ':'
1060 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1062 else // not defined yet
1064 // find a unique function name
1065 fixPythonName( aFunctionType );
1066 Standard_Integer nb = 0;
1067 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1068 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1071 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1074 anUpdatedScript += helper + "\n\n" + funDef;
1079 anUpdatedScript.Insert( 1, funDef);
1080 where += funDef.Length();
1083 anUpdatedScript.InsertBefore( where, functionName ); // call function
1086 aValidScript = true;
1088 return anUpdatedScript;
1091 //=============================================================================
1095 //=============================================================================
1096 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1098 TCollection_AsciiString aScript;
1100 // Dump trace of API methods calls
1101 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1102 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1103 Standard_Integer istr, aLen = aPythonScript->Length();
1104 for (istr = 1; istr <= aLen; istr++) {
1106 aScript += aPythonScript->Value(istr);
1114 //=============================================================================
1118 //=============================================================================
1119 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1121 TCollection_AsciiString aScript;
1123 // Clean trace of API methods calls
1124 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1125 myPythonScripts[theStudyID]->Clear();