]> SALOME platform Git repositories - samples/pylight.git/blob - src/PYLIGHTGUI/PYLIGHTGUI.py
Salome HOME
Deleted deprecated parameter
[samples/pylight.git] / src / PYLIGHTGUI / PYLIGHTGUI.py
1 # Copyright (C) 2009-2016  OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 #  Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com)
21 #  Date   : 13/04/2009
22 #
23 import traceback
24 from SalomePyQt import *
25 import PYLIGHT_DataModel
26 from qtsalome import *
27 import libSALOME_Swig
28
29 import os
30 import libSalomePy
31 import vtk
32
33 # Get SALOME PyQt interface
34 sgPyQt = SalomePyQt()
35 # Get SALOME Swig interface
36 sg = libSALOME_Swig.SALOMEGUI_Swig()
37
38 ################################################
39 # GUI context class
40 # Used to store actions, menus, toolbars, etc...
41 ################################################
42
43 # data model
44 __data_model__ = None
45
46 class GUIcontext:
47
48     # constructor
49     def __init__( self ):
50         global __data_model__
51         # Load File action
52         sgPyQt.createAction(dict_actions["loadfile"], "Load text File", "Load text file")
53         # Save File action
54         sgPyQt.createAction(dict_actions["savefile"], "Save text File", "Save text file")
55         # Insert Line action
56         sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new text line")
57         # Insert new line action
58         sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new line")
59         # Edit selected line action
60         sgPyQt.createAction(dict_actions["editLine"], "Edit Line", "Edit selected line")
61         # Remove selected line action
62         sgPyQt.createAction(dict_actions["removeLine"], "Remove Lines", "Remove selected lines")
63         # Clear paragraph
64         sgPyQt.createAction(dict_actions["clearParagraph"], "Clear Paragraph", "Clear selected paragraph")
65         # Clear all paragraphs
66         sgPyQt.createAction(dict_actions["clearAll"], "Clear All", "Clear all paragraphs")
67         # Display line
68         sgPyQt.createAction(dict_actions["displayLine"], "Display Line", "Display selected line")
69         # Erase line
70         sgPyQt.createAction(dict_actions["eraseLine"], "Erase Line", "Erase selected line")
71         # Separator
72         separator = sgPyQt.createSeparator()
73
74         # Get Menu 'File'
75         menuFile = sgPyQt.createMenu( "File", -1, -1 )
76         # Add actions in the menu 'File'
77         sgPyQt.createMenu( separator,                menuFile, -1, 10)
78         sgPyQt.createMenu( dict_actions["loadfile"], menuFile, 10 );
79         sgPyQt.createMenu( dict_actions["savefile"], menuFile, 10 );
80         sgPyQt.createMenu( separator,                menuFile, -1, 10)
81         # Create 'PyLight' menu 
82         menuPyLight = sgPyQt.createMenu( "PyLight", -1, -1, 50)
83         # Add actions in the menu 'PyLight'
84         sgPyQt.createMenu( dict_actions["insertLine"],  menuPyLight, 10 );
85         sgPyQt.createMenu( dict_actions["editLine"],    menuPyLight, 10 );
86         sgPyQt.createMenu( dict_actions["removeLine"],  menuPyLight, 10 );
87         sgPyQt.createMenu( separator,                   menuPyLight, -1, 10);
88         sgPyQt.createMenu( dict_actions["clearAll"],    menuPyLight, 10 );
89         sgPyQt.createMenu( separator,                   menuPyLight, -1, 10);
90         sgPyQt.createMenu( dict_actions["displayLine"], menuPyLight, 10 );
91         sgPyQt.createMenu( dict_actions["eraseLine"],   menuPyLight, 10 );
92
93         # Create DataModel
94         if __data_model__ is None:
95             __data_model__ = PYLIGHT_DataModel.PYLIGHT_DataModel()
96             pass
97             
98         pass # def __init__( self )
99
100     pass # class GUIcontext
101
102 ################################################
103 # Global variables and functions
104 ################################################
105
106 # verbosity level
107 __verbose__ = None
108
109 ###
110 # Get verbose level
111 ###
112 def verbose():
113     global __verbose__
114     if __verbose__ is None:
115         try:
116             __verbose__ = int( os.getenv( 'SALOME_VERBOSE', 0 ) )
117         except:
118             __verbose__ = 0
119             pass
120         pass
121     return __verbose__
122
123 ################################################
124
125 # Create actions and menus
126 def initialize():
127     if verbose(): print "PYLIGHTGUI::initialize()"
128     return
129
130 # called when module is activated
131 # returns True if activating is successfull and False otherwise
132 def activate():
133     if verbose() : print "PYLIGHTGUI.activate()"
134     GUIcontext()
135     return True
136
137 # called when module is deactivated
138 def deactivate():
139     if verbose() : print "PYLIGHTGUI.deactivate()"
140     pass
141
142 # Process GUI action
143 def OnGUIEvent(commandID):
144     if verbose() : print "PYLIGHTGUI::OnGUIEvent : commandID = %d" % commandID
145     if dict_command.has_key( commandID ):
146         try:
147             dict_command[commandID]()
148         except:
149             traceback.print_exc()
150     else:
151        if verbose() : print "The command is not implemented: %d" % commandID
152     pass
153
154 # Customize popup menu
155 def createPopupMenu(popup, context):
156     global __data_model__
157     if verbose() : print "PYLIGHTGUI.createPopupMenu(): context = %s" % context
158
159     if context != 'ObjectBrowser':
160         return
161     
162     selcount = sg.SelectedCount()
163     if selcount == 1:
164         entry = sg.getSelected( 0 )
165         obj = __data_model__.getObject(entry)
166         if obj is not None:
167             if obj.getText() != "\n":
168                 # Line is selected
169                 popup.addAction(sgPyQt.action(dict_actions["editLine"]))
170                 popup.addAction(sgPyQt.action(dict_actions["removeLine"]))
171                 popup.addSeparator()
172                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
173                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
174                 popup.addAction(sgPyQt.action(dict_actions["eraseLine"]))
175                 pass
176             else:
177                 # Paragraph is selected
178                 popup.addAction(sgPyQt.action(dict_actions["insertLine"]))
179                 popup.addAction(sgPyQt.action(dict_actions["clearParagraph"]))
180                 pass
181             pass
182         else:
183             onlyLines = True
184             pass
185         pass # if selcount == 1
186     pass
187
188 # For saving data in the study
189 def saveFiles(prefix):
190     global __data_model__
191     if verbose(): print "PYLIGHTGUI::saveFile()"
192     postfix = "PYLIGHT.txt"
193     filename = prefix+postfix
194     __data_model__.saveFile(filename)
195     return postfix
196
197 # For restore data from the study
198 def openFiles(filelist):
199     global __data_model__
200     if verbose(): print "PYLIGHTGUI::openFile()"
201     filename =  filelist[0]
202     filename.append(filelist[1])
203     __data_model__.loadFile(filename)
204     return True
205
206 # Loading a text file
207 def loadfile():
208     global __data_model__
209     aFilter = "Text files (*.txt)"
210     filename = QFileDialog.getOpenFileName(sgPyQt.getDesktop(), "Open text file", "", aFilter, "Choose a text file to open")
211
212     if isinstance(filename,tuple) and len(filename) >=2:
213        filename = filename[0]
214
215     filename = unicode(filename)
216
217     if len(filename) == 0:
218         return
219     
220     if os.access(str(filename),os.R_OK):
221         __data_model__.loadFile(filename)
222     else:
223         QMessageBox.warning(sgPyQt.getDesktop(),
224                             "Error!",
225                             "Can not read file:\n%s"%(filename))
226         pass
227     sg.updateObjBrowser()
228     pass
229
230 # Saving a text file
231 def savefile():
232     global __data_model__
233     aFilter = "Text files (*.txt)"
234     filename = QFileDialog.getSaveFileName(sgPyQt.getDesktop(),"Save text file", "", aFilter, "Choose a text file to save")
235
236     if isinstance(filename,tuple) and len(filename) >=2:
237         filename = filename[0]
238
239     filename = unicode(filename)
240
241     if filename.endswith(".txt") == 0:
242         filename+=".txt"
243         pass
244
245     fn = filename
246     # Get directory name and check access
247     if os.access(str(fn[:fn.rindex(os.path.sep)]), os.W_OK):
248         __data_model__.saveFile(filename)
249     else:
250         QMessageBox.warning(sgPyQt.getDesktop(),
251                             "Error!",
252                             "Can not save file:\n%s"%(filename))
253         pass
254     pass
255
256 def insertLine():
257     '''
258     Insert new line in the selected paragraph.
259     '''
260     global __data_model__
261     #Get result
262     res = QInputDialog.getText(sgPyQt.getDesktop(),
263                                "Add new line",
264                                "Enter the text",
265                                QLineEdit.Normal)
266     if not res[1]: ### user click cancel button
267         return
268     
269     text = res[0]
270     # Nb selected objects
271     selcount = sg.SelectedCount()
272     # Nb object in the Data Model
273     paragrCount = len(__data_model__.getParagraphs())
274
275     # Create first paragraph
276     if paragrCount == 0:
277         __data_model__.createObject()
278         # If line not empty create first line
279         if text != "\n":
280             __data_model__.createObject(text,__data_model__.getParagraphs()[0])
281         sg.updateObjBrowser()
282         return
283     # Create paragraph
284     if text == "\n":
285         __data_model__.createObject()
286         sg.updateObjBrowser()
287         return
288     else:
289         if selcount == 0:
290             QMessageBox.warning(sgPyQt.getDesktop(),
291                                 'Error!',
292                                 'Please, select paragraph!')
293             return
294         if selcount == 1:
295             entry = sg.getSelected( 0 )
296             obj = __data_model__.getObject(entry)
297             if obj is not None:
298                 # Create line
299                 if(obj.getText() == "\n"):
300                     __data_model__.createObject(text,entry)
301                     sg.updateObjBrowser();
302                     return
303                 else:
304                     QMessageBox.warning(sgPyQt.getDesktop(),
305                                         'Error!',
306                                         'Please, select paragraph!')
307             elif selcount > 1:
308                 QMessageBox.warning(sgPyQt.getDesktop(),
309                                     'Error!',
310                                     'Please, select only one paragraph!')
311     pass
312         
313         
314 # Edit selected line
315 def editLine():
316     global __data_model__
317     if sg.SelectedCount() == 1:
318         entry = sg.getSelected( 0 )
319         obj = __data_model__.getObject(entry)
320         if(obj.getText() != "\n"):
321             #Get text line
322             res = QInputDialog.getText(sgPyQt.getDesktop(),
323                                        "Edit line",
324                                        "Enter the text",
325                                        QLineEdit.Normal,
326                                        PYLIGHT_DataModel.processText(obj.getText()))
327             if not res[1]: ### user click cancel button
328                 return
329             text = res[0]
330             
331             obj.setText(text)
332         else:
333             QMessageBox.information(sgPyQt.getDesktop(),
334                                     'Info',
335                                     'Please, select line!') 
336     else:
337         QMessageBox.information(sgPyQt.getDesktop(),
338                                 'Info',
339                                 'Please, select one line!')
340     sg.updateObjBrowser();
341     pass
342
343 # Remove selected lines
344 def removeLine():
345     global __data_model__
346     selcount = sg.SelectedCount()
347     onlyLines = True
348     lines = []
349     while selcount != 0:
350         entry = sg.getSelected( selcount - 1)
351         #Check what only lines selected
352         if __data_model__.getObject(entry).getText() == "\n":
353             onlyLines = False
354             break
355         lines.append(entry)
356         selcount = selcount-1
357         pass
358     if not onlyLines:
359         return
360     else:
361         renderer=libSalomePy.getRenderer()
362         for ln in lines:
363             actor = getActor(ln)
364             if actor is not None:
365                 renderer.RemoveActor(actor)
366                 pass
367             pass
368         __data_model__.removeObjects(lines)
369         sg.updateObjBrowser()
370         pass
371     pass
372
373 # Remove all lines from all paragraphs
374 def clearAll():
375     global __data_model__
376     paragraphs = __data_model__.getParagraphs()
377     for paragr in paragraphs:
378         lines = sgPyQt.getChildren(paragr)
379         __data_model__.removeObjects(lines)
380         renderer=libSalomePy.getRenderer()
381         for l in lines:
382             actor = getActor(l)
383             if actor is not None:
384                 renderer.RemoveActor(actor)
385                 pass
386             pass
387     sg.updateObjBrowser()
388     pass
389
390 # Display the selected line
391 def displayLine():
392     global __data_model__
393     if sg.SelectedCount() != 1:
394         return
395     entry = sg.getSelected(0)
396     text = __data_model__.getObject(entry).getText()
397     if text == "\n":
398         return
399     renderer=libSalomePy.getRenderer()
400     actor = getActor(entry)
401     if actor is None:
402         actor = vtk.vtkTextActor()
403         dict_actors[entry] = actor
404         pass
405     center = renderer.GetCenter()
406     actor.SetInput(str(text))
407     actor.SetPosition(center[0],center[1])
408     txtPr = vtk.vtkTextProperty()
409     txtPr.SetFontSize(30)
410     actor.SetTextProperty(txtPr)
411     for act in  dict_actors.values():
412         renderer.RemoveActor(act)
413     renderer.AddActor(actor)
414     pass
415
416 # Clear remove all lines under selected paragraph
417 def clearParagraph():
418     global __data_model__
419     lines = sgPyQt.getChildren(sg.getSelected(0))
420     __data_model__.removeObjects(lines)
421     sg.updateObjBrowser()
422     pass
423
424 # Erase the selected line
425 def eraseLine():
426     global __data_model__
427     if sg.SelectedCount() != 1:
428         return
429     entry = sg.getSelected(0)
430     text = __data_model__.getObject(entry).getText()
431     if text == "\n":
432         return
433     renderer=libSalomePy.getRenderer()
434     actor = getActor(entry)
435     if actor is not None:
436         renderer.RemoveActor(actor)
437         pass
438     pass
439
440 # Return vtkActor by entry
441 def getActor(entry):
442     entry = str(entry)
443     if dict_actors.has_key(entry):
444         return dict_actors[entry]
445     return None
446
447 # Define commands
448 dict_command = {
449     951 : loadfile,
450     952 : savefile,
451     961 : insertLine,
452     962 : editLine,
453     963 : removeLine,
454     964 : clearAll,
455     971 : displayLine,
456     972 : eraseLine,
457     973 : clearParagraph,
458     }
459
460 # Define actions
461 dict_actions = {
462     "loadfile"   :    951,
463     "savefile"   :    952,
464     "insertLine" :    961,
465     "editLine"   :    962,
466     "removeLine" :    963,
467     "clearAll"   :    964,
468     "displayLine":    971,
469     "eraseLine"  :    972,
470     "clearParagraph": 973,
471     }
472
473 # Define Actors
474 dict_actors = {}