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