1 // Copyright (C) 2007-2010 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
23 // File : SMESH_Gen_i_DumpPython.cxx
24 // Created : Thu Mar 24 17:17:59 2005
25 // Author : Julia DOROVSKIKH
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_Gen_i.hxx"
31 #include "SMESH_Filter_i.hxx"
32 #include "SMESH_MeshEditor_i.hxx"
33 #include "SMESH_2smeshpy.hxx"
35 #include <TColStd_HSequenceOfInteger.hxx>
36 #include <TCollection_AsciiString.hxx>
37 #include <SMESH_Comment.hxx>
41 static int MYDEBUG = 0;
43 static int MYDEBUG = 0;
46 static TCollection_AsciiString NotPublishedObjectName()
48 return "__NOT__Published__Object__";
54 size_t TPythonDump::myCounter = 0;
65 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
66 std::string aString = myStream.str();
67 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
68 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
69 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
70 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
71 if(MYDEBUG) MESSAGE(aString);
78 operator<<(long int theArg){
85 operator<<(int theArg){
92 operator<<(double theArg){
99 operator<<(float theArg){
106 operator<<(const void* theArg){
113 operator<<(const char* theArg){
121 operator<<(const SMESH::ElementType& theArg)
125 case ALL: myStream<<"ALL";break;
126 case NODE: myStream<<"NODE";break;
127 case EDGE: myStream<<"EDGE";break;
128 case FACE: myStream<<"FACE";break;
129 case VOLUME:myStream<<"VOLUME";break;
136 operator<<(const SMESH::GeometryType& theArg)
140 case Geom_POINT: myStream<<"Geom_POINT"; break;
141 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
142 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
143 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
144 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
145 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
146 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
147 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
148 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
149 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
154 template<class TArray>
155 void DumpArray(const TArray& theArray, TPythonDump & theStream)
158 for (int i = 1; i <= theArray.length(); i++) {
159 theStream << theArray[i-1];
160 if ( i < theArray.length() )
167 TPythonDump::operator<<(const SMESH::long_array& theArg)
169 DumpArray( theArg, *this );
174 TPythonDump::operator<<(const SMESH::double_array& theArg)
176 DumpArray( theArg, *this );
182 operator<<(SALOMEDS::SObject_ptr aSObject)
184 if ( !aSObject->_is_nil() )
185 myStream << aSObject->GetID();
187 myStream << NotPublishedObjectName();
193 operator<<(CORBA::Object_ptr theArg)
195 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
196 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
197 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
198 if(!aSObject->_is_nil()) {
199 CORBA::String_var id = aSObject->GetID();
201 } else if ( !CORBA::is_nil(theArg)) {
202 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
203 myStream << "smeshObj_" << size_t(theArg);
205 myStream << NotPublishedObjectName();
214 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
216 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
217 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
218 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
219 myStream << "hyp_" << theArg->GetId();
221 *this << CORBA::Object_ptr( theArg );
227 operator<<(SMESH::SMESH_IDSource_ptr theArg)
229 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
230 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
231 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
232 if(!aSObject->_is_nil() || CORBA::is_nil( theArg ))
233 return *this << aSObject;
234 SMESH::long_array_var anElementsId = theArg->GetIDs();
235 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
236 SMESH::array_of_ElementType_var types = theArg->GetTypes();
237 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
238 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
243 operator<<(SMESH::FilterLibrary_i* theArg)
245 myStream<<"aFilterLibrary"<<theArg;
251 operator<<(SMESH::FilterManager_i* theArg)
253 myStream<<"aFilterManager";
259 operator<<(SMESH::Filter_i* theArg)
261 myStream<<"aFilter"<<theArg;
267 operator<<(SMESH::Functor_i* theArg)
270 FunctorType aFunctorType = theArg->GetFunctorType();
271 switch(aFunctorType){
272 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
273 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
274 case FT_Warping: myStream<< "aWarping"; break;
275 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
276 case FT_Taper: myStream<< "aTaper"; break;
277 case FT_Skew: myStream<< "aSkew"; break;
278 case FT_Area: myStream<< "aArea"; break;
279 case FT_Volume3D: myStream<< "aVolume3D"; break;
280 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
281 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
282 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
283 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
284 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
285 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
286 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
287 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
288 case FT_Length: myStream<< "aLength"; break;
289 case FT_Length2D: myStream<< "aLength2D"; break;
290 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
291 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
292 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
293 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
294 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
295 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
296 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
297 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
298 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
299 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
300 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
301 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
302 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
303 case FT_GroupColor: myStream<< "aGroupColor"; break;
304 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
305 case FT_LessThan: myStream<< "aLessThan"; break;
306 case FT_MoreThan: myStream<< "aMoreThan"; break;
307 case FT_EqualTo: myStream<< "anEqualTo"; break;
308 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
309 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
310 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
312 default: myStream<< "anUndefined"; break;
321 operator<<(SMESH::Measurements_i* theArg)
323 myStream<<"aMeasurements";
328 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
330 myStream << SMESHGenName(); return *this;
333 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
335 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
338 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
340 myStream << theStr; return *this;
344 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
346 switch (theVersion) {
347 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
348 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
349 default: myStream << theVersion;
354 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
356 myStream << "SMESH.AxisStruct( "
360 << theAxis.vx << ", "
361 << theAxis.vy << ", "
362 << theAxis.vz << " )";
366 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
368 const SMESH::PointStruct & P = theDir.PS;
369 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
376 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
378 DumpArray( theList, *this );
381 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
383 DumpArray( theList, *this );
387 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
388 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
390 //================================================================================
392 * \brief Return marker of long string literal beginning
393 * \param type - a name of functionality producing the string literal
394 * \retval TCollection_AsciiString - the marker string to be written into
395 * a raw python script
397 //================================================================================
399 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
403 (Standard_Integer) strlen(type) +
408 //================================================================================
410 * \brief Return marker of long string literal end
411 * \retval TCollection_AsciiString - the marker string to be written into
412 * a raw python script
414 //================================================================================
416 TCollection_AsciiString TPythonDump::LongStringEnd()
418 return myLongStringEnd;
421 //================================================================================
423 * \brief Cut out a long string literal from a string
424 * \param theText - text possibly containing string literals
425 * \param theFrom - position in the text to search from
426 * \param theLongString - the retrieved literal
427 * \param theStringType - a name of functionality produced the literal
428 * \retval bool - true if a string literal found
430 * The literal is removed from theText; theFrom points position right after
431 * the removed literal
433 //================================================================================
435 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
437 TCollection_AsciiString & theLongString,
438 TCollection_AsciiString & theStringType)
440 if ( theFrom < 1 || theFrom > theText.Length() )
443 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
444 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
445 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
448 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
452 // find where literal begins
453 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
454 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
455 int typeLen = atoi ( typeLenStr ); // = 7
456 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
457 literalBeg++; // 26 -> 27
460 literalBeg += typeLen + 1; // = 35
461 if ( literalBeg > theText.Length() )
464 // where literal ends (i.e. end marker begins)
465 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
467 literalEnd = theText.Length();
470 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
472 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
474 literalEnd += myLongStringEnd.Length(); // = 79
475 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
476 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
482 //=======================================================================
483 //function : DumpPython
485 //=======================================================================
486 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
487 CORBA::Boolean isPublished,
488 CORBA::Boolean& isValidScript)
490 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
491 if (CORBA::is_nil(aStudy))
492 return new Engines::TMPFile(0);
494 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
495 if (CORBA::is_nil(aSO))
496 return new Engines::TMPFile(0);
498 // Map study entries to object names
499 Resource_DataMapOfAsciiStringAsciiString aMap;
500 Resource_DataMapOfAsciiStringAsciiString aMapNames;
501 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
503 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
504 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
505 SALOMEDS::SObject_var aValue = Itr->Value();
506 CORBA::String_var anID = aValue->GetID();
507 CORBA::String_var aName = aValue->GetName();
508 TCollection_AsciiString aGUIName ( (char*) aName.in() );
509 TCollection_AsciiString anEnrty ( (char*) anID.in() );
510 if (aGUIName.Length() > 0) {
511 aMapNames.Bind( anEnrty, aGUIName );
512 aMap.Bind( anEnrty, aGUIName );
516 // Get trace of restored study
517 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
518 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
519 SALOMEDS::GenericAttribute_var anAttr =
520 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
522 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
523 TCollection_AsciiString aSavedTrace (oldValue);
525 // Add trace of API methods calls and replace study entries by names
526 TCollection_AsciiString aScript;
527 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
528 isPublished, isValidScript, aSavedTrace);
530 int aLen = aScript.Length();
531 unsigned char* aBuffer = new unsigned char[aLen+1];
532 strcpy((char*)aBuffer, aScript.ToCString());
534 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
535 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
537 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
538 isValidScript = isValidScript && !hasNotPublishedObjects;
540 return aStreamFile._retn();
543 //=============================================================================
547 //=============================================================================
548 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
550 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
551 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
553 myPythonScripts[theStudyID]->Append(theString);
556 //=============================================================================
558 * RemoveLastFromPythonScript
560 //=============================================================================
561 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
563 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
564 int aLen = myPythonScripts[theStudyID]->Length();
565 myPythonScripts[theStudyID]->Remove(aLen);
569 //=======================================================================
570 //function : SavePython
572 //=======================================================================
573 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
575 // Dump trace of API methods calls
576 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
578 // Check contents of PythonObject attribute
579 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
580 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
581 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
582 SALOMEDS::GenericAttribute_var anAttr =
583 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
585 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
586 TCollection_AsciiString oldScript (oldValue);
588 if (oldScript.Length() > 0) {
590 oldScript += aScript;
595 // Store in PythonObject attribute
596 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
598 // Clean trace of API methods calls
599 CleanPythonTrace(theStudy->StudyId());
606 //=============================================================================
608 * FindEntries: Returns a sequence of start/end positions of entries in the string
610 //=============================================================================
611 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
613 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
614 Standard_Integer aLen = theString.Length();
615 Standard_Boolean isFound = Standard_False;
617 char* arr = (char*) theString.ToCString();
618 Standard_Integer i = 0, j;
623 if ( isdigit( c )) { //Is digit?
625 isFound = Standard_False;
626 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
628 if(c == ':') isFound = Standard_True;
632 int prev = (i < 1) ? 0 : (int)arr[i - 1];
633 // to distinguish from a sketcher command:
634 // last char should be a digit, not ":",
635 // previous char should not be '"'.
636 if (arr[j-2] != ':' && prev != '"') {
637 aSeq->Append(i+1); // +1 because AsciiString starts from 1
651 //================================================================================
653 * \brief Make a string be a valid python name
654 * \param aName - a string to fix
655 * \retval bool - true if aName was not modified
657 //================================================================================
659 bool fixPythonName(TCollection_AsciiString & aName )
661 const TCollection_AsciiString allowedChars =
662 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
663 bool isValidName = true;
664 int p=1; // replace not allowed chars with underscore
665 while (p <= aName.Length() &&
666 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
668 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
669 aName.Remove( p, 1 ); // remove double _ and from the start and the end
671 aName.SetValue(p, '_');
674 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
675 aName.Insert( 1, 'a' );
682 //=============================================================================
686 //=============================================================================
687 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
688 (SALOMEDS::Study_ptr theStudy,
689 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
690 Resource_DataMapOfAsciiStringAsciiString& theNames,
693 const TCollection_AsciiString& theSavedTrace)
695 int aStudyID = theStudy->StudyId();
697 TCollection_AsciiString helper; // to comfortably concatenate C strings
698 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
699 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
700 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
702 TCollection_AsciiString aScript;
703 aScript = "def RebuildData(theStudy):\n\t";
704 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
705 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
707 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
709 aScript += aSMESHGen + ".SetCurrentStudy(None)";
711 // import python files corresponding to plugins
712 set<string> moduleNameSet;
713 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
714 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
715 string moduleName = hyp_creator->second->GetModuleName();
716 bool newModule = moduleNameSet.insert( moduleName ).second;
718 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
721 // Dump trace of restored study
722 if (theSavedTrace.Length() > 0) {
723 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
724 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
725 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
727 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
728 if ( !isNewVersion ) {
729 TCollection_AsciiString aSavedTrace( theSavedTrace );
730 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
731 int beg, end = aSavedTrace.Length(), from = 1;
732 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
733 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
734 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
735 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
738 from = beg + aSmeshCall.Length();
740 aScript += helper + "\n" + aSavedTrace;
743 // append a saved trace to the script
744 aScript += helper + "\n" + theSavedTrace;
747 // Dump trace of API methods calls
748 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
749 if (aNewLines.Length() > 0) {
750 aScript += helper + "\n" + aNewLines;
753 // Convert IDL API calls into smesh.py API.
754 // Some objects are wrapped with python classes and
755 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
756 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
757 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod, theObjectNames );
759 // Find entries to be replaced by names
760 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
761 Standard_Integer aLen = aSeq->Length();
766 // Replace entries by the names
767 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
768 TColStd_SequenceOfAsciiString seqRemoved;
769 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
770 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
771 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
773 // Collect names of GEOM objects to exclude same names for SMESH objects
774 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
775 int ign = 0, nbgn = aGeomNames->length();
776 for (; ign < nbgn; ign++) {
777 aName = aGeomNames[ign];
778 theObjectNames.Bind(aName, "1");
781 bool importGeom = false;
782 for (Standard_Integer i = 1; i <= aLen; i += 2) {
783 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
784 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
786 aName = geom->GetDumpName( anEntry.ToCString() );
787 if (aName.IsEmpty()) {
789 if (theObjectNames.IsBound(anEntry)) {
790 // The Object is in Study
791 aName = theObjectNames.Find(anEntry);
792 // check validity of aName
793 bool isValidName = fixPythonName( aName );
794 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
795 // diff objects have same name - make a new name by appending a digit
796 TCollection_AsciiString aName2;
797 Standard_Integer i = 0;
799 aName2 = aName + "_" + ++i;
800 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
805 theObjectNames(anEntry) = aName;
810 aName = aBaseName + (++objectCounter);
811 } while (theObjectNames.IsBound(aName));
812 seqRemoved.Append(aName);
813 mapRemoved.Bind(anEntry, "1");
814 theObjectNames.Bind(anEntry, aName);
816 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
822 anUpdatedScript += aName;
823 aStart = aSeq->Value(i + 1) + 1;
826 // set initial part of aSript
827 TCollection_AsciiString initPart = "import salome, SMESH, SALOMEDS\n";
828 initPart += helper + "import " + aSmeshpy + "\n\n";
831 initPart += ("## import GEOM dump file ## \n"
832 "import string, os, sys, re\n"
833 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
834 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
836 anUpdatedScript.Insert ( 1, initPart );
838 // add final part of aScript
839 if (aSeq->Value(aLen) < aScriptLength)
840 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
843 SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
844 if( !CORBA::is_nil(aComp) )
846 SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
847 for( Itr->InitEx(true); Itr->More(); Itr->Next() )
849 SALOMEDS::SObject_var aSObj = Itr->Value();
850 SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
852 if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
854 CORBA::String_var anEntry = aSObj->GetID();
856 SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
858 SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
859 if( !CORBA::is_nil(aGroup) )
861 SALOMEDS::Color aColor = aGroup->GetColor();
862 if ( aColor.R >= 0 || aColor.G >= 0 || aColor.B >= 0 )
864 CORBA::String_var anEntry = aSObj->GetID();
865 anUpdatedScript += SMESH_Comment("\n\t")
866 << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
867 << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
873 // Remove removed objects
874 if ( seqRemoved.Length() > 0 ) {
875 anUpdatedScript += "\n\t## some objects were removed";
876 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
878 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
879 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
880 anUpdatedScript += seqRemoved.Value(ir);
881 // for object wrapped by class of smesh.py
882 anEntry = theObjectNames( seqRemoved.Value(ir) );
883 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
884 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
885 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
889 anUpdatedScript += "\n\t## set object names";
890 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
891 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
892 // anUpdatedScript += "\n";
894 TCollection_AsciiString aGUIName;
895 Resource_DataMapOfAsciiStringAsciiString mapEntries;
896 for (Standard_Integer i = 1; i <= aLen; i += 2)
898 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
899 aName = geom->GetDumpName( anEntry.ToCString() );
900 if (aName.IsEmpty() && // Not a GEOM object
901 theNames.IsBound(anEntry) &&
902 !mapEntries.IsBound(anEntry) && // Not yet processed
903 !mapRemoved.IsBound(anEntry)) // Was not removed
905 aName = theObjectNames.Find(anEntry);
906 aGUIName = theNames.Find(anEntry);
907 mapEntries.Bind(anEntry, aName);
908 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
909 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
910 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
911 anUpdatedScript += helper + ", '" + aGUIName + "')";
914 anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
915 anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
917 // -----------------------------------------------------------------
918 // store visual properties of displayed objects
919 // -----------------------------------------------------------------
923 //Output the script that sets up the visual parameters.
924 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
925 if (script && strlen(script) > 0) {
926 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
927 anUpdatedScript += script;
928 CORBA::string_free(script);
931 anUpdatedScript += "\n\n\tpass\n";
933 // -----------------------------------------------------------------
934 // put string literals describing patterns into separate functions
935 // -----------------------------------------------------------------
937 TCollection_AsciiString aLongString, aFunctionType;
939 set< string > functionNameSet;
940 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
942 // make a python string literal
943 aLongString.Prepend(":\n\treturn '''\n");
944 aLongString += "\n\t'''\n\tpass\n";
946 TCollection_AsciiString functionName;
948 // check if the function returning this literal is already defined
949 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
950 if ( posAlready ) // already defined
952 // find the function name
953 int functBeg = posAlready;
954 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
955 while ( *script != ' ' ) {
959 functBeg++; // do not take ' '
960 posAlready--; // do not take ':'
961 functionName = anUpdatedScript.SubString( functBeg, posAlready );
963 else // not defined yet
965 // find a unique function name
966 fixPythonName( aFunctionType );
967 Standard_Integer nb = 0;
968 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
969 while ( !functionNameSet.insert( functionName.ToCString() ).second );
971 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
973 anUpdatedScript.InsertBefore( where, functionName ); // call function
978 return anUpdatedScript;
981 //=============================================================================
985 //=============================================================================
986 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
988 TCollection_AsciiString aScript;
990 // Dump trace of API methods calls
991 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
992 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
993 Standard_Integer istr, aLen = aPythonScript->Length();
994 for (istr = 1; istr <= aLen; istr++) {
996 aScript += aPythonScript->Value(istr);
1004 //=============================================================================
1008 //=============================================================================
1009 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1011 TCollection_AsciiString aScript;
1013 // Clean trace of API methods calls
1014 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1015 myPythonScripts[theStudyID]->Clear();