Salome HOME
Revert "Synchronize adm files"
[modules/kernel.git] / src / KERNEL_PY / kernel / services.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 # Author: Guillaume Boulant (EDF/R&D)
22
23 ## \defgroup service service
24 #  \{ 
25 #  \details Helper for using %SALOME kernel services
26 #  \}
27
28 #
29 # WARNING: development notes
30 #
31 # This python module is aimed to be a (yet another?) end user
32 # interface to manipulate the KERNEL SALOME services. Note that it
33 # does not replace the salome module (i.e. what you get when typing
34 # "import salome", actually implemented in the file __init__.py of the
35 # salome python package). It provides instead functions that help to
36 # use the salome module in a end user context (development of domain
37 # specific tools by programmers that are not ten years experienced in
38 # SALOME development).
39
40 import salome
41 from deprecation import is_called_by_sphinx
42 if not is_called_by_sphinx() and salome.lcc is None:
43     try:
44         salome.salome_init()
45     except Exception, e:
46         print e
47
48 # Note that the salome module provides you with standard SALOME
49 # objects: CORBA broker (orb): salome.orb lyfe cycle (lcc) :
50 # salome.lcc naming service : salome.naming_service study manager :
51 # salome.myStudyManager The default study : salome.myStudy
52 #
53 # Alternatively, you may obtain these objects directly with the
54 # following instructions:
55 #
56 #   from omniORB import CORBA
57 #   from LifeCycleCORBA import LifeCycleCORBA
58 #   orb = CORBA.ORB_init( [''], CORBA.ORB_ID )
59 #   lcc = LifeCycleCORBA( orb )
60
61 #   from SALOME_NamingServicePy import SALOME_NamingServicePy_i
62 #   naming_service = SALOME_NamingServicePy_i( orb )
63 #
64 # (See salome.py page in the KERNEL documentation)
65
66 #
67 # ==============================================================================
68 # Helper functions for SALOME components
69 # ==============================================================================
70 #
71
72 ## Get a %SALOME CORBA component from its name
73 #  \param componentName is the name of the component as declared in the XML
74 #  %SALOME catalog. %A loadable library with name lib<componentName>Engine.so
75 #  is supposed to be reachable. This library is supposed to provide a
76 #  factory function with the prototype:
77 #
78 #  \code
79 #  PortableServer::ObjectId * <componentName>Engine_factory( CORBA::ORB_ptr orb,
80 #                                                            PortableServer::POA_ptr poa,
81 #                                                            PortableServer::ObjectId* contId,
82 #                                                            const char *instanceName,
83 #                                                            const char *interfaceName );
84 #  \endcode
85 #
86 #  \param corbaModule is the name of the IDL module that contains the
87 #  definition of the interface of the component. This name corresponds
88 #  to the namespace of the servant classes.
89 #
90 #  \param containerType specified the container in which the servants are
91 #  executed.
92 #  \ingroup service
93 def getComponent(componentName = "SalomeTestComponent",
94                  corbaModule   = "Engines",
95                  containerType = "FactoryServer"):
96     """
97     Get a SALOME CORBA component from its name
98     """
99     print "INF: getting component %s from CORBA module %s ..."%(componentName,corbaModule)
100     __import__(corbaModule)
101     component=salome.lcc.FindOrLoadComponent(containerType,componentName)
102     if component is None:
103         print "ERR: the SALOME component "+componentName+" can't be reached"
104     print "INF: component %s obtained from CORBA module %s"%(componentName,corbaModule)
105     return component
106
107 # Note that an alternative (and maybe better) method to get a component
108 # is to use the module catalog. Here, we just use the catalog to get
109 # the list of components defined in the current session.
110 import SALOME_ModuleCatalog
111
112 ## Get the list of names of all %SALOME componenents register in
113 #  the catalog.
114 #  \ingroup service
115 def getComponentList():
116     """
117     Get the list of names of all SALOME componenents register in
118     the catalog.
119     """
120     obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
121     catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
122     if not catalog:
123         raise RuntimeError, "Can't accesss module catalog"
124     return catalog.GetComponentList()
125
126 ## Get a study manager to create and manage %SALOME studies
127 #  \ingroup service
128 def getStudyManager():
129     """Get a study manager to create and manage SALOME studies"""
130     return salome.myStudyManager
131
132 import SALOMEDS
133 ## Get a study manager to create and manage SALOME studies. 
134 #  \warning you should use instead the variable salome.myStudyManager. 
135 #  This function is given for illustration of usage of the naming service
136 #  \ingroup service
137 def __getStudyManager_demo():
138     """
139     Get a study manager to create and manage SALOME studies. WARN: you
140     should use instead the variable salome.myStudyManager. This
141     function is given for illustration of usage of the naming service
142     """
143     naming_service = SALOME_NamingServicePy_i( orb )
144     obj = naming_service.Resolve( '/myStudyManager' )
145     studyManager = obj._narrow( SALOMEDS.StudyManager)
146     return studyManager
147
148
149 #
150 # ==============================================================================
151 # Helper functions for manipulating objects, sobjects and entry
152 # ==============================================================================
153 #
154
155 # - the SObject is an item in a study (Study Object).
156 # - the entry is the identifier of an item.
157 # - the ID is the entry
158 # - the object (geom object or smesh object) is a CORBA servant
159 #   embedded in the SALOME component container and with a reference in
160 #   the SALOME study, so that it can be retrieved.
161
162 # __GBO__ WARN: theses functions are already defined in
163 # salome_study.py, but without the possibility to specify the
164 # underlying study (in salome_study.py, the study is the default study
165 # binded to the salome.myStudy attribute). TODO: see if it can be
166 # extends to the prototype (with the study as an argument) below and
167 # resorb the functions below.
168
169 def IDToObject(id, study=None):
170     myObj = None
171     if study is None:
172         myStudy = salome.myStudy
173     else:
174         myStudy = study
175     mySO = myStudy.FindObjectID(id);
176     if mySO is not None:
177         ok, anAttr = mySO.FindAttribute("AttributeIOR")
178         if ok:
179             AtIOR = anAttr._narrow(SALOMEDS.AttributeIOR)
180             if AtIOR.Value() != "":
181                 myObj = salome.orb.string_to_object(AtIOR.Value())
182     return myObj
183
184 def ObjectToSObject(obj, study=None):
185     mySO = None
186
187     if study is None:
188         myStudy = salome.myStudy
189     else:
190         myStudy = study
191
192     if obj is not None:
193         ior =  salome.orb.object_to_string(obj)
194         if ior != "":
195             mySO = myStudy.FindObjectIOR(ior)
196     return mySO
197
198 def ObjectToID(obj, study=None):
199     mySO = ObjectToSObject(obj,study)
200     if mySO:
201         return mySO.GetID()
202     return ""
203
204 def IDToSObject(id, study=None):
205     if study is None:
206         myStudy = salome.myStudy
207     else:
208         myStudy = study
209
210     mySO = myStudy.FindObjectID(id);
211     return mySO
212
213 def SObjectToID(sobject):
214     if sobject is None: return None
215     return sobject.GetID()
216
217
218 #
219 # ==============================================================================
220 # Basic use cases and unit tests
221 # ==============================================================================
222 #
223
224 def TEST_getComponent():
225     component=getComponent(componentName = "SalomeTestComponent")
226     
227     ref_string = 'TestComponent_i : L = 3'
228     res_string = component.Coucou(3)
229     if ref_string != ref_string:
230         return False
231     return True
232
233 def TEST_getComponentList():
234     componentList=getComponentList()
235     if 'SalomeTestComponent' not in componentList:
236         return False
237     return True
238
239 def TEST_createObject():
240     """
241     WARNING: for this test, we need GEOM (used to create an object) 
242     """
243     import GEOM
244     from salome.geom import geomBuilder
245     geompy = geomBuilder.New(salome.myStudy)
246
247     box = geompy.MakeBoxDXDYDZ(200, 200, 200)
248     id = geompy.addToStudy( box, 'box' )
249     return id
250
251 def TEST_objectsManipulation():
252     myEntry = TEST_createObject()
253
254     mySObject = IDToSObject(myEntry)
255     entry     = SObjectToID(mySObject)
256
257     if str(entry) != str(myEntry):
258         return False
259
260
261     myObject = IDToObject(myEntry)
262     print myObject
263     if myObject is None:
264         return False
265
266     return True
267
268 if __name__ == "__main__":
269     import unittester
270     unittester.run("services","TEST_getComponent")
271     unittester.run("services","TEST_getComponentList")
272     unittester.run("services","TEST_objectsManipulation")