Salome HOME
890959cfb9e1482420ecddc3a4e40953eae0727c
[modules/geom.git] / src / GEOM_PY / geomtools.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2007-2011  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 """
22 This module provides tools to facilitate the use of geom engine and geom
23 objects in Salome.
24 """
25
26 import salome
27 GEOM = None    # GEOM module is loaded only when needed
28
29 from salome.kernel.logger import Logger
30 from salome.kernel import termcolor
31 logger = Logger("salome.geom.geomtools", color = termcolor.RED)
32
33 from salome.kernel.studyedit import getActiveStudyId, getStudyEditor
34 from salome.kernel.services import IDToObject
35 try:
36     from salome.gui import helper
37 except:
38     pass
39
40 _geompys = {}
41
42 def getGeompy(studyId = None):
43     """
44     Return an object behaving exactly like geompy module, except that it is
45     associated with the study `studyId`. If `studyId` is :const:`None`, return
46     a pseudo geompy object for the current study.
47     """
48     # We can't use geompy module because it initializes GEOM with
49     # salome.myStudy, which may not exist. So we use this trick to create
50     # a pseudo geompy module. 
51     salome.salome_init()
52     if studyId is None:
53         studyId = getActiveStudyId()
54     if not _geompys.has_key(studyId):
55         import geompyDC
56         _geompys[studyId] = salome.lcc.FindOrLoadComponent("FactoryServer",
57                                                            "GEOM")
58         _geompys[studyId].ShapeType = geompyDC.ShapeType
59         _geompys[studyId].GEOM = geompyDC.GEOM
60         _geompys[studyId].kind = geompyDC.kind
61         _geompys[studyId].info = geompyDC.info
62         _geompys[studyId].PackData = geompyDC.PackData
63         _geompys[studyId].ReadTexture = geompyDC.ReadTexture
64         study = salome.myStudyManager.GetStudyByID(studyId)
65         _geompys[studyId].init_geom(study)
66     return _geompys[studyId]
67
68
69 ModeWireFrame = 0
70 ModeShading = 1
71 DisplayMode=ModeShading
72
73 class GeomStudyTools:
74     """
75     This class provides several methods to manipulate geom objects in Salome
76     study. The parameter `studyEditor` defines a
77     :class:`~salome.kernel.studyedit.StudyEditor` object used to access the study. If
78     :const:`None`, the method returns a :class:`~salome.kernel.studyedit.StudyEditor`
79     object on the current study.
80
81     .. attribute:: editor
82     
83        This instance attribute contains the underlying
84        :class:`~salome.kernel.studyedit.StudyEditor` object. It can be used to access
85        the study but the attribute itself should not be modified.
86
87     """
88
89     def __init__(self, studyEditor = None):
90         global GEOM
91         if GEOM is None:
92             GEOM = __import__("GEOM")
93         if studyEditor is None:
94             studyEditor = getStudyEditor()
95         self.editor = studyEditor
96
97     def displayShapeByName(self, shapeName, color = None):
98         """
99         Display the geometrical shape whose name in the study is `shapeName`.
100         
101         :type   shapeName: string
102         :param  shapeName: name of the geometrical shape
103         
104         :type   color: tuple (triplet)
105         :param  color: RGB components of the color of the shape
106         
107         :return: True if the shape was found, False otherwise
108         """
109         logger.debug("displayShapeByName in PAL: %s with color %s" %
110                      (shapeName, color))
111         listSO = self.editor.study.FindObjectByName(shapeName, "GEOM")
112         for sObj in listSO:
113             entry = sObj.GetID()
114             geomObj = self.editor.getOrLoadObject(sObj)
115             if geomObj:
116                 shape = geomObj._narrow(GEOM.GEOM_Object)
117                 if shape:
118                     return self.displayShapeByEntry(entry,color)
119         return False
120
121     def displayShapeByEntry(self, entry, color = None):
122         """
123         Display the geometrical shape whose entry is given by `entry`.
124         """
125         geomgui = salome.ImportComponentGUI("GEOM")            
126         geomgui.createAndDisplayGO(entry)
127         geomgui.setDisplayMode(entry, DisplayMode)
128         if color is not None:
129             geomgui.setColor(entry, color[0], color[1], color[2])
130         return True
131
132     def eraseShapeByEntry(self, entry):
133         """
134         Erase the geometrical shape whose entry is given by
135         `entry`. Please note that the shape is just erased from the
136         viewer. The associated study object still exists in the study,
137         and the geom object still exists in the GEOM engine.
138         """
139         geomgui = salome.ImportComponentGUI("GEOM")
140         eraseFromAllWindows=True
141         geomgui.eraseGO(entry,eraseFromAllWindows)
142         return True
143     
144     def getGeomObjectSelected(self):
145         '''
146         Returns the GEOM object currently selected in the objects browser.
147         '''
148         sobject, entry = helper.getSObjectSelected()
149         geomObject = self.getGeomObjectFromEntry(entry)
150         return geomObject
151
152     def getGeomObjectFromEntry(self,entry):
153         '''
154         Returns the GEOM object associated to the specified entry,
155         (the entry is the identifier of an item in the active study)
156         '''
157         if entry is None:
158             return None
159         geomObject=IDToObject(entry, self.editor.study)
160         return geomObject._narrow(GEOM.GEOM_Object)
161
162 #
163 # ==================================================================
164 # Use cases and demo functions
165 # ==================================================================
166 #
167
168 # How to test?
169 # 1. Run a SALOME application including GEOM, and create a new study
170 # 2. In the console, enter:
171 #    >>> from salome.geom import geomtools
172 #    >>> geomtools.TEST_createBox()
173 # 3. Select the object named "box" in the browser
174 # 4. In the console, enter:
175 #    >>> geomtools.TEST_getGeomObjectSelected()
176
177 def TEST_createBox():
178     geompy = getGeompy()
179     box = geompy.MakeBoxDXDYDZ(200, 200, 200)
180     geompy.addToStudy( box, 'box' )    
181     if salome.sg.hasDesktop():
182         salome.sg.updateObjBrowser(1)
183
184
185 def TEST_getGeomObjectSelected():
186     tool = GeomStudyTools()
187     myGeomObject = tool.getGeomObjectSelected()
188     print myGeomObject
189
190 if __name__ == "__main__":
191     TEST_getGeomObjectSelected()
192
193
194