Salome HOME
d0b581ef550ebe5c8e8504932d3ae001fc8a5233
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2014-2023  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 <fstream>
74 #include <iomanip>
75 #include <cctype>
76 #include <cmath>
77
78 // ===========    Implementation of storage of dumped data    ===========
79 static const int THE_DUMP_PRECISION = 16;
80
81 class ModelHighAPI_Dumper::DumpStorageBuffer : public ModelHighAPI_Dumper::DumpStorage
82 {
83 public:
84   void addStorage(const ModelHighAPI_Dumper::DumpStoragePtr& theStorage)
85   { myStorageArray.push_back(theStorage); }
86
87   void clear() { myStorageArray.clear(); }
88
89   bool isBufferEmpty()
90   {
91     return myStorageArray.empty() || myStorageArray.front()->buffer().str().empty();
92   }
93
94   void mergeBuffer()
95   {
96     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
97     for (; anIt != myStorageArray.end(); ++anIt) {
98       // avoid multiple empty lines
99       std::string aBuf = (*anIt)->buffer().str();
100       size_t anInd = std::string::npos;
101       while ((anInd = aBuf.find("\n\n\n")) != std::string::npos)
102         aBuf.erase(anInd, 1);
103
104       (*anIt)->fullDump() << aBuf;
105       (*anIt)->buffer().str("");
106     }
107   }
108
109   void write(const std::string& theValue)
110   {
111     if (myStorageArray.empty())
112       addStorage(DumpStoragePtr(new DumpStorage));
113
114     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
115     for (; anIt != myStorageArray.end(); ++anIt)
116       (*anIt)->buffer() << theValue;
117   }
118
119   DumpStorageBuffer& operator<<(const char theChar)
120   {
121     std::ostringstream out;
122     out << theChar;
123     write(out.str());
124     return *this;
125   }
126
127   DumpStorageBuffer& operator<<(const char* theString)
128   {
129     write(theString);
130     return *this;
131   }
132
133   DumpStorageBuffer& operator<<(const std::string& theString)
134   {
135     write(theString);
136     return *this;
137   }
138
139   DumpStorageBuffer& operator<<(const bool theValue)
140   {
141     std::ostringstream out;
142     out << theValue;
143     write(out.str());
144     return *this;
145   }
146
147   DumpStorageBuffer& operator<<(const int theValue)
148   {
149     std::ostringstream out;
150     out << theValue;
151     write(out.str());
152     return *this;
153   }
154
155   DumpStorageBuffer& operator<<(const double theValue)
156   {
157     std::ostringstream out;
158     out << std::setprecision(THE_DUMP_PRECISION) << theValue;
159     write(out.str());
160     return *this;
161   }
162   /// Dump std::endl
163   friend
164   DumpStorageBuffer& operator<<(DumpStorageBuffer& theBuffer,
165                                 std::basic_ostream<char>& (*)(std::basic_ostream<char>&))
166   {
167     theBuffer.write("\n");
168     return theBuffer;
169   }
170
171   void dumpArray(int theSize, double* theValues, std::string* theTexts)
172   {
173     std::ostringstream anOutput;
174     anOutput << std::setprecision(THE_DUMP_PRECISION);
175     for (int i = 0; i < theSize; ++i) {
176       if (i > 0)
177         anOutput << ", ";
178       if (theTexts[i].empty())
179         anOutput << theValues[i];
180       else
181         anOutput << "\"" << theTexts[i] << "\"";
182     }
183     write(anOutput.str());
184   }
185
186   virtual void write(const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
187   {
188     if (myStorageArray.empty())
189       addStorage(DumpStoragePtr(new DumpStorage));
190
191     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
192     for (; anIt != myStorageArray.end(); ++anIt)
193       (*anIt)->write(theAttrSelect);
194   }
195
196   virtual void reserveBuffer()
197   {
198     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
199     for (; anIt != myStorageArray.end(); ++anIt)
200       (*anIt)->reserveBuffer();
201   }
202
203   virtual void restoreReservedBuffer()
204   {
205     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
206     for (; anIt != myStorageArray.end(); ++anIt)
207       (*anIt)->restoreReservedBuffer();
208   }
209
210   virtual bool exportTo(const std::string& theFilename, const ModulesSet& theUsedModules)
211   {
212     static const std::string THE_EXT = ".py";
213     std::string aFilenameBase = theFilename;
214     if (aFilenameBase.rfind(THE_EXT) == aFilenameBase.size() - THE_EXT.size())
215       aFilenameBase = aFilenameBase.substr(0, aFilenameBase.size() - THE_EXT.size());
216
217     bool isOk = true;
218     std::list<ModelHighAPI_Dumper::DumpStoragePtr>::iterator anIt = myStorageArray.begin();
219     for (; anIt != myStorageArray.end(); ++anIt) {
220       std::string aFilename = aFilenameBase + (*anIt)->myFilenameSuffix + THE_EXT;
221       isOk = (*anIt)->exportTo(aFilename, theUsedModules) && isOk;
222     }
223     return isOk;
224   }
225
226 private:
227   std::list<ModelHighAPI_Dumper::DumpStoragePtr> myStorageArray;
228 };
229
230
231 ModelHighAPI_Dumper::DumpStorage::DumpStorage(const DumpStorage& theOther)
232   : myFilenameSuffix(theOther.myFilenameSuffix),
233     myDumpBufferHideout(theOther.myDumpBufferHideout)
234 {
235   myFullDump.str(theOther.myFullDump.str());
236   myDumpBuffer.str(theOther.myDumpBuffer.str());
237 }
238
239 const ModelHighAPI_Dumper::DumpStorage&
240 ModelHighAPI_Dumper::DumpStorage::operator=(const ModelHighAPI_Dumper::DumpStorage& theOther)
241 {
242   myFilenameSuffix = theOther.myFilenameSuffix;
243   myFullDump.str(theOther.myFullDump.str());
244   myDumpBuffer.str(theOther.myDumpBuffer.str());
245   myDumpBufferHideout = theOther.myDumpBufferHideout;
246   return *this;
247 }
248
249 void ModelHighAPI_Dumper::DumpStorage::reserveBuffer()
250 {
251   myDumpBufferHideout.push(myDumpBuffer.str());
252   myDumpBuffer.str("");
253 }
254
255 void ModelHighAPI_Dumper::DumpStorage::restoreReservedBuffer()
256 {
257   myDumpBuffer << myDumpBufferHideout.top();
258   myDumpBufferHideout.pop();
259 }
260
261 bool ModelHighAPI_Dumper::DumpStorage::exportTo(const std::string& theFilename,
262                                                 const ModulesSet& theUsedModules)
263 {
264   std::ofstream 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 aFoundKind =
645           aFIt->second.find(aKind);
646         if (aFoundKind != aFIt->second.end())
647           aFullIndex += aFoundKind->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   std::list<ResultPtr> allRes;
688   ModelAPI_Tools::allResults(theFeature, allRes);
689   for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
690     std::pair<std::wstring, bool> aName = ModelAPI_Tools::getDefaultName(*aRes, true, true);
691     std::string aDefaultName = Locale::Convert::toString(aName.first);
692     std::string aResName = Locale::Convert::toString((*aRes)->data()->name());
693     bool isUserDefined = !(isFeatureDefaultName && aDefaultName == aResName);
694     myNames[*aRes] =
695       EntityName(aResName, (isUserDefined ? aResName : std::string()), !isUserDefined);
696   }
697 }
698
699 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
700                                   const std::string& theFileName)
701 {
702   // dump top level document feature
703   static const std::string aDocName("partSet");
704   myNames[theDoc] = EntityName(aDocName, std::string(), true);
705   *this << aDocName << " = model.moduleDocument()" << std::endl;
706
707   // dump subfeatures and store result to file
708   bool isOk = process(theDoc) && myDumpStorage->exportTo(theFileName, myModules);
709   return isOk;
710 }
711
712 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
713 {
714   bool isOk = true;
715   std::list<ObjectPtr> anObjects = theDoc->allObjects();
716   std::list<ObjectPtr>::const_iterator anObjIt = anObjects.begin();
717   // firstly, dump all parameters
718   for (; anObjIt != anObjects.end(); ++ anObjIt) {
719     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
720     if (aFeature)
721       dumpParameter(aFeature);
722   }
723   // dump all other features
724   for (anObjIt = anObjects.begin(); anObjIt != anObjects.end(); ++anObjIt) {
725     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anObjIt);
726     if (aCompFeat) {
727       // iteratively process composite features,
728       // if the composite feature is the last in the document, no need to dump "model.do()" action
729       std::list<ObjectPtr>::const_iterator aNext = anObjIt;
730       isOk = process(aCompFeat, false, ++aNext != anObjects.end()) && isOk;
731     }
732     else if (!isDumped(EntityPtr(*anObjIt))) {
733       // dump folder
734       FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anObjIt);
735       if (aFolder)
736         dumpFolder(aFolder);
737       else {
738         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIt);
739         if (aFeature) // dump common feature
740           dumpFeature(aFeature);
741       }
742     }
743   }
744   // dump folders if any
745   dumpPostponed(true);
746   return isOk;
747 }
748
749 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
750                                   bool isForce, bool isDumpModelDo)
751 {
752   // increase composite features stack
753   ++gCompositeStackDepth;
754   // dump composite itself
755   if (!isDumped(EntityPtr(theComposite)) || isForce)
756     dumpFeature(FeaturePtr(theComposite), isForce);
757
758   // sub-part is processed independently, because it provides separate document
759   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
760     // dump name of the part if it is different from default
761     if (!myEntitiesStack.empty())
762       dumpEntitySetName();
763
764     // decrease composite features stack because we run into separate document
765     --gCompositeStackDepth;
766
767     ResultPartPtr aPartResult =
768         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
769     if (!aPartResult)
770       return false;
771     DocumentPtr aSubDoc = aPartResult->partDoc();
772     if (!aSubDoc)
773       return false;
774     // set name of document
775     const std::string& aPartName = myNames[theComposite].myCurrentName;
776     std::string aDocName = aPartName + "_doc";
777     myNames[aSubDoc] = EntityName(aDocName, std::string(), true);
778
779     // dump document in a separate line
780     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
781     // dump features in the document
782     bool aRes = process(aSubDoc);
783     if (isDumpModelDo)
784       *this << "\nmodel.do()\n";
785     *this << std::endl;
786     return aRes;
787   }
788
789   // dump sub-features
790   bool isOk = processSubs(theComposite);
791   // decrease composite features stack
792   --gCompositeStackDepth;
793
794   return isOk;
795 }
796
797 bool ModelHighAPI_Dumper::processSubs(
798   const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
799   bool theDumpModelDo)
800 {
801   bool isOk = true;
802   // dump all sub-features;
803   bool isSubDumped = false;
804   int aNbSubs = theComposite->numberOfSubs();
805   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
806     FeaturePtr aFeature = theComposite->subFeature(anIndex);
807     if (isDumped(EntityPtr(aFeature)))
808       continue;
809
810     isSubDumped = true;
811     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
812     if (aCompFeat) // iteratively process composite features
813       isOk = process(aCompFeat) && isOk;
814     else
815       dumpFeature(aFeature, true);
816   }
817
818   bool isDumpSetName = !myEntitiesStack.empty() &&
819       myEntitiesStack.top().myEntity == EntityPtr(theComposite);
820   bool isForceModelDo = isSubDumped && isDumpSetName &&
821       (myEntitiesStack.top().myUserName || !myEntitiesStack.top().myResults.empty());
822   // It is necessary for the sketch to create its result when complete (command "model.do()").
823   // This option is set by flat theDumpModelDo.
824   // However, nested sketches are rebuilt by parent feature, so, they do not need
825   // explicit call of "model.do()". This will be controlled by the depth of the stack.
826   if (isForceModelDo || (theDumpModelDo && gCompositeStackDepth <= 1))
827     *this << "model.do()" << std::endl;
828
829   // dump "setName" for composite feature
830   if (isDumpSetName)
831     dumpEntitySetName();
832   return isOk;
833 }
834
835 void ModelHighAPI_Dumper::postpone(const EntityPtr& theEntity)
836 {
837   // keep the name
838   name(theEntity, false);
839   myPostponed.push_back(theEntity);
840 }
841
842 void ModelHighAPI_Dumper::dumpPostponed(bool theDumpFolders)
843 {
844   if (myDumpPostponedInProgress)
845     return;
846
847   myDumpPostponedInProgress = true;
848   // make a copy of postponed entities, because the list will be updated
849   // if some features are not able to be dumped
850   std::list<EntityPtr> aPostponedCopy = myPostponed;
851   myPostponed.clear();
852
853   // iterate over postponed entities and try to dump them
854   std::list<EntityPtr>::const_iterator anIt = aPostponedCopy.begin();
855   for (; anIt != aPostponedCopy.end(); ++anIt) {
856     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(*anIt);
857     if (aFolder) {
858       if (theDumpFolders)
859         dumpFolder(aFolder);
860       else
861         myPostponed.push_back(*anIt);
862     }
863     else {
864       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
865       if (aFeature)
866         dumpFeature(aFeature, true);
867     }
868   }
869   myDumpPostponedInProgress = false;
870 }
871
872 void ModelHighAPI_Dumper::dumpSubFeatureNameAndColor(const std::string theSubFeatureGet,
873                                                      const FeaturePtr& theSubFeature)
874 {
875   name(theSubFeature, false);
876   myNames[theSubFeature] =
877     EntityName(theSubFeatureGet, Locale::Convert::toString(theSubFeature->name()), false);
878
879   // store results if they have user-defined names or colors
880   std::list<ResultPtr> aResultsWithNameOrColor;
881   const std::list<ResultPtr>& aResults = theSubFeature->results();
882   std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
883   for (; aResIt != aResults.end(); ++aResIt) {
884     std::string aResName = Locale::Convert::toString((*aResIt)->data()->name());
885     myNames[*aResIt] = EntityName(aResName, aResName, false);
886     aResultsWithNameOrColor.push_back(*aResIt);
887   }
888
889   // store just dumped entity to stack
890   myEntitiesStack.push(LastDumpedEntity(theSubFeature, true, aResultsWithNameOrColor));
891
892   dumpEntitySetName();
893 }
894
895 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName)
896 {
897   myModules.insert(theModuleName);
898 }
899
900 void ModelHighAPI_Dumper::dumpEntitySetName()
901 {
902   const LastDumpedEntity& aLastDumped = myEntitiesStack.top();
903   bool isBufferEmpty = myDumpStorage->isBufferEmpty();
904
905   // dump "setName" for the entity
906   if (aLastDumped.myUserName) {
907     EntityName& anEntityNames = myNames[aLastDumped.myEntity];
908     if (!anEntityNames.myIsDefault)
909       *myDumpStorage << anEntityNames.myCurrentName << ".setName(\""
910                      << anEntityNames.myUserName << "\")\n";
911     // don't dump "setName" for the entity twice
912     anEntityNames.myUserName.clear();
913     anEntityNames.myIsDefault = true;
914   }
915   // dump "setName" for results
916   std::list<ResultPtr>::const_iterator aResIt = aLastDumped.myResults.begin();
917   std::list<ResultPtr>::const_iterator aResEnd = aLastDumped.myResults.end();
918   for (; aResIt != aResEnd; ++aResIt) {
919     // set result name
920     EntityName& anEntityNames = myNames[*aResIt];
921     if (!anEntityNames.myIsDefault) {
922       *this << *aResIt;
923       *myDumpStorage << ".setName(\"" << anEntityNames.myUserName << "\")\n";
924       // don't dump "setName" for the entity twice
925       anEntityNames.myUserName.clear();
926       anEntityNames.myIsDefault = true;
927     }
928     // set result color
929     if (!isDefaultColor(*aResIt)) {
930       AttributeIntArrayPtr aColor = (*aResIt)->data()->intArray(ModelAPI_Result::COLOR_ID());
931       if (aColor && aColor->isInitialized()) {
932         *this << *aResIt;
933         *myDumpStorage << ".setColor(" << aColor->value(0) << ", " << aColor->value(1)
934                        << ", " << aColor->value(2) << ")\n";
935       }
936     }
937     // set result deflection
938     if (!isDefaultDeflection(*aResIt)) {
939       AttributeDoublePtr aDeflectionAttr =
940         (*aResIt)->data()->real(ModelAPI_Result::DEFLECTION_ID());
941       if(aDeflectionAttr.get() && aDeflectionAttr->isInitialized()) {
942         *this << *aResIt;
943         *myDumpStorage << ".setDeflection(" << aDeflectionAttr->value() << ")\n";
944       }
945     }
946     // set result transparency
947     if (!isDefaultTransparency(*aResIt)) {
948       AttributeDoublePtr aTransparencyAttr =
949         (*aResIt)->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
950       if(aTransparencyAttr.get() && aTransparencyAttr->isInitialized()) {
951         *this << *aResIt;
952         *myDumpStorage << ".setTransparency(" << aTransparencyAttr->value() << ")\n";
953       }
954     }
955   }
956
957   myNames[aLastDumped.myEntity].myIsDumped = true;
958   myEntitiesStack.pop();
959
960   // clean buffer if it was clear before
961   if (isBufferEmpty)
962     myDumpStorage->mergeBuffer();
963 }
964
965 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
966 {
967   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
968   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
969   return (aFound != myNames.end() && aFound->second.myIsDumped) ||
970          myFeaturesToSkip.find(aFeature) != myFeaturesToSkip.end();
971 }
972
973 bool ModelHighAPI_Dumper::isDumped(const AttributeRefAttrPtr& theRefAttr) const
974 {
975   FeaturePtr aFeature;
976   if (theRefAttr->isObject())
977     aFeature = ModelAPI_Feature::feature(theRefAttr->object());
978   else
979     aFeature = ModelAPI_Feature::feature(theRefAttr->attr()->owner());
980   return aFeature && isDumped(EntityPtr(aFeature));
981 }
982
983 bool ModelHighAPI_Dumper::isDumped(const AttributeRefListPtr& theRefList) const
984 {
985   std::list<ObjectPtr> aRefs = theRefList->list();
986   std::list<ObjectPtr>::iterator anIt = aRefs.begin();
987   for (; anIt != aRefs.end(); ++anIt) {
988     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
989     if (aFeature && !isDumped(EntityPtr(aFeature)))
990       return false;
991   }
992   return true;
993 }
994
995 size_t ModelHighAPI_Dumper::indexOfFirstNotDumped(
996     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList) const
997 {
998   size_t anIndex = 0;
999   std::list<ObjectPtr> anObjects = theRefList->list();
1000   for (std::list<ObjectPtr>::const_iterator anIt = anObjects.begin();
1001        anIt != anObjects.end(); ++anIt, ++anIndex)
1002     if (!isDumped(ModelAPI_Feature::feature(*anIt)))
1003       break;
1004   return anIndex;
1005 }
1006
1007 static bool isSketchSub(const FeaturePtr& theFeature)
1008 {
1009   static const std::string SKETCH("Sketch");
1010   CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theFeature);
1011   return anOwner && anOwner->getKind() == SKETCH;
1012 }
1013
1014 bool ModelHighAPI_Dumper::isDefaultColor(const ResultPtr& theResult) const
1015 {
1016   AttributeIntArrayPtr aColor = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1017   if (!aColor || !aColor->isInitialized())
1018     return true;
1019
1020   // check the result belongs to sketch entity, do not dump color in this way
1021   ResultConstructionPtr aResConstr =
1022       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theResult);
1023   if (aResConstr) {
1024     FeaturePtr aFeature = ModelAPI_Feature::feature(theResult->data()->owner());
1025     if (isSketchSub(aFeature))
1026       return true;
1027   }
1028
1029   std::string aSection, aName, aDefault;
1030   theResult->colorConfigInfo(aSection, aName, aDefault);
1031
1032   // dump current color
1033   std::ostringstream aColorInfo;
1034   aColorInfo << aColor->value(0) << "," << aColor->value(1) << "," << aColor->value(2);
1035
1036   return aDefault == aColorInfo.str();
1037 }
1038
1039 bool ModelHighAPI_Dumper::isDefaultDeflection(const ResultPtr& theResult) const
1040 {
1041   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1042   if(!aDeflectionAttr || !aDeflectionAttr->isInitialized()) {
1043     return true;
1044   }
1045
1046   double aCurrent = aDeflectionAttr->value();
1047   double aDefault = -1;
1048
1049   bool isConstruction = false;
1050   std::string aResultGroup = theResult->groupName();
1051   if (aResultGroup == ModelAPI_ResultConstruction::group())
1052     isConstruction = true;
1053   else if (aResultGroup == ModelAPI_ResultBody::group()) {
1054     GeomShapePtr aGeomShape = theResult->shape();
1055     if (aGeomShape.get()) {
1056       // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
1057       // correction of deviation for them should not influence to the application performance
1058       GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
1059       isConstruction = !anExp.more();
1060     }
1061   }
1062   if (isConstruction)
1063     aDefault = Config_PropManager::real("Visualization", "construction_deflection");
1064   else
1065     aDefault = Config_PropManager::real("Visualization", "body_deflection");
1066
1067   return fabs(aCurrent - aDefault) < 1.e-12;
1068 }
1069
1070 bool ModelHighAPI_Dumper::isDefaultTransparency(const ResultPtr& theResult) const
1071 {
1072   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1073   if(!anAttribute || !anAttribute->isInitialized()) {
1074     return true;
1075   }
1076   return fabs(anAttribute->value()) < 1.e-12;
1077 }
1078
1079 bool ModelHighAPI_Dumper::dumpCommentBeforeFeature(const FeaturePtr& theFeature) const
1080 {
1081   // currently, the comment should not be dumped only before the filters
1082   FiltersFeaturePtr aFilters = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(theFeature);
1083   if (aFilters)
1084     return false;
1085   // all other features should be commented before the dump
1086   return !isDumped(theFeature);
1087 }
1088
1089 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
1090 {
1091   *myDumpStorage << theChar;
1092   return *this;
1093 }
1094
1095 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
1096 {
1097   *myDumpStorage << theString;
1098   return *this;
1099 }
1100
1101 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
1102 {
1103   *myDumpStorage << theString;
1104   return *this;
1105 }
1106
1107 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::wstring& theString)
1108 {
1109   *myDumpStorage << Locale::Convert::toString(theString);
1110   return *this;
1111 }
1112
1113 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
1114 {
1115   *myDumpStorage << (theValue ? "True" : "False");
1116   return *this;
1117 }
1118
1119 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
1120 {
1121   *myDumpStorage << theValue;
1122   return *this;
1123 }
1124
1125 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
1126 {
1127   *myDumpStorage << theValue;
1128   return *this;
1129 }
1130
1131 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
1132 {
1133   importModule("GeomAPI");
1134   *myDumpStorage << "GeomAPI_Pnt(" << thePoint->x() << ", "
1135                  << thePoint->y() << ", " << thePoint->z() << ")";
1136   return *this;
1137 }
1138
1139 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
1140 {
1141   importModule("GeomAPI");
1142   *myDumpStorage << "GeomAPI_Dir(" << theDir->x() << ", "
1143                  << theDir->y() << ", " << theDir->z() << ")";
1144   return *this;
1145 }
1146
1147 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1148     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
1149 {
1150   *myDumpStorage << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
1151   return *this;
1152 }
1153
1154 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1155     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
1156 {
1157   static const int aSize = 3;
1158   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
1159   std::string aTexts[aSize] = {
1160       Locale::Convert::toString(thePoint->textX()),
1161       Locale::Convert::toString(thePoint->textY()),
1162       Locale::Convert::toString(thePoint->textZ())
1163   };
1164   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1165   return *this;
1166 }
1167
1168 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1169     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
1170 {
1171   static const int aSize = 2;
1172   double aValues[aSize] = {thePoint->x(), thePoint->y()};
1173   std::string aTexts[aSize] = {
1174       Locale::Convert::toString(thePoint->textX()),
1175       Locale::Convert::toString(thePoint->textY())
1176   };
1177   myDumpStorage->dumpArray(aSize, aValues, aTexts);
1178   return *this;
1179 }
1180
1181 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1182   const std::shared_ptr<GeomDataAPI_Point2DArray>& thePointArray)
1183 {
1184   static const int aThreshold = 4;
1185   static bool aDumpAsIs = false;
1186   static std::string aSeparator = "";
1187   // if number of elements in the list if greater than a threshold,
1188   // dump it in a separate line with specific name
1189   int aSize = thePointArray->size();
1190   if (aDumpAsIs || aSize <= aThreshold) {
1191     *myDumpStorage << "[";
1192     GeomPnt2dPtr aPoint = thePointArray->pnt(0);
1193     *myDumpStorage << "(" << aPoint->x() << ", " << aPoint->y() << ")";
1194     for (int anIndex = 1; anIndex < aSize; ++anIndex) {
1195       aPoint = thePointArray->pnt(anIndex);
1196       *myDumpStorage << "," << aSeparator << " (" << aPoint->x() << ", " << aPoint->y() << ")";
1197     }
1198     *myDumpStorage << aSeparator << "]";
1199   }
1200   else {
1201     // name of list
1202     FeaturePtr anOwner = ModelAPI_Feature::feature(thePointArray->owner());
1203     std::string aListName = name(anOwner) + "_" + thePointArray->id();
1204     // reserve dumped buffer and store list "as is"
1205     myDumpStorage->reserveBuffer();
1206     aDumpAsIs = true;
1207     aSeparator = std::string("\n") + std::string(aListName.size() + 3, ' ');
1208     *this << aListName << " = " << thePointArray << "\n";
1209     aDumpAsIs = false;
1210     aSeparator = "";
1211     // append reserved data to the end of the current buffer
1212     myDumpStorage->restoreReservedBuffer();
1213     *myDumpStorage << aListName;
1214   }
1215   return *this;
1216 }
1217
1218 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1219     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
1220 {
1221   *myDumpStorage << (theAttrBool->value() ? "True" : "False");
1222   return *this;
1223 }
1224
1225 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1226     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
1227 {
1228   std::string aText = Locale::Convert::toString(theAttrInt->text());
1229   if (aText.empty())
1230     *myDumpStorage << theAttrInt->value();
1231   else
1232     *myDumpStorage << "\"" << aText << "\"";
1233   return *this;
1234 }
1235
1236 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1237     const std::shared_ptr<ModelAPI_AttributeIntArray>& theArray)
1238 {
1239   *myDumpStorage << "[";
1240   int aSize = theArray->size();
1241   if (aSize > 0) {
1242     *myDumpStorage << theArray->value(0);
1243     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1244       *myDumpStorage << ", " << theArray->value(anIndex);
1245   }
1246   *myDumpStorage << "]";
1247   return *this;
1248 }
1249
1250 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1251     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
1252 {
1253   std::string aText = Locale::Convert::toString(theAttrReal->text());
1254   if (aText.empty())
1255     *myDumpStorage << theAttrReal->value();
1256   else
1257     *myDumpStorage << "\"" << aText << "\"";
1258   return *this;
1259 }
1260
1261 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1262   const std::shared_ptr<ModelAPI_AttributeDoubleArray>& theArray)
1263 {
1264   *myDumpStorage << "[";
1265   int aSize = theArray->size();
1266   if (aSize > 0) {
1267     *myDumpStorage << theArray->value(0);
1268     for (int anIndex = 1; anIndex < aSize; ++anIndex)
1269       *myDumpStorage << ", " << theArray->value(anIndex);
1270   }
1271   *myDumpStorage << "]";
1272   return *this;
1273 }
1274
1275 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1276     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
1277 {
1278   // escaping the quote signs in the string under dumping
1279   std::string aStr = theAttrStr->value();
1280   /*
1281   size_t aPos = aStr.find("\"");
1282   while (aPos != std::string::npos) {
1283     aStr.insert(aPos, "\\");
1284     aPos = aStr.find("\"", aPos + 2);
1285   }
1286   aPos = aStr.find("\'");
1287   while (aPos != std::string::npos) {
1288     aStr.insert(aPos, "\\");
1289     aPos = aStr.find("\'", aPos + 2);
1290   }
1291   */
1292   size_t aPos = aStr.find_first_of("\"\'");
1293   while (aPos != std::string::npos) {
1294     aStr.insert(aPos, "\\");
1295     aPos = aStr.find_first_of("\"\'", aPos + 2);
1296   }
1297   *myDumpStorage << "'" << aStr << "'";
1298   return *this;
1299 }
1300
1301 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FolderPtr& theFolder)
1302 {
1303   *myDumpStorage << name(theFolder);
1304
1305   // add dumped folder to a stack
1306   if (!myNames[theFolder].myIsDumped &&
1307      (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theFolder))
1308     myEntitiesStack.push(LastDumpedEntity(theFolder, !myNames[theFolder].myIsDefault));
1309
1310   return *this;
1311 }
1312
1313 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
1314 {
1315   *myDumpStorage << name(theEntity);
1316
1317   if (!myNames[theEntity].myIsDumped) {
1318     bool isUserDefinedName = !myNames[theEntity].myIsDefault;
1319     // store results if they have user-defined names or colors
1320     std::list<ResultPtr> aResultsWithNameOrColor;
1321     std::list<ResultPtr> allRes;
1322     ModelAPI_Tools::allResults(theEntity, allRes);
1323     for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
1324       if(!myNames[*aRes].myIsDefault || !isDefaultColor(*aRes) ||
1325          !isDefaultDeflection(*aRes) || !isDefaultTransparency(*aRes))
1326         aResultsWithNameOrColor.push_back(*aRes);
1327     }
1328     // store just dumped entity to stack
1329     if (myEntitiesStack.empty() || myEntitiesStack.top().myEntity != theEntity)
1330       myEntitiesStack.push(
1331           LastDumpedEntity(theEntity, isUserDefinedName, aResultsWithNameOrColor));
1332   }
1333
1334   // remove entity from the list of not dumped items
1335   myNotDumpedEntities.erase(theEntity);
1336   return *this;
1337 }
1338
1339 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
1340 {
1341   // iterate in the structure of sub-results to the parent
1342   ResultPtr aCurRes = theResult;
1343   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
1344   std::list<int> anIndices; // indexes of results in the parent result, starting from topmost
1345   while(aCurRes.get()) {
1346     ResultBodyPtr aParent = ModelAPI_Tools::bodyOwner(aCurRes);
1347     if (aParent) {
1348       anIndices.push_front(ModelAPI_Tools::bodyIndex(aCurRes));
1349     } else { // index of the result in the feature
1350       std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
1351       for(int anIndex = 0; aRes != aFeature->results().cend(); aRes++, anIndex++) {
1352         if (*aRes == aCurRes) {
1353           anIndices.push_front(anIndex);
1354           break;
1355         }
1356       }
1357     }
1358     aCurRes = aParent;
1359   }
1360
1361   *myDumpStorage << name(aFeature);
1362   for (std::list<int>::iterator anI = anIndices.begin(); anI != anIndices.end(); anI++) {
1363     if (anI == anIndices.begin()) {
1364       if(*anI == 0) {
1365         *myDumpStorage << ".result()";
1366       }
1367       else {
1368         *myDumpStorage << ".results()[" << *anI << "]";
1369       }
1370     } else {
1371       *myDumpStorage << ".subResult(" << *anI << ")";
1372     }
1373   }
1374
1375   return *this;
1376 }
1377
1378 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::list<ResultPtr>& theResults)
1379 {
1380   *this << "[";
1381   for (std::list<ResultPtr>::const_iterator anIt = theResults.begin();
1382        anIt != theResults.end(); ++anIt) {
1383     if (anIt != theResults.begin())
1384       *this << ", ";
1385     *this << *anIt;
1386   }
1387   *this << "]";
1388   return *this;
1389 }
1390
1391 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
1392 {
1393   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
1394   if(aFeature.get()) {
1395     *myDumpStorage << name(aFeature);
1396     return *this;
1397   }
1398
1399   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1400   if(aResult.get()) {
1401     *this << aResult;
1402     return *this;
1403   }
1404
1405   return *this;
1406 }
1407
1408 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
1409 {
1410   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
1411
1412   std::string aWrapperPrefix, aWrapperSuffix;
1413   // Check the attribute belongs to copied (in multi-translation or multi-rotation) feature.
1414   // In this case we need to cast explicitly feature to appropriate type.
1415   AttributeBooleanPtr isCopy = anOwner->boolean("Copy");
1416   AttributeReferencePtr hasParent = anOwner->reference("ParentFeature");
1417   if ((isCopy.get() && isCopy->value()) || (hasParent && hasParent->value())) {
1418     aWrapperPrefix = featureWrapper(anOwner) + "(";
1419     aWrapperSuffix = ")";
1420     importModule("SketchAPI");
1421   }
1422
1423   *myDumpStorage << aWrapperPrefix << name(anOwner) << aWrapperSuffix
1424                  << "." << attributeGetter(anOwner, theAttr->id()) << "()";
1425   return *this;
1426 }
1427
1428 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1429     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
1430 {
1431   if (theRefAttr->isObject())
1432     *this << theRefAttr->object();
1433   else
1434     *this << theRefAttr->attr();
1435   return *this;
1436 }
1437
1438 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1439     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
1440 {
1441   *myDumpStorage << "[";
1442   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
1443   bool isAdded = false;
1444   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
1445   for (; anIt != aList.end(); ++anIt) {
1446     if (isAdded)
1447       *myDumpStorage << ", ";
1448     else
1449       isAdded = true;
1450     if (anIt->first)
1451       *this << anIt->first;
1452     else if (anIt->second)
1453       * this << anIt->second;
1454   }
1455   *myDumpStorage << "]";
1456   return *this;
1457 }
1458
1459 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1460     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
1461 {
1462   *this << theReference->value();
1463   return *this;
1464 }
1465
1466 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1467     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
1468 {
1469   static const int aThreshold = 2;
1470   static bool aDumpAsIs = false;
1471   // if number of elements in the list if greater than a threshold,
1472   // dump it in a separate line with specific name
1473   if (aDumpAsIs || theRefList->size() <= aThreshold) {
1474     *myDumpStorage << "[";
1475     std::list<ObjectPtr> aList = theRefList->list();
1476     bool isAdded = false;
1477     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
1478     for (; anIt != aList.end(); ++anIt) {
1479       if (!(*anIt))
1480         continue;
1481       if (!isDumped(ModelAPI_Feature::feature(*anIt)))
1482         break; // stop if the object is not dumped yet (parent feature should be postponed)
1483
1484       if (isAdded)
1485         *myDumpStorage << ", ";
1486       else
1487         isAdded = true;
1488
1489       *this << *anIt;
1490     }
1491     *myDumpStorage << "]";
1492   } else {
1493     // name of list
1494     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
1495     std::string aListName = name(anOwner) + "_objects";
1496     // reserve dumped buffer and store list "as is"
1497     myDumpStorage->reserveBuffer();
1498     aDumpAsIs = true;
1499     *this << aListName << " = " << theRefList << "\n";
1500     aDumpAsIs = false;
1501     // append reserved data to the end of the current buffer
1502     myDumpStorage->restoreReservedBuffer();
1503     *myDumpStorage << aListName;
1504   }
1505   return *this;
1506 }
1507
1508 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1509     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
1510 {
1511   myDumpStorage->write(theAttrSelect);
1512   return *this;
1513 }
1514
1515 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1516     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
1517 {
1518   static const int aThreshold = 2;
1519   static int aNbSpaces = 0;
1520   // if number of elements in the list if greater than a threshold,
1521   // dump it in a separate line with specific name
1522   if (aNbSpaces > 0 || theAttrSelList->size() <= aThreshold) {
1523     *myDumpStorage << "[";
1524
1525     GeomShapePtr aShape;
1526     std::string aShapeTypeStr;
1527
1528     bool isAdded = false;
1529
1530     for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
1531       AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
1532       aShape = anAttribute->value();
1533       if(!aShape.get()) {
1534         ResultPtr aContext = anAttribute->context();
1535         if (aContext.get())
1536           aShape = aContext->shape();
1537       }
1538
1539       if(!aShape.get()) {
1540         continue;
1541       }
1542
1543       if(isAdded) {
1544         // print each attribute on separate line with the appropriate shift
1545         if (aNbSpaces > 0) {
1546           std::string aSpaces(aNbSpaces + 1, ' ');
1547           *myDumpStorage << ",\n" << aSpaces;
1548         } else
1549           *myDumpStorage << ", ";
1550       } else {
1551         isAdded = true;
1552       }
1553       *this << anAttribute;
1554     }
1555
1556     // check selection list is obtained by filters
1557     FiltersFeaturePtr aFilters = theAttrSelList->filters();
1558     if (aFilters) {
1559       if (theAttrSelList->size() > 0)
1560         *myDumpStorage << ", ";
1561       dumpFeature(aFilters, true);
1562     }
1563
1564     *myDumpStorage << "]";
1565   } else {
1566     // obtain name of list (the feature may contain several selection lists)
1567     FeaturePtr anOwner = ModelAPI_Feature::feature(theAttrSelList->owner());
1568     std::string aListName = name(anOwner) + "_objects";
1569     std::list<AttributePtr> aSelLists =
1570         anOwner->data()->attributes(ModelAPI_AttributeSelectionList::typeId());
1571     if (aSelLists.size() > 1) {
1572       int anIndex = 1;
1573       for (std::list<AttributePtr>::iterator aSIt = aSelLists.begin();
1574            aSIt != aSelLists.end(); ++aSIt, ++anIndex)
1575         if ((*aSIt).get() == theAttrSelList.get())
1576           break;
1577       std::ostringstream aSStream;
1578       aSStream << aListName << "_" << anIndex;
1579       aListName = aSStream.str();
1580     }
1581     // reserve dumped buffer and store list "as is"
1582     myDumpStorage->reserveBuffer();
1583     aNbSpaces = (int)aListName.size() + 3;
1584     *this << aListName << " = " << theAttrSelList << "\n";
1585     aNbSpaces = 0;
1586     // append reserved data to the end of the current buffer
1587     myDumpStorage->restoreReservedBuffer();
1588     *myDumpStorage << aListName;
1589   }
1590   return *this;
1591 }
1592
1593 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
1594   const std::shared_ptr<ModelAPI_AttributeStringArray>& theArray)
1595 {
1596   std::ostringstream aBuffer;
1597   aBuffer << "[";
1598   for(int anIndex = 0; anIndex < theArray->size(); ++anIndex) {
1599     if (anIndex != 0)
1600       aBuffer << ", ";
1601
1602     aBuffer << "\"" << theArray->value(anIndex) << "\"";
1603   }
1604   aBuffer << "]";
1605
1606   myDumpStorage->write(aBuffer.str());
1607   return *this;
1608 }
1609
1610 void ModelHighAPI_Dumper::newline()
1611 {
1612   *this << std::endl;
1613 }
1614
1615 /// Dump std::endl
1616 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
1617                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
1618 {
1619   *theDumper.myDumpStorage << theEndl;
1620
1621   if (!theDumper.myEntitiesStack.empty()) {
1622     bool isCopy;
1623     // all copies have been stored into stack, pop them all
1624     do {
1625       isCopy = false;
1626       // Name for composite feature is dumped when all sub-entities are dumped
1627       // (see method ModelHighAPI_Dumper::processSubs).
1628       const ModelHighAPI_Dumper::LastDumpedEntity& aLastDumped = theDumper.myEntitiesStack.top();
1629       CompositeFeaturePtr aComposite =
1630           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aLastDumped.myEntity);
1631       if (!aComposite) {
1632         theDumper.dumpEntitySetName();
1633         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastDumped.myEntity);
1634         if (aFeature) {
1635           AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1636           isCopy = aCopyAttr.get() && aCopyAttr->value();
1637         }
1638       }
1639     } while (isCopy && !theDumper.myEntitiesStack.empty());
1640   }
1641
1642   // store all not-dumped entities first
1643   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
1644   theDumper.clearNotDumped();
1645   theDumper.myDumpStorage->reserveBuffer();
1646   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
1647   for (; anIt != aNotDumped.end(); ++anIt) {
1648     // if the feature is composite, dump it with all subs
1649     CompositeFeaturePtr aCompFeat =
1650         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
1651     if (aCompFeat)
1652       theDumper.process(aCompFeat, true);
1653     else {
1654       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1655       theDumper.dumpFeature(aFeature, true);
1656       // dump the Projection feature which produces this "Copy" entity
1657       AttributeBooleanPtr aCopyAttr = aFeature->boolean("Copy");
1658       if (aCopyAttr.get() && aCopyAttr->value())
1659       {
1660         const std::set<AttributePtr>& aRefs = aFeature->data()->refsToMe();
1661         std::set<AttributePtr>::iterator aRefIt = aRefs.begin();
1662         for (; aRefIt != aRefs.end(); ++aRefIt)
1663           if ((*aRefIt)->id() == "ProjectedFeature")
1664           { // process projection only
1665             FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
1666             if (anOwner && !theDumper.isDumped(EntityPtr(anOwner)))
1667               theDumper.dumpFeature(anOwner, true);
1668           }
1669       }
1670     }
1671   }
1672
1673   // then store the reserved data
1674   theDumper.myDumpStorage->restoreReservedBuffer();
1675   theDumper.myDumpStorage->mergeBuffer();
1676
1677   // now, store all postponed features
1678   theDumper.dumpPostponed();
1679
1680   return theDumper;
1681 }
1682
1683
1684 void ModelHighAPI_Dumper::exportVariables() const
1685 {
1686   DocumentPtr aRoot = ModelAPI_Session::get()->moduleDocument();
1687   EntityNameMap::const_iterator aNameIter = myNames.cbegin();
1688   for(; aNameIter != myNames.end(); aNameIter++) {
1689     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aNameIter->first);
1690     if (aFeature.get() && aFeature->document() != aRoot) {
1691       FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, aFeature->document());
1692       if (aPartFeat.get()) {
1693         int aFeatureId = aFeature->data()->featureId();
1694         int aPartId = aPartFeat->data()->featureId();
1695         std::ostringstream anEntryStr;
1696         anEntryStr<<aPartId<<":"<<aFeatureId;
1697         std::string anEntry = anEntryStr.str();
1698         exportVariable(anEntry, aNameIter->second.myCurrentName);
1699         size_t aSize = aFeature->results().size();
1700         if (aSize > 1) { // additional entries for features with more than one result
1701           for(size_t a = 1; a < aSize; a++) {
1702             std::ostringstream aResEntryStr;
1703             aResEntryStr<<anEntry<<":"<<a;
1704             std::string aResEntry = aResEntryStr.str();
1705             exportVariable(aResEntry, aNameIter->second.myCurrentName);
1706           }
1707         }
1708       }
1709     }
1710   }
1711 }