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