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