Salome HOME
983b68e83fcdd9d3fdb79a21d3bbf85ce6b2feff
[modules/geom.git] / src / GEOMImpl / GEOMImpl_IInsertOperations.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include <Standard_Stream.hxx>
24
25 #include <GEOMImpl_IInsertOperations.hxx>
26
27 #include <GEOMImpl_CopyDriver.hxx>
28 #include <GEOMImpl_ExportDriver.hxx>
29 #include <GEOMImpl_ImportDriver.hxx>
30 #include <GEOMImpl_ICopy.hxx>
31 #include <GEOMImpl_IImportExport.hxx>
32 #include <GEOMImpl_Types.hxx>
33 #include "GEOMImpl_IShapesOperations.hxx"
34 #include "GEOMImpl_IGroupOperations.hxx"
35 #include "GEOMImpl_IFieldOperations.hxx"
36 #include "GEOMImpl_XAODriver.hxx"
37 #include "GEOMImpl_IImportExportXAO.hxx"
38
39 #include <GEOM_Function.hxx>
40 #include <GEOM_PythonDump.hxx>
41 #include "GEOM_ISubShape.hxx"
42
43 #include <XAO_Xao.hxx>
44 #include <XAO_Geometry.hxx>
45 #include <XAO_BrepGeometry.hxx>
46 #include <XAO_Group.hxx>
47 #include <XAO_Field.hxx>
48 #include <XAO_XaoUtils.hxx>
49 #include <XAO_BooleanField.hxx>
50 #include <XAO_IntegerField.hxx>
51 #include <XAO_DoubleField.hxx>
52 #include <XAO_StringField.hxx>
53 #include <XAO_BooleanStep.hxx>
54 #include <XAO_IntegerStep.hxx>
55 #include <XAO_DoubleStep.hxx>
56 #include <XAO_StringStep.hxx>
57
58 #include <Basics_OCCTVersion.hxx>
59
60 #include "utilities.h"
61 #include <OpUtil.hxx>
62 #include <Utils_ExceptHandlers.hxx>
63
64 #include <TFunction_DriverTable.hxx>
65 #include <TFunction_Driver.hxx>
66 #include <TFunction_Logbook.hxx>
67 #include <TDF_ChildIDIterator.hxx>
68 #include <TDF_Tool.hxx>
69 #include <TDataStd_Integer.hxx>
70 #include <TNaming_NamedShape.hxx>
71 #include <TDataStd_Comment.hxx>
72 #include <TopTools_IndexedMapOfShape.hxx>
73 #include <TopExp.hxx>
74
75 #include <TopoDS.hxx>
76 #include <TopoDS_Vertex.hxx>
77 #include <BRep_Builder.hxx>
78 #include <BRep_Tool.hxx>
79 #include <BRepTools.hxx>
80 #include <gp_Pnt.hxx>
81
82 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
83 #include <TColStd_HArray1OfByte.hxx>
84 #include <TColStd_HArray1OfReal.hxx>
85 #else
86 #include <TDataStd_HArray1OfByte.hxx>
87 #endif
88
89 #include <Standard_Failure.hxx>
90 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
91
92 /**
93  * This function returns the input format name from the original format name.
94  */
95 static TCollection_AsciiString GetImportFormatName
96         (const TCollection_AsciiString& theFormatName)
97 {
98   return theFormatName.Token("_");
99 }
100
101 //=============================================================================
102 /*!
103  *  constructor
104  */
105 //=============================================================================
106 GEOMImpl_IInsertOperations::GEOMImpl_IInsertOperations(GEOM_Engine* theEngine, int theDocID)
107 : GEOM_IOperations(theEngine, theDocID)
108 {
109   MESSAGE("GEOMImpl_IInsertOperations::GEOMImpl_IInsertOperations");
110   myShapesOperations = new GEOMImpl_IShapesOperations(GetEngine(), GetDocID());
111   myGroupOperations = new GEOMImpl_IGroupOperations(GetEngine(), GetDocID());
112   myFieldOperations = new GEOMImpl_IFieldOperations(GetEngine(), GetDocID());
113 }
114
115 //=============================================================================
116 /*!
117  *  destructor
118  */
119 //=============================================================================
120 GEOMImpl_IInsertOperations::~GEOMImpl_IInsertOperations()
121 {
122   MESSAGE("GEOMImpl_IInsertOperations::~GEOMImpl_IInsertOperations");
123   delete myShapesOperations;
124   delete myGroupOperations;
125   delete myFieldOperations;
126 }
127
128 //=============================================================================
129 /*!
130  *  MakeCopy
131  */
132 //=============================================================================
133 Handle(GEOM_Object) GEOMImpl_IInsertOperations::MakeCopy (Handle(GEOM_Object) theOriginal)
134 {
135   SetErrorCode(KO);
136
137   if (theOriginal.IsNull()) return NULL;
138
139   //Add a new Copy object
140   Handle(GEOM_Object) aCopy = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
141
142   //Add a Copy function for creation a copy object
143   Handle(GEOM_Function) aFunction = aCopy->AddFunction(GEOMImpl_CopyDriver::GetID(), COPY_WITH_REF);
144
145   //Check if the function is set correctly
146   if(aFunction->GetDriverGUID() != GEOMImpl_CopyDriver::GetID()) return NULL;
147
148   GEOMImpl_ICopy aCI(aFunction);
149
150   Handle(GEOM_Function) aRefFunction = theOriginal->GetLastFunction();
151   if (aRefFunction.IsNull()) return NULL;
152
153   aCI.SetOriginal(aRefFunction);
154
155   //Compute the Copy value
156   try {
157 #if OCC_VERSION_LARGE > 0x06010000
158     OCC_CATCH_SIGNALS;
159 #endif
160     if (!GetSolver()->ComputeFunction(aFunction)) {
161       SetErrorCode("Copy driver failed");
162       return NULL;
163     }
164   }
165   catch (Standard_Failure) {
166     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
167     SetErrorCode(aFail->GetMessageString());
168     return NULL;
169   }
170
171   //Make a Python command
172   GEOM::TPythonDump(aFunction) << aCopy << " = geompy.MakeCopy(" << theOriginal << ")";
173
174   SetErrorCode(OK);
175   return aCopy;
176 }
177
178 //=============================================================================
179 /*!
180  *  Export
181  */
182 //=============================================================================
183 void GEOMImpl_IInsertOperations::Export
184                      (const Handle(GEOM_Object)      theOriginal,
185                       const TCollection_AsciiString& theFileName,
186                       const TCollection_AsciiString& theFormatName)
187 {
188   SetErrorCode(KO);
189
190   if (theOriginal.IsNull()) return;
191
192   Handle(GEOM_Function) aRefFunction = theOriginal->GetLastFunction();
193   if (aRefFunction.IsNull()) return;  //There is no function which creates an object to be exported
194
195   //Add a new result object
196   Handle(GEOM_Object) result = GetEngine()->AddObject(GetDocID(), GEOM_IMPORT);
197
198   //Add an Export function
199   Handle(GEOM_Function) aFunction = result->AddFunction(GEOMImpl_ExportDriver::GetID(), EXPORT_SHAPE);
200   if (aFunction.IsNull()) return;
201
202   //Check if the function is set correctly
203   if (aFunction->GetDriverGUID() != GEOMImpl_ExportDriver::GetID()) return;
204
205   Handle(TCollection_HAsciiString) aHLibName;
206   if (!IsSupported(Standard_False, theFormatName, aHLibName)) {
207     return;
208   }
209   TCollection_AsciiString aLibName = aHLibName->String();
210
211   //Set parameters
212   GEOMImpl_IImportExport aCI (aFunction);
213   aCI.SetOriginal(aRefFunction);
214   aCI.SetFileName(theFileName);
215   aCI.SetFormatName(theFormatName);
216   aCI.SetPluginName(aLibName);
217
218   //Perform the Export
219   try {
220 #if OCC_VERSION_LARGE > 0x06010000
221     OCC_CATCH_SIGNALS;
222 #endif
223     if (!GetSolver()->ComputeFunction(aFunction)) {
224       SetErrorCode("Not enough space on disk, or you haven't permissions to write this directory");
225       return;
226     }
227   }
228   catch (Standard_Failure) {
229     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
230     SetErrorCode(aFail->GetMessageString());
231     return;
232   }
233
234   //Make a Python command
235   GEOM::TPythonDump(aFunction) << "geompy.Export(" << theOriginal << ", \""
236     << theFileName.ToCString() << "\", \"" << theFormatName.ToCString() << "\")";
237
238   SetErrorCode(OK);
239 }
240
241 //=============================================================================
242 /*!
243  *  Import
244  */
245 //=============================================================================
246 Handle(TColStd_HSequenceOfTransient) GEOMImpl_IInsertOperations::Import
247                                  (const TCollection_AsciiString& theFileName,
248                                   const TCollection_AsciiString& theFormatName)
249 {
250   SetErrorCode(KO);
251
252   if (theFileName.IsEmpty() || theFormatName.IsEmpty()) return NULL;
253
254   //Add a new result object
255   Handle(GEOM_Object) anImported = GetEngine()->AddObject(GetDocID(), GEOM_IMPORT);
256
257   //Add an Import function
258   Handle(GEOM_Function) aFunction =
259     anImported->AddFunction(GEOMImpl_ImportDriver::GetID(), IMPORT_SHAPE);
260
261   if (aFunction.IsNull()) return NULL;
262
263   //Check if the function is set correctly
264   if (aFunction->GetDriverGUID() != GEOMImpl_ImportDriver::GetID()) return NULL;
265
266   Handle(TCollection_HAsciiString) aHLibName;
267   if (!IsSupported
268           (Standard_True, GetImportFormatName(theFormatName), aHLibName)) {
269     return NULL;
270   }
271   TCollection_AsciiString aLibName = aHLibName->String();
272
273   //Set parameters
274   GEOMImpl_IImportExport aCI (aFunction);
275   aCI.SetFileName(theFileName);
276   aCI.SetFormatName(theFormatName);
277   aCI.SetPluginName(aLibName);
278
279   //Perform the Import
280   Handle(TColStd_HSequenceOfTransient) aSeq = new TColStd_HSequenceOfTransient;
281
282   try {
283 #if OCC_VERSION_LARGE > 0x06010000
284     OCC_CATCH_SIGNALS;
285 #endif
286     if (!GetSolver()->ComputeFunction(aFunction)) {
287       SetErrorCode("Import driver failed");
288       return NULL;
289     }
290
291     aSeq->Append(anImported);
292
293     // Greate material groups.
294     MakeMaterialGroups(anImported, aSeq);
295   }
296   catch (Standard_Failure) {
297     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
298     SetErrorCode(aFail->GetMessageString());
299     return NULL;
300   }
301
302   //Make a Python command
303   if (theFormatName != "IGES_UNIT") {
304     GEOM::TPythonDump pd (aFunction);
305     if (theFormatName == "BREP")
306       pd << anImported << " = geompy.ImportBREP(\"" << theFileName.ToCString() << "\")";
307     else if (theFormatName == "IGES")
308       pd << anImported << " = geompy.ImportIGES(\"" << theFileName.ToCString() << "\")";
309     else if (theFormatName == "IGES_SCALE")
310       pd << anImported << " = geompy.ImportIGES(\"" << theFileName.ToCString() << "\", True)";
311     else if (theFormatName == "STEP")
312       pd << anImported << " = geompy.ImportSTEP(\"" << theFileName.ToCString() << "\")";
313     else if (theFormatName == "STEP_SCALE")
314       pd << anImported << " = geompy.ImportSTEP(\"" << theFileName.ToCString() << "\", True)";
315     else {
316       pd << anImported << " = geompy.ImportFile(\""
317          << theFileName.ToCString() << "\", \"" << theFormatName.ToCString() << "\")";
318     }
319   }
320
321   SetErrorCode(OK);
322
323   // OLD CODE: begin
324   if (theFormatName == "IGES_UNIT") {
325     TopoDS_Shape S = aFunction->GetValue();
326     TopoDS_Vertex V = TopoDS::Vertex(S);
327     gp_Pnt P = BRep_Tool::Pnt(V);
328     double scale = P.X();
329     TCollection_AsciiString aUnitName = "UNIT_M";
330     if (fabs(scale-0.01) < 1.e-6)
331       aUnitName = "UNIT_CM";
332     else if (fabs(scale-0.001) < 1.e-6)
333       aUnitName = "UNIT_MM";
334     //cout<<"IIO: aUnitName = "<<aUnitName.ToCString()<<endl;
335     SetErrorCode(aUnitName);
336   }
337   // OLD CODE: end
338
339   return aSeq;
340 }
341
342 //=============================================================================
343 /*!
344  *  ReadValue
345  */
346 //=============================================================================
347 TCollection_AsciiString GEOMImpl_IInsertOperations::ReadValue
348                                  (const TCollection_AsciiString& theFileName,
349                                   const TCollection_AsciiString& theFormatName,
350                                   const TCollection_AsciiString& theParameterName)
351 {
352   SetErrorCode(KO);
353
354   TCollection_AsciiString aValue, anError;
355
356   if (theFileName.IsEmpty() || theFormatName.IsEmpty() || theParameterName.IsEmpty()) return aValue;
357
358   Handle(TCollection_HAsciiString) aHLibName;
359   if (!IsSupported
360           (Standard_True, GetImportFormatName(theFormatName), aHLibName)) {
361     return aValue;
362   }
363   TCollection_AsciiString aLibName = aHLibName->String();
364
365   aValue = GEOMImpl_ImportDriver::ReadValue(theFileName, aLibName, theParameterName, anError);
366   if (anError.IsEmpty())
367     SetErrorCode(OK);
368   else
369     SetErrorCode(anError.ToCString());
370
371   return aValue;
372 }
373
374 //=============================================================================
375 /*!
376  *  ImportTranslators
377  */
378 //=============================================================================
379 Standard_Boolean GEOMImpl_IInsertOperations::ImportTranslators
380                      (Handle(TColStd_HSequenceOfAsciiString)& theFormats,
381                       Handle(TColStd_HSequenceOfAsciiString)& thePatterns)
382 {
383   if (theFormats.IsNull())
384     theFormats = new TColStd_HSequenceOfAsciiString;
385   else
386     theFormats->Clear();
387
388   if (thePatterns.IsNull())
389     thePatterns = new TColStd_HSequenceOfAsciiString;
390   else
391     thePatterns->Clear();
392
393   if (!InitResMgr()) return Standard_False;
394
395   // Read Import formats from directories
396   Handle(Resource_Manager) aResMgr;
397   Handle(TColStd_HSequenceOfAsciiString) aFormatsToAdd;
398   for(int index = 0; index < myResMgrList.size(); index++) {
399     int anOldLen = theFormats->Length();
400     aResMgr = myResMgrList.at(index);
401     if (aResMgr->Find("Import")) {
402       TCollection_AsciiString aFormats (aResMgr->Value("Import"));
403       TCollection_AsciiString aToken = aFormats.Token("| \t", 1);
404       for (int i = 1; !aToken.IsEmpty(); aToken = aFormats.Token("| \t", ++i)) {
405         int aLenFormats = theFormats->Length();
406         bool isFound = false;
407         for(int aInd=1;aInd<=aLenFormats;aInd++){
408           if( theFormats->Value(aInd) == aToken ){
409             isFound = true;
410             break;
411           }
412         }
413         if(!isFound)
414           theFormats->Append(aToken);
415       }
416     }
417
418     // Read Patterns for each supported format
419     for (int j = anOldLen+1; j <= theFormats->Length(); j++) {
420       TCollection_AsciiString aKey, aPattern;
421       aKey = theFormats->Value(j) + ".ImportPattern";
422       if (aResMgr->Find(aKey.ToCString()))
423         aPattern = aResMgr->Value(aKey.ToCString());
424       else {
425         aKey = theFormats->Value(j) + ".Pattern";
426         if (aResMgr->Find(aKey.ToCString()))
427           aPattern = aResMgr->Value(aKey.ToCString());
428         else {
429           aPattern = theFormats->Value(j);
430           aPattern += " Files ( *.* )";
431         }
432       }
433       thePatterns->Append(aPattern);
434     }
435   }
436
437   return (!theFormats->IsEmpty());
438 }
439
440 //=============================================================================
441 /*!
442  *  ExportTranslators
443  */
444 //=============================================================================
445 Standard_Boolean GEOMImpl_IInsertOperations::ExportTranslators
446                      (Handle(TColStd_HSequenceOfAsciiString)& theFormats,
447                       Handle(TColStd_HSequenceOfAsciiString)& thePatterns)
448 {
449   if (theFormats.IsNull())
450     theFormats = new TColStd_HSequenceOfAsciiString;
451   else
452     theFormats->Clear();
453
454   if (thePatterns.IsNull())
455     thePatterns = new TColStd_HSequenceOfAsciiString;
456   else
457     thePatterns->Clear();
458
459   if (!InitResMgr()) return Standard_False;
460
461   // Read Export formats list from directories
462   Handle(Resource_Manager) aResMgr;
463   for(int index=0; index < myResMgrList.size(); index++) {
464     int anOldLen = theFormats->Length();
465     aResMgr = myResMgrList.at(index);
466     if (aResMgr->Find("Export")) {
467       TCollection_AsciiString aFormats (aResMgr->Value("Export"));
468       TCollection_AsciiString aToken = aFormats.Token("| \t", 1);
469       for (int i = 1; !aToken.IsEmpty(); aToken = aFormats.Token("| \t", ++i)) {
470         int aLenFormats = theFormats->Length();
471         bool isFound = false;
472         for(int aInd=1;aInd<=aLenFormats;aInd++){
473           if( theFormats->Value(aInd) == aToken){
474             isFound = true;
475             break;
476           }
477         }
478         if(!isFound)
479           theFormats->Append(aToken);
480       }
481     }
482
483     // Read Patterns for each supported format
484     for (int j = anOldLen+1; j <= theFormats->Length(); j++) {
485       TCollection_AsciiString aKey, aPattern;
486       aKey = theFormats->Value(j) + ".ExportPattern";
487       if (aResMgr->Find(aKey.ToCString()))
488         aPattern = aResMgr->Value(aKey.ToCString());
489       else {
490         aKey = theFormats->Value(j) + ".Pattern";
491         if (aResMgr->Find(aKey.ToCString()))
492           aPattern = aResMgr->Value(aKey.ToCString());
493         else {
494           aPattern = theFormats->Value(j);
495           aPattern += " Files ( *.* )";
496         }
497       }
498       thePatterns->Append(aPattern);
499     }
500   }
501
502   return (!theFormats->IsEmpty());
503 }
504
505 //=============================================================================
506 /*!
507  *  IsSupported
508  */
509 //=============================================================================
510 Standard_Boolean GEOMImpl_IInsertOperations::IsSupported
511                             (const Standard_Boolean isImport,
512                              const TCollection_AsciiString& theFormat,
513                              Handle(TCollection_HAsciiString)& theLibName)
514 {
515   if (!InitResMgr()) return Standard_False;
516
517   // Import/Export mode
518   TCollection_AsciiString aMode;
519   //Standard_CString aMode;
520   if (isImport) aMode = "Import";
521   else aMode = "Export";
522
523   // Read supported formats for the certain mode from user directory
524   Handle(Resource_Manager) aResMgr;
525   for(int index=0; index < myResMgrList.size(); index++) {
526     aResMgr = myResMgrList.at(index);
527     if (aResMgr->Find(aMode.ToCString())) {
528       TCollection_AsciiString aFormats (aResMgr->Value(aMode.ToCString()));
529       if (aFormats.Search(theFormat) > -1) {
530         // Read library name for the supported format
531         TCollection_AsciiString aKey (theFormat);
532         aKey += ".";
533         aKey += aMode;
534         if (aResMgr->Find(aKey.ToCString())) {
535           TCollection_AsciiString aLibName (aResMgr->Value(aKey.ToCString()));
536   #ifndef WIN32
537           if ( aLibName.Length() > 3 && aLibName.SubString(1,3) != "lib" )
538             aLibName.Prepend("lib");
539           aLibName += ".so";
540   #else
541           aLibName += ".dll";
542   #endif
543           theLibName = new TCollection_HAsciiString (aLibName);
544           return Standard_True;
545         }
546       }
547     }
548   }
549   
550   return Standard_False;
551 }
552
553 //=============================================================================
554 /*!
555  *  InitResMgr
556  */
557 //=============================================================================
558 Standard_Boolean GEOMImpl_IInsertOperations::InitResMgr()
559 {
560   bool isResourceFound = false;
561   TCollection_AsciiString aNull;
562   
563   myResMgrList.clear();
564
565   // Initialize the GEOM Resource Manager
566   TCollection_AsciiString aResDir = TCollection_AsciiString(getenv("GEOM_ROOT_DIR"));
567 #ifdef WIN32
568   aResDir += "\\share\\salome\\resources\\geom";
569 #else
570   aResDir += "/share/salome/resources/geom";
571 #endif
572   Handle(Resource_Manager) aGeomResMgr = new Resource_Manager ("ImportExport", aResDir, aNull, Standard_False);
573   if ( aGeomResMgr->Find("Import") || aGeomResMgr->Find("Export") ) {
574     myResMgrList.push_back( aGeomResMgr );
575     isResourceFound = true;
576   }
577
578   // Initialize the user's Resource Manager
579   TCollection_AsciiString aResDirsStr = getenv("GEOM_ENGINE_RESOURCES_DIR");
580   if ( !aResDirsStr.IsEmpty() )
581   {
582     std::string aSep = ":";
583 #ifdef WIN32
584     aSep = ";";
585 #endif
586     aResDir = aResDirsStr.Token(aSep.c_str(), 1);
587     for (int i = 1; !aResDir.IsEmpty(); aResDir = aResDirsStr.Token(aSep.c_str(), ++i)) {
588       Handle(Resource_Manager) anUserResMgr = new Resource_Manager ("ImportExport", aNull, aResDir, Standard_False);
589       if (anUserResMgr->Find("Import") || anUserResMgr->Find("Export")) {
590         myResMgrList.push_back( anUserResMgr );
591         isResourceFound = true;
592       }
593     }
594   }
595   else
596   {
597     aResDir = getenv("HOME");
598 #ifdef WIN32
599     aResDir += "\\.config\\salome";
600 #else
601     aResDir += "/.config/salome";
602 #endif
603     Handle(Resource_Manager) anUserResMgr = new Resource_Manager ("ImportExport", aNull, aResDir, Standard_False);
604     if (anUserResMgr->Find("Import") || anUserResMgr->Find("Export")) {
605       myResMgrList.push_back( anUserResMgr );
606       isResourceFound = true;
607     }
608   }
609   return isResourceFound;
610 }
611
612 //=============================================================================
613 /*!
614  *  RestoreShape
615  */
616 //=============================================================================
617 Handle(GEOM_Object) GEOMImpl_IInsertOperations::RestoreShape (std::istringstream& theStream)
618 {
619   SetErrorCode(KO);
620
621   //Add a new result object
622   Handle(GEOM_Object) result = GetEngine()->AddObject(GetDocID(), GEOM_COPY);
623
624   //Add a Copy function
625   Handle(GEOM_Function) aFunction = result->AddFunction(GEOMImpl_CopyDriver::GetID(), COPY_WITHOUT_REF);
626   if (aFunction.IsNull()) return NULL;
627
628   //Check if the function is set correctly
629   if (aFunction->GetDriverGUID() != GEOMImpl_CopyDriver::GetID()) return NULL;
630
631   //Read a shape from the stream
632   TopoDS_Shape aShape;
633   BRep_Builder B;
634   BRepTools::Read(aShape, theStream, B);
635   if (aShape.IsNull()) {
636     SetErrorCode("RestoreShape error: BREP reading failed");
637   }
638
639   //Set function value
640   aFunction->SetValue(aShape);
641
642   //Special dump to avoid restored shapes publication.
643   //See correcponding code in GEOM_Engine.cxx (method ProcessFunction)
644   //GEOM::TPythonDump(aFunction) << "#";
645
646   GEOM::TPythonDump(aFunction) << result
647     << " = geompy.RestoreShape(\"\") # the shape string has not been dump for performance reason";
648
649   SetErrorCode(OK);
650
651   return result;
652 }
653
654 int GEOMImpl_IInsertOperations::LoadTexture(const TCollection_AsciiString& theTextureFile)
655 {
656   SetErrorCode(KO);
657
658   if (theTextureFile.IsEmpty()) return 0;
659
660 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
661   Handle(TColStd_HArray1OfByte) aTexture;
662 #else
663   Handle(TDataStd_HArray1OfByte) aTexture;
664 #endif
665
666   FILE* fp = fopen(theTextureFile.ToCString(), "r");
667   if (!fp) return 0;
668
669   std::list<std::string> lines;
670   char buffer[4096];
671   int maxlen = 0;
672   while (!feof(fp)) {
673     if ((fgets(buffer, 4096, fp)) == NULL) break;
674     int aLen = strlen(buffer);
675     if (buffer[aLen-1] == '\n') buffer[aLen-1] = '\0';
676     lines.push_back(buffer);
677     maxlen = std::max(maxlen, (int)strlen(buffer));
678   }
679
680   fclose(fp);
681
682   int lenbytes = maxlen/8;
683   if (maxlen%8) lenbytes++;
684
685   if (lenbytes == 0 || lines.empty())
686     return 0;
687
688   std::list<unsigned char> bytedata;
689   std::list<std::string>::const_iterator it;
690   for (it = lines.begin(); it != lines.end(); ++it) {
691     std::string line = *it;
692     int lenline = (line.size()/8 + (line.size()%8 ? 1 : 0)) * 8;
693     for (int i = 0; i < lenline/8; i++) {
694       unsigned char byte = 0;
695       for (int j = 0; j < 8; j++)
696         byte = (byte << 1) + ( i*8+j < line.size() && line[i*8+j] != '0' ? 1 : 0 );
697       bytedata.push_back(byte);
698     }
699     for (int i = lenline/8; i < lenbytes; i++)
700       bytedata.push_back((unsigned char)0);
701   }
702
703   if (bytedata.empty() || bytedata.size() != lines.size()*lenbytes)
704     return 0;
705
706 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
707   aTexture = new TColStd_HArray1OfByte (1, lines.size()*lenbytes);
708 #else
709   aTexture = new TDataStd_HArray1OfByte (1, lines.size()*lenbytes);
710 #endif
711
712   std::list<unsigned char>::iterator bdit;
713   int i;
714   for (i = 1, bdit = bytedata.begin(); bdit != bytedata.end(); ++bdit, ++i)
715     aTexture->SetValue(i, (Standard_Byte)(*bdit));
716
717   int aTextureId = GetEngine()->addTexture(GetDocID(), lenbytes*8, lines.size(), aTexture, theTextureFile);
718   if (aTextureId > 0) SetErrorCode(OK);
719   return aTextureId;
720 }
721   
722 int GEOMImpl_IInsertOperations::AddTexture(int theWidth, int theHeight, 
723 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
724                                            const Handle(TColStd_HArray1OfByte)& theTexture)
725 #else
726                                            const Handle(TDataStd_HArray1OfByte)& theTexture)
727 #endif
728 {
729   SetErrorCode(KO);
730   int aTextureId = GetEngine()->addTexture(GetDocID(), theWidth, theHeight, theTexture);
731   if (aTextureId > 0) SetErrorCode(OK);
732   return aTextureId;
733 }
734
735 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
736 Handle(TColStd_HArray1OfByte) GEOMImpl_IInsertOperations::GetTexture(int theTextureId,
737 #else
738 Handle(TDataStd_HArray1OfByte) GEOMImpl_IInsertOperations::GetTexture(int theTextureId,
739 #endif
740                                                                       int& theWidth, int& theHeight)
741 {
742   SetErrorCode(KO);
743   
744 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
745   Handle(TColStd_HArray1OfByte) aTexture;
746 #else
747   Handle(TDataStd_HArray1OfByte) aTexture;
748 #endif
749
750   theWidth = theHeight = 0;
751   TCollection_AsciiString aFileName;
752
753   if (theTextureId <= 0)
754     return aTexture;
755
756   aTexture = GetEngine()->getTexture(GetDocID(), theTextureId, theWidth, theHeight, aFileName);
757
758   if (theWidth > 0 && theHeight > 0 && aTexture->Length() > 0) SetErrorCode(OK);
759
760   return aTexture;
761 }
762
763 std::list<int> GEOMImpl_IInsertOperations::GetAllTextures()
764 {
765   SetErrorCode(KO);
766   std::list<int> id_list = GetEngine()->getAllTextures(GetDocID());
767   SetErrorCode(OK);
768   return id_list;
769 }
770
771 TopAbs_ShapeEnum getGroupDimension(XAO::Group* group)
772 {
773   XAO::Dimension dim = group->getDimension();
774   TopAbs_ShapeEnum rdim;
775   switch ( dim )
776   {
777   case XAO::VERTEX:
778     rdim = TopAbs_VERTEX; break;
779   case XAO::EDGE:
780     rdim = TopAbs_EDGE; break;
781   case XAO::FACE:
782     rdim = TopAbs_FACE; break;
783   case XAO::SOLID:
784     rdim = TopAbs_SOLID; break;
785   default:
786     rdim = TopAbs_COMPOUND; break;
787   }
788   return rdim;
789 }
790
791 XAO::Dimension shapeEnumToDimension(const TopAbs_ShapeEnum& shape)
792 {
793   XAO::Dimension dim;
794   switch( shape ) {
795   case TopAbs_VERTEX:
796     dim = XAO::VERTEX; break;
797   case TopAbs_EDGE:
798     dim = XAO::EDGE; break;
799   case TopAbs_FACE:
800     dim = XAO::FACE; break;
801   case TopAbs_SOLID:
802     dim = XAO::SOLID; break;
803   default:
804     throw SALOME_Exception("Bad type"); // TODO
805   }
806   return dim;
807 }
808
809 void GEOMImpl_IInsertOperations::exportGroups(std::list<Handle(GEOM_Object)> groupList,
810                                               XAO::Xao* xaoObject,
811                                               XAO::BrepGeometry* geometry)
812 {
813   // add the groups
814   std::list<Handle(GEOM_Object)>::iterator groupIterator = groupList.begin();
815   while (groupIterator != groupList.end())
816   {
817     Handle(GEOM_Object) currGroup = (*groupIterator++);
818     Handle(TColStd_HArray1OfInteger) groupIds = myGroupOperations->GetObjects(currGroup);
819     
820     TopAbs_ShapeEnum shapeGroup = myGroupOperations->GetType(currGroup);
821     XAO::Dimension dim = shapeEnumToDimension(shapeGroup);
822     XAO::Group* group = xaoObject->addGroup(dim, currGroup->GetName().ToCString());
823     
824     switch (shapeGroup)
825     {
826     case TopAbs_VERTEX:
827       for (int i = 1; i <= groupIds->Length(); i++)
828       {
829         std::string ref = XAO::XaoUtils::intToString(groupIds->Value(i));
830         int index = geometry->getVertexIndexByReference(ref);
831         group->add(index);
832       }
833       break;
834     case TopAbs_EDGE:
835       for (int i = 1; i <= groupIds->Length(); i++)
836       {
837         std::string ref = XAO::XaoUtils::intToString(groupIds->Value(i));
838         int index = geometry->getEdgeIndexByReference(ref);
839         group->add(index);
840       }
841       break;
842     case TopAbs_FACE:
843       for (int i = 1; i <= groupIds->Length(); i++)
844       {
845         std::string ref = XAO::XaoUtils::intToString(groupIds->Value(i));
846         int index = geometry->getFaceIndexByReference(ref);
847         group->add(index);
848       }
849       break;
850     case TopAbs_SOLID:
851       for (int i = 1; i <= groupIds->Length(); i++)
852       {
853         std::string ref = XAO::XaoUtils::intToString(groupIds->Value(i));
854         int index = geometry->getSolidIndexByReference(ref);
855         group->add(index);
856       }
857       break;
858     }
859   }
860 }
861
862 void GEOMImpl_IInsertOperations::exportFields(std::list<Handle(GEOM_Field)> fieldList,
863                                               XAO::Xao* xaoObject,
864                                               XAO::BrepGeometry* geometry)
865 {
866     std::list<Handle(GEOM_Field)>::iterator fieldIterator = fieldList.begin();
867     while (fieldIterator != fieldList.end())
868     {
869         Handle(GEOM_Field) currField = (*fieldIterator++);
870
871         int fdim = currField->GetDimension();
872         int ftype = currField->GetDataType();
873         int nbComponents = currField->GetNbComponents();
874         std::string name = currField->GetName().ToCString();
875
876         XAO::Field* field = xaoObject->addField((XAO::Type)ftype, (XAO::Dimension)fdim, nbComponents, name);
877
878         Handle(TColStd_HArray1OfExtendedString) components = currField->GetComponents();
879         for (int i = components->Lower(), j = 0; i <= components->Upper(); ++i, ++j)
880         {
881             field->setComponentName(j, TCollection_AsciiString(components->Value(i)).ToCString());
882         }
883
884         std::list< Handle(GEOM_FieldStep)> steps = currField->GetSteps();
885         std::list<Handle(GEOM_FieldStep)>::iterator stepIterator = steps.begin();
886         while (stepIterator != steps.end())
887         {
888             Handle(GEOM_FieldStep) currStep = (*stepIterator++);
889
890             XAO::Step* step = field->addNewStep(currStep->GetID());
891             step->setStamp(currStep->GetStamp());
892
893             switch (ftype)
894             {
895                 case 0: // bool
896                 {
897                     XAO::BooleanStep* bs = (XAO::BooleanStep*)step;
898                     Handle(TColStd_HArray1OfInteger) bvalues = currStep->GetIntValues();
899                     std::vector<bool> bv;
900                     bv.reserve(bvalues->Upper());
901                     for ( int i = bvalues->Lower(), nb = bvalues->Upper(); i <= nb; ++i )
902                     {
903                         bv.push_back(bvalues->Value(i) != 0);
904                     }
905                     bs->setValues(bv);
906                     break;
907                 }
908                 case 1: // integer
909                 {
910                     XAO::IntegerStep* is = (XAO::IntegerStep*)step;
911                     Handle(TColStd_HArray1OfInteger) ivalues = currStep->GetIntValues();
912                     std::vector<int> iv;
913                     iv.reserve(ivalues->Upper());
914                     for ( int i = ivalues->Lower(), nb = ivalues->Upper(); i <= nb; ++i )
915                     {
916                         iv.push_back(ivalues->Value(i));
917                     }
918                     is->setValues(iv);
919                     break;
920                 }
921                 case 2: // double
922                 {
923                     XAO::DoubleStep* ds = (XAO::DoubleStep*)step;
924                     Handle(TColStd_HArray1OfReal) dvalues = currStep->GetDoubleValues();
925                     std::vector<double> dv;
926                     dv.reserve(dvalues->Upper());
927                     for ( int i = dvalues->Lower(), nb = dvalues->Upper(); i <= nb; ++i )
928                     {
929                         dv.push_back(dvalues->Value(i));
930                     }
931                     ds->setValues(dv);
932                     break;
933                 }
934                 case 3: // string
935                 {
936                     XAO::StringStep* ss = (XAO::StringStep*)step;
937                     Handle(TColStd_HArray1OfExtendedString) svalues = currStep->GetStringValues();
938                     std::vector<std::string> sv;
939                     sv.reserve(svalues->Upper());
940                     for ( int i = svalues->Lower(), nb = svalues->Upper(); i <= nb; ++i )
941                     {
942                         sv.push_back(TCollection_AsciiString(svalues->Value(i)).ToCString());
943                     }
944                     ss->setValues(sv);
945                     break;
946                 }
947             }
948         }
949     }
950 }
951
952 void GEOMImpl_IInsertOperations::exportSubshapes(const Handle(GEOM_Object)& shape, XAO::BrepGeometry* geometry)
953 {
954   Handle(TColStd_HSequenceOfTransient) subObjects = myShapesOperations->GetExistingSubObjects(shape, false);
955   int nbSubObjects = subObjects->Length();
956   // set the names of the sub shapes
957   for (int i = 1; i <= nbSubObjects; i++)
958   {
959     Handle(Standard_Transient) transientSubObject = subObjects->Value(i);
960     if (transientSubObject.IsNull())
961       continue;
962     
963     Handle(GEOM_Object) subObject = Handle(GEOM_Object)::DownCast(transientSubObject);
964     if (subObject->GetType() != GEOM_GROUP)
965     {
966       int subIndex = myShapesOperations->GetSubShapeIndex(shape, subObject);
967       switch (subObject->GetValue().ShapeType())
968       {
969       case TopAbs_VERTEX:
970         geometry->changeVertexName(subIndex, subObject->GetName().ToCString());
971         break;
972       case TopAbs_EDGE:
973         geometry->changeEdgeName(subIndex, subObject->GetName().ToCString());
974         break;
975       case TopAbs_FACE:
976         geometry->changeFaceName(subIndex, subObject->GetName().ToCString());
977         break;
978       case TopAbs_SOLID:
979         geometry->changeSolidName(subIndex, subObject->GetName().ToCString());
980         break;
981       }
982     }
983   }
984 }
985
986 //=============================================================================
987 /*!
988  *  Export a shape to XAO format
989  *  \param shape The shape to export
990  *  \param groups The list of groups to export
991  *  \param fields The list of fields to export
992  *  \param fileName The name of the file to exported
993  *  \return boolean indicating if export was succeful.
994  */
995 //=============================================================================
996 bool GEOMImpl_IInsertOperations::ExportXAO(Handle(GEOM_Object) shape,
997                                            std::list<Handle(GEOM_Object)> groupList,
998                                            std::list<Handle(GEOM_Field)> fieldList,
999                                            const char* author,
1000                                            const char* fileName)
1001 {
1002   SetErrorCode(KO);
1003
1004   if (shape.IsNull()) return false;
1005   
1006   // add a new shape function with parameters
1007   Handle(GEOM_Function) lastFunction = shape->GetLastFunction();
1008   if (lastFunction.IsNull()) return false;
1009   
1010   // add a new result object
1011   Handle(GEOM_Object) result = GetEngine()->AddObject(GetDocID(), GEOM_IMPORT);
1012   
1013   // add an Export function
1014   Handle(GEOM_Function) exportFunction = result->AddFunction(GEOMImpl_XAODriver::GetID(), IMPORTEXPORT_EXPORTXAO);
1015   if (exportFunction.IsNull()) return false;
1016   if (exportFunction->GetDriverGUID() != GEOMImpl_XAODriver::GetID()) return false;
1017   
1018   // create the XAO object
1019   XAO::Xao* xaoObject = new XAO::Xao();
1020   xaoObject->setAuthor(author);
1021   
1022   // add the geometry
1023   XAO::BrepGeometry* geometry = (XAO::BrepGeometry*)XAO::Geometry::createGeometry(XAO::BREP);
1024   TopoDS_Shape topoShape = shape->GetValue();
1025   exportFunction->SetValue(topoShape);
1026   XAO::BrepGeometry* brep = (XAO::BrepGeometry*)geometry;
1027   brep->setTopoDS_Shape(topoShape);
1028   
1029   geometry->setName(shape->GetName().ToCString());
1030   exportSubshapes(shape, geometry);
1031   xaoObject->setGeometry(geometry);
1032   
1033   exportGroups(groupList, xaoObject, geometry);
1034   exportFields(fieldList, xaoObject, geometry);
1035   
1036   // export the XAO to the file
1037   xaoObject->exportXAO(fileName);
1038   
1039   // make a Python command
1040   GEOM::TPythonDump pd(exportFunction);
1041   pd << "exported = geompy.ExportXAO(" << shape;
1042   
1043   // list of groups
1044   pd << ", [";
1045   if (groupList.size() > 0)
1046   {
1047     std::list<Handle(GEOM_Object)>::iterator itGroup = groupList.begin();
1048     pd << (*itGroup++);
1049     while (itGroup != groupList.end())
1050     {
1051       pd << ", " << (*itGroup++);
1052     }
1053   }
1054
1055   // list of fields
1056   pd << "], [";
1057   if (fieldList.size() > 0)
1058   {
1059     std::list<Handle(GEOM_Field)>::iterator itField = fieldList.begin();
1060     pd << (*itField++);
1061     while (itField != fieldList.end())
1062     {
1063       pd << ", " << (*itField++);
1064     }
1065   }
1066   pd << "], ";
1067   pd << "\"" << author << "\", \"" << fileName << "\")";
1068   
1069   SetErrorCode(OK);
1070   delete xaoObject;
1071   
1072   return true;
1073 }
1074
1075 void GEOMImpl_IInsertOperations::importSubShapes(XAO::Geometry* xaoGeometry,
1076                                                  Handle(GEOM_Function) function, int shapeType, int dim,
1077                                                  Handle(TColStd_HSequenceOfTransient)& subShapeList)
1078 {
1079   Handle(GEOM_Object) subShape;
1080   Handle(GEOM_Function) aFunction;
1081   Handle(TColStd_HArray1OfInteger) anArray;
1082   
1083   XAO::GeometricElementList::iterator elementIterator = xaoGeometry->begin((XAO::Dimension)dim);
1084   for (; elementIterator != xaoGeometry->end((XAO::Dimension)dim); elementIterator++)
1085   {
1086     XAO::GeometricElement element = elementIterator->second;
1087     if (!element.hasName())
1088       continue;
1089     
1090     std::string name = element.getName();
1091     std::string ref = element.getReference();
1092     int iref = XAO::XaoUtils::stringToInt(ref);
1093     
1094     anArray = new TColStd_HArray1OfInteger(1, 1);
1095     anArray->SetValue(1, iref);
1096     
1097     subShape = GetEngine()->AddObject(GetDocID(), GEOM_SUBSHAPE);
1098     Handle(GEOM_Function) aFunction = subShape->AddFunction(GEOM_Object::GetSubShapeID(), 1);
1099     if (aFunction.IsNull())
1100       return;
1101     
1102     subShape->SetName(name.c_str());
1103     subShape->SetType(shapeType);
1104     
1105     GEOM_ISubShape aSSI(aFunction);
1106     aSSI.SetMainShape(function);
1107     aSSI.SetIndices(anArray);
1108     
1109     //aFunction->SetValue(aValue);
1110     subShapeList->Append(subShape);
1111     
1112     // Put this subshape in the list of sub-shapes of theMainShape
1113     function->AddSubShapeReference(aFunction);
1114   }
1115 }
1116
1117 //=============================================================================
1118 /*!
1119  *  Import a shape from XAO format
1120  *  \param fileName The name of the file to import
1121  *  \param shape The imported shape
1122  *  \param subShapes The list of imported groups
1123  *  \param groups The list of imported groups
1124  *  \param fields The list of imported fields
1125  *  \return boolean indicating if import was succeful.
1126  */
1127 //=============================================================================
1128 bool GEOMImpl_IInsertOperations::ImportXAO(const char* fileName,
1129                                            Handle(GEOM_Object)& shape,
1130                                            Handle(TColStd_HSequenceOfTransient)& subShapes,
1131                                            Handle(TColStd_HSequenceOfTransient)& groups,
1132                                            Handle(TColStd_HSequenceOfTransient)& fields)
1133 {
1134   SetErrorCode(KO);
1135   
1136   if (fileName == NULL || groups.IsNull() || fields.IsNull())
1137     return false;
1138   
1139   // Read the XAO
1140   XAO::Xao* xaoObject = new XAO::Xao();
1141   try
1142   {
1143     xaoObject->importXAO(fileName);
1144   }
1145   catch (XAO::XAO_Exception& exc)
1146   {
1147     delete xaoObject;
1148     SetErrorCode(exc.what());
1149     return false;
1150   }
1151   
1152   XAO::Geometry* xaoGeometry = xaoObject->getGeometry();
1153   if (xaoGeometry == NULL)
1154   {
1155     delete xaoObject;
1156     SetErrorCode("Cannot import XAO: geometry format not supported.");
1157     return false;
1158   }
1159   
1160   // create the shape
1161   shape = GetEngine()->AddObject(GetDocID(), GEOM_IMPORT);
1162   Handle(GEOM_Function) function = shape->AddFunction(GEOMImpl_XAODriver::GetID(), IMPORTEXPORT_EXPORTXAO);
1163   if (function.IsNull()) return false;
1164   if (function->GetDriverGUID() != GEOMImpl_XAODriver::GetID()) return false;
1165   
1166   // set the geometry
1167   if (xaoGeometry->getFormat() == XAO::BREP)
1168   {
1169     XAO::BrepGeometry* brep = (XAO::BrepGeometry*)xaoGeometry;
1170     TopoDS_Shape geomShape = brep->getTopoDS_Shape();
1171     function->SetValue(geomShape);
1172     shape->SetName(xaoGeometry->getName().c_str());
1173   }
1174   else
1175   {
1176     delete xaoObject;
1177     SetErrorCode("Cannot import XAO: geometry format not supported.");
1178     return false;
1179   }
1180   
1181   // create sub shapes with names
1182   importSubShapes(xaoGeometry, function, GEOM_POINT, XAO::VERTEX, subShapes);
1183   importSubShapes(xaoGeometry, function, GEOM_EDGE, XAO::EDGE, subShapes);
1184   importSubShapes(xaoGeometry, function, GEOM_FACE, XAO::FACE, subShapes);
1185   importSubShapes(xaoGeometry, function, GEOM_SOLID, XAO::SOLID, subShapes);
1186   
1187   // create groups
1188   int nbGroups = xaoObject->countGroups();
1189   for (int i = 0; i < nbGroups; ++i)
1190   {
1191     XAO::Group* xaoGroup = xaoObject->getGroup(i);
1192     
1193     // build an array with the indexes of the sub shapes
1194     int nbElt = xaoGroup->count();
1195     Handle(TColStd_HArray1OfInteger) array = new TColStd_HArray1OfInteger(1, nbElt);
1196     int j = 0;
1197     for (std::set<int>::iterator it = xaoGroup->begin(); it != xaoGroup->end(); ++it)
1198     {
1199       int index = (*it);
1200       std::string ref = xaoGeometry->getElementReference(xaoGroup->getDimension(), index);
1201       array->SetValue(++j, XAO::XaoUtils::stringToInt(ref));
1202     }
1203     
1204     // create the group with the array of sub shapes indexes
1205     Handle(GEOM_Object) group = GetEngine()->AddSubShape(shape, array);
1206     group->SetType(GEOM_GROUP);
1207     group->SetName(xaoGroup->getName().c_str());
1208     
1209     // Set a sub-shape type
1210     TDF_Label freeLabel = group->GetFreeLabel();
1211     TDataStd_Integer::Set(freeLabel, (Standard_Integer) getGroupDimension(xaoGroup));
1212     groups->Append(group);
1213     
1214     function = group->GetLastFunction();
1215   }
1216   
1217   // create the fields
1218   int nbFields = xaoObject->countFields();
1219   for (int i = 0; i < nbFields; ++i)
1220   {
1221     XAO::Field* xaoField = xaoObject->getField(i);
1222
1223     Handle(TColStd_HArray1OfExtendedString) components = new TColStd_HArray1OfExtendedString(0, xaoField->countComponents()-1);
1224     for (int j = 0; j < xaoField->countComponents(); ++j)
1225     {
1226         components->SetValue(j, (TCollection_ExtendedString)xaoField->getComponentName(j).c_str());
1227     }
1228
1229     Handle(GEOM_Field) field = myFieldOperations->CreateField(shape,
1230                  xaoField->getName().c_str(),
1231                  (int)xaoField->getType(),
1232                  (int)xaoField->getDimension(),
1233                  components);
1234
1235     switch (xaoField->getType())
1236     {
1237         case XAO::BOOLEAN:
1238         {
1239             XAO::BooleanField* bfield = (XAO::BooleanField*)xaoField;
1240             for (int j = 0; j < xaoField->countSteps(); ++j)
1241             {
1242                 XAO::BooleanStep* bstep = bfield->getStep(j);
1243                 Handle(GEOM_FieldStep) step = field->AddStep(bstep->getStep(), bstep->getStamp());
1244
1245                 Handle(TColStd_HArray1OfInteger) values = new TColStd_HArray1OfInteger(0, bstep->countValues()-1);
1246                 std::vector<bool> bvalues = bstep->getValues();
1247                 for (int k = 0; k < bstep->countValues(); ++k)
1248                 {
1249                     values->SetValue(k, bvalues[k] ? 1 : 0);
1250                 }
1251                 step->SetValues(values);
1252             }
1253             break;
1254         }
1255         case XAO::INTEGER:
1256         {
1257             XAO::IntegerField* ifield = (XAO::IntegerField*)xaoField;
1258             for (int j = 0; j < xaoField->countSteps(); ++j)
1259             {
1260                 XAO::IntegerStep* istep = ifield->getStep(j);
1261                 Handle(GEOM_FieldStep) step = field->AddStep(istep->getStep(), istep->getStamp());
1262
1263                 Handle(TColStd_HArray1OfInteger) values = new TColStd_HArray1OfInteger(0, istep->countValues()-1);
1264                 std::vector<int> ivalues = istep->getValues();
1265                 for (int k = 0; k < istep->countValues(); ++k)
1266                 {
1267                     values->SetValue(k, ivalues[k]);
1268                 }
1269                 step->SetValues(values);
1270             }
1271             break;
1272         }
1273         case XAO::DOUBLE:
1274         {
1275             XAO::DoubleField* dfield = (XAO::DoubleField*)xaoField;
1276             for (int j = 0; j < xaoField->countSteps(); ++j)
1277             {
1278                 XAO::DoubleStep* dstep = dfield->getStep(j);
1279                 Handle(GEOM_FieldStep) step = field->AddStep(dstep->getStep(), dstep->getStamp());
1280
1281                 Handle(TColStd_HArray1OfReal) values = new TColStd_HArray1OfReal(0, dstep->countValues()-1);
1282                 std::vector<double> dvalues = dstep->getValues();
1283                 for (int k = 0; k < dstep->countValues(); ++k)
1284                 {
1285                     values->SetValue(k, dvalues[k]);
1286                 }
1287                 step->SetValues(values);
1288             }
1289             break;
1290         }
1291         case XAO::STRING:
1292         {
1293             XAO::StringField* sfield = (XAO::StringField*)xaoField;
1294             for (int j = 0; j < xaoField->countSteps(); ++j)
1295             {
1296                 XAO::StringStep* sstep = sfield->getStep(j);
1297                 Handle(GEOM_FieldStep) step = field->AddStep(sstep->getStep(), sstep->getStamp());
1298
1299                 Handle(TColStd_HArray1OfExtendedString) values = new TColStd_HArray1OfExtendedString(0, sstep->countValues()-1);
1300                 std::vector<std::string> svalues = sstep->getValues();
1301                 for (int k = 0; k < sstep->countValues(); ++k)
1302                 {
1303                     values->SetValue(k, TCollection_ExtendedString(svalues[k].c_str()));
1304                 }
1305                 step->SetValues(values);
1306             }
1307             break;
1308         }
1309     }
1310
1311     fields->Append(field);
1312   }
1313   
1314   // make a Python command
1315   GEOM::TPythonDump pd(function);
1316   pd << "(imported, " << shape << ", ";
1317   
1318   // list of sub shapes
1319   pd << "[";
1320   int nbSubshapes = subShapes->Length();
1321   if (nbSubshapes > 0)
1322   {
1323     for (int i = 1; i <= nbSubshapes; i++)
1324     {
1325       Handle(GEOM_Object) obj = Handle(GEOM_Object)::DownCast(subShapes->Value(i));
1326       pd << obj << ((i < nbSubshapes) ? ", " : "");
1327     }
1328   }
1329   pd << "], [";
1330   
1331   // list of groups
1332   if (nbGroups > 0)
1333   {
1334     for (int i = 1; i <= nbGroups; i++)
1335     {
1336       Handle(GEOM_Object) obj = Handle(GEOM_Object)::DownCast(groups->Value(i));
1337       pd << obj << ((i < nbGroups) ? ", " : "");
1338     }
1339   }
1340   
1341   pd << "], [";
1342   
1343   // list of fields
1344   if (nbFields > 0)
1345   {
1346     for (int i = 1; i <= nbFields; i++)
1347     {
1348       Handle(GEOM_Field) obj = Handle(GEOM_Field)::DownCast(fields->Value(i));
1349       pd << obj << ((i < nbFields) ? ", " : "");
1350     }
1351   }
1352   pd << "]";
1353   pd << ") = geompy.ImportXAO(\"" << fileName << "\")";
1354   
1355   delete xaoObject;
1356   SetErrorCode(OK);
1357   
1358   return true;
1359 }
1360
1361 //=============================================================================
1362 /*!
1363  *  This method creates material groups for an imported object.
1364  *  \param theObject the imported object.
1365  */
1366 //=============================================================================
1367 void GEOMImpl_IInsertOperations::MakeMaterialGroups
1368                         (const Handle(GEOM_Object) &theObject,
1369                          const Handle(TColStd_HSequenceOfTransient) &theSeq)
1370 {
1371   TopoDS_Shape aResShape = theObject->GetValue();
1372
1373   if (aResShape.IsNull() == Standard_False) {
1374     // Group shapes by material names.
1375     Handle(GEOM_Function)      aFunction = theObject->GetLastFunction();
1376     DataMapOfStringListOfShape aMapMaterialShapes;
1377
1378     // check all named shapes using iterator
1379     TDF_ChildIDIterator anIt (aFunction->GetNamingEntry(),
1380         TNaming_NamedShape::GetID(), Standard_True);
1381
1382     for (; anIt.More(); anIt.Next()) {
1383       Handle(TNaming_NamedShape) anAttr =
1384           Handle(TNaming_NamedShape)::DownCast(anIt.Value());
1385
1386       if (anAttr.IsNull() == Standard_False) {
1387         TDF_Label                aLabel = anAttr->Label();
1388         Handle(TDataStd_Comment) aComment;
1389
1390         if (aLabel.FindAttribute(TDataStd_Comment::GetID(), aComment)) {
1391           TCollection_ExtendedString aMatName = aComment->Get();
1392           TopoDS_Shape               aShape   = anAttr->Get();
1393
1394           if (aMapMaterialShapes.IsBound(aMatName) == Standard_False) {
1395             NCollection_List<TopoDS_Shape> anEmptyList;
1396
1397             aMapMaterialShapes.Bind(aMatName, anEmptyList);
1398           }
1399
1400           aMapMaterialShapes(aMatName).Append(aShape);
1401         }
1402       }
1403     }
1404
1405     if (aMapMaterialShapes.IsEmpty() == Standard_False) {
1406       // Construct groups.
1407       TopAbs_ShapeEnum aType = aResShape.ShapeType();
1408       Standard_Integer i;
1409       DataMapOfStringListOfShape::Iterator aMapIter;
1410
1411       // Check each shape type.
1412       for(i = aType; i <= TopAbs_VERTEX; i++) {
1413         DataMapOfStringListOfShape::Iterator aMapIter(aMapMaterialShapes);
1414
1415         for (; aMapIter.More(); aMapIter.Next()) {
1416           NCollection_List<TopoDS_Shape> &aShList = aMapIter.ChangeValue();
1417           NCollection_List<TopoDS_Shape>::Iterator aShIter(aShList);
1418           NCollection_List<TopoDS_Shape>  aShListSameType;
1419
1420           while (aShIter.More()) {
1421             const TopoDS_Shape &aShape = aShIter.Value();
1422
1423             if (i == aShape.ShapeType()) {
1424               // Treat this element.
1425               aShListSameType.Append(aShape);
1426               aShList.Remove(aShIter);
1427             } else {
1428               // Go to the next element.
1429               aShIter.Next();
1430             }
1431           }
1432
1433           if (aShListSameType.IsEmpty() == Standard_False) {
1434             // Construct a group.
1435             Handle(GEOM_Object) aGroup =
1436               MakeGroup(theObject, aMapIter.Key(), aShListSameType);
1437
1438             if (aGroup.IsNull() == Standard_False) {
1439               theSeq->Append(aGroup);
1440             }
1441           }
1442         }
1443       }
1444     }
1445   }
1446 }
1447
1448
1449 //=============================================================================
1450 /*!
1451  *  This method creates a group of shapes of certain type.
1452  *  \param theObject the imported object.
1453  *  \param theName the material name.
1454  *  \param theShapes the list of shapes to be added to this group.
1455  *  \return the created group.
1456  */
1457 //=============================================================================
1458 Handle(GEOM_Object) GEOMImpl_IInsertOperations::MakeGroup
1459                   (const Handle(GEOM_Object)            &theObject,
1460                    const TCollection_ExtendedString     &theName,
1461                    const NCollection_List<TopoDS_Shape> &theShapes)
1462 {
1463   Handle(GEOM_Object)                aGroup;
1464   TopTools_IndexedMapOfShape         anIndices;
1465   Handle(TColStd_HSequenceOfInteger) aSeqIDs = new TColStd_HSequenceOfInteger;
1466   NCollection_List<TopoDS_Shape>::Iterator anIter(theShapes);
1467
1468   TopExp::MapShapes(theObject->GetValue(), anIndices);
1469
1470   // Compose shape IDs.
1471   for (; anIter.More(); anIter.Next()) {
1472     const TopoDS_Shape &aShape = anIter.Value();
1473     const Standard_Integer anIndex = anIndices.FindIndex(aShape);
1474
1475     if (anIndex > 0) {
1476       aSeqIDs->Append(anIndex);
1477     }
1478   }
1479
1480   if (aSeqIDs->IsEmpty() == Standard_False) {
1481     // Create a group.
1482     const TopAbs_ShapeEnum aType  = theShapes.First().ShapeType();
1483
1484     aGroup = myGroupOperations->CreateGroup(theObject, aType);
1485
1486     if (aGroup.IsNull() == Standard_False) {
1487       aGroup->GetLastFunction()->SetDescription("");
1488       myGroupOperations->UnionIDs(aGroup, aSeqIDs);
1489       aGroup->GetLastFunction()->SetDescription("");
1490
1491       // Compose the group name.
1492       TCollection_AsciiString aGroupName(theName);
1493
1494       switch(aType) {
1495         case TopAbs_VERTEX:
1496           aGroupName += "_VERTEX";
1497           break;
1498         case TopAbs_EDGE:
1499           aGroupName += "_EDGE";
1500           break;
1501         case TopAbs_WIRE:
1502           aGroupName += "_WIRE";
1503           break;
1504         case TopAbs_FACE:
1505           aGroupName += "_FACE";
1506           break;
1507         case TopAbs_SHELL:
1508           aGroupName += "_SHELL";
1509           break;
1510         case TopAbs_SOLID:
1511           aGroupName += "_SOLID";
1512           break;
1513         case TopAbs_COMPSOLID:
1514           aGroupName += "_COMPSOLID";
1515           break;
1516         case TopAbs_COMPOUND:
1517           aGroupName += "_COMPOUND";
1518           break;
1519         default:
1520           aGroupName += "_SHAPE";
1521           break;
1522       }
1523
1524       aGroup->SetName(aGroupName.ToCString());
1525     }
1526   }
1527
1528   return aGroup;
1529 }