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/
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_2smeshpy.hxx"
31 #include <TColStd_HSequenceOfInteger.hxx>
32 #include <TCollection_AsciiString.hxx>
36 static int MYDEBUG = 0;
38 static int MYDEBUG = 0;
41 static TCollection_AsciiString NotPublishedObjectName()
43 return "__NOT__Published__Object__";
49 size_t TPythonDump::myCounter = 0;
60 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
61 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
62 if(!aStudy->_is_nil()){
63 std::string aString = myStream.str();
64 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
65 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
66 if(MYDEBUG) MESSAGE(aString);
73 operator<<(long int theArg){
80 operator<<(int theArg){
87 operator<<(double theArg){
94 operator<<(float theArg){
101 operator<<(const void* theArg){
108 operator<<(const char* theArg){
116 operator<<(const SMESH::ElementType& theArg)
120 case ALL: myStream<<"ALL";break;
121 case NODE: myStream<<"NODE";break;
122 case EDGE: myStream<<"EDGE";break;
123 case FACE: myStream<<"FACE";break;
124 case VOLUME:myStream<<"VOLUME";break;
129 template<class TArray>
130 void DumpArray(const TArray& theArray, std::ostringstream & theStream)
133 for (int i = 1; i <= theArray.length(); i++) {
134 theStream << theArray[i-1];
135 if ( i < theArray.length() )
142 TPythonDump::operator<<(const SMESH::long_array& theArg)
144 DumpArray( theArg, myStream );
149 TPythonDump::operator<<(const SMESH::double_array& theArg)
151 DumpArray( theArg, myStream );
157 operator<<(SALOMEDS::SObject_ptr aSObject)
159 if ( !aSObject->_is_nil() )
160 myStream << aSObject->GetID();
162 myStream << NotPublishedObjectName();
168 operator<<(CORBA::Object_ptr theArg)
170 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
171 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
172 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
173 if(!aSObject->_is_nil()) {
174 myStream << aSObject->GetID();
175 } else if ( !CORBA::is_nil(theArg)) {
176 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
177 myStream << "smeshObj_" << size_t(theArg);
179 myStream << NotPublishedObjectName();
188 operator<<(SMESH::FilterLibrary_i* theArg)
190 myStream<<"aFilterLibrary"<<theArg;
196 operator<<(SMESH::FilterManager_i* theArg)
198 myStream<<"aFilterManager";
204 operator<<(SMESH::Filter_i* theArg)
206 myStream<<"aFilter"<<theArg;
212 operator<<(SMESH::Functor_i* theArg)
215 FunctorType aFunctorType = theArg->GetFunctorType();
216 switch(aFunctorType){
217 case FT_AspectRatio: myStream<< "anAspectRatio"; break;
218 case FT_AspectRatio3D: myStream<< "anAspectRatio3D"; break;
219 case FT_Warping: myStream<< "aWarping"; break;
220 case FT_MinimumAngle: myStream<< "aMinimumAngle"; break;
221 case FT_Taper: myStream<< "aTaper"; break;
222 case FT_Skew: myStream<< "aSkew"; break;
223 case FT_Area: myStream<< "aArea"; break;
224 case FT_FreeBorders: myStream<< "aFreeBorders"; break;
225 case FT_FreeEdges: myStream<< "aFreeEdges"; break;
226 case FT_MultiConnection: myStream<< "aMultiConnection"; break;
227 case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
228 case FT_Length: myStream<< "aLength"; break;
229 case FT_Length2D: myStream<< "aLength"; break;
230 case FT_BelongToGeom: myStream<< "aBelongToGeom"; break;
231 case FT_BelongToPlane: myStream<< "aBelongToPlane"; break;
232 case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
233 case FT_LyingOnGeom: myStream<< "aLyingOnGeom"; break;
234 case FT_RangeOfIds: myStream<< "aRangeOfIds"; break;
235 case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
236 case FT_LessThan: myStream<< "aLessThan"; break;
237 case FT_MoreThan: myStream<< "aMoreThan"; break;
238 case FT_EqualTo: myStream<< "anEqualTo"; break;
239 case FT_LogicalNOT: myStream<< "aLogicalNOT"; break;
240 case FT_LogicalAND: myStream<< "aLogicalAND"; break;
241 case FT_LogicalOR: myStream<< "aLogicalOR"; break;
242 case FT_Undefined: myStream<< "anUndefined"; break;
249 TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
251 myStream << SMESHGenName(); return *this;
254 TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
256 myStream << MeshEditorName(); return *this;
259 TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
261 myStream << theStr; return *this;
265 TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
267 switch (theVersion) {
268 case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
269 case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
270 default: myStream << theVersion;
275 TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
277 myStream << "SMESH.AxisStruct( "
281 << theAxis.vx << ", "
282 << theAxis.vy << ", "
283 << theAxis.vz << " )";
287 TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
289 const SMESH::PointStruct & P = theDir.PS;
290 myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
298 //=======================================================================
299 //function : DumpPython
301 //=======================================================================
302 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
303 CORBA::Boolean isPublished,
304 CORBA::Boolean& isValidScript)
306 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
307 if (CORBA::is_nil(aStudy))
308 return new Engines::TMPFile(0);
310 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
311 if (CORBA::is_nil(aSO))
312 return new Engines::TMPFile(0);
314 // Map study entries to object names
315 Resource_DataMapOfAsciiStringAsciiString aMap;
316 Resource_DataMapOfAsciiStringAsciiString aMapNames;
317 //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
319 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
320 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
321 SALOMEDS::SObject_var aValue = Itr->Value();
322 CORBA::String_var anID = aValue->GetID();
323 CORBA::String_var aName = aValue->GetName();
324 TCollection_AsciiString aGUIName ( (char*) aName.in() );
325 TCollection_AsciiString anEnrty ( (char*) anID.in() );
326 if (aGUIName.Length() > 0) {
327 aMapNames.Bind( anEnrty, aGUIName );
328 aMap.Bind( anEnrty, aGUIName );
332 // Get trace of restored study
333 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
334 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
335 SALOMEDS::GenericAttribute_var anAttr =
336 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
338 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
339 TCollection_AsciiString aSavedTrace (oldValue);
341 // Add trace of API methods calls and replace study entries by names
342 TCollection_AsciiString aScript =
343 "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
344 aScript += DumpPython_impl(aStudy->StudyId(), aMap, aMapNames,
345 isPublished, isValidScript, aSavedTrace);
347 int aLen = aScript.Length();
348 unsigned char* aBuffer = new unsigned char[aLen+1];
349 strcpy((char*)aBuffer, aScript.ToCString());
351 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
352 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
354 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
355 isValidScript = isValidScript && !hasNotPublishedObjects;
357 return aStreamFile._retn();
360 //=============================================================================
364 //=============================================================================
365 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
367 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
368 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
370 myPythonScripts[theStudyID]->Append(theString);
373 //=============================================================================
375 * RemoveLastFromPythonScript
377 //=============================================================================
378 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
380 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
381 int aLen = myPythonScripts[theStudyID]->Length();
382 myPythonScripts[theStudyID]->Remove(aLen);
386 //=======================================================================
387 //function : SavePython
389 //=======================================================================
390 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
392 // Dump trace of API methods calls
393 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
395 // Check contents of PythonObject attribute
396 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
397 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
398 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
399 SALOMEDS::GenericAttribute_var anAttr =
400 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
402 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
403 TCollection_AsciiString oldScript (oldValue);
405 if (oldScript.Length() > 0) {
407 oldScript += aScript;
412 // Store in PythonObject attribute
413 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
415 // Clean trace of API methods calls
416 CleanPythonTrace(theStudy->StudyId());
423 //=============================================================================
425 * FindEntries: Returns a sequence of start/end positions of entries in the string
427 //=============================================================================
428 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
430 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
431 Standard_Integer aLen = theString.Length();
432 Standard_Boolean isFound = Standard_False;
434 char* arr = theString.ToCString();
435 Standard_Integer i = 0, j;
440 if ( isdigit( c )) { //Is digit?
442 isFound = Standard_False;
443 while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
445 if(c == ':') isFound = Standard_True;
449 int prev = (i < 1) ? 0 : (int)arr[i - 1];
450 // to distinguish from a sketcher command:
451 // last char should be a digit, not ":",
452 // previous char should not be '"'.
453 if (arr[j-2] != ':' && prev != '"') {
454 aSeq->Append(i+1); // +1 because AsciiString starts from 1
466 //=============================================================================
470 //=============================================================================
471 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
473 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
474 Resource_DataMapOfAsciiStringAsciiString& theNames,
477 const TCollection_AsciiString& theSavedTrace)
479 TCollection_AsciiString helper; // to comfortably concatenate C strings
480 TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
481 TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
482 TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
484 TCollection_AsciiString aScript;
485 aScript = "def RebuildData(theStudy):\n\t";
486 aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
488 aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
490 aScript += aSMESHGen + ".SetCurrentStudy(None)";
492 // import python files corresponding to plugins
493 set<string> moduleNameSet;
494 map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
495 for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
496 string moduleName = hyp_creator->second->GetModuleName();
497 bool newModule = moduleNameSet.insert( moduleName ).second;
499 aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
502 // Dump trace of restored study
503 if (theSavedTrace.Length() > 0) {
504 // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
505 // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
506 // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
508 theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
509 if ( !isNewVersion ) {
510 TCollection_AsciiString aSavedTrace( theSavedTrace );
511 TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
512 int beg, end = aSavedTrace.Length(), from = 1;
513 while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
514 char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
515 if ( isspace( charBefore ) || charBefore == '=' ) {
516 aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );
519 from = beg + aSmeshCall.Length();
521 aScript += helper + "\n" + aSavedTrace;
524 // append a saved trace to the script
525 aScript += helper + "\n" + theSavedTrace;
528 // Dump trace of API methods calls
529 TCollection_AsciiString aNewLines = GetNewPythonLines(theStudyID);
530 if (aNewLines.Length() > 0) {
531 aScript += helper + "\n" + aNewLines;
534 // Convert IDL API calls into smesh.py API.
535 // Some objects are wrapped with python classes and
536 // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
537 Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
538 aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod );
540 // Find entries to be replaced by names
541 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
542 Standard_Integer aLen = aSeq->Length();
547 // Replace entries by the names
548 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
549 TColStd_SequenceOfAsciiString seqRemoved;
550 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
551 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
552 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_"),
553 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
555 // Collect names of GEOM objects to exclude same names for SMESH objects
556 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
557 int ign = 0, nbgn = aGeomNames->length();
558 for (; ign < nbgn; ign++) {
559 aName = aGeomNames[ign];
560 theObjectNames.Bind(aName, "1");
563 bool importGeom = false;
564 for (Standard_Integer i = 1; i <= aLen; i += 2) {
565 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
566 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
568 aName = geom->GetDumpName( anEntry.ToCString() );
569 if (aName.IsEmpty()) {
571 if (theObjectNames.IsBound(anEntry)) {
572 // The Object is in Study
573 aName = theObjectNames.Find(anEntry);
574 // check validity of aName
575 bool isValidName = true;
576 int p=1; // replace not allowed chars with underscore
577 while (p <= aName.Length() &&
578 (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
580 if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
581 aName.Remove( p, 1 ); // remove double _ and from the start and the end
583 aName.SetValue(p, '_');
586 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
587 aName.Insert( 1, 'a' );
590 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
591 // diff objects have same name - make a new name by appending a digit
592 TCollection_AsciiString aName2;
593 Standard_Integer i = 0;
595 aName2 = aName + "_" + ++i;
596 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
601 theObjectNames(anEntry) = aName;
606 aName = aBaseName + (++objectCounter);
607 } while (theObjectNames.IsBound(aName));
608 seqRemoved.Append(aName);
609 mapRemoved.Bind(anEntry, "1");
610 theObjectNames.Bind(anEntry, aName);
612 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
618 anUpdatedScript += aName;
619 aStart = aSeq->Value(i + 1) + 1;
622 // set initial part of aSript
623 TCollection_AsciiString initPart = "import salome, SMESH\n";
624 initPart += helper + "import " + aSmeshpy + "\n\n";
627 initPart += ("## import GEOM dump file ## \n"
628 "import string, os, sys, re\n"
629 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
630 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
632 anUpdatedScript.Insert ( 1, initPart );
634 // add final part of aScript
635 if (aSeq->Value(aLen) < aScriptLength)
636 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
638 // Remove removed objects
639 if ( seqRemoved.Length() > 0 ) {
640 anUpdatedScript += "\n\t## some objects were removed";
641 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
643 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
644 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
645 anUpdatedScript += seqRemoved.Value(ir);
646 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
650 anUpdatedScript += "\n\t## set object names";
651 anUpdatedScript += helper + " \n\tisGUIMode = " + isPublished;
652 anUpdatedScript += "\n\tif isGUIMode and salome.sg.hasDesktop():";
653 // anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
654 // anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
655 // anUpdatedScript += "\n";
657 TCollection_AsciiString aGUIName;
658 Resource_DataMapOfAsciiStringAsciiString mapEntries;
659 for (Standard_Integer i = 1; i <= aLen; i += 2)
661 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
662 aName = geom->GetDumpName( anEntry.ToCString() );
663 if (aName.IsEmpty() && // Not a GEOM object
664 theNames.IsBound(anEntry) &&
665 !mapEntries.IsBound(anEntry) && // Not yet processed
666 !mapRemoved.IsBound(anEntry)) // Was not removed
668 aName = theObjectNames.Find(anEntry);
669 aGUIName = theNames.Find(anEntry);
670 mapEntries.Bind(anEntry, aName);
671 anUpdatedScript += helper + "\n\t\t" + aSmeshpy + ".SetName(" + aName;
672 if ( anEntry2AccessorMethod.IsBound( anEntry ) )
673 anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
674 anUpdatedScript += helper + ", '" + aGUIName + "')";
677 anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
679 anUpdatedScript += "\n\n\tpass\n";
683 return anUpdatedScript;
686 //=============================================================================
690 //=============================================================================
691 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
693 TCollection_AsciiString aScript;
695 // Dump trace of API methods calls
696 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
697 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
698 Standard_Integer istr, aLen = aPythonScript->Length();
699 for (istr = 1; istr <= aLen; istr++) {
701 aScript += aPythonScript->Value(istr);
709 //=============================================================================
713 //=============================================================================
714 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
716 TCollection_AsciiString aScript;
718 // Clean trace of API methods calls
719 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
720 myPythonScripts[theStudyID]->Clear();