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