1 // Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
9 // This library is distributed in the hope that it will be useful
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : SMESH_Gen_i_DumpPython.cxx
21 // Created : Thu Mar 24 17:17:59 2005
22 // Author : Julia DOROVSKIKH
26 #include "SMESH_PythonDump.hxx"
27 #include "SMESH_Gen_i.hxx"
28 #include "SMESH_Filter_i.hxx"
29 #include "SMESH_MeshEditor_i.hxx"
30 #include "SMESH_2smeshpy.hxx"
32 #include <TColStd_HSequenceOfInteger.hxx>
33 #include <TCollection_AsciiString.hxx>
34 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
38 static int MYDEBUG = 0;
40 static int MYDEBUG = 0;
43 static TCollection_AsciiString NotPublishedObjectName()
45 return "__NOT__Published__Object__";
51 size_t TPythonDump::myCounter = 0;
62 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
63 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
64 if(!aStudy->_is_nil()){
65 std::string aString = myStream.str();
66 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
67 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
68 if(MYDEBUG) MESSAGE(aString);
75 operator<<(long int theArg){
82 operator<<(int theArg){
89 operator<<(double theArg){
96 operator<<(float theArg){
103 operator<<(const void* theArg){
110 operator<<(const char* theArg){
118 operator<<(const SMESH::ElementType& theArg)
122 case ALL: myStream<<"ALL";break;
123 case NODE: myStream<<"NODE";break;
124 case EDGE: myStream<<"EDGE";break;
125 case FACE: myStream<<"FACE";break;
126 case VOLUME:myStream<<"VOLUME";break;
131 template<class TArray>
132 void DumpArray(const TArray& theArray, std::ostringstream & theStream)
135 for (int i = 1; i <= theArray.length(); i++) {
136 theStream << theArray[i-1];
137 if ( i < theArray.length() )
144 TPythonDump::operator<<(const SMESH::long_array& theArg)
146 DumpArray( theArg, myStream );
151 TPythonDump::operator<<(const SMESH::double_array& theArg)
153 DumpArray( theArg, myStream );
159 operator<<(SALOMEDS::SObject_ptr aSObject)
161 if ( !aSObject->_is_nil() )
162 myStream << aSObject->GetID();
164 myStream << NotPublishedObjectName();
170 operator<<(CORBA::Object_ptr theArg)
172 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
173 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
174 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
175 if(!aSObject->_is_nil()) {
176 myStream << aSObject->GetID();
177 } else if ( !CORBA::is_nil(theArg)) {
178 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
179 myStream << "smeshObj_" << size_t(theArg);
181 myStream << NotPublishedObjectName();
190 operator<<(SMESH::FilterLibrary_i* theArg)
192 myStream<<"aFilterLibrary"<<theArg;
198 operator<<(SMESH::FilterManager_i* theArg)
200 myStream<<"aFilterManager";
206 operator<<(SMESH::Filter_i* theArg)
208 myStream<<"aFilter"<<theArg;
214 operator<<(SMESH::Functor_i* theArg)
217 FunctorType aFunctorType = theArg->GetFunctorType();
218 switch(aFunctorType){
219 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
220 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
221 case FT_Warping: myStream<< "aWarping"; break;
222 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
223 case FT_Taper: myStream<< "aTaper"; break;
224 case FT_Skew: myStream<< "aSkew"; break;
225 case FT_Area: myStream<< "aArea"; break;
226 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
227 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
228 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
229 case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
230 case FT_Length: myStream<< "aLength"; break;
231 case FT_Length2D: myStream<< "aLength"; break;
232 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
233 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
234 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
235 case FT_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
236 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
237 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
238 case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
239 case FT_LessThan: myStream<< "aLessThan"; break;
240 case FT_MoreThan: myStream<< "aMoreThan"; break;
241 case FT_EqualTo: myStream<< "anEqualTo"; break;
242 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
243 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
244 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
245 case FT_Undefined: myStream<< "anUndefined"; break;
252 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
254 myStream << SMESHGenName(); return *this;
257 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
259 myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
262 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
264 myStream << theStr; return *this;
268 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
270 switch (theVersion) {
271 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
272 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
273 default: myStream << theVersion;
278 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
280 myStream << "SMESH.AxisStruct( "
284 << theAxis.vx << ", "
285 << theAxis.vy << ", "
286 << theAxis.vz << " )";
290 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
292 const SMESH::PointStruct & P = theDir.PS;
293 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
300 TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
301 TCollection_AsciiString myLongStringEnd ( "TPythonDump::LongStringEnd" );
303 //================================================================================
305 * \brief Return marker of long string literal beginning
306 * \param type - a name of functionality producing the string literal
307 * \retval TCollection_AsciiString - the marker string to be written into
308 * a raw python script
310 //================================================================================
312 TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
316 (Standard_Integer) strlen(type) +
321 //================================================================================
323 * \brief Return marker of long string literal end
324 * \retval TCollection_AsciiString - the marker string to be written into
325 * a raw python script
327 //================================================================================
329 TCollection_AsciiString TPythonDump::LongStringEnd()
331 return myLongStringEnd;
334 //================================================================================
336 * \brief Cut out a long string literal from a string
337 * \param theText - text possibly containing string literals
338 * \param theFrom - position in the text to search from
339 * \param theLongString - the retrieved literal
340 * \param theStringType - a name of functionality produced the literal
341 * \retval bool - true if a string literal found
343 * The literal is removed from theText; theFrom points position right after
344 * the removed literal
346 //================================================================================
348 bool TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
350 TCollection_AsciiString & theLongString,
351 TCollection_AsciiString & theStringType)
353 if ( theFrom < 1 || theFrom > theText.Length() )
356 // ...script \ beg marker \ \ type \ literal \ end marker \ script...
357 // "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
358 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
361 theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
365 // find where literal begins
366 int literalBeg = theFrom + myLongStringStart.Length(); // = 26
367 char* typeLenStr = theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
368 int typeLen = atoi ( typeLenStr ); // = 7
369 while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
370 literalBeg++; // 26 -> 27
373 literalBeg += typeLen + 1; // = 35
374 if ( literalBeg > theText.Length() )
377 // where literal ends (i.e. end marker begins)
378 int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
380 literalEnd = theText.Length();
383 theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
385 theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
387 literalEnd += myLongStringEnd.Length(); // = 79
388 TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
389 theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
395 //=======================================================================
396 //function : DumpPython
398 //=======================================================================
399 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
400 CORBA::Boolean isPublished,
401 CORBA::Boolean& isValidScript)
403 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
404 if (CORBA::is_nil(aStudy))
405 return new Engines::TMPFile(0);
407 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
408 if (CORBA::is_nil(aSO))
409 return new Engines::TMPFile(0);
411 // Map study entries to object names
412 Resource_DataMapOfAsciiStringAsciiString aMap;
413 Resource_DataMapOfAsciiStringAsciiString aMapNames;
414 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
416 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
417 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
418 SALOMEDS::SObject_var aValue = Itr->Value();
419 CORBA::String_var anID = aValue->GetID();
420 CORBA::String_var aName = aValue->GetName();
421 TCollection_AsciiString aGUIName ( (char*) aName.in() );
422 TCollection_AsciiString anEnrty ( (char*) anID.in() );
423 if (aGUIName.Length() > 0) {
424 aMapNames.Bind( anEnrty, aGUIName );
425 aMap.Bind( anEnrty, aGUIName );
429 // Get trace of restored study
430 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
431 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
432 SALOMEDS::GenericAttribute_var anAttr =
433 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
435 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
436 TCollection_AsciiString aSavedTrace (oldValue);
438 // Add trace of API methods calls and replace study entries by names
439 TCollection_AsciiString aScript =
440 "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
441 aScript += DumpPython_impl(aStudy->StudyId(), aMap, aMapNames,
442 isPublished, isValidScript, aSavedTrace);
444 //inserting export for Object Names
445 TCollection_AsciiString def = "def RebuildData(theStudy):\n";
446 int pos = aScript.Search( def );
449 //insert global definition
450 TCollection_AsciiString glob;
451 for( Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString It(aMap);
452 It.More(); It.Next() )
454 TCollection_AsciiString name = It.Value();
456 if ( !name.IsEmpty() && name.Search(' ') == -1 && name.Search( ':' ) == -1
457 && !name.IsIntegerValue() && !name.IsEqual("Hypotheses") && !name.IsEqual("Algorithms") )
459 if ( glob.Length() > 0 )
464 if ( glob.Length() > 0 )
466 glob.Prepend( "\tglobal " );
470 aScript.Insert( pos + def.Length(), glob );
473 int aLen = aScript.Length();
474 unsigned char* aBuffer = new unsigned char[aLen+1];
475 strcpy((char*)aBuffer, aScript.ToCString());
477 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
478 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
480 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
481 isValidScript = isValidScript && !hasNotPublishedObjects;
483 return aStreamFile._retn();
486 //=============================================================================
490 //=============================================================================
491 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
493 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
494 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
496 myPythonScripts[theStudyID]->Append(theString);
499 //=============================================================================
501 * RemoveLastFromPythonScript
503 //=============================================================================
504 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
506 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
507 int aLen = myPythonScripts[theStudyID]->Length();
508 myPythonScripts[theStudyID]->Remove(aLen);
512 //=======================================================================
513 //function : SavePython
515 //=======================================================================
516 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
518 // Dump trace of API methods calls
519 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
521 // Check contents of PythonObject attribute
522 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
523 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
524 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
525 SALOMEDS::GenericAttribute_var anAttr =
526 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
528 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
529 TCollection_AsciiString oldScript (oldValue);
531 if (oldScript.Length() > 0) {
533 oldScript += aScript;
538 // Store in PythonObject attribute
539 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
541 // Clean trace of API methods calls
542 CleanPythonTrace(theStudy->StudyId());
549 //=============================================================================
551 * FindEntries: Returns a sequence of start/end positions of entries in the string
553 //=============================================================================
554 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
556 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
557 Standard_Integer aLen = theString.Length();
558 Standard_Boolean isFound = Standard_False;
560 char* arr = theString.ToCString();
561 Standard_Integer i = 0, j;
566 if ( isdigit( c )) { //Is digit?
568 isFound = Standard_False;
569 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
571 if(c == ':') isFound = Standard_True;
575 int prev = (i < 1) ? 0 : (int)arr[i - 1];
576 // to distinguish from a sketcher command:
577 // last char should be a digit, not ":",
578 // previous char should not be '"'.
579 if (arr[j-2] != ':' && prev != '"') {
580 aSeq->Append(i+1); // +1 because AsciiString starts from 1
594 //================================================================================
596 * \brief Make a string be a valid python name
597 * \param aName - a string to fix
598 * \retval bool - true if aName was not modified
600 //================================================================================
602 bool fixPythonName(TCollection_AsciiString & aName )
604 const TCollection_AsciiString allowedChars =
605 "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
606 bool isValidName = true;
607 int p=1; // replace not allowed chars with underscore
608 while (p <= aName.Length() &&
609 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
611 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
612 aName.Remove( p, 1 ); // remove double _ and from the start and the end
614 aName.SetValue(p, '_');
617 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
618 aName.Insert( 1, 'a' );
625 //=============================================================================
629 //=============================================================================
630 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
632 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
633 Resource_DataMapOfAsciiStringAsciiString& theNames,
636 const TCollection_AsciiString& theSavedTrace)
638 TCollection_AsciiString helper; // to comfortably concatenate C strings
639 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
640 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
641 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
643 TCollection_AsciiString aScript;
644 aScript = "def RebuildData(theStudy):\n\t";
645 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
647 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
649 aScript += aSMESHGen + ".SetCurrentStudy(None)";
651 // import python files corresponding to plugins
652 set<string> moduleNameSet;
653 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
654 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
655 string moduleName = hyp_creator->second->GetModuleName();
656 bool newModule = moduleNameSet.insert( moduleName ).second;
658 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
661 // Dump trace of restored study
662 if (theSavedTrace.Length() > 0) {
663 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
664 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
665 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
667 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
668 if ( !isNewVersion ) {
669 TCollection_AsciiString aSavedTrace( theSavedTrace );
670 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
671 int beg, end = aSavedTrace.Length(), from = 1;
672 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
673 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
674 if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
675 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
678 from = beg + aSmeshCall.Length();
680 aScript += helper + "\n" + aSavedTrace;
683 // append a saved trace to the script
684 aScript += helper + "\n" + theSavedTrace;
687 // Dump trace of API methods calls
688 TCollection_AsciiString aNewLines = GetNewPythonLines(theStudyID);
689 if (aNewLines.Length() > 0) {
690 aScript += helper + "\n" + aNewLines;
693 // Convert IDL API calls into smesh.py API.
694 // Some objects are wrapped with python classes and
695 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
696 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
697 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod );
699 // Find entries to be replaced by names
700 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
701 Standard_Integer aLen = aSeq->Length();
706 // Replace entries by the names
707 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
708 TColStd_SequenceOfAsciiString seqRemoved;
709 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
710 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
711 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
713 // Collect names of GEOM objects to exclude same names for SMESH objects
714 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
715 int ign = 0, nbgn = aGeomNames->length();
716 for (; ign < nbgn; ign++) {
717 aName = aGeomNames[ign];
718 theObjectNames.Bind(aName, "1");
721 bool importGeom = false;
722 for (Standard_Integer i = 1; i <= aLen; i += 2) {
723 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
724 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
726 aName = geom->GetDumpName( anEntry.ToCString() );
727 if (aName.IsEmpty()) {
729 if (theObjectNames.IsBound(anEntry)) {
730 // The Object is in Study
731 aName = theObjectNames.Find(anEntry);
732 // check validity of aName
733 bool isValidName = fixPythonName( aName );
734 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
735 // diff objects have same name - make a new name by appending a digit
736 TCollection_AsciiString aName2;
737 Standard_Integer i = 0;
739 aName2 = aName + "_" + ++i;
740 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
745 theObjectNames(anEntry) = aName;
750 aName = aBaseName + (++objectCounter);
751 } while (theObjectNames.IsBound(aName));
752 seqRemoved.Append(aName);
753 mapRemoved.Bind(anEntry, "1");
754 theObjectNames.Bind(anEntry, aName);
756 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
762 anUpdatedScript += aName;
763 aStart = aSeq->Value(i + 1) + 1;
766 // set initial part of aSript
767 TCollection_AsciiString initPart = "import salome, SMESH\n";
768 initPart += helper + "import " + aSmeshpy + "\n\n";
771 initPart += ("## import GEOM dump file ## \n"
772 "import string, os, sys, re\n"
773 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
774 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
776 anUpdatedScript.Insert ( 1, initPart );
778 // add final part of aScript
779 if (aSeq->Value(aLen) < aScriptLength)
780 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
782 // Remove removed objects
783 if ( seqRemoved.Length() > 0 ) {
784 anUpdatedScript += "\n\t## some objects were removed";
785 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
787 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
788 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
789 anUpdatedScript += seqRemoved.Value(ir);
790 // for object wrapped by class of smesh.py
791 anEntry = theObjectNames( seqRemoved.Value(ir) );
792 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
793 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
794 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
798 anUpdatedScript += "\n\t## set object names";
799 anUpdatedScript += helper + " \n\tisGUIMode = " + isPublished;
800 anUpdatedScript += "\n\tif isGUIMode and salome.sg.hasDesktop():";
801 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
802 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
803 // anUpdatedScript += "\n";
805 TCollection_AsciiString aGUIName;
806 Resource_DataMapOfAsciiStringAsciiString mapEntries;
807 for (Standard_Integer i = 1; i <= aLen; i += 2)
809 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
810 aName = geom->GetDumpName( anEntry.ToCString() );
811 if (aName.IsEmpty() && // Not a GEOM object
812 theNames.IsBound(anEntry) &&
813 !mapEntries.IsBound(anEntry) && // Not yet processed
814 !mapRemoved.IsBound(anEntry)) // Was not removed
816 aName = theObjectNames.Find(anEntry);
817 aGUIName = theNames.Find(anEntry);
818 mapEntries.Bind(anEntry, aName);
819 anUpdatedScript += helper + "\n\t\t" + aSmeshpy + ".SetName(" + aName;
820 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
821 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
822 anUpdatedScript += helper + ", '" + aGUIName + "')";
825 anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
827 anUpdatedScript += "\n\n\tpass\n";
829 // -----------------------------------------------------------------
830 // put string literals describing patterns into separate functions
831 // -----------------------------------------------------------------
833 TCollection_AsciiString aLongString, aFunctionType;
835 set< string > functionNameSet;
836 while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
838 // make a python string literal
839 aLongString.Prepend(":\n\treturn '''\n");
840 aLongString += "\n\t'''\n\tpass\n";
842 TCollection_AsciiString functionName;
844 // check if the function returning this literal is already defined
845 int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
846 if ( posAlready ) // already defined
848 // find the function name
849 int functBeg = posAlready;
850 char* script = anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
851 while ( *script != ' ' ) {
855 functBeg++; // do not take ' '
856 posAlready--; // do not take ':'
857 functionName = anUpdatedScript.SubString( functBeg, posAlready );
859 else // not defined yet
861 // find a unique function name
862 fixPythonName( aFunctionType );
863 Standard_Integer nb = 0;
864 do functionName = aFunctionType + "_" + ( nb++ ) + "()";
865 while ( !functionNameSet.insert( functionName.ToCString() ).second );
867 anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
869 anUpdatedScript.InsertBefore( where, functionName ); // call function
874 return anUpdatedScript;
877 //=============================================================================
881 //=============================================================================
882 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
884 TCollection_AsciiString aScript;
886 // Dump trace of API methods calls
887 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
888 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
889 Standard_Integer istr, aLen = aPythonScript->Length();
890 for (istr = 1; istr <= aLen; istr++) {
892 aScript += aPythonScript->Value(istr);
900 //=============================================================================
904 //=============================================================================
905 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
907 TCollection_AsciiString aScript;
909 // Clean trace of API methods calls
910 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
911 myPythonScripts[theStudyID]->Clear();