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