]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM_I/GEOM_Gen_i.cc
Salome HOME
#18963 Minimize compiler warnings
[modules/geom.git] / src / GEOM_I / GEOM_Gen_i.cc
1 // Copyright (C) 2007-2020  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 #ifdef WIN32
24 #pragma warning( disable:4786 )
25 #endif
26
27 #include <Standard_Stream.hxx>
28
29 #include "GEOM_Gen_i.hh"
30 #include "GEOM_Object_i.hh"
31 #include "GEOM_Field_i.hh"
32 #include "GEOM_version.h"
33
34 #include "Utils_CorbaException.hxx"
35 #include "OpUtil.hxx"
36 #include "Utils_ExceptHandlers.hxx"
37 #include "utilities.h"
38
39 #include "GEOM_Object.hxx"
40 #include "GEOM_Function.hxx"
41 #include "GEOM_ISubShape.hxx"
42 #include "GEOM_PythonDump.hxx"
43 #include "GEOMImpl_Types.hxx"
44 #include "GEOMImpl_CopyDriver.hxx"
45 #include "GEOMImpl_IInsertOperations.hxx"
46 #include "GEOM_wrap.hxx"
47 #include "GEOMUtils_XmlHandler.hxx"
48
49 // Cascade headers
50 #include <BRep_Builder.hxx>
51 #include <BRepTools.hxx>
52 #include <TDF_Label.hxx>
53 #include <TDF_Tool.hxx>
54 #include <TDF_ChildIDIterator.hxx>
55 #include <TNaming_NamedShape.hxx>
56 #include <TDataStd_Name.hxx>
57 #include <TCollection_AsciiString.hxx>
58 #include <TColStd_HArray1OfInteger.hxx>
59 #include <TopAbs_ShapeEnum.hxx>
60 #include <TopExp.hxx>
61 #include <OSD.hxx>
62 #include <TDataStd_ChildNodeIterator.hxx>
63 #include <TDocStd_Owner.hxx>
64 #include <TDataStd_ListIteratorOfListOfExtendedString.hxx>
65
66 #include <SALOMEDS_Tool.hxx>
67 #include <SALOMEDS_wrap.hxx>
68 #include <Basics_DirUtils.hxx>
69 #include <Basics_Utils.hxx>
70
71 #include <set>
72 #include <sstream>
73
74 #ifdef WIN32
75  #include <windows.h>
76  #include <process.h>
77 #else
78  #include <dlfcn.h>
79 #endif
80
81 #ifdef WIN32
82  #define LibHandle HMODULE
83  #define LoadLib( name ) LoadLibrary( name )
84  #define GetProc GetProcAddress
85  #define UnLoadLib( handle ) FreeLibrary( handle );
86 #else
87  #define LibHandle void*
88  #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
89  #define GetProc dlsym
90  #define UnLoadLib( handle ) dlclose( handle );
91 #endif
92
93 //============================================================================
94 // function : GEOM_Gen_i()
95 // purpose  : constructor to be called for servant creation.
96 //============================================================================
97 GEOM_Gen_i::GEOM_Gen_i(CORBA::ORB_ptr            orb,
98                        PortableServer::POA_ptr   poa,
99                        PortableServer::ObjectId* contId,
100                        const char*               instanceName,
101                        const char*               interfaceName) :
102   Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
103 {
104   _thisObj = this;
105   _id = _poa->activate_object(_thisObj);
106   name_service = new SALOME_NamingService(_orb);
107
108   _impl = new ::GEOMImpl_Gen;
109
110   //PAL10867: disable signals catching with "noexcepthandler" option
111   char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
112   if (!envNoCatchSignals || !atoi(envNoCatchSignals))
113   {
114     //work around PAL12004, PAL12628
115     //OSD::SetSignal( true );
116     bool raiseFPE = false;
117 #if defined(_DEBUG_) | defined(_DEBUG) //the Last for WIN32 default settings
118     char* envEnableFPE = getenv("ENABLE_FPE");
119     if (envEnableFPE && atoi(envEnableFPE))
120       raiseFPE = true;
121 #endif
122     OSD::SetSignal( raiseFPE );
123   }
124
125   GEOMUtils::PluginInfo plugins = GEOMUtils::ReadPluginInfo();
126   GEOMUtils::PluginInfo::const_iterator it;
127   for (it = plugins.begin(); it != plugins.end(); ++it)
128   {
129     try {
130       LoadPlugin((*it).serverLib);
131     }
132     catch (...)  {
133       MESSAGE("Warning: can't load plugin library " << (*it).serverLib);
134     }
135   }
136 }
137
138 //============================================================================
139 // function : ~GEOM_Gen_i()
140 // purpose  : destructor
141 //============================================================================
142 GEOM_Gen_i::~GEOM_Gen_i() {
143   delete name_service;
144   delete _impl;
145   std::map<std::string, GEOM_GenericOperationsCreator*>::const_iterator it;
146   for ( it = myOpCreatorMap.begin(); it != myOpCreatorMap.end(); ++it)
147     delete (*it).second;
148 }
149
150
151 //============================================================================
152 // function : IORToLocalPersistentID()
153 // purpose  :
154 //============================================================================
155 char* GEOM_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr /*theSObject*/,
156                                          const char* IORString,
157                                          CORBA::Boolean /*isMultiFile*/,
158                                          CORBA::Boolean /*isASCII*/)
159 {
160   GEOM::GEOM_BaseObject_var anObject =
161     GEOM::GEOM_BaseObject::_narrow(_orb->string_to_object(IORString));
162   if (!CORBA::is_nil(anObject)) {
163     return anObject->GetEntry();
164   }
165   return 0;
166 }
167
168
169 //============================================================================
170 // function : LocalPersistentIDToIOR()
171 // purpose  : Create/Load CORBA object from a persistent ref (an entry)
172 //          : Used when a study is loaded
173 //          : The IOR (IORName) of object created is returned
174 //============================================================================
175 char* GEOM_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr /*theSObject*/,
176                                          const char* aLocalPersistentID,
177                                          CORBA::Boolean /*isMultiFile*/,
178                                          CORBA::Boolean /*isASCII*/)
179 {
180   Handle(::GEOM_BaseObject) anObject =
181     _impl->GetObject(aLocalPersistentID);
182   if ( !anObject.IsNull() )
183   {
184     TCollection_AsciiString anEntry;
185     TDF_Tool::Entry(anObject->GetEntry(), anEntry);
186     GEOM::GEOM_BaseObject_var obj = GetObject(anEntry.ToCString());
187
188     CORBA::String_var aPersRefString = _orb->object_to_string(obj);
189     return CORBA::string_dup(aPersRefString);
190   }
191   else
192   {
193     return CORBA::string_dup("");
194   }
195 }
196
197 //============================================================================
198 // function : CanPublishInStudy
199 // purpose  :
200 //============================================================================
201 bool GEOM_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
202 {
203   GEOM::GEOM_Object_var anObject = GEOM::GEOM_Object::_narrow(theIOR);
204   return !(anObject->_is_nil());
205 }
206
207
208 //============================================================================
209 // function : PublishInStudy
210 // purpose  :
211 //============================================================================
212 SALOMEDS::SObject_ptr GEOM_Gen_i::PublishInStudy(SALOMEDS::SObject_ptr theSObject,
213                                                  CORBA::Object_ptr     theObject,
214                                                  const char*           theName)
215   
216 {
217   Unexpect aCatch(SALOME_SalomeException);
218   SALOMEDS::SObject_var aResultSO;
219   SALOMEDS::Study_var aStudy = getStudyServant();
220   if(CORBA::is_nil(theObject) || aStudy->_is_nil()) return aResultSO;
221   GEOM::GEOM_BaseObject_var aBaseObj = GEOM::GEOM_BaseObject::_narrow(theObject);
222   GEOM::GEOM_Object_var       aShape = GEOM::GEOM_Object::_narrow(theObject);
223   if(aBaseObj->_is_nil()) return aResultSO;
224
225   SALOMEDS::GenericAttribute_var anAttr;
226   SALOMEDS::StudyBuilder_var     aStudyBuilder = aStudy->NewBuilder();
227   SALOMEDS::UseCaseBuilder_wrap  useCaseBuilder = aStudy->GetUseCaseBuilder();
228
229   SALOMEDS::SComponent_var aFather = findOrCreateComponent();
230   if (aFather->_is_nil()) return aResultSO;
231
232   if (CORBA::is_nil(theSObject)) {
233     aResultSO = aStudyBuilder->NewObject(aFather);
234   } else {
235     if (!theSObject->ReferencedObject(aResultSO))
236       aResultSO = SALOMEDS::SObject::_duplicate(theSObject); //SRN: Added Aug 24,2004 : for  the method AddInStudy with theFather argumenet != NULL
237     //THROW_SALOME_CORBA_EXCEPTION("Publish in study supervision graph error",SALOME::BAD_PARAM);
238   }
239   CORBA::String_var aGeomObjIOR = _orb->object_to_string(theObject);
240   aResultSO->SetAttrString("AttributeIOR",aGeomObjIOR);
241
242   TCollection_AsciiString anObjectName, aNamePrefix("Shape_");
243   CORBA::Long mytype=aBaseObj->GetType();
244
245   // BEGIN: try to find existed name for current shape
246   if ( !aShape->_is_nil() && mytype != GEOM_GROUP)
247   {
248     // receive current TopoDS shape
249     CORBA::String_var entry = aShape->GetEntry();
250     Handle(::GEOM_Object) aGShape = Handle(::GEOM_Object)::DownCast
251       ( _impl->GetObject( entry ));
252     TopoDS_Shape TopoSh = aGShape->GetValue();
253     // find label of main shape
254     GEOM::GEOM_Object_var aMainSh = aShape;
255     while( !aMainSh->IsMainShape() ) {
256       aMainSh = aMainSh->GetMainShape();
257     }
258     entry = aMainSh->GetEntry();
259     Handle(::GEOM_BaseObject) anObj = _impl->GetObject( entry );
260     TDF_Label aMainLbl = anObj->GetFunction(1)->GetNamingEntry();
261
262     // check all named shapes using iterator
263     TDF_ChildIDIterator anIt (aMainLbl, TNaming_NamedShape::GetID(), Standard_True);
264
265     for (; anIt.More() && anObjectName.IsEmpty(); anIt.Next()) {
266       Handle(TNaming_NamedShape) anAttr =
267         Handle(TNaming_NamedShape)::DownCast(anIt.Value());
268       if (anAttr.IsNull()) continue;
269       TopoDS_Shape S = anAttr->Get();
270       if (S.IsEqual(TopoSh)) {
271         TDF_Label L = anAttr->Label();
272         Handle(TDataStd_Name) aName;
273         if (L.FindAttribute(TDataStd_Name::GetID(), aName))
274           anObjectName = aName->Get();
275       }
276     }
277   }
278   // END: try to find existed name for current shape
279
280   if ( mytype == GEOM_GROUP ) {
281     GEOM::GEOM_IGroupOperations_var anOp = GetIGroupOperations();
282     switch ( (TopAbs_ShapeEnum)anOp->GetType( aShape )) {
283     case TopAbs_VERTEX:
284       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_PNT" );
285       aNamePrefix = "Group_Of_Vertices_";
286       break;
287     case TopAbs_EDGE:
288       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_EDGE");
289       aNamePrefix = "Group_Of_Edges_";
290       break;
291     case TopAbs_FACE:
292       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_FACE");
293       aNamePrefix = "Group_Of_Faces_";
294       break;
295     case TopAbs_SOLID:
296       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_GROUP_SOLID");
297       aNamePrefix = "Group_Of_Solids_";
298       break;
299     default:
300       aNamePrefix = "Group_";
301     }
302   } else if ( mytype == GEOM_MARKER ) {
303     aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_LCS");
304     aNamePrefix = "LocalCS_";
305   }  else if ( mytype >= USER_TYPE_EX ) {
306     char buf[20];
307     sprintf( buf, "%d", aBaseObj->GetType() );
308     GEOM::CreationInformationSeq_var infoSeq = aBaseObj->GetCreationInformation();
309     std::string plgId;
310     for ( size_t j = 0; j < infoSeq->length(); ++j )
311       for ( size_t i = 0; i < infoSeq[j].params.length(); ++i ) {
312         std::string param_name  = infoSeq[j].params[i].name.in();
313         std::string param_value = infoSeq[j].params[i].value.in();
314         if( param_name == PLUGIN_NAME) {
315           plgId = param_value;
316           break;
317         }
318       }
319     if(plgId.length() > 0 ) {
320       plgId += "::";
321     }
322     plgId +="ICON_OBJBROWSER_";
323     plgId += buf;
324     aResultSO->SetAttrString("AttributePixMap",plgId.c_str());
325   } else if ( mytype > USER_TYPE ) {
326     char buf[20];
327     sprintf( buf, "%d", aBaseObj->GetType() );
328     std::string advId = "ICON_OBJBROWSER_ADVANCED_"; advId += buf;
329     aResultSO->SetAttrString("AttributePixMap",advId.c_str());
330     aNamePrefix = "Advanced_";
331   } else if ( mytype == GEOM_FIELD ) {
332     aNamePrefix = "Field_";
333     GEOM::GEOM_Field_var aField = GEOM::GEOM_Field::_narrow(theObject);
334     if ( !aField->_is_nil() )
335       switch( aField->GetDimension() ) {
336       case 0:
337         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_PNT" ); break;
338       case 1:
339         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_EDGE"); break;
340       case 2:
341         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_FACE"); break;
342       case 3:
343         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_SOLID"); break;
344       default:
345         aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FIELD_SOLID");
346       }
347   } else if ( mytype == GEOM_FIELD_STEP ) {
348     aNamePrefix = "Step_";
349   } else if ( !aShape->_is_nil() ) {
350     GEOM::shape_type myshapetype=aShape->GetShapeType();
351     if ( myshapetype == GEOM::COMPOUND ) {
352       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_COMPOUND" );
353       aNamePrefix = "Compound_";
354     } else if ( myshapetype == GEOM::COMPSOLID ) {
355       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_COMPSOLID");
356       aNamePrefix = "Compsolid_";
357     } else if ( myshapetype == GEOM::SOLID ) {
358       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_SOLID");
359       aNamePrefix = "Solid_";
360     } else if ( myshapetype == GEOM::SHELL ) {
361       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_SHELL");
362       aNamePrefix = "Shell_";
363     } else if ( myshapetype == GEOM::FACE ) {
364       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_FACE");
365       aNamePrefix = "Face_";
366     } else if ( myshapetype == GEOM::WIRE ) {
367       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_WIRE");
368       aNamePrefix = "Wire_";
369     } else if ( myshapetype == GEOM::EDGE ) {
370       aResultSO->SetAttrString("AttributePixMap", "ICON_OBJBROWSER_EDGE");
371       aNamePrefix = "Edge_";
372     } else if ( myshapetype == GEOM::VERTEX ) {
373       aResultSO->SetAttrString("AttributePixMap","ICON_OBJBROWSER_VERTEX" );
374       aNamePrefix = "Vertex_";
375     }
376   }
377   if ( anObjectName.IsEmpty() )
378   {
379     //if (strlen(theName) == 0) aNamePrefix += TCollection_AsciiString(aResultSO->Tag());
380     //else anObjectName = TCollection_AsciiString(CORBA::string_dup(theName));
381
382     // asv : 11.11.04 Introducing a more sofisticated method of name creation, just as
383     //       it is done in GUI in GEOMBase::GetDefaultName() - not just add a Tag() == number
384     //       of objects in the study, but compute a number of objects with the same prefix
385     //       and build a new name as Prefix_N+1
386     if ( strlen( theName ) == 0 ) { // MOST PROBABLY CALLED FROM BATCHMODE OR SUPERVISOR
387       int i = 0;                    // (WITH EMPTY NEW NAME)
388       SALOMEDS::SObject_var obj;
389       do {
390         anObjectName = aNamePrefix + TCollection_AsciiString(++i);
391         obj = aStudy->FindObject( anObjectName.ToCString() );
392       }
393       while ( !obj->_is_nil() );
394     }
395     else { // MOST PROBABLY CALLED FROM GEOM GUI (ALREADY WITH VALID NAME)
396       anObjectName = theName;
397     }
398   }
399
400   //Set the study entry as a name of  the published GEOM_Object
401   CORBA::String_var anID = aResultSO->GetID();
402   aBaseObj->SetStudyEntry(anID.in());
403
404   //Set a name of the added shape
405   aResultSO->SetAttrString("AttributeName",anObjectName.ToCString());
406
407   //Set NoteBook variables used in the object creation
408   TCollection_AsciiString aVars;
409   CORBA::String_var aString=aBaseObj->GetParameters();
410   SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(aString);
411   for(int i = 0, n = aSections->length(); i < n; i++) {
412     SALOMEDS::ListOfStrings aListOfVars = aSections[i];
413     for(int j = 0, m = aListOfVars.length(); j < m; j++) {
414       if(aStudy->IsVariable(aListOfVars[j].in()))
415         aVars += aListOfVars[j].in();
416       if(j != m-1)
417         aVars += ":";
418     }
419     if(i != n-1)
420       aVars += "|";
421   }
422   aResultSO->SetAttrString("AttributeString",aVars.ToCString());
423
424   aFather->UnRegister();
425
426   //Set a name of the GEOM object
427   aBaseObj->SetName(anObjectName.ToCString());
428
429   // add object to the use case tree
430   // (to support tree representation customization and drag-n-drop)
431   useCaseBuilder->AppendTo( aResultSO->GetFather(), aResultSO );
432
433   return aResultSO._retn();
434 }
435
436 //============================================================================
437 // function : CreateAndPublishGroup
438 // purpose  : auxiliary for PublishNamedShapesInStudy
439 //============================================================================
440 void GEOM_Gen_i::CreateAndPublishGroup(GEOM::GEOM_Object_var theMainShape,
441                                        const TopTools_IndexedMapOfShape& anIndices,
442                                        const TopTools_SequenceOfShape& SeqS,
443                                        const TColStd_SequenceOfAsciiString& /*SeqN*/,
444                                        const Standard_CString& GrName,
445                                        GEOM::ListOfGO_var /*aResList*/)
446 {
447   CORBA::String_var entry = theMainShape->GetEntry();
448   //Handle(::GEOM_Object) aMainShape = _impl->GetObject(entry);
449   Handle(TColStd_HArray1OfInteger) anArray;
450   if(SeqS.Length()>0) {
451     // create a group
452     GEOM::GEOM_IGroupOperations_var GOp = GetIGroupOperations();
453     GEOM::GEOM_Object_wrap GrObj = GOp->CreateGroup( theMainShape, SeqS(1).ShapeType() );
454     AddInStudy(GrObj, GrName, theMainShape._retn());
455     //CORBA::String_var GrEntry = GrObj->GetEntry();
456     //Handle(::GEOM_Object) HGrObj = _impl->GetObject(GrEntry);
457     // add named objects
458     //Handle(::GEOM_Object) anObj;
459     for(int i=1; i<=SeqS.Length(); i++) {
460       TopoDS_Shape aValue = SeqS.Value(i);
461       //anArray = new TColStd_HArray1OfInteger(1,1);
462       Standard_Integer anIndex = anIndices.FindIndex(aValue);
463       //anArray->SetValue(1, anIndex);
464       GOp->AddObject(GrObj,anIndex);
465       //anObj = GEOM_Engine::GetEngine()->AddObject(GEOM_SUBSHAPE);
466       //if (anObj.IsNull()) continue;
467       //Handle(::GEOM_Function) aFunction = anObj->AddFunction(GEOM_Object::GetSubShapeID(), 1);
468       //if (aFunction.IsNull()) continue;
469       //GEOM_ISubShape aSSI(aFunction);
470       //aSSI.SetMainShape(aMainShape->GetLastFunction());
471       //aSSI.SetIndices(anArray);
472       //aFunction->SetValue(aValue);
473       //GOp->UnionIDs(GrObj, anIndex);
474       //SALOMEDS::SObject_var aResultSO;
475       //TCollection_AsciiString anEntry;
476       //TDF_Tool::Entry(anObj->GetEntry(),anEntry);
477       //GEOM::GEOM_Object_var aGObj = GetObject(anEntry.ToCString());
478       //AddInStudy(aGObj._retn(), SeqN.Value(i).ToCString(), GrObj);
479     }
480   }
481 }
482
483
484 //============================================================================
485 // function : PublishNamedShapesInStudy
486 // purpose  :
487 //============================================================================
488 GEOM::ListOfGO* GEOM_Gen_i::
489             PublishNamedShapesInStudy(//SALOMEDS::SObject_ptr theSObject,
490                                       CORBA::Object_ptr theObject)
491 {
492   //Unexpect aCatch(SALOME_SalomeException);
493   GEOM::ListOfGO_var aResList = new GEOM::ListOfGO;
494
495   //CORBA::Object_var theObject = theSObject->GetObject();
496   GEOM::GEOM_Object_var theMainShape = GEOM::GEOM_Object::_narrow(theObject);
497   if(theMainShape->_is_nil()) return aResList._retn();
498
499   CORBA::String_var entry = theMainShape->GetEntry();
500   Handle(::GEOM_Object) aMainShape = Handle(::GEOM_Object)::DownCast
501     ( _impl->GetObject( entry ));
502   if (aMainShape.IsNull()) return aResList._retn();
503   TopoDS_Shape MainSh = aMainShape->GetValue();
504
505   TDF_Label aMainLbl = aMainShape->GetEntry();
506   TopTools_SequenceOfShape SolidSeqS, FaceSeqS, EdgeSeqS, VertSeqS;
507   TColStd_SequenceOfAsciiString SolidSeqN, FaceSeqN, EdgeSeqN, VertSeqN;
508   TDF_ChildIDIterator anIt(aMainLbl, TNaming_NamedShape::GetID(), Standard_True);
509   for(; anIt.More(); anIt.Next()) {
510     Handle(TNaming_NamedShape) anAttr =
511       Handle(TNaming_NamedShape)::DownCast(anIt.Value());
512     if(anAttr.IsNull()) continue;
513     TopoDS_Shape S = anAttr->Get();
514     TDF_Label L = anAttr->Label();
515     //if(S.IsEqual(MainSh)) continue;
516     Handle(TDataStd_Name) aName;
517     if(L.FindAttribute(TDataStd_Name::GetID(),aName)) {
518       TCollection_ExtendedString EName = aName->Get();
519       if(S.ShapeType()==TopAbs_SOLID) {
520         SolidSeqS.Append(S);
521         SolidSeqN.Append(aName->Get());
522       }
523       else if(S.ShapeType()==TopAbs_FACE) {
524         FaceSeqS.Append(S);
525         FaceSeqN.Append(aName->Get());
526       }
527       else if(S.ShapeType()==TopAbs_EDGE) {
528         EdgeSeqS.Append(S);
529         EdgeSeqN.Append(aName->Get());
530       }
531       else if(S.ShapeType()==TopAbs_VERTEX) {
532         VertSeqS.Append(S);
533         VertSeqN.Append(aName->Get());
534       }
535     }
536   }
537
538   TopTools_IndexedMapOfShape anIndices;
539   TopExp::MapShapes(MainSh, anIndices);
540
541   CreateAndPublishGroup(theMainShape, anIndices, SolidSeqS, SolidSeqN,
542                         "Group_Of_Named_Solids", aResList);
543
544   CreateAndPublishGroup(theMainShape, anIndices, FaceSeqS, FaceSeqN,
545                         "Group_Of_Named_Faces", aResList);
546
547   CreateAndPublishGroup(theMainShape, anIndices, EdgeSeqS, EdgeSeqN,
548                         "Group_Of_Named_Edges", aResList);
549
550   CreateAndPublishGroup(theMainShape, anIndices, VertSeqS, VertSeqN,
551                         "Group_Of_Named_Vertices", aResList);
552
553   return aResList._retn();
554 }
555
556
557 //============================================================================
558 // function : Save()
559 // purpose  : save OCAF/Geom document
560 //============================================================================
561 SALOMEDS::TMPFile* GEOM_Gen_i::Save(SALOMEDS::SComponent_ptr /*theComponent*/,
562                                     const char* theURL,
563                                     bool isMultiFile) {
564   SALOMEDS::TMPFile_var aStreamFile;
565   // Get a temporary directory to store a file
566   std::string aTmpDir = (isMultiFile)?theURL:SALOMEDS_Tool::GetTmpDir();
567
568   // OCCT BUG: cannot save a document (in current folder)
569   // if directory name is empty
570   if (aTmpDir.size() == 0) {
571 #ifdef WIN32
572     aTmpDir = ".\\";
573 #else
574     aTmpDir = "./";
575 #endif
576   }
577
578   // Create a list to store names of created files
579   SALOMEDS_Tool::ListOfFiles aSeq;
580   aSeq.reserve(1);
581   // Prepare a file name to open
582   TCollection_AsciiString aNameWithExt("");
583   if (isMultiFile) 
584     aNameWithExt = TCollection_AsciiString((char*)(SALOMEDS_Tool::GetNameFromPath(
585                           Kernel_Utils::encode(getStudyServant()->URL())).c_str()));
586   aNameWithExt += TCollection_AsciiString("_GEOM.cbf");
587   aSeq.push_back(CORBA::string_dup(aNameWithExt.ToCString()));
588   // Build a full file name of temporary file
589   TCollection_AsciiString aFullName = TCollection_AsciiString((char*)aTmpDir.c_str()) + aNameWithExt;
590   // Save GEOM component in this file
591   if (_impl->Save((char*) aFullName.ToCString())) {
592     // Convert a file to the byte stream
593     aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.c_str(), aSeq, isMultiFile);
594     // Remove the created file and tmp directory
595     if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq, true);
596   }
597   // Return the created byte stream
598   return aStreamFile._retn();
599 }
600
601
602 //============================================================================
603 // function : SaveASCII()
604 // purpose  :
605 //============================================================================
606 SALOMEDS::TMPFile* GEOM_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
607                                          const char* theURL,
608                                          bool isMultiFile) {
609   SALOMEDS::TMPFile_var aStreamFile = Save(theComponent, theURL, isMultiFile);
610   return aStreamFile._retn();
611 }
612
613
614 //============================================================================
615 // function : Load()
616 // purpose  :
617 //============================================================================
618 CORBA::Boolean GEOM_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
619                                 const SALOMEDS::TMPFile& theStream,
620                                 const char* theURL,
621                                 bool isMultiFile) {
622
623   if (theStream.length() <= 9) {
624     MESSAGE("The TMPFile is too short : " << theStream.length() << " bytes ");
625     return false;
626   }
627
628   // Get a temporary directory for a file
629   std::string aTmpDir = isMultiFile?theURL:SALOMEDS_Tool::GetTmpDir();
630
631   // OCCT BUG: cannot load a document (from current folder)
632   // if directory name is empty
633   if (aTmpDir.size() == 0) {
634 #ifdef WIN32
635     aTmpDir = ".\\";
636 #else
637     aTmpDir = "./";
638 #endif
639   }
640
641   // Conver the byte stream theStream to a file and place it in tmp directory
642   SALOMEDS_Tool::ListOfFiles aSeq =
643     SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir.c_str(), isMultiFile);
644
645   // Prepare a file name to open
646   TCollection_AsciiString aNameWithExt("");
647   SALOMEDS::Study_var study = getStudyServant();
648
649   // Get the file name.
650   int         i;
651   int         aLength  = aSeq.size();
652   const char *aGeomSgd = "_GEOM.sgd";
653   const char *aGeomcbf = "_GEOM.cbf";
654
655   for(i = 0; i < aLength; i++) {
656     std::string aName(aSeq[i]);
657
658     if (aName.rfind(aGeomSgd) != std::string::npos ||
659         aName.rfind(aGeomcbf) != std::string::npos) {
660       aNameWithExt = aName.c_str();
661       break;
662     }
663   }
664
665   TCollection_AsciiString aFullName = (TCollection_AsciiString((char*)aTmpDir.c_str()) + aNameWithExt);
666
667   // Open document
668   if (!_impl->Load((char*) aFullName.ToCString())) return false;
669
670   // Remove the created file and tmp directory
671   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq, true);
672
673   // creation of tree nodes for all data objects in the study
674   // to support tree representation customization and drag-n-drop:
675   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
676   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
677     useCaseBuilder->SetRootCurrent();
678     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
679   }
680
681   SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
682   for ( it->InitEx(true); it->More(); it->Next() ) {
683     if ( !useCaseBuilder->IsUseCaseNode( it->Value() ) ) {
684       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
685     }
686   }
687
688   return true;
689 }
690
691
692 //============================================================================
693 // function : LoadASCII()
694 // purpose  :
695 //============================================================================
696 CORBA::Boolean GEOM_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
697                                      const SALOMEDS::TMPFile& theStream,
698                                      const char* theURL,
699                                      bool isMultiFile) {
700   return Load(theComponent, theStream, theURL, isMultiFile);
701 }
702
703
704 //============================================================================
705 // function : Close()
706 // purpose  :
707 //============================================================================
708 void GEOM_Gen_i::Close(SALOMEDS::SComponent_ptr /*theComponent*/)
709 {
710   _impl->Close();
711 }
712
713 //============================================================================
714 // function : CanCopy()
715 // purpose  :
716 //============================================================================
717 CORBA::Boolean GEOM_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) {
718   // Try to retrieve known by Geometry component GEOM_Object by given IOR
719   SALOMEDS::GenericAttribute_var anAttr;
720   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
721
722   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
723
724   CORBA::String_var aString=anIOR->Value();
725   anIOR->UnRegister();
726   CORBA::Object_var anObj = _orb->string_to_object(aString);
727   GEOM::GEOM_Object_var anObject = GEOM::GEOM_Object::_narrow(anObj);
728   // If the object is null one it can't be copied: return false
729   if (anObject->_is_nil()) return false;
730   return true;
731 }
732
733 //============================================================================
734 // function : CopyFrom()
735 // purpose  :
736 //============================================================================
737 SALOMEDS::TMPFile* GEOM_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID)
738 {
739   // Declare a sequence of the byte to store the copied object
740   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
741
742   // Try to get GEOM_Object object by given SObject
743   SALOMEDS::GenericAttribute_var anAttr;
744   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return aStreamFile._retn();
745   GEOM::GEOM_Object_var anObject = GEOM::GEOM_Object::_narrow
746     (_orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value()));
747   if (anObject->_is_nil()) return aStreamFile._retn();
748
749   aStreamFile = anObject->GetShapeStream();
750
751   // Assign an ID  the type of  GEOM_Object
752   theObjectID = anObject->GetType();
753
754   // Return created TMPFile
755   return aStreamFile._retn();
756 }
757
758 //============================================================================
759 // function : CanPaste()
760 // purpose  :
761 //============================================================================
762 CORBA::Boolean GEOM_Gen_i::CanPaste(const char* theComponentName, CORBA::Long /*theObjectID*/) {
763   // The Geometry component can paste only objects copied by Geometry component
764   // and with the object type = 1
765   if (strcmp(theComponentName, ComponentDataType()) != 0) return false;
766   return true;
767 }
768
769 //============================================================================
770 // function : PasteInto()
771 // purpose  :
772 //============================================================================
773 SALOMEDS::SObject_ptr GEOM_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
774                                             CORBA::Long theObjectID,
775                                             SALOMEDS::SObject_ptr theObject) {
776   // Find the current Study and StudyBuilder
777   SALOMEDS::Study_var aStudy = getStudyServant();
778   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
779   SALOMEDS::UseCaseBuilder_var anUseCaseBuilder = aStudy->GetUseCaseBuilder();
780   SALOMEDS::SObject_var aNewSO;
781   // Retrieve a TopoDS_Shape from byte stream
782   TopoDS_Shape aTopology;
783   std::istringstream aStreamedBrep((char*) &theStream[0]);
784   BRep_Builder aBuilder;
785   try {
786     BRepTools::Read(aTopology, aStreamedBrep, aBuilder);
787   } catch (Standard_Failure&) {
788     return aNewSO._retn();
789   }
790
791   // SObject of the created shape is theObject or new Child of Component if theObject == geom component
792   if (strcmp(theObject->GetFatherComponent()->GetID(),theObject->GetID()) == 0) {
793     aNewSO = aStudyBuilder->NewObject(theObject);
794   } else aNewSO = SALOMEDS::SObject::_duplicate(theObject);
795
796
797   //Create a new GEOM_Object
798   Handle(::GEOM_Object) anObj = _impl->AddObject(theObjectID);
799   Handle(::GEOM_Function) aFunction = anObj->AddFunction(GEOMImpl_CopyDriver::GetID(), COPY_WITHOUT_REF);
800   aFunction->SetValue(aTopology);
801
802   TCollection_AsciiString anEntry;
803   TDF_Tool::Entry(anObj->GetEntry(), anEntry);
804   GEOM::GEOM_BaseObject_var obj = GetObject(anEntry.ToCString());
805
806   //Set the study entry of the published GEOM_Object
807   obj->SetStudyEntry(aNewSO->GetID());
808
809   // Add IORAttribute to the Study and set IOR of the created GEOM_Object to it
810   SALOMEDS::GenericAttribute_var anAttr = aStudyBuilder->FindOrCreateAttribute(aNewSO, "AttributeIOR");
811   SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
812   CORBA::String_var objStr = _orb->object_to_string(obj);
813   anIOR->SetValue(objStr.in());
814   anIOR->UnRegister();
815
816   // add object to the use case tree
817   // (to support tree representation customization and drag-n-drop)
818   anUseCaseBuilder->AppendTo( aNewSO->GetFather(), aNewSO );
819
820   // Return the created in the Study SObject
821   return aNewSO._retn();
822 }
823
824 //============================================================================
825 // function : ComponentDataType()
826 // purpose  :
827 //============================================================================
828 char* GEOM_Gen_i::ComponentDataType()
829 {
830   return CORBA::string_dup("GEOM");
831 }
832
833 //============================================================================
834 // function : AddInStudy
835 // purpose  :
836 //============================================================================
837 SALOMEDS::SObject_ptr GEOM_Gen_i::AddInStudy (GEOM::GEOM_BaseObject_ptr theObject,
838                                               const char*               theName,
839                                               GEOM::GEOM_BaseObject_ptr theFather)
840 {
841   SALOMEDS::SObject_var aResultSO;
842   SALOMEDS::Study_var aStudy = getStudyServant();
843   if(theObject->_is_nil() || aStudy->_is_nil()) return aResultSO;
844
845   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
846   CORBA::String_var IOR;
847
848   if(!theFather->_is_nil()) {
849     IOR = _orb->object_to_string(theFather);
850     SALOMEDS::SObject_wrap aFatherSO = aStudy->FindObjectIOR(IOR.in());
851     if(aFatherSO->_is_nil()) return aResultSO._retn();
852     aResultSO = aStudyBuilder->NewObject(aFatherSO);
853     //aStudyBuilder->Addreference(aResultSO, aResultSO);
854   }
855
856   aResultSO = PublishInStudy(aResultSO, theObject, theName);
857   if(aResultSO->_is_nil()) return aResultSO._retn();
858
859   GEOM::ListOfGBO_var aList = theObject->GetDependency();
860   Standard_Integer aLength = aList->length();
861   if(aLength < 1) return aResultSO._retn();
862
863   //Publish the arguments
864   TCollection_AsciiString aPrevID; // to avoid multiple references to same object
865   for(Standard_Integer i = 0; i< aLength; i++) {
866     GEOM::GEOM_BaseObject_var anObject = aList[i];
867     if(anObject->_is_nil()) continue;
868     IOR = _orb->object_to_string(anObject);
869     SALOMEDS::SObject_wrap aSO =  aStudy->FindObjectIOR(IOR.in());
870     if(aSO->_is_nil()) continue;
871     CORBA::String_var anID = aSO->GetID();
872     if ( aPrevID == anID.in() ) continue;
873     aPrevID = anID.in();
874     SALOMEDS::SObject_wrap aSubSO = aStudyBuilder->NewObject(aResultSO);
875     aStudyBuilder->Addreference(aSubSO, aSO);
876     aStudy->GetUseCaseBuilder()->AppendTo( aResultSO, aSubSO );
877   }
878
879   return aResultSO._retn();
880 }
881
882 //============================================================================
883 // function : RestoreSubShapesO
884 // purpose  : Publish sub-shapes, standing for arguments and sub-shapes of arguments.
885 //            To be used from python scripts out of geompy.addToStudy (non-default usage)
886 //============================================================================
887 GEOM::ListOfGO* GEOM_Gen_i::RestoreSubShapesO (GEOM::GEOM_Object_ptr   theObject,
888                                                const GEOM::ListOfGO&   theArgs,
889                                                GEOM::find_shape_method theFindMethod,
890                                                CORBA::Boolean          theInheritFirstArg,
891                                                CORBA::Boolean          theAddPrefix)
892 {
893   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
894   SALOMEDS::Study_var aStudy = getStudyServant();
895   if (CORBA::is_nil(aStudy) || CORBA::is_nil(theObject))
896     return aParts._retn();
897
898   // find SObject in the study if it is already published
899   CORBA::String_var anIORo = _orb->object_to_string(theObject);
900   SALOMEDS::SObject_var aSO = aStudy->FindObjectIOR(anIORo.in());
901   //PTv, IMP 0020001, The salome object <aSO>
902   // is not obligatory in case of invocation from script
903   // if (CORBA::is_nil(aSO))
904   //  return aParts._retn();
905
906   aParts = RestoreSubShapes(theObject, aSO, theArgs,
907                             theFindMethod, theInheritFirstArg, theAddPrefix);
908   if (!CORBA::is_nil(aSO)) aSO->UnRegister();
909   return aParts._retn();
910 }
911
912 //============================================================================
913 // function : RestoreGivenSubShapesO
914 // purpose  : Publish sub-shapes, standing for arguments and sub-shapes of arguments.
915 //            To be used from python scripts, generated by Dump Python.
916 //============================================================================
917 GEOM::ListOfGO* GEOM_Gen_i::RestoreGivenSubShapesO (GEOM::GEOM_Object_ptr   theObject,
918                                                     const GEOM::ListOfGO&   theArgs,
919                                                     GEOM::find_shape_method theFindMethod,
920                                                     CORBA::Boolean          theInheritFirstArg,
921                                                     CORBA::Boolean          theAddPrefix)
922 {
923   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
924   if (CORBA::is_nil(getStudyServant()) || CORBA::is_nil(theObject))
925     return aParts._retn();
926
927   // find SObject in the study if it is already published
928   CORBA::String_var anIORo = _orb->object_to_string(theObject);
929   SALOMEDS::SObject_var aSO = getStudyServant()->FindObjectIOR(anIORo.in());
930   //PTv, IMP 0020001, The salome object <aSO>
931   // is not obligatory in case of invocation from script
932   // if (CORBA::is_nil(aSO))
933   //  return aParts._retn();
934
935   aParts = RestoreGivenSubShapes(theObject, aSO, theArgs,
936                                  theFindMethod, theInheritFirstArg, theAddPrefix);
937   if (!CORBA::is_nil(aSO)) aSO->UnRegister();
938   return aParts._retn();
939 }
940
941 //============================================================================
942 // function : RestoreSubShapesSO
943 // purpose  : Publish sub-shapes, standing for arguments and sub-shapes of arguments.
944 //            To be used from GUI and from geompy.addToStudy
945 //============================================================================
946 GEOM::ListOfGO* GEOM_Gen_i::RestoreSubShapesSO (SALOMEDS::SObject_ptr   theSObject,
947                                                 const GEOM::ListOfGO&   theArgs,
948                                                 GEOM::find_shape_method theFindMethod,
949                                                 CORBA::Boolean          theInheritFirstArg,
950                                                 CORBA::Boolean          theAddPrefix)
951 {
952   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
953   if (CORBA::is_nil(getStudyServant()) || CORBA::is_nil(theSObject))
954     return aParts._retn();
955
956   SALOMEDS::GenericAttribute_var anAttr;
957   if (!theSObject->FindAttribute(anAttr, "AttributeIOR"))
958     return aParts._retn();
959
960   SALOMEDS::AttributeIOR_var anAttrIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
961   CORBA::String_var anIORso = anAttrIOR->Value();
962
963   // get Object from SObject
964   GEOM::GEOM_Object_var anO = GEOM::GEOM_Object::_narrow(_orb->string_to_object(anIORso));
965   if (CORBA::is_nil(anO))
966     return aParts._retn();
967
968   aParts = RestoreSubShapes(anO, theSObject, theArgs,
969                             theFindMethod, theInheritFirstArg, theAddPrefix);
970   return aParts._retn();
971 }
972
973 //============================================================================
974 // function : addToListOfGO
975 // purpose  : static local function
976 //============================================================================
977 static void addToListOfGO( GEOM::GEOM_Object_ptr theObject,
978                            GEOM::ListOfGO& theList )
979 {
980   const int oldLen = theList.length();
981   theList.length(oldLen + 1);
982   theList[ oldLen ] = GEOM::GEOM_Object::_duplicate( theObject );
983 }
984
985 //============================================================================
986 // function : addToListOfGO
987 // purpose  : static local function
988 //============================================================================
989 static void addToListOfGO( const GEOM::ListOfGO& theSrcList,
990                            GEOM::ListOfGO& theTrgList )
991 {
992   const int oldLen = theTrgList.length();
993   const int srcLen = theSrcList.length();
994   theTrgList.length(oldLen + srcLen);
995   for( int i = 0; i < srcLen; i++ )
996     theTrgList[ oldLen + i ] = GEOM::GEOM_Object::_duplicate( theSrcList[ i ] );
997 }
998
999 //============================================================================
1000 // function : RestoreSubShapes
1001 // purpose  : Private method. Works only if both theObject and theSObject
1002 //            are defined, and does not check, if they correspond to each other.
1003 //============================================================================
1004 GEOM::ListOfGO* GEOM_Gen_i::RestoreSubShapes(GEOM::GEOM_Object_ptr   theObject,
1005                                              SALOMEDS::SObject_ptr   theSObject,
1006                                              const GEOM::ListOfGO&   theArgs,
1007                                              GEOM::find_shape_method theFindMethod,
1008                                              CORBA::Boolean          theInheritFirstArg,
1009                                              CORBA::Boolean          theAddPrefix)
1010 {
1011   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
1012   SALOMEDS::Study_var aStudy = getStudyServant();
1013   //PTv, IMP 0020001, The salome object <theSObject>
1014   //     is not obligatory in case of invocation from script
1015   if (CORBA::is_nil(aStudy) || CORBA::is_nil(theObject) /*|| CORBA::is_nil(theSObject)*/)
1016     return aParts._retn();
1017
1018   // For Dump Python (mantis issue 0020768)
1019   GEOM::ListOfGO_var anOutArgs = new GEOM::ListOfGO;
1020
1021   // Arguments to be published
1022   GEOM::ListOfGO_var aList;
1023
1024   // If theArgs list is empty, we try to publish all arguments,
1025   // otherwise publish only passed args
1026   Standard_Integer nbArgsActual = -1; // -1 means unknown
1027   Standard_Integer aLength = theArgs.length();
1028   if (aLength > 0) {
1029     aList = new GEOM::ListOfGO;
1030     aList->length(aLength);
1031     for (int i = 0; i < aLength; i++) {
1032       aList[i] = GEOM::GEOM_Object::_duplicate( theArgs[i] );
1033     }
1034   }
1035   else {
1036     // Get all arguments
1037     GEOM::ListOfGBO_var boList = theObject->GetDependency();
1038     aLength = boList->length();
1039     aList = new GEOM::ListOfGO;
1040     aList->length(aLength);
1041     for (int i = 0; i < aLength; i++)
1042       aList[i] = GEOM::GEOM_Object::_narrow( boList[i] );
1043     nbArgsActual = aLength;
1044   }
1045
1046   if (aLength < 1)
1047     return aParts._retn();
1048
1049   if (theInheritFirstArg || (nbArgsActual == 1)) {
1050     // Do not publish argument's reflection,
1051     // but only reconstruct its published sub-shapes
1052
1053     CORBA::String_var anIOR = _orb->object_to_string(aList[0]);
1054     SALOMEDS::SObject_var anArgSO = aStudy->FindObjectIOR(anIOR.in());
1055
1056     // remember restored objects for Python Dump
1057     addToListOfGO(aList[0], anOutArgs);
1058
1059     aParts = RestoreSubShapesOneLevel(anArgSO, theSObject, theObject,
1060                                       anOutArgs, theFindMethod, theAddPrefix);
1061
1062     // set the color of the transformed shape to the color of initial shape
1063     theObject->SetColor(aList[0]->GetColor());
1064     // set the texture
1065     if (theObject->GetShapeType() == GEOM::VERTEX) {
1066       theObject->SetMarkerStd(aList[0]->GetMarkerType(), aList[0]->GetMarkerSize());
1067       if (aList[0]->GetMarkerType() == GEOM::MT_USER)
1068         theObject->SetMarkerTexture(aList[0]->GetMarkerTexture());
1069     }
1070     if (!CORBA::is_nil(anArgSO))
1071       anArgSO->UnRegister();
1072   }
1073   else {
1074     // Get interface, containing method, which we will use to reconstruct sub-shapes
1075     GEOM::GEOM_IShapesOperations_var  aShapesOp = GetIShapesOperations();
1076     GEOM::GEOM_IGroupOperations_var    aGroupOp = GetIGroupOperations();
1077     GEOM::GEOM_ITransformOperations_var aTrsfOp = GetITransformOperations();
1078
1079     PortableServer::Servant aServant = _poa->reference_to_servant(aTrsfOp.in());
1080     GEOM_ITransformOperations_i*      aTrsfOpSv = dynamic_cast<GEOM_ITransformOperations_i*>(aServant);
1081
1082     // Reconstruct arguments and tree of sub-shapes of the arguments
1083     CORBA::String_var anIOR;
1084     SALOMEDS::StudyBuilder_var      aStudyBuilder = aStudy->NewBuilder();
1085     SALOMEDS::UseCaseBuilder_wrap  useCaseBuilder = aStudy->GetUseCaseBuilder();
1086     for (Standard_Integer i = 0; i < aLength; i++)
1087     {
1088       GEOM::GEOM_Object_var anArgO = aList[i];
1089       if (!CORBA::is_nil(anArgO)) {
1090         anIOR = _orb->object_to_string(anArgO);
1091         SALOMEDS::SObject_var anArgSO = aStudy->FindObjectIOR(anIOR.in());
1092         TCollection_AsciiString anArgName;
1093         if (CORBA::is_nil(anArgSO)) {
1094           anArgName = "arg_";
1095           anArgName += TCollection_AsciiString(i);
1096         }
1097         else {
1098           anArgName = anArgSO->GetName();
1099         }
1100
1101         // Find a sub-shape of theObject in place of the argument
1102         GEOM::GEOM_Object_var aSubO;
1103         switch (theFindMethod) {
1104         case GEOM::FSM_GetInPlace:
1105           {
1106             // Use GetInPlace
1107             aSubO = aShapesOp->GetInPlace(theObject, anArgO);
1108           }
1109           break;
1110         case GEOM::FSM_MultiTransformed:
1111           {
1112             // Only for Multi-transformations
1113             GEOM::GEOM_Object_var anArgOTrsf = aTrsfOpSv->TransformLikeOtherCopy(anArgO, theObject);
1114             if (!CORBA::is_nil(anArgOTrsf)) {
1115               CORBA::String_var anArgOTrsfEntry = anArgOTrsf->GetEntry();
1116               Handle(::GEOM_BaseObject) anArgOTrsfImpl = _impl->GetObject(anArgOTrsfEntry);
1117               Handle(::GEOM_Function) anArgOTrsfFun = anArgOTrsfImpl->GetLastFunction();
1118               anArgOTrsfFun->SetDescription("");
1119               aSubO = aShapesOp->GetInPlace(theObject, anArgOTrsf);
1120             }
1121             /*
1122             Handle(::GEOM_Function) anOFun = theObject->GetLastFunction();
1123             if (!anOFun.IsNull()) {
1124               CORBA::String_var entryArg = anArgO->GetEntry();
1125               Handle(::GEOM_Object) anArgOImpl = _impl->GetObject(entryArg);
1126               if (!anArgOImpl.IsNull()) {
1127                 TopoDS_Shape anArgOShape = anArgOImpl->GetValue();
1128                 TopoDS_Shape aMultiArgShape;
1129                 //GEOM::GEOM_Object_var anArgOMulti; // ???
1130                 switch (anOFun->GetType()) {
1131                 case TRANSLATE_1D:
1132                   {
1133                     GEOMImpl_ITranslate aTI (anOFun);
1134                     aMultiArgShape = GEOMImpl_ITransformOperations::TranslateShape1D(anArgOShape, &aTI);
1135                     //anArgOMulti = aTrsfOpSv->Translate1D(anArgO, , , );
1136                   }
1137                   break;
1138                 case TRANSLATE_2D:
1139                   {
1140                     GEOMImpl_ITranslate aTI (anOFun);
1141                     aMultiArgShape = GEOMImpl_ITransformOperations::TranslateShape2D(anArgOShape, &aTI);
1142                   }
1143                   break;
1144                 case ROTATE_1D:
1145                   {
1146                     GEOMImpl_IRotate aTI (anOFun);
1147                     //aMultiArgShape = GEOMImpl_ITransformOperations::TranslateShape2D(anArgOShape, &aTI);
1148                   }
1149                   break;
1150                 case ROTATE_2D:
1151                   {
1152                     GEOMImpl_IRotate aTI (anOFun);
1153                     //aMultiArgShape = GEOMImpl_ITransformOperations::TranslateShape2D(anArgOShape, &aTI);
1154                   }
1155                   break;
1156                 default:
1157                   {}
1158                 }
1159                 GEOM::GEOM_Object_var anArgOMulti = (aMultiArgShape); // TODO
1160                 Handle(::GEOM_Function) anArgOMultiFun = anArgOMulti->GetLastFunction();
1161                 anArgOMultiFun->SetDescription("");
1162                 aSubO = aShapesOp->GetInPlace(theObject, anArgOMulti);
1163               }
1164             }
1165             */
1166           }
1167           break;
1168         case GEOM::FSM_Transformed:
1169           {
1170             // transformation, cannot use GetInPlace, operate with indices
1171             GEOM::ListOfLong_var anIDs = anArgO->GetSubShapeIndices();
1172             if (anIDs->length() > 1) {
1173               // group
1174               aSubO = aGroupOp->CreateGroup(theObject, aGroupOp->GetType(anArgO));
1175               if (!CORBA::is_nil(aSubO))
1176                 aGroupOp->UnionIDs(aSubO, anIDs);
1177             }
1178             else if (anIDs->length() > 0) {
1179               // single sub-shape
1180               aSubO = aShapesOp->GetSubShape(theObject, anIDs[0]);
1181             }
1182           }
1183           break;
1184         case GEOM::FSM_GetSame:
1185           {
1186             // Use GetSame
1187             aSubO = aShapesOp->GetSame(theObject, anArgO);
1188           }
1189           break;
1190         case GEOM::FSM_GetShapesOnShape:
1191           {
1192             // Use GetShapesOnShape. Can work only on solids, so it has sense to search only solids
1193             aSubO = aShapesOp->GetShapesOnShapeAsCompound(anArgO, theObject,
1194               (short)GEOM::SOLID, GEOM::ST_ONIN);
1195           }
1196           break;
1197         case GEOM::FSM_GetInPlaceByHistory:
1198           {
1199             // Use GetInPlaceByHistory
1200             aSubO = aShapesOp->GetInPlaceByHistory(theObject, anArgO);
1201           }
1202           break;
1203         default:
1204           {}
1205         }
1206
1207         if (!CORBA::is_nil(aSubO)) {
1208           // remember restored objects for Python Dump
1209           addToListOfGO(anArgO, anOutArgs);
1210
1211           // add to parts list
1212           addToListOfGO( aSubO, aParts );
1213
1214           // Publish the sub-shape
1215           SALOMEDS::SObject_var aSubSO;
1216           if (!CORBA::is_nil(theSObject)) {
1217             TCollection_AsciiString aSubName;
1218             if (theAddPrefix) {
1219               aSubName = "from_";
1220             }
1221             aSubName += anArgName;
1222             aSubSO = aStudyBuilder->NewObject(theSObject);
1223             aSubSO = PublishInStudy(aSubSO, aSubO, aSubName.ToCString());
1224             // Restore color
1225             aSubO->SetColor(anArgO->GetColor());
1226             // set the texture
1227             if (aSubO->GetShapeType() == GEOM::VERTEX) {
1228               aSubO->SetMarkerStd(anArgO->GetMarkerType(), anArgO->GetMarkerSize());
1229               if (anArgO->GetMarkerType() == GEOM::MT_USER)
1230                 aSubO->SetMarkerTexture(anArgO->GetMarkerTexture());
1231             }
1232           }
1233
1234           if (!CORBA::is_nil(anArgSO)) {
1235             // Restore published sub-shapes of the argument
1236             GEOM::ListOfGO_var aSubParts;
1237             if (theFindMethod == GEOM::FSM_GetInPlaceByHistory)
1238               // pass theObject, because only it has the history
1239               aSubParts = RestoreSubShapesOneLevel(anArgSO, aSubSO,
1240                                                    theObject, anOutArgs, theFindMethod, theAddPrefix);
1241             else
1242               aSubParts = RestoreSubShapesOneLevel(anArgSO, aSubSO,
1243                                                    aSubO, anOutArgs, theFindMethod, theAddPrefix);
1244             // add to parts list
1245             addToListOfGO( aSubParts, aParts );
1246           }
1247         }
1248         else { // GetInPlace failed, try to build from published parts
1249           if (!CORBA::is_nil(anArgSO)) {
1250             SALOMEDS::SObject_var aSubSO;
1251             if (!CORBA::is_nil(theSObject))
1252             {
1253               aSubSO = aStudyBuilder->NewObject(theSObject);
1254               useCaseBuilder->AppendTo( theSObject, aSubSO );
1255             }
1256
1257             // Restore published sub-shapes of the argument
1258             GEOM::ListOfGO_var aSubParts =
1259               RestoreSubShapesOneLevel(anArgSO, aSubSO,
1260                                        theObject, anOutArgs, theFindMethod, theAddPrefix);
1261
1262             // add to parts list
1263             addToListOfGO( aSubParts, aParts );
1264
1265             if (aSubParts->length() > 0) {
1266               // remember restored objects for Python Dump
1267               addToListOfGO(anArgO, anOutArgs);
1268
1269               // try to build an argument from a set of its sub-shapes,
1270               // that published and will be reconstructed
1271               if (aSubParts->length() > 1) {
1272                 aSubO = aShapesOp->MakeCompound(aSubParts);
1273                 // add to parts list
1274                 addToListOfGO( aSubO, aParts );
1275               }
1276               else {
1277                 aSubO = aSubParts[0];
1278               }
1279               if (!CORBA::is_nil(aSubO) && !CORBA::is_nil(aSubSO)) {
1280                 // Publish the sub-shape
1281                 TCollection_AsciiString aSubName;
1282                 if (theAddPrefix) {
1283                   aSubName = "from_parts_of_";
1284                 }
1285                 aSubName += anArgName;
1286                 aSubSO = PublishInStudy(aSubSO, aSubO, aSubName.ToCString());
1287                 // Restore color
1288                 aSubO->SetColor(anArgO->GetColor());
1289                 // set the texture
1290                 if (aSubO->GetShapeType() == GEOM::VERTEX) {
1291                   aSubO->SetMarkerStd(anArgO->GetMarkerType(), anArgO->GetMarkerSize());
1292                   if (anArgO->GetMarkerType() == GEOM::MT_USER)
1293                     aSubO->SetMarkerTexture(anArgO->GetMarkerTexture());
1294                 }
1295               }
1296             }
1297             else if (!CORBA::is_nil(aSubSO)) {
1298               // remove created aSubSO, because no parts have been found
1299               aStudyBuilder->RemoveObject(aSubSO);
1300             }
1301           }
1302         } // try to build from published parts
1303         if (!CORBA::is_nil(anArgSO))
1304           anArgSO->UnRegister();
1305       }
1306     } // process arguments
1307   }
1308   std::set<std::string> anObjEntryMap;
1309   GEOM::ListOfGO_var aResParts = new GEOM::ListOfGO;
1310   int nbRes = 0;
1311   int nb = aParts->length();
1312   aResParts->length(nb);
1313   if (nb > 0)
1314   {
1315     Handle(::GEOM_BaseObject) aMainObj = _impl->GetObject(theObject->GetEntry());
1316     Handle(::GEOM_Function) aFunction = aMainObj->GetLastFunction();
1317     GEOM::TPythonDump pd (aFunction, true);
1318     pd <<"[";
1319     int i = 0, j = 0;
1320     for ( ; i < nb; i++ )
1321     {
1322       GEOM::GEOM_Object_var anObj = GEOM::GEOM_Object::_duplicate( aParts[ i ] );
1323       if (CORBA::is_nil(anObj))
1324         continue;
1325       char* anEntry = anObj->GetEntry();
1326       if (anObjEntryMap.count(anEntry))
1327         continue; // already treated
1328       anObjEntryMap.insert(anEntry);
1329       aResParts[nbRes++] = anObj;
1330       // clear python dump of object
1331       Handle(::GEOM_BaseObject) aGeomObj = _impl->GetObject(anEntry);
1332       Handle(::GEOM_Function)   anObjFun = aGeomObj->GetLastFunction();
1333       if ( !anObjFun.IsNull() )
1334         anObjFun->SetDescription( "" );
1335       if ( j > 0 )
1336         pd << ", ";
1337       pd << aGeomObj;
1338       j++;
1339     }
1340     pd <<"]" << " = geompy.RestoreGivenSubShapes(" << aMainObj << ", " << "[";
1341     //i = 0; nb = theArgs.length(); j = 0;
1342     i = 0; nb = anOutArgs->length(); j = 0;
1343     for ( ; i < nb; i++ )
1344     {
1345       //GEOM::GEOM_Object_var anObj = theArgs[ i ];
1346       GEOM::GEOM_Object_var anObj = anOutArgs[ i ];
1347       if (CORBA::is_nil(anObj))
1348         continue;
1349       Handle(::GEOM_BaseObject) aGeomObj = _impl->GetObject(anObj->GetEntry());
1350       if ( j > 0 )
1351         pd << ", ";
1352       pd << aGeomObj;
1353       j++;
1354     }
1355     pd <<"]" << ", " <<"GEOM.";
1356     switch (theFindMethod) {
1357     case GEOM::FSM_GetInPlace:
1358       pd << "FSM_GetInPlace"; break;
1359     case GEOM::FSM_MultiTransformed:
1360       pd << "FSM_MultiTransformed"; break;
1361     case GEOM::FSM_Transformed:
1362       pd << "FSM_Transformed"; break;
1363     case GEOM::FSM_GetSame:
1364       pd << "FSM_GetSame"; break;
1365     case GEOM::FSM_GetShapesOnShape:
1366       pd << "FSM_GetShapesOnShape"; break;
1367     case GEOM::FSM_GetInPlaceByHistory:
1368     default:
1369       pd << "FSM_GetInPlaceByHistory"; break;
1370     }
1371     pd << ", " << theInheritFirstArg << ", " << theAddPrefix << ")";
1372   }
1373   aResParts->length(nbRes);
1374   return aResParts._retn();
1375 }
1376
1377 //============================================================================
1378 // function : RestoreSubShapesOneLevel
1379 // purpose  : Private method
1380 //============================================================================
1381 GEOM::ListOfGO* GEOM_Gen_i::RestoreSubShapesOneLevel (SALOMEDS::SObject_ptr   theOldSO,
1382                                                       SALOMEDS::SObject_ptr   theNewSO,
1383                                                       GEOM::GEOM_Object_ptr   theNewO,
1384                                                       GEOM::ListOfGO&         theOutArgs,
1385                                                       GEOM::find_shape_method theFindMethod,
1386                                                       CORBA::Boolean          theAddPrefix)
1387 {
1388   int i = 0;
1389   SALOMEDS::Study_var aStudy = getStudyServant();
1390   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
1391   GEOM::ListOfGO_var aNewParts = new GEOM::ListOfGO;
1392   if (CORBA::is_nil(aStudy) || CORBA::is_nil(theOldSO) ||
1393       CORBA::is_nil(theNewO) /*|| CORBA::is_nil(theNewSO)*/)
1394     return aParts._retn();
1395
1396   SALOMEDS::StudyBuilder_var     aStudyBuilder = aStudy->NewBuilder();
1397   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
1398
1399   // Get interface, containing method, which we will use to reconstruct sub-shapes
1400   GEOM::GEOM_IShapesOperations_var  aShapesOp = GetIShapesOperations();
1401   GEOM::GEOM_IGroupOperations_var    aGroupOp = GetIGroupOperations();
1402   GEOM::GEOM_ITransformOperations_var aTrsfOp = GetITransformOperations();
1403
1404   PortableServer::Servant aServant = _poa->reference_to_servant(aTrsfOp.in());
1405   GEOM_ITransformOperations_i*      aTrsfOpSv = dynamic_cast<GEOM_ITransformOperations_i*>(aServant);
1406
1407   // Reconstruct published sub-shapes
1408   SALOMEDS::ChildIterator_var it = aStudy->NewChildIterator(theOldSO);
1409
1410   int aLen = 0;
1411   for (it->Init(); it->More(); it->Next()) {
1412     aLen++;
1413   }
1414   aParts->length(aLen);
1415
1416   for (it->Init(); it->More(); it->Next()) {
1417     SALOMEDS::SObject_var anOldSubSO = it->Value();
1418
1419     TCollection_AsciiString anArgName = anOldSubSO->GetName();
1420
1421     SALOMEDS::GenericAttribute_var anAttr;
1422     if (anOldSubSO->FindAttribute(anAttr, "AttributeIOR")) {
1423       SALOMEDS::AttributeIOR_var anAttrIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
1424       GEOM::GEOM_Object_var anOldSubO =
1425         GEOM::GEOM_Object::_narrow(_orb->string_to_object(anAttrIOR->Value()));
1426       if (!CORBA::is_nil(anOldSubO)) {
1427         // Find a sub-shape of theNewO in place of anOldSubO
1428         GEOM::GEOM_Object_var aNewSubO;
1429         switch (theFindMethod) {
1430         case GEOM::FSM_GetInPlace:
1431           {
1432             // Use GetInPlace
1433             aNewSubO = aShapesOp->GetInPlace(theNewO, anOldSubO);
1434           }
1435           break;
1436         case GEOM::FSM_MultiTransformed:
1437           {
1438             // Only for Multi-transformations
1439             GEOM::GEOM_Object_var anArgOTrsf = aTrsfOpSv->TransformLikeOtherCopy(anOldSubO, theNewO);
1440             if (!CORBA::is_nil(anArgOTrsf)) {
1441               CORBA::String_var anArgOTrsfEntry = anArgOTrsf->GetEntry();
1442               Handle(::GEOM_BaseObject) anArgOTrsfImpl = _impl->GetObject(anArgOTrsfEntry);
1443               Handle(::GEOM_Function) anArgOTrsfFun = anArgOTrsfImpl->GetLastFunction();
1444               anArgOTrsfFun->SetDescription("");
1445               aNewSubO = aShapesOp->GetInPlace(theNewO, anArgOTrsf);
1446             }
1447           }
1448           break;
1449         case GEOM::FSM_Transformed:
1450           {
1451             // transformation, cannot use GetInPlace, operate with indices
1452             GEOM::ListOfLong_var anIDs = anOldSubO->GetSubShapeIndices();
1453             if (anIDs->length() > 1) {
1454               // group
1455               aNewSubO = aGroupOp->CreateGroup(theNewO, aGroupOp->GetType(anOldSubO));
1456               if (!CORBA::is_nil(aNewSubO))
1457                 aGroupOp->UnionIDs(aNewSubO, anIDs);
1458             }
1459             else {
1460               // single sub-shape
1461               aNewSubO = aShapesOp->GetSubShape(theNewO, anIDs[0]);
1462             }
1463           }
1464           break;
1465         case GEOM::FSM_GetSame:
1466           {
1467             // Use GetSame
1468             aNewSubO = aShapesOp->GetSame(theNewO, anOldSubO);
1469           }
1470           break;
1471         case GEOM::FSM_GetShapesOnShape:
1472           {
1473             // Use GetShapesOnShape. Can work only on solids, so it has sense to search only solids
1474             aNewSubO = aShapesOp->GetShapesOnShapeAsCompound(anOldSubO, theNewO,
1475                                                              (short)GEOM::SOLID, GEOM::ST_ONIN);
1476           }
1477           break;
1478         case GEOM::FSM_GetInPlaceByHistory:
1479           {
1480             // Use GetInPlaceByHistory
1481             aNewSubO = aShapesOp->GetInPlaceByHistory(theNewO, anOldSubO);
1482           }
1483           break;
1484         default:
1485           {}
1486         }
1487
1488         if (!CORBA::is_nil(aNewSubO)) {
1489           // remember restored objects for Python Dump
1490           addToListOfGO(anOldSubO, theOutArgs);
1491
1492           // add the part to the list
1493           aParts[i] = aNewSubO;
1494           i++;
1495           // add to parts list
1496           addToListOfGO( aNewSubO, aNewParts );
1497
1498           SALOMEDS::SObject_var aNewSubSO;
1499           if (!CORBA::is_nil(theNewSO)) {
1500               // Publish the sub-shape
1501             TCollection_AsciiString aSubName;
1502             if (theAddPrefix) {
1503               aSubName = "from_";
1504             }
1505             aSubName += anArgName;
1506             aNewSubSO = aStudyBuilder->NewObject(theNewSO);
1507             aNewSubSO = PublishInStudy(aNewSubSO, aNewSubO, aSubName.ToCString());
1508             // Restore color
1509             aNewSubO->SetColor(anOldSubO->GetColor());
1510             // set the texture
1511             if (aNewSubO->GetShapeType() == GEOM::VERTEX) {
1512               aNewSubO->SetMarkerStd(anOldSubO->GetMarkerType(), anOldSubO->GetMarkerSize());
1513               if (anOldSubO->GetMarkerType() == GEOM::MT_USER)
1514                 aNewSubO->SetMarkerTexture(anOldSubO->GetMarkerTexture());
1515             }
1516             // reference to arg
1517             SALOMEDS::SObject_wrap aReferenceSO = aStudyBuilder->NewObject( aNewSubSO );
1518             aStudyBuilder->Addreference( aReferenceSO, anOldSubSO );
1519             useCaseBuilder->AppendTo( theNewSO, aReferenceSO );
1520           }
1521           // Restore published sub-shapes of the argument
1522           GEOM::ListOfGO_var aSubParts;
1523           if (theFindMethod == GEOM::FSM_GetInPlaceByHistory)
1524             // pass the main shape as Object, because only it has the history
1525             aSubParts = RestoreSubShapesOneLevel(anOldSubSO, aNewSubSO,
1526                                                  theNewO, theOutArgs, theFindMethod, theAddPrefix);
1527           else
1528             aSubParts = RestoreSubShapesOneLevel(anOldSubSO, aNewSubSO,
1529                                                  aNewSubO, theOutArgs, theFindMethod, theAddPrefix);
1530           // add to parts list
1531           addToListOfGO( aSubParts, aNewParts );
1532         }
1533         else { // GetInPlace failed, try to build from published parts
1534           SALOMEDS::SObject_var aNewSubSO;
1535           if (!CORBA::is_nil(theNewSO))
1536           {
1537             aNewSubSO = aStudyBuilder->NewObject(theNewSO);
1538             useCaseBuilder->AppendTo( theNewSO, aNewSubSO );
1539           }
1540           // Restore published sub-shapes of the argument
1541           GEOM::ListOfGO_var aSubParts =
1542             RestoreSubShapesOneLevel(anOldSubSO, aNewSubSO,
1543                                      theNewO, theOutArgs, theFindMethod, theAddPrefix);
1544           // add to parts list
1545           addToListOfGO( aSubParts, aNewParts );
1546
1547           if (aSubParts->length() > 0) {
1548             // remember restored objects for Python Dump
1549             addToListOfGO(anOldSubO, theOutArgs);
1550
1551             // try to build an object from a set of its sub-shapes,
1552             // that published and will be reconstructed
1553             if (aSubParts->length() > 1) {
1554               aNewSubO = aShapesOp->MakeCompound(aSubParts);
1555               // add to parts list
1556               addToListOfGO( aNewSubO, aNewParts );
1557             }
1558             else {
1559               aNewSubO = aSubParts[0];
1560             }
1561
1562             if (!CORBA::is_nil(aNewSubO)) {
1563               // add the part to the list
1564               aSubParts[i] = aNewSubO;
1565               i++;
1566
1567               // Publish the sub-shape
1568               if (!CORBA::is_nil(aNewSubSO)) {
1569                 TCollection_AsciiString aSubName;
1570                 if (theAddPrefix) {
1571                   aSubName = "from_parts_of_";
1572                 }
1573                 aSubName += anArgName;
1574                 aNewSubSO = PublishInStudy(aNewSubSO, aNewSubO, aSubName.ToCString());
1575                 // Restore color
1576                 aNewSubO->SetColor(anOldSubO->GetColor());
1577                 // set the texture
1578                 if (aNewSubO->GetShapeType() == GEOM::VERTEX) {
1579                   aNewSubO->SetMarkerStd(anOldSubO->GetMarkerType(), anOldSubO->GetMarkerSize());
1580                   if (anOldSubO->GetMarkerType() == GEOM::MT_USER)
1581                     aNewSubO->SetMarkerTexture(anOldSubO->GetMarkerTexture());
1582                 }
1583               }
1584             }
1585           }
1586           else if (!CORBA::is_nil(aNewSubSO)) {
1587             // remove created aSubSO, because no parts have been found
1588             aStudyBuilder->RemoveObject(aNewSubSO);
1589           }
1590         } // try to build from published parts
1591       }
1592     }
1593   } // iterate on published sub-shapes
1594
1595   aParts->length(i);
1596   // add to parts list
1597   addToListOfGO( aNewParts, aParts );
1598   return aParts._retn();
1599 }
1600
1601 //============================================================================
1602 // function : RestoreGivenSubShapes
1603 // purpose  : Private method. Works only if both theObject and theSObject
1604 //            are defined, and does not check, if they correspond to each other.
1605 //            List theArgs in this case contains not only operation arguments,
1606 //            but also all subshapes, which must be published.
1607 //============================================================================
1608 GEOM::ListOfGO* GEOM_Gen_i::RestoreGivenSubShapes(GEOM::GEOM_Object_ptr   theObject,
1609                                                   SALOMEDS::SObject_ptr   theSObject,
1610                                                   const GEOM::ListOfGO&   theArgs,
1611                                                   GEOM::find_shape_method theFindMethod,
1612                                                   CORBA::Boolean          theInheritFirstArg,
1613                                                   CORBA::Boolean          theAddPrefix)
1614 {
1615   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
1616   SALOMEDS::Study_var aStudy = getStudyServant();
1617   //PTv, IMP 0020001, The salome object <theSObject>
1618   //     is not obligatory in case of invocation from script
1619   if (CORBA::is_nil(aStudy) || CORBA::is_nil(theObject) /*|| CORBA::is_nil(theSObject)*/)
1620     return aParts._retn();
1621
1622   // If theArgs list is empty, nothing to do
1623   Standard_Integer aLength = theArgs.length();
1624   if (aLength == 0)
1625     return aParts._retn();
1626
1627   // Get all arguments
1628   GEOM::ListOfGBO_var anOpArgsList = theObject->GetDependency();
1629   Standard_Integer    nbOpArgs     = anOpArgsList->length();
1630   Standard_Integer    nbArgsActual = nbOpArgs;
1631
1632   // If anOpArgsList list is empty, nothing to do
1633   if (nbArgsActual == 0)
1634     return aParts._retn();
1635
1636   // Entries of arguments and subshapes
1637   std::set<std::string> anArgs;
1638   for (int i = 0; i < aLength; i++) {
1639     CORBA::String_var anEntry = theArgs[i]->GetEntry();
1640     anArgs.insert(anEntry.in());
1641   }
1642
1643   // Arguments to be published
1644   // We try to publish all arguments, that are in theArgs list
1645   GEOM::ListOfGO_var aList = new GEOM::ListOfGO;
1646   aList->length(nbArgsActual);
1647
1648   int k = 0;
1649   for (int j = 0; j < nbArgsActual; j++) {
1650     CORBA::String_var anEntry = anOpArgsList[j]->GetEntry();
1651     if (anArgs.count(anEntry.in())) {
1652       aList[k] = GEOM::GEOM_Object::_narrow(anOpArgsList[j]);
1653       k++;
1654     }
1655   }
1656   nbArgsActual = k;
1657   //aList->length(nbArgsActual);
1658
1659   if (nbArgsActual < 1)
1660     return aParts._retn();
1661
1662   if (theInheritFirstArg || (nbOpArgs == 1)) {
1663     // Do not publish argument's reflection,
1664     // but only reconstruct its published sub-shapes
1665
1666     CORBA::String_var anIOR = _orb->object_to_string(aList[0]);
1667     SALOMEDS::SObject_var anArgSO = aStudy->FindObjectIOR(anIOR.in());
1668
1669     aParts = RestoreGivenSubShapesOneLevel(anArgSO, theSObject, theObject,
1670                                            anArgs, theFindMethod, theAddPrefix);
1671
1672     // set the color of the transformed shape to the color of initial shape
1673     theObject->SetColor(aList[0]->GetColor());
1674     // set the texture
1675     if (theObject->GetShapeType() == GEOM::VERTEX) {
1676       theObject->SetMarkerStd(aList[0]->GetMarkerType(), aList[0]->GetMarkerSize());
1677       if (aList[0]->GetMarkerType() == GEOM::MT_USER)
1678         theObject->SetMarkerTexture(aList[0]->GetMarkerTexture());
1679     }
1680
1681     anArgSO->UnRegister();
1682   }
1683   else {
1684     // Get interface, containing method, which we will use to reconstruct sub-shapes
1685     GEOM::GEOM_IShapesOperations_var  aShapesOp = GetIShapesOperations();
1686     GEOM::GEOM_IGroupOperations_var    aGroupOp = GetIGroupOperations();
1687     GEOM::GEOM_ITransformOperations_var aTrsfOp = GetITransformOperations();
1688
1689     PortableServer::Servant aServant = _poa->reference_to_servant(aTrsfOp.in());
1690     GEOM_ITransformOperations_i*      aTrsfOpSv = dynamic_cast<GEOM_ITransformOperations_i*>(aServant);
1691
1692     // Reconstruct arguments and tree of sub-shapes of the arguments
1693     CORBA::String_var anIOR;
1694     SALOMEDS::StudyBuilder_var      aStudyBuilder = aStudy->NewBuilder();
1695     SALOMEDS::UseCaseBuilder_wrap  useCaseBuilder = aStudy->GetUseCaseBuilder();
1696     for (Standard_Integer i = 0; i < nbArgsActual; i++)
1697     {
1698       GEOM::GEOM_Object_var anArgO = aList[i];
1699       if (!CORBA::is_nil(anArgO)) {
1700         anIOR = _orb->object_to_string(anArgO);
1701         SALOMEDS::SObject_var anArgSO = aStudy->FindObjectIOR(anIOR.in());
1702         TCollection_AsciiString anArgName;
1703         if (CORBA::is_nil(anArgSO)) {
1704           anArgName = "arg_";
1705           anArgName += TCollection_AsciiString(i);
1706         }
1707         else {
1708           anArgName = anArgSO->GetName();
1709         }
1710
1711         // Find a sub-shape of theObject in place of the argument
1712         GEOM::GEOM_Object_var aSubO;
1713         switch (theFindMethod) {
1714         case GEOM::FSM_GetInPlace:
1715           {
1716             // Use GetInPlace
1717             aSubO = aShapesOp->GetInPlace(theObject, anArgO);
1718           }
1719           break;
1720         case GEOM::FSM_MultiTransformed:
1721           {
1722             // Only for Multi-transformations
1723             GEOM::GEOM_Object_var anArgOTrsf = aTrsfOpSv->TransformLikeOtherCopy(anArgO, theObject);
1724             if (!CORBA::is_nil(anArgOTrsf)) {
1725               CORBA::String_var anArgOTrsfEntry = anArgOTrsf->GetEntry();
1726               Handle(::GEOM_BaseObject) anArgOTrsfImpl = _impl->GetObject(anArgOTrsfEntry);
1727               Handle(::GEOM_Function) anArgOTrsfFun = anArgOTrsfImpl->GetLastFunction();
1728               anArgOTrsfFun->SetDescription("");
1729               aSubO = aShapesOp->GetInPlace(theObject, anArgOTrsf);
1730             }
1731           }
1732           break;
1733         case GEOM::FSM_Transformed:
1734           {
1735             // transformation, cannot use GetInPlace, operate with indices
1736             GEOM::ListOfLong_var anIDs = anArgO->GetSubShapeIndices();
1737             if (anIDs->length() > 1) {
1738               // group
1739               aSubO = aGroupOp->CreateGroup(theObject, aGroupOp->GetType(anArgO));
1740               if (!CORBA::is_nil(aSubO))
1741                 aGroupOp->UnionIDs(aSubO, anIDs);
1742             }
1743             else if (anIDs->length() > 0) {
1744               // single sub-shape
1745               aSubO = aShapesOp->GetSubShape(theObject, anIDs[0]);
1746             }
1747           }
1748           break;
1749         case GEOM::FSM_GetSame:
1750           {
1751             // Use GetSame
1752             aSubO = aShapesOp->GetSame(theObject, anArgO);
1753           }
1754           break;
1755         case GEOM::FSM_GetShapesOnShape:
1756           {
1757             // Use GetShapesOnShape. Can work only on solids, so it has sense to search only solids
1758             aSubO = aShapesOp->GetShapesOnShapeAsCompound(anArgO, theObject,
1759               (short)GEOM::SOLID, GEOM::ST_ONIN);
1760           }
1761           break;
1762         case GEOM::FSM_GetInPlaceByHistory:
1763           {
1764             // Use GetInPlaceByHistory
1765             aSubO = aShapesOp->GetInPlaceByHistory(theObject, anArgO);
1766           }
1767           break;
1768         default:
1769           {}
1770         }
1771
1772         if (!CORBA::is_nil(aSubO)) {
1773           // add to parts list
1774           addToListOfGO( aSubO, aParts );
1775
1776           // Publish the sub-shape
1777           SALOMEDS::SObject_var aSubSO;
1778           if (!CORBA::is_nil(theSObject)) {
1779             TCollection_AsciiString aSubName;
1780             if (theAddPrefix) {
1781               aSubName = "from_";
1782             }
1783             aSubName += anArgName;
1784             aSubSO = aStudyBuilder->NewObject(theSObject);
1785             aSubSO = PublishInStudy(aSubSO, aSubO, aSubName.ToCString());
1786             // Restore color
1787             aSubO->SetColor(anArgO->GetColor());
1788             // set the texture
1789             if (aSubO->GetShapeType() == GEOM::VERTEX) {
1790               aSubO->SetMarkerStd(anArgO->GetMarkerType(), anArgO->GetMarkerSize());
1791               if (anArgO->GetMarkerType() == GEOM::MT_USER)
1792                 aSubO->SetMarkerTexture(anArgO->GetMarkerTexture());
1793             }
1794           }
1795
1796           if (!CORBA::is_nil(anArgSO)) {
1797             // Restore published sub-shapes of the argument
1798             GEOM::ListOfGO_var aSubParts;
1799             if (theFindMethod == GEOM::FSM_GetInPlaceByHistory)
1800               // pass theObject, because only it has the history
1801               aSubParts = RestoreGivenSubShapesOneLevel(anArgSO, aSubSO,
1802                                                         theObject, anArgs, theFindMethod, theAddPrefix);
1803             else
1804               aSubParts = RestoreGivenSubShapesOneLevel(anArgSO, aSubSO,
1805                                                         aSubO, anArgs, theFindMethod, theAddPrefix);
1806             // add to parts list
1807             addToListOfGO( aSubParts, aParts );
1808           }
1809         }
1810         else { // GetInPlace failed, try to build from published parts
1811           if (!CORBA::is_nil(anArgSO)) {
1812             SALOMEDS::SObject_var aSubSO;
1813             if (!CORBA::is_nil(theSObject))
1814             {
1815               aSubSO = aStudyBuilder->NewObject(theSObject);
1816               useCaseBuilder->AppendTo( theSObject, aSubSO );
1817             }
1818             // Restore published sub-shapes of the argument
1819             GEOM::ListOfGO_var aSubParts =
1820               RestoreGivenSubShapesOneLevel(anArgSO, aSubSO,
1821                                             theObject, anArgs, theFindMethod, theAddPrefix);
1822
1823             // add to parts list
1824             addToListOfGO( aSubParts, aParts );
1825
1826             if (aSubParts->length() > 0) {
1827               // try to build an argument from a set of its sub-shapes,
1828               // that published and will be reconstructed
1829               if (aSubParts->length() > 1) {
1830                 aSubO = aShapesOp->MakeCompound(aSubParts);
1831                 // add to parts list
1832                 addToListOfGO( aSubO, aParts );
1833               }
1834               else {
1835                 aSubO = aSubParts[0];
1836               }
1837               if (!CORBA::is_nil(aSubO) && !CORBA::is_nil(aSubSO)) {
1838                 // Publish the sub-shape
1839                 TCollection_AsciiString aSubName;
1840                 if (theAddPrefix) {
1841                   aSubName = "from_parts_of_";
1842                 }
1843                 aSubName += anArgName;
1844                 aSubSO = PublishInStudy(aSubSO, aSubO, aSubName.ToCString());
1845                 // Restore color
1846                 aSubO->SetColor(anArgO->GetColor());
1847                 // set the texture
1848                 if (aSubO->GetShapeType() == GEOM::VERTEX) {
1849                   aSubO->SetMarkerStd(anArgO->GetMarkerType(), anArgO->GetMarkerSize());
1850                   if (anArgO->GetMarkerType() == GEOM::MT_USER)
1851                     aSubO->SetMarkerTexture(anArgO->GetMarkerTexture());
1852                 }
1853               }
1854             }
1855             else if (!CORBA::is_nil(aSubSO)) {
1856               // remove created aSubSO, because no parts have been found
1857               aStudyBuilder->RemoveObject(aSubSO);
1858             }
1859           }
1860         } // try to build from published parts
1861         anArgSO->UnRegister();
1862       }
1863     } // process arguments
1864   }
1865   std::set<std::string> anObjEntryMap;
1866   GEOM::ListOfGO_var aResParts = new GEOM::ListOfGO;
1867   int nbRes = 0;
1868   int nb = aParts->length();
1869   aResParts->length(nb);
1870   if (nb > 0)
1871   {
1872     Handle(::GEOM_BaseObject) aMainObj = _impl->GetObject(theObject->GetEntry());
1873     Handle(::GEOM_Function) aFunction = aMainObj->GetLastFunction();
1874     GEOM::TPythonDump pd (aFunction, true);
1875     pd <<"[";
1876     int i = 0, j = 0;
1877     for ( ; i < nb; i++ )
1878     {
1879       GEOM::GEOM_Object_var anObj = GEOM::GEOM_Object::_duplicate( aParts[ i ] );
1880       if (CORBA::is_nil(anObj))
1881         continue;
1882       char* anEntry = anObj->GetEntry();
1883       if (anObjEntryMap.count(anEntry))
1884         continue; // already treated
1885       anObjEntryMap.insert(anEntry);
1886       aResParts[nbRes++] = anObj;
1887       // clear python dump of object
1888       Handle(::GEOM_BaseObject) aGeomObj = _impl->GetObject(anEntry);
1889       Handle(::GEOM_Function)   anObjFun = aGeomObj->GetLastFunction();
1890       if ( !anObjFun.IsNull() )
1891         anObjFun->SetDescription( "" );
1892       if ( j > 0 )
1893         pd << ", ";
1894       pd << aGeomObj;
1895       j++;
1896     }
1897     pd <<"]" << " = geompy.RestoreGivenSubShapes(" << aMainObj << ", " << "[";
1898     i = 0; nb = theArgs.length(); j = 0;
1899     for ( ; i < nb; i++ )
1900     {
1901       GEOM::GEOM_Object_var anObj = theArgs[ i ];
1902       if (CORBA::is_nil(anObj))
1903         continue;
1904       Handle(::GEOM_BaseObject) aGeomObj = _impl->GetObject(anObj->GetEntry());
1905       if ( j > 0 )
1906         pd << ", ";
1907       pd << aGeomObj;
1908       j++;
1909     }
1910     pd <<"]" << ", " <<"GEOM.";
1911     switch (theFindMethod) {
1912     case GEOM::FSM_GetInPlace:
1913       pd << "FSM_GetInPlace"; break;
1914     case GEOM::FSM_MultiTransformed:
1915       pd << "FSM_MultiTransformed"; break;
1916     case GEOM::FSM_Transformed:
1917       pd << "FSM_Transformed"; break;
1918     case GEOM::FSM_GetSame:
1919       pd << "FSM_GetSame"; break;
1920     case GEOM::FSM_GetShapesOnShape:
1921       pd << "FSM_GetShapesOnShape"; break;
1922     case GEOM::FSM_GetInPlaceByHistory:
1923     default:
1924       pd << "FSM_GetInPlaceByHistory"; break;
1925     }
1926     pd << ", " << theInheritFirstArg << ", " << theAddPrefix << ")";
1927   }
1928   aResParts->length(nbRes);
1929   return aResParts._retn();
1930 }
1931
1932 //============================================================================
1933 // function : RestoreGivenSubShapesOneLevel
1934 // purpose  : Private method
1935 //============================================================================
1936 GEOM::ListOfGO* GEOM_Gen_i::RestoreGivenSubShapesOneLevel (SALOMEDS::SObject_ptr   theOldSO,
1937                                                            SALOMEDS::SObject_ptr   theNewSO,
1938                                                            GEOM::GEOM_Object_ptr   theNewO,
1939                                                            std::set<std::string>   theArgs,
1940                                                            GEOM::find_shape_method theFindMethod,
1941                                                            CORBA::Boolean          theAddPrefix)
1942 {
1943   int i = 0;
1944   SALOMEDS::Study_var aStudy = getStudyServant();
1945   GEOM::ListOfGO_var aParts = new GEOM::ListOfGO;
1946   GEOM::ListOfGO_var aNewParts = new GEOM::ListOfGO;
1947   if (CORBA::is_nil(aStudy) || CORBA::is_nil(theOldSO) ||
1948       CORBA::is_nil(theNewO) /*|| CORBA::is_nil(theNewSO)*/)
1949     return aParts._retn();
1950
1951   SALOMEDS::StudyBuilder_var      aStudyBuilder = aStudy->NewBuilder();
1952   SALOMEDS::UseCaseBuilder_wrap  useCaseBuilder = aStudy->GetUseCaseBuilder();
1953
1954   // Get interface, containing method, which we will use to reconstruct sub-shapes
1955   GEOM::GEOM_IShapesOperations_var  aShapesOp = GetIShapesOperations();
1956   GEOM::GEOM_IGroupOperations_var    aGroupOp = GetIGroupOperations();
1957   GEOM::GEOM_ITransformOperations_var aTrsfOp = GetITransformOperations();
1958
1959   PortableServer::Servant aServant = _poa->reference_to_servant(aTrsfOp.in());
1960   GEOM_ITransformOperations_i*      aTrsfOpSv = dynamic_cast<GEOM_ITransformOperations_i*>(aServant);
1961
1962   // Reconstruct published sub-shapes
1963   SALOMEDS::ChildIterator_var it = aStudy->NewChildIterator(theOldSO);
1964
1965   int aLen = 0;
1966   for (it->Init(); it->More(); it->Next()) {
1967     aLen++;
1968   }
1969   aParts->length(aLen);
1970
1971   for (it->Init(); it->More(); it->Next()) {
1972     SALOMEDS::SObject_var anOldSubSO = it->Value();
1973
1974     TCollection_AsciiString anArgName = anOldSubSO->GetName();
1975
1976     SALOMEDS::GenericAttribute_var anAttr;
1977     if (anOldSubSO->FindAttribute(anAttr, "AttributeIOR")) {
1978       SALOMEDS::AttributeIOR_var anAttrIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
1979       GEOM::GEOM_Object_var anOldSubO =
1980         GEOM::GEOM_Object::_narrow(_orb->string_to_object(anAttrIOR->Value()));
1981
1982       bool okToContinue = false;
1983
1984       if (!CORBA::is_nil(anOldSubO)) {
1985         CORBA::String_var anEntry = anOldSubO->GetEntry();
1986         okToContinue = theArgs.count(anEntry.in());
1987       }
1988
1989       if (okToContinue) {
1990         // Find a sub-shape of theNewO in place of anOldSubO
1991         GEOM::GEOM_Object_var aNewSubO;
1992         switch (theFindMethod) {
1993         case GEOM::FSM_GetInPlace:
1994           {
1995             // Use GetInPlace
1996             aNewSubO = aShapesOp->GetInPlace(theNewO, anOldSubO);
1997           }
1998           break;
1999         case GEOM::FSM_MultiTransformed:
2000           {
2001             // Only for Multi-transformations
2002             GEOM::GEOM_Object_var anArgOTrsf = aTrsfOpSv->TransformLikeOtherCopy(anOldSubO, theNewO);
2003             if (!CORBA::is_nil(anArgOTrsf)) {
2004               CORBA::String_var anArgOTrsfEntry = anArgOTrsf->GetEntry();
2005               Handle(::GEOM_BaseObject) anArgOTrsfImpl = _impl->GetObject(anArgOTrsfEntry);
2006               Handle(::GEOM_Function) anArgOTrsfFun = anArgOTrsfImpl->GetLastFunction();
2007               anArgOTrsfFun->SetDescription("");
2008               aNewSubO = aShapesOp->GetInPlace(theNewO, anArgOTrsf);
2009             }
2010           }
2011           break;
2012         case GEOM::FSM_Transformed:
2013           {
2014             // transformation, cannot use GetInPlace, operate with indices
2015             GEOM::ListOfLong_var anIDs = anOldSubO->GetSubShapeIndices();
2016             if (anIDs->length() > 1) {
2017               // group
2018               aNewSubO = aGroupOp->CreateGroup(theNewO, aGroupOp->GetType(anOldSubO));
2019               if (!CORBA::is_nil(aNewSubO))
2020                 aGroupOp->UnionIDs(aNewSubO, anIDs);
2021             }
2022             else {
2023               // single sub-shape
2024               aNewSubO = aShapesOp->GetSubShape(theNewO, anIDs[0]);
2025             }
2026           }
2027           break;
2028         case GEOM::FSM_GetSame:
2029           {
2030             // Use GetSame
2031             aNewSubO = aShapesOp->GetSame(theNewO, anOldSubO);
2032           }
2033           break;
2034         case GEOM::FSM_GetShapesOnShape:
2035           {
2036             // Use GetShapesOnShape. Can work only on solids, so it has sense to search only solids
2037             aNewSubO = aShapesOp->GetShapesOnShapeAsCompound(anOldSubO, theNewO,
2038                                                              (short)GEOM::SOLID, GEOM::ST_ONIN);
2039           }
2040           break;
2041         case GEOM::FSM_GetInPlaceByHistory:
2042           {
2043             // Use GetInPlaceByHistory
2044             aNewSubO = aShapesOp->GetInPlaceByHistory(theNewO, anOldSubO);
2045           }
2046           break;
2047         default:
2048           {}
2049         }
2050
2051         if (!CORBA::is_nil(aNewSubO)) {
2052           // add the part to the list
2053           aParts[i] = aNewSubO;
2054           i++;
2055           // add to parts list
2056           addToListOfGO( aNewSubO, aNewParts );
2057
2058           SALOMEDS::SObject_var aNewSubSO;
2059           if (!CORBA::is_nil(theNewSO)) {
2060               // Publish the sub-shape
2061             TCollection_AsciiString aSubName;
2062             if (theAddPrefix) {
2063               aSubName = "from_";
2064             }
2065             aSubName += anArgName;
2066             aNewSubSO = aStudyBuilder->NewObject(theNewSO);
2067             aNewSubSO = PublishInStudy(aNewSubSO, aNewSubO, aSubName.ToCString());
2068             // Restore color
2069             aNewSubO->SetColor(anOldSubO->GetColor());
2070             // set the texture
2071             if (aNewSubO->GetShapeType() == GEOM::VERTEX) {
2072               aNewSubO->SetMarkerStd(anOldSubO->GetMarkerType(), anOldSubO->GetMarkerSize());
2073               if (anOldSubO->GetMarkerType() == GEOM::MT_USER)
2074                 aNewSubO->SetMarkerTexture(anOldSubO->GetMarkerTexture());
2075             }
2076             // reference to arg
2077             SALOMEDS::SObject_wrap aReferenceSO = aStudyBuilder->NewObject( aNewSubSO );
2078             aStudyBuilder->Addreference( aReferenceSO, anOldSubSO );
2079             useCaseBuilder->AppendTo( theNewSO, aReferenceSO );
2080           }
2081           // Restore published sub-shapes of the argument
2082           GEOM::ListOfGO_var aSubParts;
2083           if (theFindMethod == GEOM::FSM_GetInPlaceByHistory)
2084             // pass the main shape as Object, because only it has the history
2085             aSubParts = RestoreGivenSubShapesOneLevel(anOldSubSO, aNewSubSO,
2086                                                       theNewO, theArgs, theFindMethod, theAddPrefix);
2087           else
2088             aSubParts = RestoreGivenSubShapesOneLevel(anOldSubSO, aNewSubSO,
2089                                                       aNewSubO, theArgs, theFindMethod, theAddPrefix);
2090           // add to parts list
2091           addToListOfGO( aSubParts, aNewParts );
2092         }
2093         else { // GetInPlace failed, try to build from published parts
2094           SALOMEDS::SObject_var aNewSubSO;
2095           if (!CORBA::is_nil(theNewSO))
2096           {
2097             aNewSubSO = aStudyBuilder->NewObject(theNewSO);
2098             useCaseBuilder->AppendTo( theNewSO, aNewSubSO );
2099           }
2100           // Restore published sub-shapes of the argument
2101           GEOM::ListOfGO_var aSubParts =
2102             RestoreGivenSubShapesOneLevel(anOldSubSO, aNewSubSO,
2103                                           theNewO, theArgs, theFindMethod, theAddPrefix);
2104           // add to parts list
2105           addToListOfGO( aSubParts, aNewParts );
2106
2107           if (aSubParts->length() > 0) {
2108             // try to build an object from a set of its sub-shapes,
2109             // that published and will be reconstructed
2110             if (aSubParts->length() > 1) {
2111               aNewSubO = aShapesOp->MakeCompound(aSubParts);
2112               // add to parts list
2113               addToListOfGO( aNewSubO, aNewParts );
2114             }
2115             else {
2116               aNewSubO = aSubParts[0];
2117             }
2118
2119             if (!CORBA::is_nil(aNewSubO)) {
2120               // add the part to the list
2121               aSubParts[i] = aNewSubO;
2122               i++;
2123
2124               // Publish the sub-shape
2125               if (!CORBA::is_nil(aNewSubSO)) {
2126                 TCollection_AsciiString aSubName;
2127                 if (theAddPrefix) {
2128                   aSubName = "from_parts_of_";
2129                 }
2130                 aSubName += anArgName;
2131                 aNewSubSO = PublishInStudy(aNewSubSO, aNewSubO, aSubName.ToCString());
2132                 // Restore color
2133                 aNewSubO->SetColor(anOldSubO->GetColor());
2134                 // set the texture
2135                 if (aNewSubO->GetShapeType() == GEOM::VERTEX) {
2136                   aNewSubO->SetMarkerStd(anOldSubO->GetMarkerType(), anOldSubO->GetMarkerSize());
2137                   if (anOldSubO->GetMarkerType() == GEOM::MT_USER)
2138                     aNewSubO->SetMarkerTexture(anOldSubO->GetMarkerTexture());
2139                 }
2140               }
2141             }
2142           }
2143           else if (!CORBA::is_nil(aNewSubSO)) {
2144             // remove created aSubSO, because no parts have been found
2145             aStudyBuilder->RemoveObject(aNewSubSO);
2146           }
2147         } // try to build from published parts
2148       }
2149     }
2150   } // iterate on published sub-shapes
2151
2152   aParts->length(i);
2153   // add to parts list
2154   addToListOfGO( aNewParts, aParts );
2155   return aParts._retn();
2156 }
2157
2158 //============================================================================
2159 // function : register()
2160 // purpose  : register 'name' in 'name_service'
2161 //============================================================================
2162 void GEOM_Gen_i::register_name(char * name)
2163 {
2164   GEOM::GEOM_Gen_var g = _this();
2165   name_service->Register(g, name);
2166 }
2167
2168 //============================================================================
2169 // function : getStudyServant()
2170 // purpose  : Get Study
2171 //============================================================================
2172 SALOMEDS::Study_var GEOM_Gen_i::getStudyServant()
2173 {
2174   static SALOMEDS::Study_var aStudy;
2175   if(CORBA::is_nil(aStudy)){
2176     CORBA::Object_ptr anObject = name_service->Resolve("/Study");
2177     aStudy = SALOMEDS::Study::_narrow(anObject);
2178   }
2179   return aStudy;
2180 }
2181
2182 //============================================================================
2183 // function : findOrCreateComponent()
2184 // purpose  : Find root study component; create if it does not exist
2185 //============================================================================
2186 SALOMEDS::SComponent_var GEOM_Gen_i::findOrCreateComponent()
2187 {
2188   SALOMEDS::SComponent_var aComponent;
2189
2190   SALOMEDS::Study_var aStudy = getStudyServant();
2191   if (aStudy->_is_nil()) return aComponent;
2192
2193   SALOMEDS::GenericAttribute_var anAttr;
2194   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
2195   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
2196
2197   aComponent = aStudy->FindComponent(ComponentDataType());
2198   if (aComponent->_is_nil()) {
2199     aComponent = aStudyBuilder->NewComponent(ComponentDataType());
2200     anAttr = aStudyBuilder->FindOrCreateAttribute(aComponent.in(), "AttributeName");
2201     SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
2202     aName->SetValue("Geometry");
2203     aName->UnRegister();
2204     anAttr = aStudyBuilder->FindOrCreateAttribute(aComponent.in(), "AttributePixMap");
2205     SALOMEDS::AttributePixMap_var aPixMap=SALOMEDS::AttributePixMap::_narrow(anAttr);
2206     aPixMap->SetPixMap("ICON_OBJBROWSER_Geometry");
2207     aPixMap->UnRegister();
2208     aStudyBuilder->DefineComponentInstance(aComponent.in(), (GEOM::GEOM_Gen_var)GEOM_Gen::_this());
2209     // add component to the use case tree
2210     // (to support tree representation customization and drag-n-drop)
2211     useCaseBuilder->SetRootCurrent();
2212     useCaseBuilder->Append(aComponent.in()); // component object is added as the top level item
2213   }
2214   return aComponent;
2215 }
2216
2217 //============================================================================
2218 // function : Undo
2219 // purpose  :
2220 //============================================================================
2221 void GEOM_Gen_i::Undo()
2222 {
2223   _impl->Undo();
2224 }
2225
2226 //============================================================================
2227 // function : Redo
2228 // purpose  :
2229 //============================================================================
2230 void GEOM_Gen_i::Redo()
2231 {
2232   _impl->Redo();
2233 }
2234
2235 //============================================================================
2236 // function : GetIBasicOperations
2237 // purpose  :
2238 //============================================================================
2239 GEOM::GEOM_IBasicOperations_ptr GEOM_Gen_i::GetIBasicOperations()
2240 {
2241   Unexpect aCatch(SALOME_SalomeException);
2242   MESSAGE( "GEOM_Gen_i::GetIBasicOperations" );
2243
2244   GEOM::GEOM_Gen_ptr engine = _this();
2245
2246   //transfer reference on engine
2247   GEOM_IBasicOperations_i* aServant =
2248     new GEOM_IBasicOperations_i(_poa, engine, _impl->GetIBasicOperations());
2249
2250   PortableServer::ObjectId_var id = _poa->activate_object(aServant);
2251   // activate the CORBA servant
2252   GEOM::GEOM_IBasicOperations_var operations = aServant->_this();
2253   return operations._retn();
2254 }
2255
2256 //============================================================================
2257 // function : GetITransformOperations
2258 // purpose  :
2259 //============================================================================
2260 GEOM::GEOM_ITransformOperations_ptr GEOM_Gen_i::GetITransformOperations()
2261 {
2262   Unexpect aCatch(SALOME_SalomeException);
2263   MESSAGE( "GEOM_Gen_i::GetITransformOperations" );
2264
2265   GEOM::GEOM_Gen_ptr engine = _this();
2266
2267   GEOM_ITransformOperations_i* aServant =
2268     new GEOM_ITransformOperations_i(_poa, engine, _impl->GetITransformOperations());
2269
2270   // activate the CORBA servant
2271   GEOM::GEOM_ITransformOperations_var operations = aServant->_this();
2272   return operations._retn();
2273 }
2274
2275 //============================================================================
2276 // function : GetI3DPrimOperations
2277 // purpose  :
2278 //============================================================================
2279 GEOM::GEOM_I3DPrimOperations_ptr GEOM_Gen_i::GetI3DPrimOperations()
2280      
2281 {
2282   Unexpect aCatch(SALOME_SalomeException);
2283   MESSAGE( "GEOM_Gen_i::GetI3DPrimOperations" );
2284
2285   GEOM::GEOM_Gen_ptr engine = _this();
2286
2287   GEOM_I3DPrimOperations_i* aServant =
2288     new GEOM_I3DPrimOperations_i(_poa, engine, _impl->GetI3DPrimOperations());
2289   PortableServer::ObjectId_var id = _poa->activate_object(aServant);
2290
2291   // activate the CORBA servant
2292   GEOM::GEOM_I3DPrimOperations_var operations = aServant->_this();
2293   return operations._retn();
2294 }
2295
2296 //============================================================================
2297 // function : GetIShapesOperations
2298 // purpose  :
2299 //============================================================================
2300 GEOM::GEOM_IShapesOperations_ptr GEOM_Gen_i::GetIShapesOperations()
2301      
2302 {
2303   Unexpect aCatch(SALOME_SalomeException);
2304   MESSAGE( "GEOM_Gen_i::GetIShapesOperations" );
2305
2306   GEOM::GEOM_Gen_ptr engine = _this();
2307
2308   GEOM_IShapesOperations_i* aServant =
2309     new GEOM_IShapesOperations_i(_poa, engine, _impl->GetIShapesOperations());
2310
2311   // activate the CORBA servant
2312   GEOM::GEOM_IShapesOperations_var operations = aServant->_this();
2313   return operations._retn();
2314 }
2315
2316 //============================================================================
2317 // function : GetIBlocksOperations
2318 // purpose  :
2319 //============================================================================
2320 GEOM::GEOM_IBlocksOperations_ptr GEOM_Gen_i::GetIBlocksOperations()
2321      
2322 {
2323   Unexpect aCatch(SALOME_SalomeException);
2324   MESSAGE( "GEOM_Gen_i::GetIBlocksOperations" );
2325
2326   GEOM::GEOM_Gen_ptr engine = _this();
2327
2328   GEOM_IBlocksOperations_i* aServant =
2329     new GEOM_IBlocksOperations_i(_poa, engine, _impl->GetIBlocksOperations());
2330
2331   // activate the CORBA servant
2332   GEOM::GEOM_IBlocksOperations_var operations = aServant->_this();
2333   return operations._retn();
2334 }
2335
2336 //============================================================================
2337 // function : GetIBooleanOperations
2338 // purpose  :
2339 //============================================================================
2340 GEOM::GEOM_IBooleanOperations_ptr GEOM_Gen_i::GetIBooleanOperations()
2341      
2342 {
2343   Unexpect aCatch(SALOME_SalomeException);
2344   MESSAGE( "GEOM_Gen_i::GetIBooleanOperations" );
2345
2346   GEOM::GEOM_Gen_ptr engine = _this();
2347
2348   GEOM_IBooleanOperations_i* aServant =
2349     new GEOM_IBooleanOperations_i(_poa, engine, _impl->GetIBooleanOperations());
2350
2351   // activate the CORBA servant
2352   GEOM::GEOM_IBooleanOperations_var operations = aServant->_this();
2353   return operations._retn();
2354 }
2355
2356 //============================================================================
2357 // function : GetICurvesOperations
2358 // purpose  :
2359 //============================================================================
2360 GEOM::GEOM_ICurvesOperations_ptr GEOM_Gen_i::GetICurvesOperations()
2361      
2362 {
2363   Unexpect aCatch(SALOME_SalomeException);
2364   MESSAGE( "GEOM_Gen_i::GetICurvesOperations" );
2365
2366   GEOM::GEOM_Gen_ptr engine = _this();
2367
2368   GEOM_ICurvesOperations_i* aServant =
2369     new GEOM_ICurvesOperations_i(_poa, engine, _impl->GetICurvesOperations());
2370
2371   // activate the CORBA servant
2372   GEOM::GEOM_ICurvesOperations_var operations = aServant->_this();
2373   return operations._retn();
2374 }
2375
2376 //============================================================================
2377 // function : GetILocalOperations
2378 // purpose  :
2379 //============================================================================
2380 GEOM::GEOM_ILocalOperations_ptr GEOM_Gen_i::GetILocalOperations()
2381      
2382 {
2383   Unexpect aCatch(SALOME_SalomeException);
2384   MESSAGE( "GEOM_Gen_i::GetILocalOperations" );
2385
2386   GEOM::GEOM_Gen_ptr engine = _this();
2387
2388   GEOM_ILocalOperations_i* aServant =
2389     new GEOM_ILocalOperations_i(_poa, engine, _impl->GetILocalOperations());
2390
2391   // activate the CORBA servant
2392   GEOM::GEOM_ILocalOperations_var operations = aServant->_this();
2393   return operations._retn();
2394 }
2395
2396 //============================================================================
2397 // function : GetIHealingOperations
2398 // purpose  :
2399 //============================================================================
2400 GEOM::GEOM_IHealingOperations_ptr GEOM_Gen_i::GetIHealingOperations()
2401      
2402 {
2403   Unexpect aCatch(SALOME_SalomeException);
2404   MESSAGE( "GEOM_Gen_i::IHealingOperations" );
2405
2406   GEOM::GEOM_Gen_ptr engine = _this();
2407
2408   GEOM_IHealingOperations_i* aServant =
2409     new GEOM_IHealingOperations_i(_poa, engine, _impl->GetIHealingOperations());
2410
2411   // activate the CORBA servant
2412   GEOM::GEOM_IHealingOperations_var operations = aServant->_this();
2413   return operations._retn();
2414 }
2415
2416 //============================================================================
2417 // function : GetIInsertOperations
2418 // purpose  :
2419 //============================================================================
2420 GEOM::GEOM_IInsertOperations_ptr GEOM_Gen_i::GetIInsertOperations()
2421      
2422 {
2423   Unexpect aCatch(SALOME_SalomeException);
2424   MESSAGE( "GEOM_Gen_i::GetIInsertOperations" );
2425
2426   GEOM::GEOM_Gen_ptr engine = _this();
2427
2428   GEOM_IInsertOperations_i* aServant =
2429     new GEOM_IInsertOperations_i(_poa, engine, _impl->GetIInsertOperations());
2430
2431   // activate the CORBA servant
2432   GEOM::GEOM_IInsertOperations_var operations = aServant->_this();
2433   return operations._retn();
2434 }
2435
2436 //============================================================================
2437 // function : GetIMeasureOperations
2438 // purpose  :
2439 //============================================================================
2440 GEOM::GEOM_IMeasureOperations_ptr GEOM_Gen_i::GetIMeasureOperations()
2441      
2442 {
2443   Unexpect aCatch(SALOME_SalomeException);
2444   MESSAGE( "GEOM_Gen_i::GetIMeasureOperations" );
2445
2446   GEOM::GEOM_Gen_ptr engine = _this();
2447
2448   GEOM_IMeasureOperations_i* aServant =
2449     new GEOM_IMeasureOperations_i(_poa, engine, _impl->GetIMeasureOperations());
2450
2451   // activate the CORBA servant
2452   GEOM::GEOM_IMeasureOperations_var operations = aServant->_this();
2453   return operations._retn();
2454 }
2455
2456 //============================================================================
2457 // function : GetIGroupOperations
2458 // purpose  :
2459 //============================================================================
2460 GEOM::GEOM_IGroupOperations_ptr GEOM_Gen_i::GetIGroupOperations()
2461      
2462 {
2463   Unexpect aCatch(SALOME_SalomeException);
2464   MESSAGE( "GEOM_Gen_i::GetIGroupOperations" );
2465
2466   GEOM::GEOM_Gen_ptr engine = _this();
2467
2468   GEOM_IGroupOperations_i* aServant =
2469     new GEOM_IGroupOperations_i(_poa, engine, _impl->GetIGroupOperations());
2470
2471   // activate the CORBA servant
2472   GEOM::GEOM_IGroupOperations_var operations = aServant->_this();
2473   return operations._retn();
2474 }
2475
2476 //============================================================================
2477 // function : GetIFieldOperations
2478 // purpose  :
2479 //============================================================================
2480 GEOM::GEOM_IFieldOperations_ptr GEOM_Gen_i::GetIFieldOperations()
2481      
2482 {
2483   Unexpect aCatch(SALOME_SalomeException);
2484   MESSAGE( "GEOM_Gen_i::GetIFieldOperations" );
2485
2486   GEOM::GEOM_Gen_ptr engine = _this();
2487
2488   GEOM_IFieldOperations_i* aServant =
2489     new GEOM_IFieldOperations_i(_poa, engine, _impl->GetIFieldOperations());
2490
2491   // activate the CORBA servant
2492   GEOM::GEOM_IFieldOperations_var operations = aServant->_this();
2493   return operations._retn();
2494 }
2495
2496 //============================================================================
2497 // function : GetPluginOperations
2498 // purpose  :
2499 //============================================================================
2500 GEOM::GEOM_IOperations_ptr GEOM_Gen_i::GetPluginOperations(const char* theLibName)
2501      
2502 {
2503   Unexpect aCatch(SALOME_SalomeException);
2504   MESSAGE( "GEOM_Gen_i::GetPluginOperations" );
2505
2506   GEOM::GEOM_Gen_ptr engine = _this();
2507
2508   GEOM::GEOM_IOperations_var operations;
2509
2510   std::string aLibName = theLibName;
2511
2512   try {
2513     // load plugin library
2514     LoadPlugin(aLibName);
2515     // create a new operations object, store its ref. in engine
2516     if ( myOpCreatorMap.find(aLibName) != myOpCreatorMap.end() ) {
2517       GEOM_IOperations_i* aServant = 0;
2518       aServant = myOpCreatorMap[aLibName]->Create(_poa, engine, _impl);
2519       // activate the CORBA servant
2520       if (aServant)
2521         operations = aServant->_this();
2522     }
2523   }
2524   catch (SALOME_Exception& S_ex) {
2525     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2526   }
2527
2528   return operations._retn();
2529 }
2530
2531 //============================================================================
2532 // function : LoadPlugin
2533 // purpose  : load plugin library and retrieve an instance of operations creator
2534 //============================================================================
2535 void GEOM_Gen_i::LoadPlugin(const std::string& theLibName)
2536 {
2537   std::string aPlatformLibName;
2538 #if !defined(WIN32)
2539   aPlatformLibName = "lib";
2540 #endif
2541   aPlatformLibName += theLibName;
2542 #if defined(WIN32)
2543   aPlatformLibName += ".dll" ;
2544 #elif defined(__APPLE__)
2545   aPlatformLibName += ".dylib";
2546 #else
2547   aPlatformLibName += ".so";
2548 #endif
2549
2550   // check, if corresponding operations are already created
2551   if (myOpCreatorMap.find(theLibName) == myOpCreatorMap.end()) {
2552 #if WIN32
2553   #if UNICODE 
2554         std::wstring strL = Kernel_Utils::utf8_decode_s(aPlatformLibName);
2555     const wchar_t* aPath = strL.c_str();
2556   #else
2557     const char* aPath = aPlatformLibName.c_str();
2558   #endif
2559     // load plugin library
2560     LibHandle libHandle = LoadLib(aPath);
2561 #else
2562     LibHandle libHandle = LoadLib(aPlatformLibName.c_str());
2563 #endif
2564     if (!libHandle) {
2565       // report any error, if occurred
2566 #ifndef WIN32
2567       throw(SALOME_Exception(dlerror()));
2568 #else
2569       throw(SALOME_Exception(LOCALIZED( "Can't load server geometry plugin library" )));
2570 #endif
2571     }
2572
2573     // get method, returning operations creator
2574     typedef GEOM_GenericOperationsCreator* (*GetOperationsCreator)();
2575     GetOperationsCreator procHandle =
2576       (GetOperationsCreator)GetProc( libHandle, "GetOperationsCreator" );
2577     if (!procHandle) {
2578       UnLoadLib(libHandle);
2579       throw(SALOME_Exception(LOCALIZED("bad geometry plugin library")));
2580     }
2581
2582     // get operations creator
2583     GEOM_GenericOperationsCreator* aCreator = procHandle();
2584     if (aCreator) {
2585       // map operations creator to a plugin name
2586       myOpCreatorMap[theLibName] = aCreator;
2587     }
2588     else {
2589       throw(SALOME_Exception(LOCALIZED("bad geometry plugin library implementation")));
2590     }
2591   }
2592 }
2593
2594 //=============================================================================
2595 /*!
2596  *  AddSubShape
2597  */
2598 //=============================================================================
2599 GEOM::GEOM_Object_ptr GEOM_Gen_i::AddSubShape (GEOM::GEOM_Object_ptr   theMainShape,
2600                                                const GEOM::ListOfLong& theIndices)
2601 {
2602   if (CORBA::is_nil(theMainShape) || theIndices.length() < 1)
2603     return GEOM::GEOM_Object::_nil();
2604   CORBA::String_var entry = theMainShape->GetEntry();
2605   Handle(::GEOM_Object) aMainShape = Handle(::GEOM_Object)::DownCast
2606     ( _impl->GetObject( entry ));
2607   if (aMainShape.IsNull()) return GEOM::GEOM_Object::_nil();
2608
2609   Handle(TColStd_HArray1OfInteger) anArray = new TColStd_HArray1OfInteger(1, theIndices.length());
2610   for(CORBA::ULong i = 0; i<theIndices.length(); i++) anArray->SetValue(i+1, theIndices[i]);
2611
2612   Handle(::GEOM_Object) anObject = _impl->AddSubShape(aMainShape, anArray, true);
2613   if(anObject.IsNull()) return GEOM::GEOM_Object::_nil();
2614
2615   TCollection_AsciiString anEntry;
2616   TDF_Tool::Entry(anObject->GetEntry(), anEntry);
2617   return GEOM::GEOM_Object::_narrow( GetObject(anEntry.ToCString()));
2618 }
2619
2620 //=============================================================================
2621 /*!
2622  *  RemoveObject
2623  */
2624 //=============================================================================
2625 void GEOM_Gen_i::RemoveObject(GEOM::GEOM_BaseObject_ptr theObject)
2626 {
2627   CORBA::String_var anEntry = theObject->GetEntry();
2628   Handle(::GEOM_BaseObject) anObject = _impl->GetObject(anEntry, false);
2629   if (!anObject.IsNull())
2630     _impl->RemoveObject(anObject);
2631 }
2632
2633 //=================================================================================
2634 // function : GetStringFromIOR()
2635 // purpose  : returns a string that represents  a 'GEOM::GEOM_Object_var'
2636 //=================================================================================
2637 char* GEOM_Gen_i::GetStringFromIOR(GEOM::GEOM_Object_ptr theObject)
2638 {
2639   return _orb->object_to_string(theObject);
2640 }
2641
2642 //=================================================================================
2643 // function : GetIORFromString()
2644 // purpose  : returns a 'GEOM::GEOM_Object_var' from a string representing it
2645 //=================================================================================
2646 GEOM::GEOM_Object_ptr GEOM_Gen_i::GetIORFromString(const char* stringIOR) {
2647   GEOM::GEOM_Object_var aGeomObject;
2648   if(strcmp(stringIOR,"") != 0){
2649     CORBA::Object_var anObject = _orb->string_to_object(stringIOR);
2650     if(!CORBA::is_nil(anObject))
2651       aGeomObject =  GEOM::GEOM_Object::_narrow(anObject.in());
2652   }
2653   return aGeomObject._retn();
2654 }
2655
2656 //=================================================================================
2657 // function : GetObject()
2658 // purpose  :
2659 //=================================================================================
2660 GEOM::GEOM_BaseObject_ptr GEOM_Gen_i::GetObject (const char* theEntry)
2661 {
2662   GEOM::GEOM_BaseObject_var obj;
2663   Handle(::GEOM_BaseObject) handle_object = _impl->GetObject((char*)theEntry);
2664   if (handle_object.IsNull()) return obj._retn();
2665
2666   TCollection_AsciiString stringIOR = handle_object->GetIOR();
2667   if (stringIOR.Length() > 1) {
2668     CORBA::Object_var corba_object = _orb->string_to_object(stringIOR.ToCString());
2669     if (!CORBA::is_nil(corba_object)) obj = GEOM::GEOM_BaseObject::_narrow(corba_object);
2670     return obj._retn();
2671   }
2672
2673   GEOM::GEOM_Gen_ptr engine = _this();
2674   //transfer the reference to GEOM_Object_i
2675   GEOM_BaseObject_i* servant = 0;
2676   switch( handle_object->GetType() ) {
2677   case GEOM_FIELD: {
2678     servant = new GEOM_Field_i (_poa, engine, Handle(::GEOM_Field)::DownCast( handle_object ));
2679     break;
2680   }
2681   case GEOM_FIELD_STEP: {
2682     Handle(::GEOM_FieldStep) step = Handle(::GEOM_FieldStep)::DownCast( handle_object );
2683     Handle(::GEOM_Field)    field = step->GetField();
2684     int type = ( !field.IsNull() ? field->GetDataType() : 0 );
2685     switch( type ) {
2686     case GEOM::FDT_Bool:
2687       servant = new GEOM_BoolFieldStep_i (_poa, engine, step );
2688       break;
2689     case GEOM::FDT_Int:
2690       servant = new GEOM_IntFieldStep_i (_poa, engine, step );
2691       break;
2692     case GEOM::FDT_Double:
2693       servant = new GEOM_DoubleFieldStep_i (_poa, engine, step );
2694       break;
2695     default:
2696       servant = new GEOM_StringFieldStep_i (_poa, engine, step );
2697     }
2698     break;
2699   }
2700   default:
2701     servant = new GEOM_Object_i (_poa, engine, Handle(::GEOM_Object)::DownCast( handle_object ));
2702   }
2703   PortableServer::ObjectId_var id = _poa->activate_object(servant);
2704
2705   obj = servant->_this();
2706   CORBA::String_var objStr = _orb->object_to_string(obj);
2707   TCollection_AsciiString anAscii( (char *)objStr.in() );
2708   handle_object->SetIOR( anAscii );
2709   return obj._retn();
2710 }
2711
2712 //=================================================================================
2713 // function : hasObjectInfo()
2714 // purpose  : shows if module provides information for its objects
2715 //=================================================================================
2716 bool GEOM_Gen_i::hasObjectInfo()
2717 {
2718   return true;
2719 }
2720
2721 //=================================================================================
2722 // function : getObjectInfo()
2723 // purpose  : returns an information for a given object by its entry
2724 //=================================================================================
2725 char* GEOM_Gen_i::getObjectInfo(const char* entry)
2726 {
2727   GEOM::GEOM_Object_var aGeomObject;
2728
2729   SALOMEDS::SObject_var aSObj = getStudyServant()->FindObjectID( entry );
2730   SALOMEDS::SObject_var aResultSObj;
2731   if (aSObj->ReferencedObject(aResultSObj))
2732     aSObj = aResultSObj;
2733
2734   SALOMEDS::GenericAttribute_var anAttr;
2735   if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
2736     SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
2737     CORBA::String_var aVal = anIOR->Value();
2738     anIOR->UnRegister();
2739     CORBA::Object_var anObject = getStudyServant()->ConvertIORToObject(aVal);
2740     aGeomObject = GEOM::GEOM_Object::_narrow(anObject);
2741   }
2742   if (!aSObj->_is_nil() )
2743     aSObj->UnRegister();
2744
2745   const char* aTypeInfo = "Object";
2746   if ( !aGeomObject->_is_nil() ) {
2747     GEOM::GEOM_IKindOfShape::shape_kind aKind;
2748     GEOM::ListOfLong_var anInts;
2749     GEOM::ListOfDouble_var aDbls;
2750
2751     GEOM::GEOM_IMeasureOperations_var anOp = GetIMeasureOperations();
2752     aKind = anOp->KindOfShape( aGeomObject, anInts, aDbls );
2753
2754     if ( anOp->IsDone() ) {
2755       switch ( aKind ) {
2756       case GEOM::GEOM_IKindOfShape::COMPOUND:
2757         aTypeInfo = "Compound";
2758         break;
2759       case GEOM::GEOM_IKindOfShape::COMPSOLID:
2760         aTypeInfo = "CompSolid";
2761         break;
2762       case GEOM::GEOM_IKindOfShape::SHELL:
2763         aTypeInfo = "Shell";
2764         break;
2765       case GEOM::GEOM_IKindOfShape::WIRE:
2766         if ( anInts[0] == 1 )
2767           aTypeInfo = "Closed Wire";
2768         else if ( anInts[0] == 2 )
2769           aTypeInfo = "Opened Wire";
2770         else
2771           aTypeInfo = "Wire";
2772         break;
2773         // SOLIDs
2774       case GEOM::GEOM_IKindOfShape::SPHERE:
2775         aTypeInfo = "Sphere";
2776         break;
2777       case GEOM::GEOM_IKindOfShape::CYLINDER:
2778         aTypeInfo = "Cylinder";
2779         break;
2780       case GEOM::GEOM_IKindOfShape::BOX:
2781       case GEOM::GEOM_IKindOfShape::ROTATED_BOX:
2782         aTypeInfo = "Box";
2783         break;
2784       case GEOM::GEOM_IKindOfShape::TORUS:
2785         aTypeInfo = "Torus";
2786         break;
2787       case GEOM::GEOM_IKindOfShape::CONE:
2788         aTypeInfo = "Cone";
2789         break;
2790       case GEOM::GEOM_IKindOfShape::POLYHEDRON:
2791         aTypeInfo = "Polyhedron";
2792         break;
2793       case GEOM::GEOM_IKindOfShape::SOLID:
2794         aTypeInfo = "Solid";
2795         break;
2796         // FACEs
2797       case GEOM::GEOM_IKindOfShape::SPHERE2D:
2798         aTypeInfo = "Spherical Face";
2799         break;
2800       case GEOM::GEOM_IKindOfShape::CYLINDER2D:
2801         aTypeInfo = "Cylindrical Face";
2802         break;
2803       case GEOM::GEOM_IKindOfShape::TORUS2D:
2804         aTypeInfo = "Toroidal Face";
2805         break;
2806       case GEOM::GEOM_IKindOfShape::CONE2D:
2807         aTypeInfo = "Conical Face";
2808         break;
2809       case GEOM::GEOM_IKindOfShape::DISK_CIRCLE:
2810         aTypeInfo = "Disk";
2811         break;
2812       case GEOM::GEOM_IKindOfShape::DISK_ELLIPSE:
2813         aTypeInfo = "Elliptical Face";
2814         break;
2815       case GEOM::GEOM_IKindOfShape::POLYGON:
2816         aTypeInfo = "Polygon";
2817         break;
2818       case GEOM::GEOM_IKindOfShape::PLANE:
2819         aTypeInfo = "Plane";
2820         break;
2821       case GEOM::GEOM_IKindOfShape::PLANAR:
2822         aTypeInfo = "Planar Face";
2823         break;
2824       case GEOM::GEOM_IKindOfShape::FACE:
2825         aTypeInfo = "Face";
2826         break;
2827         // EDGEs
2828       case GEOM::GEOM_IKindOfShape::CIRCLE:
2829         aTypeInfo = "Circle";
2830         break;
2831       case GEOM::GEOM_IKindOfShape::ARC_CIRCLE:
2832         aTypeInfo = "Arc Circle";
2833         break;
2834       case GEOM::GEOM_IKindOfShape::ELLIPSE:
2835         aTypeInfo = "Ellipse";
2836         break;
2837       case GEOM::GEOM_IKindOfShape::ARC_ELLIPSE:
2838         aTypeInfo = "Arc Ellipse";
2839         break;
2840       case GEOM::GEOM_IKindOfShape::LINE:
2841         aTypeInfo = "Line";
2842         break;
2843       case GEOM::GEOM_IKindOfShape::SEGMENT:
2844         aTypeInfo = "Segment";
2845         break;
2846       case GEOM::GEOM_IKindOfShape::EDGE:
2847         aTypeInfo = "Edge";
2848         break;
2849       case GEOM::GEOM_IKindOfShape::VERTEX:
2850         aTypeInfo = "Vertex";
2851         break;
2852       default:
2853         break;
2854       }
2855     }
2856   }
2857
2858   CORBA::String_var compType = ComponentDataType();
2859   char* anInfo = new char[strlen("Module ") + strlen(compType.in()) + strlen(", ") + strlen(aTypeInfo) + 3];
2860   sprintf(anInfo, "Module %s, %s", compType.in(), aTypeInfo);
2861
2862   char* ret = CORBA::string_dup(anInfo);
2863   delete [] anInfo;
2864   return ret;
2865 }
2866
2867 // Version information
2868 char* GEOM_Gen_i::getVersion()
2869 {
2870 #if GEOM_DEVELOPMENT
2871   return CORBA::string_dup(GEOM_VERSION_STR"dev");
2872 #else
2873   return CORBA::string_dup(GEOM_VERSION_STR);
2874 #endif
2875 }
2876
2877 //=================================================================================
2878 // function : CreateFolder()
2879 // purpose  : Creates and returns a new folder object
2880 //=================================================================================
2881 SALOMEDS::SObject_ptr GEOM_Gen_i::CreateFolder(const char* theName,
2882                                                SALOMEDS::SObject_ptr theFather)
2883 {
2884   SALOMEDS::SObject_var aFolderSO;
2885
2886   if ( CORBA::is_nil(theFather) ) {
2887     SALOMEDS::SComponent_var aComponent = findOrCreateComponent();
2888     if (aComponent->_is_nil()) return aFolderSO._retn();
2889     theFather = SALOMEDS::SObject::_narrow(aComponent);
2890   }
2891   if ( CORBA::is_nil(theFather) ) return aFolderSO._retn();
2892
2893   SALOMEDS::GenericAttribute_var anAttr;
2894   if ( strcmp(theFather->GetFatherComponent()->GetID(), theFather->GetID()) != 0 ) {
2895     // not a GEOM component object was selected
2896     if ( !theFather->FindAttribute(anAttr, "AttributeLocalID") ) return aFolderSO._retn();
2897     SALOMEDS::AttributeLocalID_var aLocalID = SALOMEDS::AttributeLocalID::_narrow(anAttr);
2898     if( aLocalID->Value() != 999 ) {
2899       // not a Folder object was selected
2900       GEOM::GEOM_Object_var aGeomObject = GEOM::GEOM_Object::_narrow(theFather);
2901       if ( CORBA::is_nil(aGeomObject) ) return aFolderSO._retn();
2902       // another GEOM object was selected, so get GEOM component as father object
2903       theFather = theFather->GetFatherComponent();
2904     }
2905     aLocalID->UnRegister();
2906   }
2907
2908   SALOMEDS::Study_var aStudy = getStudyServant();
2909   SALOMEDS::StudyBuilder_var aStudyBuilder( aStudy->NewBuilder() );
2910   aFolderSO = aStudyBuilder->NewObject( theFather );
2911
2912   anAttr = aStudyBuilder->FindOrCreateAttribute(aFolderSO, "AttributeLocalID");
2913   SALOMEDS::AttributeLocalID_var aLocalID = SALOMEDS::AttributeLocalID::_narrow(anAttr);
2914   aLocalID->SetValue( 999 ); // mark of the "Folder" object
2915   aLocalID->UnRegister();
2916
2917   anAttr = aStudyBuilder->FindOrCreateAttribute(aFolderSO, "AttributeName");
2918   SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
2919   aName->SetValue( theName );
2920   aName->UnRegister();
2921
2922   anAttr = aStudyBuilder->FindOrCreateAttribute(aFolderSO, "AttributePixMap");
2923   SALOMEDS::AttributePixMap_var aPixMap = SALOMEDS::AttributePixMap::_narrow(anAttr);
2924   aPixMap->SetPixMap("ICON_FOLDER");
2925   aPixMap->UnRegister();
2926
2927   // add object to the use case tree
2928   // (to support tree representation customization and drag-n-drop)
2929   SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
2930   useCaseBuilder->AppendTo( theFather, aFolderSO );
2931
2932   return aFolderSO._retn();
2933 }
2934
2935 //=================================================================================
2936 // function : MoveToFolder()
2937 // purpose  : Moves GEOM object to the specified folder
2938 //=================================================================================
2939 void GEOM_Gen_i::MoveToFolder(GEOM::GEOM_Object_ptr theObject,
2940                               SALOMEDS::SObject_ptr theFolder) {
2941   GEOM::object_list_var objects = new GEOM::object_list();
2942   objects->length( 1 );
2943   SALOMEDS::SObject_var aSO = getStudyServant()->FindObjectID( theObject->GetStudyEntry() );
2944   objects[0] = aSO;
2945   Move( objects, theFolder, -1 );
2946 }
2947
2948 //=================================================================================
2949 // function : MoveListToFolder()
2950 // purpose  : Moves list of GEOM objects to the specified folder
2951 //=================================================================================
2952 void GEOM_Gen_i::MoveListToFolder (const GEOM::ListOfGO& theListOfGO,
2953                                    SALOMEDS::SObject_ptr theFolder) {
2954   int aLen = theListOfGO.length();
2955   GEOM::object_list_var objects = new GEOM::object_list();
2956   objects->length( aLen );
2957   GEOM::GEOM_Object_var aGO;
2958   SALOMEDS::SObject_var aSO;
2959   for (int i = 0; i < aLen; i++) {
2960     aGO = GEOM::GEOM_Object::_duplicate( theListOfGO[i] );
2961     aSO = getStudyServant()->FindObjectID( aGO->GetStudyEntry() );
2962     objects[i] = aSO;
2963   }
2964   if ( objects->length() > 0 )
2965     Move( objects, theFolder, -1 );
2966 }
2967
2968 //=================================================================================
2969 // function : Move()
2970 // purpose  : Moves objects to the specified position.
2971 //            Is used in the drag-n-drop functionality.
2972 //=================================================================================
2973 void GEOM_Gen_i::Move( const GEOM::object_list& what,
2974                        SALOMEDS::SObject_ptr where,
2975                        CORBA::Long row )
2976 {
2977   if ( CORBA::is_nil( where ) ) return;
2978
2979   SALOMEDS::Study_var study = getStudyServant();
2980   SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
2981   SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
2982   SALOMEDS::SComponent_var father = where->GetFatherComponent();
2983   std::string dataType = father->ComponentDataType();
2984   if ( dataType != "GEOM" ) return; // not a GEOM component
2985
2986   SALOMEDS::SObject_var objAfter;
2987   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
2988     // insert at given row -> find insertion position
2989     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
2990     int i;
2991     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
2992     if ( i == row && useCaseIt->More() ) {
2993       objAfter = useCaseIt->Value();
2994     }
2995   }
2996
2997   for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
2998     SALOMEDS::SObject_var sobj = what[i];
2999     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
3000     // insert the object to the use case tree
3001     if ( !CORBA::is_nil( objAfter ) )
3002       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
3003     else
3004       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
3005   }
3006 }
3007
3008 //=======================================================================
3009 // function : GetDependencyTree
3010 // purpose  : Collects dependencies of the given objects from other ones
3011 //=======================================================================
3012 SALOMEDS::TMPFile* GEOM_Gen_i::GetDependencyTree( const GEOM::string_array& theObjectEntries )
3013 {
3014   // fill in the tree structure
3015   GEOMUtils::TreeModel tree;
3016
3017   std::string entry;
3018   for ( CORBA::ULong i = 0; i < theObjectEntries.length(); i++ ) {
3019     // process objects one-by-one
3020     entry = theObjectEntries[i].in();
3021     GEOM::GEOM_BaseObject_var anObj = GetObject(entry.c_str() );
3022     if ( anObj->_is_nil() )
3023       continue;
3024     std::map< std::string, std::set<std::string> > passedEntries;
3025     GEOMUtils::LevelsList upLevelList;
3026     // get objects from which current one depends on recursively
3027     getUpwardDependency( anObj, upLevelList, passedEntries );
3028     GEOMUtils::LevelsList downLevelList;
3029     // get objects that depends on current one recursively
3030     getDownwardDependency( anObj, downLevelList, passedEntries );
3031     tree.insert( std::pair<std::string, std::pair<GEOMUtils::LevelsList,GEOMUtils::LevelsList> >(entry, std::pair<GEOMUtils::LevelsList,GEOMUtils::LevelsList>( upLevelList, downLevelList ) ) );
3032   }
3033
3034   // translation the tree into string
3035   std::string treeStr;
3036   GEOMUtils::ConvertTreeToString( tree, treeStr );
3037
3038   // put string into stream
3039   char* aBuffer = (char*)CORBA::string_dup(treeStr.c_str());
3040   int aBufferSize = strlen((char*)aBuffer);
3041
3042   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
3043
3044   SALOMEDS::TMPFile_var aStream = new SALOMEDS::TMPFile(aBufferSize, aBufferSize, anOctetBuf, 1);
3045
3046   return aStream._retn();
3047 }
3048
3049 //=======================================================================
3050 // function : getUpwardDependency
3051 // purpose  : Collects the entries of objects on that the given one depends
3052 //=======================================================================
3053 void GEOM_Gen_i::getUpwardDependency( GEOM::GEOM_BaseObject_ptr gbo,
3054                                       GEOMUtils::LevelsList &upLevelList,
3055                                       std::map< std::string, std::set<std::string> > &passedEntries,
3056                                       int level ) {
3057   std::string aGboEntry = gbo->GetEntry();
3058   GEOMUtils::NodeLinks anEntries;
3059   GEOMUtils::LevelInfo aLevelMap;
3060   if ( level > 0 ) {
3061     if ( level-1 >= (int)upLevelList.size() ) {
3062       // create a new map
3063       upLevelList.push_back( aLevelMap );
3064     } else {
3065       // get the existent map
3066       aLevelMap = upLevelList.at(level-1);
3067       if ( aLevelMap.count( aGboEntry ) > 0 ) {
3068         anEntries = aLevelMap[ aGboEntry ];
3069       }
3070     }
3071   }
3072   // get objects on that the current one depends
3073   GEOM::ListOfGBO_var depList = gbo->GetDependency();
3074   std::string aDepEntry;
3075   for( CORBA::ULong j = 0; j < depList->length(); j++ ) {
3076     if ( depList[j]->_is_nil() )
3077       continue;
3078     aDepEntry = depList[j]->GetEntry();
3079     if ( passedEntries.count( aGboEntry ) > 0 &&
3080          passedEntries[aGboEntry].count( aDepEntry ) > 0 ) {
3081       //avoid checking the passed objects
3082       continue;
3083     }
3084     passedEntries[aGboEntry].insert( aDepEntry );
3085     if ( level > 0 ) {
3086       anEntries.push_back( aDepEntry );
3087     }
3088     // get dependencies recursively
3089     getUpwardDependency(depList[j], upLevelList, passedEntries, level+1);
3090   }
3091   if ( level > 0 ) {
3092     aLevelMap.insert( std::pair<std::string, GEOMUtils::NodeLinks>(aGboEntry, anEntries) );
3093     upLevelList[level-1] = aLevelMap;
3094   }
3095 }
3096
3097 //=======================================================================
3098 // function : getDownwardDependency
3099 // purpose  : Collects the entries of objects that depends on the given one
3100 //=======================================================================
3101 void GEOM_Gen_i::getDownwardDependency( GEOM::GEOM_BaseObject_ptr gbo,
3102                                         GEOMUtils::LevelsList &downLevelList,
3103                                         std::map< std::string, std::set<std::string> > &passedEntries,
3104                                         int level ) {
3105   std::string aGboEntry = gbo->GetEntry();
3106   Handle(TDocStd_Document) aDoc = GEOM_Engine::GetEngine()->GetDocument();
3107   Handle(TDataStd_TreeNode) aNode, aRoot;
3108   Handle(::GEOM_Function) aFunction;
3109   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
3110     // go through the whole OCAF tree
3111     TDataStd_ChildNodeIterator Itr( aRoot );
3112     for (; Itr.More(); Itr.Next()) {
3113       aNode = Itr.Value();
3114       aFunction = GEOM_Function::GetFunction(aNode->Label());
3115       if (aFunction.IsNull()) {
3116         continue;
3117       }
3118       TDF_Label aLabel  = aFunction->GetOwnerEntry();
3119       if(aLabel.IsNull()) continue;
3120       TCollection_AsciiString anEntry;
3121       TDF_Tool::Entry(aLabel, anEntry);
3122       GEOM::GEOM_BaseObject_var geomObj = GetObject(anEntry.ToCString() );
3123       if( CORBA::is_nil( geomObj ) )
3124         continue;
3125       // get dependencies for current object in the tree
3126       GEOM::ListOfGBO_var depList = geomObj->GetDependency();
3127       if( depList->length() == 0 )
3128         continue;
3129       std::string aGoEntry = geomObj->GetEntry();
3130       // go through dependencies of current object to check whether it depends on the given object
3131       for( CORBA::ULong i = 0; i < depList->length(); i++ ) {
3132         if ( depList[i]->_is_nil() )
3133           continue;
3134         if ( depList[i]->_is_equivalent( gbo ) ) {
3135           // yes, the current object depends on the given object
3136           if ( passedEntries.count( aGoEntry ) > 0 &&
3137                passedEntries[aGoEntry].count( aGboEntry ) > 0 ) {
3138             //avoid checking the passed objects
3139             continue;
3140           }
3141           passedEntries[aGoEntry].insert( aGboEntry );
3142           GEOMUtils::NodeLinks anEntries;
3143           GEOMUtils::LevelInfo aLevelMap;
3144           anEntries.push_back( aGboEntry );
3145           if ( level >= (int)downLevelList.size() ) {
3146             downLevelList.push_back( aLevelMap );
3147           } else {
3148             aLevelMap = downLevelList.at(level);
3149             if ( aLevelMap.count( aGoEntry ) > 0 ) {
3150               anEntries = aLevelMap[ aGoEntry ];
3151             }
3152           }
3153           aLevelMap.insert( std::pair<std::string, GEOMUtils::NodeLinks>(aGoEntry, anEntries) );
3154           downLevelList[level] = aLevelMap;
3155           // get dependencies of the current object recursively
3156           getDownwardDependency(geomObj, downLevelList, passedEntries, level+1);
3157           break;
3158         }
3159       }
3160     }
3161   }
3162 }
3163
3164 //==============================================================================
3165 // function : GetEntriesToReduceStudy
3166 // purpose  : Fills 3 lists that is used to clean study of redundant objects
3167 //==============================================================================
3168 void GEOM_Gen_i::GetEntriesToReduceStudy(GEOM::string_array& theSelectedEntries,
3169                                          GEOM::string_array& theParentEntries,
3170                                          GEOM::string_array& theSubEntries,
3171                                          GEOM::string_array& theOtherEntries)
3172 {
3173   std::set<std::string> aSelected, aParents, aChildren, anOthers;
3174   for ( CORBA::ULong i = 0; i < theSelectedEntries.length(); i++ ) {
3175     aSelected.insert( CORBA::string_dup( theSelectedEntries[i] ) );
3176   }
3177
3178   Handle(TDocStd_Document) aDoc = GEOM_Engine::GetEngine()->GetDocument();
3179   Handle(TDataStd_TreeNode) aNode, aRoot;
3180   Handle(::GEOM_Function) aFunction;
3181   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
3182     // go through the whole OCAF tree
3183     TDF_Label aLabel;
3184     std::string anEntry;
3185     TCollection_AsciiString anAsciiEntry;
3186     TDataStd_ChildNodeIterator Itr( aRoot );
3187     for (; Itr.More(); Itr.Next()) {
3188       aNode = Itr.Value();
3189       aFunction = GEOM_Function::GetFunction(aNode->Label());
3190       if (aFunction.IsNull()) {
3191         continue;
3192       }
3193       aLabel = aFunction->GetOwnerEntry();
3194       if(aLabel.IsNull())
3195         continue;
3196       TDF_Tool::Entry(aLabel, anAsciiEntry);
3197       anEntry = anAsciiEntry.ToCString();
3198       GEOM::GEOM_BaseObject_var geomObj = GetObject(anEntry.c_str() );
3199       if( CORBA::is_nil( geomObj ) )
3200         continue;
3201
3202       if ( aSelected.count( anEntry ) > 0 &&
3203            aParents.count( anEntry ) == 0 ) {
3204         includeParentDependencies( geomObj, aSelected, aParents, aChildren, anOthers );
3205       } else if ( aParents.count( anEntry ) == 0 &&
3206                   aChildren.count( anEntry ) == 0 ) {
3207         anOthers.insert( geomObj->GetEntry() );
3208       }
3209     }
3210
3211     std::set<std::string>::iterator it;
3212     std::set<std::string>::iterator foundIt;
3213     TCollection_AsciiString stringIOR;
3214     GEOM::GEOM_Object_var geomObj;
3215
3216     // filling list of sub-objects
3217     for ( it = aSelected.begin(); it != aSelected.end(); ++it ) {
3218       includeSubObjects( *it, aSelected, aParents, aChildren, anOthers );
3219     }
3220
3221     // if some selected object is not a main shape,
3222     // we move it's main shapes into 'selected' list,
3223     // because they could not be modified anyhow.
3224     std::set<std::string> aToBeInSelected;
3225     for ( it = aSelected.begin(); it != aSelected.end(); ++it ) {
3226       Handle(::GEOM_BaseObject) handle_object = _impl->GetObject((*it).c_str(), false);
3227       if ( handle_object.IsNull() )
3228         continue;
3229
3230       stringIOR = handle_object->GetIOR();
3231       if ( stringIOR.Length() < 1 )
3232         continue;
3233
3234       geomObj = GetIORFromString( stringIOR.ToCString() );
3235       while ( !geomObj->IsMainShape() ) {
3236         geomObj = geomObj->GetMainShape();
3237         anEntry = geomObj->GetEntry();
3238
3239         foundIt = aParents.find( anEntry );
3240         if ( foundIt != aParents.end() )
3241           aParents.erase( foundIt );
3242
3243         foundIt = aChildren.find( anEntry );
3244         if ( foundIt != aChildren.end() )
3245           aChildren.erase( foundIt );
3246
3247         foundIt = anOthers.find( anEntry );
3248         if ( foundIt != anOthers.end() )
3249           anOthers.erase( foundIt );
3250
3251         aToBeInSelected.insert( anEntry );
3252       }
3253     }
3254     aSelected.insert( aToBeInSelected.begin(), aToBeInSelected.end() );
3255
3256     // fill the CORBA arrays with values from sets
3257     int i;
3258     theSelectedEntries.length( aSelected.size() );
3259     for ( i = 0, it = aSelected.begin(); it != aSelected.end(); ++it, i++ )
3260       theSelectedEntries[i]  = CORBA::string_dup( (*it).c_str() );
3261     theParentEntries.length( aParents.size() );
3262     for ( i = 0, it = aParents.begin(); it != aParents.end(); ++it, i++ )
3263       theParentEntries[i]  = CORBA::string_dup( (*it).c_str() );
3264     theSubEntries.length( aChildren.size() );
3265     for ( i = 0, it = aChildren.begin(); it != aChildren.end(); ++it, i++ )
3266       theSubEntries[i]  = CORBA::string_dup( (*it).c_str() );
3267     theOtherEntries.length( anOthers.size() );
3268     for ( i = 0, it = anOthers.begin(); it != anOthers.end(); ++it, i++ )
3269       theOtherEntries[i]  = CORBA::string_dup( (*it).c_str() );
3270   }
3271 }
3272
3273 //==============================================================================
3274 // function : includeParentDependencies
3275 // purpose  :
3276 //==============================================================================
3277 void GEOM_Gen_i::includeParentDependencies(GEOM::GEOM_BaseObject_ptr geomObj,
3278                                            std::set<std::string>& aSelected,
3279                                            std::set<std::string>& aParents,
3280                                            std::set<std::string>& aChildren,
3281                                            std::set<std::string>& anOthers)
3282 {
3283   std::string anEntry = geomObj->GetEntry();
3284   if ( aSelected.count( anEntry ) == 0 ) {
3285     aParents.insert( anEntry );
3286     std::set<std::string>::iterator it;
3287     it = aChildren.find( anEntry );
3288     if ( it != aChildren.end() )
3289       aChildren.erase( it );
3290     it = anOthers.find( anEntry );
3291     if ( it != anOthers.end() )
3292       anOthers.erase( it );
3293   }
3294   // get dependencies for current object in the tree
3295   GEOM::ListOfGBO_var depList = geomObj->GetDependency();
3296   if( depList->length() == 0 )
3297     return;
3298   // go through dependencies of current object to check whether it depends on the given object
3299   std::string aDepEntry;
3300   for( CORBA::ULong i = 0; i < depList->length(); i++ ) {
3301     aDepEntry = depList[i]->GetEntry();
3302     if ( depList[i]->_is_nil() ||
3303          aDepEntry == anEntry ||             // skip self-depending
3304          aSelected.count( aDepEntry ) > 0 || // skip selected objects
3305          aParents.count( aDepEntry ) > 0     // skip already processed objects
3306          )
3307       continue;
3308     includeParentDependencies( depList[i], aSelected, aParents, aChildren, anOthers );
3309   }
3310 }
3311
3312 //==============================================================================
3313 // function : includeSubObjects
3314 // purpose  :
3315 //==============================================================================
3316 void GEOM_Gen_i::includeSubObjects(const std::string& aSelectedEntry,
3317                                    std::set<std::string>& aSelected,
3318                                    std::set<std::string>& aParents,
3319                                    std::set<std::string>& aChildren,
3320                                    std::set<std::string>& anOthers)
3321 {
3322   std::set<std::string>::iterator foundIt;
3323   Handle(::GEOM_BaseObject) handle_object = _impl->GetObject(aSelectedEntry.c_str(), false);
3324   if ( handle_object.IsNull() )
3325     return;
3326
3327   Handle(::GEOM_Function) aShapeFun = handle_object->GetFunction(1);
3328   if ( aShapeFun.IsNull() || !aShapeFun->HasSubShapeReferences() )
3329     return;
3330
3331   const TDataStd_ListOfExtendedString& aListEntries = aShapeFun->GetSubShapeReferences();
3332   if ( aListEntries.IsEmpty() )
3333     return;
3334
3335   TDataStd_ListIteratorOfListOfExtendedString anIt (aListEntries);
3336   for ( ; anIt.More(); anIt.Next() ) {
3337     TCollection_ExtendedString aSubEntry = anIt.Value();
3338     Standard_Integer aStrLen = aSubEntry.LengthOfCString();
3339     char* aSubEntryStr = new char[aStrLen+1];
3340     aSubEntry.ToUTF8CString( aSubEntryStr );
3341     foundIt = aParents.find( aSubEntryStr );
3342     if ( foundIt == aParents.end() ) { // add to sub-objects if it is not in parents list
3343       foundIt = aSelected.find( aSubEntryStr );
3344       if ( foundIt == aSelected.end() ) { // add to sub-objects if it is not in selected list
3345             aChildren.insert( aSubEntryStr );
3346             foundIt = anOthers.find( aSubEntryStr );
3347             if ( foundIt != anOthers.end() )
3348               anOthers.erase( foundIt );
3349       }
3350     }
3351     includeSubObjects( aSubEntryStr, aSelected, aParents, aChildren, anOthers );
3352   }
3353 }
3354 //=====================================================================================
3355 // EXPORTED METHODS
3356 //=====================================================================================
3357 extern "C"
3358 {
3359   /*
3360   GEOM_I_EXPORT
3361   PortableServer::ObjectId* GEOMEngine_factory(CORBA::ORB*, PortableServer::POA*, PortableServer::ObjectId*, const char*, const char*);
3362   */
3363
3364   GEOM_I_EXPORT
3365   PortableServer::ObjectId* GEOMEngine_factory(CORBA::ORB_ptr            orb,
3366                                                PortableServer::POA_ptr   poa,
3367                                                PortableServer::ObjectId* contId,
3368                                                const char*               instanceName,
3369                                                const char*               interfaceName)
3370   {
3371     GEOM_Gen_i* myGEOM_Gen_i = new GEOM_Gen_i(orb, poa, contId, instanceName, interfaceName);
3372     return myGEOM_Gen_i->getId();
3373   }
3374 }