Salome HOME
29d5024f110bbba5ffa83c8b90f52cddbaac2659
[samples/pylight.git] / src / PYLIGHTGUI / PYLIGHTGUI.py
1 #  Copyright (C) 2007-2008  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.
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 #  Author : Roman NIKOLAEV Open CASCADE S.A.S. (roman.nikolaev@opencascade.com)
23 #  Date   : 13/04/2009
24
25 import traceback
26 from SalomePyQt import *
27 import PYLIGHT_DataModel
28 from PyQt4.QtGui import *
29 from PyQt4.QtCore import *
30 import libSALOME_Swig
31
32 import os
33 import libSalomePy
34 import vtk
35
36 # Get SALOME PyQt interface
37 sgPyQt=SalomePyQt()
38 # Get SALOME Swig interface
39 sg = libSALOME_Swig.SALOMEGUI_Swig()
40
41 # Create DataModel
42 DM = PYLIGHT_DataModel.PYLIGHT_DataModel()
43
44 # Create actions and menus
45 def initialize():
46     
47     print "PYLIGHTGUI::initialize()"
48     # Load File action
49     sgPyQt.createAction(dict_actions["loadfile"], "Load text File", "Load text file")
50     # Save File action
51     sgPyQt.createAction(dict_actions["savefile"], "Save text File", "Save text file")
52     # Insert Line action
53     sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new text line")
54     # Separator
55     separator = sgPyQt.createSeparator()
56     # Get Menu 'File'
57     menuFile = sgPyQt.createMenu( "File", -1, -1 )
58     # Add actions in the menu 'File'
59     sgPyQt.createMenu( separator ,menuFile, -1, 10)
60     sgPyQt.createMenu( dict_actions["loadfile"],  menuFile, 10 );
61     sgPyQt.createMenu( dict_actions["savefile"],  menuFile, 10 );
62     sgPyQt.createMenu( separator ,menuFile, -1, 10)
63     
64     # Insert new line action
65     sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new line")
66     # Edit selected line action
67     sgPyQt.createAction(dict_actions["editLine"], "Edit Line", "Edit selected line")
68     # Remove selected line action
69     sgPyQt.createAction(dict_actions["removeLine"], "Remove Lines", "Remove selected lines")
70     # Clear all paragraphs
71     sgPyQt.createAction(dict_actions["clearAll"], "Clear All", "Clear all paragraphs")
72     # Display line
73     sgPyQt.createAction(dict_actions["displayLine"], "Display Line", "Display selected line")
74     # Erase line
75     sgPyQt.createAction(dict_actions["eraseLine"], "Erase Line", "Erase selected line")
76     
77     # Create 'PyLight' menu 
78     menuPyLight = sgPyQt.createMenu( "PyLight",-1,-1,50)
79     # Add actions in the menu 'PyLight'
80     sgPyQt.createMenu( dict_actions["insertLine"],  menuPyLight, 10 );
81     sgPyQt.createMenu( dict_actions["editLine"],  menuPyLight, 10 );
82     sgPyQt.createMenu( dict_actions["removeLine"],  menuPyLight, 10 );
83     sgPyQt.createMenu( separator, menuPyLight, -1, 10);
84     sgPyQt.createMenu( dict_actions["clearAll"],  menuPyLight, 10 );
85     sgPyQt.createMenu( separator, menuPyLight, -1, 10);
86     sgPyQt.createMenu( dict_actions["displayLine"],  menuPyLight, 10 );
87     sgPyQt.createMenu( dict_actions["eraseLine"],  menuPyLight, 10 );
88     
89     return
90
91
92 # Process GUI action
93 def OnGUIEvent(commandID):
94     print "PYLIGHTGUI::OnGUIEvent : commandID =",commandID
95     if dict_command.has_key( commandID ):
96         try:
97             dict_command[commandID]()
98         except:
99             traceback.print_exc()
100     else:
101        print "The command is not implemented: ",commandID
102     pass
103
104 # Customize popup menu
105 def createPopupMenu(popup, context):
106
107
108     
109     if context != 'ObjectBrowser':
110         return
111     
112     selcount = sg.SelectedCount()
113     if selcount == 1:
114         entry = sg.getSelected( 0 )
115         obj = DM.getObject(entry)
116         if obj is not None:
117             if obj.getText() != "\n":
118                 #Line is selected
119                 popup.addAction(sgPyQt.action(dict_actions["editLine"]))
120                 popup.addAction(sgPyQt.action(dict_actions["removeLine"]))
121                 popup.addSeparator()
122                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
123                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
124                 popup.addAction(sgPyQt.action(dict_actions["eraseLine"]))
125
126                                                 
127             else:
128                 #Paragraph is selected
129                 popup.addAction(sgPyQt.action(dict_actions["insertLine"]))
130                 popup.addAction(sgPyQt.action(dict_actions["clearParagraph"]))
131         else:
132             onlyLines = True            
133     pass
134
135 # For saving data in the study
136 def saveFiles(prefix):
137     print "PYLIGHTGUI::saveFile()"
138     postfix = "PYLIGHT.txt"
139     filename = prefix+postfix
140     DM.saveFile(QString(filename))
141     return postfix
142
143 # For restore data from the study
144 def openFiles(filelist):
145     print "PYLIGHTGUI::openFile()"
146     filename =  filelist[0]
147     filename.append(filelist[1])
148     DM.loadFile(filename)
149     return True
150
151 # Loading a text file
152 def loadfile():
153     aFilter = "Text files (*.txt)"
154     filename = QFileDialog.getOpenFileName(sgPyQt.getDesktop(), "Open text file", "", aFilter, "Choose a text file to open")
155     if filename.isEmpty():
156         return
157     
158     if os.access(str(filename),os.R_OK):
159         DM.loadFile(filename)
160     else:
161         QMessageBox.warning(sgPyQt.getDesktop(),
162                             "Error!",
163                             QString("Can not read file:\n%1").arg(filename))
164         pass
165     sg.updateObjBrowser(True)
166     pass
167
168 # Saving a text file
169 def savefile():
170     aFilter = "Text files (*.txt)"
171     filename = QFileDialog.getSaveFileName(sgPyQt.getDesktop(),"Save text file", "", aFilter, "Choose a text file to save")
172     if filename.contains(".txt") == 0:
173         filename.append(".txt")
174         pass
175     fn = filename
176     print filename
177     # Get directory name and check access
178     if os.access(str(fn.left(fn.lastIndexOf("/"))), os.W_OK):
179         DM.saveFile(filename)
180     else:
181         QMessageBox.warning(sgPyQt.getDesktop(),
182                             "Error!",
183                             QString("Can not save file:\n%1").arg(filename))
184         pass
185     pass
186
187 def insertLine():
188     '''
189     Insert new line in the selected paragraph.
190     '''
191     #Get result
192     res = QInputDialog.getText(sgPyQt.getDesktop(),
193                                "Add new line",
194                                "Enter the text",
195                                QLineEdit.Normal)
196     if not res[1]: ### user click cancel button
197         return
198     
199     text = res[0]
200     # Nb selected objects
201     selcount = sg.SelectedCount()
202     # Nb object in the Data Model
203     paragrCount = len(DM.getParagraphs())
204
205     # Create first paragraph
206     if paragrCount == 0:
207         DM.createObject()
208         # If line not empty create first line
209         if text != "\n":
210             DM.createObject(text,DM.getParagraphs()[0])
211         sg.updateObjBrowser(True)
212         return
213     # Create paragraph
214     if text == "\n":
215         DM.createObject()
216         sg.updateObjBrowser(True)
217         return
218     else:
219         if selcount == 0:
220             QMessageBox.warning(sgPyQt.getDesktop(),
221                                 'Error!',
222                                 'Please, select paragraph!')
223             return
224         if selcount == 1:
225             entry = sg.getSelected( 0 )
226             obj = DM.getObject(entry)
227             if obj is not None:
228                 # Create line
229                 if(obj.getText() == "\n"):
230                     DM.createObject(text,entry)
231                     sg.updateObjBrowser(True);
232                     return
233                 else:
234                     QMessageBox.warning(sgPyQt.getDesktop(),
235                                         'Error!',
236                                         'Please, select paragraph!')
237             elif selcount > 1:
238                 QMessageBox.warning(sgPyQt.getDesktop(),
239                                     'Error!',
240                                     'Please, select only one paragraph!')
241     pass
242         
243         
244 # Edit selected line
245 def editLine():
246     if sg.SelectedCount() == 1:
247         entry = sg.getSelected( 0 )
248         obj = DM.getObject(entry)
249         if(obj.getText() != "\n"):
250             #Get text line
251             res = QInputDialog.getText(sgPyQt.getDesktop(),
252                                        "Edit line",
253                                        "Enter the text",
254                                        QLineEdit.Normal,
255                                        PYLIGHT_DataModel.processText(obj.getText()))
256             if not res[1]: ### user click cancel button
257                 return
258             text = res[0]
259             
260             obj.setText(text)
261         else:
262             QMessageBox.information(sgPyQt.getDesktop(),
263                                     'Info',
264                                     'Please, select line!') 
265     else:
266         QMessageBox.information(sgPyQt.getDesktop(),
267                                 'Info',
268                                 'Please, select one line!')
269     sg.updateObjBrowser(True);
270     pass
271
272 # Remove selected lines
273 def removeLine():
274     selcount = sg.SelectedCount()
275     onlyLines = True
276     lines = []
277     while selcount != 0:
278         entry = sg.getSelected( selcount - 1)
279         #Check what only lines selected
280         if DM.getObject(entry).getText() == "\n":
281             onlyLines = False
282             break
283         lines.append(entry)
284         selcount = selcount-1
285         pass
286     if not onlyLines:
287         return
288     else:
289         renderer=libSalomePy.getRenderer()
290         for ln in lines:
291             actor = getActor(ln)
292             if actor is not None:
293                 renderer.RemoveActor(actor)
294                 pass
295             pass
296         DM.removeObjects(lines)
297         sg.updateObjBrowser(True)
298         pass
299     pass
300
301 # Remove all lines from all paragraphs
302 def clearAll():
303     paragraphs = DM.getParagraphs()
304     for paragr in paragraphs:
305         lines = sgPyQt.getChildren(paragr)
306         DM.removeObjects(lines)
307         renderer=libSalomePy.getRenderer()
308         for l in lines:
309             actor = getActor(l)
310             if actor is not None:
311                 renderer.RemoveActor(actor)
312                 pass
313             pass
314     sg.updateObjBrowser(True)
315     pass
316
317 # Display the selected line
318 def displayLine():
319     if sg.SelectedCount() != 1:
320         return
321     entry = sg.getSelected(0)
322     text = DM.getObject(entry).getText()
323     if text == "\n":
324         return
325     renderer=libSalomePy.getRenderer()
326     actor = getActor(entry)
327     if actor is None:
328         actor = vtk.vtkTextActor()
329         dict_actors[entry] = actor
330         pass
331     center = renderer.GetCenter()
332     actor.SetInput(str(text))
333     actor.SetPosition(center[0],center[1])
334     txtPr = vtk.vtkTextProperty()
335     txtPr.SetFontSize(30)
336     actor.SetTextProperty(txtPr)
337     for act in  dict_actors.values():
338         renderer.RemoveActor(act)
339     renderer.AddActor(actor)
340     pass
341
342 # Clear remove all lines under selected paragraph
343 def clearParagraph():
344     lines = sgPyQt.getChildren(sg.getSelected(0))
345     DM.removeObjects(lines)
346     sg.updateObjBrowser(True)
347     pass
348
349 # Erase the selected line
350 def eraseLine():
351     if sg.SelectedCount() != 1:
352         return
353     entry = sg.getSelected(0)
354     text = DM.getObject(entry).getText()
355     if text == "\n":
356         return
357     renderer=libSalomePy.getRenderer()
358     actor = getActor(entry)
359     if actor is not None:
360         renderer.RemoveActor(actor)
361         pass
362     pass
363
364 # Return vtkActor by entry
365 def getActor(entry):
366     if isinstance(entry,QString):
367         entry = entry.toLatin1().data()
368     if dict_actors.has_key(entry):
369         return dict_actors[entry]
370     return None
371
372 # Define commands
373 dict_command = {
374     951 : loadfile,
375     952 : savefile,
376     961 : insertLine,
377     962 : editLine,
378     963 : removeLine,
379     964 : clearAll,
380     971 : displayLine,
381     972 : eraseLine,
382     973 : clearParagraph,
383     }
384
385 # Define actions
386 dict_actions = {
387     "loadfile"   :    951,
388     "savefile"   :    952,
389     "insertLine" :    961,
390     "editLine"   :    962,
391     "removeLine" :    963,
392     "clearAll"   :    964,
393     "displayLine":    971,
394     "eraseLine"  :    972,
395     "clearParagraph": 973,
396     }
397
398 # Define Actors
399 dict_actors = {}