Salome HOME
Merge remote-tracking branch 'remotes/origin/occ/compounds_processing'
[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   return isOk;
691 }
692
693 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
694 {
695   bool isOk = true;
696   std::list<ObjectPtr> anObjects = theDoc->allObjects();
697   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
698   // firstly, dump all parameters
699   for (; anObjIt != anObjects.end(); ++ anObjIt) {
700     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
701     if (aFeature)
702       dumpParameter(aFeature);
703   }
704   // dump all other features
705   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
706     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
707     if (aCompFeat) {
708       // iteratively process composite features,
709       // if the composite feature is the last in the document, no need to dump "model.do()" action
710       std::list<ObjectPtr>::const_iterator aNext = anObjIt;
711       isOk = process(aCompFeat, false, ++aNext != anObjects.end()) && isOk;
712     }
713     else if (!isDumped(EntityPtr(*anObjIt))) {
714       // dump folder
715       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
716       if (aFolder)
717         dumpFolder(aFolder);
718       else {
719         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
720         if (aFeature) // dump common feature
721           dumpFeature(aFeature);
722       }
723     }
724   }
725   // dump folders if any
726   dumpPostponed(true);
727   return isOk;
728 }
729
730 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
731                                   bool isForce, bool isDumpModelDo)
732 {
733   // increase composite features stack
734   ++gCompositeStackDepth;
735   // dump composite itself
736   if (!isDumped(EntityPtr(theComposite)) || isForce)
737     dumpFeature(FeaturePtr(theComposite), isForce);
738
739   // sub-part is processed independently, because it provides separate document
740   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
741     // dump name of the part if it is different from default
742     if (!myEntitiesStack.empty())
743       dumpEntitySetName();
744
745     // decrease composite features stack because we run into separate document
746     --gCompositeStackDepth;
747
748     ResultPartPtr aPartResult =
749         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
750     if (!aPartResult)
751       return false;
752     DocumentPtr aSubDoc = aPartResult->partDoc();
753     if (!aSubDoc)
754       return false;
755     // set name of document
756     const std::string& aPartName = myNames[theComposite].myCurrentName;
757     std::string aDocName = aPartName + "_doc";
758     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
759
760     // dump document in a separate line
761     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
762     // dump features in the document
763     bool aRes = process(aSubDoc);
764     if (isDumpModelDo)
765       *this << "model.do()\n";
766     *this << std::endl;
767     return aRes;
768   }
769
770   // dump sub-features
771   bool isOk = processSubs(theComposite);
772   // decrease composite features stack
773   --gCompositeStackDepth;
774
775   return isOk;
776 }
777
778 bool ModelHighAPI_Dumper::processSubs(
779   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
780   bool theDumpModelDo)
781 {
782   bool isOk = true;
783   // dump all sub-features;
784   bool isSubDumped = false;
785   int aNbSubs = theComposite->numberOfSubs();
786   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
787     FeaturePtr aFeature = theComposite->subFeature(anIndex);
788     if (isDumped(EntityPtr(aFeature)))
789       continue;
790
791     isSubDumped = true;
792     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
793     if (aCompFeat) // iteratively process composite features
794       isOk = process(aCompFeat) && isOk;
795     else
796       dumpFeature(aFeature, true);
797   }
798
799   bool isDumpSetName = !myEntitiesStack.empty() &&
800       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
801   bool isForceModelDo = isSubDumped && isDumpSetName &&
802       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
803   // It is necessary for the sketch to create its result when complete (command "model.do()").
804   // This option is set by flat theDumpModelDo.
805   // However, nested sketches are rebuilt by parent feature, so, they do not need
806   // explicit call of "model.do()". This will be controlled by the depth of the stack.
807   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
808     *this << "model.do()" << std::endl;
809
810   // dump "setName" for composite feature
811   if (isDumpSetName)
812     dumpEntitySetName();
813   return isOk;
814 }
815
816 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
817 {
818   // keep the name
819   name(theEntity, false);
820   myPostponed.push_back(theEntity);
821 }
822
823 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
824 {
825   if (myDumpPostponedInProgress)
826     return;
827
828   myDumpPostponedInProgress = true;
829   // make a copy of postponed entities, because the list will be updated
830   // if some features are not able to be dumped
831   std::list<EntityPtr> aPostponedCopy = myPostponed;
832   myPostponed.clear();
833
834   // iterate over postponed entities and try to dump them
835   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
836   for (; anIt != aPostponedCopy.end(); ++anIt) {
837     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
838     if (aFolder) {
839       if (theDumpFolders)
840         dumpFolder(aFolder);
841       else
842         myPostponed.push_back(*anIt);
843     }
844     else {
845       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
846       if (aFeature)
847         dumpFeature(aFeature, true);
848     }
849   }
850   myDumpPostponedInProgress = false;
851 }
852
853 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
854                                                      const FeaturePtr& theSubFeature)
855 {
856   name(theSubFeature, false);
857   myNames[theSubFeature] = EntityName(theSubFeatureGet, theSubFeature->name(), false);
858
859   // store results if they have user-defined names or colors
860   std::list<ResultPtr> aResultsWithNameOrColor;
861   const std::list<ResultPtr>& aResults = theSubFeature->results();
862   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
863   for (; aResIt != aResults.end(); ++aResIt) {
864     std::string aResName = (*aResIt)->data()->name();
865     myNames[*aResIt] = EntityName(aResName, aResName, false);
866     aResultsWithNameOrColor.push_back(*aResIt);
867   }
868
869   // store just dumped entity to stack
870   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
871
872   dumpEntitySetName();
873 }
874
875 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName)
876 {
877   myModules.insert(theModuleName);
878 }
879
880 void ModelHighAPI_Dumper::dumpEntitySetName()
881 {
882   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
883   bool isBufferEmpty = myDumpStorage->isBufferEmpty();
884
885   // dump "setName" for the entity
886   if (aLastDumped.myUserName) {
887     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
888     if (!anEntityNames.myIsDefault)
889       *myDumpStorage << anEntityNames.myCurrentName << ".setName(\""
890                      << anEntityNames.myUserName << "\")\n";
891     // don't dump "setName" for the entity twice
892     anEntityNames.myUserName.clear();
893     anEntityNames.myIsDefault = true;
894   }
895   // dump "setName" for results
896   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
897   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
898   for (; aResIt != aResEnd; ++aResIt) {
899     // set result name
900     EntityName& anEntityNames = myNames[*aResIt];
901     if (!anEntityNames.myIsDefault) {
902       *this << *aResIt;
903       *myDumpStorage << ".setName(\"" << anEntityNames.myUserName << "\")\n";
904       // don't dump "setName" for the entity twice
905       anEntityNames.myUserName.clear();
906       anEntityNames.myIsDefault = true;
907     }
908     // set result color
909     if (!isDefaultColor(*aResIt)) {
910       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
911       if (aColor && aColor->isInitialized()) {
912         *this << *aResIt;
913         *myDumpStorage << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
914                        << ", " << aColor->value(2) << ")\n";
915       }
916     }
917     // set result deflection
918     if (!isDefaultDeflection(*aResIt)) {
919       AttributeDoublePtr aDeflectionAttr =
920         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
921       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
922         *this << *aResIt;
923         *myDumpStorage << ".setDeflection(" << aDeflectionAttr->value() << ")\n";
924       }
925     }
926     // set result transparency
927     if (!isDefaultTransparency(*aResIt)) {
928       AttributeDoublePtr aTransparencyAttr =
929         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
930       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
931         *this << *aResIt;
932         *myDumpStorage << ".setTransparency(" << aTransparencyAttr->value() << ")\n";
933       }
934     }
935   }
936
937   myNames[aLastDumped.myEntity].myIsDumped = true;
938   myEntitiesStack.pop();
939
940   // clean buffer if it was clear before
941   if (isBufferEmpty)
942     myDumpStorage->mergeBuffer();
943 }
944
945 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
946 {
947   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
948   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
949   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
950          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
951 }
952
953 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
954 {
955   FeaturePtr aFeature;
956   if (theRefAttr->isObject())
957     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
958   else
959     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
960   return aFeature && isDumped(EntityPtr(aFeature));
961 }
962
963 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
964 {
965   std::list<ObjectPtr> aRefs = theRefList->list();
966   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
967   for (; anIt != aRefs.end(); ++anIt) {
968     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
969     if (aFeature && !isDumped(EntityPtr(aFeature)))
970       return false;
971   }
972   return true;
973 }
974
975 static bool isSketchSub(const FeaturePtr& theFeature)
976 {
977   static const std::string SKETCH("Sketch");
978   CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
979   return anOwner && anOwner->getKind() == SKETCH;
980 }
981
982 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
983 {
984   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
985   if (!aColor || !aColor->isInitialized())
986     return true;
987
988   // check the result belongs to sketch entity, do not dump color in this way
989   ResultConstructionPtr aResConstr =
990       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theResult);
991   if (aResConstr) {
992     FeaturePtr aFeature = ModelAPI_Feature::feature(theResult->data()->owner());
993     if (isSketchSub(aFeature))
994       return true;
995   }
996
997   std::string aSection, aName, aDefault;
998   theResult->colorConfigInfo(aSection, aName, aDefault);
999
1000   // dump current color
1001   std::ostringstream aColorInfo;
1002   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
1003
1004   return aDefault == aColorInfo.str();
1005 }
1006
1007 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
1008 {
1009   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1010   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
1011     return true;
1012   }
1013
1014   double aCurrent = aDeflectionAttr->value();
1015   double aDefault = -1;
1016
1017   bool isConstruction = false;
1018   std::string aResultGroup = theResult->groupName();
1019   if (aResultGroup == ModelAPI_ResultConstruction::group())
1020     isConstruction = true;
1021   else if (aResultGroup == ModelAPI_ResultBody::group()) {
1022     GeomShapePtr aGeomShape = theResult->shape();
1023     if (aGeomShape.get()) {
1024       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
1025       // correction of deviation for them should not influence to the application performance
1026       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
1027       isConstruction = !anExp.more();
1028     }
1029   }
1030   if (isConstruction)
1031     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
1032   else
1033     aDefault = Config_PropManager::real("Visualization", "body_deflection");
1034
1035   return fabs(aCurrent - aDefault) < 1.e-12;
1036 }
1037
1038 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
1039 {
1040   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1041   if(!anAttribute || !anAttribute->isInitialized()) {
1042     return true;
1043   }
1044   return fabs(anAttribute->value()) < 1.e-12;
1045 }
1046
1047 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
1048 {
1049   *myDumpStorage << theChar;
1050   return *this;
1051 }
1052
1053 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
1054 {
1055   *myDumpStorage << theString;
1056   return *this;
1057 }
1058
1059 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
1060 {
1061   *myDumpStorage << theString;
1062   return *this;
1063 }
1064
1065 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
1066 {
1067   *myDumpStorage << (theValue ? "True" : "False");
1068   return *this;
1069 }
1070
1071 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
1072 {
1073   *myDumpStorage << theValue;
1074   return *this;
1075 }
1076
1077 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
1078 {
1079   *myDumpStorage << theValue;
1080   return *this;
1081 }
1082
1083 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
1084 {
1085   importModule("GeomAPI");
1086   *myDumpStorage << "GeomAPI_Pnt(" << thePoint->x() << ", "
1087                  << thePoint->y() << ", " << thePoint->z() << ")";
1088   return *this;
1089 }
1090
1091 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
1092 {
1093   importModule("GeomAPI");
1094   *myDumpStorage << "GeomAPI_Dir(" << theDir->x() << ", "
1095                  << theDir->y() << ", " << theDir->z() << ")";
1096   return *this;
1097 }
1098
1099 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1100     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
1101 {
1102   *myDumpStorage << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
1103   return *this;
1104 }
1105
1106 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1107     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
1108 {
1109   static const int aSize = 3;
1110   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
1111   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
1112   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1113   return *this;
1114 }
1115
1116 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1117     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
1118 {
1119   static const int aSize = 2;
1120   double aValues[aSize] = {thePoint->x(), thePoint->y()};
1121   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
1122   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1123   return *this;
1124 }
1125
1126 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1127   const std::shared_ptr<GeomDataAPI_Point2DArray>& thePointArray)
1128 {
1129   static const int aThreshold = 4;
1130   static bool aDumpAsIs = false;
1131   static std::string aSeparator = "";
1132   // if number of elements in the list if greater than a threshold,
1133   // dump it in a separate line with specific name
1134   int aSize = thePointArray->size();
1135   if (aDumpAsIs || aSize <= aThreshold) {
1136     *myDumpStorage << "[";
1137     GeomPnt2dPtr aPoint = thePointArray->pnt(0);
1138     *myDumpStorage << "(" << aPoint->x() << ", " << aPoint->y() << ")";
1139     for (int anIndex = 1; anIndex < aSize; ++anIndex) {
1140       aPoint = thePointArray->pnt(anIndex);
1141       *myDumpStorage << "," << aSeparator << " (" << aPoint->x() << ", " << aPoint->y() << ")";
1142     }
1143     *myDumpStorage << aSeparator << "]";
1144   }
1145   else {
1146     // name of list
1147     FeaturePtr anOwner = ModelAPI_Feature::feature(thePointArray->owner());
1148     std::string aListName = name(anOwner) + "_" + thePointArray->id();
1149     // reserve dumped buffer and store list "as is"
1150     myDumpStorage->reserveBuffer();
1151     aDumpAsIs = true;
1152     aSeparator = std::string("\n") + std::string(aListName.size() + 3, ' ');
1153     *this << aListName << " = " << thePointArray << "\n";
1154     aDumpAsIs = false;
1155     aSeparator = "";
1156     // append reserved data to the end of the current buffer
1157     myDumpStorage->restoreReservedBuffer();
1158     *myDumpStorage << aListName;
1159   }
1160   return *this;
1161 }
1162
1163 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1164     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
1165 {
1166   *myDumpStorage << (theAttrBool->value() ? "True" : "False");
1167   return *this;
1168 }
1169
1170 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1171     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
1172 {
1173   std::string aText = theAttrInt->text();
1174   if (aText.empty())
1175     *myDumpStorage << theAttrInt->value();
1176   else
1177     *myDumpStorage << "\"" << aText << "\"";
1178   return *this;
1179 }
1180
1181 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1182     const std::shared_ptr<ModelAPI_AttributeIntArray>& theArray)
1183 {
1184   *myDumpStorage << "[";
1185   int aSize = theArray->size();
1186   if (aSize > 0) {
1187     *myDumpStorage << theArray->value(0);
1188     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1189       *myDumpStorage << ", " << theArray->value(anIndex);
1190   }
1191   *myDumpStorage << "]";
1192   return *this;
1193 }
1194
1195 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1196     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
1197 {
1198   std::string aText = theAttrReal->text();
1199   if (aText.empty())
1200     *myDumpStorage << theAttrReal->value();
1201   else
1202     *myDumpStorage << "\"" << aText << "\"";
1203   return *this;
1204 }
1205
1206 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1207   const std::shared_ptr<ModelAPI_AttributeDoubleArray>& theArray)
1208 {
1209   *myDumpStorage << "[";
1210   int aSize = theArray->size();
1211   if (aSize > 0) {
1212     *myDumpStorage << theArray->value(0);
1213     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1214       *myDumpStorage << ", " << theArray->value(anIndex);
1215   }
1216   *myDumpStorage << "]";
1217   return *this;
1218 }
1219
1220 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1221     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
1222 {
1223   *myDumpStorage << "\"" << theAttrStr->value() << "\"";
1224   return *this;
1225 }
1226
1227 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
1228 {
1229   *myDumpStorage << name(theFolder);
1230
1231   // add dumped folder to a stack
1232   if (!myNames[theFolder].myIsDumped &&
1233      (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theFolder))
1234     myEntitiesStack.push(LastDumpedEntity(theFolder, !myNames[theFolder].myIsDefault));
1235
1236   return *this;
1237 }
1238
1239 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
1240 {
1241   *myDumpStorage << name(theEntity);
1242
1243   if (!myNames[theEntity].myIsDumped) {
1244     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
1245     // store results if they have user-defined names or colors
1246     std::list<ResultPtr> aResultsWithNameOrColor;
1247     std::list<ResultPtr> allRes;
1248     ModelAPI_Tools::allResults(theEntity, allRes);
1249     for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1250       if(!myNames[*aRes].myIsDefault || !isDefaultColor(*aRes) ||
1251          !isDefaultDeflection(*aRes) || !isDefaultTransparency(*aRes))
1252         aResultsWithNameOrColor.push_back(*aRes);
1253     }
1254     // store just dumped entity to stack
1255     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
1256       myEntitiesStack.push(
1257           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
1258   }
1259
1260   // remove entity from the list of not dumped items
1261   myNotDumpedEntities.erase(theEntity);
1262   return *this;
1263 }
1264
1265 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
1266 {
1267   // iterate in the structure of sub-results to the parent
1268   ResultPtr aCurRes = theResult;
1269   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
1270   std::list<int> anIndices; // indexes of results in the parent result, starting from topmost
1271   while(aCurRes.get()) {
1272     ResultBodyPtr aParent = ModelAPI_Tools::bodyOwner(aCurRes);
1273     if (aParent) {
1274       anIndices.push_front(ModelAPI_Tools::bodyIndex(aCurRes));
1275     } else { // index of the result in the feature
1276       std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
1277       for(int anIndex = 0; aRes != aFeature->results().cend(); aRes++, anIndex++) {
1278         if (*aRes == aCurRes) {
1279           anIndices.push_front(anIndex);
1280           break;
1281         }
1282       }
1283     }
1284     aCurRes = aParent;
1285   }
1286
1287   *myDumpStorage << name(aFeature);
1288   for (std::list<int>::iterator anI = anIndices.begin(); anI != anIndices.end(); anI++) {
1289     if (anI == anIndices.begin()) {
1290       if(*anI == 0) {
1291         *myDumpStorage << ".result()";
1292       }
1293       else {
1294         *myDumpStorage << ".results()[" << *anI << "]";
1295       }
1296     } else {
1297       *myDumpStorage << ".subResult(" << *anI << ")";
1298     }
1299   }
1300
1301   return *this;
1302 }
1303
1304 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::list<ResultPtr>& theResults)
1305 {
1306   *this << "[";
1307   for (std::list<ResultPtr>::const_iterator anIt = theResults.begin();
1308        anIt != theResults.end(); ++anIt) {
1309     if (anIt != theResults.begin())
1310       *this << ", ";
1311     *this << *anIt;
1312   }
1313   *this << "]";
1314   return *this;
1315 }
1316
1317 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
1318 {
1319   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
1320   if(aFeature.get()) {
1321     *myDumpStorage << name(aFeature);
1322     return *this;
1323   }
1324
1325   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1326   if(aResult.get()) {
1327     *this << aResult;
1328     return *this;
1329   }
1330
1331   return *this;
1332 }
1333
1334 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
1335 {
1336   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
1337
1338   std::string aWrapperPrefix, aWrapperSuffix;
1339   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
1340   // In this case we need to cast explicitly feature to appropriate type.
1341   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
1342   AttributeReferencePtr hasParent = anOwner->reference("ParentFeature");
1343   if ((isCopy.get() && isCopy->value()) || (hasParent && hasParent->value())) {
1344     aWrapperPrefix = featureWrapper(anOwner) + "(";
1345     aWrapperSuffix = ")";
1346     importModule("SketchAPI");
1347   }
1348
1349   *myDumpStorage << aWrapperPrefix << name(anOwner) << aWrapperSuffix
1350                  << "." << attributeGetter(anOwner, theAttr->id()) << "()";
1351   return *this;
1352 }
1353
1354 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1355     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
1356 {
1357   if (theRefAttr->isObject())
1358     *this << theRefAttr->object();
1359   else
1360     *this << theRefAttr->attr();
1361   return *this;
1362 }
1363
1364 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1365     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
1366 {
1367   *myDumpStorage << "[";
1368   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
1369   bool isAdded = false;
1370   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
1371   for (; anIt != aList.end(); ++anIt) {
1372     if (isAdded)
1373       *myDumpStorage << ", ";
1374     else
1375       isAdded = true;
1376     if (anIt->first)
1377       *this << anIt->first;
1378     else if (anIt->second)
1379       * this << anIt->second;
1380   }
1381   *myDumpStorage << "]";
1382   return *this;
1383 }
1384
1385 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1386     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
1387 {
1388   *this << theReference->value();
1389   return *this;
1390 }
1391
1392 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1393     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
1394 {
1395   static const int aThreshold = 2;
1396   static bool aDumpAsIs = false;
1397   // if number of elements in the list if greater than a threshold,
1398   // dump it in a separate line with specific name
1399   if (aDumpAsIs || theRefList->size() <= aThreshold) {
1400     *myDumpStorage << "[";
1401     std::list<ObjectPtr> aList = theRefList->list();
1402     bool isAdded = false;
1403     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
1404     for (; anIt != aList.end(); ++anIt) {
1405       if (isAdded)
1406         *myDumpStorage << ", ";
1407       else
1408         isAdded = true;
1409
1410       *this << *anIt;
1411     }
1412     *myDumpStorage << "]";
1413   } else {
1414     // name of list
1415     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
1416     std::string aListName = name(anOwner) + "_objects";
1417     // reserve dumped buffer and store list "as is"
1418     myDumpStorage->reserveBuffer();
1419     aDumpAsIs = true;
1420     *this << aListName << " = " << theRefList << "\n";
1421     aDumpAsIs = false;
1422     // append reserved data to the end of the current buffer
1423     myDumpStorage->restoreReservedBuffer();
1424     *myDumpStorage << aListName;
1425   }
1426   return *this;
1427 }
1428
1429 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1430     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
1431 {
1432   myDumpStorage->write(theAttrSelect);
1433   return *this;
1434 }
1435
1436 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1437     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
1438 {
1439   static const int aThreshold = 2;
1440   static bool aDumpAsIs = false;
1441   // if number of elements in the list if greater than a threshold,
1442   // dump it in a separate line with specific name
1443   if (aDumpAsIs || theAttrSelList->size() <= aThreshold) {
1444     *myDumpStorage << "[";
1445
1446     GeomShapePtr aShape;
1447     std::string aShapeTypeStr;
1448
1449     bool isAdded = false;
1450
1451     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
1452       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1453       aShape = anAttribute->value();
1454       if(!aShape.get()) {
1455         ResultPtr aContext = anAttribute->context();
1456         if (aContext.get())
1457           aShape = aContext->shape();
1458       }
1459
1460       if(!aShape.get()) {
1461         continue;
1462       }
1463
1464       if(isAdded) {
1465         *myDumpStorage << ", ";
1466       } else {
1467         isAdded = true;
1468       }
1469       *this << anAttribute;
1470     }
1471
1472     // check selection list is obtained by filters
1473     FiltersFeaturePtr aFilters = theAttrSelList->filters();
1474     if (aFilters) {
1475       if (theAttrSelList->size() > 0)
1476         *myDumpStorage << ", ";
1477       dumpFeature(aFilters, true);
1478     }
1479
1480     *myDumpStorage << "]";
1481   } else {
1482     // obtain name of list (the feature may contain several selection lists)
1483     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1484     std::string aListName = name(anOwner) + "_objects";
1485     std::list<AttributePtr> aSelLists =
1486         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1487     if (aSelLists.size() > 1) {
1488       int anIndex = 1;
1489       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1490            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1491         if ((*aSIt).get() == theAttrSelList.get())
1492           break;
1493       std::ostringstream aSStream;
1494       aSStream << aListName << "_" << anIndex;
1495       aListName = aSStream.str();
1496     }
1497     // reserve dumped buffer and store list "as is"
1498     myDumpStorage->reserveBuffer();
1499     aDumpAsIs = true;
1500     *this << aListName << " = " << theAttrSelList << "\n";
1501     aDumpAsIs = false;
1502     // append reserved data to the end of the current buffer
1503     myDumpStorage->restoreReservedBuffer();
1504     *myDumpStorage << aListName;
1505   }
1506   return *this;
1507 }
1508
1509 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1510   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1511 {
1512   std::ostringstream aBuffer;
1513   aBuffer << "[";
1514   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1515     if (anIndex != 0)
1516       aBuffer << ", ";
1517
1518     aBuffer << "\"" << theArray->value(anIndex) << "\"";
1519   }
1520   aBuffer << "]";
1521
1522   myDumpStorage->write(aBuffer.str());
1523   return *this;
1524 }
1525
1526 /// Dump std::endl
1527 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1528                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1529 {
1530   *theDumper.myDumpStorage << theEndl;
1531
1532   if (!theDumper.myEntitiesStack.empty()) {
1533     bool isCopy;
1534     // all copies have been stored into stack, pop them all
1535     do {
1536       isCopy = false;
1537       // Name for composite feature is dumped when all sub-entities are dumped
1538       // (see method ModelHighAPI_Dumper::processSubs).
1539       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1540       CompositeFeaturePtr aComposite =
1541           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1542       if (!aComposite) {
1543         theDumper.dumpEntitySetName();
1544         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1545         if (aFeature) {
1546           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1547           isCopy = aCopyAttr.get() && aCopyAttr->value();
1548         }
1549       }
1550     } while (isCopy && !theDumper.myEntitiesStack.empty());
1551   }
1552
1553   // store all not-dumped entities first
1554   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1555   theDumper.myDumpStorage->reserveBuffer();
1556   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1557   for (; anIt != aNotDumped.end(); ++anIt) {
1558     // if the feature is composite, dump it with all subs
1559     CompositeFeaturePtr aCompFeat =
1560         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1561     if (aCompFeat)
1562       theDumper.process(aCompFeat, true);
1563     else {
1564       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1565       theDumper.dumpFeature(aFeature, true);
1566       // dump the Projection feature which produces this "Copy" entity
1567       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1568       if (aCopyAttr.get() && aCopyAttr->value())
1569       {
1570         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1571         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1572         for (; aRefIt != aRefs.end(); ++aRefIt)
1573           if ((*aRefIt)->id() == "ProjectedFeature")
1574           { // process projection only
1575             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1576             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1577               theDumper.dumpFeature(anOwner, true);
1578           }
1579       }
1580     }
1581   }
1582
1583   // then store the reserved data
1584   theDumper.myDumpStorage->restoreReservedBuffer();
1585   theDumper.myDumpStorage->mergeBuffer();
1586
1587   // now, store all postponed features
1588   theDumper.dumpPostponed();
1589
1590   return theDumper;
1591 }
1592
1593
1594 void ModelHighAPI_Dumper::exportVariables() const
1595 {
1596   DocumentPtr aRoot = ModelAPI_Session::get()->moduleDocument();
1597   EntityNameMap::const_iterator aNameIter = myNames.cbegin();
1598   for(; aNameIter != myNames.end(); aNameIter++) {
1599     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aNameIter->first);
1600     if (aFeature.get() && aFeature->document() != aRoot) {
1601       FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, aFeature->document());
1602       if (aPartFeat.get()) {
1603         int aFeatureId = aFeature->data()->featureId();
1604         int aPartId = aPartFeat->data()->featureId();
1605         std::ostringstream anEntryStr;
1606         anEntryStr<<aPartId<<":"<<aFeatureId;
1607         std::string anEntry = anEntryStr.str();
1608         exportVariable(anEntry, aNameIter->second.myCurrentName);
1609       }
1610     }
1611   }
1612 }