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