Salome HOME
0023636: EDF 18217 - Problem wen suppressing CAD
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i_1.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  File      : SMESH_Gen_i_1.cxx
23 //  Created   : Thu Oct 21 17:24:06 2004
24 //  Author    : Edward AGAPOV (eap)
25 //  Module    : SMESH
26
27 #include "SMESH_Gen_i.hxx"
28
29 #include "SMESHDS_Mesh.hxx"
30 #include "SMESH_Algo_i.hxx"
31 #include "SMESH_Comment.hxx"
32 #include "SMESH_Group_i.hxx"
33 #include "SMESH_Hypothesis_i.hxx"
34 #include "SMESH_Mesh_i.hxx"
35 #include "SMESH_subMesh_i.hxx"
36
37 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
38
39 #include <utilities.h>
40 #include <Utils_ExceptHandlers.hxx>
41 #include <SALOMEDS_wrap.hxx>
42 #include <SALOMEDS_Attributes_wrap.hxx>
43 #include <SALOME_KernelServices.hxx>
44
45 #include <TCollection_AsciiString.hxx>
46 #include <TopoDS_Solid.hxx>
47
48 #include <cctype>
49
50 #ifdef _DEBUG_
51 static int MYDEBUG = 0;
52 #else
53 static int MYDEBUG = 0;
54 #endif
55
56 using namespace std;
57
58 //=============================================================================
59 /*!
60  *  Get...Tag [ static ]
61  *
62  *  Methods which determine SMESH data model structure
63  */
64 //=============================================================================
65
66 long SMESH_Gen_i::GetHypothesisRootTag()
67 {
68   return SMESH::Tag_HypothesisRoot;
69 }
70
71 long SMESH_Gen_i::GetAlgorithmsRootTag()
72 {
73   return SMESH::Tag_AlgorithmsRoot;
74 }
75
76 long SMESH_Gen_i::GetRefOnShapeTag()
77 {
78   return SMESH::Tag_RefOnShape;
79 }
80
81 long SMESH_Gen_i::GetRefOnAppliedHypothesisTag()
82 {
83   return SMESH::Tag_RefOnAppliedHypothesis;
84 }
85
86 long SMESH_Gen_i::GetRefOnAppliedAlgorithmsTag()
87 {
88   return SMESH::Tag_RefOnAppliedAlgorithms;
89 }
90
91 long SMESH_Gen_i::GetSubMeshOnVertexTag()
92 {
93   return SMESH::Tag_SubMeshOnVertex;
94 }
95
96 long SMESH_Gen_i::GetSubMeshOnEdgeTag()
97 {
98   return SMESH::Tag_SubMeshOnEdge;
99 }
100
101 long SMESH_Gen_i::GetSubMeshOnFaceTag()
102 {
103   return SMESH::Tag_SubMeshOnFace;
104 }
105
106 long SMESH_Gen_i::GetSubMeshOnSolidTag()
107 {
108   return SMESH::Tag_SubMeshOnSolid;
109 }
110
111 long SMESH_Gen_i::GetSubMeshOnCompoundTag()
112 {
113   return SMESH::Tag_SubMeshOnCompound;
114 }
115
116 long SMESH_Gen_i::GetSubMeshOnWireTag()
117 {
118   return SMESH::Tag_SubMeshOnWire;
119 }
120
121 long SMESH_Gen_i::GetSubMeshOnShellTag()
122 {
123   return SMESH::Tag_SubMeshOnShell;
124 }
125
126 long SMESH_Gen_i::GetNodeGroupsTag()
127 {
128   return SMESH::Tag_NodeGroups;
129 }
130
131 long SMESH_Gen_i::GetEdgeGroupsTag()
132 {
133   return SMESH::Tag_EdgeGroups;
134 }
135
136 long SMESH_Gen_i::GetFaceGroupsTag()
137 {
138   return SMESH::Tag_FaceGroups;
139 }
140
141 long SMESH_Gen_i::GetVolumeGroupsTag()
142 {
143   return SMESH::Tag_VolumeGroups;
144 }
145
146 long SMESH_Gen_i::Get0DElementsGroupsTag()
147 {
148   return SMESH::Tag_0DElementsGroups;
149 }
150
151 long SMESH_Gen_i::GetBallElementsGroupsTag()
152 {
153   return SMESH::Tag_BallElementsGroups;
154 }
155
156 //=============================================================================
157 /*!
158  *  SMESH_Gen_i::CanPublishInStudy
159  *
160  *  Returns true if object can be published in the study
161  */
162 //=============================================================================
163
164 bool SMESH_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
165 {
166   if(MYDEBUG) MESSAGE("CanPublishInStudy - "<<!CORBA::is_nil(getStudyServant()));
167   
168   if ( !myIsEnablePublish )
169     return false;
170
171   SMESH::SMESH_Mesh_var aMesh       = SMESH::SMESH_Mesh::_narrow(theIOR);
172   if( !aMesh->_is_nil() )
173     return true;
174
175   SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow(theIOR);
176   if( !aSubMesh->_is_nil() )
177     return true;
178
179   SMESH::SMESH_Hypothesis_var aHyp  = SMESH::SMESH_Hypothesis::_narrow(theIOR);
180   if( !aHyp->_is_nil() )
181     return true;
182
183   SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(theIOR);
184   if( !aGroup->_is_nil() )
185     return true;
186
187   if(MYDEBUG) MESSAGE("CanPublishInStudy--CANT");
188   return false;
189 }
190
191 //=======================================================================
192 //function : ObjectToSObject
193 //purpose  : Put a result into a SALOMEDS::SObject_wrap or call UnRegister()!
194 //=======================================================================
195
196 SALOMEDS::SObject_ptr SMESH_Gen_i::ObjectToSObject(CORBA::Object_ptr theObject)
197 {
198   SALOMEDS::SObject_wrap aSO;
199   if ( !CORBA::is_nil( theObject ))
200   {
201     CORBA::String_var objStr = SMESH_Gen_i::GetORB()->object_to_string( theObject );
202     aSO = getStudyServant()->FindObjectIOR( objStr.in() );
203   }
204   return aSO._retn();
205 }
206
207 //=======================================================================
208 //function : GetStudyPtr
209 //purpose  : Get study from naming service
210 //=======================================================================
211 SALOMEDS::Study_var SMESH_Gen_i::getStudyServant()
212 {
213   return SALOMEDS::Study::_duplicate(KERNEL::getStudyServant());
214 }
215
216 //=======================================================================
217 //function : objectToServant
218 //purpose  : 
219 //=======================================================================
220
221 template<typename T> static inline T* objectToServant( CORBA::Object_ptr theIOR )
222 {
223   return dynamic_cast<T*>( SMESH_Gen_i::GetServant( theIOR ).in() );
224 }
225
226 //=======================================================================
227 //function : ShapeToGeomObject
228 //purpose  : 
229 //=======================================================================
230
231 GEOM::GEOM_Object_ptr SMESH_Gen_i::ShapeToGeomObject (const TopoDS_Shape& theShape )
232 {
233   GEOM::GEOM_Object_var aShapeObj;
234   if ( !theShape.IsNull() ) {
235     GEOM_Client* aClient = GetShapeReader();
236     TCollection_AsciiString IOR;
237     if ( aClient && aClient->Find( theShape, IOR ))
238     {
239       CORBA::Object_var obj = GetORB()->string_to_object( IOR.ToCString() );
240       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 = false;
843       std::string pm[2] = { "ICON_SMESH_TREE_GROUP", "ICON_SMESH_TREE_MESH_WARN" };
844       if ( SMESH::DownCast< SMESH_GroupOnFilter_i* > ( theGroup ))
845       {
846         pm[0] = "ICON_SMESH_TREE_GROUP_ON_FILTER";
847       }
848       else if ( SMESH::DownCast< SMESH_Group_i* > ( theGroup ))
849       {
850         if ( theGroup->GetType() == SMESH::NODE )
851           isEmpty = ( theMesh->NbNodes() == 0 );
852         else
853         {
854           SMESH::array_of_ElementType_var allElemTypes = theMesh->GetTypes();
855           for ( size_t i =0; i < allElemTypes->length() && isEmpty; ++i )
856             isEmpty = ( allElemTypes[i] != theGroup->GetType() );
857         }
858       }
859       aGroupSO = publish ( theGroup, aRootSO, 0, pm[isEmpty].c_str() );
860     }
861     if ( aGroupSO->_is_nil() )
862       return aGroupSO._retn();
863   }
864
865   SetName( aGroupSO, theName, "Group" );
866
867   //Add reference to geometry
868   if ( !theShapeObject->_is_nil() )
869     addReference( aGroupSO, theShapeObject, GetRefOnShapeTag() );
870
871   return aGroupSO._retn();
872 }
873
874 //=======================================================================
875 //function : PublishHypothesis
876 //purpose  : 
877 //=======================================================================
878
879 SALOMEDS::SObject_ptr
880   SMESH_Gen_i::PublishHypothesis (SMESH::SMESH_Hypothesis_ptr theHyp,
881                                   const char*                 theName)
882 {
883   if(MYDEBUG) MESSAGE("PublishHypothesis")
884   if ( !myIsEnablePublish )
885     return SALOMEDS::SObject::_nil();
886   if (theHyp->_is_nil())
887     return SALOMEDS::SObject::_nil();
888
889   CORBA::String_var hypType = theHyp->GetName();
890
891   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
892   if ( aHypSO->_is_nil() )
893   {
894     SALOMEDS::SComponent_wrap father = PublishComponent();
895     if ( father->_is_nil() )
896       return aHypSO._retn();
897
898     //Find or Create Hypothesis root
899     bool isAlgo = ( !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil() );
900     int aRootTag = isAlgo ? GetAlgorithmsRootTag() : GetHypothesisRootTag();
901     SALOMEDS::SObject_wrap aRootSO =
902       publish (CORBA::Object::_nil(),father, aRootTag,
903                isAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
904     SetName( aRootSO, isAlgo ?  "Algorithms" : "Hypotheses" );
905
906     // Add New Hypothesis
907     string aPmName = isAlgo ? "ICON_SMESH_TREE_ALGO_" : "ICON_SMESH_TREE_HYPO_";
908     aPmName += hypType.in();
909     // prepend plugin name to pixmap name
910     string pluginName = myHypCreatorMap[ hypType.in() ]->GetModuleName();
911     if ( pluginName != "StdMeshers" )
912       aPmName = pluginName + "::" + aPmName;
913     aHypSO = publish( theHyp, aRootSO, 0, aPmName.c_str() );
914   }
915
916   SetName( aHypSO, theName, hypType.in() );
917
918   if(MYDEBUG) MESSAGE("PublishHypothesis--END")
919   return aHypSO._retn();
920 }
921
922 //=======================================================================
923 //function : UpdateIcons
924 //purpose  : update icons of a mesh and its children upon mesh modification
925 //=======================================================================
926
927 void SMESH_Gen_i::UpdateIcons( SMESH::SMESH_Mesh_ptr theMesh )
928 {
929   SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( theMesh );
930   if ( ! mesh_i )
931     return;
932
933   SALOMEDS::SObject_wrap so = ObjectToSObject( theMesh );
934   if ( so->_is_nil() )
935     return;
936
937   // set icon of the mesh
938   if ( mesh_i->NbNodes() == 0 )
939     SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN" );
940   else if ( mesh_i->IsComputedOK() )
941     SetPixMap( so, "ICON_SMESH_TREE_MESH" );
942   else if ( mesh_i->HasShapeToMesh() )
943     SetPixMap( so, "ICON_SMESH_TREE_MESH_PARTIAL" );
944   else
945     SetPixMap( so, "ICON_SMESH_TREE_MESH_IMPORTED" );
946
947   // set icons of sub-objects
948   SALOMEDS::Study_var         study = getStudyServant();
949   SALOMEDS::ChildIterator_wrap iter = study->NewChildIterator( so );
950   for ( ; iter->More(); iter->Next() )
951   {
952     so = iter->Value(); // 1st level child - root of algos, hyps, sub-meshes or groups
953     if ( so->Tag() < SMESH::Tag_FirstSubMesh )
954       continue;
955
956     SALOMEDS::ChildIterator_wrap subIter = study->NewChildIterator( so );
957     for ( ; subIter->More(); subIter->Next() )
958     {
959       so = subIter->Value(); // 2nd level child - a sub-mesh or group
960
961       CORBA::Object_var           obj = SObjectToObject( so );
962       SMESH::SMESH_IDSource_var idSrc = SMESH::SMESH_IDSource::_narrow( obj );
963       if ( idSrc->_is_nil() )
964         continue;
965
966       SMESH::SMESH_GroupBase_var     grp = SMESH::SMESH_GroupBase::_narrow( obj );
967       SMESH::SMESH_GroupOnFilter_var gof = SMESH::SMESH_GroupOnFilter::_narrow( obj );
968       const bool         isGroup = !grp->_is_nil();
969       const bool isGroupOnFilter = !gof->_is_nil();
970
971       bool isEmpty = ( mesh_i->NbNodes() == 0 );
972       if ( !isEmpty )
973       {
974         if ( isGroupOnFilter ) // GetTypes() can be very long on GroupOnFilter!
975         {
976           SMESH::long_array_var nbByType = mesh_i->GetNbElementsByType();
977           isEmpty = ( nbByType[ grp->GetType() ] == 0 );
978         }
979         else
980         {
981           SMESH::array_of_ElementType_var elemTypes = idSrc->GetTypes();
982           isEmpty = ( elemTypes->length() == 0 );
983         }
984       }
985       if ( isEmpty )
986         SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN");
987       else if ( !isGroup )
988         SetPixMap( so, "ICON_SMESH_TREE_MESH" );
989       else if ( isGroupOnFilter )
990         SetPixMap( so, "ICON_SMESH_TREE_GROUP_ON_FILTER" );
991       else
992         SetPixMap( so, "ICON_SMESH_TREE_GROUP" );
993     }
994   }
995 }
996
997 //=======================================================================
998 //function : HighLightInvalid
999 //purpose  : change font color of a object in the Object Browser
1000 //=======================================================================
1001
1002 void SMESH_Gen_i::HighLightInvalid( CORBA::Object_ptr theObject, bool isInvalid )
1003 {
1004   SALOMEDS::SObject_wrap so = ObjectToSObject(theObject);
1005   highLightInvalid( so.in(), isInvalid );
1006 }
1007
1008 //=======================================================================
1009 //function : highLightInvalid
1010 //purpose  : change font color of a object in the Object Browser
1011 //=======================================================================
1012
1013 void SMESH_Gen_i::highLightInvalid( SALOMEDS::SObject_ptr theSObject, bool isInvalid )
1014 {
1015   if ( !theSObject->_is_nil() )
1016   {
1017     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1018     if ( isInvalid )
1019     {
1020       SALOMEDS::Color red = { 178,34,34 }; // to differ from reference color
1021       SALOMEDS::GenericAttribute_wrap attr =
1022         studyBuilder->FindOrCreateAttribute( theSObject, "AttributeTextColor" );
1023       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1024       colorAttr->SetTextColor( red );
1025     }
1026     else
1027     {
1028       studyBuilder->RemoveAttribute( theSObject, "AttributeTextColor" );
1029     }
1030   }
1031 }
1032
1033 //=======================================================================
1034 //function : GetMeshOrSubmeshByShape
1035 //purpose  : 
1036 //=======================================================================
1037
1038 SALOMEDS::SObject_ptr
1039 SMESH_Gen_i::GetMeshOrSubmeshByShape (SMESH::SMESH_Mesh_ptr theMesh,
1040                                       GEOM::GEOM_Object_ptr theShape)
1041 {
1042   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape")
1043   SALOMEDS::SObject_wrap aMeshOrSubMesh;
1044   if (theMesh->_is_nil() || ( theShape->_is_nil() && theMesh->HasShapeToMesh()))
1045     return aMeshOrSubMesh._retn();
1046   
1047   TopoDS_Shape aShape;
1048   if(theMesh->HasShapeToMesh())
1049     aShape = GeomObjectToShape( theShape );
1050   else
1051     aShape = SMESH_Mesh::PseudoShape();
1052
1053   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1054
1055   if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1056     SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1057     if ( aShape.IsSame( meshDS->ShapeToMesh() ))
1058       aMeshOrSubMesh = ObjectToSObject( theMesh );
1059     else {
1060       int shapeID = meshDS->ShapeToIndex( aShape );
1061       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1062       if ( !aSubMesh->_is_nil() )
1063         aMeshOrSubMesh = ObjectToSObject( aSubMesh );
1064     }
1065   }
1066   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape--END")
1067   return aMeshOrSubMesh._retn();
1068 }
1069
1070 //=======================================================================
1071 //function : AddHypothesisToShape
1072 //purpose  : 
1073 //=======================================================================
1074
1075 bool SMESH_Gen_i::AddHypothesisToShape(SMESH::SMESH_Mesh_ptr       theMesh,
1076                                        GEOM::GEOM_Object_ptr       theShape,
1077                                        SMESH::SMESH_Hypothesis_ptr theHyp)
1078 {
1079   if(MYDEBUG) MESSAGE("AddHypothesisToShape")
1080   if (theMesh->_is_nil() ||
1081       theHyp->_is_nil() || (theShape->_is_nil()
1082                             && theMesh->HasShapeToMesh()) )
1083     return false;
1084
1085   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
1086   if ( aMeshSO->_is_nil() )
1087     aMeshSO = PublishMesh( theMesh );
1088   SALOMEDS::SObject_wrap aHypSO = PublishHypothesis( theHyp );
1089   if ( aMeshSO->_is_nil() || aHypSO->_is_nil())
1090     return false;
1091
1092   // Find a mesh or submesh referring to theShape
1093   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1094     GetMeshOrSubmeshByShape( theMesh, theShape );
1095   if ( aMeshOrSubMesh->_is_nil() )
1096   {
1097     // publish submesh
1098     TopoDS_Shape aShape = GeomObjectToShape( theShape );
1099     SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1100     if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1101       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1102       int shapeID = meshDS->ShapeToIndex( aShape );
1103       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1104       aMeshOrSubMesh = PublishSubMesh( theMesh, aSubMesh, theShape );
1105     }
1106     if ( aMeshOrSubMesh->_is_nil() )
1107       return false;
1108   }
1109
1110   //Find or Create Applied Hypothesis root
1111   bool aIsAlgo = !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil();
1112   SALOMEDS::SObject_wrap AHR =
1113     publish (CORBA::Object::_nil(), aMeshOrSubMesh,
1114              aIsAlgo ? GetRefOnAppliedAlgorithmsTag() : GetRefOnAppliedHypothesisTag(),
1115              aIsAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
1116   SetName( AHR, aIsAlgo ? "Applied algorithms" : "Applied hypotheses" );
1117
1118   addReference( AHR, theHyp );
1119
1120   if(MYDEBUG) MESSAGE("AddHypothesisToShape--END")
1121   return true;
1122 }
1123
1124 //=======================================================================
1125 //function : RemoveHypothesisFromShape
1126 //purpose  : 
1127 //=======================================================================
1128
1129 bool SMESH_Gen_i::RemoveHypothesisFromShape(SMESH::SMESH_Mesh_ptr       theMesh,
1130                                             GEOM::GEOM_Object_ptr       theShape,
1131                                             SMESH::SMESH_Hypothesis_ptr theHyp)
1132 {
1133   if (theMesh->_is_nil() ||
1134       theHyp->_is_nil() || (theShape->_is_nil()
1135                             && theMesh->HasShapeToMesh()))
1136     return false;
1137
1138   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
1139   if ( aHypSO->_is_nil() )
1140     return false;
1141
1142   CORBA::String_var hypEntry = aHypSO->GetID();
1143
1144   // Find a mesh or sub-mesh referring to theShape
1145   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1146     GetMeshOrSubmeshByShape( theMesh, theShape );
1147   if ( aMeshOrSubMesh->_is_nil() )
1148     return false;
1149
1150   // Find and remove a reference to aHypSO
1151   SALOMEDS::SObject_wrap aRef, anObj;
1152   SALOMEDS::ChildIterator_wrap it = getStudyServant()->NewChildIterator( aMeshOrSubMesh );
1153   bool found = false;
1154   for ( it->InitEx( true ); ( it->More() && !found ); it->Next() ) {
1155     anObj = it->Value();
1156     if (anObj->ReferencedObject( aRef.inout() ))
1157     {
1158       CORBA::String_var refEntry = aRef->GetID();
1159       found = ( strcmp( refEntry, hypEntry ) == 0 );
1160     }
1161     if ( found )
1162     {
1163       SALOMEDS::StudyBuilder_var builder = getStudyServant()->NewBuilder();
1164       builder->RemoveObject( anObj );
1165     }
1166   }
1167
1168   return true;
1169 }
1170
1171 //================================================================================
1172 /*!
1173  * \brief Stores names of variables that WILL be passes as parameters when calling
1174  *        some method of a given object.
1175  *  \param [in] theObject - the object whose a method WILL be called with \a theParameters.
1176  *  \param [in] theParameters - a string containing parameters separated by ':'.
1177  */
1178 //================================================================================
1179
1180 void SMESH_Gen_i::UpdateParameters(CORBA::Object_ptr theObject, const char* theParameters)
1181 {
1182   // find variable names within theParameters
1183
1184   myLastObj.clear();
1185   myLastParameters.clear();
1186   myLastParamIndex.clear(); /* vector holding indices of virables within the string
1187                                of all variables used for theObject */ 
1188   int nbVars = 0;
1189   int pos = 0, prevPos = 0, len = strlen( theParameters );
1190   if ( len == 0 ) return;
1191   while ( pos <= len )
1192   {
1193     if ( pos == len || theParameters[pos] == ':' )
1194     {
1195       if ( prevPos < pos )
1196       {
1197         string val( theParameters + prevPos, theParameters + pos );
1198         if ( !getStudyServant()->IsVariable( val.c_str() ))
1199           val.clear();
1200         myLastParameters.push_back( val );
1201         nbVars += (! myLastParameters.back().empty() );
1202       }
1203       else
1204       {
1205         myLastParameters.push_back("");
1206       }
1207       prevPos = pos+1;
1208     }
1209     ++pos;
1210   }
1211
1212   if ( nbVars < 1 )
1213     return;
1214
1215   // store
1216   // (1) variable names in the string of all variables used for theObject and
1217   // (2) indices of found variables in myLastParamIndex.
1218
1219   // remember theObject
1220   SALOMEDS::SObject_wrap aSObj =  ObjectToSObject(theObject);
1221   if ( aSObj->_is_nil() )
1222     return;
1223   CORBA::String_var anObjEntry = aSObj->GetID();
1224   myLastObj = anObjEntry.in();
1225
1226   // get a string of variable names
1227   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1228   SALOMEDS::GenericAttribute_wrap     anAttr =
1229     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1230   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1231   CORBA::String_var                  oldVars = aStringAttr->Value();
1232   std::string                         varStr = oldVars.in();
1233
1234   // add new variables and find indices of variables
1235   for ( size_t i = 0; i < myLastParameters.size(); ++i )
1236   {
1237     int varIndex = -1;
1238     if ( !myLastParameters[i].empty() )
1239     {
1240       // find index of myLastParameters[i] in varStr
1241       int curIndex  = 0;
1242       bool varFound = false;
1243       size_t pos    = 0;
1244       // varStr can be "A|B::C;*=2|D"
1245       const std::string separators(":|;*=");
1246       while ( pos < varStr.size() && !varFound )
1247       {
1248         // skip separators
1249         while ( separators.find( varStr[ pos ]) != std::string::npos )
1250           if ( ++pos >= varStr.size() )
1251             break;
1252         // skip repetition number following '='
1253         if ( varStr[ pos-1 ] == '=' )
1254         {
1255           while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1256             ++pos;
1257           continue; // to skip next separator
1258         }
1259         // compare variable name
1260         if ( pos < varStr.size() )
1261         {
1262           varFound = ( varStr.compare( pos, myLastParameters[i].size(), myLastParameters[i] ) == 0 &&
1263                        // same string beginning but is length same?
1264                        ( pos + myLastParameters[i].size() >= varStr.size() ||
1265                          separators.find( varStr[ pos+1 ]) != std::string::npos ));
1266           if ( varFound )
1267             varIndex = curIndex;
1268           else
1269             pos = varStr.find_first_of( separators, pos ); // goto the next separator
1270           ++curIndex;
1271         }
1272       }
1273       // add new variable
1274       if ( !varFound )
1275       {
1276         varStr += ":" + myLastParameters[i];
1277         varIndex = curIndex;
1278       }
1279     }
1280     myLastParamIndex.push_back( varIndex );
1281   }
1282   aStringAttr->SetValue( varStr.c_str() );
1283 }
1284
1285 //================================================================================
1286 /*!
1287  * \brief Return all variables used to create an object
1288  *  \param [in] theObjectEntry - an object entry in the current study
1289  *  \return std::vector< std::string > - all variable names (or values of removed variables)
1290  */
1291 //================================================================================
1292
1293 std::vector< std::string > SMESH_Gen_i::GetAllParameters(const std::string& theObjectEntry) const
1294 {
1295   std::vector< std::string > varNames;
1296
1297   SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theObjectEntry.c_str() );
1298
1299   // get a string of variable names
1300   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1301   SALOMEDS::GenericAttribute_wrap     anAttr =
1302     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1303   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1304   CORBA::String_var                  oldVars = aStringAttr->Value();
1305   std::string                         varStr = oldVars.in();
1306
1307   // separate variables within varStr;
1308   // varStr can be "A|B::C;*=2|D"
1309   size_t pos = 0;
1310   const std::string separators(":|;*=");
1311   while ( pos < varStr.size() )
1312   {
1313     // skip separators
1314     pos = varStr.find_first_not_of( separators, pos );
1315     // while ( separators.find( varStr[ pos ]) != std::string::npos )
1316     //   if ( ++pos >= varStr.size() )
1317     //     break;
1318     // skip repetition number following '='
1319     if ( varStr[ pos-1 ] == '=' )
1320     {
1321       while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1322         ++pos;
1323       continue; // to skip next separator
1324     }
1325     // store variable name
1326     if ( pos < varStr.size() )
1327     {
1328       size_t pos2 = varStr.find_first_of( separators, pos );
1329       varNames.push_back( varStr.substr( pos, pos2 - pos));
1330       pos = pos2;
1331     }
1332   }
1333   return varNames;
1334 }
1335
1336 //=======================================================================
1337 //function : ParseParameters
1338 //purpose  : Replace variables by their values
1339 //=======================================================================
1340 // char* SMESH_Gen_i::ParseParameters(const char* theParameters)
1341 // {
1342 //   //const char* aParameters = theParameters;
1343 // //   const char* aParameters = CORBA::string_dup(theParameters);
1344 //   TCollection_AsciiString anInputParams;
1345 //   SALOMEDS::Study_var aStudy = getStudyServant();
1346 //   if( !aStudy->_is_nil() ) {
1347 // //     SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(theParameters);
1348 // //     for(int j=0;j<aSections->length();j++) {
1349 // //       SALOMEDS::ListOfStrings aVars= aSections[j];
1350 // //       for(int i=0;i<aVars.length();i++ ) {
1351 // //         anInputParams += aStudy->IsVariable(aVars[i].in()) ? 
1352 // //           TCollection_AsciiString(aVars[i].in()) : TCollection_AsciiString("");
1353 // //         if(i != aVars.length()-1)
1354 // //           anInputParams+=":";
1355 // //       }
1356 // //       if(j!=aSections->length()-1)
1357 // //         anInputParams+="|";
1358 // //     }
1359 //     TCollection_AsciiString paramStr( theParameters );
1360 //     int beg = 0, end;
1361 //     char sep, *pParams = (char*)paramStr.ToCString();
1362 //     while ( beg < paramStr.Length() )
1363 //     {
1364 //       end = beg-1;
1365 //       while ( ++end < paramStr.Length() )
1366 //         if ( pParams[end] == ':' || pParams[end] == '|')
1367 //           break;
1368 //       if ( end < paramStr.Length())
1369 //       {
1370 //         sep = pParams[end];
1371 //         pParams[end] = '\0';
1372 //       }
1373 //       if ( aStudy->IsVariable( pParams+beg ))
1374 //         anInputParams += pParams+beg;
1375 //       if ( end < paramStr.Length() )
1376 //         anInputParams += sep;
1377 //       else
1378 //         break;
1379 //       beg = end + 1;
1380 //     }
1381 //   }
1382 //   return CORBA::string_dup(anInputParams.ToCString());
1383 // }
1384
1385 //=======================================================================
1386 //function : GetParameters
1387 //purpose  : 
1388 //=======================================================================
1389
1390 char* SMESH_Gen_i::GetParameters(CORBA::Object_ptr theObject)
1391 {
1392   CORBA::String_var aResult("");
1393
1394   SALOMEDS::SObject_wrap aSObj = ObjectToSObject( theObject );
1395   if ( !aSObj->_is_nil() )
1396   {
1397     SALOMEDS::GenericAttribute_wrap attr;
1398     if ( aSObj->FindAttribute( attr.inout(), "AttributeString"))
1399     {
1400       SALOMEDS::AttributeString_wrap strAttr = attr;
1401       aResult = strAttr->Value();
1402     }
1403   }
1404   return aResult._retn();
1405 }
1406
1407 //================================================================================
1408 /*!
1409  * \brief Create a sub-mesh on a geometry that is not a sub-shape of the main shape
1410  * for the case where a valid sub-shape not found by CopyMeshWithGeom().
1411  * The invalid sub-mesh has GetId() < 0.
1412  */
1413 //================================================================================
1414
1415 SMESH::SMESH_subMesh_ptr
1416 SMESH_Gen_i::createInvalidSubMesh(SMESH::SMESH_Mesh_ptr theMesh,
1417                                   GEOM::GEOM_Object_ptr theStrangerGeom,
1418                                   const char*           theName)
1419 {
1420   SMESH::SMESH_subMesh_var subMesh;
1421
1422   try
1423   {
1424     SMESH_Mesh_i* mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1425     subMesh = mesh_i->createSubMesh( theStrangerGeom );
1426
1427     if ( !subMesh->_is_nil() && CanPublishInStudy( subMesh ))
1428     {
1429       SALOMEDS::SObject_wrap so = PublishSubMesh( theMesh, subMesh, theStrangerGeom, theName );
1430
1431       // hide a reference to geometry
1432       if ( !so->_is_nil() )
1433       {
1434         SALOMEDS::SObject_wrap refSO;
1435         if ( so->FindSubObject( GetRefOnShapeTag(), refSO.inout() ))
1436         {
1437           SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1438           SALOMEDS::GenericAttribute_wrap attr =
1439             studyBuilder->FindOrCreateAttribute( refSO, "AttributeDrawable" );
1440           SALOMEDS::AttributeDrawable_wrap ga = attr;
1441           ga->SetDrawable( false );
1442         }
1443       }
1444     }
1445   }
1446   catch (...) {
1447   }
1448
1449   return subMesh._retn();
1450 }
1451
1452
1453 // ==============
1454 // Study context
1455 // ==============
1456
1457 //=======================================================================
1458 //function : addObject
1459 //purpose  : register object in the internal map and return its id
1460 //=======================================================================
1461
1462 int StudyContext::addObject( const std::string& theIOR )
1463 {
1464   int nextId = getNextId();
1465   mapIdToIOR.Bind( nextId, theIOR );
1466   return nextId;
1467 }
1468
1469 //=======================================================================
1470 //function : findId
1471 //purpose  : find the object id in the internal map by the IOR
1472 //=======================================================================
1473
1474 int StudyContext::findId( const std::string& theIOR )
1475 {
1476   TInt2StringMap::iterator imap;
1477   for ( imap = mapIdToIOR.begin(); imap != mapIdToIOR.end(); ++imap ) {
1478     if ( *imap == theIOR )
1479       return imap.Iterator().Key();
1480   }
1481   return 0;
1482 }
1483
1484 //=======================================================================
1485 //function : getIORbyId
1486 //purpose  : get object's IOR by id
1487 //=======================================================================
1488
1489 std::string StudyContext::getIORbyId( const int theId )
1490 {
1491   if ( mapIdToIOR.IsBound( theId ) )
1492     return mapIdToIOR( theId );
1493   return std::string();
1494 }
1495
1496 //=======================================================================
1497 //function : getIORbyOldId
1498 //purpose  : get object's IOR by old id
1499 //=======================================================================
1500
1501 std::string StudyContext::getIORbyOldId( const int theOldId )
1502 {
1503   if ( mapIdToId.IsBound( theOldId ) )
1504     return getIORbyId( mapIdToId( theOldId ));
1505   return std::string();
1506 }
1507
1508 //=======================================================================
1509 //function : mapOldToNew
1510 //purpose  : maps old object id to the new one (used when restoring data)
1511 //=======================================================================
1512
1513 void StudyContext::mapOldToNew( const int oldId, const int newId )
1514 {
1515   mapIdToId.Bind( oldId, newId );
1516 }
1517
1518 //=======================================================================
1519 //function : getOldId
1520 //purpose  : get old id by a new one
1521 //=======================================================================
1522
1523 int StudyContext::getOldId( const int newId )
1524 {
1525   TInt2IntMap::iterator imap;
1526   for ( imap = mapIdToId.begin(); imap != mapIdToId.end(); ++imap ) {
1527     if ( *imap == newId )
1528       return imap.Iterator().Key();
1529   }
1530   return 0;
1531 }
1532
1533 //=======================================================================
1534 //function : Clear
1535 //purpose  : clear data
1536 //=======================================================================
1537
1538 void StudyContext::Clear()
1539 {
1540   mapIdToIOR.Clear();
1541   mapIdToId.Clear();
1542 }