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