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