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 <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
40 static int MYDEBUG = 0;
42 static int MYDEBUG = 0;
47 static TCollection_AsciiString NotPublishedObjectName()
49 return "__NOT__Published__Object__";
55 size_t TPythonDump::myCounter = 0;
66 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
67 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
68 if(!aStudy->_is_nil()){
69 string aString = myStream.str();
70 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
71 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
72 if(MYDEBUG) MESSAGE(aString);
79 operator<<(long int theArg){
86 operator<<(int theArg){
93 operator<<(double theArg){
100 operator<<(float theArg){
107 operator<<(const void* theArg){
114 operator<<(const char* theArg){
122 operator<<(const SMESH::ElementType& theArg)
126 case ALL: myStream<<"ALL";break;
127 case NODE: myStream<<"NODE";break;
128 case EDGE: myStream<<"EDGE";break;
129 case FACE: myStream<<"FACE";break;
130 case VOLUME:myStream<<"VOLUME";break;
131 case ELEMENT0D:myStream<<"ELEMENT0D";break;
136 template<class TArray>
137 void DumpArray(const TArray& theArray, std::ostringstream & theStream)
140 for (int i = 1; i <= theArray.length(); i++) {
141 theStream << theArray[i-1];
142 if ( i < theArray.length() )
149 TPythonDump::operator<<(const SMESH::long_array& theArg)
151 DumpArray( theArg, myStream );
156 TPythonDump::operator<<(const SMESH::double_array& theArg)
158 DumpArray( theArg, myStream );
164 operator<<(SALOMEDS::SObject_ptr aSObject)
166 if ( !aSObject->_is_nil() )
167 myStream << aSObject->GetID();
169 myStream << NotPublishedObjectName();
175 operator<<(CORBA::Object_ptr theArg)
177 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
178 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
179 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
180 if(!aSObject->_is_nil())
181 myStream << aSObject->GetID();
182 else if ( !CORBA::is_nil(theArg)) {
183 if ( aSMESHGen->CanPublishInStudy( theArg )) { // not published SMESH object
184 myStream << "smeshObj_" << size_t(theArg);
187 myStream << NotPublishedObjectName();
196 operator<<(SMESH::FilterLibrary_i* theArg)
198 myStream<<"aFilterLibrary"<<theArg;
204 operator<<(SMESH::FilterManager_i* theArg)
206 myStream<<"aFilterManager";
212 operator<<(SMESH::Filter_i* theArg)
214 myStream<<"aFilter"<<theArg;
220 operator<<(SMESH::Functor_i* theArg)
223 FunctorType aFunctorType = theArg->GetFunctorType();
224 switch(aFunctorType){
225 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
226 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
227 case FT_Warping: myStream<< "aWarping"; break;
228 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
229 case FT_Taper: myStream<< "aTaper"; break;
230 case FT_Skew: myStream<< "aSkew"; break;
231 case FT_Area: myStream<< "aArea"; break;
232 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
233 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
234 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
235 case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
236 case FT_Length: myStream<< "aLength"; break;
237 case FT_Length2D: myStream<< "aLength"; break;
238 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
239 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
240 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
241 case FT_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
242 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
243 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
244 case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
245 case FT_LessThan: myStream<< "aLessThan"; break;
246 case FT_MoreThan: myStream<< "aMoreThan"; break;
247 case FT_EqualTo: myStream<< "anEqualTo"; break;
248 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
249 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
250 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
251 case FT_Undefined: myStream<< "anUndefined"; break;
258 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
260 myStream << SMESHGenName(); return *this;
263 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
265 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
268 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
270 myStream << theStr; return *this;
274 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
276 switch (theVersion) {
277 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
278 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
279 default: myStream << theVersion;
284 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
286 myStream << "SMESH.AxisStruct( "
290 << theAxis.vx << ", "
291 << theAxis.vy << ", "
292 << theAxis.vz << " )";
296 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
298 const SMESH::PointStruct & P = theDir.PS;
299 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
306 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList){
307 if(theList && theList->length() > 0 ) {
308 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
309 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
311 int aListLen = theList->length();
312 for(int i = 0 ; i < aListLen; i++){
313 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,(*theList)[i]);
314 if(!aSObject->_is_nil()) {
315 myStream << aSObject->GetID();
316 i < (aListLen - 1) ? myStream<<", " : myStream<<"]";
324 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
325 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
327 //================================================================================
329 * \brief Return marker of long string literal beginning
330 * \param type - a name of functionality producing the string literal
331 * \retval TCollection_AsciiString - the marker string to be written into
332 * a raw python script
334 //================================================================================
336 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
340 (Standard_Integer) strlen(type) +
345 //================================================================================
347 * \brief Return marker of long string literal end
348 * \retval TCollection_AsciiString - the marker string to be written into
349 * a raw python script
351 //================================================================================
353 TCollection_AsciiString TPythonDump::LongStringEnd()
355 return myLongStringEnd;
358 //================================================================================
360 * \brief Cut out a long string literal from a string
361 * \param theText - text possibly containing string literals
362 * \param theFrom - position in the text to search from
363 * \param theLongString - the retrieved literal
364 * \param theStringType - a name of functionality produced the literal
365 * \retval bool - true if a string literal found
367 * The literal is removed from theText; theFrom points position right after
368 * the removed literal
370 //================================================================================
372 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
374 TCollection_AsciiString & theLongString,
375 TCollection_AsciiString & theStringType)
377 if ( theFrom < 1 || theFrom > theText.Length() )
380 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
381 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
382 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
385 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
389 // find where literal begins
390 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
391 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
392 int typeLen = atoi ( typeLenStr ); // = 7
393 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
394 literalBeg++; // 26 -> 27
397 literalBeg += typeLen + 1; // = 35
398 if ( literalBeg > theText.Length() )
401 // where literal ends (i.e. end marker begins)
402 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
404 literalEnd = theText.Length();
407 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
409 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
411 literalEnd += myLongStringEnd.Length(); // = 79
412 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
413 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
419 //=======================================================================
420 //function : DumpPython
422 //=======================================================================
423 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
424 CORBA::Boolean isPublished,
425 CORBA::Boolean& isValidScript)
427 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
428 if (CORBA::is_nil(aStudy))
429 return new Engines::TMPFile(0);
431 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
432 if (CORBA::is_nil(aSO))
433 return new Engines::TMPFile(0);
435 // Map study entries to object names
436 Resource_DataMapOfAsciiStringAsciiString aMap;
437 Resource_DataMapOfAsciiStringAsciiString aMapNames;
438 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
440 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
441 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
442 SALOMEDS::SObject_var aValue = Itr->Value();
443 CORBA::String_var anID = aValue->GetID();
444 CORBA::String_var aName = aValue->GetName();
445 TCollection_AsciiString aGUIName ( (char*) aName.in() );
446 TCollection_AsciiString anEnrty ( (char*) anID.in() );
447 if (aGUIName.Length() > 0) {
448 aMapNames.Bind( anEnrty, aGUIName );
449 aMap.Bind( anEnrty, aGUIName );
453 // Get trace of restored study
454 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
455 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
456 SALOMEDS::GenericAttribute_var anAttr =
457 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
459 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
460 TCollection_AsciiString aSavedTrace (oldValue);
462 // Add trace of API methods calls and replace study entries by names
463 TCollection_AsciiString aScript =
464 "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
465 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
466 isPublished, isValidScript, aSavedTrace);
468 //inserting export for Object Names
469 TCollection_AsciiString def = "def RebuildData(theStudy):\n";
470 int pos = aScript.Search( def );
473 //insert global definition
474 TCollection_AsciiString glob;
475 for( Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString It(aMap);
476 It.More(); It.Next() )
478 TCollection_AsciiString name = It.Value();
480 if ( !name.IsEmpty() && name.Search(' ') == -1 && name.Search( ':' ) == -1
481 && !name.IsIntegerValue() && !name.IsEqual("Hypotheses") && !name.IsEqual("Algorithms") )
483 if ( glob.Length() > 0 )
488 if ( glob.Length() > 0 )
490 glob.Prepend( "\tglobal " );
494 aScript.Insert( pos + def.Length(), glob );
496 int aLen = aScript.Length();
497 unsigned char* aBuffer = new unsigned char[aLen+1];
498 strcpy((char*)aBuffer, aScript.ToCString());
500 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
501 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
503 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
504 isValidScript = isValidScript && !hasNotPublishedObjects;
506 return aStreamFile._retn();
509 //=============================================================================
513 //=============================================================================
514 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
516 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
517 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
519 myPythonScripts[theStudyID]->Append(theString);
522 //=============================================================================
524 * RemoveLastFromPythonScript
526 //=============================================================================
527 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
529 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
530 int aLen = myPythonScripts[theStudyID]->Length();
531 myPythonScripts[theStudyID]->Remove(aLen);
535 //=======================================================================
536 //function : SavePython
538 //=======================================================================
539 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
541 // Dump trace of API methods calls
542 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
544 // Check contents of PythonObject attribute
545 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
546 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
547 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
548 SALOMEDS::GenericAttribute_var anAttr =
549 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
551 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
552 TCollection_AsciiString oldScript (oldValue);
554 if (oldScript.Length() > 0) {
556 oldScript += aScript;
561 // Store in PythonObject attribute
562 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
564 // Clean trace of API methods calls
565 CleanPythonTrace(theStudy->StudyId());
572 //=============================================================================
574 * FindEntries: Returns a sequence of start/end positions of entries in the string
576 //=============================================================================
577 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
579 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
580 Standard_Integer aLen = theString.Length();
581 Standard_Boolean isFound = Standard_False;
583 char* arr = (char*) theString.ToCString();
584 Standard_Integer i = 0, j;
589 if ( isdigit( c )) { //Is digit?
591 isFound = Standard_False;
592 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
594 if(c == ':') isFound = Standard_True;
598 int prev = (i < 1) ? 0 : (int)arr[i - 1];
599 // to distinguish from a sketcher command:
600 // last char should be a digit, not ":",
601 // previous char should not be '"'.
602 if (arr[j-2] != ':' && prev != '"') {
603 aSeq->Append(i+1); // +1 because AsciiString starts from 1
617 //================================================================================
619 * \brief Make a string be a valid python name
620 * \param aName - a string to fix
621 * \retval bool - true if aName was not modified
623 //================================================================================
625 bool fixPythonName(TCollection_AsciiString & aName )
627 const TCollection_AsciiString allowedChars =
628 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
629 bool isValidName = true;
630 int p=1; // replace not allowed chars with underscore
631 while (p <= aName.Length() &&
632 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
634 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
635 aName.Remove( p, 1 ); // remove double _ and from the start and the end
637 aName.SetValue(p, '_');
640 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
641 aName.Insert( 1, 'a' );
648 //=============================================================================
652 //=============================================================================
653 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
654 (SALOMEDS::Study_ptr theStudy,
655 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
656 Resource_DataMapOfAsciiStringAsciiString& theNames,
659 const TCollection_AsciiString& theSavedTrace)
661 TCollection_AsciiString helper; // to comfortably concatenate C strings
662 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
663 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
664 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
666 TCollection_AsciiString aScript;
667 aScript = "def RebuildData(theStudy):\n\t";
668 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
670 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
672 aScript += aSMESHGen + ".SetCurrentStudy(None)";
674 // import python files corresponding to plugins
675 set<string> moduleNameSet;
676 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
677 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
678 string moduleName = hyp_creator->second->GetModuleName();
679 bool newModule = moduleNameSet.insert( moduleName ).second;
681 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
684 // Dump trace of restored study
685 if (theSavedTrace.Length() > 0) {
686 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
687 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
688 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
690 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
691 if ( !isNewVersion ) {
692 TCollection_AsciiString aSavedTrace( theSavedTrace );
693 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
694 int beg, end = aSavedTrace.Length(), from = 1;
695 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
696 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
697 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
698 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
701 from = beg + aSmeshCall.Length();
703 aScript += helper + "\n" + aSavedTrace;
706 // append a saved trace to the script
707 aScript += helper + "\n" + theSavedTrace;
710 // Dump trace of API methods calls
711 TCollection_AsciiString aNewLines = GetNewPythonLines(theStudy->StudyId());
712 if (aNewLines.Length() > 0) {
713 aScript += helper + "\n" + aNewLines;
716 // Convert IDL API calls into smesh.py API.
717 // Some objects are wrapped with python classes and
718 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
719 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
720 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod );
722 // Find entries to be replaced by names
723 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
724 Standard_Integer aLen = aSeq->Length();
729 // Replace entries by the names
730 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
731 TColStd_SequenceOfAsciiString seqRemoved;
732 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
733 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
734 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
736 // Collect names of GEOM objects to exclude same names for SMESH objects
737 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
738 int ign = 0, nbgn = aGeomNames->length();
739 for (; ign < nbgn; ign++) {
740 aName = aGeomNames[ign];
741 theObjectNames.Bind(aName, "1");
744 bool importGeom = false;
745 for (Standard_Integer i = 1; i <= aLen; i += 2) {
746 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
747 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
749 aName = geom->GetDumpName( anEntry.ToCString() );
750 if (aName.IsEmpty()) {
752 if (theObjectNames.IsBound(anEntry)) {
753 // The Object is in Study
754 aName = theObjectNames.Find(anEntry);
755 // check validity of aName
756 bool isValidName = fixPythonName( aName );
757 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
758 // diff objects have same name - make a new name by appending a digit
759 TCollection_AsciiString aName2;
760 Standard_Integer i = 0;
762 aName2 = aName + "_" + ++i;
763 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
768 theObjectNames(anEntry) = aName;
773 aName = aBaseName + (++objectCounter);
774 } while (theObjectNames.IsBound(aName));
775 seqRemoved.Append(aName);
776 mapRemoved.Bind(anEntry, "1");
777 theObjectNames.Bind(anEntry, aName);
779 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
785 anUpdatedScript += aName;
786 aStart = aSeq->Value(i + 1) + 1;
789 // set initial part of aSript
790 TCollection_AsciiString initPart = "import salome, SMESH\n";
791 initPart += helper + "import " + aSmeshpy + "\n\n";
794 initPart += ("## import GEOM dump file ## \n"
795 "import string, os, sys, re\n"
796 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
797 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
799 anUpdatedScript.Insert ( 1, initPart );
801 // add final part of aScript
802 if (aSeq->Value(aLen) < aScriptLength)
803 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
806 SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
807 if( !CORBA::is_nil(aComp) )
809 SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
810 for( Itr->InitEx(true); Itr->More(); Itr->Next() )
812 SALOMEDS::SObject_var aSObj = Itr->Value();
813 SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
815 if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
817 CORBA::String_var anEntry = aSObj->GetID();
819 SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
821 SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
822 if( !CORBA::is_nil(aGroup) )
824 SALOMEDS::Color aColor = aGroup->GetColor();
825 if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
827 CORBA::String_var anEntry = aSObj->GetID();
828 anUpdatedScript += SMESH_Comment("\n\t")
829 << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
830 << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
836 // Remove removed objects
837 if ( seqRemoved.Length() > 0 ) {
838 anUpdatedScript += "\n\t## some objects were removed";
839 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
841 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
842 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
843 anUpdatedScript += seqRemoved.Value(ir);
844 // for object wrapped by class of smesh.py
845 anEntry = theObjectNames( seqRemoved.Value(ir) );
846 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
847 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
848 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
852 anUpdatedScript += "\n\t## set object names";
853 anUpdatedScript += helper + " \n\tisGUIMode = " + isPublished;
854 anUpdatedScript += "\n\tif isGUIMode and salome.sg.hasDesktop():";
855 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
856 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
857 // anUpdatedScript += "\n";
859 TCollection_AsciiString aGUIName;
860 Resource_DataMapOfAsciiStringAsciiString mapEntries;
861 for (Standard_Integer i = 1; i <= aLen; i += 2)
863 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
864 aName = geom->GetDumpName( anEntry.ToCString() );
865 if (aName.IsEmpty() && // Not a GEOM object
866 theNames.IsBound(anEntry) &&
867 !mapEntries.IsBound(anEntry) && // Not yet processed
868 !mapRemoved.IsBound(anEntry)) // Was not removed
870 aName = theObjectNames.Find(anEntry);
871 aGUIName = theNames.Find(anEntry);
872 mapEntries.Bind(anEntry, aName);
873 anUpdatedScript += helper + "\n\t\t" + aSmeshpy + ".SetName(" + aName;
874 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
875 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
876 anUpdatedScript += helper + ", '" + aGUIName + "')";
879 anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
881 anUpdatedScript += "\n\n\tpass\n";
883 // -----------------------------------------------------------------
884 // put string literals describing patterns into separate functions
885 // -----------------------------------------------------------------
887 TCollection_AsciiString aLongString, aFunctionType;
889 set< string > functionNameSet;
890 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
892 // make a python string literal
893 aLongString.Prepend(":\n\treturn '''\n");
894 aLongString += "\n\t'''\n\tpass\n";
896 TCollection_AsciiString functionName;
898 // check if the function returning this literal is already defined
899 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
900 if ( posAlready ) // already defined
902 // find the function name
903 int functBeg = posAlready;
904 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
905 while ( *script != ' ' ) {
909 functBeg++; // do not take ' '
910 posAlready--; // do not take ':'
911 functionName = anUpdatedScript.SubString( functBeg, posAlready );
913 else // not defined yet
915 // find a unique function name
916 fixPythonName( aFunctionType );
917 Standard_Integer nb = 0;
918 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
919 while ( !functionNameSet.insert( functionName.ToCString() ).second );
921 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
923 anUpdatedScript.InsertBefore( where, functionName ); // call function
928 return anUpdatedScript;
931 //=============================================================================
935 //=============================================================================
936 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
938 TCollection_AsciiString aScript;
940 // Dump trace of API methods calls
941 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
942 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
943 Standard_Integer istr, aLen = aPythonScript->Length();
944 for (istr = 1; istr <= aLen; istr++) {
946 aScript += aPythonScript->Value(istr);
954 //=============================================================================
958 //=============================================================================
959 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
961 TCollection_AsciiString aScript;
963 // Clean trace of API methods calls
964 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
965 myPythonScripts[theStudyID]->Clear();