]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModelHighAPI/ModelHighAPI_Dumper.cpp
Salome HOME
Split too long line to meet the coding style.
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2014-2019  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     std::list<FeaturePtr> anAdditionalFeatures = aDoc2->allFeatures();
336     aFeatures.insert(aFeatures.end(), anAdditionalFeatures.begin(), anAdditionalFeatures.end());
337   }
338
339   CompositeFeaturePtr aLastCompositeFeature;
340
341   std::list<FeaturePtr>::const_iterator aFIt = aFeatures.begin();
342   while (aFIt != aFeatures.end() && *aFIt != theStartFeature) {
343     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFIt);
344     if (aCompFeat)
345       aLastCompositeFeature = aCompFeat;
346     ++aFIt;
347   }
348
349   // collect the list of composite features, containing the last feature;
350   // these features should be excluded from searching,
351   // because the feature cannot select sub-shapes from its parent
352   std::set<FeaturePtr> aEndFeatureParents = ModelAPI_Tools::getParents(theEndFeature);
353
354   int aNbPossibleSelections = 0;
355   for (; aFIt != aFeatures.end() && *aFIt != theEndFeature; ++aFIt) {
356     bool isSkipFeature = false;
357     if (aLastCompositeFeature && aLastCompositeFeature->isSub(*aFIt))
358       isSkipFeature = true;
359     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFIt);
360     if (aCompFeat) {
361       ResultPartPtr aPartRes =
362           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCompFeat->firstResult());
363       if (!aPartRes)
364         aLastCompositeFeature = aCompFeat;
365       if (aEndFeatureParents.find(aCompFeat) != aEndFeatureParents.end()) {
366         // do not process the parent for the last feature,
367         // because it cannot select objects from its parent
368         isSkipFeature = true;
369       }
370     }
371     if (isSkipFeature)
372       continue;
373
374     std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anApproproate;
375     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*aFIt, thePoint, theShape->shapeType(),
376                                                  anApproproate)) {
377       bool isContinue = true;
378       std::list<std::pair<GeomShapePtr, int> > aCenters;
379       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anApproproate.begin();
380       for (; anApIt != anApproproate.end() && isContinue; ++anApIt) {
381         ++aNbPossibleSelections;
382
383         // stop if the target shape and result are found
384         GeomShapePtr aCurShape = anApIt->mySubshape;
385         if (!aCurShape)
386           aCurShape = anApIt->myResult->shape();
387
388         if (anApIt->myResult->isSame(theResult)) {
389           if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
390             isContinue = !aCurShape->isSame(theShape);
391           else if (theShape->isVertex() && aCurShape->isEdge()) {
392             GeomEdgePtr aCurEdge = aCurShape->edge();
393             GeomVertexPtr aVertex = theShape->vertex();
394             GeomPointPtr aCenter;
395             switch (anApIt->myCenterType) {
396             case (int)ModelAPI_AttributeSelection::CIRCLE_CENTER: {
397                 GeomCirclePtr aCirc = aCurEdge->circle();
398                 if (aCirc)
399                   aCenter = aCirc->center();
400                 break;
401               }
402             case (int)ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS: {
403                 GeomEllipsePtr anEllipse = aCurEdge->ellipse();
404                 if (anEllipse)
405                   aCenter = anEllipse->firstFocus();
406                 break;
407               }
408             case (int)ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS: {
409                 GeomEllipsePtr anEllipse = aCurEdge->ellipse();
410                 if (anEllipse)
411                   aCenter = anEllipse->secondFocus();
412                 break;
413               }
414             }
415             if (aCenter && aCenter->distance(aVertex->point()) < 1.e-7)
416               aCenters.push_back(std::pair<GeomShapePtr, int>(aCurShape, aNbPossibleSelections));
417           }
418         }
419       }
420       // passed till the appropriate shape, check the center of circle
421       // or a focus of ellipse is selected
422       if (isContinue && !aCenters.empty())
423         aNbPossibleSelections = aCenters.front().second;
424     }
425   }
426   return aNbPossibleSelections;
427 }
428
429 void ModelHighAPI_Dumper::DumpStorageGeom::write(const AttributeSelectionPtr& theAttrSelect)
430 {
431   GeomShapePtr aShape;
432   ResultPtr aContext;
433   getShapeAndContext(theAttrSelect, aShape, aContext);
434
435   // how to dump selection: construction features are dumped by name always
436   FeaturePtr aSelectedFeature;
437   FeaturePtr aFeature = theAttrSelect->contextFeature();
438   if (aShape && aContext && !aFeature)
439     aSelectedFeature = ModelAPI_Feature::feature(aContext->data()->owner());
440   bool isDumpByGeom = aSelectedFeature && aSelectedFeature->isInHistory();
441
442   if (isDumpByGeom) {
443     myDumpBuffer << "model.selection(\"" << aShape->shapeTypeStr();
444     // check the selected item is a ResultPart;
445     // in this case it is necessary to get shape with full transformation
446     // for correct calculation of the middle point
447     ResultPartPtr aResPart =
448       std::dynamic_pointer_cast<ModelAPI_ResultPart>(theAttrSelect->context());
449     if (aResPart && aShape->shapeType() == GeomAPI_Shape::COMPOUND)
450       aShape = aResPart->shape();
451     GeomPointPtr aMiddlePoint = aShape->middlePoint();
452     // calculate number of features, which could be selected by the same point
453     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelect->owner());
454     int aNbPossibleSelections = possibleSelectionsByPoint(aMiddlePoint,
455         theAttrSelect->context(), aShape, aSelectedFeature, anOwner);
456
457     // produce the index if the number of applicable features is greater than 1
458     std::string anIndex;
459     if (aNbPossibleSelections > 1) {
460       std::ostringstream anOutput;
461       anOutput << "_" << aNbPossibleSelections;
462       anIndex = anOutput.str();
463     }
464
465     myDumpBuffer << std::setprecision(THE_DUMP_PRECISION)
466                  << anIndex << "\", ("
467                  << aMiddlePoint->x() << ", "
468                  << aMiddlePoint->y() << ", "
469                  << aMiddlePoint->z() << ")";
470     myDumpBuffer << ")";
471   }
472   else
473     DumpStorage::write(theAttrSelect);
474 }
475
476 void ModelHighAPI_Dumper::DumpStorageWeak::write(const AttributeSelectionPtr& theAttrSelect)
477 {
478   GeomShapePtr aShape;
479   ResultPtr aContext;
480   getShapeAndContext(theAttrSelect, aShape, aContext);
481
482   bool aStandardDump = true;
483   if (aShape.get() && aContext.get() &&
484       aShape != aContext->shape()) { // weak naming for local selection only
485     GeomAlgoAPI_NExplode aNExplode(aContext->shape(), aShape->shapeType());
486     int anIndex = aNExplode.index(aShape);
487     if (anIndex != 0) { // found a week-naming index, so, export it
488       myDumpBuffer << "model.selection(\"" << aShape->shapeTypeStr() << "\", \""
489                    << theAttrSelect->contextName(aContext) << "\", " << anIndex << ")";
490       aStandardDump = false;
491     }
492   }
493   if (aStandardDump)
494     DumpStorage::write(theAttrSelect);
495 }
496 // ======================================================================
497
498
499 static int gCompositeStackDepth = 0;
500
501 ModelHighAPI_Dumper* ModelHighAPI_Dumper::mySelf = 0;
502
503 ModelHighAPI_Dumper::ModelHighAPI_Dumper()
504   : myDumpStorage(new DumpStorageBuffer),
505     myDumpPostponedInProgress(false)
506 {
507 }
508
509 ModelHighAPI_Dumper::~ModelHighAPI_Dumper()
510 {
511   delete myDumpStorage;
512 }
513
514 void ModelHighAPI_Dumper::setInstance(ModelHighAPI_Dumper* theDumper)
515 {
516   if (mySelf == 0)
517     mySelf = theDumper;
518 }
519
520 ModelHighAPI_Dumper* ModelHighAPI_Dumper::getInstance()
521 {
522   return mySelf;
523 }
524
525 void ModelHighAPI_Dumper::addCustomStorage(const ModelHighAPI_Dumper::DumpStoragePtr& theStorage)
526 {
527   myDumpStorage->addStorage(theStorage);
528 }
529
530 void ModelHighAPI_Dumper::clearCustomStorage()
531 {
532   myDumpStorage->clear();
533
534   myNames.clear();
535   myModules.clear();
536   myFeatureCount.clear();
537   myPostponed.clear();
538   while (!myEntitiesStack.empty())
539     myEntitiesStack.pop();
540   clearNotDumped();
541 }
542
543 void ModelHighAPI_Dumper::clearNotDumped()
544 {
545   myNotDumpedEntities.clear();
546 }
547
548 // Convert string to integer. If the string is not a number, return -1
549 static int toInt(const std::string& theString)
550 {
551   std::string::const_iterator aChar = theString.begin();
552   for (; aChar != theString.end(); ++aChar)
553     if (!std::isdigit(*aChar))
554       break;
555   if (aChar != theString.end())
556     return -1; // not a number
557   return std::stoi(theString);
558 }
559
560 const std::string& ModelHighAPI_Dumper::name(const EntityPtr& theEntity,
561                                              bool theSaveNotDumped,
562                                              bool theUseEntityName)
563 {
564   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
565   if (aFound != myNames.end())
566     return aFound->second.myCurrentName;
567
568   // entity is not found, store it
569   std::string aName, aKind;
570   bool isDefaultName = false;
571   bool isSaveNotDumped = theSaveNotDumped;
572   std::ostringstream aDefaultName;
573   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
574   if (aFeature) {
575     aName = aFeature->name();
576     aKind = aFeature->getKind();
577   } else {
578     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theEntity);
579     if (aFolder) {
580       aName = aFolder->data()->name();
581       aKind = ModelAPI_Folder::ID();
582       isSaveNotDumped = false;
583     }
584   }
585
586   ObjectPtr anObject = std::dynamic_pointer_cast<ModelAPI_Object>(theEntity);
587   if (anObject) {
588     DocumentPtr aDoc = anObject->document();
589     std::pair<int, int>& aNbFeatures = myFeatureCount[aDoc][aKind];
590     aNbFeatures.first += 1;
591
592     size_t anIndex = aName.find(aKind);
593     if (anIndex == 0 && aName[aKind.length()] == '_') { // name starts with "FeatureKind_"
594       std::string anIdStr = aName.substr(aKind.length() + 1);
595       int anId = toInt(anIdStr);
596
597       // Check number of already registered objects of such kind. Index of current object
598       // should be the same to identify feature's name as automatically generated.
599       if (aNbFeatures.first == anId && aNbFeatures.second < anId) {
600         // name is not user-defined
601         isDefaultName = true;
602
603         // check there are postponed features of this kind,
604         // dump their names, because the sequence of features may be changed
605         for (std::list<EntityPtr>::const_iterator aPpIt = myPostponed.begin();
606             aPpIt != myPostponed.end(); ++aPpIt) {
607           FeaturePtr aCurFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*aPpIt);
608           if (aCurFeature && aCurFeature->getKind() == aKind) {
609             myNames[*aPpIt].myIsDefault = false;
610             isDefaultName = false;
611           }
612         }
613       }
614
615       if (anId > aNbFeatures.second)
616         aNbFeatures.second = anId;
617     }
618
619     // obtain default name for the feature
620     if (theUseEntityName)
621       aDefaultName << aName;
622     else {
623       int aFullIndex = 0;
624       NbFeaturesMap::const_iterator aFIt = myFeatureCount.begin();
625       for (; aFIt != myFeatureCount.end(); ++aFIt) {
626         std::map<std::string, std::pair<int, int> >::const_iterator aFound =
627           aFIt->second.find(aKind);
628         if (aFound != aFIt->second.end())
629           aFullIndex += aFound->second.first;
630       }
631       aDefaultName << aKind << "_" << aFullIndex;
632     }
633   }
634
635   myNames[theEntity] = EntityName(aDefaultName.str(), aName, isDefaultName);
636   if (isSaveNotDumped)
637     myNotDumpedEntities.insert(theEntity);
638
639   // store names of results
640   if (aFeature)
641     saveResultNames(aFeature);
642
643   return myNames[theEntity].myCurrentName;
644 }
645
646 const std::string& ModelHighAPI_Dumper::parentName(const FeaturePtr& theEntity)
647 {
648   const std::set<AttributePtr>& aRefs = theEntity->data()->refsToMe();
649   std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
650   for (; aRefIt != aRefs.end(); ++aRefIt) {
651     CompositeFeaturePtr anOwner = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
652         ModelAPI_Feature::feature((*aRefIt)->owner()));
653     if (anOwner)
654       return name(anOwner);
655   }
656
657   static const std::string DUMMY;
658   return DUMMY;
659 }
660
661 void ModelHighAPI_Dumper::saveResultNames(const FeaturePtr& theFeature)
662 {
663   // Default name of the feature
664   bool isFeatureDefaultName = myNames[theFeature].myIsDefault;
665
666   // Save only names of results which is not correspond to default feature name
667   const std::list<ResultPtr>& aResults = theFeature->results();
668   std::list<ResultPtr> allRes;
669   ModelAPI_Tools::allResults(theFeature, allRes);
670   for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
671     std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(*aRes);
672     std::string aDefaultName = aName.first;
673     std::string aResName = (*aRes)->data()->name();
674     bool isUserDefined = !(isFeatureDefaultName && aDefaultName == aResName);
675     myNames[*aRes] =
676       EntityName(aResName, (isUserDefined ? aResName : std::string()), !isUserDefined);
677   }
678 }
679
680 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
681                                   const std::string& theFileName)
682 {
683   // dump top level document feature
684   static const std::string aDocName("partSet");
685   myNames[theDoc] = EntityName(aDocName, std::string(), true);
686   *this << aDocName << " = model.moduleDocument()" << std::endl;
687
688   // dump subfeatures and store result to file
689   bool isOk = process(theDoc) && myDumpStorage->exportTo(theFileName, myModules);
690   clearCustomStorage();
691   return isOk;
692 }
693
694 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
695 {
696   bool isOk = true;
697   std::list<ObjectPtr> anObjects = theDoc->allObjects();
698   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
699   // firstly, dump all parameters
700   for (; anObjIt != anObjects.end(); ++ anObjIt) {
701     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
702     if (aFeature)
703       dumpParameter(aFeature);
704   }
705   // dump all other features
706   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
707     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
708     if (aCompFeat) {
709       // iteratively process composite features,
710       // if the composite feature is the last in the document, no need to dump "model.do()" action
711       std::list<ObjectPtr>::const_iterator aNext = anObjIt;
712       isOk = process(aCompFeat, false, ++aNext != anObjects.end()) && isOk;
713     }
714     else if (!isDumped(EntityPtr(*anObjIt))) {
715       // dump folder
716       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
717       if (aFolder)
718         dumpFolder(aFolder);
719       else {
720         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
721         if (aFeature) // dump common feature
722           dumpFeature(aFeature);
723       }
724     }
725   }
726   // dump folders if any
727   dumpPostponed(true);
728   return isOk;
729 }
730
731 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
732                                   bool isForce, bool isDumpModelDo)
733 {
734   // increase composite features stack
735   ++gCompositeStackDepth;
736   // dump composite itself
737   if (!isDumped(EntityPtr(theComposite)) || isForce)
738     dumpFeature(FeaturePtr(theComposite), isForce);
739
740   // sub-part is processed independently, because it provides separate document
741   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
742     // dump name of the part if it is different from default
743     if (!myEntitiesStack.empty())
744       dumpEntitySetName();
745
746     // decrease composite features stack because we run into separate document
747     --gCompositeStackDepth;
748
749     ResultPartPtr aPartResult =
750         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
751     if (!aPartResult)
752       return false;
753     DocumentPtr aSubDoc = aPartResult->partDoc();
754     if (!aSubDoc)
755       return false;
756     // set name of document
757     const std::string& aPartName = myNames[theComposite].myCurrentName;
758     std::string aDocName = aPartName + "_doc";
759     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
760
761     // dump document in a separate line
762     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
763     // dump features in the document
764     bool aRes = process(aSubDoc);
765     if (isDumpModelDo)
766       *this << "model.do()\n";
767     *this << std::endl;
768     return aRes;
769   }
770
771   // dump sub-features
772   bool isOk = processSubs(theComposite);
773   // decrease composite features stack
774   --gCompositeStackDepth;
775
776   return isOk;
777 }
778
779 bool ModelHighAPI_Dumper::processSubs(
780   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
781   bool theDumpModelDo)
782 {
783   bool isOk = true;
784   // dump all sub-features;
785   bool isSubDumped = false;
786   int aNbSubs = theComposite->numberOfSubs();
787   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
788     FeaturePtr aFeature = theComposite->subFeature(anIndex);
789     if (isDumped(EntityPtr(aFeature)))
790       continue;
791
792     isSubDumped = true;
793     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
794     if (aCompFeat) // iteratively process composite features
795       isOk = process(aCompFeat) && isOk;
796     else
797       dumpFeature(aFeature, true);
798   }
799
800   bool isDumpSetName = !myEntitiesStack.empty() &&
801       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
802   bool isForceModelDo = isSubDumped && isDumpSetName &&
803       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
804   // It is necessary for the sketch to create its result when complete (command "model.do()").
805   // This option is set by flat theDumpModelDo.
806   // However, nested sketches are rebuilt by parent feature, so, they do not need
807   // explicit call of "model.do()". This will be controlled by the depth of the stack.
808   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
809     *this << "model.do()" << std::endl;
810
811   // dump "setName" for composite feature
812   if (isDumpSetName)
813     dumpEntitySetName();
814   return isOk;
815 }
816
817 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
818 {
819   // keep the name
820   name(theEntity, false);
821   myPostponed.push_back(theEntity);
822 }
823
824 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
825 {
826   if (myDumpPostponedInProgress)
827     return;
828
829   myDumpPostponedInProgress = true;
830   // make a copy of postponed entities, because the list will be updated
831   // if some features are not able to be dumped
832   std::list<EntityPtr> aPostponedCopy = myPostponed;
833   myPostponed.clear();
834
835   // iterate over postponed entities and try to dump them
836   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
837   for (; anIt != aPostponedCopy.end(); ++anIt) {
838     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
839     if (aFolder) {
840       if (theDumpFolders)
841         dumpFolder(aFolder);
842       else
843         myPostponed.push_back(*anIt);
844     }
845     else {
846       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
847       if (aFeature)
848         dumpFeature(aFeature, true);
849     }
850   }
851   myDumpPostponedInProgress = false;
852 }
853
854 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
855                                                      const FeaturePtr& theSubFeature)
856 {
857   name(theSubFeature, false);
858   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
859
860   // store results if they have user-defined names or colors
861   std::list<ResultPtr> aResultsWithNameOrColor;
862   const std::list<ResultPtr>& aResults = theSubFeature->results();
863   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
864   for (; aResIt != aResults.end(); ++aResIt) {
865     std::string aResName = (*aResIt)->data()->name();
866     myNames[*aResIt] = EntityName(aResName, aResName, false);
867     aResultsWithNameOrColor.push_back(*aResIt);
868   }
869
870   // store just dumped entity to stack
871   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
872
873   dumpEntitySetName();
874 }
875
876 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName)
877 {
878   myModules.insert(theModuleName);
879 }
880
881 void ModelHighAPI_Dumper::dumpEntitySetName()
882 {
883   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
884   bool isBufferEmpty = myDumpStorage->isBufferEmpty();
885
886   // dump "setName" for the entity
887   if (aLastDumped.myUserName) {
888     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
889     if (!anEntityNames.myIsDefault)
890       *myDumpStorage << anEntityNames.myCurrentName << ".setName(\""
891                      << anEntityNames.myUserName << "\")\n";
892     // don't dump "setName" for the entity twice
893     anEntityNames.myUserName.clear();
894     anEntityNames.myIsDefault = true;
895   }
896   // dump "setName" for results
897   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
898   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
899   for (; aResIt != aResEnd; ++aResIt) {
900     // set result name
901     EntityName& anEntityNames = myNames[*aResIt];
902     if (!anEntityNames.myIsDefault) {
903       *this << *aResIt;
904       *myDumpStorage << ".setName(\"" << anEntityNames.myUserName << "\")\n";
905       // don't dump "setName" for the entity twice
906       anEntityNames.myUserName.clear();
907       anEntityNames.myIsDefault = true;
908     }
909     // set result color
910     if (!isDefaultColor(*aResIt)) {
911       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
912       if (aColor && aColor->isInitialized()) {
913         *this << *aResIt;
914         *myDumpStorage << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
915                        << ", " << aColor->value(2) << ")\n";
916       }
917     }
918     // set result deflection
919     if (!isDefaultDeflection(*aResIt)) {
920       AttributeDoublePtr aDeflectionAttr =
921         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
922       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
923         *this << *aResIt;
924         *myDumpStorage << ".setDeflection(" << aDeflectionAttr->value() << ")\n";
925       }
926     }
927     // set result transparency
928     if (!isDefaultTransparency(*aResIt)) {
929       AttributeDoublePtr aTransparencyAttr =
930         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
931       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
932         *this << *aResIt;
933         *myDumpStorage << ".setTransparency(" << aTransparencyAttr->value() << ")\n";
934       }
935     }
936   }
937
938   myNames[aLastDumped.myEntity].myIsDumped = true;
939   myEntitiesStack.pop();
940
941   // clean buffer if it was clear before
942   if (isBufferEmpty)
943     myDumpStorage->mergeBuffer();
944 }
945
946 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
947 {
948   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
949   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
950   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
951          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
952 }
953
954 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
955 {
956   FeaturePtr aFeature;
957   if (theRefAttr->isObject())
958     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
959   else
960     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
961   return aFeature && isDumped(EntityPtr(aFeature));
962 }
963
964 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
965 {
966   std::list<ObjectPtr> aRefs = theRefList->list();
967   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
968   for (; anIt != aRefs.end(); ++anIt) {
969     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
970     if (aFeature && !isDumped(EntityPtr(aFeature)))
971       return false;
972   }
973   return true;
974 }
975
976 static bool isSketchSub(const FeaturePtr& theFeature)
977 {
978   static const std::string SKETCH("Sketch");
979   CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
980   return anOwner && anOwner->getKind() == SKETCH;
981 }
982
983 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
984 {
985   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
986   if (!aColor || !aColor->isInitialized())
987     return true;
988
989   // check the result belongs to sketch entity, do not dump color in this way
990   ResultConstructionPtr aResConstr =
991       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theResult);
992   if (aResConstr) {
993     FeaturePtr aFeature = ModelAPI_Feature::feature(theResult->data()->owner());
994     if (isSketchSub(aFeature))
995       return true;
996   }
997
998   std::string aSection, aName, aDefault;
999   theResult->colorConfigInfo(aSection, aName, aDefault);
1000
1001   // dump current color
1002   std::ostringstream aColorInfo;
1003   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
1004
1005   return aDefault == aColorInfo.str();
1006 }
1007
1008 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
1009 {
1010   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1011   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
1012     return true;
1013   }
1014
1015   double aCurrent = aDeflectionAttr->value();
1016   double aDefault = -1;
1017
1018   bool isConstruction = false;
1019   std::string aResultGroup = theResult->groupName();
1020   if (aResultGroup == ModelAPI_ResultConstruction::group())
1021     isConstruction = true;
1022   else if (aResultGroup == ModelAPI_ResultBody::group()) {
1023     GeomShapePtr aGeomShape = theResult->shape();
1024     if (aGeomShape.get()) {
1025       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
1026       // correction of deviation for them should not influence to the application performance
1027       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
1028       isConstruction = !anExp.more();
1029     }
1030   }
1031   if (isConstruction)
1032     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
1033   else
1034     aDefault = Config_PropManager::real("Visualization", "body_deflection");
1035
1036   return fabs(aCurrent - aDefault) < 1.e-12;
1037 }
1038
1039 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
1040 {
1041   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1042   if(!anAttribute || !anAttribute->isInitialized()) {
1043     return true;
1044   }
1045   return fabs(anAttribute->value()) < 1.e-12;
1046 }
1047
1048 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
1049 {
1050   *myDumpStorage << theChar;
1051   return *this;
1052 }
1053
1054 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
1055 {
1056   *myDumpStorage << theString;
1057   return *this;
1058 }
1059
1060 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
1061 {
1062   *myDumpStorage << theString;
1063   return *this;
1064 }
1065
1066 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
1067 {
1068   *myDumpStorage << (theValue ? "True" : "False");
1069   return *this;
1070 }
1071
1072 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
1073 {
1074   *myDumpStorage << theValue;
1075   return *this;
1076 }
1077
1078 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
1079 {
1080   *myDumpStorage << theValue;
1081   return *this;
1082 }
1083
1084 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
1085 {
1086   importModule("GeomAPI");
1087   *myDumpStorage << "GeomAPI_Pnt(" << thePoint->x() << ", "
1088                  << thePoint->y() << ", " << thePoint->z() << ")";
1089   return *this;
1090 }
1091
1092 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
1093 {
1094   importModule("GeomAPI");
1095   *myDumpStorage << "GeomAPI_Dir(" << theDir->x() << ", "
1096                  << theDir->y() << ", " << theDir->z() << ")";
1097   return *this;
1098 }
1099
1100 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1101     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
1102 {
1103   *myDumpStorage << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
1104   return *this;
1105 }
1106
1107 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1108     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
1109 {
1110   static const int aSize = 3;
1111   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
1112   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
1113   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1114   return *this;
1115 }
1116
1117 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1118     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
1119 {
1120   static const int aSize = 2;
1121   double aValues[aSize] = {thePoint->x(), thePoint->y()};
1122   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
1123   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1124   return *this;
1125 }
1126
1127 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1128   const std::shared_ptr<GeomDataAPI_Point2DArray>& thePointArray)
1129 {
1130   static const int aThreshold = 4;
1131   static bool aDumpAsIs = false;
1132   static std::string aSeparator = "";
1133   // if number of elements in the list if greater than a threshold,
1134   // dump it in a separate line with specific name
1135   int aSize = thePointArray->size();
1136   if (aDumpAsIs || aSize <= aThreshold) {
1137     *myDumpStorage << "[";
1138     GeomPnt2dPtr aPoint = thePointArray->pnt(0);
1139     *myDumpStorage << "(" << aPoint->x() << ", " << aPoint->y() << ")";
1140     for (int anIndex = 1; anIndex < aSize; ++anIndex) {
1141       aPoint = thePointArray->pnt(anIndex);
1142       *myDumpStorage << "," << aSeparator << " (" << aPoint->x() << ", " << aPoint->y() << ")";
1143     }
1144     *myDumpStorage << aSeparator << "]";
1145   }
1146   else {
1147     // name of list
1148     FeaturePtr anOwner = ModelAPI_Feature::feature(thePointArray->owner());
1149     std::string aListName = name(anOwner) + "_" + thePointArray->id();
1150     // reserve dumped buffer and store list "as is"
1151     myDumpStorage->reserveBuffer();
1152     aDumpAsIs = true;
1153     aSeparator = std::string("\n") + std::string(aListName.size() + 3, ' ');
1154     *this << aListName << " = " << thePointArray << "\n";
1155     aDumpAsIs = false;
1156     aSeparator = "";
1157     // append reserved data to the end of the current buffer
1158     myDumpStorage->restoreReservedBuffer();
1159     *myDumpStorage << aListName;
1160   }
1161   return *this;
1162 }
1163
1164 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1165     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
1166 {
1167   *myDumpStorage << (theAttrBool->value() ? "True" : "False");
1168   return *this;
1169 }
1170
1171 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1172     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
1173 {
1174   std::string aText = theAttrInt->text();
1175   if (aText.empty())
1176     *myDumpStorage << theAttrInt->value();
1177   else
1178     *myDumpStorage << "\"" << aText << "\"";
1179   return *this;
1180 }
1181
1182 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1183     const std::shared_ptr<ModelAPI_AttributeIntArray>& theArray)
1184 {
1185   *myDumpStorage << "[";
1186   int aSize = theArray->size();
1187   if (aSize > 0) {
1188     *myDumpStorage << theArray->value(0);
1189     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1190       *myDumpStorage << ", " << theArray->value(anIndex);
1191   }
1192   *myDumpStorage << "]";
1193   return *this;
1194 }
1195
1196 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1197     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
1198 {
1199   std::string aText = theAttrReal->text();
1200   if (aText.empty())
1201     *myDumpStorage << theAttrReal->value();
1202   else
1203     *myDumpStorage << "\"" << aText << "\"";
1204   return *this;
1205 }
1206
1207 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1208   const std::shared_ptr<ModelAPI_AttributeDoubleArray>& theArray)
1209 {
1210   *myDumpStorage << "[";
1211   int aSize = theArray->size();
1212   if (aSize > 0) {
1213     *myDumpStorage << theArray->value(0);
1214     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1215       *myDumpStorage << ", " << theArray->value(anIndex);
1216   }
1217   *myDumpStorage << "]";
1218   return *this;
1219 }
1220
1221 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1222     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
1223 {
1224   *myDumpStorage << "\"" << theAttrStr->value() << "\"";
1225   return *this;
1226 }
1227
1228 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
1229 {
1230   *myDumpStorage << name(theFolder);
1231
1232   // add dumped folder to a stack
1233   if (!myNames[theFolder].myIsDumped &&
1234      (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theFolder))
1235     myEntitiesStack.push(LastDumpedEntity(theFolder, !myNames[theFolder].myIsDefault));
1236
1237   return *this;
1238 }
1239
1240 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
1241 {
1242   *myDumpStorage << name(theEntity);
1243
1244   if (!myNames[theEntity].myIsDumped) {
1245     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
1246     // store results if they have user-defined names or colors
1247     std::list<ResultPtr> aResultsWithNameOrColor;
1248     std::list<ResultPtr> allRes;
1249     ModelAPI_Tools::allResults(theEntity, allRes);
1250     for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1251       if(!myNames[*aRes].myIsDefault || !isDefaultColor(*aRes) ||
1252          !isDefaultDeflection(*aRes) || !isDefaultTransparency(*aRes))
1253         aResultsWithNameOrColor.push_back(*aRes);
1254     }
1255     // store just dumped entity to stack
1256     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
1257       myEntitiesStack.push(
1258           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
1259   }
1260
1261   // remove entity from the list of not dumped items
1262   myNotDumpedEntities.erase(theEntity);
1263   return *this;
1264 }
1265
1266 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
1267 {
1268   // iterate in the structure of sub-results to the parent
1269   ResultPtr aCurRes = theResult;
1270   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
1271   std::list<int> anIndices; // indexes of results in the parent result, starting from topmost
1272   while(aCurRes.get()) {
1273     ResultBodyPtr aParent = ModelAPI_Tools::bodyOwner(aCurRes);
1274     if (aParent) {
1275       anIndices.push_front(ModelAPI_Tools::bodyIndex(aCurRes));
1276     } else { // index of the result in the feature
1277       std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
1278       for(int anIndex = 0; aRes != aFeature->results().cend(); aRes++, anIndex++) {
1279         if (*aRes == aCurRes) {
1280           anIndices.push_front(anIndex);
1281           break;
1282         }
1283       }
1284     }
1285     aCurRes = aParent;
1286   }
1287
1288   *myDumpStorage << name(aFeature);
1289   for (std::list<int>::iterator anI = anIndices.begin(); anI != anIndices.end(); anI++) {
1290     if (anI == anIndices.begin()) {
1291       if(*anI == 0) {
1292         *myDumpStorage << ".result()";
1293       }
1294       else {
1295         *myDumpStorage << ".results()[" << *anI << "]";
1296       }
1297     } else {
1298       *myDumpStorage << ".subResult(" << *anI << ")";
1299     }
1300   }
1301
1302   return *this;
1303 }
1304
1305 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::list<ResultPtr>& theResults)
1306 {
1307   *this << "[";
1308   for (std::list<ResultPtr>::const_iterator anIt = theResults.begin();
1309        anIt != theResults.end(); ++anIt) {
1310     if (anIt != theResults.begin())
1311       *this << ", ";
1312     *this << *anIt;
1313   }
1314   *this << "]";
1315   return *this;
1316 }
1317
1318 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
1319 {
1320   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
1321   if(aFeature.get()) {
1322     *myDumpStorage << name(aFeature);
1323     return *this;
1324   }
1325
1326   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1327   if(aResult.get()) {
1328     *this << aResult;
1329     return *this;
1330   }
1331
1332   return *this;
1333 }
1334
1335 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
1336 {
1337   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
1338
1339   std::string aWrapperPrefix, aWrapperSuffix;
1340   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
1341   // In this case we need to cast explicitly feature to appropriate type.
1342   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
1343   AttributeReferencePtr hasParent = anOwner->reference("ParentFeature");
1344   if ((isCopy.get() && isCopy->value()) || (hasParent && hasParent->value())) {
1345     aWrapperPrefix = featureWrapper(anOwner) + "(";
1346     aWrapperSuffix = ")";
1347     importModule("SketchAPI");
1348   }
1349
1350   *myDumpStorage << aWrapperPrefix << name(anOwner) << aWrapperSuffix
1351                  << "." << attributeGetter(anOwner, theAttr->id()) << "()";
1352   return *this;
1353 }
1354
1355 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1356     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
1357 {
1358   if (theRefAttr->isObject())
1359     *this << theRefAttr->object();
1360   else
1361     *this << theRefAttr->attr();
1362   return *this;
1363 }
1364
1365 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1366     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
1367 {
1368   *myDumpStorage << "[";
1369   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
1370   bool isAdded = false;
1371   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
1372   for (; anIt != aList.end(); ++anIt) {
1373     if (isAdded)
1374       *myDumpStorage << ", ";
1375     else
1376       isAdded = true;
1377     if (anIt->first)
1378       *this << anIt->first;
1379     else if (anIt->second)
1380       * this << anIt->second;
1381   }
1382   *myDumpStorage << "]";
1383   return *this;
1384 }
1385
1386 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1387     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
1388 {
1389   *this << theReference->value();
1390   return *this;
1391 }
1392
1393 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1394     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
1395 {
1396   static const int aThreshold = 2;
1397   static bool aDumpAsIs = false;
1398   // if number of elements in the list if greater than a threshold,
1399   // dump it in a separate line with specific name
1400   if (aDumpAsIs || theRefList->size() <= aThreshold) {
1401     *myDumpStorage << "[";
1402     std::list<ObjectPtr> aList = theRefList->list();
1403     bool isAdded = false;
1404     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
1405     for (; anIt != aList.end(); ++anIt) {
1406       if (isAdded)
1407         *myDumpStorage << ", ";
1408       else
1409         isAdded = true;
1410
1411       *this << *anIt;
1412     }
1413     *myDumpStorage << "]";
1414   } else {
1415     // name of list
1416     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
1417     std::string aListName = name(anOwner) + "_objects";
1418     // reserve dumped buffer and store list "as is"
1419     myDumpStorage->reserveBuffer();
1420     aDumpAsIs = true;
1421     *this << aListName << " = " << theRefList << "\n";
1422     aDumpAsIs = false;
1423     // append reserved data to the end of the current buffer
1424     myDumpStorage->restoreReservedBuffer();
1425     *myDumpStorage << aListName;
1426   }
1427   return *this;
1428 }
1429
1430 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1431     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
1432 {
1433   myDumpStorage->write(theAttrSelect);
1434   return *this;
1435 }
1436
1437 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1438     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
1439 {
1440   static const int aThreshold = 2;
1441   static bool aDumpAsIs = false;
1442   // if number of elements in the list if greater than a threshold,
1443   // dump it in a separate line with specific name
1444   if (aDumpAsIs || theAttrSelList->size() <= aThreshold) {
1445     *myDumpStorage << "[";
1446
1447     GeomShapePtr aShape;
1448     std::string aShapeTypeStr;
1449
1450     bool isAdded = false;
1451
1452     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
1453       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1454       aShape = anAttribute->value();
1455       if(!aShape.get()) {
1456         ResultPtr aContext = anAttribute->context();
1457         if (aContext.get())
1458           aShape = aContext->shape();
1459       }
1460
1461       if(!aShape.get()) {
1462         continue;
1463       }
1464
1465       if(isAdded) {
1466         *myDumpStorage << ", ";
1467       } else {
1468         isAdded = true;
1469       }
1470       *this << anAttribute;
1471     }
1472
1473     // check selection list is obtained by filters
1474     FiltersFeaturePtr aFilters = theAttrSelList->filters();
1475     if (aFilters) {
1476       if (theAttrSelList->size() > 0)
1477         *myDumpStorage << ", ";
1478       dumpFeature(aFilters, true);
1479     }
1480
1481     *myDumpStorage << "]";
1482   } else {
1483     // obtain name of list (the feature may contain several selection lists)
1484     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1485     std::string aListName = name(anOwner) + "_objects";
1486     std::list<AttributePtr> aSelLists =
1487         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1488     if (aSelLists.size() > 1) {
1489       int anIndex = 1;
1490       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1491            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1492         if ((*aSIt).get() == theAttrSelList.get())
1493           break;
1494       std::ostringstream aSStream;
1495       aSStream << aListName << "_" << anIndex;
1496       aListName = aSStream.str();
1497     }
1498     // reserve dumped buffer and store list "as is"
1499     myDumpStorage->reserveBuffer();
1500     aDumpAsIs = true;
1501     *this << aListName << " = " << theAttrSelList << "\n";
1502     aDumpAsIs = false;
1503     // append reserved data to the end of the current buffer
1504     myDumpStorage->restoreReservedBuffer();
1505     *myDumpStorage << aListName;
1506   }
1507   return *this;
1508 }
1509
1510 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1511   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1512 {
1513   std::ostringstream aBuffer;
1514   aBuffer << "[";
1515   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1516     if (anIndex != 0)
1517       aBuffer << ", ";
1518
1519     aBuffer << "\"" << theArray->value(anIndex) << "\"";
1520   }
1521   aBuffer << "]";
1522
1523   myDumpStorage->write(aBuffer.str());
1524   return *this;
1525 }
1526
1527 /// Dump std::endl
1528 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1529                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1530 {
1531   *theDumper.myDumpStorage << theEndl;
1532
1533   if (!theDumper.myEntitiesStack.empty()) {
1534     bool isCopy;
1535     // all copies have been stored into stack, pop them all
1536     do {
1537       isCopy = false;
1538       // Name for composite feature is dumped when all sub-entities are dumped
1539       // (see method ModelHighAPI_Dumper::processSubs).
1540       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1541       CompositeFeaturePtr aComposite =
1542           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1543       if (!aComposite) {
1544         theDumper.dumpEntitySetName();
1545         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1546         if (aFeature) {
1547           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1548           isCopy = aCopyAttr.get() && aCopyAttr->value();
1549         }
1550       }
1551     } while (isCopy && !theDumper.myEntitiesStack.empty());
1552   }
1553
1554   // store all not-dumped entities first
1555   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1556   theDumper.myDumpStorage->reserveBuffer();
1557   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1558   for (; anIt != aNotDumped.end(); ++anIt) {
1559     // if the feature is composite, dump it with all subs
1560     CompositeFeaturePtr aCompFeat =
1561         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1562     if (aCompFeat)
1563       theDumper.process(aCompFeat, true);
1564     else {
1565       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1566       theDumper.dumpFeature(aFeature, true);
1567       // dump the Projection feature which produces this "Copy" entity
1568       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1569       if (aCopyAttr.get() && aCopyAttr->value())
1570       {
1571         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1572         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1573         for (; aRefIt != aRefs.end(); ++aRefIt)
1574           if ((*aRefIt)->id() == "ProjectedFeature")
1575           { // process projection only
1576             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1577             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1578               theDumper.dumpFeature(anOwner, true);
1579           }
1580       }
1581     }
1582   }
1583
1584   // then store the reserved data
1585   theDumper.myDumpStorage->restoreReservedBuffer();
1586   theDumper.myDumpStorage->mergeBuffer();
1587
1588   // now, store all postponed features
1589   theDumper.dumpPostponed();
1590
1591   return theDumper;
1592 }