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