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