Salome HOME
Copyright update 2020
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "ModelHighAPI_Dumper.h"
21
22 #include <Config_PropManager.h>
23
24 #include <GeomAPI_Circ.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Ellipse.h>
27 #include <GeomAPI_Dir.h>
28 #include <GeomAPI_Pnt.h>
29 #include <GeomAPI_Pnt2d.h>
30 #include <GeomAPI_ShapeExplorer.h>
31 #include <GeomAPI_ShapeIterator.h>
32 #include <GeomAPI_Vertex.h>
33 #include <GeomAlgoAPI_NExplode.h>
34
35 #include <GeomDataAPI_Dir.h>
36 #include <GeomDataAPI_Point.h>
37 #include <GeomDataAPI_Point2D.h>
38 #include <GeomDataAPI_Point2DArray.h>
39
40 #include <ModelAPI_AttributeBoolean.h>
41 #include <ModelAPI_AttributeDouble.h>
42 #include <ModelAPI_AttributeDoubleArray.h>
43 #include <ModelAPI_AttributeIntArray.h>
44 #include <ModelAPI_AttributeInteger.h>
45 #include <ModelAPI_AttributeRefAttr.h>
46 #include <ModelAPI_AttributeRefAttrList.h>
47 #include <ModelAPI_AttributeReference.h>
48 #include <ModelAPI_AttributeRefList.h>
49 #include <ModelAPI_AttributeSelection.h>
50 #include <ModelAPI_AttributeSelectionList.h>
51 #include <ModelAPI_AttributeString.h>
52 #include <ModelAPI_AttributeStringArray.h>
53 #include <ModelAPI_CompositeFeature.h>
54 #include <ModelAPI_Document.h>
55 #include <ModelAPI_Entity.h>
56 #include <ModelAPI_Feature.h>
57 #include <ModelAPI_FiltersFeature.h>
58 #include <ModelAPI_Folder.h>
59 #include <ModelAPI_Result.h>
60 #include <ModelAPI_ResultBody.h>
61 #include <ModelAPI_ResultConstruction.h>
62 #include <ModelAPI_ResultGroup.h>
63 #include <ModelAPI_ResultPart.h>
64 #include <ModelAPI_Session.h>
65 #include <ModelAPI_Tools.h>
66
67 #include <ModelGeomAlgo_Shape.h>
68
69 #include <PartSetPlugin_Part.h>
70
71 #include <OSD_OpenFile.hxx>
72
73 #include <fstream>
74
75 // ===========    Implementation of storage of dumped data    ===========
76 static const int THE_DUMP_PRECISION = 16;
77
78 class ModelHighAPI_Dumper::DumpStorageBuffer : public ModelHighAPI_Dumper::DumpStorage
79 {
80 public:
81   void addStorage(const ModelHighAPI_Dumper::DumpStoragePtr& theStorage)
82   { myStorageArray.push_back(theStorage); }
83
84   void clear() { myStorageArray.clear(); }
85
86   bool isBufferEmpty()
87   {
88     return myStorageArray.empty() || myStorageArray.front()->buffer().str().empty();
89   }
90
91   void mergeBuffer()
92   {
93     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
94     for (; anIt != myStorageArray.end(); ++anIt) {
95       // avoid multiple empty lines
96       std::string aBuf = (*anIt)->buffer().str();
97       size_t anInd = std::string::npos;
98       while ((anInd = aBuf.find("\n\n\n")) != std::string::npos)
99         aBuf.erase(anInd, 1);
100
101       (*anIt)->fullDump() << aBuf;
102       (*anIt)->buffer().str("");
103     }
104   }
105
106   void write(const std::string& theValue)
107   {
108     if (myStorageArray.empty())
109       addStorage(DumpStoragePtr(new DumpStorage));
110
111     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
112     for (; anIt != myStorageArray.end(); ++anIt)
113       (*anIt)->buffer() << theValue;
114   }
115
116   DumpStorageBuffer& operator<<(const char theChar)
117   {
118     std::ostringstream out;
119     out << theChar;
120     write(out.str());
121     return *this;
122   }
123
124   DumpStorageBuffer& operator<<(const char* theString)
125   {
126     write(theString);
127     return *this;
128   }
129
130   DumpStorageBuffer& operator<<(const std::string& theString)
131   {
132     write(theString);
133     return *this;
134   }
135
136   DumpStorageBuffer& operator<<(const bool theValue)
137   {
138     std::ostringstream out;
139     out << theValue;
140     write(out.str());
141     return *this;
142   }
143
144   DumpStorageBuffer& operator<<(const int theValue)
145   {
146     std::ostringstream out;
147     out << theValue;
148     write(out.str());
149     return *this;
150   }
151
152   DumpStorageBuffer& operator<<(const double theValue)
153   {
154     std::ostringstream out;
155     out << std::setprecision(THE_DUMP_PRECISION) << theValue;
156     write(out.str());
157     return *this;
158   }
159   /// Dump std::endl
160   friend
161   DumpStorageBuffer& operator<<(DumpStorageBuffer& theBuffer,
162                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
163   {
164     theBuffer.write("\n");
165     return theBuffer;
166   }
167
168   void dumpArray(int theSize, double* theValues, std::string* theTexts)
169   {
170     std::ostringstream anOutput;
171     anOutput << std::setprecision(THE_DUMP_PRECISION);
172     for (int i = 0; i < theSize; ++i) {
173       if (i > 0)
174         anOutput << ", ";
175       if (theTexts[i].empty())
176         anOutput << theValues[i];
177       else
178         anOutput << "\"" << theTexts[i] << "\"";
179     }
180     write(anOutput.str());
181   }
182
183   virtual void write(const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
184   {
185     if (myStorageArray.empty())
186       addStorage(DumpStoragePtr(new DumpStorage));
187
188     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
189     for (; anIt != myStorageArray.end(); ++anIt)
190       (*anIt)->write(theAttrSelect);
191   }
192
193   virtual void reserveBuffer()
194   {
195     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
196     for (; anIt != myStorageArray.end(); ++anIt)
197       (*anIt)->reserveBuffer();
198   }
199
200   virtual void restoreReservedBuffer()
201   {
202     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
203     for (; anIt != myStorageArray.end(); ++anIt)
204       (*anIt)->restoreReservedBuffer();
205   }
206
207   virtual bool exportTo(const std::string& theFilename, const ModulesSet& theUsedModules)
208   {
209     static const std::string THE_EXT = ".py";
210     std::string aFilenameBase = theFilename;
211     if (aFilenameBase.rfind(THE_EXT) == aFilenameBase.size() - THE_EXT.size())
212       aFilenameBase = aFilenameBase.substr(0, aFilenameBase.size() - THE_EXT.size());
213
214     bool isOk = true;
215     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
216     for (; anIt != myStorageArray.end(); ++anIt) {
217       std::string aFilename = aFilenameBase + (*anIt)->myFilenameSuffix + THE_EXT;
218       isOk = (*anIt)->exportTo(aFilename, theUsedModules) && isOk;
219     }
220     return isOk;
221   }
222
223 private:
224   std::list<ModelHighAPI_Dumper::DumpStoragePtr> myStorageArray;
225 };
226
227
228 ModelHighAPI_Dumper::DumpStorage::DumpStorage(const DumpStorage& theOther)
229   : myFilenameSuffix(theOther.myFilenameSuffix),
230     myDumpBufferHideout(theOther.myDumpBufferHideout)
231 {
232   myFullDump.str(theOther.myFullDump.str());
233   myDumpBuffer.str(theOther.myDumpBuffer.str());
234 }
235
236 const ModelHighAPI_Dumper::DumpStorage&
237 ModelHighAPI_Dumper::DumpStorage::operator=(const ModelHighAPI_Dumper::DumpStorage& theOther)
238 {
239   myFilenameSuffix = theOther.myFilenameSuffix;
240   myFullDump.str(theOther.myFullDump.str());
241   myDumpBuffer.str(theOther.myDumpBuffer.str());
242   myDumpBufferHideout = theOther.myDumpBufferHideout;
243   return *this;
244 }
245
246 void ModelHighAPI_Dumper::DumpStorage::reserveBuffer()
247 {
248   myDumpBufferHideout.push(myDumpBuffer.str());
249   myDumpBuffer.str("");
250 }
251
252 void ModelHighAPI_Dumper::DumpStorage::restoreReservedBuffer()
253 {
254   myDumpBuffer << myDumpBufferHideout.top();
255   myDumpBufferHideout.pop();
256 }
257
258 bool ModelHighAPI_Dumper::DumpStorage::exportTo(const std::string& theFilename,
259                                                 const ModulesSet& theUsedModules)
260 {
261   std::ofstream aFile;
262   OSD_OpenStream(aFile, theFilename.c_str(), std::ofstream::out);
263   if (!aFile.is_open())
264     return false;
265
266   // standard header imported modules
267   for (ModulesSet::const_iterator aModIt = theUsedModules.begin();
268     aModIt != theUsedModules.end(); ++aModIt) {
269     aFile << "from " << *aModIt << " import *" << std::endl;
270   }
271   if (!theUsedModules.empty())
272     aFile << std::endl;
273
274   aFile << "from salome.shaper import model" << std::endl << std::endl;
275   aFile << "model.begin()" << std::endl;
276
277   // dump collected data
278   aFile << myFullDump.str();
279   aFile << myDumpBuffer.str();
280
281   // standard footer
282   aFile << "model.end()" << std::endl;
283   aFile.close();
284
285   return true;
286 }
287
288 static void getShapeAndContext(const AttributeSelectionPtr& theAttrSelect,
289                                GeomShapePtr& theShape, ResultPtr& theContext)
290 {
291   if (theAttrSelect->isInitialized()) {
292     theShape = theAttrSelect->value();
293     theContext = theAttrSelect->context();
294     if (!theShape.get())
295       theShape = theContext->shape();
296
297     if (theAttrSelect->isGeometricalSelection() &&
298         theShape.get() && theShape->shapeType() == GeomAPI_Shape::COMPOUND &&
299         theContext.get() && !theShape->isEqual(theContext->shape()) &&
300         theContext->groupName() != ModelAPI_ResultPart::group() &&
301         theContext->groupName() != ModelAPI_ResultGroup::group()) {
302       GeomAPI_ShapeIterator anIt(theShape);
303       theShape = anIt.current();
304     }
305   }
306 }
307
308 void ModelHighAPI_Dumper::DumpStorage::write(const AttributeSelectionPtr& theAttrSelect)
309 {
310   myDumpBuffer << "model.selection(";
311
312   GeomShapePtr aShape;
313   ResultPtr aContext;
314   getShapeAndContext(theAttrSelect, aShape, aContext);
315
316   if (aShape.get()) {
317     myDumpBuffer << "\"" << aShape->shapeTypeStr() << "\", \""
318                  << theAttrSelect->namingName() << "\"";
319   }
320
321   myDumpBuffer << ")";
322 }
323
324 static int possibleSelectionsByPoint(const GeomPointPtr& thePoint,
325                                      const ResultPtr& theResult,
326                                      const GeomShapePtr& theShape,
327                                      const FeaturePtr& theStartFeature,
328                                      const FeaturePtr& theEndFeature)
329 {
330   DocumentPtr aDoc1 = theStartFeature->document();
331   DocumentPtr aDoc2 = theEndFeature->document();
332
333   std::list<FeaturePtr> aFeatures = aDoc1->allFeatures();
334   if (aDoc1 != aDoc2) {
335     // Find the position of the part, where its features should be inserted.
336     // It will avoid checking of appropriate elements in partSet after the current part.
337     std::list<FeaturePtr>::iterator aFIt = aFeatures.begin();
338     for (; aFIt != aFeatures.end(); ++aFIt) {
339       ResultPartPtr aPartRes =
340           std::dynamic_pointer_cast<ModelAPI_ResultPart>((*aFIt)->lastResult());
341       if (aPartRes && aPartRes->partDoc() == aDoc2)
342         break;
343     }
344
345     std::list<FeaturePtr> anAdditionalFeatures = aDoc2->allFeatures();
346     aFeatures.insert(aFIt, anAdditionalFeatures.begin(), anAdditionalFeatures.end());
347   }
348
349   CompositeFeaturePtr aLastCompositeFeature;
350
351   std::list<FeaturePtr>::const_iterator aFIt = aFeatures.begin();
352   while (aFIt != aFeatures.end() && *aFIt != theStartFeature) {
353     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFIt);
354     if (aCompFeat)
355       aLastCompositeFeature = aCompFeat;
356     ++aFIt;
357   }
358
359   // collect the list of composite features, containing the last feature;
360   // these features should be excluded from searching,
361   // because the feature cannot select sub-shapes from its parent
362   std::set<FeaturePtr> aEndFeatureParents = ModelAPI_Tools::getParents(theEndFeature);
363
364   int aNbPossibleSelections = 0;
365   for (; aFIt != aFeatures.end() && *aFIt != theEndFeature; ++aFIt) {
366     bool isSkipFeature = false;
367     if (aLastCompositeFeature && aLastCompositeFeature->isSub(*aFIt))
368       isSkipFeature = true;
369     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFIt);
370     if (aCompFeat) {
371       ResultPartPtr aPartRes =
372           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCompFeat->firstResult());
373       if (!aPartRes)
374         aLastCompositeFeature = aCompFeat;
375       if (aEndFeatureParents.find(aCompFeat) != aEndFeatureParents.end()) {
376         // do not process the parent for the last feature,
377         // because it cannot select objects from its parent
378         isSkipFeature = true;
379       }
380     }
381     if (isSkipFeature)
382       continue;
383
384     std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anApproproate;
385     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*aFIt, thePoint, theShape->shapeType(),
386                                                  anApproproate)) {
387       bool isContinue = true;
388       std::list<std::pair<GeomShapePtr, int> > aCenters;
389       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anApproproate.begin();
390       for (; anApIt != anApproproate.end() && isContinue; ++anApIt) {
391         ++aNbPossibleSelections;
392
393         // stop if the target shape and result are found
394         GeomShapePtr aCurShape = anApIt->mySubshape;
395         if (!aCurShape)
396           aCurShape = anApIt->myResult->shape();
397
398         if (anApIt->myResult->isSame(theResult)) {
399           if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
400             isContinue = !aCurShape->isSame(theShape);
401           else if (theShape->isVertex() && aCurShape->isEdge()) {
402             GeomEdgePtr aCurEdge = aCurShape->edge();
403             GeomVertexPtr aVertex = theShape->vertex();
404             GeomPointPtr aCenter;
405             switch (anApIt->myCenterType) {
406             case (int)ModelAPI_AttributeSelection::CIRCLE_CENTER: {
407                 GeomCirclePtr aCirc = aCurEdge->circle();
408                 if (aCirc)
409                   aCenter = aCirc->center();
410                 break;
411               }
412             case (int)ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS: {
413                 GeomEllipsePtr anEllipse = aCurEdge->ellipse();
414                 if (anEllipse)
415                   aCenter = anEllipse->firstFocus();
416                 break;
417               }
418             case (int)ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS: {
419                 GeomEllipsePtr anEllipse = aCurEdge->ellipse();
420                 if (anEllipse)
421                   aCenter = anEllipse->secondFocus();
422                 break;
423               }
424             }
425             if (aCenter && aCenter->distance(aVertex->point()) < 1.e-7)
426               aCenters.push_back(std::pair<GeomShapePtr, int>(aCurShape, aNbPossibleSelections));
427           }
428         }
429       }
430       // passed till the appropriate shape, check the center of circle
431       // or a focus of ellipse is selected
432       if (isContinue && !aCenters.empty())
433         aNbPossibleSelections = aCenters.front().second;
434     }
435   }
436   return aNbPossibleSelections;
437 }
438
439 void ModelHighAPI_Dumper::DumpStorageGeom::write(const AttributeSelectionPtr& theAttrSelect)
440 {
441   GeomShapePtr aShape;
442   ResultPtr aContext;
443   getShapeAndContext(theAttrSelect, aShape, aContext);
444
445   // how to dump selection: construction features are dumped by name always
446   FeaturePtr aSelectedFeature;
447   FeaturePtr aFeature = theAttrSelect->contextFeature();
448   if (aShape && aContext && !aFeature)
449     aSelectedFeature = ModelAPI_Feature::feature(aContext->data()->owner());
450   bool isDumpByGeom = aSelectedFeature && aSelectedFeature->isInHistory();
451
452   if (isDumpByGeom) {
453     myDumpBuffer << "model.selection(\"" << aShape->shapeTypeStr();
454     // check the selected item is a ResultPart;
455     // in this case it is necessary to get shape with full transformation
456     // for correct calculation of the middle point
457     ResultPartPtr aResPart =
458       std::dynamic_pointer_cast<ModelAPI_ResultPart>(theAttrSelect->context());
459     if (aResPart && aShape->shapeType() == GeomAPI_Shape::COMPOUND)
460       aShape = aResPart->shape();
461     GeomPointPtr aMiddlePoint = aShape->middlePoint();
462     // calculate number of features, which could be selected by the same point
463     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelect->owner());
464     int aNbPossibleSelections = possibleSelectionsByPoint(aMiddlePoint,
465         theAttrSelect->context(), aShape, aSelectedFeature, anOwner);
466
467     // produce the index if the number of applicable features is greater than 1
468     std::string anIndex;
469     if (aNbPossibleSelections > 1) {
470       std::ostringstream anOutput;
471       anOutput << "_" << aNbPossibleSelections;
472       anIndex = anOutput.str();
473     }
474
475     myDumpBuffer << std::setprecision(THE_DUMP_PRECISION)
476                  << anIndex << "\", ("
477                  << aMiddlePoint->x() << ", "
478                  << aMiddlePoint->y() << ", "
479                  << aMiddlePoint->z() << ")";
480     myDumpBuffer << ")";
481   }
482   else
483     DumpStorage::write(theAttrSelect);
484 }
485
486 void ModelHighAPI_Dumper::DumpStorageWeak::write(const AttributeSelectionPtr& theAttrSelect)
487 {
488   GeomShapePtr aShape;
489   ResultPtr aContext;
490   getShapeAndContext(theAttrSelect, aShape, aContext);
491
492   bool aStandardDump = true;
493   if (aShape.get() && aContext.get() &&
494       aShape != aContext->shape()) { // weak naming for local selection only
495     GeomAlgoAPI_NExplode aNExplode(aContext->shape(), aShape->shapeType());
496     int anIndex = aNExplode.index(aShape);
497     if (anIndex != 0) { // found a week-naming index, so, export it
498       myDumpBuffer << "model.selection(\"" << aShape->shapeTypeStr() << "\", \""
499                    << theAttrSelect->contextName(aContext) << "\", " << anIndex << ")";
500       aStandardDump = false;
501     }
502   }
503   if (aStandardDump)
504     DumpStorage::write(theAttrSelect);
505 }
506 // ======================================================================
507
508
509 static int gCompositeStackDepth = 0;
510
511 ModelHighAPI_Dumper* ModelHighAPI_Dumper::mySelf = 0;
512
513 ModelHighAPI_Dumper::ModelHighAPI_Dumper()
514   : myDumpStorage(new DumpStorageBuffer),
515     myDumpPostponedInProgress(false)
516 {
517 }
518
519 ModelHighAPI_Dumper::~ModelHighAPI_Dumper()
520 {
521   delete myDumpStorage;
522 }
523
524 void ModelHighAPI_Dumper::setInstance(ModelHighAPI_Dumper* theDumper)
525 {
526   if (mySelf == 0)
527     mySelf = theDumper;
528 }
529
530 ModelHighAPI_Dumper* ModelHighAPI_Dumper::getInstance()
531 {
532   return mySelf;
533 }
534
535 void ModelHighAPI_Dumper::addCustomStorage(const ModelHighAPI_Dumper::DumpStoragePtr& theStorage)
536 {
537   myDumpStorage->addStorage(theStorage);
538 }
539
540 void ModelHighAPI_Dumper::clearCustomStorage()
541 {
542   myDumpStorage->clear();
543
544   myNames.clear();
545   myModules.clear();
546   myFeatureCount.clear();
547   myPostponed.clear();
548   while (!myEntitiesStack.empty())
549     myEntitiesStack.pop();
550   clearNotDumped();
551 }
552
553 void ModelHighAPI_Dumper::clearNotDumped()
554 {
555   myNotDumpedEntities.clear();
556 }
557
558 // Convert string to integer. If the string is not a number, return -1
559 static int toInt(const std::string& theString)
560 {
561   std::string::const_iterator aChar = theString.begin();
562   for (; aChar != theString.end(); ++aChar)
563     if (!std::isdigit(*aChar))
564       break;
565   if (aChar != theString.end())
566     return -1; // not a number
567   return std::stoi(theString);
568 }
569
570 const std::string& ModelHighAPI_Dumper::name(const EntityPtr& theEntity,
571                                              bool theSaveNotDumped,
572                                              bool theUseEntityName)
573 {
574   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
575   if (aFound != myNames.end())
576     return aFound->second.myCurrentName;
577
578   // entity is not found, store it
579   std::string aName, aKind;
580   bool isDefaultName = false;
581   bool isSaveNotDumped = theSaveNotDumped;
582   std::ostringstream aDefaultName;
583   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
584   if (aFeature) {
585     aName = aFeature->name();
586     aKind = aFeature->getKind();
587   } else {
588     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theEntity);
589     if (aFolder) {
590       aName = aFolder->data()->name();
591       aKind = ModelAPI_Folder::ID();
592       isSaveNotDumped = false;
593     }
594   }
595
596   ObjectPtr anObject = std::dynamic_pointer_cast<ModelAPI_Object>(theEntity);
597   if (anObject) {
598     DocumentPtr aDoc = anObject->document();
599     std::pair<int, int>& aNbFeatures = myFeatureCount[aDoc][aKind];
600     aNbFeatures.first += 1;
601
602     size_t anIndex = aName.find(aKind);
603     if (anIndex == 0 && aName[aKind.length()] == '_') { // name starts with "FeatureKind_"
604       std::string anIdStr = aName.substr(aKind.length() + 1);
605       int anId = toInt(anIdStr);
606
607       // Check number of already registered objects of such kind. Index of current object
608       // should be the same to identify feature's name as automatically generated.
609       if (aNbFeatures.first == anId && aNbFeatures.second < anId) {
610         // name is not user-defined
611         isDefaultName = true;
612
613         // check there are postponed features of this kind,
614         // dump their names, because the sequence of features may be changed
615         for (std::list<EntityPtr>::const_iterator aPpIt = myPostponed.begin();
616             aPpIt != myPostponed.end(); ++aPpIt) {
617           FeaturePtr aCurFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*aPpIt);
618           if (aCurFeature && aCurFeature->getKind() == aKind) {
619             myNames[*aPpIt].myIsDefault = false;
620             isDefaultName = false;
621           }
622         }
623       }
624
625       if (anId > aNbFeatures.second)
626         aNbFeatures.second = anId;
627     }
628
629     // obtain default name for the feature
630     if (theUseEntityName)
631       aDefaultName << aName;
632     else {
633       int aFullIndex = 0;
634       NbFeaturesMap::const_iterator aFIt = myFeatureCount.begin();
635       for (; aFIt != myFeatureCount.end(); ++aFIt) {
636         std::map<std::string, std::pair<int, int> >::const_iterator aFound =
637           aFIt->second.find(aKind);
638         if (aFound != aFIt->second.end())
639           aFullIndex += aFound->second.first;
640       }
641       aDefaultName << aKind << "_" << aFullIndex;
642     }
643   }
644
645   myNames[theEntity] = EntityName(aDefaultName.str(), aName, isDefaultName);
646   if (isSaveNotDumped)
647     myNotDumpedEntities.insert(theEntity);
648
649   // store names of results
650   if (aFeature)
651     saveResultNames(aFeature);
652
653   return myNames[theEntity].myCurrentName;
654 }
655
656 const std::string& ModelHighAPI_Dumper::parentName(const FeaturePtr& theEntity)
657 {
658   const std::set<AttributePtr>& aRefs = theEntity->data()->refsToMe();
659   std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
660   for (; aRefIt != aRefs.end(); ++aRefIt) {
661     CompositeFeaturePtr anOwner = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
662         ModelAPI_Feature::feature((*aRefIt)->owner()));
663     if (anOwner)
664       return name(anOwner);
665   }
666
667   static const std::string DUMMY;
668   return DUMMY;
669 }
670
671 void ModelHighAPI_Dumper::saveResultNames(const FeaturePtr& theFeature)
672 {
673   // Default name of the feature
674   bool isFeatureDefaultName = myNames[theFeature].myIsDefault;
675
676   // Save only names of results which is not correspond to default feature name
677   const std::list<ResultPtr>& aResults = theFeature->results();
678   std::list<ResultPtr> allRes;
679   ModelAPI_Tools::allResults(theFeature, allRes);
680   for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
681     std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(*aRes);
682     std::string aDefaultName = aName.first;
683     std::string aResName = (*aRes)->data()->name();
684     bool isUserDefined = !(isFeatureDefaultName && aDefaultName == aResName);
685     myNames[*aRes] =
686       EntityName(aResName, (isUserDefined ? aResName : std::string()), !isUserDefined);
687   }
688 }
689
690 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
691                                   const std::string& theFileName)
692 {
693   // dump top level document feature
694   static const std::string aDocName("partSet");
695   myNames[theDoc] = EntityName(aDocName, std::string(), true);
696   *this << aDocName << " = model.moduleDocument()" << std::endl;
697
698   // dump subfeatures and store result to file
699   bool isOk = process(theDoc) && myDumpStorage->exportTo(theFileName, myModules);
700   return isOk;
701 }
702
703 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
704 {
705   bool isOk = true;
706   std::list<ObjectPtr> anObjects = theDoc->allObjects();
707   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
708   // firstly, dump all parameters
709   for (; anObjIt != anObjects.end(); ++ anObjIt) {
710     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
711     if (aFeature)
712       dumpParameter(aFeature);
713   }
714   // dump all other features
715   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
716     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
717     if (aCompFeat) {
718       // iteratively process composite features,
719       // if the composite feature is the last in the document, no need to dump "model.do()" action
720       std::list<ObjectPtr>::const_iterator aNext = anObjIt;
721       isOk = process(aCompFeat, false, ++aNext != anObjects.end()) && isOk;
722     }
723     else if (!isDumped(EntityPtr(*anObjIt))) {
724       // dump folder
725       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
726       if (aFolder)
727         dumpFolder(aFolder);
728       else {
729         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
730         if (aFeature) // dump common feature
731           dumpFeature(aFeature);
732       }
733     }
734   }
735   // dump folders if any
736   dumpPostponed(true);
737   return isOk;
738 }
739
740 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
741                                   bool isForce, bool isDumpModelDo)
742 {
743   // increase composite features stack
744   ++gCompositeStackDepth;
745   // dump composite itself
746   if (!isDumped(EntityPtr(theComposite)) || isForce)
747     dumpFeature(FeaturePtr(theComposite), isForce);
748
749   // sub-part is processed independently, because it provides separate document
750   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
751     // dump name of the part if it is different from default
752     if (!myEntitiesStack.empty())
753       dumpEntitySetName();
754
755     // decrease composite features stack because we run into separate document
756     --gCompositeStackDepth;
757
758     ResultPartPtr aPartResult =
759         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
760     if (!aPartResult)
761       return false;
762     DocumentPtr aSubDoc = aPartResult->partDoc();
763     if (!aSubDoc)
764       return false;
765     // set name of document
766     const std::string& aPartName = myNames[theComposite].myCurrentName;
767     std::string aDocName = aPartName + "_doc";
768     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
769
770     // dump document in a separate line
771     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
772     // dump features in the document
773     bool aRes = process(aSubDoc);
774     if (isDumpModelDo)
775       *this << "model.do()\n";
776     *this << std::endl;
777     return aRes;
778   }
779
780   // dump sub-features
781   bool isOk = processSubs(theComposite);
782   // decrease composite features stack
783   --gCompositeStackDepth;
784
785   return isOk;
786 }
787
788 bool ModelHighAPI_Dumper::processSubs(
789   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
790   bool theDumpModelDo)
791 {
792   bool isOk = true;
793   // dump all sub-features;
794   bool isSubDumped = false;
795   int aNbSubs = theComposite->numberOfSubs();
796   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
797     FeaturePtr aFeature = theComposite->subFeature(anIndex);
798     if (isDumped(EntityPtr(aFeature)))
799       continue;
800
801     isSubDumped = true;
802     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
803     if (aCompFeat) // iteratively process composite features
804       isOk = process(aCompFeat) && isOk;
805     else
806       dumpFeature(aFeature, true);
807   }
808
809   bool isDumpSetName = !myEntitiesStack.empty() &&
810       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
811   bool isForceModelDo = isSubDumped && isDumpSetName &&
812       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
813   // It is necessary for the sketch to create its result when complete (command "model.do()").
814   // This option is set by flat theDumpModelDo.
815   // However, nested sketches are rebuilt by parent feature, so, they do not need
816   // explicit call of "model.do()". This will be controlled by the depth of the stack.
817   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
818     *this << "model.do()" << std::endl;
819
820   // dump "setName" for composite feature
821   if (isDumpSetName)
822     dumpEntitySetName();
823   return isOk;
824 }
825
826 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
827 {
828   // keep the name
829   name(theEntity, false);
830   myPostponed.push_back(theEntity);
831 }
832
833 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
834 {
835   if (myDumpPostponedInProgress)
836     return;
837
838   myDumpPostponedInProgress = true;
839   // make a copy of postponed entities, because the list will be updated
840   // if some features are not able to be dumped
841   std::list<EntityPtr> aPostponedCopy = myPostponed;
842   myPostponed.clear();
843
844   // iterate over postponed entities and try to dump them
845   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
846   for (; anIt != aPostponedCopy.end(); ++anIt) {
847     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
848     if (aFolder) {
849       if (theDumpFolders)
850         dumpFolder(aFolder);
851       else
852         myPostponed.push_back(*anIt);
853     }
854     else {
855       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
856       if (aFeature)
857         dumpFeature(aFeature, true);
858     }
859   }
860   myDumpPostponedInProgress = false;
861 }
862
863 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
864                                                      const FeaturePtr& theSubFeature)
865 {
866   name(theSubFeature, false);
867   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
868
869   // store results if they have user-defined names or colors
870   std::list<ResultPtr> aResultsWithNameOrColor;
871   const std::list<ResultPtr>& aResults = theSubFeature->results();
872   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
873   for (; aResIt != aResults.end(); ++aResIt) {
874     std::string aResName = (*aResIt)->data()->name();
875     myNames[*aResIt] = EntityName(aResName, aResName, false);
876     aResultsWithNameOrColor.push_back(*aResIt);
877   }
878
879   // store just dumped entity to stack
880   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
881
882   dumpEntitySetName();
883 }
884
885 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName)
886 {
887   myModules.insert(theModuleName);
888 }
889
890 void ModelHighAPI_Dumper::dumpEntitySetName()
891 {
892   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
893   bool isBufferEmpty = myDumpStorage->isBufferEmpty();
894
895   // dump "setName" for the entity
896   if (aLastDumped.myUserName) {
897     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
898     if (!anEntityNames.myIsDefault)
899       *myDumpStorage << anEntityNames.myCurrentName << ".setName(\""
900                      << anEntityNames.myUserName << "\")\n";
901     // don't dump "setName" for the entity twice
902     anEntityNames.myUserName.clear();
903     anEntityNames.myIsDefault = true;
904   }
905   // dump "setName" for results
906   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
907   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
908   for (; aResIt != aResEnd; ++aResIt) {
909     // set result name
910     EntityName& anEntityNames = myNames[*aResIt];
911     if (!anEntityNames.myIsDefault) {
912       *this << *aResIt;
913       *myDumpStorage << ".setName(\"" << anEntityNames.myUserName << "\")\n";
914       // don't dump "setName" for the entity twice
915       anEntityNames.myUserName.clear();
916       anEntityNames.myIsDefault = true;
917     }
918     // set result color
919     if (!isDefaultColor(*aResIt)) {
920       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
921       if (aColor && aColor->isInitialized()) {
922         *this << *aResIt;
923         *myDumpStorage << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
924                        << ", " << aColor->value(2) << ")\n";
925       }
926     }
927     // set result deflection
928     if (!isDefaultDeflection(*aResIt)) {
929       AttributeDoublePtr aDeflectionAttr =
930         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
931       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
932         *this << *aResIt;
933         *myDumpStorage << ".setDeflection(" << aDeflectionAttr->value() << ")\n";
934       }
935     }
936     // set result transparency
937     if (!isDefaultTransparency(*aResIt)) {
938       AttributeDoublePtr aTransparencyAttr =
939         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
940       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
941         *this << *aResIt;
942         *myDumpStorage << ".setTransparency(" << aTransparencyAttr->value() << ")\n";
943       }
944     }
945   }
946
947   myNames[aLastDumped.myEntity].myIsDumped = true;
948   myEntitiesStack.pop();
949
950   // clean buffer if it was clear before
951   if (isBufferEmpty)
952     myDumpStorage->mergeBuffer();
953 }
954
955 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
956 {
957   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
958   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
959   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
960          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
961 }
962
963 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
964 {
965   FeaturePtr aFeature;
966   if (theRefAttr->isObject())
967     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
968   else
969     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
970   return aFeature && isDumped(EntityPtr(aFeature));
971 }
972
973 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
974 {
975   std::list<ObjectPtr> aRefs = theRefList->list();
976   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
977   for (; anIt != aRefs.end(); ++anIt) {
978     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
979     if (aFeature && !isDumped(EntityPtr(aFeature)))
980       return false;
981   }
982   return true;
983 }
984
985 static bool isSketchSub(const FeaturePtr& theFeature)
986 {
987   static const std::string SKETCH("Sketch");
988   CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
989   return anOwner && anOwner->getKind() == SKETCH;
990 }
991
992 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
993 {
994   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
995   if (!aColor || !aColor->isInitialized())
996     return true;
997
998   // check the result belongs to sketch entity, do not dump color in this way
999   ResultConstructionPtr aResConstr =
1000       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theResult);
1001   if (aResConstr) {
1002     FeaturePtr aFeature = ModelAPI_Feature::feature(theResult->data()->owner());
1003     if (isSketchSub(aFeature))
1004       return true;
1005   }
1006
1007   std::string aSection, aName, aDefault;
1008   theResult->colorConfigInfo(aSection, aName, aDefault);
1009
1010   // dump current color
1011   std::ostringstream aColorInfo;
1012   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
1013
1014   return aDefault == aColorInfo.str();
1015 }
1016
1017 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
1018 {
1019   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1020   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
1021     return true;
1022   }
1023
1024   double aCurrent = aDeflectionAttr->value();
1025   double aDefault = -1;
1026
1027   bool isConstruction = false;
1028   std::string aResultGroup = theResult->groupName();
1029   if (aResultGroup == ModelAPI_ResultConstruction::group())
1030     isConstruction = true;
1031   else if (aResultGroup == ModelAPI_ResultBody::group()) {
1032     GeomShapePtr aGeomShape = theResult->shape();
1033     if (aGeomShape.get()) {
1034       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
1035       // correction of deviation for them should not influence to the application performance
1036       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
1037       isConstruction = !anExp.more();
1038     }
1039   }
1040   if (isConstruction)
1041     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
1042   else
1043     aDefault = Config_PropManager::real("Visualization", "body_deflection");
1044
1045   return fabs(aCurrent - aDefault) < 1.e-12;
1046 }
1047
1048 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
1049 {
1050   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1051   if(!anAttribute || !anAttribute->isInitialized()) {
1052     return true;
1053   }
1054   return fabs(anAttribute->value()) < 1.e-12;
1055 }
1056
1057 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
1058 {
1059   *myDumpStorage << theChar;
1060   return *this;
1061 }
1062
1063 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
1064 {
1065   *myDumpStorage << theString;
1066   return *this;
1067 }
1068
1069 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
1070 {
1071   *myDumpStorage << theString;
1072   return *this;
1073 }
1074
1075 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
1076 {
1077   *myDumpStorage << (theValue ? "True" : "False");
1078   return *this;
1079 }
1080
1081 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
1082 {
1083   *myDumpStorage << theValue;
1084   return *this;
1085 }
1086
1087 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
1088 {
1089   *myDumpStorage << theValue;
1090   return *this;
1091 }
1092
1093 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
1094 {
1095   importModule("GeomAPI");
1096   *myDumpStorage << "GeomAPI_Pnt(" << thePoint->x() << ", "
1097                  << thePoint->y() << ", " << thePoint->z() << ")";
1098   return *this;
1099 }
1100
1101 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
1102 {
1103   importModule("GeomAPI");
1104   *myDumpStorage << "GeomAPI_Dir(" << theDir->x() << ", "
1105                  << theDir->y() << ", " << theDir->z() << ")";
1106   return *this;
1107 }
1108
1109 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1110     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
1111 {
1112   *myDumpStorage << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
1113   return *this;
1114 }
1115
1116 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1117     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
1118 {
1119   static const int aSize = 3;
1120   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
1121   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
1122   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1123   return *this;
1124 }
1125
1126 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1127     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
1128 {
1129   static const int aSize = 2;
1130   double aValues[aSize] = {thePoint->x(), thePoint->y()};
1131   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
1132   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1133   return *this;
1134 }
1135
1136 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1137   const std::shared_ptr<GeomDataAPI_Point2DArray>& thePointArray)
1138 {
1139   static const int aThreshold = 4;
1140   static bool aDumpAsIs = false;
1141   static std::string aSeparator = "";
1142   // if number of elements in the list if greater than a threshold,
1143   // dump it in a separate line with specific name
1144   int aSize = thePointArray->size();
1145   if (aDumpAsIs || aSize <= aThreshold) {
1146     *myDumpStorage << "[";
1147     GeomPnt2dPtr aPoint = thePointArray->pnt(0);
1148     *myDumpStorage << "(" << aPoint->x() << ", " << aPoint->y() << ")";
1149     for (int anIndex = 1; anIndex < aSize; ++anIndex) {
1150       aPoint = thePointArray->pnt(anIndex);
1151       *myDumpStorage << "," << aSeparator << " (" << aPoint->x() << ", " << aPoint->y() << ")";
1152     }
1153     *myDumpStorage << aSeparator << "]";
1154   }
1155   else {
1156     // name of list
1157     FeaturePtr anOwner = ModelAPI_Feature::feature(thePointArray->owner());
1158     std::string aListName = name(anOwner) + "_" + thePointArray->id();
1159     // reserve dumped buffer and store list "as is"
1160     myDumpStorage->reserveBuffer();
1161     aDumpAsIs = true;
1162     aSeparator = std::string("\n") + std::string(aListName.size() + 3, ' ');
1163     *this << aListName << " = " << thePointArray << "\n";
1164     aDumpAsIs = false;
1165     aSeparator = "";
1166     // append reserved data to the end of the current buffer
1167     myDumpStorage->restoreReservedBuffer();
1168     *myDumpStorage << aListName;
1169   }
1170   return *this;
1171 }
1172
1173 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1174     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
1175 {
1176   *myDumpStorage << (theAttrBool->value() ? "True" : "False");
1177   return *this;
1178 }
1179
1180 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1181     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
1182 {
1183   std::string aText = theAttrInt->text();
1184   if (aText.empty())
1185     *myDumpStorage << theAttrInt->value();
1186   else
1187     *myDumpStorage << "\"" << aText << "\"";
1188   return *this;
1189 }
1190
1191 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1192     const std::shared_ptr<ModelAPI_AttributeIntArray>& theArray)
1193 {
1194   *myDumpStorage << "[";
1195   int aSize = theArray->size();
1196   if (aSize > 0) {
1197     *myDumpStorage << theArray->value(0);
1198     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1199       *myDumpStorage << ", " << theArray->value(anIndex);
1200   }
1201   *myDumpStorage << "]";
1202   return *this;
1203 }
1204
1205 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1206     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
1207 {
1208   std::string aText = theAttrReal->text();
1209   if (aText.empty())
1210     *myDumpStorage << theAttrReal->value();
1211   else
1212     *myDumpStorage << "\"" << aText << "\"";
1213   return *this;
1214 }
1215
1216 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1217   const std::shared_ptr<ModelAPI_AttributeDoubleArray>& theArray)
1218 {
1219   *myDumpStorage << "[";
1220   int aSize = theArray->size();
1221   if (aSize > 0) {
1222     *myDumpStorage << theArray->value(0);
1223     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1224       *myDumpStorage << ", " << theArray->value(anIndex);
1225   }
1226   *myDumpStorage << "]";
1227   return *this;
1228 }
1229
1230 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1231     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
1232 {
1233   *myDumpStorage << "\"" << theAttrStr->value() << "\"";
1234   return *this;
1235 }
1236
1237 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
1238 {
1239   *myDumpStorage << name(theFolder);
1240
1241   // add dumped folder to a stack
1242   if (!myNames[theFolder].myIsDumped &&
1243      (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theFolder))
1244     myEntitiesStack.push(LastDumpedEntity(theFolder, !myNames[theFolder].myIsDefault));
1245
1246   return *this;
1247 }
1248
1249 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
1250 {
1251   *myDumpStorage << name(theEntity);
1252
1253   if (!myNames[theEntity].myIsDumped) {
1254     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
1255     // store results if they have user-defined names or colors
1256     std::list<ResultPtr> aResultsWithNameOrColor;
1257     std::list<ResultPtr> allRes;
1258     ModelAPI_Tools::allResults(theEntity, allRes);
1259     for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1260       if(!myNames[*aRes].myIsDefault || !isDefaultColor(*aRes) ||
1261          !isDefaultDeflection(*aRes) || !isDefaultTransparency(*aRes))
1262         aResultsWithNameOrColor.push_back(*aRes);
1263     }
1264     // store just dumped entity to stack
1265     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
1266       myEntitiesStack.push(
1267           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
1268   }
1269
1270   // remove entity from the list of not dumped items
1271   myNotDumpedEntities.erase(theEntity);
1272   return *this;
1273 }
1274
1275 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
1276 {
1277   // iterate in the structure of sub-results to the parent
1278   ResultPtr aCurRes = theResult;
1279   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
1280   std::list<int> anIndices; // indexes of results in the parent result, starting from topmost
1281   while(aCurRes.get()) {
1282     ResultBodyPtr aParent = ModelAPI_Tools::bodyOwner(aCurRes);
1283     if (aParent) {
1284       anIndices.push_front(ModelAPI_Tools::bodyIndex(aCurRes));
1285     } else { // index of the result in the feature
1286       std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
1287       for(int anIndex = 0; aRes != aFeature->results().cend(); aRes++, anIndex++) {
1288         if (*aRes == aCurRes) {
1289           anIndices.push_front(anIndex);
1290           break;
1291         }
1292       }
1293     }
1294     aCurRes = aParent;
1295   }
1296
1297   *myDumpStorage << name(aFeature);
1298   for (std::list<int>::iterator anI = anIndices.begin(); anI != anIndices.end(); anI++) {
1299     if (anI == anIndices.begin()) {
1300       if(*anI == 0) {
1301         *myDumpStorage << ".result()";
1302       }
1303       else {
1304         *myDumpStorage << ".results()[" << *anI << "]";
1305       }
1306     } else {
1307       *myDumpStorage << ".subResult(" << *anI << ")";
1308     }
1309   }
1310
1311   return *this;
1312 }
1313
1314 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::list<ResultPtr>& theResults)
1315 {
1316   *this << "[";
1317   for (std::list<ResultPtr>::const_iterator anIt = theResults.begin();
1318        anIt != theResults.end(); ++anIt) {
1319     if (anIt != theResults.begin())
1320       *this << ", ";
1321     *this << *anIt;
1322   }
1323   *this << "]";
1324   return *this;
1325 }
1326
1327 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
1328 {
1329   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
1330   if(aFeature.get()) {
1331     *myDumpStorage << name(aFeature);
1332     return *this;
1333   }
1334
1335   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1336   if(aResult.get()) {
1337     *this << aResult;
1338     return *this;
1339   }
1340
1341   return *this;
1342 }
1343
1344 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
1345 {
1346   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
1347
1348   std::string aWrapperPrefix, aWrapperSuffix;
1349   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
1350   // In this case we need to cast explicitly feature to appropriate type.
1351   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
1352   AttributeReferencePtr hasParent = anOwner->reference("ParentFeature");
1353   if ((isCopy.get() && isCopy->value()) || (hasParent && hasParent->value())) {
1354     aWrapperPrefix = featureWrapper(anOwner) + "(";
1355     aWrapperSuffix = ")";
1356     importModule("SketchAPI");
1357   }
1358
1359   *myDumpStorage << aWrapperPrefix << name(anOwner) << aWrapperSuffix
1360                  << "." << attributeGetter(anOwner, theAttr->id()) << "()";
1361   return *this;
1362 }
1363
1364 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1365     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
1366 {
1367   if (theRefAttr->isObject())
1368     *this << theRefAttr->object();
1369   else
1370     *this << theRefAttr->attr();
1371   return *this;
1372 }
1373
1374 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1375     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
1376 {
1377   *myDumpStorage << "[";
1378   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
1379   bool isAdded = false;
1380   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
1381   for (; anIt != aList.end(); ++anIt) {
1382     if (isAdded)
1383       *myDumpStorage << ", ";
1384     else
1385       isAdded = true;
1386     if (anIt->first)
1387       *this << anIt->first;
1388     else if (anIt->second)
1389       * this << anIt->second;
1390   }
1391   *myDumpStorage << "]";
1392   return *this;
1393 }
1394
1395 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1396     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
1397 {
1398   *this << theReference->value();
1399   return *this;
1400 }
1401
1402 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1403     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
1404 {
1405   static const int aThreshold = 2;
1406   static bool aDumpAsIs = false;
1407   // if number of elements in the list if greater than a threshold,
1408   // dump it in a separate line with specific name
1409   if (aDumpAsIs || theRefList->size() <= aThreshold) {
1410     *myDumpStorage << "[";
1411     std::list<ObjectPtr> aList = theRefList->list();
1412     bool isAdded = false;
1413     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
1414     for (; anIt != aList.end(); ++anIt) {
1415       if (isAdded)
1416         *myDumpStorage << ", ";
1417       else
1418         isAdded = true;
1419
1420       *this << *anIt;
1421     }
1422     *myDumpStorage << "]";
1423   } else {
1424     // name of list
1425     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
1426     std::string aListName = name(anOwner) + "_objects";
1427     // reserve dumped buffer and store list "as is"
1428     myDumpStorage->reserveBuffer();
1429     aDumpAsIs = true;
1430     *this << aListName << " = " << theRefList << "\n";
1431     aDumpAsIs = false;
1432     // append reserved data to the end of the current buffer
1433     myDumpStorage->restoreReservedBuffer();
1434     *myDumpStorage << aListName;
1435   }
1436   return *this;
1437 }
1438
1439 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1440     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
1441 {
1442   myDumpStorage->write(theAttrSelect);
1443   return *this;
1444 }
1445
1446 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1447     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
1448 {
1449   static const int aThreshold = 2;
1450   static bool aDumpAsIs = false;
1451   // if number of elements in the list if greater than a threshold,
1452   // dump it in a separate line with specific name
1453   if (aDumpAsIs || theAttrSelList->size() <= aThreshold) {
1454     *myDumpStorage << "[";
1455
1456     GeomShapePtr aShape;
1457     std::string aShapeTypeStr;
1458
1459     bool isAdded = false;
1460
1461     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
1462       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1463       aShape = anAttribute->value();
1464       if(!aShape.get()) {
1465         ResultPtr aContext = anAttribute->context();
1466         if (aContext.get())
1467           aShape = aContext->shape();
1468       }
1469
1470       if(!aShape.get()) {
1471         continue;
1472       }
1473
1474       if(isAdded) {
1475         *myDumpStorage << ", ";
1476       } else {
1477         isAdded = true;
1478       }
1479       *this << anAttribute;
1480     }
1481
1482     // check selection list is obtained by filters
1483     FiltersFeaturePtr aFilters = theAttrSelList->filters();
1484     if (aFilters) {
1485       if (theAttrSelList->size() > 0)
1486         *myDumpStorage << ", ";
1487       dumpFeature(aFilters, true);
1488     }
1489
1490     *myDumpStorage << "]";
1491   } else {
1492     // obtain name of list (the feature may contain several selection lists)
1493     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1494     std::string aListName = name(anOwner) + "_objects";
1495     std::list<AttributePtr> aSelLists =
1496         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1497     if (aSelLists.size() > 1) {
1498       int anIndex = 1;
1499       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1500            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1501         if ((*aSIt).get() == theAttrSelList.get())
1502           break;
1503       std::ostringstream aSStream;
1504       aSStream << aListName << "_" << anIndex;
1505       aListName = aSStream.str();
1506     }
1507     // reserve dumped buffer and store list "as is"
1508     myDumpStorage->reserveBuffer();
1509     aDumpAsIs = true;
1510     *this << aListName << " = " << theAttrSelList << "\n";
1511     aDumpAsIs = false;
1512     // append reserved data to the end of the current buffer
1513     myDumpStorage->restoreReservedBuffer();
1514     *myDumpStorage << aListName;
1515   }
1516   return *this;
1517 }
1518
1519 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1520   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1521 {
1522   std::ostringstream aBuffer;
1523   aBuffer << "[";
1524   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1525     if (anIndex != 0)
1526       aBuffer << ", ";
1527
1528     aBuffer << "\"" << theArray->value(anIndex) << "\"";
1529   }
1530   aBuffer << "]";
1531
1532   myDumpStorage->write(aBuffer.str());
1533   return *this;
1534 }
1535
1536 /// Dump std::endl
1537 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1538                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1539 {
1540   *theDumper.myDumpStorage << theEndl;
1541
1542   if (!theDumper.myEntitiesStack.empty()) {
1543     bool isCopy;
1544     // all copies have been stored into stack, pop them all
1545     do {
1546       isCopy = false;
1547       // Name for composite feature is dumped when all sub-entities are dumped
1548       // (see method ModelHighAPI_Dumper::processSubs).
1549       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1550       CompositeFeaturePtr aComposite =
1551           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1552       if (!aComposite) {
1553         theDumper.dumpEntitySetName();
1554         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1555         if (aFeature) {
1556           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1557           isCopy = aCopyAttr.get() && aCopyAttr->value();
1558         }
1559       }
1560     } while (isCopy && !theDumper.myEntitiesStack.empty());
1561   }
1562
1563   // store all not-dumped entities first
1564   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1565   theDumper.myDumpStorage->reserveBuffer();
1566   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1567   for (; anIt != aNotDumped.end(); ++anIt) {
1568     // if the feature is composite, dump it with all subs
1569     CompositeFeaturePtr aCompFeat =
1570         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1571     if (aCompFeat)
1572       theDumper.process(aCompFeat, true);
1573     else {
1574       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1575       theDumper.dumpFeature(aFeature, true);
1576       // dump the Projection feature which produces this "Copy" entity
1577       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1578       if (aCopyAttr.get() && aCopyAttr->value())
1579       {
1580         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1581         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1582         for (; aRefIt != aRefs.end(); ++aRefIt)
1583           if ((*aRefIt)->id() == "ProjectedFeature")
1584           { // process projection only
1585             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1586             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1587               theDumper.dumpFeature(anOwner, true);
1588           }
1589       }
1590     }
1591   }
1592
1593   // then store the reserved data
1594   theDumper.myDumpStorage->restoreReservedBuffer();
1595   theDumper.myDumpStorage->mergeBuffer();
1596
1597   // now, store all postponed features
1598   theDumper.dumpPostponed();
1599
1600   return theDumper;
1601 }
1602
1603
1604 void ModelHighAPI_Dumper::exportVariables() const
1605 {
1606   DocumentPtr aRoot = ModelAPI_Session::get()->moduleDocument();
1607   EntityNameMap::const_iterator aNameIter = myNames.cbegin();
1608   for(; aNameIter != myNames.end(); aNameIter++) {
1609     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aNameIter->first);
1610     if (aFeature.get() && aFeature->document() != aRoot) {
1611       FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, aFeature->document());
1612       if (aPartFeat.get()) {
1613         int aFeatureId = aFeature->data()->featureId();
1614         int aPartId = aPartFeat->data()->featureId();
1615         std::ostringstream anEntryStr;
1616         anEntryStr<<aPartId<<":"<<aFeatureId;
1617         std::string anEntry = anEntryStr.str();
1618         exportVariable(anEntry, aNameIter->second.myCurrentName);
1619         size_t aSize = aFeature->results().size();
1620         if (aSize > 1) { // additional entries for features with more than one result
1621           for(int a = 1; a < aSize; a++) {
1622             std::ostringstream aResEntryStr;
1623             aResEntryStr<<anEntry<<":"<<a;
1624             std::string aResEntry = aResEntryStr.str();
1625             exportVariable(aResEntry, aNameIter->second.myCurrentName);
1626           }
1627         }
1628       }
1629     }
1630   }
1631 }