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