Salome HOME
Fix compilation errors under Windows: VS-2017
[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       }
1014       if ( isEmpty )
1015         SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN");
1016       else if ( !isGroup )
1017         SetPixMap( so, "ICON_SMESH_TREE_MESH" );
1018       else if ( isGroupOnFilter )
1019         SetPixMap( so, "ICON_SMESH_TREE_GROUP_ON_FILTER" );
1020       else
1021         SetPixMap( so, "ICON_SMESH_TREE_GROUP" );
1022     }
1023   }
1024 }
1025
1026 //=======================================================================
1027 //function : HighLightInvalid
1028 //purpose  : change font color of a object in the Object Browser
1029 //=======================================================================
1030
1031 void SMESH_Gen_i::HighLightInvalid( CORBA::Object_ptr theObject, bool isInvalid )
1032 {
1033   SALOMEDS::SObject_wrap so = ObjectToSObject(theObject);
1034   highLightInvalid( so.in(), isInvalid );
1035 }
1036
1037 //=======================================================================
1038 //function : highLightInvalid
1039 //purpose  : change font color of a object in the Object Browser
1040 //=======================================================================
1041
1042 void SMESH_Gen_i::highLightInvalid( SALOMEDS::SObject_ptr theSObject, bool isInvalid )
1043 {
1044   if ( !theSObject->_is_nil() )
1045   {
1046     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1047     if ( isInvalid )
1048     {
1049       SALOMEDS::Color red = { 178,34,34 }; // to differ from reference color
1050       SALOMEDS::GenericAttribute_wrap attr =
1051         studyBuilder->FindOrCreateAttribute( theSObject, "AttributeTextColor" );
1052       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1053       colorAttr->SetTextColor( red );
1054     }
1055     else
1056     {
1057       studyBuilder->RemoveAttribute( theSObject, "AttributeTextColor" );
1058     }
1059   }
1060 }
1061
1062 //=======================================================================
1063 //function : IsInvalid
1064 //purpose  : Check object validity == absence of AttributeTextColor=(178,34,34)
1065 //=======================================================================
1066
1067 bool SMESH_Gen_i::IsInvalid( SALOMEDS::SObject_ptr theSObject )
1068 {
1069   bool isValid = true;
1070   if ( !theSObject->_is_nil() )
1071   {
1072     SALOMEDS::GenericAttribute_wrap attr;
1073     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1074     if ( studyBuilder->FindAttribute( theSObject, attr.inout(), "AttributeTextColor" ))
1075     {
1076       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1077       SALOMEDS::Color color = colorAttr->TextColor();
1078       isValid = ( color.R != 178 || color.G != 34 || color.B != 34 );
1079     }
1080   }
1081   return isValid;
1082 }
1083
1084 //=======================================================================
1085 //function : GetMeshOrSubmeshByShape
1086 //purpose  : 
1087 //=======================================================================
1088
1089 SALOMEDS::SObject_ptr
1090 SMESH_Gen_i::GetMeshOrSubmeshByShape (SMESH::SMESH_Mesh_ptr theMesh,
1091                                       GEOM::GEOM_Object_ptr theShape)
1092 {
1093   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape")
1094   SALOMEDS::SObject_wrap aMeshOrSubMesh;
1095   if (theMesh->_is_nil() || ( theShape->_is_nil() && theMesh->HasShapeToMesh()))
1096     return aMeshOrSubMesh._retn();
1097   
1098   TopoDS_Shape aShape;
1099   if(theMesh->HasShapeToMesh())
1100     aShape = GeomObjectToShape( theShape );
1101   else
1102     aShape = SMESH_Mesh::PseudoShape();
1103
1104   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1105
1106   if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1107     SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1108     if ( aShape.IsSame( meshDS->ShapeToMesh() ))
1109       aMeshOrSubMesh = ObjectToSObject( theMesh );
1110     else {
1111       int shapeID = meshDS->ShapeToIndex( aShape );
1112       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1113       if ( !aSubMesh->_is_nil() )
1114         aMeshOrSubMesh = ObjectToSObject( aSubMesh );
1115     }
1116   }
1117   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape--END")
1118   return aMeshOrSubMesh._retn();
1119 }
1120
1121 //=======================================================================
1122 //function : AddHypothesisToShape
1123 //purpose  : 
1124 //=======================================================================
1125
1126 bool SMESH_Gen_i::AddHypothesisToShape(SMESH::SMESH_Mesh_ptr       theMesh,
1127                                        GEOM::GEOM_Object_ptr       theShape,
1128                                        SMESH::SMESH_Hypothesis_ptr theHyp)
1129 {
1130   if(MYDEBUG) MESSAGE("AddHypothesisToShape")
1131   if (theMesh->_is_nil() ||
1132       theHyp->_is_nil() || (theShape->_is_nil()
1133                             && theMesh->HasShapeToMesh()) )
1134     return false;
1135
1136   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
1137   if ( aMeshSO->_is_nil() )
1138     aMeshSO = PublishMesh( theMesh );
1139   SALOMEDS::SObject_wrap aHypSO = PublishHypothesis( theHyp );
1140   if ( aMeshSO->_is_nil() || aHypSO->_is_nil())
1141     return false;
1142
1143   // Find a mesh or submesh referring to theShape
1144   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1145     GetMeshOrSubmeshByShape( theMesh, theShape );
1146   if ( aMeshOrSubMesh->_is_nil() )
1147   {
1148     // publish submesh
1149     TopoDS_Shape aShape = GeomObjectToShape( theShape );
1150     SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1151     if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1152       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1153       int shapeID = meshDS->ShapeToIndex( aShape );
1154       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1155       aMeshOrSubMesh = PublishSubMesh( theMesh, aSubMesh, theShape );
1156     }
1157     if ( aMeshOrSubMesh->_is_nil() )
1158       return false;
1159   }
1160
1161   //Find or Create Applied Hypothesis root
1162   bool aIsAlgo = !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil();
1163   SALOMEDS::SObject_wrap AHR =
1164     publish (CORBA::Object::_nil(), aMeshOrSubMesh,
1165              aIsAlgo ? GetRefOnAppliedAlgorithmsTag() : GetRefOnAppliedHypothesisTag(),
1166              aIsAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
1167   SetName( AHR, aIsAlgo ? "Applied algorithms" : "Applied hypotheses" );
1168
1169   addReference( AHR, theHyp );
1170
1171   if(MYDEBUG) MESSAGE("AddHypothesisToShape--END")
1172   return true;
1173 }
1174
1175 //=======================================================================
1176 //function : RemoveHypothesisFromShape
1177 //purpose  : 
1178 //=======================================================================
1179
1180 bool SMESH_Gen_i::RemoveHypothesisFromShape(SMESH::SMESH_Mesh_ptr       theMesh,
1181                                             GEOM::GEOM_Object_ptr       theShape,
1182                                             SMESH::SMESH_Hypothesis_ptr theHyp)
1183 {
1184   if (theMesh->_is_nil() ||
1185       theHyp->_is_nil() || (theShape->_is_nil()
1186                             && theMesh->HasShapeToMesh()))
1187     return false;
1188
1189   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
1190   if ( aHypSO->_is_nil() )
1191     return false;
1192
1193   CORBA::String_var hypEntry = aHypSO->GetID();
1194
1195   // Find a mesh or sub-mesh referring to theShape
1196   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1197     GetMeshOrSubmeshByShape( theMesh, theShape );
1198   if ( aMeshOrSubMesh->_is_nil() )
1199     return false;
1200
1201   // Find and remove a reference to aHypSO
1202   SALOMEDS::SObject_wrap aRef, anObj;
1203   SALOMEDS::ChildIterator_wrap it = getStudyServant()->NewChildIterator( aMeshOrSubMesh );
1204   bool found = false;
1205   for ( it->InitEx( true ); ( it->More() && !found ); it->Next() ) {
1206     anObj = it->Value();
1207     if (anObj->ReferencedObject( aRef.inout() ))
1208     {
1209       CORBA::String_var refEntry = aRef->GetID();
1210       found = ( strcmp( refEntry, hypEntry ) == 0 );
1211     }
1212     if ( found )
1213     {
1214       SALOMEDS::StudyBuilder_var builder = getStudyServant()->NewBuilder();
1215       builder->RemoveObject( anObj );
1216     }
1217   }
1218
1219   return true;
1220 }
1221
1222 //================================================================================
1223 /*!
1224  * \brief Stores names of variables that WILL be passes as parameters when calling
1225  *        some method of a given object.
1226  *  \param [in] theObject - the object whose a method WILL be called with \a theParameters.
1227  *  \param [in] theParameters - a string containing parameters separated by ':'.
1228  */
1229 //================================================================================
1230
1231 void SMESH_Gen_i::UpdateParameters(CORBA::Object_ptr theObject, const char* theParameters)
1232 {
1233   // find variable names within theParameters
1234
1235   myLastObj.clear();
1236   myLastParameters.clear();
1237   myLastParamIndex.clear(); /* vector holding indices of virables within the string
1238                                of all variables used for theObject */ 
1239   int nbVars = 0;
1240   int pos = 0, prevPos = 0, len = strlen( theParameters );
1241   if ( len == 0 ) return;
1242   while ( pos <= len )
1243   {
1244     if ( pos == len || theParameters[pos] == ':' )
1245     {
1246       if ( prevPos < pos )
1247       {
1248         string val( theParameters + prevPos, theParameters + pos );
1249         if ( !getStudyServant()->IsVariable( val.c_str() ))
1250           val.clear();
1251         myLastParameters.push_back( val );
1252         nbVars += (! myLastParameters.back().empty() );
1253       }
1254       else
1255       {
1256         myLastParameters.push_back("");
1257       }
1258       prevPos = pos+1;
1259     }
1260     ++pos;
1261   }
1262
1263   if ( nbVars < 1 )
1264     return;
1265
1266   // store
1267   // (1) variable names in the string of all variables used for theObject and
1268   // (2) indices of found variables in myLastParamIndex.
1269
1270   // remember theObject
1271   SALOMEDS::SObject_wrap aSObj =  ObjectToSObject(theObject);
1272   if ( aSObj->_is_nil() )
1273     return;
1274   CORBA::String_var anObjEntry = aSObj->GetID();
1275   myLastObj = anObjEntry.in();
1276
1277   // get a string of variable names
1278   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1279   SALOMEDS::GenericAttribute_wrap     anAttr =
1280     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1281   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1282   CORBA::String_var                  oldVars = aStringAttr->Value();
1283   std::string                         varStr = oldVars.in();
1284
1285   // add new variables and find indices of variables
1286   for ( size_t i = 0; i < myLastParameters.size(); ++i )
1287   {
1288     int varIndex = -1;
1289     if ( !myLastParameters[i].empty() )
1290     {
1291       // find index of myLastParameters[i] in varStr
1292       int curIndex  = 0;
1293       bool varFound = false;
1294       size_t pos    = 0;
1295       // varStr can be "A|B::C;*=2|D"
1296       const std::string separators(":|;*=");
1297       while ( pos < varStr.size() && !varFound )
1298       {
1299         // skip separators
1300         while ( separators.find( varStr[ pos ]) != std::string::npos )
1301           if ( ++pos >= varStr.size() )
1302             break;
1303         // skip repetition number following '='
1304         if ( varStr[ pos-1 ] == '=' )
1305         {
1306           while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1307             ++pos;
1308           continue; // to skip next separator
1309         }
1310         // compare variable name
1311         if ( pos < varStr.size() )
1312         {
1313           varFound = ( varStr.compare( pos, myLastParameters[i].size(), myLastParameters[i] ) == 0 &&
1314                        // same string beginning but is length same?
1315                        ( pos + myLastParameters[i].size() >= varStr.size() ||
1316                          separators.find( varStr[ pos+1 ]) != std::string::npos ));
1317           if ( varFound )
1318             varIndex = curIndex;
1319           else
1320             pos = varStr.find_first_of( separators, pos ); // goto the next separator
1321           ++curIndex;
1322         }
1323       }
1324       // add new variable
1325       if ( !varFound )
1326       {
1327         varStr += ":" + myLastParameters[i];
1328         varIndex = curIndex;
1329       }
1330     }
1331     myLastParamIndex.push_back( varIndex );
1332   }
1333   aStringAttr->SetValue( varStr.c_str() );
1334 }
1335
1336 //================================================================================
1337 /*!
1338  * \brief Return all variables used to create an object
1339  *  \param [in] theObjectEntry - an object entry in the current study
1340  *  \return std::vector< std::string > - all variable names (or values of removed variables)
1341  */
1342 //================================================================================
1343
1344 std::vector< std::string > SMESH_Gen_i::GetAllParameters(const std::string& theObjectEntry) const
1345 {
1346   std::vector< std::string > varNames;
1347
1348   SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theObjectEntry.c_str() );
1349
1350   // get a string of variable names
1351   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1352   SALOMEDS::GenericAttribute_wrap     anAttr =
1353     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1354   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1355   CORBA::String_var                  oldVars = aStringAttr->Value();
1356   std::string                         varStr = oldVars.in();
1357
1358   // separate variables within varStr;
1359   // varStr can be "A|B::C;*=2|D"
1360   size_t pos = 0;
1361   const std::string separators(":|;*=");
1362   while ( pos < varStr.size() )
1363   {
1364     // skip separators
1365     pos = varStr.find_first_not_of( separators, pos );
1366     // while ( separators.find( varStr[ pos ]) != std::string::npos )
1367     //   if ( ++pos >= varStr.size() )
1368     //     break;
1369     // skip repetition number following '='
1370     if ( varStr[ pos-1 ] == '=' )
1371     {
1372       while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1373         ++pos;
1374       continue; // to skip next separator
1375     }
1376     // store variable name
1377     if ( pos < varStr.size() )
1378     {
1379       size_t pos2 = varStr.find_first_of( separators, pos );
1380       varNames.push_back( varStr.substr( pos, pos2 - pos));
1381       pos = pos2;
1382     }
1383   }
1384   return varNames;
1385 }
1386
1387 //=======================================================================
1388 //function : ParseParameters
1389 //purpose  : Replace variables by their values
1390 //=======================================================================
1391 // char* SMESH_Gen_i::ParseParameters(const char* theParameters)
1392 // {
1393 //   //const char* aParameters = theParameters;
1394 // //   const char* aParameters = CORBA::string_dup(theParameters);
1395 //   TCollection_AsciiString anInputParams;
1396 //   SALOMEDS::Study_var aStudy = getStudyServant();
1397 //   if( !aStudy->_is_nil() ) {
1398 // //     SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(theParameters);
1399 // //     for(int j=0;j<aSections->length();j++) {
1400 // //       SALOMEDS::ListOfStrings aVars= aSections[j];
1401 // //       for(int i=0;i<aVars.length();i++ ) {
1402 // //         anInputParams += aStudy->IsVariable(aVars[i].in()) ? 
1403 // //           TCollection_AsciiString(aVars[i].in()) : TCollection_AsciiString("");
1404 // //         if(i != aVars.length()-1)
1405 // //           anInputParams+=":";
1406 // //       }
1407 // //       if(j!=aSections->length()-1)
1408 // //         anInputParams+="|";
1409 // //     }
1410 //     TCollection_AsciiString paramStr( theParameters );
1411 //     int beg = 0, end;
1412 //     char sep, *pParams = (char*)paramStr.ToCString();
1413 //     while ( beg < paramStr.Length() )
1414 //     {
1415 //       end = beg-1;
1416 //       while ( ++end < paramStr.Length() )
1417 //         if ( pParams[end] == ':' || pParams[end] == '|')
1418 //           break;
1419 //       if ( end < paramStr.Length())
1420 //       {
1421 //         sep = pParams[end];
1422 //         pParams[end] = '\0';
1423 //       }
1424 //       if ( aStudy->IsVariable( pParams+beg ))
1425 //         anInputParams += pParams+beg;
1426 //       if ( end < paramStr.Length() )
1427 //         anInputParams += sep;
1428 //       else
1429 //         break;
1430 //       beg = end + 1;
1431 //     }
1432 //   }
1433 //   return CORBA::string_dup(anInputParams.ToCString());
1434 // }
1435
1436 //=======================================================================
1437 //function : GetParameters
1438 //purpose  : 
1439 //=======================================================================
1440
1441 char* SMESH_Gen_i::GetParameters(CORBA::Object_ptr theObject)
1442 {
1443   CORBA::String_var aResult("");
1444
1445   SALOMEDS::SObject_wrap aSObj = ObjectToSObject( theObject );
1446   if ( !aSObj->_is_nil() )
1447   {
1448     SALOMEDS::GenericAttribute_wrap attr;
1449     if ( aSObj->FindAttribute( attr.inout(), "AttributeString"))
1450     {
1451       SALOMEDS::AttributeString_wrap strAttr = attr;
1452       aResult = strAttr->Value();
1453     }
1454   }
1455   return aResult._retn();
1456 }
1457
1458 //================================================================================
1459 /*!
1460  * \brief Create a sub-mesh on a geometry that is not a sub-shape of the main shape
1461  * for the case where a valid sub-shape not found by CopyMeshWithGeom().
1462  * The invalid sub-mesh has GetId() < 0.
1463  */
1464 //================================================================================
1465
1466 SMESH::SMESH_subMesh_ptr
1467 SMESH_Gen_i::createInvalidSubMesh(SMESH::SMESH_Mesh_ptr theMesh,
1468                                   GEOM::GEOM_Object_ptr theStrangerGeom,
1469                                   const char*           theName)
1470 {
1471   SMESH::SMESH_subMesh_var subMesh;
1472
1473   try
1474   {
1475     SMESH_Mesh_i* mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1476     subMesh = mesh_i->createSubMesh( theStrangerGeom );
1477
1478     if ( !subMesh->_is_nil() && CanPublishInStudy( subMesh ))
1479     {
1480       SALOMEDS::SObject_wrap so = PublishSubMesh( theMesh, subMesh, theStrangerGeom, theName );
1481
1482       // hide a reference to geometry
1483       if ( !so->_is_nil() )
1484       {
1485         SALOMEDS::SObject_wrap refSO;
1486         if ( so->FindSubObject( GetRefOnShapeTag(), refSO.inout() ))
1487         {
1488           SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1489           SALOMEDS::GenericAttribute_wrap attr =
1490             studyBuilder->FindOrCreateAttribute( refSO, "AttributeDrawable" );
1491           SALOMEDS::AttributeDrawable_wrap ga = attr;
1492           ga->SetDrawable( false );
1493         }
1494       }
1495     }
1496   }
1497   catch (...) {
1498   }
1499
1500   return subMesh._retn();
1501 }
1502
1503
1504 // ==============
1505 // Study context
1506 // ==============
1507
1508 //=======================================================================
1509 //function : addObject
1510 //purpose  : register object in the internal map and return its id
1511 //=======================================================================
1512
1513 int StudyContext::addObject( const std::string& theIOR )
1514 {
1515   int nextId = getNextId();
1516   mapIdToIOR.Bind( nextId, theIOR );
1517   return nextId;
1518 }
1519
1520 //=======================================================================
1521 //function : findId
1522 //purpose  : find the object id in the internal map by the IOR
1523 //=======================================================================
1524
1525 int StudyContext::findId( const std::string& theIOR )
1526 {
1527   TInt2StringMap::iterator imap;
1528   for ( imap = mapIdToIOR.begin(); imap != mapIdToIOR.end(); ++imap ) {
1529     if ( *imap == theIOR )
1530       return imap.Iterator().Key();
1531   }
1532   return 0;
1533 }
1534
1535 //=======================================================================
1536 //function : getIORbyId
1537 //purpose  : get object's IOR by id
1538 //=======================================================================
1539
1540 std::string StudyContext::getIORbyId( const int theId )
1541 {
1542   if ( mapIdToIOR.IsBound( theId ) )
1543     return mapIdToIOR( theId );
1544   return std::string();
1545 }
1546
1547 //=======================================================================
1548 //function : getIORbyOldId
1549 //purpose  : get object's IOR by old id
1550 //=======================================================================
1551
1552 std::string StudyContext::getIORbyOldId( const int theOldId )
1553 {
1554   if ( mapIdToId.IsBound( theOldId ) )
1555     return getIORbyId( mapIdToId( theOldId ));
1556   return std::string();
1557 }
1558
1559 //=======================================================================
1560 //function : mapOldToNew
1561 //purpose  : maps old object id to the new one (used when restoring data)
1562 //=======================================================================
1563
1564 void StudyContext::mapOldToNew( const int oldId, const int newId )
1565 {
1566   mapIdToId.Bind( oldId, newId );
1567 }
1568
1569 //=======================================================================
1570 //function : getOldId
1571 //purpose  : get old id by a new one
1572 //=======================================================================
1573
1574 int StudyContext::getOldId( const int newId )
1575 {
1576   TInt2IntMap::iterator imap;
1577   for ( imap = mapIdToId.begin(); imap != mapIdToId.end(); ++imap ) {
1578     if ( *imap == newId )
1579       return imap.Iterator().Key();
1580   }
1581   return 0;
1582 }
1583
1584 //=======================================================================
1585 //function : Clear
1586 //purpose  : clear data
1587 //=======================================================================
1588
1589 void StudyContext::Clear()
1590 {
1591   mapIdToIOR.Clear();
1592   mapIdToId.Clear();
1593 }