Salome HOME
Memory leak hunting
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i_1.cxx
1 // Copyright (C) 2007-2021  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   std::string 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 && compDataType == cdt.in() && ior == ior_i.in()) {
566       father = f_i;
567       break;
568     }
569   }
570   
571   if ( !CORBA::is_nil( father ) ) {
572     // check that the component is added to the use case browser
573     if ( !useCaseBuilder->IsUseCaseNode( father ) ) {
574       useCaseBuilder->SetRootCurrent();
575       useCaseBuilder->Append( father ); // component object is added as the top level item
576     }
577     return father._retn();
578   }
579
580   // If component for this SMESH engine does not exist in the study, create it
581
582   SALOME_ModuleCatalog::ModuleCatalog_var aCat = this->getModuleCatalog();
583   if ( CORBA::is_nil( aCat ) )
584     return father._retn();
585
586   SALOME_ModuleCatalog::Acomponent_var aComp = aCat->GetComponent( compDataType.c_str() );
587   if ( CORBA::is_nil( aComp ) )
588     return father._retn();
589
590   SALOMEDS::GenericAttribute_wrap anAttr;
591   SALOMEDS::AttributePixMap_wrap  aPixmap;
592
593   father  = aStudyBuilder->NewComponent( compDataType.c_str() );
594   aStudyBuilder->DefineComponentInstance( father, SMESH_Gen::_this() );
595   anAttr  = aStudyBuilder->FindOrCreateAttribute( father, "AttributePixMap" );
596   aPixmap = anAttr;
597   aPixmap->SetPixMap( "ICON_OBJBROWSER_SMESH" );
598   CORBA::String_var userName = aComp->componentusername();
599   SetName( father, userName.in(), "MESH" );
600   // add component to the use case tree
601   // (to support tree representation customization and drag-n-drop)
602   useCaseBuilder->SetRootCurrent();
603   useCaseBuilder->Append( father ); // component object is added as the top level item
604   if(MYDEBUG) MESSAGE("PublishComponent--END");
605
606   return father._retn();
607 }
608
609 //=======================================================================
610 //function : PublishMesh
611 //purpose  : 
612 //=======================================================================
613
614 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishMesh (SMESH::SMESH_Mesh_ptr theMesh,
615                                                 const char*           theName)
616 {
617   if ( !myIsEnablePublish )
618     return SALOMEDS::SObject::_nil();
619   if ( CORBA::is_nil( theMesh ))
620     return SALOMEDS::SObject::_nil();
621   if(MYDEBUG) MESSAGE("PublishMesh--IN");
622
623   // find or publish a mesh
624
625   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
626   if ( aMeshSO->_is_nil() )
627   {
628     SALOMEDS::SComponent_wrap father = PublishComponent();
629     if ( father->_is_nil() )
630       return aMeshSO._retn();
631
632     // Find correct free tag
633     long aTag = father->GetLastChildTag();
634     if ( aTag <= GetAlgorithmsRootTag() )
635       aTag = GetAlgorithmsRootTag() + 1;
636     else
637       aTag++;
638
639     aMeshSO = publish( theMesh, father, aTag, "ICON_SMESH_TREE_MESH_WARN" );
640     if ( aMeshSO->_is_nil() )
641       return aMeshSO._retn();
642   }
643   SetName( aMeshSO, theName, "Mesh" );
644
645   // Add shape reference
646
647   GEOM::GEOM_Object_var aShapeObject = theMesh->GetShapeToMesh();
648   if ( !CORBA::is_nil( aShapeObject )) {
649     addReference( aMeshSO, aShapeObject, GetRefOnShapeTag() );
650
651     // Publish global hypotheses
652
653     SMESH::ListOfHypothesis_var hypList = theMesh->GetHypothesisList( aShapeObject );
654     for ( CORBA::ULong i = 0; i < hypList->length(); i++ )
655     {
656       SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( hypList[ i ]);
657       SALOMEDS::SObject_wrap so = PublishHypothesis( aHyp );
658       AddHypothesisToShape( theMesh, aShapeObject, aHyp );
659     }
660   }
661
662   // Publish submeshes
663
664   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
665   if ( !mesh_i )
666     return aMeshSO._retn();
667   map<int, SMESH_subMesh_i*>& subMap = mesh_i->_mapSubMesh_i;
668   map<int, SMESH_subMesh_i*>::iterator subIt = subMap.begin();
669   for ( ; subIt != subMap.end(); subIt++ ) {
670     SMESH::SMESH_subMesh_ptr aSubMesh = (*subIt).second->_this();
671     if ( !CORBA::is_nil( aSubMesh )) {
672       aShapeObject = aSubMesh->GetSubShape();
673       SALOMEDS::SObject_wrap( PublishSubMesh( theMesh, aSubMesh, aShapeObject ));
674     }
675   }
676
677   // Publish groups
678   const map<int, SMESH::SMESH_GroupBase_ptr>& grMap = mesh_i->getGroups();
679   map<int, SMESH::SMESH_GroupBase_ptr>::const_iterator it = grMap.begin();
680   for ( ; it != grMap.end(); it++ )
681   {
682     SMESH::SMESH_GroupBase_ptr aGroup = (*it).second;
683     if ( !aGroup->_is_nil() ) {
684       GEOM::GEOM_Object_var aShapeObj;
685       SMESH::SMESH_GroupOnGeom_var aGeomGroup = SMESH::SMESH_GroupOnGeom::_narrow( aGroup );
686       if ( !aGeomGroup->_is_nil() )
687         aShapeObj = aGeomGroup->GetShape();
688       SALOMEDS::SObject_wrap( PublishGroup( theMesh, aGroup, aShapeObj ));
689     }
690   }
691
692   if(MYDEBUG) MESSAGE("PublishMesh_END");
693   return aMeshSO._retn();
694 }
695
696 //=======================================================================
697 //function : PublishSubMesh
698 //purpose  : 
699 //=======================================================================
700
701 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishSubMesh (SMESH::SMESH_Mesh_ptr    theMesh,
702                                                    SMESH::SMESH_subMesh_ptr theSubMesh,
703                                                    GEOM::GEOM_Object_ptr    theShapeObject,
704                                                    const char*              theName)
705 {
706   if ( !myIsEnablePublish )
707     return SALOMEDS::SObject::_nil();
708   if ( theMesh->_is_nil() || theSubMesh->_is_nil() || theShapeObject->_is_nil() )
709     return SALOMEDS::SObject::_nil();
710
711   std::string newName( theName ? theName : "" );
712
713   SALOMEDS::SObject_wrap aSubMeshSO = ObjectToSObject( theSubMesh );
714   if ( aSubMeshSO->_is_nil() )
715   {
716     SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
717     if ( aMeshSO->_is_nil() ) {
718       aMeshSO = PublishMesh( theMesh );
719       if ( aMeshSO->_is_nil())
720         return SALOMEDS::SObject::_nil();
721     }
722     // Find submesh sub-tree tag
723     long aRootTag;
724     const char* aRootName = "";
725     switch ( theShapeObject->GetShapeType() ) {
726     case GEOM::VERTEX:
727       aRootTag  = GetSubMeshOnVertexTag();
728       aRootName = "SubMeshes on Vertex";
729       break;
730     case GEOM::EDGE:
731       aRootTag  = GetSubMeshOnEdgeTag();
732       aRootName = "SubMeshes on Edge";
733       break;
734     case GEOM::WIRE:
735       aRootTag  = GetSubMeshOnWireTag();
736       aRootName = "SubMeshes on Wire";
737       break;
738     case GEOM::FACE:
739       aRootTag  = GetSubMeshOnFaceTag();
740       aRootName = "SubMeshes on Face";    
741       break;
742     case GEOM::SHELL:
743       aRootTag  = GetSubMeshOnShellTag();
744       aRootName = "SubMeshes on Shell";   
745       break;
746     case GEOM::SOLID:
747       aRootTag  = GetSubMeshOnSolidTag();
748       aRootName = "SubMeshes on Solid";
749       break;
750     default:
751       aRootTag  = GetSubMeshOnCompoundTag();
752       aRootName = "SubMeshes on Compound";
753       break;
754     }
755
756     // Find or create submesh root
757     SALOMEDS::SObject_wrap aRootSO = publish ( CORBA::Object::_nil(),
758                                                aMeshSO, aRootTag, 0, false );
759     if ( aRootSO->_is_nil() )
760       return aSubMeshSO._retn();
761
762     SetName( aRootSO, aRootName );
763
764     // Add new sub-mesh to corresponding sub-tree
765     int tag = 0; // to use a new SObject
766     if ( theName && theName[0] == '0' )
767     {
768       // theName can be an entry of an invalid sub-mesh which theSubMesh should replace
769       SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theName );
770       if ( aSObj )
771       {
772         CORBA::String_var oldName = aSObj->GetName();
773         newName = oldName.in();
774         SALOMEDS::SObject_wrap aRootSO2 = aSObj->GetFather();
775         if ( aRootSO->Tag() == aRootSO2->Tag() ) // same parent
776           tag = aSObj->Tag(); // to use the same SObject
777         else
778         {
779           CORBA::Object_var anObj = SObjectToObject( aSObj );
780           SMESH::SMESH_subMesh_var sm = SMESH::SMESH_subMesh::_narrow( anObj );
781           theMesh->RemoveSubMesh( sm );
782         }
783       }
784     }
785     SMESH::array_of_ElementType_var elemTypes = theSubMesh->GetTypes();
786     const int isEmpty = ( elemTypes->length() == 0 );
787     const char* pm[2] = { "ICON_SMESH_TREE_MESH", "ICON_SMESH_TREE_MESH_WARN" };
788     aSubMeshSO = publish ( theSubMesh, aRootSO, tag, pm[isEmpty] );
789     if ( aSubMeshSO->_is_nil() )
790       return aSubMeshSO._retn();
791
792     highLightInvalid( aSubMeshSO, false ); // now it is valid
793   }
794   SetName( aSubMeshSO, newName.c_str(), "SubMesh" );
795
796   // Add reference to theShapeObject
797
798   addReference( aSubMeshSO, theShapeObject, GetRefOnShapeTag() );
799
800   // Publish hypothesis
801
802   SMESH::ListOfHypothesis_var hypList = theMesh->GetHypothesisList( theShapeObject );
803   for ( CORBA::ULong i = 0; i < hypList->length(); i++ )
804   {
805     SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( hypList[ i ]);
806     SALOMEDS::SObject_wrap so = PublishHypothesis( aHyp );
807     AddHypothesisToShape( theMesh, theShapeObject, aHyp );
808   }
809
810   return aSubMeshSO._retn();
811 }
812
813 //=======================================================================
814 //function : PublishGroup
815 //purpose  : 
816 //=======================================================================
817
818 SALOMEDS::SObject_ptr SMESH_Gen_i::PublishGroup (SMESH::SMESH_Mesh_ptr  theMesh,
819                                                  SMESH::SMESH_GroupBase_ptr theGroup,
820                                                  GEOM::GEOM_Object_ptr  theShapeObject,
821                                                  const char*            theName)
822 {
823   if ( !myIsEnablePublish )
824     return SALOMEDS::SObject::_nil();
825   if (theMesh->_is_nil() || theGroup->_is_nil() )
826     return SALOMEDS::SObject::_nil();
827
828   SALOMEDS::SObject_wrap aGroupSO = ObjectToSObject( theGroup );
829   if ( aGroupSO->_is_nil() )
830   {
831     SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
832     if ( aMeshSO->_is_nil() ) {
833       aMeshSO = PublishInStudy( SALOMEDS::SObject::_nil(), theMesh, "");
834       if ( aMeshSO->_is_nil())
835         return SALOMEDS::SObject::_nil();
836     }
837     size_t aType = (int)theGroup->GetType();
838     const char* aRootNames[] = {
839       "Compound Groups", "Groups of Nodes", "Groups of Edges",
840       "Groups of Faces", "Groups of Volumes", "Groups of 0D Elements",
841       "Groups of Balls" };
842
843     // Currently, groups with heterogeneous content are not supported
844     if ( aType != SMESH::ALL )
845     {
846       long aRootTag = GetNodeGroupsTag() + aType - 1;
847
848       // Find or create groups root
849       SALOMEDS::SObject_wrap aRootSO = publish ( CORBA::Object::_nil(),
850                                                  aMeshSO, aRootTag, 0, false );
851       if ( aRootSO->_is_nil() ) return SALOMEDS::SObject::_nil();
852
853       if ( aType < sizeof(aRootNames)/sizeof(char*) )
854         SetName( aRootSO, aRootNames[aType] );
855
856       // Add new group to corresponding sub-tree
857       int isEmpty = ( theMesh->NbNodes() == 0 );
858       std::string pm[2] = { "ICON_SMESH_TREE_GROUP", "ICON_SMESH_TREE_MESH_WARN" };
859       if ( !isEmpty )
860       {
861         if ( SMESH::DownCast< SMESH_GroupOnFilter_i* > ( theGroup )) // on filter
862         {
863           pm[0] = "ICON_SMESH_TREE_GROUP_ON_FILTER";
864
865           if ( theGroup->GetType() != SMESH::NODE )
866           {
867             isEmpty = true;
868             SMESH::array_of_ElementType_var allElemTypes = theMesh->GetTypes();
869             for ( size_t i =0; i < allElemTypes->length() && isEmpty; ++i )
870               isEmpty = ( allElemTypes[i] != theGroup->GetType() );
871           }
872         }
873         else // standalone or on geometry
874         {
875           isEmpty = ( theGroup->Size() == 0 );
876         }
877       }
878       aGroupSO = publish ( theGroup, aRootSO, 0, pm[isEmpty].c_str() );
879     }
880     if ( aGroupSO->_is_nil() )
881       return aGroupSO._retn();
882   }
883
884   SetName( aGroupSO, theName, "Group" );
885
886   //Add reference to geometry
887   if ( !theShapeObject->_is_nil() )
888     addReference( aGroupSO, theShapeObject, GetRefOnShapeTag() );
889
890   return aGroupSO._retn();
891 }
892
893 //=======================================================================
894 //function : PublishHypothesis
895 //purpose  :
896 //=======================================================================
897
898 SALOMEDS::SObject_ptr
899 SMESH_Gen_i::PublishHypothesis (SMESH::SMESH_Hypothesis_ptr theHyp,
900                                 const char*                 theName)
901 {
902   if(MYDEBUG) MESSAGE("PublishHypothesis");
903   if ( !myIsEnablePublish )
904     return SALOMEDS::SObject::_nil();
905   if (theHyp->_is_nil())
906     return SALOMEDS::SObject::_nil();
907
908   CORBA::String_var hypType = theHyp->GetName();
909
910   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
911   if ( aHypSO->_is_nil() )
912   {
913     SALOMEDS::SComponent_wrap father = PublishComponent();
914     if ( father->_is_nil() )
915       return aHypSO._retn();
916
917     //Find or Create Hypothesis root
918     bool isAlgo = ( !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil() );
919     int aRootTag = isAlgo ? GetAlgorithmsRootTag() : GetHypothesisRootTag();
920     SALOMEDS::SObject_wrap aRootSO =
921       publish (CORBA::Object::_nil(),father, aRootTag,
922                isAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
923     SetName( aRootSO, isAlgo ?  "Algorithms" : "Hypotheses" );
924
925     // Add New Hypothesis
926     string aPmName = isAlgo ? "ICON_SMESH_TREE_ALGO_" : "ICON_SMESH_TREE_HYPO_";
927     aPmName += hypType.in();
928     // prepend plugin name to pixmap name
929     string pluginName = myHypCreatorMap[ hypType.in() ]->GetModuleName();
930     if ( pluginName != "StdMeshers" )
931       aPmName = pluginName + "::" + aPmName;
932     aHypSO = publish( theHyp, aRootSO, 0, aPmName.c_str() );
933   }
934
935   SetName( aHypSO, theName, hypType.in() );
936
937   if(MYDEBUG) MESSAGE("PublishHypothesis--END")
938   return aHypSO._retn();
939 }
940
941 //=======================================================================
942 //function : UpdateIcons
943 //purpose  : update icons of a mesh and its children upon mesh modification
944 //=======================================================================
945
946 void SMESH_Gen_i::UpdateIcons( SMESH::SMESH_Mesh_ptr theMesh )
947 {
948   SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( theMesh );
949   if ( ! mesh_i )
950     return;
951
952   SALOMEDS::SObject_wrap so = ObjectToSObject( theMesh );
953   if ( so->_is_nil() )
954     return;
955
956   // set icon of the mesh
957   if ( mesh_i->NbNodes() == 0 )
958     SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN" );
959   else if ( mesh_i->IsComputedOK() )
960     SetPixMap( so, "ICON_SMESH_TREE_MESH" );
961   else if ( mesh_i->HasShapeToMesh() )
962     SetPixMap( so, "ICON_SMESH_TREE_MESH_PARTIAL" );
963   else
964     SetPixMap( so, "ICON_SMESH_TREE_MESH_IMPORTED" );
965
966   // set icons of sub-objects
967   SALOMEDS::Study_var         study = getStudyServant();
968   SALOMEDS::ChildIterator_wrap iter = study->NewChildIterator( so );
969   for ( ; iter->More(); iter->Next() )
970   {
971     so = iter->Value(); // 1st level child - root of algos, hyps, sub-meshes or groups
972     if ( so->Tag() < SMESH::Tag_FirstSubMesh )
973       continue;
974
975     SALOMEDS::ChildIterator_wrap subIter = study->NewChildIterator( so );
976     for ( ; subIter->More(); subIter->Next() )
977     {
978       so = subIter->Value(); // 2nd level child - a sub-mesh or group
979
980       CORBA::Object_var           obj = SObjectToObject( so );
981       SMESH::SMESH_IDSource_var idSrc = SMESH::SMESH_IDSource::_narrow( obj );
982       if ( idSrc->_is_nil() )
983         continue;
984
985       SMESH::SMESH_GroupBase_var     grp = SMESH::SMESH_GroupBase::_narrow( obj );
986       SMESH::SMESH_GroupOnFilter_var gof = SMESH::SMESH_GroupOnFilter::_narrow( obj );
987       const bool         isGroup = !grp->_is_nil();
988       const bool isGroupOnFilter = !gof->_is_nil();
989
990       bool isEmpty = ( mesh_i->NbNodes() == 0 );
991       if ( !isEmpty )
992       {
993         if ( isGroupOnFilter ) // GetTypes() can be very long on GroupOnFilter!
994         {
995           SMESH::smIdType_array_var nbByType = mesh_i->GetNbElementsByType();
996           isEmpty = ( nbByType[ grp->GetType() ] == 0 );
997         }
998         else
999         {
1000           SMESH::array_of_ElementType_var elemTypes = idSrc->GetTypes();
1001           isEmpty = ( elemTypes->length() == 0 );
1002
1003           if ( !isEmpty )
1004           {
1005             // check if all sub-shapes of sub-mesh on group are computed
1006             // (pb: "Compute sub-mesh" menu is missing if a sub-mesh is partially computed)
1007             SMESH::SMESH_subMesh_var subMesh = SMESH::SMESH_subMesh::_narrow( obj );
1008             if ( !subMesh->_is_nil() )
1009               if ( SMESH_subMesh* sm = mesh_i->GetImpl().GetSubMeshContaining( subMesh->GetId() ))
1010                 if ( sm->IsComputedPartially() )
1011                 {
1012                   SetPixMap( so, "ICON_SMESH_TREE_MESH_PARTIAL" );
1013                   continue;
1014                 }
1015           }
1016         }
1017       }
1018
1019       if ( isEmpty )
1020         SetPixMap( so, "ICON_SMESH_TREE_MESH_WARN");
1021       else if ( !isGroup )
1022         SetPixMap( so, "ICON_SMESH_TREE_MESH" );
1023       else if ( isGroupOnFilter )
1024         SetPixMap( so, "ICON_SMESH_TREE_GROUP_ON_FILTER" );
1025       else
1026         SetPixMap( so, "ICON_SMESH_TREE_GROUP" );
1027
1028     } // loop on sub-meshes or groups
1029   } // loop on roots
1030 }
1031
1032 //=======================================================================
1033 //function : HighLightInvalid
1034 //purpose  : change font color of a object in the Object Browser
1035 //=======================================================================
1036
1037 void SMESH_Gen_i::HighLightInvalid( CORBA::Object_ptr theObject, bool isInvalid )
1038 {
1039   SALOMEDS::SObject_wrap so = ObjectToSObject(theObject);
1040   highLightInvalid( so.in(), isInvalid );
1041 }
1042
1043 //=======================================================================
1044 //function : highLightInvalid
1045 //purpose  : change font color of a object in the Object Browser
1046 //=======================================================================
1047
1048 void SMESH_Gen_i::highLightInvalid( SALOMEDS::SObject_ptr theSObject, bool isInvalid )
1049 {
1050   if ( !theSObject->_is_nil() )
1051   {
1052     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1053     if ( isInvalid )
1054     {
1055       SALOMEDS::Color red = { 178,34,34 }; // to differ from reference color
1056       SALOMEDS::GenericAttribute_wrap attr =
1057         studyBuilder->FindOrCreateAttribute( theSObject, "AttributeTextColor" );
1058       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1059       colorAttr->SetTextColor( red );
1060     }
1061     else
1062     {
1063       studyBuilder->RemoveAttribute( theSObject, "AttributeTextColor" );
1064     }
1065   }
1066 }
1067
1068 //=======================================================================
1069 //function : IsInvalid
1070 //purpose  : Check object validity == absence of AttributeTextColor=(178,34,34)
1071 //=======================================================================
1072
1073 bool SMESH_Gen_i::IsInvalid( SALOMEDS::SObject_ptr theSObject )
1074 {
1075   bool isValid = true;
1076   if ( !theSObject->_is_nil() )
1077   {
1078     SALOMEDS::GenericAttribute_wrap attr;
1079     SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1080     if ( studyBuilder->FindAttribute( theSObject, attr.inout(), "AttributeTextColor" ))
1081     {
1082       SALOMEDS::AttributeTextColor_wrap colorAttr = attr;
1083       SALOMEDS::Color color = colorAttr->TextColor();
1084       isValid = ( color.R != 178 || color.G != 34 || color.B != 34 );
1085     }
1086   }
1087   return isValid;
1088 }
1089
1090 //=======================================================================
1091 //function : GetMeshOrSubmeshByShape
1092 //purpose  : 
1093 //=======================================================================
1094
1095 SALOMEDS::SObject_ptr
1096 SMESH_Gen_i::GetMeshOrSubmeshByShape (SMESH::SMESH_Mesh_ptr theMesh,
1097                                       GEOM::GEOM_Object_ptr theShape)
1098 {
1099   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape")
1100   SALOMEDS::SObject_wrap aMeshOrSubMesh;
1101   if (theMesh->_is_nil() || ( theShape->_is_nil() && theMesh->HasShapeToMesh()))
1102     return aMeshOrSubMesh._retn();
1103   
1104   TopoDS_Shape aShape;
1105   if(theMesh->HasShapeToMesh())
1106     aShape = GeomObjectToShape( theShape );
1107   else
1108     aShape = SMESH_Mesh::PseudoShape();
1109
1110   SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1111
1112   if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1113     SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1114     if ( aShape.IsSame( meshDS->ShapeToMesh() ))
1115       aMeshOrSubMesh = ObjectToSObject( theMesh );
1116     else {
1117       int shapeID = meshDS->ShapeToIndex( aShape );
1118       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1119       if ( !aSubMesh->_is_nil() )
1120         aMeshOrSubMesh = ObjectToSObject( aSubMesh );
1121     }
1122   }
1123   if(MYDEBUG) MESSAGE("GetMeshOrSubmeshByShape--END")
1124   return aMeshOrSubMesh._retn();
1125 }
1126
1127 //=======================================================================
1128 //function : AddHypothesisToShape
1129 //purpose  : 
1130 //=======================================================================
1131
1132 bool SMESH_Gen_i::AddHypothesisToShape(SMESH::SMESH_Mesh_ptr       theMesh,
1133                                        GEOM::GEOM_Object_ptr       theShape,
1134                                        SMESH::SMESH_Hypothesis_ptr theHyp)
1135 {
1136   if(MYDEBUG) MESSAGE("AddHypothesisToShape")
1137   if (theMesh->_is_nil() ||
1138       theHyp->_is_nil() || (theShape->_is_nil()
1139                             && theMesh->HasShapeToMesh()) )
1140     return false;
1141
1142   SALOMEDS::SObject_wrap aMeshSO = ObjectToSObject( theMesh );
1143   if ( aMeshSO->_is_nil() )
1144     aMeshSO = PublishMesh( theMesh );
1145   SALOMEDS::SObject_wrap aHypSO = PublishHypothesis( theHyp );
1146   if ( aMeshSO->_is_nil() || aHypSO->_is_nil())
1147     return false;
1148
1149   // Find a mesh or submesh referring to theShape
1150   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1151     GetMeshOrSubmeshByShape( theMesh, theShape );
1152   if ( aMeshOrSubMesh->_is_nil() )
1153   {
1154     // publish submesh
1155     TopoDS_Shape aShape = GeomObjectToShape( theShape );
1156     SMESH_Mesh_i* mesh_i = objectToServant<SMESH_Mesh_i>( theMesh );
1157     if ( !aShape.IsNull() && mesh_i && mesh_i->GetImpl().GetMeshDS() ) {
1158       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
1159       int shapeID = meshDS->ShapeToIndex( aShape );
1160       SMESH::SMESH_subMesh_var aSubMesh = mesh_i->getSubMesh(shapeID);
1161       aMeshOrSubMesh = PublishSubMesh( theMesh, aSubMesh, theShape );
1162     }
1163     if ( aMeshOrSubMesh->_is_nil() )
1164       return false;
1165   }
1166
1167   //Find or Create Applied Hypothesis root
1168   bool aIsAlgo = !SMESH::SMESH_Algo::_narrow( theHyp )->_is_nil();
1169   SALOMEDS::SObject_wrap AHR =
1170     publish (CORBA::Object::_nil(), aMeshOrSubMesh,
1171              aIsAlgo ? GetRefOnAppliedAlgorithmsTag() : GetRefOnAppliedHypothesisTag(),
1172              aIsAlgo ? "ICON_SMESH_TREE_ALGO" : "ICON_SMESH_TREE_HYPO", false);
1173   SetName( AHR, aIsAlgo ? "Applied algorithms" : "Applied hypotheses" );
1174
1175   addReference( AHR, theHyp );
1176
1177   if(MYDEBUG) MESSAGE("AddHypothesisToShape--END")
1178   return true;
1179 }
1180
1181 //=======================================================================
1182 //function : RemoveHypothesisFromShape
1183 //purpose  : 
1184 //=======================================================================
1185
1186 bool SMESH_Gen_i::RemoveHypothesisFromShape(SMESH::SMESH_Mesh_ptr       theMesh,
1187                                             GEOM::GEOM_Object_ptr       theShape,
1188                                             SMESH::SMESH_Hypothesis_ptr theHyp)
1189 {
1190   if (theMesh->_is_nil() ||
1191       theHyp->_is_nil() || (theShape->_is_nil()
1192                             && theMesh->HasShapeToMesh()))
1193     return false;
1194
1195   SALOMEDS::SObject_wrap aHypSO = ObjectToSObject( theHyp );
1196   if ( aHypSO->_is_nil() )
1197     return false;
1198
1199   CORBA::String_var hypEntry = aHypSO->GetID();
1200
1201   // Find a mesh or sub-mesh referring to theShape
1202   SALOMEDS::SObject_wrap aMeshOrSubMesh =
1203     GetMeshOrSubmeshByShape( theMesh, theShape );
1204   if ( aMeshOrSubMesh->_is_nil() )
1205     return false;
1206
1207   // Find and remove a reference to aHypSO
1208   SALOMEDS::SObject_wrap aRef, anObj;
1209   SALOMEDS::ChildIterator_wrap it = getStudyServant()->NewChildIterator( aMeshOrSubMesh );
1210   bool found = false;
1211   for ( it->InitEx( true ); ( it->More() && !found ); it->Next() ) {
1212     anObj = it->Value();
1213     if (anObj->ReferencedObject( aRef.inout() ))
1214     {
1215       CORBA::String_var refEntry = aRef->GetID();
1216       found = ( strcmp( refEntry, hypEntry ) == 0 );
1217     }
1218     if ( found )
1219     {
1220       SALOMEDS::StudyBuilder_var builder = getStudyServant()->NewBuilder();
1221       builder->RemoveObject( anObj );
1222     }
1223   }
1224
1225   return true;
1226 }
1227
1228 //================================================================================
1229 /*!
1230  * \brief Stores names of variables that WILL be passes as parameters when calling
1231  *        some method of a given object.
1232  *  \param [in] theObject - the object whose a method WILL be called with \a theParameters.
1233  *  \param [in] theParameters - a string containing parameters separated by ':'.
1234  */
1235 //================================================================================
1236
1237 void SMESH_Gen_i::UpdateParameters(CORBA::Object_ptr theObject, const char* theParameters)
1238 {
1239   // find variable names within theParameters
1240
1241   myLastObj.clear();
1242   myLastParameters.clear();
1243   myLastParamIndex.clear(); /* vector holding indices of virables within the string
1244                                of all variables used for theObject */ 
1245   int nbVars = 0;
1246   int pos = 0, prevPos = 0, len = strlen( theParameters );
1247   if ( len == 0 ) return;
1248   while ( pos <= len )
1249   {
1250     if ( pos == len || theParameters[pos] == ':' )
1251     {
1252       if ( prevPos < pos )
1253       {
1254         string val( theParameters + prevPos, theParameters + pos );
1255         if ( !getStudyServant()->IsVariable( val.c_str() ))
1256           val.clear();
1257         myLastParameters.push_back( val );
1258         nbVars += (! myLastParameters.back().empty() );
1259       }
1260       else
1261       {
1262         myLastParameters.push_back("");
1263       }
1264       prevPos = pos+1;
1265     }
1266     ++pos;
1267   }
1268
1269   if ( nbVars < 1 )
1270     return;
1271
1272   // store
1273   // (1) variable names in the string of all variables used for theObject and
1274   // (2) indices of found variables in myLastParamIndex.
1275
1276   // remember theObject
1277   SALOMEDS::SObject_wrap aSObj =  ObjectToSObject(theObject);
1278   if ( aSObj->_is_nil() )
1279     return;
1280   CORBA::String_var anObjEntry = aSObj->GetID();
1281   myLastObj = anObjEntry.in();
1282
1283   // get a string of variable names
1284   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1285   SALOMEDS::GenericAttribute_wrap     anAttr =
1286     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1287   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1288   CORBA::String_var                  oldVars = aStringAttr->Value();
1289   std::string                         varStr = oldVars.in();
1290
1291   // add new variables and find indices of variables
1292   for ( size_t i = 0; i < myLastParameters.size(); ++i )
1293   {
1294     int varIndex = -1;
1295     if ( !myLastParameters[i].empty() )
1296     {
1297       // find index of myLastParameters[i] in varStr
1298       int curIndex  = 0;
1299       bool varFound = false;
1300       size_t pos    = 0;
1301       // varStr can be "A|B::C;*=2|D"
1302       const std::string separators(":|;*=");
1303       while ( pos < varStr.size() && !varFound )
1304       {
1305         // skip separators
1306         while ( separators.find( varStr[ pos ]) != std::string::npos )
1307           if ( ++pos >= varStr.size() )
1308             break;
1309         // skip repetition number following '='
1310         if ( varStr[ pos-1 ] == '=' )
1311         {
1312           while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1313             ++pos;
1314           continue; // to skip next separator
1315         }
1316         // compare variable name
1317         if ( pos < varStr.size() )
1318         {
1319           varFound = ( varStr.compare( pos, myLastParameters[i].size(), myLastParameters[i] ) == 0 &&
1320                        // same string beginning but is length same?
1321                        ( pos + myLastParameters[i].size() >= varStr.size() ||
1322                          separators.find( varStr[ pos+1 ]) != std::string::npos ));
1323           if ( varFound )
1324             varIndex = curIndex;
1325           else
1326             pos = varStr.find_first_of( separators, pos ); // goto the next separator
1327           ++curIndex;
1328         }
1329       }
1330       // add new variable
1331       if ( !varFound )
1332       {
1333         varStr += ":" + myLastParameters[i];
1334         varIndex = curIndex;
1335       }
1336     }
1337     myLastParamIndex.push_back( varIndex );
1338   }
1339   aStringAttr->SetValue( varStr.c_str() );
1340 }
1341
1342 //================================================================================
1343 /*!
1344  * \brief Return all variables used to create an object
1345  *  \param [in] theObjectEntry - an object entry in the current study
1346  *  \return std::vector< std::string > - all variable names (or values of removed variables)
1347  */
1348 //================================================================================
1349
1350 std::vector< std::string > SMESH_Gen_i::GetAllParameters(const std::string& theObjectEntry) const
1351 {
1352   std::vector< std::string > varNames;
1353
1354   SALOMEDS::SObject_wrap aSObj = getStudyServant()->FindObjectID( theObjectEntry.c_str() );
1355
1356   // get a string of variable names
1357   SALOMEDS::StudyBuilder_var   aStudyBuilder = getStudyServant()->NewBuilder();
1358   SALOMEDS::GenericAttribute_wrap     anAttr =
1359     aStudyBuilder->FindOrCreateAttribute( aSObj, "AttributeString" );
1360   SALOMEDS::AttributeString_wrap aStringAttr = anAttr;
1361   CORBA::String_var                  oldVars = aStringAttr->Value();
1362   std::string                         varStr = oldVars.in();
1363
1364   // separate variables within varStr;
1365   // varStr can be "A|B::C;*=2|D"
1366   size_t pos = 0;
1367   const std::string separators(":|;*=");
1368   while ( pos < varStr.size() )
1369   {
1370     // skip separators
1371     pos = varStr.find_first_not_of( separators, pos );
1372     // while ( separators.find( varStr[ pos ]) != std::string::npos )
1373     //   if ( ++pos >= varStr.size() )
1374     //     break;
1375     // skip repetition number following '='
1376     if ( varStr[ pos-1 ] == '=' )
1377     {
1378       while ( '0' <= varStr[ pos ] && varStr[ pos ] <= '9' )
1379         ++pos;
1380       continue; // to skip next separator
1381     }
1382     // store variable name
1383     if ( pos < varStr.size() )
1384     {
1385       size_t pos2 = varStr.find_first_of( separators, pos );
1386       varNames.push_back( varStr.substr( pos, pos2 - pos));
1387       pos = pos2;
1388     }
1389   }
1390   return varNames;
1391 }
1392
1393 //=======================================================================
1394 //function : ParseParameters
1395 //purpose  : Replace variables by their values
1396 //=======================================================================
1397 // char* SMESH_Gen_i::ParseParameters(const char* theParameters)
1398 // {
1399 //   //const char* aParameters = theParameters;
1400 // //   const char* aParameters = CORBA::string_dup(theParameters);
1401 //   TCollection_AsciiString anInputParams;
1402 //   SALOMEDS::Study_var aStudy = getStudyServant();
1403 //   if( !aStudy->_is_nil() ) {
1404 // //     SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(theParameters);
1405 // //     for(int j=0;j<aSections->length();j++) {
1406 // //       SALOMEDS::ListOfStrings aVars= aSections[j];
1407 // //       for(int i=0;i<aVars.length();i++ ) {
1408 // //         anInputParams += aStudy->IsVariable(aVars[i].in()) ? 
1409 // //           TCollection_AsciiString(aVars[i].in()) : TCollection_AsciiString("");
1410 // //         if(i != aVars.length()-1)
1411 // //           anInputParams+=":";
1412 // //       }
1413 // //       if(j!=aSections->length()-1)
1414 // //         anInputParams+="|";
1415 // //     }
1416 //     TCollection_AsciiString paramStr( theParameters );
1417 //     int beg = 0, end;
1418 //     char sep, *pParams = (char*)paramStr.ToCString();
1419 //     while ( beg < paramStr.Length() )
1420 //     {
1421 //       end = beg-1;
1422 //       while ( ++end < paramStr.Length() )
1423 //         if ( pParams[end] == ':' || pParams[end] == '|')
1424 //           break;
1425 //       if ( end < paramStr.Length())
1426 //       {
1427 //         sep = pParams[end];
1428 //         pParams[end] = '\0';
1429 //       }
1430 //       if ( aStudy->IsVariable( pParams+beg ))
1431 //         anInputParams += pParams+beg;
1432 //       if ( end < paramStr.Length() )
1433 //         anInputParams += sep;
1434 //       else
1435 //         break;
1436 //       beg = end + 1;
1437 //     }
1438 //   }
1439 //   return CORBA::string_dup(anInputParams.ToCString());
1440 // }
1441
1442 //=======================================================================
1443 //function : GetParameters
1444 //purpose  : 
1445 //=======================================================================
1446
1447 char* SMESH_Gen_i::GetParameters(CORBA::Object_ptr theObject)
1448 {
1449   CORBA::String_var aResult("");
1450
1451   SALOMEDS::SObject_wrap aSObj = ObjectToSObject( theObject );
1452   if ( !aSObj->_is_nil() )
1453   {
1454     SALOMEDS::GenericAttribute_wrap attr;
1455     if ( aSObj->FindAttribute( attr.inout(), "AttributeString"))
1456     {
1457       SALOMEDS::AttributeString_wrap strAttr = attr;
1458       aResult = strAttr->Value();
1459     }
1460   }
1461   return aResult._retn();
1462 }
1463
1464 //================================================================================
1465 /*!
1466  * \brief Create a sub-mesh on a geometry that is not a sub-shape of the main shape
1467  * for the case where a valid sub-shape not found by CopyMeshWithGeom().
1468  * The invalid sub-mesh has GetId() < 0.
1469  */
1470 //================================================================================
1471
1472 SMESH::SMESH_subMesh_ptr
1473 SMESH_Gen_i::createInvalidSubMesh(SMESH::SMESH_Mesh_ptr theMesh,
1474                                   GEOM::GEOM_Object_ptr theStrangerGeom,
1475                                   const char*           theName)
1476 {
1477   SMESH::SMESH_subMesh_var subMesh;
1478
1479   try
1480   {
1481     SMESH_Mesh_i* mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1482     subMesh = mesh_i->createSubMesh( theStrangerGeom );
1483
1484     if ( !subMesh->_is_nil() && CanPublishInStudy( subMesh ))
1485     {
1486       SALOMEDS::SObject_wrap so = PublishSubMesh( theMesh, subMesh, theStrangerGeom, theName );
1487
1488       // hide a reference to geometry
1489       if ( !so->_is_nil() )
1490       {
1491         SALOMEDS::SObject_wrap refSO;
1492         if ( so->FindSubObject( GetRefOnShapeTag(), refSO.inout() ))
1493         {
1494           SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
1495           SALOMEDS::GenericAttribute_wrap attr =
1496             studyBuilder->FindOrCreateAttribute( refSO, "AttributeDrawable" );
1497           SALOMEDS::AttributeDrawable_wrap ga = attr;
1498           ga->SetDrawable( false );
1499         }
1500       }
1501     }
1502   }
1503   catch (...) {
1504   }
1505
1506   return subMesh._retn();
1507 }
1508
1509
1510 // ==============
1511 // Study context
1512 // ==============
1513
1514 //=======================================================================
1515 //function : addObject
1516 //purpose  : register object in the internal map and return its id
1517 //=======================================================================
1518
1519 int StudyContext::addObject( const std::string& theIOR )
1520 {
1521   int nextId = getNextId();
1522   mapIdToIOR.Bind( nextId, theIOR );
1523   return nextId;
1524 }
1525
1526 //=======================================================================
1527 //function : findId
1528 //purpose  : find the object id in the internal map by the IOR
1529 //=======================================================================
1530
1531 int StudyContext::findId( const std::string& theIOR )
1532 {
1533   TInt2StringMap::iterator imap;
1534   for ( imap = mapIdToIOR.begin(); imap != mapIdToIOR.end(); ++imap ) {
1535     if ( *imap == theIOR )
1536       return imap.Iterator().Key();
1537   }
1538   return 0;
1539 }
1540
1541 //=======================================================================
1542 //function : getIORbyId
1543 //purpose  : get object's IOR by id
1544 //=======================================================================
1545
1546 std::string StudyContext::getIORbyId( const int theId )
1547 {
1548   if ( mapIdToIOR.IsBound( theId ) )
1549     return mapIdToIOR( theId );
1550   return std::string();
1551 }
1552
1553 //=======================================================================
1554 //function : getIORbyOldId
1555 //purpose  : get object's IOR by old id
1556 //=======================================================================
1557
1558 std::string StudyContext::getIORbyOldId( const int theOldId )
1559 {
1560   if ( mapIdToId.IsBound( theOldId ) )
1561     return getIORbyId( mapIdToId( theOldId ));
1562   return std::string();
1563 }
1564
1565 //=======================================================================
1566 //function : mapOldToNew
1567 //purpose  : maps old object id to the new one (used when restoring data)
1568 //=======================================================================
1569
1570 void StudyContext::mapOldToNew( const int oldId, const int newId )
1571 {
1572   mapIdToId.Bind( oldId, newId );
1573 }
1574
1575 //=======================================================================
1576 //function : getOldId
1577 //purpose  : get old id by a new one
1578 //=======================================================================
1579
1580 int StudyContext::getOldId( const int newId )
1581 {
1582   TInt2IntMap::iterator imap;
1583   for ( imap = mapIdToId.begin(); imap != mapIdToId.end(); ++imap ) {
1584     if ( *imap == newId )
1585       return imap.Iterator().Key();
1586   }
1587   return 0;
1588 }
1589
1590 //=======================================================================
1591 //function : Clear
1592 //purpose  : clear data
1593 //=======================================================================
1594
1595 void StudyContext::Clear()
1596 {
1597   mapIdToIOR.Clear();
1598   mapIdToId.Clear();
1599 }