Salome HOME
Issue #1648: Dump Python in the High Level Parameterized Geometry API
[modules/shaper.git] / src / ModelHighAPI / ModelHighAPI_Dumper.cpp
1 // Copyright (C) 2016-20xx CEA/DEN, EDF R&D -->
2
3 // File:        ModelHighAPI_Dumper.cpp
4 // Created:     1 August 2016
5 // Author:      Artem ZHIDKOV
6
7 //--------------------------------------------------------------------------------------
8 #include "ModelHighAPI_Dumper.h"
9
10 #include <GeomAPI_Pnt.h>
11 #include <GeomAPI_Dir.h>
12
13 #include <GeomDataAPI_Dir.h>
14 #include <GeomDataAPI_Point.h>
15 #include <GeomDataAPI_Point2D.h>
16
17 #include <ModelAPI_AttributeBoolean.h>
18 #include <ModelAPI_AttributeDouble.h>
19 #include <ModelAPI_AttributeInteger.h>
20 #include <ModelAPI_AttributeRefAttr.h>
21 #include <ModelAPI_AttributeRefAttrList.h>
22 #include <ModelAPI_AttributeReference.h>
23 #include <ModelAPI_AttributeRefList.h>
24 #include <ModelAPI_AttributeSelection.h>
25 #include <ModelAPI_AttributeSelectionList.h>
26 #include <ModelAPI_AttributeString.h>
27 #include <ModelAPI_CompositeFeature.h>
28 #include <ModelAPI_Document.h>
29 #include <ModelAPI_Entity.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_Result.h>
32 #include <ModelAPI_ResultPart.h>
33
34 #include <PartSetPlugin_Part.h>
35
36 #include <OSD_OpenFile.hxx>
37
38 #include <fstream>
39
40 #define DUMP_USER_DEFINED_NAMES
41
42 static int gCompositeStackDepth = 0;
43
44 ModelHighAPI_Dumper* ModelHighAPI_Dumper::mySelf = 0;
45
46 ModelHighAPI_Dumper::ModelHighAPI_Dumper()
47 {
48   clear();
49 }
50
51 void ModelHighAPI_Dumper::setInstance(ModelHighAPI_Dumper* theDumper)
52 {
53   if (mySelf == 0)
54     mySelf = theDumper;
55 }
56
57 ModelHighAPI_Dumper* ModelHighAPI_Dumper::getInstance()
58 {
59   return mySelf;
60 }
61
62 void ModelHighAPI_Dumper::clear(bool bufferOnly)
63 {
64   myDumpBuffer = std::ostringstream();
65   myDumpBuffer << std::setprecision(16);
66
67   clearNotDumped();
68
69   if (!bufferOnly) {
70     myFullDump = std::ostringstream();
71     myFullDump << std::setprecision(16);
72
73     myNames.clear();
74     myModules.clear();
75     myFeatureCount.clear();
76     myLastEntityWithName = EntityPtr();
77   }
78 }
79
80 void ModelHighAPI_Dumper::clearNotDumped()
81 {
82   myNotDumpedEntities.clear();
83 }
84
85 const std::string& ModelHighAPI_Dumper::name(const EntityPtr& theEntity)
86 {
87   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
88   if (aFound != myNames.end())
89     return aFound->second.first;
90
91   // entity is not found, store it
92   std::string aName;
93   bool isUserDefined = false;
94   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theEntity);
95   if (aFeature) {
96     isUserDefined = true;
97     aName = aFeature->name();
98     const std::string& aKind = aFeature->getKind();
99     DocumentPtr aDoc = aFeature->document();
100     int& aNbFeatures = myFeatureCount[aDoc][aKind];
101
102     size_t anIndex = aName.find(aKind);
103     if (anIndex == 0 && aName[aKind.length()] == '_') { // name starts with "FeatureKind_"
104       std::string anIdStr = aName.substr(aKind.length() + 1, std::string::npos);
105       int anId = std::stoi(anIdStr);
106
107       // Check number of already registered objects of such kind. Index of current object
108       // should be greater than it to identify feature's name as automatically generated.
109       if (aNbFeatures < anId) {
110         isUserDefined = false;
111         aNbFeatures = anId - 1;
112       }
113     }
114
115     aNbFeatures += 1;
116   }
117
118   myNames[theEntity] = std::pair<std::string, bool>(aName, isUserDefined);
119   myNotDumpedEntities.insert(theEntity);
120   return myNames[theEntity].first;
121 }
122
123 const std::string& ModelHighAPI_Dumper::parentName(const FeaturePtr& theEntity)
124 {
125   const std::set<AttributePtr>& aRefs = theEntity->data()->refsToMe();
126   std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
127   for (; aRefIt != aRefs.end(); ++aRefIt) {
128     CompositeFeaturePtr anOwner = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
129         ModelAPI_Feature::feature((*aRefIt)->owner()));
130     if (anOwner)
131       return name(anOwner);
132   }
133
134   static const std::string DUMMY;
135   return DUMMY;
136 }
137
138 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc,
139                                   const std::string& theFileName)
140 {
141   // dump top level document feature
142   static const std::string aDocName("partSet");
143   myNames[theDoc] = std::pair<std::string, bool>(aDocName, false);
144   *this << aDocName << " = model.moduleDocument()" << std::endl;
145
146   // dump subfeatures and store result to file
147   return process(theDoc) && exportTo(theFileName);
148 }
149
150 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_Document>& theDoc)
151 {
152   bool isOk = true;
153   // dump all features
154   std::list<FeaturePtr> aFeatures = theDoc->allFeatures();
155   std::list<FeaturePtr>::const_iterator aFeatIt = aFeatures.begin();
156   for (; aFeatIt != aFeatures.end(); ++aFeatIt) {
157     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFeatIt);
158     if (aCompFeat) // iteratively process composite features
159       isOk = process(aCompFeat) && isOk;
160     else if (!isDumped(*aFeatIt)) // dump common feature 
161       dumpFeature(*aFeatIt);
162   }
163   return isOk;
164 }
165
166 bool ModelHighAPI_Dumper::process(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite, bool isForce)
167 {
168   // increase composite features stack
169   ++gCompositeStackDepth;
170   // dump composite itself
171   if (!isDumped(theComposite) || isForce)
172     dumpFeature(theComposite, isForce);
173
174   // sub-part is processed independently, because it provides separate document
175   if (theComposite->getKind() == PartSetPlugin_Part::ID()) {
176     // decrease composite features stack because we run into separate document
177     --gCompositeStackDepth;
178
179     ResultPartPtr aPartResult =
180         std::dynamic_pointer_cast<ModelAPI_ResultPart>(theComposite->lastResult());
181     if (!aPartResult)
182       return false;
183     DocumentPtr aSubDoc = aPartResult->partDoc();
184     // set name of document
185     const std::string& aPartName = myNames[theComposite].first;
186     std::string aDocName = aPartName + "_doc";
187     myNames[aSubDoc] = std::pair<std::string, bool>(aDocName, false);
188
189     // dump document in a separate line
190     *this << aDocName << " = " << aPartName << ".document()" << std::endl;
191     // dump features in the document
192     return process(aSubDoc);
193   }
194
195   // dump sub-features
196   bool isOk = processSubs(theComposite);
197   // decrease composite features stack
198   --gCompositeStackDepth;
199
200   return isOk;
201 }
202
203 bool ModelHighAPI_Dumper::processSubs(const std::shared_ptr<ModelAPI_CompositeFeature>& theComposite,
204                                       bool theDumpModelDo)
205 {
206   bool isOk = true;
207   // dump all sub-features;
208   int aNbSubs = theComposite->numberOfSubs();
209   for (int anIndex = 0; anIndex < aNbSubs; ++anIndex) {
210     FeaturePtr aFeature = theComposite->subFeature(anIndex);
211     if (isDumped(aFeature))
212       continue;
213
214     CompositeFeaturePtr aCompFeat = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
215     if (aCompFeat) // iteratively process composite features
216       isOk = process(aCompFeat) && isOk;
217     else
218       dumpFeature(aFeature, true);
219   }
220
221   // It is necessary for the sketch to create its result when complete (command "model.do()").
222   // This option is set by flat theDumpModelDo.
223   // However, nested sketches are rebuilt by parent feature, so, they do not need
224   // explicit call of "model.do()". This will be controlled by the depth of the stack.
225   if (theDumpModelDo && gCompositeStackDepth <= 1)
226     *this << "model.do()" << std::endl;
227   return isOk;
228 }
229
230 bool ModelHighAPI_Dumper::exportTo(const std::string& theFileName)
231 {
232   std::ofstream aFile;
233   OSD_OpenStream(aFile, theFileName.c_str(), std::ofstream::out);
234   if (!aFile.is_open())
235     return false;
236
237   // standard header
238   for (ModulesMap::const_iterator aModIt = myModules.begin();
239        aModIt != myModules.end(); ++aModIt) {
240     aFile << "from " << aModIt->first << " import ";
241     if (aModIt->second.empty() || 
242         aModIt->second.find(std::string()) != aModIt->second.end())
243       aFile << "*"; // import whole module
244     else {
245       // import specific features
246       std::set<std::string>::const_iterator anObjIt = aModIt->second.begin();
247       aFile << *anObjIt;
248       for (++anObjIt; anObjIt != aModIt->second.end(); ++anObjIt)
249         aFile << ", " << *anObjIt;
250     }
251     aFile << std::endl;
252   }
253   if (!myModules.empty())
254     aFile << std::endl;
255
256   aFile << "import model" << std::endl << std::endl;
257   aFile << "model.begin()" << std::endl;
258
259   // dump collected data
260   aFile << myFullDump.str();
261
262   // standard footer
263   aFile << "model.end()" << std::endl;
264
265   aFile.close();
266   clear();
267
268   return true;
269 }
270
271 void ModelHighAPI_Dumper::importModule(const std::string& theModuleName,
272                                        const std::string& theObject)
273 {
274   myModules[theModuleName].insert(theObject);
275 }
276
277 void ModelHighAPI_Dumper::dumpEntitySetName()
278 {
279   if (!myLastEntityWithName)
280     return;
281
282 #ifdef DUMP_USER_DEFINED_NAMES
283   const std::string& aName = name(myLastEntityWithName);
284   myDumpBuffer << aName;
285   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myLastEntityWithName);
286   if (aFeature)
287     myDumpBuffer << ".feature()";
288   myDumpBuffer << ".data().setName(\"" << aName << "\")" << std::endl;
289 #endif
290   myNames[myLastEntityWithName].second = false; // don't dump "setName" for the entity twice
291   myLastEntityWithName = EntityPtr();
292 }
293
294 bool ModelHighAPI_Dumper::isDumped(const EntityPtr& theEntity) const
295 {
296   EntityNameMap::const_iterator aFound = myNames.find(theEntity);
297   return aFound != myNames.end();
298 }
299
300 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char theChar)
301 {
302   myDumpBuffer << theChar;
303   return *this;
304 }
305
306 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const char* theString)
307 {
308   myDumpBuffer << theString;
309   return *this;
310 }
311
312 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::string& theString)
313 {
314   myDumpBuffer << theString;
315   return *this;
316 }
317
318 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const bool theValue)
319 {
320   myDumpBuffer << (theValue ? "True" : "False");
321   return *this;
322 }
323
324 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const int theValue)
325 {
326   myDumpBuffer << theValue;
327   return *this;
328 }
329
330 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const double theValue)
331 {
332   myDumpBuffer << theValue;
333   return *this;
334 }
335
336 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Pnt>& thePoint)
337 {
338   importModule("GeomAPI", "GeomAPI_Pnt");
339   myDumpBuffer << "GeomAPI_Pnt(" << thePoint->x() << ", "
340                << thePoint->y() << ", " << thePoint->z() << ")";
341   return *this;
342 }
343
344 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const std::shared_ptr<GeomAPI_Dir>& theDir)
345 {
346   importModule("GeomAPI", "GeomAPI_Dir");
347   myDumpBuffer << "GeomAPI_Dir(" << theDir->x() << ", "
348                << theDir->y() << ", " << theDir->z() << ")";
349   return *this;
350 }
351
352 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
353     const std::shared_ptr<GeomDataAPI_Dir>& theDir)
354 {
355   myDumpBuffer << theDir->x() << ", " << theDir->y() << ", " << theDir->z();
356   return *this;
357 }
358
359 static void dumpArray(std::ostringstream& theOutput, int theSize,
360                       double* theValues, std::string* theTexts)
361 {
362   for (int i = 0; i < theSize; ++i) {
363     if (i > 0)
364       theOutput << ", ";
365     if (theTexts[i].empty())
366       theOutput << theValues[i];
367     else
368       theOutput << "\"" << theTexts[i] << "\"";
369   }
370 }
371
372 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
373     const std::shared_ptr<GeomDataAPI_Point>& thePoint)
374 {
375   static const int aSize = 3;
376   double aValues[aSize] = {thePoint->x(), thePoint->y(), thePoint->z()};
377   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY(), thePoint->textZ()};
378   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
379   return *this;
380 }
381
382 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
383     const std::shared_ptr<GeomDataAPI_Point2D>& thePoint)
384 {
385   static const int aSize = 2;
386   double aValues[aSize] = {thePoint->x(), thePoint->y()};
387   std::string aTexts[aSize] = {thePoint->textX(), thePoint->textY()};
388   dumpArray(myDumpBuffer, aSize, aValues, aTexts);
389   return *this;
390 }
391
392 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
393     const std::shared_ptr<ModelAPI_AttributeBoolean>& theAttrBool)
394 {
395   myDumpBuffer << (theAttrBool->value() ? "True" : "False");
396   return *this;
397 }
398
399 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
400     const std::shared_ptr<ModelAPI_AttributeInteger>& theAttrInt)
401 {
402   std::string aText = theAttrInt->text();
403   if (aText.empty())
404     myDumpBuffer << theAttrInt->value();
405   else
406     myDumpBuffer << "\"" << aText << "\"";
407   return *this;
408 }
409
410 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
411     const std::shared_ptr<ModelAPI_AttributeDouble>& theAttrReal)
412 {
413   std::string aText = theAttrReal->text();
414   if (aText.empty())
415     myDumpBuffer << theAttrReal->value();
416   else
417     myDumpBuffer << "\"" << aText << "\"";
418   return *this;
419 }
420
421 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
422     const std::shared_ptr<ModelAPI_AttributeString>& theAttrStr)
423 {
424   myDumpBuffer << "\"" << theAttrStr->value() << "\"";
425   return *this;
426 }
427
428 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const FeaturePtr& theEntity)
429 {
430   myDumpBuffer << name(theEntity);
431   if (myNames[theEntity].second)
432     myLastEntityWithName = theEntity;
433   myNotDumpedEntities.erase(theEntity);
434   return *this;
435 }
436
437 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ResultPtr& theResult)
438 {
439   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
440   int anIndex = 0;
441   std::list<ResultPtr> aResults = aFeature->results();
442   for(std::list<ResultPtr>::const_iterator anIt = aResults.cbegin(); anIt != aResults.cend(); ++anIt, ++anIndex) {
443     if(theResult->isSame(*anIt)) {
444       break;
445     }
446   }
447   myDumpBuffer << name(aFeature) << ".result()[" << anIndex << "]";
448   return *this;
449 }
450
451 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const ObjectPtr& theObject)
452 {
453   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
454   if(aFeature.get()) {
455     myDumpBuffer << name(aFeature);
456     return *this;
457   }
458
459   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
460   if(aResult.get()) {
461     *this << aResult;
462     return *this;
463   }
464
465   return *this;
466 }
467
468 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(const AttributePtr& theAttr)
469 {
470   FeaturePtr anOwner = ModelAPI_Feature::feature(theAttr->owner());
471   myDumpBuffer << name(anOwner) << "." << attributeGetter(anOwner, theAttr->id()) << "()";
472   return *this;
473 }
474
475 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
476     const std::shared_ptr<ModelAPI_AttributeRefAttr>& theRefAttr)
477 {
478   if (theRefAttr->isObject())
479     *this << theRefAttr->object();
480   else
481     *this << theRefAttr->attr();
482   return *this;
483 }
484
485 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
486     const std::shared_ptr<ModelAPI_AttributeRefAttrList>& theRefAttrList)
487 {
488   myDumpBuffer << "[";
489   std::list<std::pair<ObjectPtr, AttributePtr> > aList = theRefAttrList->list();
490   bool isAdded = false;
491   std::list<std::pair<ObjectPtr, AttributePtr> >::const_iterator anIt = aList.begin();
492   for (; anIt != aList.end(); ++anIt) {
493     if (isAdded)
494       myDumpBuffer << ", ";
495     else
496       isAdded = true;
497     if (anIt->first)
498       *this << anIt->first;
499     else if (anIt->second)
500       * this << anIt->second;
501   }
502   myDumpBuffer << "]";
503   return *this;
504 }
505
506 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
507     const std::shared_ptr<ModelAPI_AttributeReference>& theReference)
508 {
509   *this << theReference->value();
510   return *this;
511 }
512
513 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
514     const std::shared_ptr<ModelAPI_AttributeRefList>& theRefList)
515 {
516   static const int aThreshold = 2;
517   // if number of elements in the list if greater than a threshold,
518   // dump it in a separate line with specific name
519   std::string aDumped = myDumpBuffer.str();
520   if (aDumped.empty() || theRefList->size() <= aThreshold) {
521     myDumpBuffer << "[";
522     std::list<ObjectPtr> aList = theRefList->list();
523     bool isAdded = false;
524     std::list<ObjectPtr>::const_iterator anIt = aList.begin();
525     for (; anIt != aList.end(); ++anIt) {
526       if (isAdded)
527         myDumpBuffer << ", ";
528       else
529         isAdded = true;
530
531       *this << *anIt;
532     }
533     myDumpBuffer << "]";
534   } else {
535     // clear buffer and store list "as is"
536     myDumpBuffer = std::ostringstream();
537     *this << theRefList;
538     // save buffer and clear it again
539     std::string aDumpedList = myDumpBuffer.str();
540     myDumpBuffer = std::ostringstream();
541     // obtain name of list
542     FeaturePtr anOwner = ModelAPI_Feature::feature(theRefList->owner());
543     std::string aListName = name(anOwner) + "_objects";
544     // store all previous data
545     myDumpBuffer << aListName << " = " << aDumpedList << std::endl
546                  << aDumped << aListName;
547   }
548   return *this;
549 }
550
551 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
552     const std::shared_ptr<ModelAPI_AttributeSelection>& theAttrSelect)
553 {
554   myDumpBuffer << "model.selection(";
555
556   if(!theAttrSelect->isInitialized()) {
557     myDumpBuffer << ")";
558     return *this;
559   }
560
561   GeomShapePtr aShape = theAttrSelect->value();
562   if(!aShape.get()) {
563     aShape = theAttrSelect->context()->shape();
564   }
565
566   if(!aShape.get()) {
567     myDumpBuffer << ")";
568     return *this;
569   }
570
571   myDumpBuffer << "\"" << aShape->shapeTypeStr() << "\", \"" << theAttrSelect->namingName() << "\")";
572   return *this;
573 }
574
575 ModelHighAPI_Dumper& ModelHighAPI_Dumper::operator<<(
576     const std::shared_ptr<ModelAPI_AttributeSelectionList>& theAttrSelList)
577 {
578   myDumpBuffer << "[";
579
580   GeomShapePtr aShape;
581   std::string aShapeTypeStr;
582
583   bool isAdded = false;
584
585   for(int anIndex = 0; anIndex < theAttrSelList->size(); ++anIndex) {
586     AttributeSelectionPtr anAttribute = theAttrSelList->value(anIndex);
587     aShape = anAttribute->value();
588     if(!aShape.get()) {
589       aShape = anAttribute->context()->shape();
590     }
591
592     if(!aShape.get()) {
593       continue;
594     }
595
596     if(isAdded) {
597       myDumpBuffer << ", ";
598     } else {
599       isAdded = true;
600     }
601     myDumpBuffer << "model.selection(\"" << aShape->shapeTypeStr() << "\", \"" << anAttribute->namingName() << "\")";
602   }
603
604   myDumpBuffer << "]";
605   return *this;
606 }
607
608 /// Dump std::endl
609 MODELHIGHAPI_EXPORT
610 ModelHighAPI_Dumper& operator<<(ModelHighAPI_Dumper& theDumper,
611                                 std::basic_ostream<char>& (*theEndl)(std::basic_ostream<char>&))
612 {
613   theDumper.myDumpBuffer << theEndl;
614   theDumper.dumpEntitySetName();
615
616   // store all not-dumped entities first
617   std::set<EntityPtr> aNotDumped = theDumper.myNotDumpedEntities;
618   std::string aBufCopy = theDumper.myDumpBuffer.str();
619   theDumper.clear(true);
620   std::set<EntityPtr>::const_iterator anIt = aNotDumped.begin();
621   for (; anIt != aNotDumped.end(); ++anIt) {
622     // if the feature is composite, dump it with all subs
623     CompositeFeaturePtr aCompFeat =
624         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
625     if (aCompFeat)
626       theDumper.process(aCompFeat, true);
627     else {
628       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
629       theDumper.dumpFeature(aFeature, true);
630     }
631   }
632
633   // avoid multiple empty lines
634   size_t anInd = std::string::npos;
635   while ((anInd = aBufCopy.find("\n\n\n")) != std::string::npos)
636     aBufCopy.erase(anInd, 1);
637   // then store currently dumped string
638   theDumper.myFullDump << aBufCopy;
639
640   return theDumper;
641 }