1 // Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #pragma warning( disable:4786 )
26 #include "GEOM_Engine.hxx"
28 #include "GEOM_Solver.hxx"
29 #include "GEOM_Function.hxx"
30 #include "GEOM_ISubShape.hxx"
31 #include "GEOM_SubShapeDriver.hxx"
32 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
33 #include "GEOM_PythonDump.hxx"
35 #include "utilities.h"
37 #include <TDF_Tool.hxx>
38 #include <TDF_Data.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_LabelSequence.hxx>
41 #include <TDataStd_Integer.hxx>
42 #include <TDataStd_ChildNodeIterator.hxx>
43 #include <TFunction_Driver.hxx>
44 #include <TFunction_DriverTable.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
49 #include <TCollection_AsciiString.hxx>
50 #include <TCollection_ExtendedString.hxx>
51 #include <TColStd_SequenceOfAsciiString.hxx>
52 #include <TColStd_MapOfTransient.hxx>
53 #include <TColStd_HSequenceOfInteger.hxx>
55 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
56 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
69 #define O_SQR_BRACKET '['
70 #define C_SQR_BRACKET ']'
71 #define PY_NULL "None"
74 static int MYDEBUG = 0;
76 static int MYDEBUG = 0;
79 static GEOM_Engine* TheEngine = NULL;
83 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
85 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
86 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
87 anID+=(TCollection_AsciiString("_")+anEntry);
91 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
93 TCollection_AsciiString anID(theDocID);
94 anID+=(TCollection_AsciiString("_")+theEntry);
98 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
100 TCollection_AsciiString aDocID = theID.Token("_");
101 if(aDocID.Length() < 1) return -1;
102 return aDocID.IntegerValue();
105 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
106 TCollection_AsciiString& theScript,
107 TCollection_AsciiString& theAfterScript,
108 const TVariablesList& theVariables,
109 const bool theIsPublished,
110 TDF_LabelMap& theProcessed,
111 std::set<std::string>& theIgnoreObjs,
112 bool& theIsDumpCollected);
114 void ReplaceVariables(TCollection_AsciiString& theCommand,
115 const TVariablesList& theVariables);
117 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
119 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
120 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
121 const bool theIsPublished,
122 Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
123 TColStd_SequenceOfAsciiString& theObjListToPublish);
125 void AddObjectColors (const Handle(TDocStd_Document)& theDoc,
126 TCollection_AsciiString& theScript,
127 const Resource_DataMapOfAsciiStringAsciiString& theObjectNames);
129 void PublishObject (const TCollection_AsciiString& theEntry,
130 const TCollection_AsciiString& theName,
131 const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
132 const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
133 const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
134 const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
135 std::map< int, std::string >& theEntryToCommandMap,
136 std::set<std::string>& theMapOfPublished);
138 //=============================================================================
142 //=============================================================================
143 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
145 //=============================================================================
149 //=============================================================================
150 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
152 //=============================================================================
156 //=============================================================================
157 GEOM_Engine::GEOM_Engine()
159 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
161 _OCAFApp = new GEOM_Application();
168 GEOM_Engine::~GEOM_Engine()
170 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
171 for(; It.More(); It.Next())
173 RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
176 //Close all documents not closed
177 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
180 _mapIDDocument.Clear();
184 //=============================================================================
188 //=============================================================================
189 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
191 Handle(TDocStd_Document) aDoc;
192 if(!_mapIDDocument.IsBound(theDocID)) {
193 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
194 aDoc->SetUndoLimit(_UndoLimit);
195 _mapIDDocument.Bind(theDocID, aDoc);
196 TDataStd_Integer::Set(aDoc->Main(), theDocID);
199 return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
202 //=============================================================================
206 //=============================================================================
207 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
209 if(theDocument.IsNull()) return -1;
210 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
211 if(anItr.Value() == theDocument) return anItr.Key();
217 //=============================================================================
221 //=============================================================================
222 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
224 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
225 if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
228 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
229 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
230 Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
232 _objects.Bind(anID, anObject);
237 //=============================================================================
241 //=============================================================================
242 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
244 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
245 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
247 // NPAL18604: use existing label to decrease memory usage,
248 // if this label has been freed (object deleted)
249 bool useExisting = false;
251 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
252 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
253 if (!aFreeLabels.empty()) {
255 aChild = aFreeLabels.front();
256 aFreeLabels.pop_front();
261 aChild = TDF_TagSource::NewChild(aDoc->Main());
264 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
266 //Put an object in the map of created objects
267 TCollection_AsciiString anID = BuildIDFromObject(anObject);
268 if(_objects.IsBound(anID)) _objects.UnBind(anID);
269 _objects.Bind(anID, anObject);
274 //=============================================================================
278 //=============================================================================
279 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
280 Handle(TColStd_HArray1OfInteger) theIndices,
281 bool isStandaloneOperation)
283 if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
285 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
286 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
288 // NPAL18604: use existing label to decrease memory usage,
289 // if this label has been freed (object deleted)
290 bool useExisting = false;
293 if (!_lastCleared.IsNull()) {
294 if (_lastCleared.Root() == aDoc->Main().Root()) {
296 aChild = _lastCleared;
297 // 0020229: if next label exists and is empty, try to reuse it
298 Standard_Integer aNextTag = aChild.Tag() + 1;
299 TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
300 if (!aNextL.IsNull() && !aNextL.HasAttribute())
301 _lastCleared = aNextL;
303 _lastCleared.Nullify();
307 int aDocID = theMainShape->GetDocID();
308 if (_freeLabels.find(aDocID) != _freeLabels.end()) {
309 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
310 if (!aFreeLabels.empty()) {
312 aChild = aFreeLabels.front();
313 aFreeLabels.pop_front();
318 aChild = TDF_TagSource::NewChild(aDoc->Main());
321 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
322 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
323 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
325 GEOM_ISubShape aSSI(aFunction);
326 aSSI.SetMainShape(aMainShape);
327 aSSI.SetIndices(theIndices);
330 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
333 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
334 if (!aSolver.ComputeFunction(aFunction)) {
335 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
339 catch (Standard_Failure) {
340 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
341 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
345 //Put an object in the map of created objects
346 TCollection_AsciiString anID = BuildIDFromObject(anObject);
347 if(_objects.IsBound(anID)) _objects.UnBind(anID);
348 _objects.Bind(anID, anObject);
350 GEOM::TPythonDump pd (aFunction);
352 if (isStandaloneOperation) {
353 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
354 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
355 for (; i <= up - 1; i++) {
356 pd << theIndices->Value(i) << ", ";
358 pd << theIndices->Value(up) << "])";
366 //=============================================================================
370 //=============================================================================
371 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
373 if (!theObject) return false;
375 int aDocID = theObject->GetDocID();
377 //Remove an object from the map of available objects
378 TCollection_AsciiString anID = BuildIDFromObject(theObject);
379 if (_objects.IsBound(anID)) _objects.UnBind(anID);
381 int nb = theObject->GetNbFunctions();
382 Handle(TDataStd_TreeNode) aNode;
383 for (int i = 1; i<=nb; i++) {
384 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
385 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
389 TDF_Label aLabel = theObject->GetEntry();
390 aLabel.ForgetAllAttributes(Standard_True);
392 // Remember the label to reuse it then
393 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
394 aFreeLabels.push_back(aLabel);
401 //=============================================================================
405 //=============================================================================
406 void GEOM_Engine::Undo(int theDocID)
408 GetDocument(theDocID)->Undo();
411 //=============================================================================
415 //=============================================================================
416 void GEOM_Engine::Redo(int theDocID)
418 GetDocument(theDocID)->Redo();
421 //=============================================================================
425 //=============================================================================
426 bool GEOM_Engine::Save(int theDocID, char* theFileName)
428 if(!_mapIDDocument.IsBound(theDocID)) return false;
429 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
431 _OCAFApp->SaveAs(aDoc, theFileName);
436 //=============================================================================
440 //=============================================================================
441 bool GEOM_Engine::Load(int theDocID, char* theFileName)
443 Handle(TDocStd_Document) aDoc;
444 if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
448 aDoc->SetUndoLimit(_UndoLimit);
450 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
451 _mapIDDocument.Bind(theDocID, aDoc);
453 TDataStd_Integer::Set(aDoc->Main(), theDocID);
458 //=============================================================================
462 //=============================================================================
463 void GEOM_Engine::Close(int theDocID)
465 if (_mapIDDocument.IsBound(theDocID)) {
466 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
468 //Remove all GEOM Objects associated to the given document
469 TColStd_SequenceOfAsciiString aSeq;
470 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
471 for (; It.More(); It.Next()) {
472 TCollection_AsciiString anObjID (It.Key());
473 Standard_Integer anID = ExtractDocID(anObjID);
474 if (theDocID == anID) aSeq.Append(It.Key());
476 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
478 // Forget free labels for this document
479 TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
480 if (anIt != _freeLabels.end()) {
481 _freeLabels.erase(anIt);
484 _mapIDDocument.UnBind(theDocID);
485 _OCAFApp->Close(aDoc);
490 //=============================================================================
494 //=============================================================================
495 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
496 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
497 TVariablesList theVariables,
501 TCollection_AsciiString aScript;
502 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
504 if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
506 aScript = "import geompy\n";
507 aScript += "import math\n";
508 aScript += "import SALOMEDS\n\n";
509 aScript += "def RebuildData(theStudy):";
510 aScript += "\n\tgeompy.init_geom(theStudy)";
512 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
514 Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
515 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
516 // build maps entry <-> studyEntry
517 for (anEntryToNameIt.Initialize( theObjectNames );
518 anEntryToNameIt.More();
519 anEntryToNameIt.Next())
521 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
522 // look for an object by entry
524 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
525 if ( L.IsNull() ) continue;
526 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
528 if ( !obj.IsNull() ) {
529 TCollection_AsciiString aStudyEntry (obj->GetAuxData());
530 aEntry2StEntry.Bind( aEntry, aStudyEntry);
531 aStEntry2Entry.Bind( aStudyEntry, aEntry );
535 // collect objects entries to be published
536 TColStd_SequenceOfAsciiString aObjListToPublish;
538 // iterates on functions till critical (that requiers publication of objects)
539 Handle(TDataStd_TreeNode) aNode, aRoot;
540 Handle(GEOM_Function) aFunction;
541 TDF_LabelMap aCheckedFuncMap;
542 std::set<std::string> anIgnoreObjMap;
544 TCollection_AsciiString aFuncScript;
545 Resource_DataMapOfAsciiStringAsciiString anEntryToBadName;
547 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
548 TDataStd_ChildNodeIterator Itr(aRoot);
549 for (; Itr.More(); Itr.Next()) {
551 aFunction = GEOM_Function::GetFunction(aNode->Label());
552 if (aFunction.IsNull()) {
553 MESSAGE ( "Null function !!!!" );
556 bool isDumpCollected = false;
557 TCollection_AsciiString aCurScript, anAfterScript;
558 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
559 isPublished, aCheckedFuncMap, anIgnoreObjMap,
562 // add function description before dump
563 if (!aCurScript.IsEmpty())
564 aFuncScript += aCurScript;
565 if (isDumpCollected ) {
566 // Replace entries by the names
567 ReplaceEntriesByNames( aFuncScript, theObjectNames,
568 isPublished, anEntryToBadName, aObjListToPublish );
570 // publish collected objects
571 std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
572 int i = 1, n = aObjListToPublish.Length();
573 for ( ; i <= n; i++ )
575 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
576 if (!theObjectNames.IsBound( aEntry ))
578 PublishObject( aEntry, theObjectNames.Find(aEntry),
579 theObjectNames, aEntry2StEntry, aStEntry2Entry,
580 anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
582 // add publishing commands to the script
583 std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
584 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
585 aFuncScript += (char*)anEntryToCommand->second.c_str();
587 // PTv, 0020001 add result objects from RestoreSubShapes into ignore list,
588 // because they will be published during command execution
589 int indx = anAfterScript.Search( "RestoreSubShapes" );
591 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
592 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
593 i = 1, n = aSeq->Length();
594 for ( ; i <= n; i+=2) {
595 TCollection_AsciiString anEntry =
596 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
597 if (!anIgnoreObjMap.count(anEntry.ToCString()))
598 anIgnoreObjMap.insert(anEntry.ToCString());
602 aObjListToPublish.Clear();
603 aScript += aFuncScript;
606 aFuncScript += anAfterScript;
610 // Replace entries by the names
611 aObjListToPublish.Clear();
612 ReplaceEntriesByNames( aFuncScript, theObjectNames,
613 isPublished, anEntryToBadName, aObjListToPublish );
615 aScript += aFuncScript;
618 AddObjectColors( aDoc, aScript, theObjectNames );
620 // Make script to publish in study
623 std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
624 for (anEntryToNameIt.Initialize( theObjectNames );
625 anEntryToNameIt.More();
626 anEntryToNameIt.Next())
628 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
629 if (anIgnoreObjMap.count(aEntry.ToCString()))
630 continue; // should not be dumped
631 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
632 PublishObject( aEntry, aName, theObjectNames,
633 aEntry2StEntry, aStEntry2Entry,
634 anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
636 // add publishing commands to the script
637 std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
638 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
639 aScript += (char*)anEntryToCommand->second.c_str();
642 //aScript += "\n\tpass\n";
646 // fill _studyEntry2NameMap and build globalVars
647 TCollection_AsciiString globalVars;
648 _studyEntry2NameMap.Clear();
649 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
650 for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
651 aStEntryToEntryIt.More();
652 aStEntryToEntryIt.Next() )
654 const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
655 _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
656 if ( !globalVars.IsEmpty() )
660 if ( !globalVars.IsEmpty() ) {
661 globalVars.Insert( 1, "\n\tglobal " );
662 aScript.Insert( posToInsertGlobalVars, globalVars );
668 //=======================================================================
669 //function : GetDumpName
671 //=======================================================================
673 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
675 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
676 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
681 //=======================================================================
682 //function : GetAllDumpNames
684 //=======================================================================
686 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
688 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
690 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
691 for (; it.More(); it.Next()) {
692 aRetSeq->Append(it.Value());
699 //===========================================================================
700 // Internal functions
701 //===========================================================================
703 //=============================================================================
705 * ProcessFunction: Dump fucntion description into script
707 //=============================================================================
708 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
709 TCollection_AsciiString& theScript,
710 TCollection_AsciiString& theAfterScript,
711 const TVariablesList& theVariables,
712 const bool theIsPublished,
713 TDF_LabelMap& theProcessed,
714 std::set<std::string>& theIgnoreObjs,
715 bool& theIsDumpCollected)
717 theIsDumpCollected = false;
718 if (theFunction.IsNull()) return false;
720 if (theProcessed.Contains(theFunction->GetEntry())) return false;
722 // pass functions, that depends on nonexisting ones
723 bool doNotProcess = false;
724 TDF_LabelSequence aSeq;
725 theFunction->GetDependency(aSeq);
726 Standard_Integer aLen = aSeq.Length();
727 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
728 TDF_Label aRefLabel = aSeq.Value(i);
729 Handle(TDF_Reference) aRef;
730 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
734 if (aRef.IsNull() || aRef->Get().IsNull()) {
738 Handle(TDataStd_TreeNode) aT;
739 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
743 TDF_Label aDepLabel = aT->Label();
744 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
746 if (aFunction.IsNull()) doNotProcess = true;
747 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
754 TCollection_AsciiString anObjEntry;
755 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
756 theIgnoreObjs.insert(anObjEntry.ToCString());
759 theProcessed.Add(theFunction->GetEntry());
761 TCollection_AsciiString aDescr = theFunction->GetDescription();
762 if(aDescr.Length() == 0) return false;
764 //Check if its internal function which doesn't requires dumping
765 if(aDescr == "None") return false;
767 // 0020001 PTv, check for critical functions, which requier dump of objects
770 // currently, there is only one function "RestoreSubShapes",
771 // later this check could be replaced by iterations on list of such functions
772 if (aDescr.Search( "RestoreSubShapes" ) != -1)
773 theIsDumpCollected = true;
776 //Replace parameter by notebook variables
777 ReplaceVariables(aDescr,theVariables);
778 if ( theIsDumpCollected ) {
780 bool isBefore = true;
781 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
782 while (!aSubStr.IsEmpty()) {
783 if (isBefore && aSubStr.Search( "RestoreSubShapes" ) == -1)
784 theScript += TCollection_AsciiString("\n\t") + aSubStr;
786 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
787 aSubStr = aDescr.Token("\n\t", i++);
797 //=============================================================================
799 * FindEntries: Returns a sequence of start/end positions of entries in the string
801 //=============================================================================
802 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
804 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
805 Standard_Integer aLen = theString.Length();
806 Standard_Boolean isFound = Standard_False;
808 const char* arr = theString.ToCString();
809 Standard_Integer i = 0, j;
814 if(c >= 48 && c <= 57) { //Is digit?
816 isFound = Standard_False;
817 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
819 if(c == 58) isFound = Standard_True;
822 if(isFound && arr[j-2] != 58) { // last char should be a diggit
823 aSeq->Append(i+1); // +1 because AsciiString starts from 1
834 //=============================================================================
836 * ReplaceVariables: Replace parameters of the function by variales from
839 //=============================================================================
840 void ReplaceVariables(TCollection_AsciiString& theCommand,
841 const TVariablesList& theVariables)
844 cout<<"Command : "<<theCommand<<endl;
847 cout<<"All Entries:"<<endl;
848 TVariablesList::const_iterator it = theVariables.begin();
849 for(;it != theVariables.end();it++)
850 cout<<"\t'"<<(*it).first<<"'"<<endl;
853 //Additional case - multi-row commands
854 int aCommandIndex = 1;
855 while( aCommandIndex < 10 ) { // tmp check
856 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
857 if( aCommand.Length() == 0 )
861 cout<<"Sub-command : "<<aCommand<<endl;
863 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
864 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
866 //Get Entry of the result object
867 TCollection_AsciiString anEntry;
868 if( aCommand.Search("=") != -1 ) // command returns an object
869 anEntry = aCommand.Token("=",1);
870 else { // command modifies the object
871 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
872 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
873 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
875 //Remove white spaces
876 anEntry.RightAdjust();
877 anEntry.LeftAdjust();
879 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
881 if ( anEntry.IsEmpty() ) {
886 //Check if result is list of entries - enough to get the first entry in this case
888 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
889 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
891 TCollection_AsciiString aSeparator(COMMA);
892 anEntry = anEntry.Token(aSeparator.ToCString(),1);
893 anEntry.Remove( 1, 1 );
894 anEntry.RightAdjust();
895 anEntry.LeftAdjust();
897 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
900 //Find variables used for object construction
901 ObjectStates* aStates = 0;
902 TVariablesList::const_iterator it = theVariables.find(anEntry);
903 if( it != theVariables.end() )
904 aStates = (*it).second;
908 cout<<"Valiables list empty!!!"<<endl;
913 TState aVariables = aStates->GetCurrectState();
916 cout<<"Variables from SObject:"<<endl;
917 for (int i = 0; i < aVariables.size();i++)
918 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
921 //Calculate total number of parameters
922 Standard_Integer aTotalNbParams = 1;
923 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
927 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
929 Standard_Integer aFirstParam = aNbEntries;
931 //Replace parameters by variables
932 Standard_Integer aStartPos = 0;
933 Standard_Integer aEndPos = 0;
935 TCollection_AsciiString aVar, aReplacedVar;
936 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
937 //Replace first parameter (bettwen '(' character and first ',' character)
940 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
941 if(aTotalNbParams - aNbEntries > 0 )
942 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
944 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
946 //Replace last parameter (bettwen ',' character and ')' character)
947 else if(i == aTotalNbParams)
949 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
950 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
952 //Replace other parameters (bettwen two ',' characters)
953 else if(i != aFirstParam && i != aTotalNbParams )
955 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
956 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
959 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
961 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
963 if ( aStartPos == aEndPos )
964 continue; // PAL20889: for "[]"
967 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
969 aVar = aCommand.SubString(aStartPos, aEndPos-1);
974 cout<<"Variable: '"<< aVar <<"'"<<endl;
976 // specific case for sketcher
977 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
978 Standard_Integer aNbSections = 1;
979 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
983 int aStartSectionPos = 0, aEndSectionPos = 0;
984 TCollection_AsciiString aSection, aReplacedSection;
985 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
986 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
987 if( aSectionIndex != aNbSections )
988 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
990 aEndSectionPos = aVar.Length();
992 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
994 cout<<"aSection: "<<aSection<<endl;
996 Standard_Integer aNbParams = 1;
997 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1001 int aStartParamPos = 0, aEndParamPos = 0;
1002 TCollection_AsciiString aParameter, aReplacedParameter;
1003 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1004 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1005 if( aParamIndex != aNbParams )
1006 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1008 aEndParamPos = aSection.Length() + 1;
1010 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1012 cout<<"aParameter: "<<aParameter<<endl;
1014 if(iVar >= aVariables.size())
1017 aReplacedParameter = aVariables[iVar].myVariable;
1018 if(aReplacedParameter.IsEmpty()) {
1023 if(aVariables[iVar].isVariable) {
1024 aReplacedParameter.InsertBefore(1,"'");
1025 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1029 cout<<"aSection before : "<<aSection<<endl;
1030 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1031 aSection.Insert(aStartParamPos, aReplacedParameter);
1033 cout<<"aSection after : "<<aSection<<endl<<endl;
1037 cout<<"aVar before : "<<aVar<<endl;
1038 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1039 aVar.Insert(aStartSectionPos, aSection);
1041 cout<<"aVar after : "<<aVar<<endl<<endl;
1045 cout<<"aCommand before : "<<aCommand<<endl;
1046 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1047 aCommand.Insert(aStartPos, aVar);
1049 cout<<"aCommand after : "<<aCommand<<endl;
1052 } // end of specific case for sketcher
1054 //If parameter is entry or 'None', skip it
1055 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1058 if(iVar >= aVariables.size())
1061 aReplacedVar = aVariables[iVar].myVariable;
1062 if(aReplacedVar.IsEmpty()) {
1067 if(aVariables[iVar].isVariable) {
1068 aReplacedVar.InsertBefore(1,"\"");
1069 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1072 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1073 aCommand.Insert(aStartPos, aReplacedVar);
1077 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1078 theCommand.Insert(aStartCommandPos, aCommand);
1082 aStates->IncrementState();
1086 cout<<"Command : "<<theCommand<<endl;
1089 //=============================================================================
1091 * ReplaceEntriesByNames: Replace object entries by their names
1093 //=============================================================================
1094 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1095 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1096 const bool theIsPublished,
1097 Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
1098 TColStd_SequenceOfAsciiString& theObjListToPublish)
1100 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1101 Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = theScript.Length();
1102 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
1104 //Replace entries by the names
1105 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1106 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1107 if (aLen == 0) anUpdatedScript = theScript;
1109 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1110 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1111 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1112 theObjListToPublish.Append( anEntry );
1113 if (theObjectNames.IsBound(anEntry)) {
1114 aName = theObjectNames.Find(anEntry);
1115 // check validity of aName
1116 bool isValidName = true;
1117 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
1118 aName.Insert( 1, 'a' );
1119 isValidName = false;
1121 int p, p2=1; // replace not allowed chars
1122 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
1123 aName.SetValue(p, '_');
1125 isValidName = false;
1127 if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
1128 { // diff objects have same name - make a new name by appending a digit
1129 TCollection_AsciiString aName2;
1130 Standard_Integer i = 0;
1132 aName2 = aName + "_" + ++i;
1133 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
1135 isValidName = false;
1137 if ( !isValidName ) {
1138 if ( theIsPublished )
1139 theEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
1140 theObjectNames( anEntry ) = aName;
1145 aName = aBaseName + TCollection_AsciiString(++objectCounter);
1146 } while(aNameToEntry.IsBound(aName));
1147 theObjectNames.Bind(anEntry, aName);
1149 aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
1151 anUpdatedScript += aName;
1152 aStart = aSeq->Value(i+1) + 1;
1155 //Add final part of the script
1156 if (aLen && aSeq->Value(aLen) < aScriptLength)
1157 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1159 theScript = anUpdatedScript;
1162 //=============================================================================
1164 * AddObjectColors: Add color to objects
1166 //=============================================================================
1167 void AddObjectColors (const Handle(TDocStd_Document)& theDoc,
1168 TCollection_AsciiString& theScript,
1169 const Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
1171 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
1172 for (anEntryToNameIt.Initialize( theObjectNames );
1173 anEntryToNameIt.More();
1174 anEntryToNameIt.Next())
1176 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
1177 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
1180 TDF_Tool::Label( theDoc->GetData(), aEntry, L );
1184 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1188 bool anAutoColor = obj->GetAutoColor();
1191 TCollection_AsciiString aCommand( "\n\t" );
1192 aCommand += aName + ".SetAutoColor(1)";
1193 theScript += aCommand.ToCString();
1196 SALOMEDS::Color aColor = obj->GetColor();
1197 if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
1199 TCollection_AsciiString aCommand( "\n\t" );
1200 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1201 theScript += aCommand.ToCString();
1206 //=============================================================================
1208 * PublishObject: publish object in study script
1210 //=============================================================================
1211 void PublishObject (const TCollection_AsciiString& theEntry,
1212 const TCollection_AsciiString& theName,
1213 const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1214 const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
1215 const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
1216 const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
1217 std::map< int, std::string >& theEntryToCommandMap,
1218 std::set<std::string>& theMapOfPublished)
1220 if ( !theEntry2StEntry.IsBound( theEntry ))
1221 return; // was not published
1222 if ( theMapOfPublished.count(theEntry.ToCString()) )
1223 return; // aready published
1224 theMapOfPublished.insert( theEntry.ToCString() );
1226 TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
1228 // find a father entry
1229 const TCollection_AsciiString& aStudyEntry = theEntry2StEntry( theEntry );
1230 TCollection_AsciiString aFatherStudyEntry =
1231 aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
1232 if ( theStEntry2Entry.IsBound( aFatherStudyEntry ))
1233 aFatherEntry = theStEntry2Entry( aFatherStudyEntry );
1236 if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
1237 aCommand += "addToStudyInFather( ";
1238 aCommand += theObjectNames( aFatherEntry ) + ", ";
1241 aCommand += "addToStudy( ";
1242 if ( theEntryToBadName.IsBound( theEntry ))
1243 aCommand += theName + ", \"" + theEntryToBadName( theEntry ) + "\" )";
1245 aCommand += theName + ", \"" + theName + "\" )";
1247 // bind a command to the last digit of the entry
1249 theEntry.SubString( theEntry.SearchFromEnd(":")+1, theEntry.Length() ).IntegerValue();
1250 theEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
1253 //================================================================================
1255 * \brief Constructor
1257 //================================================================================
1258 ObjectStates::ObjectStates()
1263 //================================================================================
1267 //================================================================================
1268 ObjectStates::~ObjectStates()
1272 //================================================================================
1274 * \brief Return current object state
1275 * \retval state - Object state (vector of notebook variable)
1277 //================================================================================
1278 TState ObjectStates::GetCurrectState() const
1280 if(_states.size() > _dumpstate)
1281 return _states[_dumpstate];
1285 //================================================================================
1287 * \brief Add new object state
1288 * \param theState - Object state (vector of notebook variable)
1290 //================================================================================
1291 void ObjectStates::AddState(const TState &theState)
1293 _states.push_back(theState);
1296 //================================================================================
1298 * \brief Increment object state
1300 //================================================================================
1301 void ObjectStates::IncrementState()