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 if ( theVarValue.myVals.empty() ) return *this;
90 const std::vector< std::string >& varNames = SMESH_Gen_i::GetSMESHGen()->GetLastParameters();
91 if ( theVarValue.myVals.size() > 1 )
94 for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
96 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
97 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
99 myStream << theVarValue.myVals[i-1];
100 if ( i < theVarValue.myVals.size() )
108 if ( myVarsCounter < varNames.size() && !varNames[ myVarsCounter ].empty() )
109 myStream << TVar::Quote() << varNames[ myVarsCounter ] << TVar::Quote();
111 myStream << theVarValue.myVals[0];
119 operator<<(long int theArg){
126 operator<<(int theArg){
133 operator<<(double theArg){
140 operator<<(float theArg){
147 operator<<(const void* theArg){
154 operator<<(const char* theArg){
162 operator<<(const SMESH::ElementType& theArg)
166 case ALL: myStream<<"ALL"; break;
167 case NODE: myStream<<"NODE"; break;
168 case EDGE: myStream<<"EDGE"; break;
169 case FACE: myStream<<"FACE"; break;
170 case VOLUME: myStream<<"VOLUME"; break;
171 case ELEM0D: myStream<<"ELEM0D"; break;
172 case BALL: myStream<<"BALL"; break;
173 default: myStream<<"__UNKNOWN__ElementType: " << theArg;
180 operator<<(const SMESH::GeometryType& theArg)
184 case Geom_POINT: myStream<<"Geom_POINT"; break;
185 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
186 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
187 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
188 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
189 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
190 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
191 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
192 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
193 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
194 case Geom_BALL: myStream<<"Geom_BALL"; break;
195 default: myStream<<"__UNKNOWN__GeometryType: " << theArg;
200 template<class TArray>
201 void DumpArray(const TArray& theArray, TPythonDump & theStream)
204 for (int i = 1; i <= theArray.length(); i++) {
205 theStream << theArray[i-1];
206 if ( i < theArray.length() )
213 TPythonDump::operator<<(const SMESH::long_array& theArg)
215 DumpArray( theArg, *this );
220 TPythonDump::operator<<(const SMESH::double_array& theArg)
222 DumpArray( theArg, *this );
227 TPythonDump::operator<<(const SMESH::string_array& theArray)
230 for (int i = 1; i <= theArray.length(); i++) {
231 myStream << "'" << theArray[i-1] << "'";
232 if ( i < theArray.length() )
241 operator<<(SALOMEDS::SObject_ptr aSObject)
243 if ( !aSObject->_is_nil() )
244 myStream << aSObject->GetID();
246 myStream << NotPublishedObjectName();
252 operator<<(CORBA::Object_ptr theArg)
254 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
255 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
256 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
257 if(!aSObject->_is_nil()) {
258 CORBA::String_var id = aSObject->GetID();
260 } else if ( !CORBA::is_nil(theArg)) {
261 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
262 myStream << "smeshObj_" << size_t(theArg);
264 myStream << NotPublishedObjectName();
273 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
275 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
276 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
277 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
278 myStream << "hyp_" << theArg->GetId();
280 *this << CORBA::Object_ptr( theArg );
286 operator<<(SMESH::SMESH_IDSource_ptr theArg)
288 if ( CORBA::is_nil( theArg ) )
289 return *this << "None";
290 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
291 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
292 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
293 if(!aSObject->_is_nil())
294 return *this << aSObject;
295 if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
296 return *this << filter;
297 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
298 if ( !theArg->_is_equivalent( mesh ))
300 SMESH::long_array_var anElementsId = theArg->GetIDs();
301 SMESH::array_of_ElementType_var types = theArg->GetTypes();
302 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
303 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
310 operator<<(SMESH::FilterLibrary_i* theArg)
312 myStream<<"aFilterLibrary"<<theArg;
318 operator<<(SMESH::FilterManager_i* theArg)
320 myStream<<"aFilterManager";
326 operator<<(SMESH::Filter_i* theArg)
328 myStream<<"aFilter"<<theArg;
334 operator<<(SMESH::Functor_i* theArg)
337 FunctorType aFunctorType = theArg->GetFunctorType();
338 switch(aFunctorType){
339 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
340 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
341 case FT_Warping: myStream<< "aWarping"; break;
342 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
343 case FT_Taper: myStream<< "aTaper"; break;
344 case FT_Skew: myStream<< "aSkew"; break;
345 case FT_Area: myStream<< "aArea"; break;
346 case FT_Volume3D: myStream<< "aVolume3D"; break;
347 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
348 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
349 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
350 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
351 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
352 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
353 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
354 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
355 case FT_Length: myStream<< "aLength"; break;
356 case FT_Length2D: myStream<< "aLength2D"; break;
357 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
358 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
359 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
360 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
361 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
362 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
363 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
364 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
365 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
366 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
367 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
368 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
369 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
370 case FT_GroupColor: myStream<< "aGroupColor"; break;
371 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
372 case FT_LessThan: myStream<< "aLessThan"; break;
373 case FT_MoreThan: myStream<< "aMoreThan"; break;
374 case FT_EqualTo: myStream<< "anEqualTo"; break;
375 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
376 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
377 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
379 default: myStream<< "anUndefined"; break;
388 operator<<(SMESH::Measurements_i* theArg)
390 myStream<<"aMeasurements";
395 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
397 myStream << SMESHGenName(); return *this;
400 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
402 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
405 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
407 myStream << theStr; return *this;
411 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
413 switch (theVersion) {
414 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
415 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
416 default: myStream << theVersion;
421 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
423 *this << "SMESH.AxisStruct( "
424 << TVar( theAxis.x ) << ", "
425 << TVar( theAxis.y ) << ", "
426 << TVar( theAxis.z ) << ", "
427 << TVar( theAxis.vx ) << ", "
428 << TVar( theAxis.vy ) << ", "
429 << TVar( theAxis.vz ) << " )";
433 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
435 const SMESH::PointStruct & P = theDir.PS;
436 *this << "SMESH.DirStruct( SMESH.PointStruct ( "
437 << TVar( P.x ) << ", "
438 << TVar( P.y ) << ", "
439 << TVar( P.z ) << " ))";
443 TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
445 *this << "SMESH.PointStruct ( "
446 << TVar( P.x ) << ", "
447 << TVar( P.y ) << ", "
448 << TVar( P.z ) << " )";
452 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
454 DumpArray( theList, *this );
457 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
459 DumpArray( *theList, *this );
462 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
464 DumpArray( theList, *this );
468 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
469 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
471 //================================================================================
473 * \brief Return marker of long string literal beginning
474 * \param type - a name of functionality producing the string literal
475 * \retval TCollection_AsciiString - the marker string to be written into
476 * a raw python script
478 //================================================================================
480 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
484 (Standard_Integer) strlen(type) +
489 //================================================================================
491 * \brief Return marker of long string literal end
492 * \retval TCollection_AsciiString - the marker string to be written into
493 * a raw python script
495 //================================================================================
497 TCollection_AsciiString TPythonDump::LongStringEnd()
499 return myLongStringEnd;
502 //================================================================================
504 * \brief Cut out a long string literal from a string
505 * \param theText - text possibly containing string literals
506 * \param theFrom - position in the text to search from
507 * \param theLongString - the retrieved literal
508 * \param theStringType - a name of functionality produced the literal
509 * \retval bool - true if a string literal found
511 * The literal is removed from theText; theFrom points position right after
512 * the removed literal
514 //================================================================================
516 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
518 TCollection_AsciiString & theLongString,
519 TCollection_AsciiString & theStringType)
521 if ( theFrom < 1 || theFrom > theText.Length() )
524 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
525 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
526 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
529 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
533 // find where literal begins
534 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
535 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
536 int typeLen = atoi ( typeLenStr ); // = 7
537 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
538 literalBeg++; // 26 -> 27
541 literalBeg += typeLen + 1; // = 35
542 if ( literalBeg > theText.Length() )
545 // where literal ends (i.e. end marker begins)
546 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
548 literalEnd = theText.Length();
551 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
553 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
555 literalEnd += myLongStringEnd.Length(); // = 79
556 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
557 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
563 //=======================================================================
564 //function : RemoveTabulation
566 //=======================================================================
567 void RemoveTabulation( TCollection_AsciiString& theScript )
569 std::string aString( theScript.ToCString() );
570 std::string::size_type aPos = 0;
571 while( aPos < aString.length() )
573 aPos = aString.find( "\n\t", aPos );
574 if( aPos == std::string::npos )
576 aString.replace( aPos, 2, "\n" );
579 theScript = aString.c_str();
582 //=======================================================================
583 //function : DumpPython
585 //=======================================================================
586 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
587 CORBA::Boolean isPublished,
588 CORBA::Boolean isMultiFile,
589 CORBA::Boolean& isValidScript)
591 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
592 if (CORBA::is_nil(aStudy))
593 return new Engines::TMPFile(0);
595 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
596 if (CORBA::is_nil(aSO))
597 return new Engines::TMPFile(0);
599 // Map study entries to object names
600 Resource_DataMapOfAsciiStringAsciiString aMap;
601 Resource_DataMapOfAsciiStringAsciiString aMapNames;
602 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
604 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
605 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
606 SALOMEDS::SObject_var aValue = Itr->Value();
607 CORBA::String_var anID = aValue->GetID();
608 CORBA::String_var aName = aValue->GetName();
609 TCollection_AsciiString aGUIName ( (char*) aName.in() );
610 TCollection_AsciiString anEnrty ( (char*) anID.in() );
611 if (aGUIName.Length() > 0) {
612 aMapNames.Bind( anEnrty, aGUIName );
613 aMap.Bind( anEnrty, aGUIName );
617 // Get trace of restored study
618 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
619 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
620 SALOMEDS::GenericAttribute_var anAttr =
621 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
623 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
624 TCollection_AsciiString aSavedTrace (oldValue);
626 // Add trace of API methods calls and replace study entries by names
627 TCollection_AsciiString aScript;
628 aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
629 myIsHistoricalPythonDump, isValidScript, aSavedTrace);
631 int aLen = aScript.Length();
632 unsigned char* aBuffer = new unsigned char[aLen+1];
633 strcpy((char*)aBuffer, aScript.ToCString());
635 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
636 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
638 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
639 isValidScript = isValidScript && !hasNotPublishedObjects;
641 return aStreamFile._retn();
644 //=============================================================================
648 //=============================================================================
649 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
651 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
652 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
654 myPythonScripts[theStudyID]->Append(theString);
657 //=============================================================================
659 * RemoveLastFromPythonScript
661 //=============================================================================
662 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
664 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
665 int aLen = myPythonScripts[theStudyID]->Length();
666 myPythonScripts[theStudyID]->Remove(aLen);
670 //=======================================================================
671 //function : SavePython
673 //=======================================================================
674 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
676 // Dump trace of API methods calls
677 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
679 // Check contents of PythonObject attribute
680 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
681 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
682 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
683 SALOMEDS::GenericAttribute_var anAttr =
684 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
686 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
687 TCollection_AsciiString oldScript (oldValue);
689 if (oldScript.Length() > 0) {
691 oldScript += aScript;
696 // Store in PythonObject attribute
697 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
699 // Clean trace of API methods calls
700 CleanPythonTrace(theStudy->StudyId());
707 //=============================================================================
709 * FindEntries: Returns a sequence of start/end positions of entries in the string
711 //=============================================================================
712 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
714 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
715 Standard_Integer aLen = theString.Length();
716 Standard_Boolean isFound = Standard_False;
718 char* arr = (char*) theString.ToCString();
719 Standard_Integer i = 0, j;
724 if ( isdigit( c )) { //Is digit?
726 isFound = Standard_False;
727 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
729 if(c == ':') isFound = Standard_True;
733 int prev = (i < 1) ? 0 : (int)arr[i - 1];
734 // to distinguish from a sketcher command:
735 // last char should be a digit, not ":",
736 // previous char should not be '"'.
737 if (arr[j-2] != ':' && prev != '"') {
738 aSeq->Append(i+1); // +1 because AsciiString starts from 1
752 //================================================================================
754 * \brief Make a string be a valid python name
755 * \param aName - a string to fix
756 * \retval bool - true if aName was not modified
758 //================================================================================
760 bool fixPythonName(TCollection_AsciiString & aName )
762 const TCollection_AsciiString allowedChars =
763 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
764 bool isValidName = true;
765 int nbUnderscore = 0;
766 int p=1; // replace not allowed chars by underscore
767 while (p <= aName.Length() &&
768 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
770 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
771 aName.Remove( p, 1 ); // remove double _ from the start and the end
773 aName.SetValue(p, '_'), nbUnderscore++;
776 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
777 aName.Insert( 1, 'a' );
780 // shorten names like CartesianParameters3D_400_400_400_1000000_1
781 if ( aName.Length() > 20 && nbUnderscore > 2 )
783 p = aName.Location( "_", 20, aName.Length());
791 //=============================================================================
795 //=============================================================================
796 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
797 (SALOMEDS::Study_ptr theStudy,
798 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
799 Resource_DataMapOfAsciiStringAsciiString& theNames,
802 bool isHistoricalDump,
804 const TCollection_AsciiString& theSavedTrace)
806 int aStudyID = theStudy->StudyId();
808 TCollection_AsciiString helper; // to comfortably concatenate C strings
809 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
810 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
811 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
813 TCollection_AsciiString aScript;
815 aScript += "def RebuildData(theStudy):";
817 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
818 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
820 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
822 aScript += aSMESHGen + ".SetCurrentStudy(None)";
824 // import python files corresponding to plugins
825 set<string> moduleNameSet;
826 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
827 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
828 string moduleName = hyp_creator->second->GetModuleName();
829 bool newModule = moduleNameSet.insert( moduleName ).second;
831 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
834 // Dump trace of restored study
835 if (theSavedTrace.Length() > 0) {
836 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
837 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
838 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
840 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
841 if ( !isNewVersion ) {
842 TCollection_AsciiString aSavedTrace( theSavedTrace );
843 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
844 int beg, end = aSavedTrace.Length(), from = 1;
845 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
846 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
847 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
848 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
851 from = beg + aSmeshCall.Length();
853 aScript += helper + "\n" + aSavedTrace;
856 // append a saved trace to the script
857 aScript += helper + "\n" + theSavedTrace;
860 // Dump trace of API methods calls
861 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
862 if (aNewLines.Length() > 0) {
863 aScript += helper + "\n" + aNewLines;
866 // Convert IDL API calls into smesh.py API.
867 // Some objects are wrapped with python classes and
868 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
869 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
870 if ( !getenv("NO_2smeshpy_conversion"))
871 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod,
872 theObjectNames, theStudy, isHistoricalDump );
874 // Replace characters used instead of quote marks to quote notebook variables
877 while (( pos = aScript.Location( 1, SMESH::TVar::Quote(), pos, aScript.Length() )))
878 aScript.SetValue( pos, '"' );
881 // Find entries to be replaced by names
882 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
883 Standard_Integer aLen = aSeq->Length();
885 if (aLen == 0 && isMultiFile)
888 // Replace entries by the names
889 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
890 TColStd_SequenceOfAsciiString seqRemoved;
891 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
892 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
893 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
895 // Collect names of GEOM objects to exclude same names of SMESH objects
896 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
897 int ign = 0, nbgn = aGeomNames->length();
898 for (; ign < nbgn; ign++) {
899 aName = aGeomNames[ign];
900 theObjectNames.Bind(aName, "1");
903 bool importGeom = false;
904 for (Standard_Integer i = 1; i <= aLen; i += 2) {
905 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
906 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
908 aName = geom->GetDumpName( anEntry.ToCString() );
909 if (aName.IsEmpty()) {
911 if (theObjectNames.IsBound(anEntry)) {
912 // The Object is in Study
913 aName = theObjectNames.Find(anEntry);
914 // check validity of aName
915 bool isValidName = fixPythonName( aName );
916 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
917 // diff objects have same name - make a new name by appending a digit
918 TCollection_AsciiString aName2;
919 Standard_Integer i = 0;
921 aName2 = aName + "_" + ++i;
922 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
927 theObjectNames(anEntry) = aName;
932 aName = aBaseName + (++objectCounter);
933 } while (theObjectNames.IsBound(aName));
934 seqRemoved.Append(aName);
935 mapRemoved.Bind(anEntry, "1");
936 theObjectNames.Bind(anEntry, aName);
938 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
944 anUpdatedScript += aName;
945 aStart = aSeq->Value(i + 1) + 1;
948 // set initial part of aSript
949 TCollection_AsciiString initPart = "import ";
951 initPart += helper + "salome, ";
952 initPart += aSmeshpy + ", SMESH, SALOMEDS\n";
953 if ( importGeom && isMultiFile )
955 initPart += ("\n## import GEOM dump file ## \n"
956 "import string, os, sys, re\n"
957 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
958 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n");
960 anUpdatedScript.Insert ( 1, initPart );
962 // add final part of aScript
963 if (aLen && aSeq->Value(aLen) < aScriptLength)
964 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
966 // Remove removed objects
967 if ( seqRemoved.Length() > 0 ) {
968 anUpdatedScript += "\n\t## some objects were removed";
969 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
971 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
972 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
973 anUpdatedScript += seqRemoved.Value(ir);
974 // for object wrapped by class of smesh.py
975 anEntry = theObjectNames( seqRemoved.Value(ir) );
976 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
977 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
978 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
982 anUpdatedScript += "\n\t## set object names";
983 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
984 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
985 // anUpdatedScript += "\n";
987 TCollection_AsciiString aGUIName;
988 Resource_DataMapOfAsciiStringAsciiString mapEntries;
989 for (Standard_Integer i = 1; i <= aLen; i += 2)
991 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
992 aName = geom->GetDumpName( anEntry.ToCString() );
993 if (aName.IsEmpty() && // Not a GEOM object
994 theNames.IsBound(anEntry) &&
995 !mapEntries.IsBound(anEntry) && // Not yet processed
996 !mapRemoved.IsBound(anEntry)) // Was not removed
998 aName = theObjectNames.Find(anEntry);
999 aGUIName = theNames.Find(anEntry);
1000 mapEntries.Bind(anEntry, aName);
1001 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
1002 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1003 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
1004 anUpdatedScript += helper + ", '" + aGUIName + "')";
1008 // Issue 0021249: removed (a similar block is dumped by SALOMEDSImpl_Study)
1009 //anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
1010 //anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
1012 // -----------------------------------------------------------------
1013 // store visual properties of displayed objects
1014 // -----------------------------------------------------------------
1018 //Output the script that sets up the visual parameters.
1019 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
1020 if (script && strlen(script) > 0) {
1021 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
1022 anUpdatedScript += script;
1023 CORBA::string_free(script);
1028 anUpdatedScript += "\n\tpass";
1029 anUpdatedScript += "\n";
1031 if( !isMultiFile ) // remove unnecessary tabulation
1032 RemoveTabulation( anUpdatedScript );
1034 // -----------------------------------------------------------------
1035 // put string literals describing patterns into separate functions
1036 // -----------------------------------------------------------------
1038 TCollection_AsciiString aLongString, aFunctionType;
1040 set< string > functionNameSet;
1041 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1043 // make a python string literal
1044 aLongString.Prepend(":\n\treturn '''\n");
1045 aLongString += "\n\t'''\n\tpass\n";
1047 TCollection_AsciiString functionName;
1049 // check if the function returning this literal is already defined
1050 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1051 if ( posAlready ) // already defined
1053 // find the function name
1054 int functBeg = posAlready;
1055 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1056 while ( *script != ' ' ) {
1060 functBeg++; // do not take ' '
1061 posAlready--; // do not take ':'
1062 functionName = anUpdatedScript.SubString( functBeg, posAlready );
1064 else // not defined yet
1066 // find a unique function name
1067 fixPythonName( aFunctionType );
1068 Standard_Integer nb = 0;
1069 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1070 while ( !functionNameSet.insert( functionName.ToCString() ).second );
1073 TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1076 anUpdatedScript += helper + "\n\n" + funDef;
1081 anUpdatedScript.Insert( 1, funDef);
1082 where += funDef.Length();
1085 anUpdatedScript.InsertBefore( where, functionName ); // call function
1088 aValidScript = true;
1090 return anUpdatedScript;
1093 //=============================================================================
1097 //=============================================================================
1098 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1100 TCollection_AsciiString aScript;
1102 // Dump trace of API methods calls
1103 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1104 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1105 Standard_Integer istr, aLen = aPythonScript->Length();
1106 for (istr = 1; istr <= aLen; istr++) {
1108 aScript += aPythonScript->Value(istr);
1116 //=============================================================================
1120 //=============================================================================
1121 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1123 TCollection_AsciiString aScript;
1125 // Clean trace of API methods calls
1126 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1127 myPythonScripts[theStudyID]->Clear();