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"
30 #include <TColStd_HSequenceOfInteger.hxx>
31 #include <TCollection_AsciiString.hxx>
35 static int MYDEBUG = 0;
37 static int MYDEBUG = 0;
40 static TCollection_AsciiString NotPublishedObjectName()
42 return "__NOT__Published__Object__";
48 size_t TPythonDump::myCounter = 0;
59 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
60 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
61 if(!aStudy->_is_nil()){
62 std::string aString = myStream.str();
63 TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
64 aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
65 if(MYDEBUG) MESSAGE(aString);
72 operator<<(long int theArg){
79 operator<<(int theArg){
86 operator<<(double theArg){
93 operator<<(float theArg){
100 operator<<(const void* theArg){
107 operator<<(const char* theArg){
114 operator<<(const SMESH::ElementType& theArg)
140 operator<<(const SMESH::long_array& theArg)
143 CORBA::Long i = 1, iEnd = theArg.length();
144 for(; i <= iEnd; i++) {
145 myStream<<theArg[i-1];
156 operator<<(CORBA::Object_ptr theArg)
158 TCollection_AsciiString aString("None");
159 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
160 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
161 SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
162 if(!aSObject->_is_nil()){
163 aString = aSObject->GetID();
164 }else if(!CORBA::is_nil(theArg)){
165 aString = "smeshObj_";
166 if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
167 aString += (int) theArg;
169 aString = NotPublishedObjectName();
171 myStream<<aString.ToCString();
177 operator<<(SMESH::FilterLibrary_i* theArg)
179 myStream<<"aFilterLibrary"<<theArg;
185 operator<<(SMESH::FilterManager_i* theArg)
187 myStream<<"aFilterManager";
193 operator<<(SMESH::Filter_i* theArg)
195 myStream<<"aFilter"<<theArg;
201 operator<<(SMESH::Functor_i* theArg)
203 FunctorType aFunctorType = theArg->GetFunctorType();
204 switch(aFunctorType){
206 myStream<<"anAspectRatio";
208 case FT_AspectRatio3D:
209 myStream<<"anAspectRatio3D";
212 myStream<<"aWarping";
214 case FT_MinimumAngle:
215 myStream<<"aMinimumAngle";
227 myStream<<"aFreeBorders";
230 myStream<<"aFreeEdges";
232 case FT_MultiConnection:
233 myStream<<"aMultiConnection";
235 case FT_MultiConnection2D:
236 myStream<<"aMultiConnection2D";
244 case FT_BelongToGeom:
245 myStream<<"aBelongToGeom";
247 case FT_BelongToPlane:
248 myStream<<"aBelongToPlane";
250 case FT_BelongToCylinder:
251 myStream<<"aBelongToCylinder";
254 myStream<<"aLyingOnGeom";
257 myStream<<"aRangeOfIds";
259 case FT_BadOrientedVolume:
260 myStream<<"aBadOrientedVolume";
263 myStream<<"aLessThan";
266 myStream<<"aMoreThan";
269 myStream<<"anEqualTo";
272 myStream<<"aLogicalNOT";
275 myStream<<"aLogicalAND";
278 myStream<<"aLogicalOR";
281 myStream<<"anUndefined";
289 //=======================================================================
290 //function : DumpPython
292 //=======================================================================
293 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
294 CORBA::Boolean isPublished,
295 CORBA::Boolean& isValidScript)
297 SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
298 if (CORBA::is_nil(aStudy))
299 return new Engines::TMPFile(0);
301 SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
302 if (CORBA::is_nil(aSO))
303 return new Engines::TMPFile(0);
305 // Map study entries to object names
306 Resource_DataMapOfAsciiStringAsciiString aMap;
307 Resource_DataMapOfAsciiStringAsciiString aMapNames;
308 TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
310 SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
311 for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
312 SALOMEDS::SObject_var aValue = Itr->Value();
313 CORBA::String_var anID = aValue->GetID();
314 CORBA::String_var aName = aValue->GetName();
315 TCollection_AsciiString aGUIName ( (char*) aName.in() );
316 TCollection_AsciiString anEnrty ( (char*) anID.in() );
317 if (aGUIName.Length() > 0) {
318 aMapNames.Bind( anEnrty, aGUIName );
319 aMap.Bind( anEnrty, aGUIName );
323 // Get trace of restored study
324 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
325 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
326 SALOMEDS::GenericAttribute_var anAttr =
327 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
329 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
330 TCollection_AsciiString aSavedTrace (oldValue);
332 // Add trace of API methods calls and replace study entries by names
333 //TCollection_AsciiString aScript =
334 // SALOMEDSImpl_Study::GetDumpStudyComment("SMESH") + "\n\n" +
335 // DumpPython_impl(aStudy->StudyId(), aMap, aMapNames, isPublished, isValidScript, aSavedTrace);
336 TCollection_AsciiString aScript =
337 "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
338 aScript += DumpPython_impl(aStudy->StudyId(), aMap, aMapNames,
339 isPublished, isValidScript, aSavedTrace);
341 int aLen = aScript.Length();
342 unsigned char* aBuffer = new unsigned char[aLen+1];
343 strcpy((char*)aBuffer, aScript.ToCString());
345 CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
346 Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
348 bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
349 isValidScript = isValidScript && !hasNotPublishedObjects;
351 return aStreamFile._retn();
354 //=============================================================================
358 //=============================================================================
359 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
361 if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
362 myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
364 myPythonScripts[theStudyID]->Append(theString);
367 //=============================================================================
369 * RemoveLastFromPythonScript
371 //=============================================================================
372 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
374 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
375 int aLen = myPythonScripts[theStudyID]->Length();
376 myPythonScripts[theStudyID]->Remove(aLen);
380 //=======================================================================
381 //function : AddToCurrentPyScript
383 //=======================================================================
385 void SMESH_Gen_i::AddToCurrentPyScript (const TCollection_AsciiString& theString)
387 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
388 SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
389 if (aStudy->_is_nil()) return;
390 aSMESHGen->AddToPythonScript(aStudy->StudyId(), theString);
394 //=======================================================================
395 //function : AddObject
396 //purpose : add object to script string
397 //=======================================================================
399 TCollection_AsciiString& SMESH_Gen_i::AddObject(TCollection_AsciiString& theStr,
400 CORBA::Object_ptr theObject)
402 TCollection_AsciiString aString("None");
403 SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
404 SALOMEDS::SObject_var aSObject =
405 aSMESHGen->ObjectToSObject(aSMESHGen->GetCurrentStudy(), theObject);
406 if ( !aSObject->_is_nil() ) {
407 aString = aSObject->GetID();
408 } else if ( !CORBA::is_nil( theObject )) {
409 aString = "smeshObj_";
410 if ( aSMESHGen->CanPublishInStudy( theObject )) // not published SMESH object
411 aString += (int) theObject;
413 aString = NotPublishedObjectName();
419 //=======================================================================
420 //function : SavePython
422 //=======================================================================
423 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
425 // Dump trace of API methods calls
426 TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
428 // Check contents of PythonObject attribute
429 SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
430 //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
431 SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
432 SALOMEDS::GenericAttribute_var anAttr =
433 aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
435 char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
436 TCollection_AsciiString oldScript (oldValue);
438 if (oldScript.Length() > 0) {
440 oldScript += aScript;
445 // Store in PythonObject attribute
446 SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
448 // Clean trace of API methods calls
449 CleanPythonTrace(theStudy->StudyId());
456 //=============================================================================
458 * FindEntries: Returns a sequence of start/end positions of entries in the string
460 //=============================================================================
461 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
463 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
464 Standard_Integer aLen = theString.Length();
465 Standard_Boolean isFound = Standard_False;
467 char* arr = theString.ToCString();
468 Standard_Integer i = 0, j;
473 if(c >= 48 && c <= 57) { //Is digit?
475 isFound = Standard_False;
476 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
478 if(c == 58) isFound = Standard_True;
482 int prev = (i < 1) ? 0 : (int)arr[i - 1];
483 // last char should be a diggit,
484 // previous char should not be '"'.
485 if (arr[j-2] != 58 && prev != 34) {
486 aSeq->Append(i+1); // +1 because AsciiString starts from 1
498 //=============================================================================
502 //=============================================================================
503 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
505 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
506 Resource_DataMapOfAsciiStringAsciiString& theNames,
509 const TCollection_AsciiString& theSavedTrace)
511 TCollection_AsciiString aScript;
512 aScript = "def RebuildData(theStudy):";
513 aScript += "\n\tsmesh = salome.lcc.FindOrLoadComponent(\"FactoryServer\", \"SMESH\")";
514 aScript += "\n\taFilterManager = smesh.CreateFilterManager()";
516 aScript += "\n\tsmesh.SetCurrentStudy(theStudy)";
518 aScript += "\n\tsmesh.SetCurrentStudy(None)";
520 // Dump trace of restored study
521 if (theSavedTrace.Length() > 0) {
523 aScript += theSavedTrace;
526 // Dump trace of API methods calls
527 TCollection_AsciiString aNewLines = GetNewPythonLines(theStudyID);
528 if (aNewLines.Length() > 0) {
530 aScript += aNewLines;
533 // Find entries to be replaced by names
534 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
535 Standard_Integer aLen = aSeq->Length();
540 // Replace entries by the names
541 GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
542 TColStd_SequenceOfAsciiString seqRemoved;
543 Resource_DataMapOfAsciiStringAsciiString mapRemoved;
544 Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
545 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_"),
546 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
548 // Collect names of GEOM objects to exclude same names for SMESH objects
549 GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
550 int ign = 0, nbgn = aGeomNames->length();
551 for (; ign < nbgn; ign++) {
552 aName = aGeomNames[ign];
553 theObjectNames.Bind(aName, "1");
556 bool importGeom = false;
557 for (Standard_Integer i = 1; i <= aLen; i += 2) {
558 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
559 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
561 aName = geom->GetDumpName( anEntry.ToCString() );
562 if (aName.IsEmpty()) {
564 if (theObjectNames.IsBound(anEntry)) {
565 // The Object is in Study
566 aName = theObjectNames.Find(anEntry);
567 // check validity of aName
568 bool isValidName = true;
569 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
570 aName.Insert( 1, 'a' );
573 int p, p2=1; // replace not allowed chars
574 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
575 aName.SetValue(p, '_');
579 if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
580 // diff objects have same name - make a new name by appending a digit
581 TCollection_AsciiString aName2;
582 Standard_Integer i = 0;
584 aName2 = aName + "_" + ++i;
585 } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
590 theObjectNames(anEntry) = aName;
595 aName = aBaseName + TCollection_AsciiString(++objectCounter);
596 } while (theObjectNames.IsBound(aName));
597 seqRemoved.Append(aName);
598 mapRemoved.Bind(anEntry, "1");
599 theObjectNames.Bind(anEntry, aName);
601 theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
607 anUpdatedScript += aName;
608 aStart = aSeq->Value(i + 1) + 1;
611 // set initial part of aSript
612 TCollection_AsciiString initPart = "import salome, SMESH, StdMeshers\n\n";
615 initPart += ("import string, os, sys, re\n"
616 "sys.path.insert( 0, os.path.dirname(__file__) )\n"
617 "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
619 anUpdatedScript.Insert ( 1, initPart );
621 // add final part of aScript
622 if (aSeq->Value(aLen) < aScriptLength)
623 anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
625 // Remove removed objects
626 anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
627 for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
628 anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
629 anUpdatedScript += seqRemoved.Value(ir);
630 anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
634 anUpdatedScript += "\n\n\tisGUIMode = ";
635 anUpdatedScript += isPublished;
636 anUpdatedScript += "\n\tif isGUIMode:";
637 anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
638 anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
639 anUpdatedScript += "\n";
641 TCollection_AsciiString aGUIName;
642 Resource_DataMapOfAsciiStringAsciiString mapEntries;
643 for (Standard_Integer i = 1; i <= aLen; i += 2) {
644 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
645 aName = geom->GetDumpName( anEntry.ToCString() );
646 if (aName.IsEmpty() && // Not a GEOM object
647 theNames.IsBound(anEntry) &&
648 !mapEntries.IsBound(anEntry) && // Not yet processed
649 !mapRemoved.IsBound(anEntry)) { // Was not removed
650 aName = theObjectNames.Find(anEntry);
651 aGUIName = theNames.Find(anEntry);
652 mapEntries.Bind(anEntry, aName);
653 anUpdatedScript += "\n\t\tsmeshgui.SetName(salome.ObjectToID(";
654 anUpdatedScript += aName + "), \"" + aGUIName + "\")";
657 anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
659 anUpdatedScript += "\n\n\tpass\n";
663 return anUpdatedScript;
666 //=============================================================================
670 //=============================================================================
671 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
673 TCollection_AsciiString aScript;
675 // Dump trace of API methods calls
676 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
677 Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
678 Standard_Integer istr, aLen = aPythonScript->Length();
679 for (istr = 1; istr <= aLen; istr++) {
681 aScript += aPythonScript->Value(istr);
689 //=============================================================================
693 //=============================================================================
694 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
696 TCollection_AsciiString aScript;
698 // Clean trace of API methods calls
699 if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
700 myPythonScripts[theStudyID]->Clear();