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