]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/lib/dialogs.py
A little cleanup
[wxWidgets.git] / wxPython / wx / lib / dialogs.py
1 #----------------------------------------------------------------------
2 # Name: wx.lib.dialogs
3 # Purpose: ScrolledMessageDialog, MultipleChoiceDialog and
4 # function wrappers for the common dialogs by Kevin Altis.
5 #
6 # Author: Various
7 #
8 # Created: 3-January-2002
9 # RCS-ID: $Id$
10 # Copyright: (c) 2002 by Total Control Software
11 # Licence: wxWindows license
12 #----------------------------------------------------------------------
13 # 12/01/2003 - Jeff Grimmett (grimmtooth@softhome.net)
14 #
15 # o Updated for 2.5 compatability.
16 #
17 # 12/18/2003 - Jeff Grimmett (grimmtooth@softhome.net)
18 #
19 # o wxScrolledMessageDialog -> ScrolledMessageDialog
20 # o wxMultipleChoiceDialog -> MultipleChoiceDialog
21 #
22
23 import wx
24 import layoutf
25
26 #----------------------------------------------------------------------
27
28 class ScrolledMessageDialog(wx.Dialog):
29 def __init__(self, parent, msg, caption,
30 pos=wx.DefaultPosition, size=(500,300),
31 style=wx.DEFAULT_DIALOG_STYLE):
32 wx.Dialog.__init__(self, parent, -1, caption, pos, size, style)
33 x, y = pos
34 if x == -1 and y == -1:
35 self.CenterOnScreen(wx.BOTH)
36
37 text = wx.TextCtrl(self, -1, msg,
38 style=wx.TE_MULTILINE | wx.TE_READONLY)
39
40 ok = wx.Button(self, wx.ID_OK, "OK")
41 ok.SetDefault()
42 lc = layoutf.Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self,ok))
43 text.SetConstraints(lc)
44
45 lc = layoutf.Layoutf('b=b5#1;x%w50#1;w!80;h*', (self,))
46 ok.SetConstraints(lc)
47 self.SetAutoLayout(1)
48 self.Layout()
49
50
51 class MultipleChoiceDialog(wx.Dialog):
52 def __init__(self, parent, msg, title, lst, pos = wx.DefaultPosition,
53 size = (200,200), style = wx.DEFAULT_DIALOG_STYLE):
54 wx.Dialog.__init__(self, parent, -1, title, pos, size, style)
55
56 x, y = pos
57 if x == -1 and y == -1:
58 self.CenterOnScreen(wx.BOTH)
59
60 dc = wx.ClientDC(self)
61 height = 0
62 for line in msg.splitlines():
63 height = height + dc.GetTextExtent(line)[1] + 2
64
65 stat = wx.StaticText(self, -1, msg)
66 self.lbox = wx.ListBox(self, 100, wx.DefaultPosition, wx.DefaultSize,
67 lst, wx.LB_MULTIPLE)
68
69 ok = wx.Button(self, wx.ID_OK, "OK")
70 ok.SetDefault()
71 cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
72
73 dlgsizer = wx.BoxSizer(wx.VERTICAL)
74 dlgsizer.Add(stat, 0, wx.ALL, 4)
75 dlgsizer.Add(self.lbox, 1, wx.EXPAND | wx.ALL, 4)
76
77 btnsizer = wx.StdDialogButtonSizer()
78 btnsizer.AddButton(ok)
79 btnsizer.AddButton(cancel)
80 btnsizer.Realize()
81
82 dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 4)
83
84 self.SetSizer(dlgsizer)
85
86 self.lst = lst
87 self.Layout()
88
89 def GetValue(self):
90 return self.lbox.GetSelections()
91
92 def GetValueString(self):
93 sel = self.lbox.GetSelections()
94 val = []
95
96 for i in sel:
97 val.append(self.lst[i])
98
99 return tuple(val)
100
101
102 #----------------------------------------------------------------------
103 """
104 function wrappers for wxPython system dialogs
105 Author: Kevin Altis
106 Date: 2003-1-2
107 Rev: 3
108
109 This is the third refactor of the PythonCard dialog.py module
110 for inclusion in the main wxPython distribution. There are a number of
111 design decisions and subsequent code refactoring to be done, so I'm
112 releasing this just to get some feedback.
113
114 rev 3:
115 - result dictionary replaced by DialogResults class instance
116 - should message arg be replaced with msg? most wxWindows dialogs
117 seem to use the abbreviation?
118
119 rev 2:
120 - All dialog classes have been replaced by function wrappers
121 - Changed arg lists to more closely match wxWindows docs and wxPython.lib.dialogs
122 - changed 'returned' value to the actual button id the user clicked on
123 - added a returnedString value for the string version of the return value
124 - reworked colorDialog and fontDialog so you can pass in just a color or font
125 for the most common usage case
126 - probably need to use colour instead of color to match the English English
127 spelling in wxWindows (sigh)
128 - I still think we could lose the parent arg and just always use None
129 """
130
131 class DialogResults:
132 def __init__(self, returned):
133 self.returned = returned
134 self.accepted = returned in (wx.ID_OK, wx.ID_YES)
135 self.returnedString = returnedString(returned)
136
137 def __repr__(self):
138 return str(self.__dict__)
139
140 def returnedString(ret):
141 if ret == wx.ID_OK:
142 return "Ok"
143 elif ret == wx.ID_CANCEL:
144 return "Cancel"
145 elif ret == wx.ID_YES:
146 return "Yes"
147 elif ret == wx.ID_NO:
148 return "No"
149
150
151 ## findDialog was created before wxPython got a Find/Replace dialog
152 ## but it may be instructive as to how a function wrapper can
153 ## be added for your own custom dialogs
154 ## this dialog is always modal, while wxFindReplaceDialog is
155 ## modeless and so doesn't lend itself to a function wrapper
156 def findDialog(parent=None, searchText='', wholeWordsOnly=0, caseSensitive=0):
157 dlg = wx.Dialog(parent, -1, "Find", wx.DefaultPosition, (380, 120))
158
159 wx.StaticText(dlg, -1, 'Find what:', (7, 10))
160 wSearchText = wx.TextCtrl(dlg, -1, searchText, (80, 7), (195, -1))
161 wSearchText.SetValue(searchText)
162 wx.Button(dlg, wx.ID_OK, "Find Next", (285, 5), wx.DefaultSize).SetDefault()
163 wx.Button(dlg, wx.ID_CANCEL, "Cancel", (285, 35), wx.DefaultSize)
164
165 wWholeWord = wx.CheckBox(dlg, -1, 'Match whole word only',
166 (7, 35), wx.DefaultSize, wx.NO_BORDER)
167
168 if wholeWordsOnly:
169 wWholeWord.SetValue(1)
170
171 wCase = wx.CheckBox(dlg, -1, 'Match case', (7, 55), wx.DefaultSize, wx.NO_BORDER)
172
173 if caseSensitive:
174 wCase.SetValue(1)
175
176 wSearchText.SetSelection(0, len(wSearchText.GetValue()))
177 wSearchText.SetFocus()
178
179 result = DialogResults(dlg.ShowModal())
180 result.searchText = wSearchText.GetValue()
181 result.wholeWordsOnly = wWholeWord.GetValue()
182 result.caseSensitive = wCase.GetValue()
183 dlg.Destroy()
184 return result
185
186
187 def colorDialog(parent=None, colorData=None, color=None):
188 if colorData:
189 dialog = wx.ColourDialog(parent, colorData)
190 else:
191 dialog = wx.ColourDialog(parent)
192 dialog.GetColourData().SetChooseFull(1)
193
194 if color is not None:
195 dialog.GetColourData().SetColour(color)
196
197 result = DialogResults(dialog.ShowModal())
198 result.colorData = dialog.GetColourData()
199 result.color = result.colorData.GetColour().Get()
200 dialog.Destroy()
201 return result
202
203
204 ## it is easier to just duplicate the code than
205 ## try and replace color with colour in the result
206 def colourDialog(parent=None, colourData=None, colour=None):
207 if colourData:
208 dialog = wx.ColourDialog(parent, colourData)
209 else:
210 dialog = wx.ColourDialog(parent)
211 dialog.GetColourData().SetChooseFull(1)
212
213 if colour is not None:
214 dialog.GetColourData().SetColour(color)
215
216 result = DialogResults(dialog.ShowModal())
217 result.colourData = dialog.GetColourData()
218 result.colour = result.colourData.GetColour().Get()
219 dialog.Destroy()
220 return result
221
222
223 def fontDialog(parent=None, fontData=None, font=None):
224 if fontData is None:
225 fontData = wx.FontData()
226 fontData.SetColour(wx.BLACK)
227 fontData.SetInitialFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))
228
229 if font is not None:
230 fontData.SetInitialFont(font)
231
232 dialog = wx.FontDialog(parent, fontData)
233 result = DialogResults(dialog.ShowModal())
234
235 if result.accepted:
236 fontData = dialog.GetFontData()
237 result.fontData = fontData
238 result.color = fontData.GetColour().Get()
239 result.colour = result.color
240 result.font = fontData.GetChosenFont()
241 else:
242 result.color = None
243 result.colour = None
244 result.font = None
245
246 dialog.Destroy()
247 return result
248
249
250 def textEntryDialog(parent=None, message='', title='', defaultText='',
251 style=wx.OK | wx.CANCEL):
252 dialog = wx.TextEntryDialog(parent, message, title, defaultText, style)
253 result = DialogResults(dialog.ShowModal())
254 result.text = dialog.GetValue()
255 dialog.Destroy()
256 return result
257
258
259 def messageDialog(parent=None, message='', title='Message box',
260 aStyle = wx.OK | wx.CANCEL | wx.CENTRE,
261 pos=wx.DefaultPosition):
262 dialog = wx.MessageDialog(parent, message, title, aStyle, pos)
263 result = DialogResults(dialog.ShowModal())
264 dialog.Destroy()
265 return result
266
267
268 ## KEA: alerts are common, so I'm providing a class rather than
269 ## requiring the user code to set up the right icons and buttons
270 ## the with messageDialog function
271 def alertDialog(parent=None, message='', title='Alert', pos=wx.DefaultPosition):
272 return messageDialog(parent, message, title, wx.ICON_EXCLAMATION | wx.OK, pos)
273
274
275 def scrolledMessageDialog(parent=None, message='', title='', pos=wx.DefaultPosition,
276 size=(500,300)):
277
278 dialog = ScrolledMessageDialog(parent, message, title, pos, size)
279 result = DialogResults(dialog.ShowModal())
280 dialog.Destroy()
281 return result
282
283
284 def fileDialog(parent=None, title='Open', directory='', filename='', wildcard='*.*',
285 style=wx.OPEN | wx.MULTIPLE):
286
287 dialog = wx.FileDialog(parent, title, directory, filename, wildcard, style)
288 result = DialogResults(dialog.ShowModal())
289 if result.accepted:
290 result.paths = dialog.GetPaths()
291 else:
292 result.paths = None
293 dialog.Destroy()
294 return result
295
296
297 ## openFileDialog and saveFileDialog are convenience functions
298 ## they represent the most common usages of the fileDialog
299 ## with the most common style options
300 def openFileDialog(parent=None, title='Open', directory='', filename='',
301 wildcard='All Files (*.*)|*.*',
302 style=wx.OPEN | wx.MULTIPLE):
303 return fileDialog(parent, title, directory, filename, wildcard, style)
304
305
306 def saveFileDialog(parent=None, title='Save', directory='', filename='',
307 wildcard='All Files (*.*)|*.*',
308 style=wx.SAVE | wx.HIDE_READONLY | wx.OVERWRITE_PROMPT):
309 return fileDialog(parent, title, directory, filename, wildcard, style)
310
311
312 def dirDialog(parent=None, message='Choose a directory', path='', style=0,
313 pos=wx.DefaultPosition, size=wx.DefaultSize):
314
315 dialog = wx.DirDialog(parent, message, path, style, pos, size)
316 result = DialogResults(dialog.ShowModal())
317 if result.accepted:
318 result.path = dialog.GetPath()
319 else:
320 result.path = None
321 dialog.Destroy()
322 return result
323
324 directoryDialog = dirDialog
325
326
327 def singleChoiceDialog(parent=None, message='', title='', lst=[],
328 style=wx.OK | wx.CANCEL | wx.CENTRE):
329 dialog = wx.SingleChoiceDialog(parent, message, title, list(lst), style | wx.DEFAULT_DIALOG_STYLE)
330 result = DialogResults(dialog.ShowModal())
331 result.selection = dialog.GetStringSelection()
332 dialog.Destroy()
333 return result
334
335
336 def multipleChoiceDialog(parent=None, message='', title='', lst=[], pos=wx.DefaultPosition,
337 size=(200,200)):
338
339 dialog = MultipleChoiceDialog(parent, message, title, lst, pos, size)
340 result = DialogResults(dialog.ShowModal())
341 result.selection = dialog.GetValueString()
342 dialog.Destroy()
343 return result
344
345
346 if __name__ == '__main__':
347 #import os
348 #print os.getpid()
349
350 class MyApp(wx.App):
351
352 def OnInit(self):
353 self.frame = frame = wx.Frame(None, -1, "Dialogs", size=(400, 240))
354 panel = wx.Panel(frame, -1)
355 self.panel = panel
356
357
358 dialogNames = [
359 'alertDialog',
360 'colorDialog',
361 'directoryDialog',
362 'fileDialog',
363 'findDialog',
364 'fontDialog',
365 'messageDialog',
366 'multipleChoiceDialog',
367 'openFileDialog',
368 'saveFileDialog',
369 'scrolledMessageDialog',
370 'singleChoiceDialog',
371 'textEntryDialog',
372 ]
373
374 self.nameList = wx.ListBox(panel, -1,
375 size=(130, 180),
376 choices=dialogNames,
377 style=wx.LB_SINGLE)
378 self.Bind(wx.EVT_LISTBOX, self.OnNameListSelected, self.nameList)
379
380 tstyle = wx.TE_RICH2 | wx.TE_PROCESS_TAB | wx.TE_MULTILINE
381 self.text1 = wx.TextCtrl(panel, -1, size=(200, 180), style=tstyle)
382
383 sizer = wx.BoxSizer(wx.HORIZONTAL)
384 sizer.Add(self.nameList, 0, wx.EXPAND|wx.ALL, 20)
385 sizer.Add(self.text1, 1, wx.EXPAND|wx.ALL, 20)
386
387 panel.SetSizer(sizer)
388
389 self.SetTopWindow(frame)
390 frame.Show(1)
391 return 1
392
393
394 def OnNameListSelected(self, evt):
395 import pprint
396 sel = evt.GetString()
397 result = None
398 if sel == 'alertDialog':
399 result = alertDialog(message='Danger Will Robinson')
400 elif sel == 'colorDialog':
401 result = colorDialog()
402 elif sel == 'directoryDialog':
403 result = directoryDialog()
404 elif sel == 'fileDialog':
405 wildcard = "JPG files (*.jpg;*.jpeg)|*.jpeg;*.JPG;*.JPEG;*.jpg|GIF files (*.gif)|*.GIF;*.gif|All Files (*.*)|*.*"
406 result = fileDialog(None, 'Open', '', '', wildcard)
407 elif sel == 'findDialog':
408 result = findDialog()
409 elif sel == 'fontDialog':
410 result = fontDialog()
411 elif sel == 'messageDialog':
412 result = messageDialog(None, 'Hello from Python and wxPython!',
413 'A Message Box', wx.OK | wx.ICON_INFORMATION)
414 #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION)
415 #result = messageDialog(None, 'message', 'title')
416 elif sel == 'multipleChoiceDialog':
417 result = multipleChoiceDialog(None, "message", "title", ['one', 'two', 'three'])
418 elif sel == 'openFileDialog':
419 result = openFileDialog()
420 elif sel == 'saveFileDialog':
421 result = saveFileDialog()
422 elif sel == 'scrolledMessageDialog':
423 msg = "Can't find the file dialog.py"
424 try:
425 # read this source file and then display it
426 import sys
427 filename = sys.argv[-1]
428 fp = open(filename)
429 message = fp.read()
430 fp.close()
431 except:
432 pass
433 result = scrolledMessageDialog(None, message, filename)
434 elif sel == 'singleChoiceDialog':
435 result = singleChoiceDialog(None, "message", "title", ['one', 'two', 'three'])
436 elif sel == 'textEntryDialog':
437 result = textEntryDialog(None, "message", "title", "text")
438
439 if result:
440 #self.text1.SetValue(pprint.pformat(result.__dict__))
441 self.text1.SetValue(str(result))
442
443 app = MyApp(True)
444 app.MainLoop()
445
446