Salome HOME
23586: [EDF] HYDRO: Copy mesh to new geometry
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i_1.cxx
1 // Copyright (C) 2007-2016  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 //  File      : SMESH_Gen_i_1.cxx
23 //  Created   : Thu Oct 21 17:24:06 2004
24 //  Author    : Edward AGAPOV (eap)
25 //  Module    : SMESH
26
27 #include "SMESH_Gen_i.hxx"
28
29 #include "SMESHDS_Mesh.hxx"
30 #include "SMESH_Algo_i.hxx"
31 #include "SMESH_Comment.hxx"
32 #include "SMESH_Group_i.hxx"
33 #include "SMESH_Hypothesis_i.hxx"
34 #include "SMESH_Mesh_i.hxx"
35 #include "SMESH_subMesh_i.hxx"
36
37 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
38
39 #include <utilities.h>
40 #include <Utils_ExceptHandlers.hxx>
41 #include <SALOMEDS_wrap.hxx>
42 #include <SALOMEDS_Attributes_wrap.hxx>
43 #include <SALOME_KernelServices.hxx>
44
45 #include <TCollection_AsciiString.hxx>
46 #include <TopoDS_Solid.hxx>
47
48 #include <cctype>
49
50 #ifdef _DEBUG_
51 static int MYDEBUG = 0;
52 #else
53 static int MYDEBUG = 0;
54 #endif
55
56 using namespace std;
57
58 //=============================================================================
59 /*!
60  *  Get...Tag [ static ]
61  *
62  *  Methods which determine SMESH data model structure
63  */
64 //=============================================================================
65
66 long SMESH_Gen_i::GetHypothesisRootTag()
67 {
68   return SMESH::Tag_HypothesisRoot;
69 }
70
71 long SMESH_Gen_i::GetAlgorithmsRootTag()
72 {
73   return SMESH::Tag_AlgorithmsRoot;
74 }
75
76 long SMESH_Gen_i::GetRefOnShapeTag()
77 {
78   return SMESH::Tag_RefOnShape;
79 }
80
81 long SMESH_Gen_i::GetRefOnAppliedHypothesisTag()
82 {
83   return SMESH::Tag_RefOnAppliedHypothesis;
84 }
85
86 long SMESH_Gen_i::GetRefOnAppliedAlgorithmsTag()
87 {
88   return SMESH::Tag_RefOnAppliedAlgorithms;
89 }
90
91 long SMESH_Gen_i::GetSubMeshOnVertexTag()
92 {
93   return SMESH::Tag_SubMeshOnVertex;
94 }
95
96 long SMESH_Gen_i::GetSubMeshOnEdgeTag()
97 {
98   return SMESH::Tag_SubMeshOnEdge;
99 }
100
101 long SMESH_Gen_i::GetSubMeshOnFaceTag()
102 {
103   return SMESH::Tag_SubMeshOnFace;
104 }
105
106 long SMESH_Gen_i::GetSubMeshOnSolidTag()
107 {
108   return SMESH::Tag_SubMeshOnSolid;
109 }
110
111 long SMESH_Gen_i::GetSubMeshOnCompoundTag()
112 {
113   return SMESH::Tag_SubMeshOnCompound;
114 }
115
116 long SMESH_Gen_i::GetSubMeshOnWireTag()
117 {
118   return SMESH::Tag_SubMeshOnWire;
119 }
120
121 long SMESH_Gen_i::GetSubMeshOnShellTag()
122 {
123   return SMESH::Tag_SubMeshOnShell;
124 }
125
126 long SMESH_Gen_i::GetNodeGroupsTag()
127 {
128   return SMESH::Tag_NodeGroups;
129 }
130
131 long SMESH_Gen_i::GetEdgeGroupsTag()
132 {
133   return SMESH::Tag_EdgeGroups;
134 }
135
136 long SMESH_Gen_i::GetFaceGroupsTag()
137 {
138   return SMESH::Tag_FaceGroups;
139 }
140
141 long SMESH_Gen_i::GetVolumeGroupsTag()
142 {
143   return SMESH::Tag_VolumeGroups;
144 }
145
146 long SMESH_Gen_i::Get0DElementsGroupsTag()
147 {
148   return SMESH::Tag_0DElementsGroups;
149 }
150
151 long SMESH_Gen_i::GetBallElementsGroupsTag()
152 {
153   return SMESH::Tag_BallElementsGroups;
154 }
155
156 //=============================================================================
157 /*!
158  *  SMESH_Gen_i::CanPublishInStudy
159  *
160  *  Returns true if object can be published in the study
161  */
162 //=============================================================================
163
164 bool SMESH_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
165 {
166   if(MYDEBUG) MESSAGE("CanPublishInStudy - "<<!CORBA::is_nil(getStudyServant()));
167   
168   if ( !myIsEnablePublish )
169     return false;
170
171   SMESH::SMESH_Mesh_var aMesh       = SMESH::SMESH_Mesh::_narrow(theIOR);
172   if( !aMesh->_is_nil() )
173     return true;
174
175   SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow(theIOR);
176   if( !aSubMesh->_is_nil() )
177     return true;
178
179   SMESH::SMESH_Hypothesis_var aHyp  = SMESH::SMESH_Hypothesis::_narrow(theIOR);
180   if( !aHyp->_is_nil() )
181     return true;
182
183   SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(theIOR);
184   if( !aGroup->_is_nil() )
185     return true;
186
187   if(MYDEBUG) MESSAGE("CanPublishInStudy--CANT");
188   return false;
189 }
190
191 //=======================================================================
192 //function : ObjectToSObject
193 //purpose  : Put a result into a SALOMEDS::SObject_wrap or call UnRegister()!
194 //=======================================================================
195
196 SALOMEDS::SObject_ptr SMESH_Gen_i::ObjectToSObject(CORBA::Object_ptr theObject)
197 {
198   SALOMEDS::SObject_wrap aSO;
199   if ( !CORBA::is_nil( theObject ))
200   {
201     CORBA::String_var objStr = SMESH_Gen_i::GetORB()->object_to_string( theObject );
202     aSO = getStudyServant()->FindObjectIOR( objStr.in() );
203   }
204   return aSO._retn();
205 }
206
207 //=======================================================================
208 //function : GetStudyPtr
209 //purpose  : Get study from naming service
210 //=======================================================================
211 SALOMEDS::Study_var SMESH_Gen_i::getStudyServant()
212 {
213   return SALOMEDS::Study::_duplicate(KERNEL::getStudyServant());
214 }
215
216 //=======================================================================
217 //function : objectToServant
218 //purpose  : 
219 //=======================================================================
220
221 template<typename T> static inline T* objectToServant( CORBA::Object_ptr theIOR )
222 {
223   return dynamic_cast<T*>( SMESH_Gen_i::GetServant( theIOR ).in() );
224 }
225
226 //=======================================================================
227 //function : ShapeToGeomObject
228 //purpose  : 
229 //=======================================================================
230
231 GEOM::GEOM_Object_ptr SMESH_Gen_i::ShapeToGeomObject (const TopoDS_Shape& theShape )
232 {
233   GEOM::GEOM_Object_var aShapeObj;
234   if ( !theShape.IsNull() ) {
235     GEOM_Client* aClient = GetShapeReader();
236     TCollection_AsciiString IOR;
237     if ( aClient && aClient->Find( theShape, IOR ))
238     {
239       CORBA::Object_var obj = GetORB()->string_to_object( IOR.ToCString() );
240       aShapeObj = GEOM::GEOM_Object::_narrow ( obj );
241     }
242   }
243   return aShapeObj._retn();
244 }
245
246 //=======================================================================
247 //function : GeomObjectToShape
248 //purpose  : 
249 //=======================================================================
250
251 TopoDS_Shape SMESH_Gen_i::GeomObjectToShape(GEOM::GEOM_Object_ptr theGeomObject)
252 {
253   TopoDS_Shape S;
254   if ( !theGeomObject->_is_nil() ) {
255     GEOM_Client* aClient = GetShapeReader();
256     GEOM::GEOM_Gen_ptr aGeomEngine = GetGeomEngine();
257     if ( aClient && !aGeomEngine->_is_nil () )
258       S = aClient->GetShape( aGeomEngine, theGeomObject );
259   }
260   return S;
261 }
262
263 //=======================================================================
264 //function : publish
265 //purpose  : 
266 //=======================================================================
267
268 static SALOMEDS::SObject_ptr publish(CORBA::Object_ptr     theIOR,
269                                      SALOMEDS::SObject_ptr theFatherObject,
270                                      const int             theTag = 0,
271                                      const char*           thePixMap = 0,
272                                      const bool            theSelectable = true)
273 {
274   SALOMEDS::Study_var theStudy = SMESH_Gen_i::getStudyServant();
275   SALOMEDS::SObject_wrap SO = SMESH_Gen_i::ObjectToSObject( theIOR );
276   SALOMEDS::StudyBuilder_var     aStudyBuilder = theStudy->NewBuilder();
277   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = theStudy->GetUseCaseBuilder();
278   bool isNewSO = false, isInUseCaseTree = false;
279   if ( SO->_is_nil() )
280   {
281     if ( theTag == 0 ) {
282       SO = aStudyBuilder->NewObject( theFatherObject );
283       isNewSO = true;
284     }
285     else if ( !theFatherObject->FindSubObject( theTag, SO.inout() ))
286     {
287       SO = aStudyBuilder->NewObjectToTag( theFatherObject, theTag );
288       isNewSO = true;
289     }
290     else
291     {
292       isInUseCaseTree = useCaseBuilder->IsUseCaseNode( SO );
293     }
294   }
295   else
296   {
297     isInUseCaseTree = useCaseBuilder->IsUseCaseNode( SO );
298   }
299
300   SALOMEDS::GenericAttribute_wrap anAttr;
301   if ( !CORBA::is_nil( theIOR ))
302   {
303     anAttr = aStudyBuilder->FindOrCreateAttribute( SO, "AttributeIOR" );
304     CORBA::String_var objStr = SMESH_Gen_i::GetORB()->object_to_string( theIOR );
305     SALOMEDS::AttributeIOR_wrap iorAttr = anAttr;
306     CORBA::String_var objStrCur = iorAttr->Value();
307     bool sameIOR = ( objStrCur.in() && strcmp( objStr.in(), objStrCur.in() ) == 0 );
308     if ( !sameIOR )
309     {
310       iorAttr->SetValue( objStr.in() );
311       // UnRegister() !!! --> random problems when meshing in parallel (yacs foreach) in
312       // distributed python scripts, because simultaneously created meshes are
313       // published into the same SO; as a result the mesh published first dies
314       SALOME::GenericObj_var genObj = SALOME::GenericObj::_narrow( theIOR );
315       if ( !genObj->_is_nil() )
316         genObj->UnRegister();
317     }
318   }
319
320   if ( thePixMap ) {
321     anAttr  = aStudyBuilder->FindOrCreateAttribute( SO, "AttributePixMap" );
322     SALOMEDS::AttributePixMap_wrap pm = anAttr;
323     pm->SetPixMap( thePixMap );
324   }
325
326   if ( !theSelectable ) {
327     anAttr = aStudyBuilder->FindOrCreateAttribute( SO, "AttributeSelectable" );
328     SALOMEDS::AttributeSelectable_wrap selAttr = anAttr;
329     selAttr->SetSelectable( false );
330   }
331
332   if ( !isNewSO )
333     aStudyBuilder->RemoveReference( SO );// remove garbage reference (23336)
334
335   // add object to the use case tree
336   // (to support tree representation customization and drag-n-drop)
337   if ( isNewSO || !isInUseCaseTree )
338   {
339     // define the next tag after given one in the data tree to insert SObject
340     SALOMEDS::SObject_wrap curObj, objAfter;
341     if ( theFatherObject->GetLastChildTag() > theTag && theTag > 0 )
342     {
343       SALOMEDS::UseCaseIterator_wrap
344         anUseCaseIter = useCaseBuilder->GetUseCaseIterator(theFatherObject);
345       for ( ; anUseCaseIter->More(); anUseCaseIter->Next() ) {
346         curObj = anUseCaseIter->Value();
347         if ( curObj->Tag() > theTag  ) {
348           objAfter = curObj;
349           break;
350         }
351       }
352     }
353     if ( !CORBA::is_nil( objAfter ))
354       useCaseBuilder->InsertBefore( SO, objAfter );    // insert at given tag
355     else if ( !isInUseCaseTree )
356       useCaseBuilder->AppendTo( theFatherObject, SO ); // append to the end of list
357   }
358   return SO._retn();
359 }
360
361 //=======================================================================
362 //function : setName
363 //purpose  :
364 //=======================================================================
365
366 void SMESH_Gen_i::SetName(SALOMEDS::SObject_ptr theSObject,
367                           const char*           theName,
368                           const char*           theDefaultName)
369 {
370   if ( !theSObject->_is_nil() ) {
371     SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
372     SALOMEDS::GenericAttribute_wrap   anAttr =
373       aStudyBuilder->FindOrCreateAttribute( theSObject, "AttributeName" );
374     SALOMEDS::AttributeName_wrap aNameAttr = anAttr;
375     if ( theName && theName[0] ) {
376       std::string name( theName ); // trim trailing white spaces
377       for ( size_t i = name.size()-1; i > 0; --i )
378         if ( isspace( name[i] )) name[i] = '\0';
379         else                     break;
380       aNameAttr->SetValue( name.c_str() );
381     }
382     else
383     {
384       CORBA::String_var curName = aNameAttr->Value();
385       if ( strlen( curName.in() ) == 0 ) {
386         SMESH_Comment aName(theDefaultName);
387         aNameAttr->SetValue( ( aName<< "_" << theSObject->Tag()).c_str() );
388       }
389     }
390   }
391 }
392
393 //=======================================================================
394 //function : SetPixMap
395 //purpose  :
396 //=======================================================================
397
398 void SMESH_Gen_i::SetPixMap(SALOMEDS::SObject_ptr theSObject,
399                             const char*           thePixMap)
400 {
401   if ( !theSObject->_is_nil() && thePixMap && thePixMap && thePixMap[0] )
402   {
403     SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
404     SALOMEDS::GenericAttribute_wrap anAttr =
405       aStudyBuilder->FindOrCreateAttribute( theSObject, "AttributePixMap" );
406     SALOMEDS::AttributePixMap_wrap aPMAttr = anAttr;
407     aPMAttr->SetPixMap( thePixMap );
408   }
409 }
410
411 //=======================================================================
412 //function : addReference
413 //purpose  : 
414 //=======================================================================
415
416 static void addReference (SALOMEDS::SObject_ptr theSObject,
417                           CORBA::Object_ptr     theToObject,
418                           int                   theTag = 0)
419 {
420   SALOMEDS::Study_var aStudy = SMESH_Gen_i::getStudyServant();
421   SALOMEDS::SObject_wrap aToObjSO = SMESH_Gen_i::ObjectToSObject( theToObject );
422   if ( !aToObjSO->_is_nil() && !theSObject->_is_nil() ) {
423     SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
424     SALOMEDS::SObject_wrap aReferenceSO;
425     if ( !theTag ) {
426       // check if the reference to theToObject already exists
427       // and find a free label for the reference object
428       bool isReferred = false;
429       int tag = 1;
430       SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( theSObject );
431       for ( ; !isReferred && anIter->More(); anIter->Next(), ++tag ) {
432         SALOMEDS::SObject_wrap curSO = anIter->Value();
433         if ( curSO->ReferencedObject( aReferenceSO.inout() )) {
434           CORBA::String_var refEntry = aReferenceSO->GetID();
435           CORBA::String_var  toEntry = aToObjSO->GetID();
436           if ( strcmp( refEntry, toEntry ) == 0 )
437             isReferred = true;
438         }
439         else if ( !theTag ) {
440           SALOMEDS::GenericAttribute_wrap anAttr;
441           if ( !curSO->FindAttribute( anAttr.inout(), "AttributeIOR" ))
442             theTag = tag;
443         }
444       }
445       if ( isReferred )
446         return;
447       if ( !theTag )
448         theTag = tag;
449     }
450     if ( !theSObject->FindSubObject( theTag, aReferenceSO.inout() ))
451       aReferenceSO = aStudyBuilder->NewObjectToTag( theSObject, theTag );
452
453     aStudyBuilder->Addreference( aReferenceSO, aToObjSO );
454
455     // make the reference visible (invisible ref is created by createInvalidSubMesh())
456     aStudyBuilder->RemoveAttribute( aReferenceSO, "AttributeDrawable" );
457
458     // add reference to the use case tree
459     // (to support tree representation customization and drag-n-drop)
460     SALOMEDS::UseCaseBuilder_wrap  useCaseBuilder = aStudy->GetUseCaseBuilder();
461     SALOMEDS::UseCaseIterator_wrap    useCaseIter = useCaseBuilder->GetUseCaseIterator(theSObject);
462     for ( ; useCaseIter->More(); useCaseIter->Next() )
463     {
464       SALOMEDS::SObject_wrap curSO = useCaseIter->Value();
465       if ( curSO->Tag() == theTag )
466         return;
467     }
468     useCaseBuilder->AppendTo( theSObject, aReferenceSO );
469   }
470 }
471
472 //=============================================================================
473 /*!
474  *  SMESH_Gen_i::PublishInStudy
475  *
476  *  Publish object in the study
477  */
478 //=============================================================================
479
480 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishInStudy(SALOMEDS::SObject_ptr theSObject,
481                                                   CORBA::Object_ptr     theIOR,
482                                                   const char*           theName)
483      throw (SALOME::SALOME_Exception)
484 {
485   Unexpect aCatch(SALOME_SalomeException);
486   SALOMEDS::SObject_wrap aSO;
487   if ( !myIsEnablePublish )
488     return aSO._retn();
489   if ( CORBA::is_nil( theIOR ))
490     return aSO._retn();
491   if(MYDEBUG) MESSAGE("PublishInStudy");
492
493   // Publishing a mesh
494   SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( theIOR );
495   if( !aMesh->_is_nil() )
496     aSO = PublishMesh( aMesh, theName );
497
498   // Publishing a sub-mesh
499   SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow( theIOR );
500   if( aSO->_is_nil() && !aSubMesh->_is_nil() ) {
501     GEOM::GEOM_Object_var aShapeObject = aSubMesh->GetSubShape();
502     aMesh = aSubMesh->GetFather();
503     aSO = PublishSubMesh( aMesh, aSubMesh, aShapeObject, theName );
504   }
505
506   // Publishing a hypothesis or algorithm
507   SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( theIOR );
508   if ( aSO->_is_nil() && !aHyp->_is_nil() )
509     aSO = PublishHypothesis( aHyp, theName );
510
511   // Publishing a group
512   SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(theIOR);
513   if ( aSO->_is_nil() && !aGroup->_is_nil() ) {
514     GEOM::GEOM_Object_var aShapeObject;
515     aMesh = aGroup->GetMesh();
516     aSO = PublishGroup( aMesh, aGroup, aShapeObject, theName );
517   }
518   if(MYDEBUG) MESSAGE("PublishInStudy_END");
519
520   return aSO._retn();
521 }
522
523 //=======================================================================
524 //function : PublishComponent
525 //purpose  : 
526 //=======================================================================
527
528 SALOMEDS::SComponent_ptr SMESH_Gen_i::PublishComponent()
529 {
530   if(MYDEBUG) MESSAGE("PublishComponent");
531   if ( !myIsEnablePublish )
532     return SALOMEDS::SComponent::_nil();
533
534   SALOMEDS::StudyBuilder_var    aStudyBuilder  = getStudyServant()->NewBuilder();
535   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
536
537   std::string compDataType = ComponentDataType(); // SMESH module's data type
538   std::string ior = SMESH_Gen_i::GetORB()->object_to_string( SMESH_Gen::_this() ); // IOR of this SMESH engine
539
540   // Find study component which corresponds to this SMESH engine
541
542   SALOMEDS::SComponent_wrap father;
543   SALOMEDS::SComponentIterator_wrap citer = getStudyServant()->NewComponentIterator();
544   for ( ; citer->More(); citer->Next()) {
545     SALOMEDS::SComponent_wrap f_i = citer->Value();
546     CORBA::String_var ior_i;
547     bool ok = f_i->ComponentIOR(ior_i.out());
548     if ( ok && compDataType == f_i->ComponentDataType() && ior == ior_i.in()) {
549       father = f_i;
550       break;
551     }
552   }
553   
554   if ( !CORBA::is_nil( father ) ) {
555     // check that the component is added to the use case browser
556     if ( !useCaseBuilder->IsUseCaseNode( father ) ) {
557       useCaseBuilder->SetRootCurrent();
558       useCaseBuilder->Append( father ); // component object is added as the top level item
559     }
560     return father._retn();
561   }
562
563   // If component for this SMESH engine does not exist in the study, create it
564
565   SALOME_ModuleCatalog::ModuleCatalog_var aCat =
566     SALOME_ModuleCatalog::ModuleCatalog::_narrow( GetNS()->Resolve("/Kernel/ModulCatalog") );
567   if ( CORBA::is_nil( aCat ) )
568     return father._retn();
569
570   SALOME_ModuleCatalog::Acomponent_var aComp = aCat->GetComponent( compDataType.c_str() );
571   if ( CORBA::is_nil( aComp ) )
572     return father._retn();
573
574   SALOMEDS::GenericAttribute_wrap anAttr;
575   SALOMEDS::AttributePixMap_wrap  aPixmap;
576
577   father  = aStudyBuilder->NewComponent( compDataType.c_str() );
578   aStudyBuilder->DefineComponentInstance( father, SMESH_Gen::_this() );
579   anAttr  = aStudyBuilder->FindOrCreateAttribute( father, "AttributePixMap" );
580   aPixmap = anAttr;
581   aPixmap->SetPixMap( "ICON_OBJBROWSER_SMESH" );
582   CORBA::String_var userName = aComp->componentusername();
583   SetName( father, userName.in(), "MESH" );
584   // add component to the use case tree
585   // (to support tree representation customization and drag-n-drop)
586   useCaseBuilder->SetRootCurrent();
587   useCaseBuilder->Append( father ); // component object is added as the top level item
588   if(MYDEBUG) MESSAGE("PublishComponent--END");
589
590   return father._retn();
591 }
592
593 //=======================================================================
594 //function : PublishMesh
595 //purpose  : 
596 //=======================================================================
597
598 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishMesh (SMESH::SMESH_Mesh_ptr theMesh,
599                                                 const char*           theName)
600 {
601   if ( !myIsEnablePublish )
602     return SALOMEDS::SObject::_nil();
603   if ( CORBA::is_nil( theMesh ))
604     return SALOMEDS::SObject::_nil();
605   if(MYDEBUG) MESSAGE("PublishMesh--IN");
606
607   // find or publish a mesh
608
609   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
610   if ( aMeshSO->_is_nil() )
611   {
612     SALOMEDS::SComponent_wrap father = PublishComponent();
613     if ( father->_is_nil() )
614       return aMeshSO._retn();
615
616     // Find correct free tag
617     long aTag = father->GetLastChildTag();
618     if ( aTag <= GetAlgorithmsRootTag() )
619       aTag = GetAlgorithmsRootTag() + 1;
620     else
621       aTag++;
622
623     aMeshSO = publish( theMesh, father, aTag, "ICON_SMESH_TREE_MESH_WARN" );
624     if ( aMeshSO->_is_nil() )
625       return aMeshSO._retn();
626   }
627   SetName( aMeshSO, theName, "Mesh" );
628
629   // Add shape reference
630
631   GEOM::GEOM_Object_var aShapeObject = theMesh->GetShapeToMesh();
632   if ( !CORBA::is_nil( aShapeObject )) {
633     addReference( aMeshSO, aShapeObject, GetRefOnShapeTag() );
634
635     // Publish global hypotheses
636
637     SMESH::ListOfHypothesis_var hypList = theMesh->GetHypothesisList( aShapeObject );
638     for ( CORBA::ULong i = 0; i < hypList->length(); i++ )
639     {
640       SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( hypList[ i ]);
641       SALOMEDS::SObject_wrap so = PublishHypothesis( aHyp );
642       AddHypothesisToShape( theMesh, aShapeObject, aHyp );
643     }
644   }
645
646   // Publish submeshes
647
648   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
649   if ( !mesh_i )
650     return aMeshSO._retn();
651   map<int, SMESH_subMesh_i*>& subMap = mesh_i->_mapSubMesh_i;
652   map<int, SMESH_subMesh_i*>::iterator subIt = subMap.begin();
653   for ( ; subIt != subMap.end(); subIt++ ) {
654     SMESH::SMESH_subMesh_ptr aSubMesh = (*subIt).second->_this();
655     if ( !CORBA::is_nil( aSubMesh )) {
656       aShapeObject = aSubMesh->GetSubShape();
657       SALOMEDS::SObject_wrap( PublishSubMesh( theMesh, aSubMesh, aShapeObject ));
658     }
659   }
660
661   // Publish groups
662   const map<int, SMESH::SMESH_GroupBase_ptr>& grMap = mesh_i->getGroups();
663   map<int, SMESH::SMESH_GroupBase_ptr>::const_iterator it = grMap.begin();
664   for ( ; it != grMap.end(); it++ )
665   {
666     SMESH::SMESH_GroupBase_ptr aGroup = (*it).second;
667     if ( !aGroup->_is_nil() ) {
668       GEOM::GEOM_Object_var aShapeObj;
669       SMESH::SMESH_GroupOnGeom_var aGeomGroup = SMESH::SMESH_GroupOnGeom::_narrow( aGroup );
670       if ( !aGeomGroup->_is_nil() )
671         aShapeObj = aGeomGroup->GetShape();
672       SALOMEDS::SObject_wrap( PublishGroup( theMesh, aGroup, aShapeObj ));
673     }
674   }
675
676   if(MYDEBUG) MESSAGE("PublishMesh_END");
677   return aMeshSO._retn();
678 }
679
680 //=======================================================================
681 //function : PublishSubMesh
682 //purpose  : 
683 //=======================================================================
684
685 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishSubMesh (SMESH::SMESH_Mesh_ptr    theMesh,
686                                                    SMESH::SMESH_subMesh_ptr theSubMesh,
687                                                    GEOM::GEOM_Object_ptr    theShapeObject,
688                                                    const char*              theName)
689 {
690   if ( !myIsEnablePublish )
691     return SALOMEDS::SObject::_nil();
692   if ( theMesh->_is_nil() || theSubMesh->_is_nil() || theShapeObject->_is_nil() )
693     return SALOMEDS::SObject::_nil();
694
695   std::string newName( theName ? theName : "" );
696
697   SALOMEDS::SObject_wrap aSubMeshSO = ObjectToSObject( theSubMesh );
698   if ( aSubMeshSO->_is_nil() )
699   {
700     SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
701     if ( aMeshSO->_is_nil() ) {
702       aMeshSO = PublishMesh( theMesh );
703       if ( aMeshSO->_is_nil())
704         return SALOMEDS::SObject::_nil();
705     }
706     // Find submesh sub-tree tag
707     long aRootTag;
708     const char* aRootName = "";
709     switch ( theShapeObject->GetShapeType() ) {
710     case GEOM::VERTEX:
711       aRootTag  = GetSubMeshOnVertexTag();
712       aRootName = "SubMeshes on Vertex";
713       break;
714     case GEOM::EDGE:
715       aRootTag  = GetSubMeshOnEdgeTag();
716       aRootName = "SubMeshes on Edge";
717       break;
718     case GEOM::WIRE:
719       aRootTag  = GetSubMeshOnWireTag();
720       aRootName = "SubMeshes on Wire";
721       break;
722     case GEOM::FACE:
723       aRootTag  = GetSubMeshOnFaceTag();
724       aRootName = "SubMeshes on Face";    
725       break;
726     case GEOM::SHELL:
727       aRootTag  = GetSubMeshOnShellTag();
728       aRootName = "SubMeshes on Shell";   
729       break;
730     case GEOM::SOLID:
731       aRootTag  = GetSubMeshOnSolidTag();
732       aRootName = "SubMeshes on Solid";
733       break;
734     default:
735       aRootTag  = GetSubMeshOnCompoundTag();
736       aRootName = "SubMeshes on Compound";
737       break;
738     }
739
740     // Find or create submesh root
741     SALOMEDS::SObject_wrap aRootSO = publish ( CORBA::Object::_nil(),
742                                                aMeshSO, aRootTag, 0, false );
743     if ( aRootSO->_is_nil() )
744       return aSubMeshSO._retn();
745
746     SetName( aRootSO, aRootName );
747
748     // Add new sub-mesh to corresponding sub-tree
749     int tag = 0; // to use a new SObject
750     if ( theName && theName[0] == '0' )
751     {
752       // theName can be an entry of an invalid sub-mesh which theSubMesh should replace
753       SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theName );
754       if ( aSObj )
755       {
756         CORBA::String_var oldName = aSObj->GetName();
757         newName = oldName.in();
758         SALOMEDS::SObject_wrap aRootSO2 = aSObj->GetFather();
759         if ( aRootSO->Tag() == aRootSO2->Tag() ) // same parent
760           tag = aSObj->Tag(); // to use the same SObject
761         else
762         {
763           CORBA::Object_var anObj = SObjectToObject( aSObj );
764           SMESH::SMESH_subMesh_var sm = SMESH::SMESH_subMesh::_narrow( anObj );
765           theMesh->RemoveSubMesh( sm );
766         }
767       }
768     }
769     SMESH::array_of_ElementType_var elemTypes = theSubMesh->GetTypes();
770     const int isEmpty = ( elemTypes->length() == 0 );
771     const char* pm[2] = { "ICON_SMESH_TREE_MESH", "ICON_SMESH_TREE_MESH_WARN" };
772     aSubMeshSO = publish ( theSubMesh, aRootSO, tag, pm[isEmpty] );
773     if ( aSubMeshSO->_is_nil() )
774       return aSubMeshSO._retn();
775
776     highLightInvalid( aSubMeshSO, false ); // now it is valid
777   }
778   SetName( aSubMeshSO, newName.c_str(), "SubMesh" );
779
780   // Add reference to theShapeObject
781
782   addReference( aSubMeshSO, theShapeObject, GetRefOnShapeTag() );
783
784   // Publish hypothesis
785
786   SMESH::ListOfHypothesis_var hypList = theMesh->GetHypothesisList( theShapeObject );
787   for ( CORBA::ULong i = 0; i < hypList->length(); i++ )
788   {
789     SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( hypList[ i ]);
790     SALOMEDS::SObject_wrap so = PublishHypothesis( aHyp );
791     AddHypothesisToShape( theMesh, theShapeObject, aHyp );
792   }
793
794   return aSubMeshSO._retn();
795 }
796
797 //=======================================================================
798 //function : PublishGroup
799 //purpose  : 
800 //=======================================================================
801
802 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishGroup (SMESH::SMESH_Mesh_ptr  theMesh,
803                                                  SMESH::SMESH_GroupBase_ptr theGroup,
804                                                  GEOM::GEOM_Object_ptr  theShapeObject,
805                                                  const char*            theName)
806 {
807   if ( !myIsEnablePublish )
808     return SALOMEDS::SObject::_nil();
809   if (theMesh->_is_nil() || theGroup->_is_nil() )
810     return SALOMEDS::SObject::_nil();
811
812   SALOMEDS::SObject_wrap aGroupSO = ObjectToSObject( theGroup );
813   if ( aGroupSO->_is_nil() )
814   {
815     SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
816     if ( aMeshSO->_is_nil() ) {
817       aMeshSO = PublishInStudy( SALOMEDS::SObject::_nil(), theMesh, "");
818       if ( aMeshSO->_is_nil())
819         return SALOMEDS::SObject::_nil();
820     }
821     size_t aType = (int)theGroup->GetType();
822     const char* aRootNames[] = {
823       "Compound Groups", "Groups of Nodes", "Groups of Edges",
824       "Groups of Faces", "Groups of Volumes", "Groups of 0D Elements",
825       "Groups of Balls" };
826
827     // Currently, groups with heterogeneous content are not supported
828     if ( aType != SMESH::ALL )
829     {
830       long aRootTag = GetNodeGroupsTag() + aType - 1;
831
832       // Find or create groups root
833       SALOMEDS::SObject_wrap aRootSO = publish ( CORBA::Object::_nil(),
834                                                  aMeshSO, aRootTag, 0, false );
835       if ( aRootSO->_is_nil() ) return SALOMEDS::SObject::_nil();
836
837       if ( aType < sizeof(aRootNames)/sizeof(char*) )
838         SetName( aRootSO, aRootNames[aType] );
839
840       // Add new group to corresponding sub-tree
841       int isEmpty = false;
842       std::string pm[2] = { "ICON_SMESH_TREE_GROUP", "ICON_SMESH_TREE_MESH_WARN" };
843       if ( SMESH::DownCast< SMESH_GroupOnFilter_i* > ( theGroup ))
844       {
845         pm[0] = "ICON_SMESH_TREE_GROUP_ON_FILTER";
846       }
847       else if ( SMESH::DownCast< SMESH_Group_i* > ( theGroup ))
848       {
849         if ( theGroup->GetType() == SMESH::NODE )
850           isEmpty = ( theMesh->NbNodes() == 0 );
851         else
852         {
853           SMESH::array_of_ElementType_var allElemTypes = theMesh->GetTypes();
854           for ( size_t i =0; i < allElemTypes->length() && isEmpty; ++i )
855             isEmpty = ( allElemTypes[i] != theGroup->GetType() );
856         }
857       }
858       aGroupSO = publish ( theGroup, aRootSO, 0, pm[isEmpty].c_str() );
859     }
860     if ( aGroupSO->_is_nil() )
861       return aGroupSO._retn();
862   }
863
864   SetName( aGroupSO, theName, "Group" );
865
866   //Add reference to geometry
867   if ( !theShapeObject->_is_nil() )
868     addReference( aGroupSO, theShapeObject, GetRefOnShapeTag() );
869
870   return aGroupSO._retn();
871 }
872
873 //=======================================================================
874 //function : PublishHypothesis
875 //purpose  : 
876 //=======================================================================
877
878 SALOMEDS::SObject_ptr
879   SMESH_Gen_i::PublishHypothesis (SMESH::SMESH_Hypothesis_ptr theHyp,
880                                   const char*                 theName)
881 {
882   if(MYDEBUG) MESSAGE("PublishHypothesis")
883   if ( !myIsEnablePublish )
884     return SALOMEDS::SObject::_nil();
885   if (theHyp->_is_nil())
886     return SALOMEDS::SObject::_nil();
887
888   CORBA::String_var hypType = theHyp->GetName();
889
890   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
891   if ( aHypSO->_is_nil() )
892   {
893     SALOMEDS::SComponent_wrap father = PublishComponent();
894     if ( father->_is_nil() )
895       return aHypSO._retn();
896
897     //Find or Create Hypothesis root
898     bool isAlgo = ( !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil() );
899     int aRootTag = isAlgo ? GetAlgorithmsRootTag() : GetHypothesisRootTag();
900     SALOMEDS::SObject_wrap aRootSO =
901       publish (CORBA::Object::_nil(),father, aRootTag,
902                isAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
903     SetName( aRootSO, isAlgo ?  "Algorithms" : "Hypotheses" );
904
905     // Add New Hypothesis
906     string aPmName = isAlgo ? "ICON_SMESH_TREE_ALGO_" : "ICON_SMESH_TREE_HYPO_";
907     aPmName += hypType.in();
908     // prepend plugin name to pixmap name
909     string pluginName = myHypCreatorMap[ hypType.in() ]->GetModuleName();
910     if ( pluginName != "StdMeshers" )
911       aPmName = pluginName + "::" + aPmName;
912     aHypSO = publish( theHyp, aRootSO, 0, aPmName.c_str() );
913   }
914
915   SetName( aHypSO, theName, hypType.in() );
916
917   if(MYDEBUG) MESSAGE("PublishHypothesis--END")
918   return aHypSO._retn();
919 }
920
921 //=======================================================================
922 //function : UpdateIcons
923 //purpose  : update icons of a mesh and its children upon mesh modification
924 //=======================================================================
925
926 void SMESH_Gen_i::UpdateIcons( SMESH::SMESH_Mesh_ptr theMesh )
927 {
928   SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( theMesh );
929   if ( ! mesh_i )
930     return;
931
932   SALOMEDS::SObject_wrap so = ObjectToSObject( theMesh );
933   if ( so->_is_nil() )
934     return;
935
936   // set icon of the mesh
937   if ( mesh_i->NbNodes() == 0 )
938     SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN" );
939   else if ( mesh_i->IsComputedOK() )
940     SetPixMap( so, "ICON_SMESH_TREE_MESH" );
941   else if ( mesh_i->HasShapeToMesh() )
942     SetPixMap( so, "ICON_SMESH_TREE_MESH_PARTIAL" );
943   else
944     SetPixMap( so, "ICON_SMESH_TREE_MESH_IMPORTED" );
945
946   // set icons of sub-objects
947   SALOMEDS::Study_var         study = getStudyServant();
948   SALOMEDS::ChildIterator_wrap iter = study->NewChildIterator( so );
949   for ( ; iter->More(); iter->Next() )
950   {
951     so = iter->Value(); // 1st level child - root of algos, hyps, sub-meshes or groups
952     if ( so->Tag() < SMESH::Tag_FirstSubMesh )
953       continue;
954
955     SALOMEDS::ChildIterator_wrap subIter = study->NewChildIterator( so );
956     for ( ; subIter->More(); subIter->Next() )
957     {
958       so = subIter->Value(); // 2nd level child - a sub-mesh or group
959
960       CORBA::Object_var           obj = SObjectToObject( so );
961       SMESH::SMESH_IDSource_var idSrc = SMESH::SMESH_IDSource::_narrow( obj );
962       if ( idSrc->_is_nil() )
963         continue;
964
965       SMESH::SMESH_GroupBase_var     grp = SMESH::SMESH_GroupBase::_narrow( obj );
966       SMESH::SMESH_GroupOnFilter_var gof = SMESH::SMESH_GroupOnFilter::_narrow( obj );
967       const bool         isGroup = !grp->_is_nil();
968       const bool isGroupOnFilter = !gof->_is_nil();
969
970       bool isEmpty = ( mesh_i->NbNodes() == 0 );
971       if ( !isEmpty )
972       {
973         if ( isGroupOnFilter ) // GetTypes() can be very long on GroupOnFilter!
974         {
975           SMESH::long_array_var nbByType = mesh_i->GetNbElementsByType();
976           isEmpty = ( nbByType[ grp->GetType() ] == 0 );
977         }
978         else
979         {
980           SMESH::array_of_ElementType_var elemTypes = idSrc->GetTypes();
981           isEmpty = ( elemTypes->length() == 0 );
982         }
983       }
984       if ( isEmpty )
985         SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN");
986       else if ( !isGroup )
987         SetPixMap( so, "ICON_SMESH_TREE_MESH" );
988       else if ( isGroupOnFilter )
989         SetPixMap( so, "ICON_SMESH_TREE_GROUP_ON_FILTER" );
990       else
991         SetPixMap( so, "ICON_SMESH_TREE_GROUP" );
992     }
993   }
994 }
995
996 //=======================================================================
997 //function : HighLightInvalid
998 //purpose  : change font color of a object in the Object Browser
999 //=======================================================================
1000
1001 void SMESH_Gen_i::HighLightInvalid( CORBA::Object_ptr theObject, bool isInvalid )
1002 {
1003   SALOMEDS::SObject_wrap so = ObjectToSObject(theObject);
1004   highLightInvalid( so.in(), isInvalid );
1005 }
1006
1007 //=======================================================================
1008 //function : highLightInvalid
1009 //purpose  : change font color of a object in the Object Browser
1010 //=======================================================================
1011
1012 void SMESH_Gen_i::highLightInvalid( SALOMEDS::SObject_ptr theSObject, bool isInvalid )
1013 {
1014   if ( !theSObject->_is_nil() )
1015   {
1016     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1017     if ( isInvalid )
1018     {
1019       SALOMEDS::Color red = { 178,34,34 }; // to differ from reference color
1020       SALOMEDS::GenericAttribute_wrap attr =
1021         studyBuilder->FindOrCreateAttribute( theSObject, "AttributeTextColor" );
1022       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1023       colorAttr->SetTextColor( red );
1024     }
1025     else
1026     {
1027       studyBuilder->RemoveAttribute( theSObject, "AttributeTextColor" );
1028     }
1029   }
1030 }
1031
1032 //=======================================================================
1033 //function : GetMeshOrSubmeshByShape
1034 //purpose  : 
1035 //=======================================================================
1036
1037 SALOMEDS::SObject_ptr
1038 SMESH_Gen_i::GetMeshOrSubmeshByShape (SMESH::SMESH_Mesh_ptr theMesh,
1039                                       GEOM::GEOM_Object_ptr theShape)
1040 {
1041   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape")
1042   SALOMEDS::SObject_wrap aMeshOrSubMesh;
1043   if (theMesh->_is_nil() || ( theShape->_is_nil() && theMesh->HasShapeToMesh()))
1044     return aMeshOrSubMesh._retn();
1045   
1046   TopoDS_Shape aShape;
1047   if(theMesh->HasShapeToMesh())
1048     aShape = GeomObjectToShape( theShape );
1049   else
1050     aShape = SMESH_Mesh::PseudoShape();
1051
1052   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1053
1054   if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1055     SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1056     if ( aShape.IsSame( meshDS->ShapeToMesh() ))
1057       aMeshOrSubMesh = ObjectToSObject( theMesh );
1058     else {
1059       int shapeID = meshDS->ShapeToIndex( aShape );
1060       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1061       if ( !aSubMesh->_is_nil() )
1062         aMeshOrSubMesh = ObjectToSObject( aSubMesh );
1063     }
1064   }
1065   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape--END")
1066   return aMeshOrSubMesh._retn();
1067 }
1068
1069 //=======================================================================
1070 //function : AddHypothesisToShape
1071 //purpose  : 
1072 //=======================================================================
1073
1074 bool SMESH_Gen_i::AddHypothesisToShape(SMESH::SMESH_Mesh_ptr       theMesh,
1075                                        GEOM::GEOM_Object_ptr       theShape,
1076                                        SMESH::SMESH_Hypothesis_ptr theHyp)
1077 {
1078   if(MYDEBUG) MESSAGE("AddHypothesisToShape")
1079   if (theMesh->_is_nil() ||
1080       theHyp->_is_nil() || (theShape->_is_nil()
1081                             && theMesh->HasShapeToMesh()) )
1082     return false;
1083
1084   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
1085   if ( aMeshSO->_is_nil() )
1086     aMeshSO = PublishMesh( theMesh );
1087   SALOMEDS::SObject_wrap aHypSO = PublishHypothesis( theHyp );
1088   if ( aMeshSO->_is_nil() || aHypSO->_is_nil())
1089     return false;
1090
1091   // Find a mesh or submesh referring to theShape
1092   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1093     GetMeshOrSubmeshByShape( theMesh, theShape );
1094   if ( aMeshOrSubMesh->_is_nil() )
1095   {
1096     // publish submesh
1097     TopoDS_Shape aShape = GeomObjectToShape( theShape );
1098     SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1099     if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1100       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1101       int shapeID = meshDS->ShapeToIndex( aShape );
1102       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1103       aMeshOrSubMesh = PublishSubMesh( theMesh, aSubMesh, theShape );
1104     }
1105     if ( aMeshOrSubMesh->_is_nil() )
1106       return false;
1107   }
1108
1109   //Find or Create Applied Hypothesis root
1110   bool aIsAlgo = !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil();
1111   SALOMEDS::SObject_wrap AHR =
1112     publish (CORBA::Object::_nil(), aMeshOrSubMesh,
1113              aIsAlgo ? GetRefOnAppliedAlgorithmsTag() : GetRefOnAppliedHypothesisTag(),
1114              aIsAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
1115   SetName( AHR, aIsAlgo ? "Applied algorithms" : "Applied hypotheses" );
1116
1117   addReference( AHR, theHyp );
1118
1119   if(MYDEBUG) MESSAGE("AddHypothesisToShape--END")
1120   return true;
1121 }
1122
1123 //=======================================================================
1124 //function : RemoveHypothesisFromShape
1125 //purpose  : 
1126 //=======================================================================
1127
1128 bool SMESH_Gen_i::RemoveHypothesisFromShape(SMESH::SMESH_Mesh_ptr       theMesh,
1129                                             GEOM::GEOM_Object_ptr       theShape,
1130                                             SMESH::SMESH_Hypothesis_ptr theHyp)
1131 {
1132   if (theMesh->_is_nil() ||
1133       theHyp->_is_nil() || (theShape->_is_nil()
1134                             && theMesh->HasShapeToMesh()))
1135     return false;
1136
1137   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
1138   if ( aHypSO->_is_nil() )
1139     return false;
1140
1141   CORBA::String_var hypEntry = aHypSO->GetID();
1142
1143   // Find a mesh or sub-mesh referring to theShape
1144   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1145     GetMeshOrSubmeshByShape( theMesh, theShape );
1146   if ( aMeshOrSubMesh->_is_nil() )
1147     return false;
1148
1149   // Find and remove a reference to aHypSO
1150   SALOMEDS::SObject_wrap aRef, anObj;
1151   SALOMEDS::ChildIterator_wrap it = getStudyServant()->NewChildIterator( aMeshOrSubMesh );
1152   bool found = false;
1153   for ( it->InitEx( true ); ( it->More() && !found ); it->Next() ) {
1154     anObj = it->Value();
1155     if (anObj->ReferencedObject( aRef.inout() ))
1156     {
1157       CORBA::String_var refEntry = aRef->GetID();
1158       found = ( strcmp( refEntry, hypEntry ) == 0 );
1159     }
1160     if ( found )
1161     {
1162       SALOMEDS::StudyBuilder_var builder = getStudyServant()->NewBuilder();
1163       builder->RemoveObject( anObj );
1164     }
1165   }
1166
1167   return true;
1168 }
1169
1170 //================================================================================
1171 /*!
1172  * \brief Stores names of variables that WILL be passes as parameters when calling
1173  *        some method of a given object.
1174  *  \param [in] theObject - the object whose a method WILL be called with \a theParameters.
1175  *  \param [in] theParameters - a string containing parameters separated by ':'.
1176  */
1177 //================================================================================
1178
1179 void SMESH_Gen_i::UpdateParameters(CORBA::Object_ptr theObject, const char* theParameters)
1180 {
1181   // find variable names within theParameters
1182
1183   myLastObj.clear();
1184   myLastParameters.clear();
1185   myLastParamIndex.clear(); /* vector holding indices of virables within the string
1186                                of all variables used for theObject */ 
1187   int nbVars = 0;
1188   int pos = 0, prevPos = 0, len = strlen( theParameters );
1189   if ( len == 0 ) return;
1190   while ( pos <= len )
1191   {
1192     if ( pos == len || theParameters[pos] == ':' )
1193     {
1194       if ( prevPos < pos )
1195       {
1196         string val( theParameters + prevPos, theParameters + pos );
1197         if ( !getStudyServant()->IsVariable( val.c_str() ))
1198           val.clear();
1199         myLastParameters.push_back( val );
1200         nbVars += (! myLastParameters.back().empty() );
1201       }
1202       else
1203       {
1204         myLastParameters.push_back("");
1205       }
1206       prevPos = pos+1;
1207     }
1208     ++pos;
1209   }
1210
1211   if ( nbVars < 1 )
1212     return;
1213
1214   // store
1215   // (1) variable names in the string of all variables used for theObject and
1216   // (2) indices of found variables in myLastParamIndex.
1217
1218   // remember theObject
1219   SALOMEDS::SObject_wrap aSObj =  ObjectToSObject(theObject);
1220   if ( aSObj->_is_nil() )
1221     return;
1222   CORBA::String_var anObjEntry = aSObj->GetID();
1223   myLastObj = anObjEntry.in();
1224
1225   // get a string of variable names
1226   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1227   SALOMEDS::GenericAttribute_wrap     anAttr =
1228     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1229   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1230   CORBA::String_var                  oldVars = aStringAttr->Value();
1231   std::string                         varStr = oldVars.in();
1232
1233   // add new variables and find indices of variables
1234   for ( size_t i = 0; i < myLastParameters.size(); ++i )
1235   {
1236     int varIndex = -1;
1237     if ( !myLastParameters[i].empty() )
1238     {
1239       // find index of myLastParameters[i] in varStr
1240       int curIndex  = 0;
1241       bool varFound = false;
1242       size_t pos    = 0;
1243       // varStr can be "A|B::C;*=2|D"
1244       const std::string separators(":|;*=");
1245       while ( pos < varStr.size() && !varFound )
1246       {
1247         // skip separators
1248         while ( separators.find( varStr[ pos ]) != std::string::npos )
1249           if ( ++pos >= varStr.size() )
1250             break;
1251         // skip repetition number following '='
1252         if ( varStr[ pos-1 ] == '=' )
1253         {
1254           while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1255             ++pos;
1256           continue; // to skip next separator
1257         }
1258         // compare variable name
1259         if ( pos < varStr.size() )
1260         {
1261           varFound = ( varStr.compare( pos, myLastParameters[i].size(), myLastParameters[i] ) == 0 &&
1262                        // same string beginning but is length same?
1263                        ( pos + myLastParameters[i].size() >= varStr.size() ||
1264                          separators.find( varStr[ pos+1 ]) != std::string::npos ));
1265           if ( varFound )
1266             varIndex = curIndex;
1267           else
1268             pos = varStr.find_first_of( separators, pos ); // goto the next separator
1269           ++curIndex;
1270         }
1271       }
1272       // add new variable
1273       if ( !varFound )
1274       {
1275         varStr += ":" + myLastParameters[i];
1276         varIndex = curIndex;
1277       }
1278     }
1279     myLastParamIndex.push_back( varIndex );
1280   }
1281   aStringAttr->SetValue( varStr.c_str() );
1282 }
1283
1284 //================================================================================
1285 /*!
1286  * \brief Return all variables used to create an object
1287  *  \param [in] theObjectEntry - an object entry in the current study
1288  *  \return std::vector< std::string > - all variable names (or values of removed variables)
1289  */
1290 //================================================================================
1291
1292 std::vector< std::string > SMESH_Gen_i::GetAllParameters(const std::string& theObjectEntry) const
1293 {
1294   std::vector< std::string > varNames;
1295
1296   SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theObjectEntry.c_str() );
1297
1298   // get a string of variable names
1299   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1300   SALOMEDS::GenericAttribute_wrap     anAttr =
1301     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1302   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1303   CORBA::String_var                  oldVars = aStringAttr->Value();
1304   std::string                         varStr = oldVars.in();
1305
1306   // separate variables within varStr;
1307   // varStr can be "A|B::C;*=2|D"
1308   size_t pos = 0;
1309   const std::string separators(":|;*=");
1310   while ( pos < varStr.size() )
1311   {
1312     // skip separators
1313     pos = varStr.find_first_not_of( separators, pos );
1314     // while ( separators.find( varStr[ pos ]) != std::string::npos )
1315     //   if ( ++pos >= varStr.size() )
1316     //     break;
1317     // skip repetition number following '='
1318     if ( varStr[ pos-1 ] == '=' )
1319     {
1320       while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1321         ++pos;
1322       continue; // to skip next separator
1323     }
1324     // store variable name
1325     if ( pos < varStr.size() )
1326     {
1327       size_t pos2 = varStr.find_first_of( separators, pos );
1328       varNames.push_back( varStr.substr( pos, pos2 - pos));
1329       pos = pos2;
1330     }
1331   }
1332   return varNames;
1333 }
1334
1335 //=======================================================================
1336 //function : ParseParameters
1337 //purpose  : Replace variables by their values
1338 //=======================================================================
1339 // char* SMESH_Gen_i::ParseParameters(const char* theParameters)
1340 // {
1341 //   //const char* aParameters = theParameters;
1342 // //   const char* aParameters = CORBA::string_dup(theParameters);
1343 //   TCollection_AsciiString anInputParams;
1344 //   SALOMEDS::Study_var aStudy = getStudyServant();
1345 //   if( !aStudy->_is_nil() ) {
1346 // //     SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(theParameters);
1347 // //     for(int j=0;j<aSections->length();j++) {
1348 // //       SALOMEDS::ListOfStrings aVars= aSections[j];
1349 // //       for(int i=0;i<aVars.length();i++ ) {
1350 // //         anInputParams += aStudy->IsVariable(aVars[i].in()) ? 
1351 // //           TCollection_AsciiString(aVars[i].in()) : TCollection_AsciiString("");
1352 // //         if(i != aVars.length()-1)
1353 // //           anInputParams+=":";
1354 // //       }
1355 // //       if(j!=aSections->length()-1)
1356 // //         anInputParams+="|";
1357 // //     }
1358 //     TCollection_AsciiString paramStr( theParameters );
1359 //     int beg = 0, end;
1360 //     char sep, *pParams = (char*)paramStr.ToCString();
1361 //     while ( beg < paramStr.Length() )
1362 //     {
1363 //       end = beg-1;
1364 //       while ( ++end < paramStr.Length() )
1365 //         if ( pParams[end] == ':' || pParams[end] == '|')
1366 //           break;
1367 //       if ( end < paramStr.Length())
1368 //       {
1369 //         sep = pParams[end];
1370 //         pParams[end] = '\0';
1371 //       }
1372 //       if ( aStudy->IsVariable( pParams+beg ))
1373 //         anInputParams += pParams+beg;
1374 //       if ( end < paramStr.Length() )
1375 //         anInputParams += sep;
1376 //       else
1377 //         break;
1378 //       beg = end + 1;
1379 //     }
1380 //   }
1381 //   return CORBA::string_dup(anInputParams.ToCString());
1382 // }
1383
1384 //=======================================================================
1385 //function : GetParameters
1386 //purpose  : 
1387 //=======================================================================
1388
1389 char* SMESH_Gen_i::GetParameters(CORBA::Object_ptr theObject)
1390 {
1391   CORBA::String_var aResult("");
1392
1393   SALOMEDS::SObject_wrap aSObj = ObjectToSObject( theObject );
1394   if ( !aSObj->_is_nil() )
1395   {
1396     SALOMEDS::GenericAttribute_wrap attr;
1397     if ( aSObj->FindAttribute( attr.inout(), "AttributeString"))
1398     {
1399       SALOMEDS::AttributeString_wrap strAttr = attr;
1400       aResult = strAttr->Value();
1401     }
1402   }
1403   return aResult._retn();
1404 }
1405
1406 //================================================================================
1407 /*!
1408  * \brief Create a sub-mesh on a geometry that is not a sub-shape of the main shape
1409  * for the case where a valid sub-shape not found by CopyMeshWithGeom().
1410  * The invalid sub-mesh has GetId() < 0.
1411  */
1412 //================================================================================
1413
1414 SMESH::SMESH_subMesh_ptr
1415 SMESH_Gen_i::createInvalidSubMesh(SMESH::SMESH_Mesh_ptr theMesh,
1416                                   GEOM::GEOM_Object_ptr theStrangerGeom,
1417                                   const char*           theName)
1418 {
1419   SMESH::SMESH_subMesh_var subMesh;
1420
1421   try
1422   {
1423     SMESH_Mesh_i* mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1424     subMesh = mesh_i->createSubMesh( theStrangerGeom );
1425
1426     if ( !subMesh->_is_nil() && CanPublishInStudy( subMesh ))
1427     {
1428       SALOMEDS::SObject_wrap so = PublishSubMesh( theMesh, subMesh, theStrangerGeom, theName );
1429
1430       // hide a reference to geometry
1431       if ( !so->_is_nil() )
1432       {
1433         SALOMEDS::SObject_wrap refSO;
1434         if ( so->FindSubObject( GetRefOnShapeTag(), refSO.inout() ))
1435         {
1436           SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1437           SALOMEDS::GenericAttribute_wrap attr =
1438             studyBuilder->FindOrCreateAttribute( refSO, "AttributeDrawable" );
1439           SALOMEDS::AttributeDrawable_wrap ga = attr;
1440           ga->SetDrawable( false );
1441         }
1442       }
1443     }
1444   }
1445   catch (...) {
1446   }
1447
1448   return subMesh._retn();
1449 }
1450
1451
1452 // ==============
1453 // Study context
1454 // ==============
1455
1456 //=======================================================================
1457 //function : addObject
1458 //purpose  : register object in the internal map and return its id
1459 //=======================================================================
1460
1461 int StudyContext::addObject( const std::string& theIOR )
1462 {
1463   int nextId = getNextId();
1464   mapIdToIOR.Bind( nextId, theIOR );
1465   return nextId;
1466 }
1467
1468 //=======================================================================
1469 //function : findId
1470 //purpose  : find the object id in the internal map by the IOR
1471 //=======================================================================
1472
1473 int StudyContext::findId( const std::string& theIOR )
1474 {
1475   TInt2StringMap::iterator imap;
1476   for ( imap = mapIdToIOR.begin(); imap != mapIdToIOR.end(); ++imap ) {
1477     if ( *imap == theIOR )
1478       return imap.Iterator().Key();
1479   }
1480   return 0;
1481 }
1482
1483 //=======================================================================
1484 //function : getIORbyId
1485 //purpose  : get object's IOR by id
1486 //=======================================================================
1487
1488 std::string StudyContext::getIORbyId( const int theId )
1489 {
1490   if ( mapIdToIOR.IsBound( theId ) )
1491     return mapIdToIOR( theId );
1492   return std::string();
1493 }
1494
1495 //=======================================================================
1496 //function : getIORbyOldId
1497 //purpose  : get object's IOR by old id
1498 //=======================================================================
1499
1500 std::string StudyContext::getIORbyOldId( const int theOldId )
1501 {
1502   if ( mapIdToId.IsBound( theOldId ) )
1503     return getIORbyId( mapIdToId( theOldId ));
1504   return std::string();
1505 }
1506
1507 //=======================================================================
1508 //function : mapOldToNew
1509 //purpose  : maps old object id to the new one (used when restoring data)
1510 //=======================================================================
1511
1512 void StudyContext::mapOldToNew( const int oldId, const int newId )
1513 {
1514   mapIdToId.Bind( oldId, newId );
1515 }
1516
1517 //=======================================================================
1518 //function : getOldId
1519 //purpose  : get old id by a new one
1520 //=======================================================================
1521
1522 int StudyContext::getOldId( const int newId )
1523 {
1524   TInt2IntMap::iterator imap;
1525   for ( imap = mapIdToId.begin(); imap != mapIdToId.end(); ++imap ) {
1526     if ( *imap == newId )
1527       return imap.Iterator().Key();
1528   }
1529   return 0;
1530 }
1531
1532 //=======================================================================
1533 //function : Clear
1534 //purpose  : clear data
1535 //=======================================================================
1536
1537 void StudyContext::Clear()
1538 {
1539   mapIdToIOR.Clear();
1540   mapIdToId.Clear();
1541 }