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 return *this << anElementsId;
240 operator<<(SMESH::FilterLibrary_i* theArg)
242 myStream<<"aFilterLibrary"<<theArg;
248 operator<<(SMESH::FilterManager_i* theArg)
250 myStream<<"aFilterManager";
256 operator<<(SMESH::Filter_i* theArg)
258 myStream<<"aFilter"<<theArg;
264 operator<<(SMESH::Functor_i* theArg)
267 FunctorType aFunctorType = theArg->GetFunctorType();
268 switch(aFunctorType){
269 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
270 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
271 case FT_Warping: myStream<< "aWarping"; break;
272 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
273 case FT_Taper: myStream<< "aTaper"; break;
274 case FT_Skew: myStream<< "aSkew"; break;
275 case FT_Area: myStream<< "aArea"; break;
276 case FT_Volume3D: myStream<< "aVolume3D"; break;
277 case FT_MaxElementLength2D:myStream<< "aMaxElementLength2D";break;
278 case FT_MaxElementLength3D:myStream<< "aMaxElementLength3D";break;
279 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
280 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
281 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
282 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
283 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
284 case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
285 case FT_Length: myStream<< "aLength"; break;
286 case FT_Length2D: myStream<< "aLength"; break;
287 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
288 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
289 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
290 case FT_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
291 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
292 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
293 case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
294 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
295 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
296 case FT_LinearOrQuadratic:myStream<< "aLinearOrQuadratic";break;
297 case FT_GroupColor: myStream<< "aGroupColor"; break;
298 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
299 case FT_LessThan: myStream<< "aLessThan"; break;
300 case FT_MoreThan: myStream<< "aMoreThan"; break;
301 case FT_EqualTo: myStream<< "anEqualTo"; break;
302 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
303 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
304 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
306 default: myStream<< "anUndefined"; break;
315 operator<<(SMESH::Measurements_i* theArg)
317 myStream<<"aMeasurements";
322 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
324 myStream << SMESHGenName(); return *this;
327 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
329 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
332 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
334 myStream << theStr; return *this;
338 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
340 switch (theVersion) {
341 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
342 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
343 default: myStream << theVersion;
348 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
350 myStream << "SMESH.AxisStruct( "
354 << theAxis.vx << ", "
355 << theAxis.vy << ", "
356 << theAxis.vz << " )";
360 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
362 const SMESH::PointStruct & P = theDir.PS;
363 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
370 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
372 DumpArray( theList, *this );
375 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
377 DumpArray( theList, *this );
381 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
382 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
384 //================================================================================
386 * \brief Return marker of long string literal beginning
387 * \param type - a name of functionality producing the string literal
388 * \retval TCollection_AsciiString - the marker string to be written into
389 * a raw python script
391 //================================================================================
393 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
397 (Standard_Integer) strlen(type) +
402 //================================================================================
404 * \brief Return marker of long string literal end
405 * \retval TCollection_AsciiString - the marker string to be written into
406 * a raw python script
408 //================================================================================
410 TCollection_AsciiString TPythonDump::LongStringEnd()
412 return myLongStringEnd;
415 //================================================================================
417 * \brief Cut out a long string literal from a string
418 * \param theText - text possibly containing string literals
419 * \param theFrom - position in the text to search from
420 * \param theLongString - the retrieved literal
421 * \param theStringType - a name of functionality produced the literal
422 * \retval bool - true if a string literal found
424 * The literal is removed from theText; theFrom points position right after
425 * the removed literal
427 //================================================================================
429 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
431 TCollection_AsciiString & theLongString,
432 TCollection_AsciiString & theStringType)
434 if ( theFrom < 1 || theFrom > theText.Length() )
437 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
438 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
439 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
442 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
446 // find where literal begins
447 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
448 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
449 int typeLen = atoi ( typeLenStr ); // = 7
450 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
451 literalBeg++; // 26 -> 27
454 literalBeg += typeLen + 1; // = 35
455 if ( literalBeg > theText.Length() )
458 // where literal ends (i.e. end marker begins)
459 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
461 literalEnd = theText.Length();
464 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
466 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
468 literalEnd += myLongStringEnd.Length(); // = 79
469 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
470 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
476 //=======================================================================
477 //function : DumpPython
479 //=======================================================================
480 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
481 CORBA::Boolean isPublished,
482 CORBA::Boolean& isValidScript)
484 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
485 if (CORBA::is_nil(aStudy))
486 return new Engines::TMPFile(0);
488 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
489 if (CORBA::is_nil(aSO))
490 return new Engines::TMPFile(0);
492 // Map study entries to object names
493 Resource_DataMapOfAsciiStringAsciiString aMap;
494 Resource_DataMapOfAsciiStringAsciiString aMapNames;
495 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
497 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
498 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
499 SALOMEDS::SObject_var aValue = Itr->Value();
500 CORBA::String_var anID = aValue->GetID();
501 CORBA::String_var aName = aValue->GetName();
502 TCollection_AsciiString aGUIName ( (char*) aName.in() );
503 TCollection_AsciiString anEnrty ( (char*) anID.in() );
504 if (aGUIName.Length() > 0) {
505 aMapNames.Bind( anEnrty, aGUIName );
506 aMap.Bind( anEnrty, aGUIName );
510 // Get trace of restored study
511 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
512 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
513 SALOMEDS::GenericAttribute_var anAttr =
514 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
516 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
517 TCollection_AsciiString aSavedTrace (oldValue);
519 // Add trace of API methods calls and replace study entries by names
520 TCollection_AsciiString aScript;
521 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
522 isPublished, isValidScript, aSavedTrace);
524 int aLen = aScript.Length();
525 unsigned char* aBuffer = new unsigned char[aLen+1];
526 strcpy((char*)aBuffer, aScript.ToCString());
528 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
529 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
531 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
532 isValidScript = isValidScript && !hasNotPublishedObjects;
534 return aStreamFile._retn();
537 //=============================================================================
541 //=============================================================================
542 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
544 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
545 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
547 myPythonScripts[theStudyID]->Append(theString);
550 //=============================================================================
552 * RemoveLastFromPythonScript
554 //=============================================================================
555 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
557 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
558 int aLen = myPythonScripts[theStudyID]->Length();
559 myPythonScripts[theStudyID]->Remove(aLen);
563 //=======================================================================
564 //function : SavePython
566 //=======================================================================
567 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
569 // Dump trace of API methods calls
570 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
572 // Check contents of PythonObject attribute
573 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
574 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
575 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
576 SALOMEDS::GenericAttribute_var anAttr =
577 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
579 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
580 TCollection_AsciiString oldScript (oldValue);
582 if (oldScript.Length() > 0) {
584 oldScript += aScript;
589 // Store in PythonObject attribute
590 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
592 // Clean trace of API methods calls
593 CleanPythonTrace(theStudy->StudyId());
600 //=============================================================================
602 * FindEntries: Returns a sequence of start/end positions of entries in the string
604 //=============================================================================
605 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
607 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
608 Standard_Integer aLen = theString.Length();
609 Standard_Boolean isFound = Standard_False;
611 char* arr = (char*) theString.ToCString();
612 Standard_Integer i = 0, j;
617 if ( isdigit( c )) { //Is digit?
619 isFound = Standard_False;
620 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
622 if(c == ':') isFound = Standard_True;
626 int prev = (i < 1) ? 0 : (int)arr[i - 1];
627 // to distinguish from a sketcher command:
628 // last char should be a digit, not ":",
629 // previous char should not be '"'.
630 if (arr[j-2] != ':' && prev != '"') {
631 aSeq->Append(i+1); // +1 because AsciiString starts from 1
645 //================================================================================
647 * \brief Make a string be a valid python name
648 * \param aName - a string to fix
649 * \retval bool - true if aName was not modified
651 //================================================================================
653 bool fixPythonName(TCollection_AsciiString & aName )
655 const TCollection_AsciiString allowedChars =
656 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
657 bool isValidName = true;
658 int p=1; // replace not allowed chars with underscore
659 while (p <= aName.Length() &&
660 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
662 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
663 aName.Remove( p, 1 ); // remove double _ and from the start and the end
665 aName.SetValue(p, '_');
668 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
669 aName.Insert( 1, 'a' );
676 //=============================================================================
680 //=============================================================================
681 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
682 (SALOMEDS::Study_ptr theStudy,
683 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
684 Resource_DataMapOfAsciiStringAsciiString& theNames,
687 const TCollection_AsciiString& theSavedTrace)
689 int aStudyID = theStudy->StudyId();
691 TCollection_AsciiString helper; // to comfortably concatenate C strings
692 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
693 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
694 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
696 TCollection_AsciiString aScript;
697 aScript = "def RebuildData(theStudy):\n\t";
698 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
699 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
701 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
703 aScript += aSMESHGen + ".SetCurrentStudy(None)";
705 // import python files corresponding to plugins
706 set<string> moduleNameSet;
707 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
708 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
709 string moduleName = hyp_creator->second->GetModuleName();
710 bool newModule = moduleNameSet.insert( moduleName ).second;
712 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
715 // Dump trace of restored study
716 if (theSavedTrace.Length() > 0) {
717 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
718 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
719 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
721 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
722 if ( !isNewVersion ) {
723 TCollection_AsciiString aSavedTrace( theSavedTrace );
724 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
725 int beg, end = aSavedTrace.Length(), from = 1;
726 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
727 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
728 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
729 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
732 from = beg + aSmeshCall.Length();
734 aScript += helper + "\n" + aSavedTrace;
737 // append a saved trace to the script
738 aScript += helper + "\n" + theSavedTrace;
741 // Dump trace of API methods calls
742 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
743 if (aNewLines.Length() > 0) {
744 aScript += helper + "\n" + aNewLines;
747 // Convert IDL API calls into smesh.py API.
748 // Some objects are wrapped with python classes and
749 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
750 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
751 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod, theObjectNames );
753 // Find entries to be replaced by names
754 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
755 Standard_Integer aLen = aSeq->Length();
760 // Replace entries by the names
761 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
762 TColStd_SequenceOfAsciiString seqRemoved;
763 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
764 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
765 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
767 // Collect names of GEOM objects to exclude same names for SMESH objects
768 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
769 int ign = 0, nbgn = aGeomNames->length();
770 for (; ign < nbgn; ign++) {
771 aName = aGeomNames[ign];
772 theObjectNames.Bind(aName, "1");
775 bool importGeom = false;
776 for (Standard_Integer i = 1; i <= aLen; i += 2) {
777 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
778 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
780 aName = geom->GetDumpName( anEntry.ToCString() );
781 if (aName.IsEmpty()) {
783 if (theObjectNames.IsBound(anEntry)) {
784 // The Object is in Study
785 aName = theObjectNames.Find(anEntry);
786 // check validity of aName
787 bool isValidName = fixPythonName( aName );
788 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
789 // diff objects have same name - make a new name by appending a digit
790 TCollection_AsciiString aName2;
791 Standard_Integer i = 0;
793 aName2 = aName + "_" + ++i;
794 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
799 theObjectNames(anEntry) = aName;
804 aName = aBaseName + (++objectCounter);
805 } while (theObjectNames.IsBound(aName));
806 seqRemoved.Append(aName);
807 mapRemoved.Bind(anEntry, "1");
808 theObjectNames.Bind(anEntry, aName);
810 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
816 anUpdatedScript += aName;
817 aStart = aSeq->Value(i + 1) + 1;
820 // set initial part of aSript
821 TCollection_AsciiString initPart = "import salome, SMESH, SALOMEDS\n";
822 initPart += helper + "import " + aSmeshpy + "\n\n";
825 initPart += ("## import GEOM dump file ## \n"
826 "import string, os, sys, re\n"
827 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
828 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
830 anUpdatedScript.Insert ( 1, initPart );
832 // add final part of aScript
833 if (aSeq->Value(aLen) < aScriptLength)
834 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
837 SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
838 if( !CORBA::is_nil(aComp) )
840 SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
841 for( Itr->InitEx(true); Itr->More(); Itr->Next() )
843 SALOMEDS::SObject_var aSObj = Itr->Value();
844 SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
846 if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
848 CORBA::String_var anEntry = aSObj->GetID();
850 SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
852 SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
853 if( !CORBA::is_nil(aGroup) )
855 SALOMEDS::Color aColor = aGroup->GetColor();
856 if ( aColor.R >= 0 || aColor.G >= 0 || aColor.B >= 0 )
858 CORBA::String_var anEntry = aSObj->GetID();
859 anUpdatedScript += SMESH_Comment("\n\t")
860 << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
861 << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
867 // Remove removed objects
868 if ( seqRemoved.Length() > 0 ) {
869 anUpdatedScript += "\n\t## some objects were removed";
870 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
872 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
873 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
874 anUpdatedScript += seqRemoved.Value(ir);
875 // for object wrapped by class of smesh.py
876 anEntry = theObjectNames( seqRemoved.Value(ir) );
877 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
878 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
879 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
883 anUpdatedScript += "\n\t## set object names";
884 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
885 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
886 // anUpdatedScript += "\n";
888 TCollection_AsciiString aGUIName;
889 Resource_DataMapOfAsciiStringAsciiString mapEntries;
890 for (Standard_Integer i = 1; i <= aLen; i += 2)
892 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
893 aName = geom->GetDumpName( anEntry.ToCString() );
894 if (aName.IsEmpty() && // Not a GEOM object
895 theNames.IsBound(anEntry) &&
896 !mapEntries.IsBound(anEntry) && // Not yet processed
897 !mapRemoved.IsBound(anEntry)) // Was not removed
899 aName = theObjectNames.Find(anEntry);
900 aGUIName = theNames.Find(anEntry);
901 mapEntries.Bind(anEntry, aName);
902 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
903 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
904 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
905 anUpdatedScript += helper + ", '" + aGUIName + "')";
908 anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
909 anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
911 // -----------------------------------------------------------------
912 // store visual properties of displayed objects
913 // -----------------------------------------------------------------
917 //Output the script that sets up the visual parameters.
918 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
919 if (script && strlen(script) > 0) {
920 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
921 anUpdatedScript += script;
922 CORBA::string_free(script);
925 anUpdatedScript += "\n\n\tpass\n";
927 // -----------------------------------------------------------------
928 // put string literals describing patterns into separate functions
929 // -----------------------------------------------------------------
931 TCollection_AsciiString aLongString, aFunctionType;
933 set< string > functionNameSet;
934 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
936 // make a python string literal
937 aLongString.Prepend(":\n\treturn '''\n");
938 aLongString += "\n\t'''\n\tpass\n";
940 TCollection_AsciiString functionName;
942 // check if the function returning this literal is already defined
943 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
944 if ( posAlready ) // already defined
946 // find the function name
947 int functBeg = posAlready;
948 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
949 while ( *script != ' ' ) {
953 functBeg++; // do not take ' '
954 posAlready--; // do not take ':'
955 functionName = anUpdatedScript.SubString( functBeg, posAlready );
957 else // not defined yet
959 // find a unique function name
960 fixPythonName( aFunctionType );
961 Standard_Integer nb = 0;
962 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
963 while ( !functionNameSet.insert( functionName.ToCString() ).second );
965 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
967 anUpdatedScript.InsertBefore( where, functionName ); // call function
972 return anUpdatedScript;
975 //=============================================================================
979 //=============================================================================
980 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
982 TCollection_AsciiString aScript;
984 // Dump trace of API methods calls
985 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
986 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
987 Standard_Integer istr, aLen = aPythonScript->Length();
988 for (istr = 1; istr <= aLen; istr++) {
990 aScript += aPythonScript->Value(istr);
998 //=============================================================================
1002 //=============================================================================
1003 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1005 TCollection_AsciiString aScript;
1007 // Clean trace of API methods calls
1008 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1009 myPythonScripts[theStudyID]->Clear();