1 // Copyright (C) 2007-2008 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_Gen_i_DumpPython.cxx
23 // Created : Thu Mar 24 17:17:59 2005
24 // Author : Julia DOROVSKIKH
28 #include "SMESH_PythonDump.hxx"
29 #include "SMESH_Gen_i.hxx"
30 #include "SMESH_Filter_i.hxx"
31 #include "SMESH_MeshEditor_i.hxx"
32 #include "SMESH_2smeshpy.hxx"
34 #include <TColStd_HSequenceOfInteger.hxx>
35 #include <TCollection_AsciiString.hxx>
36 #include <SMESH_Comment.hxx>
40 static int MYDEBUG = 0;
42 static int MYDEBUG = 0;
45 static TCollection_AsciiString NotPublishedObjectName()
47 return "__NOT__Published__Object__";
53 size_t TPythonDump::myCounter = 0;
64 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
65 std::string aString = myStream.str();
66 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
67 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
68 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
69 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
70 if(MYDEBUG) MESSAGE(aString);
77 operator<<(long int theArg){
84 operator<<(int theArg){
91 operator<<(double theArg){
98 operator<<(float theArg){
105 operator<<(const void* theArg){
112 operator<<(const char* theArg){
120 operator<<(const SMESH::ElementType& theArg)
124 case ALL: myStream<<"ALL";break;
125 case NODE: myStream<<"NODE";break;
126 case EDGE: myStream<<"EDGE";break;
127 case FACE: myStream<<"FACE";break;
128 case VOLUME:myStream<<"VOLUME";break;
135 operator<<(const SMESH::GeometryType& theArg)
139 case Geom_POINT: myStream<<"Geom_POINT"; break;
140 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
141 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
142 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
143 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
144 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
145 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
146 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
147 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
148 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
153 template<class TArray>
154 void DumpArray(const TArray& theArray, std::ostringstream & theStream)
157 for (int i = 1; i <= theArray.length(); i++) {
158 theStream << theArray[i-1];
159 if ( i < theArray.length() )
166 TPythonDump::operator<<(const SMESH::long_array& theArg)
168 DumpArray( theArg, myStream );
173 TPythonDump::operator<<(const SMESH::double_array& theArg)
175 DumpArray( theArg, myStream );
181 operator<<(SALOMEDS::SObject_ptr aSObject)
183 if ( !aSObject->_is_nil() )
184 myStream << aSObject->GetID();
186 myStream << NotPublishedObjectName();
192 operator<<(CORBA::Object_ptr theArg)
194 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
195 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
196 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
197 if(!aSObject->_is_nil()) {
198 CORBA::String_var id = aSObject->GetID();
200 } else if ( !CORBA::is_nil(theArg)) {
201 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
202 myStream << "smeshObj_" << size_t(theArg);
204 myStream << NotPublishedObjectName();
213 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
215 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
216 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
217 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
218 myStream << "hyp_" << theArg->GetId();
220 *this << CORBA::Object_ptr( theArg );
226 operator<<(SMESH::SMESH_IDSource_ptr theArg)
228 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
229 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
230 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
231 if(!aSObject->_is_nil() || CORBA::is_nil( theArg ))
232 return *this << aSObject;
233 SMESH::long_array_var anElementsId = theArg->GetIDs();
234 return *this << anElementsId;
239 operator<<(SMESH::FilterLibrary_i* theArg)
241 myStream<<"aFilterLibrary"<<theArg;
247 operator<<(SMESH::FilterManager_i* theArg)
249 myStream<<"aFilterManager";
255 operator<<(SMESH::Filter_i* theArg)
257 myStream<<"aFilter"<<theArg;
263 operator<<(SMESH::Functor_i* theArg)
266 FunctorType aFunctorType = theArg->GetFunctorType();
267 switch(aFunctorType){
268 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
269 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
270 case FT_Warping: myStream<< "aWarping"; break;
271 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
272 case FT_Taper: myStream<< "aTaper"; break;
273 case FT_Skew: myStream<< "aSkew"; break;
274 case FT_Area: myStream<< "aArea"; break;
275 case FT_Volume3D: myStream<< "aVolume3D"; break;
276 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
277 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
278 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
279 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
280 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
281 case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
282 case FT_Length: myStream<< "aLength"; break;
283 case FT_Length2D: myStream<< "aLength"; break;
284 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
285 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
286 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
287 case FT_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
288 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
289 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
290 case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
291 case FT_LinearOrQuadratic:myStream<< "aLinearOrQuadratic";break;
292 case FT_GroupColor: myStream<< "aGroupColor"; break;
293 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
294 case FT_LessThan: myStream<< "aLessThan"; break;
295 case FT_MoreThan: myStream<< "aMoreThan"; break;
296 case FT_EqualTo: myStream<< "anEqualTo"; break;
297 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
298 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
299 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
301 default: myStream<< "anUndefined"; break;
308 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
310 myStream << SMESHGenName(); return *this;
313 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
315 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
318 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
320 myStream << theStr; return *this;
324 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
326 switch (theVersion) {
327 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
328 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
329 default: myStream << theVersion;
334 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
336 myStream << "SMESH.AxisStruct( "
340 << theAxis.vx << ", "
341 << theAxis.vy << ", "
342 << theAxis.vz << " )";
346 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
348 const SMESH::PointStruct & P = theDir.PS;
349 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
356 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList){
357 if(theList && theList->length() > 0 ) {
358 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
359 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
361 int aListLen = theList->length();
362 for(int i = 0 ; i < aListLen; i++){
363 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,(*theList)[i]);
364 if(!aSObject->_is_nil()) {
365 myStream << aSObject->GetID();
366 i < (aListLen - 1) ? myStream<<", " : myStream<<"]";
374 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
375 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
377 //================================================================================
379 * \brief Return marker of long string literal beginning
380 * \param type - a name of functionality producing the string literal
381 * \retval TCollection_AsciiString - the marker string to be written into
382 * a raw python script
384 //================================================================================
386 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
390 (Standard_Integer) strlen(type) +
395 //================================================================================
397 * \brief Return marker of long string literal end
398 * \retval TCollection_AsciiString - the marker string to be written into
399 * a raw python script
401 //================================================================================
403 TCollection_AsciiString TPythonDump::LongStringEnd()
405 return myLongStringEnd;
408 //================================================================================
410 * \brief Cut out a long string literal from a string
411 * \param theText - text possibly containing string literals
412 * \param theFrom - position in the text to search from
413 * \param theLongString - the retrieved literal
414 * \param theStringType - a name of functionality produced the literal
415 * \retval bool - true if a string literal found
417 * The literal is removed from theText; theFrom points position right after
418 * the removed literal
420 //================================================================================
422 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
424 TCollection_AsciiString & theLongString,
425 TCollection_AsciiString & theStringType)
427 if ( theFrom < 1 || theFrom > theText.Length() )
430 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
431 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
432 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
435 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
439 // find where literal begins
440 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
441 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
442 int typeLen = atoi ( typeLenStr ); // = 7
443 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
444 literalBeg++; // 26 -> 27
447 literalBeg += typeLen + 1; // = 35
448 if ( literalBeg > theText.Length() )
451 // where literal ends (i.e. end marker begins)
452 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
454 literalEnd = theText.Length();
457 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
459 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
461 literalEnd += myLongStringEnd.Length(); // = 79
462 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
463 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
469 //=======================================================================
470 //function : DumpPython
472 //=======================================================================
473 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
474 CORBA::Boolean isPublished,
475 CORBA::Boolean& isValidScript)
477 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
478 if (CORBA::is_nil(aStudy))
479 return new Engines::TMPFile(0);
481 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
482 if (CORBA::is_nil(aSO))
483 return new Engines::TMPFile(0);
485 // Map study entries to object names
486 Resource_DataMapOfAsciiStringAsciiString aMap;
487 Resource_DataMapOfAsciiStringAsciiString aMapNames;
488 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
490 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
491 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
492 SALOMEDS::SObject_var aValue = Itr->Value();
493 CORBA::String_var anID = aValue->GetID();
494 CORBA::String_var aName = aValue->GetName();
495 TCollection_AsciiString aGUIName ( (char*) aName.in() );
496 TCollection_AsciiString anEnrty ( (char*) anID.in() );
497 if (aGUIName.Length() > 0) {
498 aMapNames.Bind( anEnrty, aGUIName );
499 aMap.Bind( anEnrty, aGUIName );
503 // Get trace of restored study
504 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
505 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
506 SALOMEDS::GenericAttribute_var anAttr =
507 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
509 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
510 TCollection_AsciiString aSavedTrace (oldValue);
512 // Add trace of API methods calls and replace study entries by names
513 TCollection_AsciiString aScript;
514 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
515 isPublished, isValidScript, aSavedTrace);
517 int aLen = aScript.Length();
518 unsigned char* aBuffer = new unsigned char[aLen+1];
519 strcpy((char*)aBuffer, aScript.ToCString());
521 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
522 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
524 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
525 isValidScript = isValidScript && !hasNotPublishedObjects;
527 return aStreamFile._retn();
530 //=============================================================================
534 //=============================================================================
535 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
537 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
538 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
540 myPythonScripts[theStudyID]->Append(theString);
543 //=============================================================================
545 * RemoveLastFromPythonScript
547 //=============================================================================
548 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
550 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
551 int aLen = myPythonScripts[theStudyID]->Length();
552 myPythonScripts[theStudyID]->Remove(aLen);
556 //=======================================================================
557 //function : SavePython
559 //=======================================================================
560 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
562 // Dump trace of API methods calls
563 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
565 // Check contents of PythonObject attribute
566 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
567 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
568 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
569 SALOMEDS::GenericAttribute_var anAttr =
570 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
572 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
573 TCollection_AsciiString oldScript (oldValue);
575 if (oldScript.Length() > 0) {
577 oldScript += aScript;
582 // Store in PythonObject attribute
583 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
585 // Clean trace of API methods calls
586 CleanPythonTrace(theStudy->StudyId());
593 //=============================================================================
595 * FindEntries: Returns a sequence of start/end positions of entries in the string
597 //=============================================================================
598 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
600 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
601 Standard_Integer aLen = theString.Length();
602 Standard_Boolean isFound = Standard_False;
604 char* arr = (char*) theString.ToCString();
605 Standard_Integer i = 0, j;
610 if ( isdigit( c )) { //Is digit?
612 isFound = Standard_False;
613 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
615 if(c == ':') isFound = Standard_True;
619 int prev = (i < 1) ? 0 : (int)arr[i - 1];
620 // to distinguish from a sketcher command:
621 // last char should be a digit, not ":",
622 // previous char should not be '"'.
623 if (arr[j-2] != ':' && prev != '"') {
624 aSeq->Append(i+1); // +1 because AsciiString starts from 1
638 //================================================================================
640 * \brief Make a string be a valid python name
641 * \param aName - a string to fix
642 * \retval bool - true if aName was not modified
644 //================================================================================
646 bool fixPythonName(TCollection_AsciiString & aName )
648 const TCollection_AsciiString allowedChars =
649 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
650 bool isValidName = true;
651 int p=1; // replace not allowed chars with underscore
652 while (p <= aName.Length() &&
653 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
655 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
656 aName.Remove( p, 1 ); // remove double _ and from the start and the end
658 aName.SetValue(p, '_');
661 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
662 aName.Insert( 1, 'a' );
669 //=============================================================================
673 //=============================================================================
674 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
675 (SALOMEDS::Study_ptr theStudy,
676 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
677 Resource_DataMapOfAsciiStringAsciiString& theNames,
680 const TCollection_AsciiString& theSavedTrace)
682 int aStudyID = theStudy->StudyId();
684 TCollection_AsciiString helper; // to comfortably concatenate C strings
685 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
686 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
687 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
689 TCollection_AsciiString aScript;
690 aScript = "def RebuildData(theStudy):\n\t";
691 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
693 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
695 aScript += aSMESHGen + ".SetCurrentStudy(None)";
697 // import python files corresponding to plugins
698 set<string> moduleNameSet;
699 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
700 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
701 string moduleName = hyp_creator->second->GetModuleName();
702 bool newModule = moduleNameSet.insert( moduleName ).second;
704 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
707 // Dump trace of restored study
708 if (theSavedTrace.Length() > 0) {
709 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
710 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
711 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
713 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
714 if ( !isNewVersion ) {
715 TCollection_AsciiString aSavedTrace( theSavedTrace );
716 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
717 int beg, end = aSavedTrace.Length(), from = 1;
718 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
719 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
720 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
721 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
724 from = beg + aSmeshCall.Length();
726 aScript += helper + "\n" + aSavedTrace;
729 // append a saved trace to the script
730 aScript += helper + "\n" + theSavedTrace;
733 // Dump trace of API methods calls
734 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
735 if (aNewLines.Length() > 0) {
736 aScript += helper + "\n" + aNewLines;
739 // Convert IDL API calls into smesh.py API.
740 // Some objects are wrapped with python classes and
741 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
742 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
743 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod, theObjectNames );
745 // Find entries to be replaced by names
746 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
747 Standard_Integer aLen = aSeq->Length();
752 // Replace entries by the names
753 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
754 TColStd_SequenceOfAsciiString seqRemoved;
755 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
756 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
757 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
759 // Collect names of GEOM objects to exclude same names for SMESH objects
760 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
761 int ign = 0, nbgn = aGeomNames->length();
762 for (; ign < nbgn; ign++) {
763 aName = aGeomNames[ign];
764 theObjectNames.Bind(aName, "1");
767 bool importGeom = false;
768 for (Standard_Integer i = 1; i <= aLen; i += 2) {
769 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
770 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
772 aName = geom->GetDumpName( anEntry.ToCString() );
773 if (aName.IsEmpty()) {
775 if (theObjectNames.IsBound(anEntry)) {
776 // The Object is in Study
777 aName = theObjectNames.Find(anEntry);
778 // check validity of aName
779 bool isValidName = fixPythonName( aName );
780 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
781 // diff objects have same name - make a new name by appending a digit
782 TCollection_AsciiString aName2;
783 Standard_Integer i = 0;
785 aName2 = aName + "_" + ++i;
786 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
791 theObjectNames(anEntry) = aName;
796 aName = aBaseName + (++objectCounter);
797 } while (theObjectNames.IsBound(aName));
798 seqRemoved.Append(aName);
799 mapRemoved.Bind(anEntry, "1");
800 theObjectNames.Bind(anEntry, aName);
802 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
808 anUpdatedScript += aName;
809 aStart = aSeq->Value(i + 1) + 1;
812 // set initial part of aSript
813 TCollection_AsciiString initPart = "import salome, SMESH, SALOMEDS\n";
814 initPart += helper + "import " + aSmeshpy + "\n\n";
817 initPart += ("## import GEOM dump file ## \n"
818 "import string, os, sys, re\n"
819 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
820 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
822 anUpdatedScript.Insert ( 1, initPart );
824 // add final part of aScript
825 if (aSeq->Value(aLen) < aScriptLength)
826 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
829 SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
830 if( !CORBA::is_nil(aComp) )
832 SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
833 for( Itr->InitEx(true); Itr->More(); Itr->Next() )
835 SALOMEDS::SObject_var aSObj = Itr->Value();
836 SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
838 if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
840 CORBA::String_var anEntry = aSObj->GetID();
842 SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
844 SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
845 if( !CORBA::is_nil(aGroup) )
847 SALOMEDS::Color aColor = aGroup->GetColor();
848 if ( aColor.R >= 0 || aColor.G >= 0 || aColor.B >= 0 )
850 CORBA::String_var anEntry = aSObj->GetID();
851 anUpdatedScript += SMESH_Comment("\n\t")
852 << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
853 << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
859 // Remove removed objects
860 if ( seqRemoved.Length() > 0 ) {
861 anUpdatedScript += "\n\t## some objects were removed";
862 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
864 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
865 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
866 anUpdatedScript += seqRemoved.Value(ir);
867 // for object wrapped by class of smesh.py
868 anEntry = theObjectNames( seqRemoved.Value(ir) );
869 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
870 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
871 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
875 anUpdatedScript += "\n\t## set object names";
876 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
877 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
878 // anUpdatedScript += "\n";
880 TCollection_AsciiString aGUIName;
881 Resource_DataMapOfAsciiStringAsciiString mapEntries;
882 for (Standard_Integer i = 1; i <= aLen; i += 2)
884 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
885 aName = geom->GetDumpName( anEntry.ToCString() );
886 if (aName.IsEmpty() && // Not a GEOM object
887 theNames.IsBound(anEntry) &&
888 !mapEntries.IsBound(anEntry) && // Not yet processed
889 !mapRemoved.IsBound(anEntry)) // Was not removed
891 aName = theObjectNames.Find(anEntry);
892 aGUIName = theNames.Find(anEntry);
893 mapEntries.Bind(anEntry, aName);
894 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
895 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
896 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
897 anUpdatedScript += helper + ", '" + aGUIName + "')";
900 anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
901 anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
903 // -----------------------------------------------------------------
904 // store visual properties of displayed objects
905 // -----------------------------------------------------------------
909 //Output the script that sets up the visual parameters.
910 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
911 if (script && strlen(script) > 0) {
912 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
913 anUpdatedScript += script;
914 CORBA::string_free(script);
917 anUpdatedScript += "\n\n\tpass\n";
919 // -----------------------------------------------------------------
920 // put string literals describing patterns into separate functions
921 // -----------------------------------------------------------------
923 TCollection_AsciiString aLongString, aFunctionType;
925 set< string > functionNameSet;
926 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
928 // make a python string literal
929 aLongString.Prepend(":\n\treturn '''\n");
930 aLongString += "\n\t'''\n\tpass\n";
932 TCollection_AsciiString functionName;
934 // check if the function returning this literal is already defined
935 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
936 if ( posAlready ) // already defined
938 // find the function name
939 int functBeg = posAlready;
940 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
941 while ( *script != ' ' ) {
945 functBeg++; // do not take ' '
946 posAlready--; // do not take ':'
947 functionName = anUpdatedScript.SubString( functBeg, posAlready );
949 else // not defined yet
951 // find a unique function name
952 fixPythonName( aFunctionType );
953 Standard_Integer nb = 0;
954 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
955 while ( !functionNameSet.insert( functionName.ToCString() ).second );
957 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
959 anUpdatedScript.InsertBefore( where, functionName ); // call function
964 return anUpdatedScript;
967 //=============================================================================
971 //=============================================================================
972 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
974 TCollection_AsciiString aScript;
976 // Dump trace of API methods calls
977 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
978 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
979 Standard_Integer istr, aLen = aPythonScript->Length();
980 for (istr = 1; istr <= aLen; istr++) {
982 aScript += aPythonScript->Value(istr);
990 //=============================================================================
994 //=============================================================================
995 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
997 TCollection_AsciiString aScript;
999 // Clean trace of API methods calls
1000 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1001 myPythonScripts[theStudyID]->Clear();