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