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