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
22 // File : SMESH_DumpPython.cxx
23 // Created : Thu Mar 24 17:17:59 2005
24 // Author : Julia DOROVSKIKH
27 #include "SMESH_PythonDump.hxx"
28 #include "SMESH_Gen_i.hxx"
29 #include "SMESH_Filter_i.hxx"
30 #include "SMESH_MeshEditor_i.hxx"
31 #include "SMESH_2smeshpy.hxx"
33 #include <TColStd_HSequenceOfInteger.hxx>
34 #include <TCollection_AsciiString.hxx>
35 #include <SMESH_Comment.hxx>
39 static int MYDEBUG = 0;
41 static int MYDEBUG = 0;
44 static TCollection_AsciiString NotPublishedObjectName()
46 return "__NOT__Published__Object__";
52 size_t TPythonDump::myCounter = 0;
63 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
64 std::string aString = myStream.str();
65 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
66 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
67 if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
68 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
69 if(MYDEBUG) MESSAGE(aString);
76 operator<<(long int theArg){
83 operator<<(int theArg){
90 operator<<(double theArg){
97 operator<<(float theArg){
104 operator<<(const void* theArg){
111 operator<<(const char* theArg){
119 operator<<(const SMESH::ElementType& theArg)
123 case ALL: myStream<<"ALL";break;
124 case NODE: myStream<<"NODE";break;
125 case EDGE: myStream<<"EDGE";break;
126 case FACE: myStream<<"FACE";break;
127 case VOLUME:myStream<<"VOLUME";break;
134 operator<<(const SMESH::GeometryType& theArg)
138 case Geom_POINT: myStream<<"Geom_POINT"; break;
139 case Geom_EDGE: myStream<<"Geom_EDGE"; break;
140 case Geom_TRIANGLE: myStream<<"Geom_TRIANGLE"; break;
141 case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
142 case Geom_POLYGON: myStream<<"Geom_POLYGON"; break;
143 case Geom_TETRA: myStream<<"Geom_TETRA"; break;
144 case Geom_PYRAMID: myStream<<"Geom_PYRAMID"; break;
145 case Geom_HEXA: myStream<<"Geom_HEXA"; break;
146 case Geom_PENTA: myStream<<"Geom_PENTA"; break;
147 case Geom_POLYHEDRA: myStream<<"Geom_POLYHEDRA"; break;
152 template<class TArray>
153 void DumpArray(const TArray& theArray, TPythonDump & theStream)
156 for (int i = 1; i <= theArray.length(); i++) {
157 theStream << theArray[i-1];
158 if ( i < theArray.length() )
165 TPythonDump::operator<<(const SMESH::long_array& theArg)
167 DumpArray( theArg, *this );
172 TPythonDump::operator<<(const SMESH::double_array& theArg)
174 DumpArray( theArg, *this );
180 operator<<(SALOMEDS::SObject_ptr aSObject)
182 if ( !aSObject->_is_nil() )
183 myStream << aSObject->GetID();
185 myStream << NotPublishedObjectName();
191 operator<<(CORBA::Object_ptr theArg)
193 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
194 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
195 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
196 if(!aSObject->_is_nil()) {
197 CORBA::String_var id = aSObject->GetID();
199 } else if ( !CORBA::is_nil(theArg)) {
200 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
201 myStream << "smeshObj_" << size_t(theArg);
203 myStream << NotPublishedObjectName();
212 operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
214 SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
215 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
216 if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
217 myStream << "hyp_" << theArg->GetId();
219 *this << CORBA::Object_ptr( theArg );
225 operator<<(SMESH::SMESH_IDSource_ptr theArg)
227 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
228 SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
229 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
230 if(!aSObject->_is_nil() || CORBA::is_nil( theArg ))
231 return *this << aSObject;
232 SMESH::long_array_var anElementsId = theArg->GetIDs();
233 SMESH::SMESH_Mesh_var mesh = theArg->GetMesh();
234 SMESH::array_of_ElementType_var types = theArg->GetTypes();
235 SMESH::ElementType type = types->length() ? types[0] : SMESH::ALL;
236 return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
241 operator<<(SMESH::FilterLibrary_i* theArg)
243 myStream<<"aFilterLibrary"<<theArg;
249 operator<<(SMESH::FilterManager_i* theArg)
251 myStream<<"aFilterManager";
257 operator<<(SMESH::Filter_i* theArg)
259 myStream<<"aFilter"<<theArg;
265 operator<<(SMESH::Functor_i* theArg)
268 FunctorType aFunctorType = theArg->GetFunctorType();
269 switch(aFunctorType){
270 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
271 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
272 case FT_Warping: myStream<< "aWarping"; break;
273 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
274 case FT_Taper: myStream<< "aTaper"; break;
275 case FT_Skew: myStream<< "aSkew"; break;
276 case FT_Area: myStream<< "aArea"; break;
277 case FT_Volume3D: myStream<< "aVolume3D"; break;
278 case FT_MaxElementLength2D: myStream<< "aMaxElementLength2D"; break;
279 case FT_MaxElementLength3D: myStream<< "aMaxElementLength3D"; break;
280 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
281 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
282 case FT_FreeNodes: myStream<< "aFreeNodes"; break;
283 case FT_FreeFaces: myStream<< "aFreeFaces"; break;
284 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
285 case FT_MultiConnection2D: myStream<< "aMultiConnection2D"; break;
286 case FT_Length: myStream<< "aLength"; break;
287 case FT_Length2D: myStream<< "aLength2D"; break;
288 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
289 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
290 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
291 case FT_BelongToGenSurface: myStream<< "aBelongToGenSurface"; break;
292 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
293 case FT_CoplanarFaces: myStream<< "aCoplanarFaces"; break;
294 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
295 case FT_BadOrientedVolume: myStream<< "aBadOrientedVolume"; break;
296 case FT_BareBorderVolume: myStream<< "aBareBorderVolume"; break;
297 case FT_BareBorderFace: myStream<< "aBareBorderFace"; break;
298 case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
299 case FT_OverConstrainedFace: myStream<< "aOverConstrainedFace"; break;
300 case FT_LinearOrQuadratic: myStream<< "aLinearOrQuadratic"; break;
301 case FT_GroupColor: myStream<< "aGroupColor"; break;
302 case FT_ElemGeomType: myStream<< "anElemGeomType"; break;
303 case FT_LessThan: myStream<< "aLessThan"; break;
304 case FT_MoreThan: myStream<< "aMoreThan"; break;
305 case FT_EqualTo: myStream<< "anEqualTo"; break;
306 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
307 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
308 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
310 default: myStream<< "anUndefined"; break;
319 operator<<(SMESH::Measurements_i* theArg)
321 myStream<<"aMeasurements";
326 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
328 myStream << SMESHGenName(); return *this;
331 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
333 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
336 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
338 myStream << theStr; return *this;
342 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
344 switch (theVersion) {
345 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
346 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
347 default: myStream << theVersion;
352 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
354 myStream << "SMESH.AxisStruct( "
358 << theAxis.vx << ", "
359 << theAxis.vy << ", "
360 << theAxis.vz << " )";
364 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
366 const SMESH::PointStruct & P = theDir.PS;
367 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
374 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
376 DumpArray( theList, *this );
379 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
381 DumpArray( *theList, *this );
384 TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
386 DumpArray( theList, *this );
390 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
391 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
393 //================================================================================
395 * \brief Return marker of long string literal beginning
396 * \param type - a name of functionality producing the string literal
397 * \retval TCollection_AsciiString - the marker string to be written into
398 * a raw python script
400 //================================================================================
402 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
406 (Standard_Integer) strlen(type) +
411 //================================================================================
413 * \brief Return marker of long string literal end
414 * \retval TCollection_AsciiString - the marker string to be written into
415 * a raw python script
417 //================================================================================
419 TCollection_AsciiString TPythonDump::LongStringEnd()
421 return myLongStringEnd;
424 //================================================================================
426 * \brief Cut out a long string literal from a string
427 * \param theText - text possibly containing string literals
428 * \param theFrom - position in the text to search from
429 * \param theLongString - the retrieved literal
430 * \param theStringType - a name of functionality produced the literal
431 * \retval bool - true if a string literal found
433 * The literal is removed from theText; theFrom points position right after
434 * the removed literal
436 //================================================================================
438 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
440 TCollection_AsciiString & theLongString,
441 TCollection_AsciiString & theStringType)
443 if ( theFrom < 1 || theFrom > theText.Length() )
446 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
447 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
448 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
451 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
455 // find where literal begins
456 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
457 char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
458 int typeLen = atoi ( typeLenStr ); // = 7
459 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
460 literalBeg++; // 26 -> 27
463 literalBeg += typeLen + 1; // = 35
464 if ( literalBeg > theText.Length() )
467 // where literal ends (i.e. end marker begins)
468 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
470 literalEnd = theText.Length();
473 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
475 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
477 literalEnd += myLongStringEnd.Length(); // = 79
478 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
479 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
485 //=======================================================================
486 //function : DumpPython
488 //=======================================================================
489 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
490 CORBA::Boolean isPublished,
491 CORBA::Boolean& isValidScript)
493 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
494 if (CORBA::is_nil(aStudy))
495 return new Engines::TMPFile(0);
497 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
498 if (CORBA::is_nil(aSO))
499 return new Engines::TMPFile(0);
501 // Map study entries to object names
502 Resource_DataMapOfAsciiStringAsciiString aMap;
503 Resource_DataMapOfAsciiStringAsciiString aMapNames;
504 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
506 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
507 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
508 SALOMEDS::SObject_var aValue = Itr->Value();
509 CORBA::String_var anID = aValue->GetID();
510 CORBA::String_var aName = aValue->GetName();
511 TCollection_AsciiString aGUIName ( (char*) aName.in() );
512 TCollection_AsciiString anEnrty ( (char*) anID.in() );
513 if (aGUIName.Length() > 0) {
514 aMapNames.Bind( anEnrty, aGUIName );
515 aMap.Bind( anEnrty, aGUIName );
519 // Get trace of restored study
520 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
521 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
522 SALOMEDS::GenericAttribute_var anAttr =
523 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
525 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
526 TCollection_AsciiString aSavedTrace (oldValue);
528 // Add trace of API methods calls and replace study entries by names
529 TCollection_AsciiString aScript;
530 aScript += DumpPython_impl(aStudy, aMap, aMapNames,
531 isPublished, isValidScript, aSavedTrace);
533 int aLen = aScript.Length();
534 unsigned char* aBuffer = new unsigned char[aLen+1];
535 strcpy((char*)aBuffer, aScript.ToCString());
537 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
538 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
540 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
541 isValidScript = isValidScript && !hasNotPublishedObjects;
543 return aStreamFile._retn();
546 //=============================================================================
550 //=============================================================================
551 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
553 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
554 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
556 myPythonScripts[theStudyID]->Append(theString);
559 //=============================================================================
561 * RemoveLastFromPythonScript
563 //=============================================================================
564 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
566 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
567 int aLen = myPythonScripts[theStudyID]->Length();
568 myPythonScripts[theStudyID]->Remove(aLen);
572 //=======================================================================
573 //function : SavePython
575 //=======================================================================
576 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
578 // Dump trace of API methods calls
579 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
581 // Check contents of PythonObject attribute
582 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
583 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
584 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
585 SALOMEDS::GenericAttribute_var anAttr =
586 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
588 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
589 TCollection_AsciiString oldScript (oldValue);
591 if (oldScript.Length() > 0) {
593 oldScript += aScript;
598 // Store in PythonObject attribute
599 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
601 // Clean trace of API methods calls
602 CleanPythonTrace(theStudy->StudyId());
609 //=============================================================================
611 * FindEntries: Returns a sequence of start/end positions of entries in the string
613 //=============================================================================
614 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
616 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
617 Standard_Integer aLen = theString.Length();
618 Standard_Boolean isFound = Standard_False;
620 char* arr = (char*) theString.ToCString();
621 Standard_Integer i = 0, j;
626 if ( isdigit( c )) { //Is digit?
628 isFound = Standard_False;
629 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
631 if(c == ':') isFound = Standard_True;
635 int prev = (i < 1) ? 0 : (int)arr[i - 1];
636 // to distinguish from a sketcher command:
637 // last char should be a digit, not ":",
638 // previous char should not be '"'.
639 if (arr[j-2] != ':' && prev != '"') {
640 aSeq->Append(i+1); // +1 because AsciiString starts from 1
654 //================================================================================
656 * \brief Make a string be a valid python name
657 * \param aName - a string to fix
658 * \retval bool - true if aName was not modified
660 //================================================================================
662 bool fixPythonName(TCollection_AsciiString & aName )
664 const TCollection_AsciiString allowedChars =
665 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
666 bool isValidName = true;
667 int p=1; // replace not allowed chars with underscore
668 while (p <= aName.Length() &&
669 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
671 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
672 aName.Remove( p, 1 ); // remove double _ and from the start and the end
674 aName.SetValue(p, '_');
677 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
678 aName.Insert( 1, 'a' );
685 //=============================================================================
689 //=============================================================================
690 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
691 (SALOMEDS::Study_ptr theStudy,
692 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
693 Resource_DataMapOfAsciiStringAsciiString& theNames,
696 const TCollection_AsciiString& theSavedTrace)
698 int aStudyID = theStudy->StudyId();
700 TCollection_AsciiString helper; // to comfortably concatenate C strings
701 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
702 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
703 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
705 TCollection_AsciiString aScript;
706 aScript = "def RebuildData(theStudy):\n\t";
707 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
708 aScript += helper + "aMeasurements = " + aSMESHGen + ".CreateMeasurements()\n\t";
710 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
712 aScript += aSMESHGen + ".SetCurrentStudy(None)";
714 // import python files corresponding to plugins
715 set<string> moduleNameSet;
716 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
717 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
718 string moduleName = hyp_creator->second->GetModuleName();
719 bool newModule = moduleNameSet.insert( moduleName ).second;
721 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
724 // Dump trace of restored study
725 if (theSavedTrace.Length() > 0) {
726 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
727 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
728 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
730 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
731 if ( !isNewVersion ) {
732 TCollection_AsciiString aSavedTrace( theSavedTrace );
733 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
734 int beg, end = aSavedTrace.Length(), from = 1;
735 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
736 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
737 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
738 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
741 from = beg + aSmeshCall.Length();
743 aScript += helper + "\n" + aSavedTrace;
746 // append a saved trace to the script
747 aScript += helper + "\n" + theSavedTrace;
750 // Dump trace of API methods calls
751 TCollection_AsciiString aNewLines = GetNewPythonLines(aStudyID);
752 if (aNewLines.Length() > 0) {
753 aScript += helper + "\n" + aNewLines;
756 // Convert IDL API calls into smesh.py API.
757 // Some objects are wrapped with python classes and
758 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
759 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
760 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod, theObjectNames );
762 // Find entries to be replaced by names
763 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
764 Standard_Integer aLen = aSeq->Length();
769 // Replace entries by the names
770 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
771 TColStd_SequenceOfAsciiString seqRemoved;
772 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
773 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
774 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
776 // Collect names of GEOM objects to exclude same names for SMESH objects
777 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
778 int ign = 0, nbgn = aGeomNames->length();
779 for (; ign < nbgn; ign++) {
780 aName = aGeomNames[ign];
781 theObjectNames.Bind(aName, "1");
784 bool importGeom = false;
785 for (Standard_Integer i = 1; i <= aLen; i += 2) {
786 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
787 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
789 aName = geom->GetDumpName( anEntry.ToCString() );
790 if (aName.IsEmpty()) {
792 if (theObjectNames.IsBound(anEntry)) {
793 // The Object is in Study
794 aName = theObjectNames.Find(anEntry);
795 // check validity of aName
796 bool isValidName = fixPythonName( aName );
797 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
798 // diff objects have same name - make a new name by appending a digit
799 TCollection_AsciiString aName2;
800 Standard_Integer i = 0;
802 aName2 = aName + "_" + ++i;
803 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
808 theObjectNames(anEntry) = aName;
813 aName = aBaseName + (++objectCounter);
814 } while (theObjectNames.IsBound(aName));
815 seqRemoved.Append(aName);
816 mapRemoved.Bind(anEntry, "1");
817 theObjectNames.Bind(anEntry, aName);
819 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
825 anUpdatedScript += aName;
826 aStart = aSeq->Value(i + 1) + 1;
829 // set initial part of aSript
830 TCollection_AsciiString initPart = "import salome, SMESH, SALOMEDS\n";
831 initPart += helper + "import " + aSmeshpy + "\n\n";
834 initPart += ("## import GEOM dump file ## \n"
835 "import string, os, sys, re\n"
836 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
837 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
839 anUpdatedScript.Insert ( 1, initPart );
841 // add final part of aScript
842 if (aSeq->Value(aLen) < aScriptLength)
843 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
846 SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
847 if( !CORBA::is_nil(aComp) )
849 SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
850 for( Itr->InitEx(true); Itr->More(); Itr->Next() )
852 SALOMEDS::SObject_var aSObj = Itr->Value();
853 SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
855 if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
857 CORBA::String_var anEntry = aSObj->GetID();
859 SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
861 SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
862 if( !CORBA::is_nil(aGroup) )
864 SALOMEDS::Color aColor = aGroup->GetColor();
865 if ( aColor.R >= 0 || aColor.G >= 0 || aColor.B >= 0 )
867 CORBA::String_var anEntry = aSObj->GetID();
868 anUpdatedScript += SMESH_Comment("\n\t")
869 << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
870 << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
876 // Remove removed objects
877 if ( seqRemoved.Length() > 0 ) {
878 anUpdatedScript += "\n\t## some objects were removed";
879 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
881 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
882 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
883 anUpdatedScript += seqRemoved.Value(ir);
884 // for object wrapped by class of smesh.py
885 anEntry = theObjectNames( seqRemoved.Value(ir) );
886 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
887 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
888 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
892 anUpdatedScript += "\n\t## set object names";
893 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
894 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
895 // anUpdatedScript += "\n";
897 TCollection_AsciiString aGUIName;
898 Resource_DataMapOfAsciiStringAsciiString mapEntries;
899 for (Standard_Integer i = 1; i <= aLen; i += 2)
901 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
902 aName = geom->GetDumpName( anEntry.ToCString() );
903 if (aName.IsEmpty() && // Not a GEOM object
904 theNames.IsBound(anEntry) &&
905 !mapEntries.IsBound(anEntry) && // Not yet processed
906 !mapRemoved.IsBound(anEntry)) // Was not removed
908 aName = theObjectNames.Find(anEntry);
909 aGUIName = theNames.Find(anEntry);
910 mapEntries.Bind(anEntry, aName);
911 anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
912 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
913 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
914 anUpdatedScript += helper + ", '" + aGUIName + "')";
917 anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
918 anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
920 // -----------------------------------------------------------------
921 // store visual properties of displayed objects
922 // -----------------------------------------------------------------
926 //Output the script that sets up the visual parameters.
927 char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
928 if (script && strlen(script) > 0) {
929 anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
930 anUpdatedScript += script;
931 CORBA::string_free(script);
934 anUpdatedScript += "\n\n\tpass\n";
936 // -----------------------------------------------------------------
937 // put string literals describing patterns into separate functions
938 // -----------------------------------------------------------------
940 TCollection_AsciiString aLongString, aFunctionType;
942 set< string > functionNameSet;
943 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
945 // make a python string literal
946 aLongString.Prepend(":\n\treturn '''\n");
947 aLongString += "\n\t'''\n\tpass\n";
949 TCollection_AsciiString functionName;
951 // check if the function returning this literal is already defined
952 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
953 if ( posAlready ) // already defined
955 // find the function name
956 int functBeg = posAlready;
957 char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
958 while ( *script != ' ' ) {
962 functBeg++; // do not take ' '
963 posAlready--; // do not take ':'
964 functionName = anUpdatedScript.SubString( functBeg, posAlready );
966 else // not defined yet
968 // find a unique function name
969 fixPythonName( aFunctionType );
970 Standard_Integer nb = 0;
971 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
972 while ( !functionNameSet.insert( functionName.ToCString() ).second );
974 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
976 anUpdatedScript.InsertBefore( where, functionName ); // call function
981 return anUpdatedScript;
984 //=============================================================================
988 //=============================================================================
989 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
991 TCollection_AsciiString aScript;
993 // Dump trace of API methods calls
994 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
995 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
996 Standard_Integer istr, aLen = aPythonScript->Length();
997 for (istr = 1; istr <= aLen; istr++) {
999 aScript += aPythonScript->Value(istr);
1007 //=============================================================================
1011 //=============================================================================
1012 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1014 TCollection_AsciiString aScript;
1016 // Clean trace of API methods calls
1017 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1018 myPythonScripts[theStudyID]->Clear();