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