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