Salome HOME
Merge Python 3 porting.
[modules/gui.git] / src / SalomeApp / pluginsdemo / salome_plugins.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2010-2016  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 # Author : Guillaume Boulant (EDF)
21
22 import salome_pluginsmanager
23
24 DEMO_IS_ACTIVATED = False
25
26 if DEMO_IS_ACTIVATED:
27   # Check that GEOM and SMESH modules are present
28   try:
29     import GEOM
30     from salome.geom import geomBuilder
31     geompy = geomBuilder.New()
32     
33     import SMESH, SALOMEDS
34     from salome.smesh import smeshBuilder
35     smesh =  smeshBuilder.New()
36   except:
37     DEMO_IS_ACTIVATED = False
38
39 if DEMO_IS_ACTIVATED:
40   # -------------------------------------------------------------------------
41   # Example 1: creation of basic objects.
42   # The plugin function is implemented here and declared in the pluginsmanager.
43   #
44   import salome
45
46   def trihedron(context):
47       import GEOM
48       from salome.geom import geomBuilder
49
50       # Intialize the geompy factory with the active study
51       geompy = geomBuilder.New()
52
53       # Create the objects
54       Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
55       Vy = geompy.MakeVectorDXDYDZ(0, 10, 0)
56       Vz = geompy.MakeVectorDXDYDZ(0, 0, 10)
57       origin = geompy.MakeVertex(0, 0, 0)
58
59       # Register the objects in the active study
60       geompy.addToStudy( Vx, "Vx" )
61       geompy.addToStudy( Vy, "Vy" )
62       geompy.addToStudy( Vz, "Vz" )
63       geompy.addToStudy( origin, "origin" )
64
65
66   salome_pluginsmanager.AddFunction('DEMO/O,Vx,Vy,Vz',
67                                     'Creates the trihedron',
68                                     trihedron)
69
70
71   # -------------------------------------------------------------------------
72   # Example 1 bis: creation of basic objects and automatic display
73   def trihedron_withdisplay(context):
74       import GEOM
75       from salome.geom import geomBuilder
76
77       # Intialize the geompy factory with the active study
78       geompy = geomBuilder.New()
79
80       # Create the objects
81       Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
82       Vy = geompy.MakeVectorDXDYDZ(0, 10, 0)
83       Vz = geompy.MakeVectorDXDYDZ(0, 0, 10)
84       origin = geompy.MakeVertex(0, 0, 0)
85
86       # Register the objects in the active study
87       entries=[]
88       entries.append(geompy.addToStudy( Vx, "Vx" ))
89       entries.append(geompy.addToStudy( Vy, "Vy" ))
90       entries.append(geompy.addToStudy( Vz, "Vz" ))
91       entries.append(geompy.addToStudy( origin, "origin" ))
92
93       # This part is to automatically display the objects in the active viewer.
94       gcomp = salome.ImportComponentGUI("GEOM")
95       for entry in entries:
96           gcomp.createAndDisplayFitAllGO(entry)
97
98
99   salome_pluginsmanager.AddFunction('DEMO/O,Vx,Vy,Vz (2)',
100                                     'Creates Basic GEOM objects',
101                                     trihedron_withdisplay)
102
103   # -------------------------------------------------------------------------
104   # Example 2: creation of a shape with parameters that can be read from a GUI.
105   # The plugin function (tube_shapewithgui) delegates some action to
106   # dedicated imported modules (tube.py and tubedialog.py).
107   #
108
109   import tubebuilder
110   import xalome
111
112   # A single dialog box is defined and recycled for every call. The
113   # fields are initialized with default values given by the tube factory
114   # tube.py.
115   import tubedialog
116   dialog = tubedialog.TubeDialog()
117   dialog.setData(tubebuilder.DEFAULT_RADIUS,
118                 tubebuilder.DEFAULT_LENGTH,
119                 tubebuilder.DEFAULT_WIDTH)
120
121   def tube_shapewithgui(context):
122       global tubebuilder, xalome, dialog
123
124       # Get the parameter values from a gui dialog box. If the dialog is
125       # closed using the Ok button, then the data are requested from the
126       # gui and used to create the shape of the tube.
127       dialog.exec_()
128       if dialog.wasOk():
129           radius, length, width = dialog.getData()
130           shape = tubebuilder.createGeometry(radius, length, width)
131           entry = xalome.addToStudy(shape, "Tube" )
132           xalome.displayShape(entry)
133
134
135   salome_pluginsmanager.AddFunction('DEMO/Tube shape from parameters',
136                                     'Creates a tube object from specified parameters',
137                                     tube_shapewithgui)
138
139
140   # -------------------------------------------------------------------------
141   # Example 2 bis: creation of a mesh with parameters that can be read from a GUI.
142   # The plugin function (tube_meshwithgui) delegates some action to
143   # dedicated imported modules (tubebuilder.py and tubedialog.py).
144   #
145   def tube_meshwithgui(context):
146       global tube, dialog
147
148       # Get the parameter values from a gui dialog box. If the dialog is
149       # closed using the Ok button, then the data are requested from the
150       # gui and used to create the shape of the tube.
151       dialog.exec_()
152       if dialog.wasOk():
153           radius, length, width = dialog.getData()
154           mesh = tubebuilder.createModel(radius, length, width)
155
156
157   salome_pluginsmanager.AddFunction('DEMO/Tube mesh from parameters',
158                                     'Creates a tube object from specified parameters',
159                                     tube_meshwithgui)
160
161
162   # -------------------------------------------------------------------------
163   # Example 2 ter: creation of a geom object with a preview function in
164   # the dialog box. This use case is more complex from the gui point of
165   # view because the dialog box is a not modal so that we can have
166   # interaction with the complete SALOME application. This modal
167   # situation requires to connect button click signal on global
168   # functions as a "callback" mechanism.
169   #
170   # TODO:
171   # - coloring the preview in pink
172   # - store the tmp study objects in a "preview" folder
173   #
174   dialogWithApply = tubedialog.TubeDialogOnTopWithApply()
175   dialogWithApply.setData(tubebuilder.DEFAULT_RADIUS,
176                           tubebuilder.DEFAULT_LENGTH,
177                           tubebuilder.DEFAULT_WIDTH)
178   previewShapeEntry = None
179
180   DEFAULT_FOLDER_NAME="TubeList"
181   DEFAULT_SHAPE_NAME="tube"
182   PREVIEW_SHAPE_NAME="preview"
183
184   def acceptCallback():
185       """Action to be done when click on Ok"""
186       global tubebuilder, xalome
187       global dialogWithApply
188       global previewShapeEntry, deletePreviewShape
189       global DEFAULT_FOLDER_NAME,DEFAULT_SHAPE_NAME
190
191       dialogWithApply.accept()
192
193       if previewShapeEntry is not None:
194           deletePreviewShape()
195
196       radius, length, width = dialogWithApply.getData()
197       shape = tubebuilder.createGeometry(radius, length, width)
198       entry = xalome.addToStudy(shape, DEFAULT_SHAPE_NAME, DEFAULT_FOLDER_NAME)
199       xalome.displayShape(entry)
200
201   def rejectCallback():
202       """Action to be done when click on Cancel"""
203       global dialogWithApply, previewShapeEntry, deletePreviewShape
204
205       dialogWithApply.reject()
206
207       if previewShapeEntry is not None:
208           deletePreviewShape()
209
210   import SALOMEDS
211   PREVIEW_COLOR=SALOMEDS.Color(1,0.6,1) # pink
212
213   def applyCallback():
214       """Action to be done when click on Apply"""
215       global tubebuilder, xalome
216       global dialogWithApply
217       global previewShapeEntry, deletePreviewShape
218       global PREVIEW_COLOR, DEFAULT_SHAPE_NAME, DEFAULT_FOLDER_NAME, PREVIEW_SHAPE_NAME
219
220       # We first have to destroy the currently displayed preview shape.
221       if previewShapeEntry is not None:
222           deletePreviewShape()
223
224       # Then we can create the new shape with the new parameter values
225       radius, length, width = dialogWithApply.getData()
226       shape = tubebuilder.createGeometry(radius, length, width)
227       # We apply a specific color on the shape for the preview state
228       shape.SetColor(PREVIEW_COLOR)
229       previewShapeEntry = xalome.addToStudy(shape, PREVIEW_SHAPE_NAME, DEFAULT_FOLDER_NAME )
230       xalome.displayShape(previewShapeEntry)
231
232   def deletePreviewShape():
233       """This delete the shape currently being displayed as a preview"""
234       global previewShapeEntry, xsalome
235       xalome.deleteShape(previewShapeEntry)
236       previewShapeEntry = None
237
238   # Connection of callback functions to the dialog butoon click signals
239   dialogWithApply.handleAcceptWith(acceptCallback)
240   dialogWithApply.handleRejectWith(rejectCallback)
241   dialogWithApply.handleApplyWith(applyCallback)
242
243   def tube_shapewithguiAndPreview(context):
244       """
245       This plugin open a dialog in an asynchronous mode. Then it
246       required callback functions to be associated to the button
247       signals.
248       """
249       global dialogWithApply
250       dialogWithApply.open()
251
252
253   salome_pluginsmanager.AddFunction('DEMO/Tube geometry from parameters with preview',
254                                     'Creates a tube object from specified parameters',
255                                     tube_shapewithguiAndPreview)
256
257
258
259 # -------------------------------------------------------------------------
260 # Example 3: run a shell session in a xterm to get a SALOME python console
261 def runSalomeShellSession(context):
262     import os,subprocess
263     import salome_version
264     version = salome_version.getVersion(full=True)
265     kernel_appli_dir = os.environ['KERNEL_ROOT_DIR']
266     command = ""
267     if os.path.exists("/usr/bin/gnome-terminal"):
268       command = 'gnome-terminal -t "SALOME %s - Shell session" -e "%s/salome shell" &'%(version,kernel_appli_dir)
269     elif os.path.exists("/usr/bin/konsole"):
270       command = 'PATH="/usr/bin:/sbin:/bin" LD_LIBRARY_PATH="" konsole -e "%s/salome shell" &'%(kernel_appli_dir)
271     elif os.path.exists("/usr/bin/xterm"):
272       command = 'xterm -T "SALOME %s - Shell session" -e "%s/salome shell" &'%(version,kernel_appli_dir)
273     else:
274       print("Neither xterm nor gnome-terminal nor konsole is installed.")
275
276     if command is not "":
277       try:
278         subprocess.check_call(command, shell = True)
279       except Exception as e:
280         print("Error: ",e)
281
282
283 salome_pluginsmanager.AddFunction('SALOME shell session',
284                                   'Execute a SALOME shell session in an external xterm',
285                                   runSalomeShellSession)