blob: 8d33a097bd5f6885e44734fe398b5b14c45362e8 [file] [log] [blame]
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +00001"""Easy to use dialogs.
2
3Message(msg) -- display a message and an OK button.
4AskString(prompt, default) -- ask for a string, display OK and Cancel buttons.
Just van Rossumcdcc0f01999-02-15 00:04:05 +00005AskPassword(prompt, default) -- like AskString(), but shows text as bullets.
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +00006AskYesNoCancel(question, default) -- display a question and Yes, No and Cancel buttons.
Jack Jansen3a87f5b1995-11-14 10:13:49 +00007bar = Progress(label, maxvalue) -- Display a progress bar
8bar.set(value) -- Set value
Jack Jansen1d63d8c1997-05-12 15:44:14 +00009bar.inc( *amount ) -- increment value by amount (default=1)
10bar.label( *newlabel ) -- get or set text label.
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000011
12More documentation in each function.
Jack Jansencc386881999-12-12 22:57:51 +000013This module uses DLOG resources 260 and on.
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000014Based upon STDWIN dialogs with the same names and functions.
15"""
16
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000017from Carbon.Dlg import GetNewDialog, SetDialogItemText, GetDialogItemText, ModalDialog
18from Carbon import Qd
19from Carbon import QuickDraw
20from Carbon import Dialogs
21from Carbon import Windows
22from Carbon import Dlg,Win,Evt,Events # sdm7g
23from Carbon import Ctl
24from Carbon import Controls
25from Carbon import Menu
Jack Jansenf0d12da2003-01-17 16:04:39 +000026import Nav
Jack Jansena5a49811998-07-01 15:47:44 +000027import MacOS
28import string
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000029from Carbon.ControlAccessor import * # Also import Controls constants
Jack Jansenf0d12da2003-01-17 16:04:39 +000030import Carbon.File
Jack Jansendde800e2002-11-07 23:07:05 +000031import macresource
Jack Jansene58962a2003-01-17 23:13:03 +000032import os
Jack Jansendde800e2002-11-07 23:07:05 +000033
34_initialized = 0
35
36def _initialize():
37 global _initialized
38 if _initialized: return
39 macresource.need("DLOG", 260, "dialogs.rsrc", __name__)
40
Jack Jansena5a49811998-07-01 15:47:44 +000041
42def cr2lf(text):
43 if '\r' in text:
44 text = string.join(string.split(text, '\r'), '\n')
45 return text
46
47def lf2cr(text):
48 if '\n' in text:
49 text = string.join(string.split(text, '\n'), '\r')
Jack Jansend5af7bd1998-09-28 10:37:08 +000050 if len(text) > 253:
51 text = text[:253] + '\311'
Jack Jansena5a49811998-07-01 15:47:44 +000052 return text
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000053
Jack Jansencc386881999-12-12 22:57:51 +000054def Message(msg, id=260, ok=None):
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000055 """Display a MESSAGE string.
56
57 Return when the user clicks the OK button or presses Return.
58
59 The MESSAGE string can be at most 255 characters long.
60 """
Jack Jansendde800e2002-11-07 23:07:05 +000061 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000062 d = GetNewDialog(id, -1)
63 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +000064 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000065 return
Jack Jansencc386881999-12-12 22:57:51 +000066 h = d.GetDialogItemAsControl(2)
Jack Jansena5a49811998-07-01 15:47:44 +000067 SetDialogItemText(h, lf2cr(msg))
Jack Jansen208c15a1999-02-16 16:06:39 +000068 if ok != None:
Jack Jansencc386881999-12-12 22:57:51 +000069 h = d.GetDialogItemAsControl(1)
70 h.SetControlTitle(ok)
Jack Jansen3a87f5b1995-11-14 10:13:49 +000071 d.SetDialogDefaultItem(1)
Jack Jansenfca049d2000-01-18 13:36:02 +000072 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +000073 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000074 while 1:
75 n = ModalDialog(None)
76 if n == 1:
77 return
78
79
Jack Jansencc386881999-12-12 22:57:51 +000080def AskString(prompt, default = "", id=261, ok=None, cancel=None):
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000081 """Display a PROMPT string and a text entry field with a DEFAULT string.
82
83 Return the contents of the text entry field when the user clicks the
84 OK button or presses Return.
85 Return None when the user clicks the Cancel button.
86
87 If omitted, DEFAULT is empty.
88
89 The PROMPT and DEFAULT strings, as well as the return value,
90 can be at most 255 characters long.
91 """
92
Jack Jansendde800e2002-11-07 23:07:05 +000093 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000094 d = GetNewDialog(id, -1)
95 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +000096 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000097 return
Jack Jansencc386881999-12-12 22:57:51 +000098 h = d.GetDialogItemAsControl(3)
Jack Jansena5a49811998-07-01 15:47:44 +000099 SetDialogItemText(h, lf2cr(prompt))
Jack Jansencc386881999-12-12 22:57:51 +0000100 h = d.GetDialogItemAsControl(4)
Jack Jansena5a49811998-07-01 15:47:44 +0000101 SetDialogItemText(h, lf2cr(default))
Jack Jansend61f92b1999-01-22 13:14:06 +0000102 d.SelectDialogItemText(4, 0, 999)
Jack Jansene4b40381995-07-17 13:25:15 +0000103# d.SetDialogItem(4, 0, 255)
Jack Jansen208c15a1999-02-16 16:06:39 +0000104 if ok != None:
Jack Jansencc386881999-12-12 22:57:51 +0000105 h = d.GetDialogItemAsControl(1)
106 h.SetControlTitle(ok)
Jack Jansen208c15a1999-02-16 16:06:39 +0000107 if cancel != None:
Jack Jansencc386881999-12-12 22:57:51 +0000108 h = d.GetDialogItemAsControl(2)
109 h.SetControlTitle(cancel)
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000110 d.SetDialogDefaultItem(1)
111 d.SetDialogCancelItem(2)
Jack Jansenfca049d2000-01-18 13:36:02 +0000112 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000113 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000114 while 1:
115 n = ModalDialog(None)
116 if n == 1:
Jack Jansencc386881999-12-12 22:57:51 +0000117 h = d.GetDialogItemAsControl(4)
Jack Jansena5a49811998-07-01 15:47:44 +0000118 return cr2lf(GetDialogItemText(h))
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000119 if n == 2: return None
120
Jack Jansen60429e01999-12-13 16:07:01 +0000121def AskPassword(prompt, default='', id=264, ok=None, cancel=None):
Jack Jansenb92268a1999-02-10 22:38:44 +0000122 """Display a PROMPT string and a text entry field with a DEFAULT string.
123 The string is displayed as bullets only.
124
125 Return the contents of the text entry field when the user clicks the
126 OK button or presses Return.
127 Return None when the user clicks the Cancel button.
128
129 If omitted, DEFAULT is empty.
130
131 The PROMPT and DEFAULT strings, as well as the return value,
132 can be at most 255 characters long.
133 """
Jack Jansendde800e2002-11-07 23:07:05 +0000134 _initialize()
Jack Jansenb92268a1999-02-10 22:38:44 +0000135 d = GetNewDialog(id, -1)
136 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000137 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Jack Jansenb92268a1999-02-10 22:38:44 +0000138 return
Jack Jansen60429e01999-12-13 16:07:01 +0000139 h = d.GetDialogItemAsControl(3)
Jack Jansenb92268a1999-02-10 22:38:44 +0000140 SetDialogItemText(h, lf2cr(prompt))
Jack Jansen60429e01999-12-13 16:07:01 +0000141 pwd = d.GetDialogItemAsControl(4)
Jack Jansenb92268a1999-02-10 22:38:44 +0000142 bullets = '\245'*len(default)
Jack Jansen60429e01999-12-13 16:07:01 +0000143## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets)
144 SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default)
145 d.SelectDialogItemText(4, 0, 999)
Jack Jansen0c1836f2000-08-25 22:06:19 +0000146 Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart)
Jack Jansen60429e01999-12-13 16:07:01 +0000147 if ok != None:
148 h = d.GetDialogItemAsControl(1)
149 h.SetControlTitle(ok)
150 if cancel != None:
151 h = d.GetDialogItemAsControl(2)
152 h.SetControlTitle(cancel)
Jack Jansenb92268a1999-02-10 22:38:44 +0000153 d.SetDialogDefaultItem(Dialogs.ok)
154 d.SetDialogCancelItem(Dialogs.cancel)
Jack Jansenfca049d2000-01-18 13:36:02 +0000155 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000156 d.GetDialogWindow().ShowWindow()
Jack Jansenb92268a1999-02-10 22:38:44 +0000157 while 1:
Jack Jansen60429e01999-12-13 16:07:01 +0000158 n = ModalDialog(None)
159 if n == 1:
160 h = d.GetDialogItemAsControl(4)
161 return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag))
162 if n == 2: return None
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000163
Jack Jansencc386881999-12-12 22:57:51 +0000164def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262):
Jack Jansencf2efc61999-02-25 22:05:45 +0000165 """Display a QUESTION string which can be answered with Yes or No.
166
167 Return 1 when the user clicks the Yes button.
168 Return 0 when the user clicks the No button.
169 Return -1 when the user clicks the Cancel button.
170
171 When the user presses Return, the DEFAULT value is returned.
172 If omitted, this is 0 (No).
173
Just van Rossum639a7402001-06-26 06:57:12 +0000174 The QUESTION string can be at most 255 characters.
Jack Jansencf2efc61999-02-25 22:05:45 +0000175 """
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000176
Jack Jansendde800e2002-11-07 23:07:05 +0000177 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000178 d = GetNewDialog(id, -1)
179 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000180 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000181 return
182 # Button assignments:
183 # 1 = default (invisible)
184 # 2 = Yes
185 # 3 = No
186 # 4 = Cancel
187 # The question string is item 5
Jack Jansencc386881999-12-12 22:57:51 +0000188 h = d.GetDialogItemAsControl(5)
Jack Jansena5a49811998-07-01 15:47:44 +0000189 SetDialogItemText(h, lf2cr(question))
Jack Jansen3f5aef71997-06-20 16:23:37 +0000190 if yes != None:
Jack Jansen85743782000-02-10 16:15:53 +0000191 if yes == '':
192 d.HideDialogItem(2)
193 else:
194 h = d.GetDialogItemAsControl(2)
195 h.SetControlTitle(yes)
Jack Jansen3f5aef71997-06-20 16:23:37 +0000196 if no != None:
Jack Jansen85743782000-02-10 16:15:53 +0000197 if no == '':
198 d.HideDialogItem(3)
199 else:
200 h = d.GetDialogItemAsControl(3)
201 h.SetControlTitle(no)
Jack Jansen3f5aef71997-06-20 16:23:37 +0000202 if cancel != None:
Jack Jansen208c15a1999-02-16 16:06:39 +0000203 if cancel == '':
204 d.HideDialogItem(4)
205 else:
Jack Jansencc386881999-12-12 22:57:51 +0000206 h = d.GetDialogItemAsControl(4)
207 h.SetControlTitle(cancel)
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000208 d.SetDialogCancelItem(4)
Jack Jansen0b690db1996-04-10 14:49:41 +0000209 if default == 1:
210 d.SetDialogDefaultItem(2)
211 elif default == 0:
212 d.SetDialogDefaultItem(3)
213 elif default == -1:
214 d.SetDialogDefaultItem(4)
Jack Jansenfca049d2000-01-18 13:36:02 +0000215 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000216 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000217 while 1:
218 n = ModalDialog(None)
219 if n == 1: return default
220 if n == 2: return 1
221 if n == 3: return 0
222 if n == 4: return -1
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000223
224
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000225
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000226
Jack Jansen362c7cd02002-11-30 00:01:29 +0000227screenbounds = Qd.GetQDGlobalsScreenBits().bounds
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000228screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
229 screenbounds[2]-4, screenbounds[3]-4
230
Jack Jansen911e87d2001-08-27 15:24:07 +0000231kControlProgressBarIndeterminateTag = 'inde' # from Controls.py
232
233
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000234class ProgressBar:
Jack Jansen911e87d2001-08-27 15:24:07 +0000235 def __init__(self, title="Working...", maxval=0, label="", id=263):
Jack Jansen5dd73622001-02-23 22:18:27 +0000236 self.w = None
237 self.d = None
Jack Jansendde800e2002-11-07 23:07:05 +0000238 _initialize()
Jack Jansen3f5aef71997-06-20 16:23:37 +0000239 self.d = GetNewDialog(id, -1)
Jack Jansen784c6112001-02-09 15:57:01 +0000240 self.w = self.d.GetDialogWindow()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000241 self.label(label)
Jack Jansenab48e902000-07-24 14:07:15 +0000242 self.title(title)
Jack Jansen911e87d2001-08-27 15:24:07 +0000243 self.set(0, maxval)
244 self.d.AutoSizeDialog()
Jack Jansen784c6112001-02-09 15:57:01 +0000245 self.w.ShowWindow()
Jack Jansencc386881999-12-12 22:57:51 +0000246 self.d.DrawDialog()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000247
248 def __del__( self ):
Jack Jansen5dd73622001-02-23 22:18:27 +0000249 if self.w:
250 self.w.BringToFront()
251 self.w.HideWindow()
Jack Jansen784c6112001-02-09 15:57:01 +0000252 del self.w
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000253 del self.d
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000254
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000255 def title(self, newstr=""):
256 """title(text) - Set title of progress window"""
Jack Jansen784c6112001-02-09 15:57:01 +0000257 self.w.BringToFront()
258 self.w.SetWTitle(newstr)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000259
260 def label( self, *newstr ):
261 """label(text) - Set text in progress box"""
Jack Jansen784c6112001-02-09 15:57:01 +0000262 self.w.BringToFront()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000263 if newstr:
Jack Jansena5a49811998-07-01 15:47:44 +0000264 self._label = lf2cr(newstr[0])
Jack Jansencc386881999-12-12 22:57:51 +0000265 text_h = self.d.GetDialogItemAsControl(2)
Jack Jansen911e87d2001-08-27 15:24:07 +0000266 SetDialogItemText(text_h, self._label)
267
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000268 def _update(self, value):
Jack Jansen58fa8181999-11-05 15:53:10 +0000269 maxval = self.maxval
Jack Jansen911e87d2001-08-27 15:24:07 +0000270 if maxval == 0: # an indeterminate bar
271 Ctl.IdleControls(self.w) # spin the barber pole
272 else: # a determinate bar
273 if maxval > 32767:
274 value = int(value/(maxval/32767.0))
275 maxval = 32767
276 progbar = self.d.GetDialogItemAsControl(3)
277 progbar.SetControlMaximum(maxval)
278 progbar.SetControlValue(value) # set the bar length
279
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000280 # Test for cancel button
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000281 ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 )
Jack Jansen911e87d2001-08-27 15:24:07 +0000282 if ready :
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000283 what,msg,when,where,mod = ev
284 part = Win.FindWindow(where)[0]
285 if Dlg.IsDialogEvent(ev):
286 ds = Dlg.DialogSelect(ev)
287 if ds[0] and ds[1] == self.d and ds[-1] == 1:
Jack Jansen5dd73622001-02-23 22:18:27 +0000288 self.w.HideWindow()
289 self.w = None
290 self.d = None
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000291 raise KeyboardInterrupt, ev
292 else:
293 if part == 4: # inDrag
Jack Jansen8d2f3d62001-07-27 09:21:28 +0000294 self.w.DragWindow(where, screenbounds)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000295 else:
296 MacOS.HandleEvent(ev)
297
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000298
Jack Jansen58fa8181999-11-05 15:53:10 +0000299 def set(self, value, max=None):
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000300 """set(value) - Set progress bar position"""
Jack Jansen58fa8181999-11-05 15:53:10 +0000301 if max != None:
302 self.maxval = max
Jack Jansen911e87d2001-08-27 15:24:07 +0000303 bar = self.d.GetDialogItemAsControl(3)
304 if max <= 0: # indeterminate bar
305 bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01')
306 else: # determinate bar
307 bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00')
308 if value < 0:
309 value = 0
310 elif value > self.maxval:
311 value = self.maxval
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000312 self.curval = value
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000313 self._update(value)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000314
315 def inc(self, n=1):
316 """inc(amt) - Increment progress bar position"""
317 self.set(self.curval + n)
318
Jack Jansenf86eda52000-09-19 22:42:38 +0000319ARGV_ID=265
320ARGV_ITEM_OK=1
321ARGV_ITEM_CANCEL=2
322ARGV_OPTION_GROUP=3
323ARGV_OPTION_EXPLAIN=4
324ARGV_OPTION_VALUE=5
325ARGV_OPTION_ADD=6
326ARGV_COMMAND_GROUP=7
327ARGV_COMMAND_EXPLAIN=8
328ARGV_COMMAND_ADD=9
329ARGV_ADD_OLDFILE=10
330ARGV_ADD_NEWFILE=11
331ARGV_ADD_FOLDER=12
332ARGV_CMDLINE_GROUP=13
333ARGV_CMDLINE_DATA=14
334
335##def _myModalDialog(d):
336## while 1:
337## ready, ev = Evt.WaitNextEvent(0xffff, -1)
338## print 'DBG: WNE', ready, ev
339## if ready :
340## what,msg,when,where,mod = ev
341## part, window = Win.FindWindow(where)
342## if Dlg.IsDialogEvent(ev):
343## didit, dlgdone, itemdone = Dlg.DialogSelect(ev)
344## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d
345## if didit and dlgdone == d:
346## return itemdone
347## elif window == d.GetDialogWindow():
348## d.GetDialogWindow().SelectWindow()
349## if part == 4: # inDrag
350## d.DragWindow(where, screenbounds)
351## else:
352## MacOS.HandleEvent(ev)
353## else:
354## MacOS.HandleEvent(ev)
355##
356def _setmenu(control, items):
Jack Jansene7bfc912001-01-09 22:22:58 +0000357 mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
Jack Jansenf86eda52000-09-19 22:42:38 +0000358 Controls.kControlPopupButtonMenuHandleTag)
359 menu = Menu.as_Menu(mhandle)
360 for item in items:
361 if type(item) == type(()):
362 label = item[0]
363 else:
364 label = item
365 if label[-1] == '=' or label[-1] == ':':
366 label = label[:-1]
367 menu.AppendMenu(label)
368## mhandle, mid = menu.getpopupinfo()
Jack Jansene7bfc912001-01-09 22:22:58 +0000369## control.SetControlData_Handle(Controls.kControlMenuPart,
Jack Jansenf86eda52000-09-19 22:42:38 +0000370## Controls.kControlPopupButtonMenuHandleTag, mhandle)
371 control.SetControlMinimum(1)
372 control.SetControlMaximum(len(items)+1)
373
374def _selectoption(d, optionlist, idx):
375 if idx < 0 or idx >= len(optionlist):
376 MacOS.SysBeep()
377 return
378 option = optionlist[idx]
Jack Jansen09c73432002-06-26 15:14:48 +0000379 if type(option) == type(()):
380 if len(option) == 4:
381 help = option[2]
382 elif len(option) > 1:
383 help = option[-1]
384 else:
385 help = ''
Jack Jansenf86eda52000-09-19 22:42:38 +0000386 else:
387 help = ''
388 h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN)
Jack Jansen09c73432002-06-26 15:14:48 +0000389 if help and len(help) > 250:
390 help = help[:250] + '...'
Jack Jansenf86eda52000-09-19 22:42:38 +0000391 Dlg.SetDialogItemText(h, help)
392 hasvalue = 0
393 if type(option) == type(()):
394 label = option[0]
395 else:
396 label = option
397 if label[-1] == '=' or label[-1] == ':':
398 hasvalue = 1
399 h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
400 Dlg.SetDialogItemText(h, '')
401 if hasvalue:
402 d.ShowDialogItem(ARGV_OPTION_VALUE)
403 d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0)
404 else:
405 d.HideDialogItem(ARGV_OPTION_VALUE)
406
407
408def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfolder=1, id=ARGV_ID):
Jack Jansendde800e2002-11-07 23:07:05 +0000409 _initialize()
Jack Jansenf86eda52000-09-19 22:42:38 +0000410 d = GetNewDialog(id, -1)
411 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000412 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Jack Jansenf86eda52000-09-19 22:42:38 +0000413 return
414# h = d.GetDialogItemAsControl(3)
415# SetDialogItemText(h, lf2cr(prompt))
416# h = d.GetDialogItemAsControl(4)
417# SetDialogItemText(h, lf2cr(default))
418# d.SelectDialogItemText(4, 0, 999)
419# d.SetDialogItem(4, 0, 255)
420 if optionlist:
421 _setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist)
422 _selectoption(d, optionlist, 0)
423 else:
424 d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl()
425 if commandlist:
426 _setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist)
Jack Jansen0bb0a902000-09-21 22:01:08 +0000427 if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1:
Jack Jansenf86eda52000-09-19 22:42:38 +0000428 help = commandlist[0][-1]
429 h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
430 Dlg.SetDialogItemText(h, help)
431 else:
432 d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl()
433 if not addoldfile:
434 d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl()
435 if not addnewfile:
436 d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl()
437 if not addfolder:
438 d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl()
439 d.SetDialogDefaultItem(ARGV_ITEM_OK)
440 d.SetDialogCancelItem(ARGV_ITEM_CANCEL)
441 d.GetDialogWindow().ShowWindow()
442 d.DrawDialog()
Jack Janseneb308432001-09-09 00:36:01 +0000443 if hasattr(MacOS, 'SchedParams'):
444 appsw = MacOS.SchedParams(1, 0)
Jack Jansenf86eda52000-09-19 22:42:38 +0000445 try:
446 while 1:
447 stringstoadd = []
448 n = ModalDialog(None)
449 if n == ARGV_ITEM_OK:
450 break
451 elif n == ARGV_ITEM_CANCEL:
452 raise SystemExit
453 elif n == ARGV_OPTION_GROUP:
454 idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
455 _selectoption(d, optionlist, idx)
456 elif n == ARGV_OPTION_VALUE:
457 pass
458 elif n == ARGV_OPTION_ADD:
459 idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
460 if 0 <= idx < len(optionlist):
Jack Jansen0bb0a902000-09-21 22:01:08 +0000461 option = optionlist[idx]
462 if type(option) == type(()):
463 option = option[0]
Jack Jansenf86eda52000-09-19 22:42:38 +0000464 if option[-1] == '=' or option[-1] == ':':
465 option = option[:-1]
466 h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
467 value = Dlg.GetDialogItemText(h)
468 else:
469 value = ''
470 if len(option) == 1:
471 stringtoadd = '-' + option
472 else:
473 stringtoadd = '--' + option
474 stringstoadd = [stringtoadd]
475 if value:
476 stringstoadd.append(value)
477 else:
478 MacOS.SysBeep()
479 elif n == ARGV_COMMAND_GROUP:
480 idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
Jack Jansen0bb0a902000-09-21 22:01:08 +0000481 if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \
Jack Jansenf86eda52000-09-19 22:42:38 +0000482 len(commandlist[idx]) > 1:
483 help = commandlist[idx][-1]
484 h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
485 Dlg.SetDialogItemText(h, help)
486 elif n == ARGV_COMMAND_ADD:
487 idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
488 if 0 <= idx < len(commandlist):
Jack Jansen0bb0a902000-09-21 22:01:08 +0000489 command = commandlist[idx]
490 if type(command) == type(()):
491 command = command[0]
492 stringstoadd = [command]
Jack Jansenf86eda52000-09-19 22:42:38 +0000493 else:
494 MacOS.SysBeep()
495 elif n == ARGV_ADD_OLDFILE:
Jack Jansen08a7a0d2003-01-21 13:56:34 +0000496 pathname = AskFileForOpen()
497 if pathname:
498 stringstoadd = [pathname]
Jack Jansenf86eda52000-09-19 22:42:38 +0000499 elif n == ARGV_ADD_NEWFILE:
Jack Jansen08a7a0d2003-01-21 13:56:34 +0000500 pathname = AskFileForSave()
501 if pathname:
502 stringstoadd = [pathname]
Jack Jansenf86eda52000-09-19 22:42:38 +0000503 elif n == ARGV_ADD_FOLDER:
Jack Jansen08a7a0d2003-01-21 13:56:34 +0000504 pathname = AskFolder()
505 if pathname:
506 stringstoadd = [pathname]
Jack Jansenf86eda52000-09-19 22:42:38 +0000507 elif n == ARGV_CMDLINE_DATA:
508 pass # Nothing to do
509 else:
510 raise RuntimeError, "Unknown dialog item %d"%n
511
512 for stringtoadd in stringstoadd:
513 if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd:
514 stringtoadd = `stringtoadd`
515 h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
516 oldstr = GetDialogItemText(h)
517 if oldstr and oldstr[-1] != ' ':
518 oldstr = oldstr + ' '
519 oldstr = oldstr + stringtoadd
520 if oldstr[-1] != ' ':
521 oldstr = oldstr + ' '
522 SetDialogItemText(h, oldstr)
523 d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
524 h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
525 oldstr = GetDialogItemText(h)
526 tmplist = string.split(oldstr)
527 newlist = []
528 while tmplist:
529 item = tmplist[0]
530 del tmplist[0]
531 if item[0] == '"':
532 while item[-1] != '"':
533 if not tmplist:
534 raise RuntimeError, "Unterminated quoted argument"
535 item = item + ' ' + tmplist[0]
536 del tmplist[0]
537 item = item[1:-1]
538 if item[0] == "'":
539 while item[-1] != "'":
540 if not tmplist:
541 raise RuntimeError, "Unterminated quoted argument"
542 item = item + ' ' + tmplist[0]
543 del tmplist[0]
544 item = item[1:-1]
545 newlist.append(item)
546 return newlist
547 finally:
Jack Janseneb308432001-09-09 00:36:01 +0000548 if hasattr(MacOS, 'SchedParams'):
549 apply(MacOS.SchedParams, appsw)
Jack Jansen0bb0a902000-09-21 22:01:08 +0000550 del d
Jack Jansenf0d12da2003-01-17 16:04:39 +0000551
552def _mktypelist(typelist):
553 # Workaround for OSX typeless files:
554 if 'TEXT' in typelist and not '\0\0\0\0' in typelist:
555 typelist = typelist + ('\0\0\0\0',)
556 if not typelist:
557 return None
558 data = 'Pyth' + struct.pack("hh", 0, len(typelist))
559 for type in typelist:
560 data = data+type
561 return Carbon.Res.Handle(data)
Jack Jansenf86eda52000-09-19 22:42:38 +0000562
Jack Jansenf0d12da2003-01-17 16:04:39 +0000563_ALLOWED_KEYS = {
564 'version':1,
565 'defaultLocation':1,
566 'dialogOptionFlags':1,
567 'location':1,
568 'clientName':1,
569 'windowTitle':1,
570 'actionButtonLabel':1,
571 'cancelButtonLabel':1,
572 'savedFileName':1,
573 'message':1,
574 'preferenceKey':1,
575 'popupExtension':1,
576 'eventProc':1,
577 'previewProc':1,
578 'filterProc':1,
579 'typeList':1,
580 'fileType':1,
581 'fileCreator':1,
582 # Our extension:
583 'wanted':1,
584 'multiple':1,
585}
586
587def _process_Nav_args(argsargs, allowed, dftflags):
588 import aepack
589 import Carbon.AE
590 import Carbon.File
591 args = argsargs.copy()
592 for k in args.keys():
593 if not allowed.has_key(k):
594 raise TypeError, "Unknown keyword argument: %s" % repr(k)
595 # Set some defaults, and modify some arguments
596 if not args.has_key('dialogOptionFlags'):
597 args['dialogOptionFlags'] = dftflags
598 if args.has_key('defaultLocation') and \
599 not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
600 defaultLocation = args['defaultLocation']
601 if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)):
602 args['defaultLocation'] = aepack.pack(defaultLocation)
603 else:
604 defaultLocation = Carbon.File.FSRef(defaultLocation)
605 args['defaultLocation'] = aepack.pack(defaultLocation)
606 if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType):
607 typeList = args['typeList'].copy()
608 # Workaround for OSX typeless files:
609 if 'TEXT' in typeList and not '\0\0\0\0' in typeList:
610 typeList = typeList + ('\0\0\0\0',)
611 data = 'Pyth' + struct.pack("hh", 0, len(typeList))
612 for type in typeList:
613 data = data+type
614 args['typeList'] = Carbon.Res.Handle(data)
615 tpwanted = str
616 if args.has_key('wanted'):
617 tpwanted = args['wanted']
618 del args['wanted']
619 return args, tpwanted
620
621def AskFileForOpen(**args):
622 default_flags = 0x56 # Or 0xe4?
623 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
624 try:
625 rr = Nav.NavChooseFile(args)
626 good = 1
627 except Nav.error, arg:
628 if arg[0] != -128: # userCancelledErr
629 raise Nav.error, arg
630 return None
631 if not rr.validRecord or not rr.selection:
632 return None
633 if issubclass(tpwanted, Carbon.File.FSRef):
634 return tpwanted(rr.selection_fsr[0])
635 if issubclass(tpwanted, Carbon.File.FSSpec):
636 return tpwanted(rr.selection[0])
637 if issubclass(tpwanted, str):
638 return tpwanted(rr.selection_fsr[0].FSRefMakePath())
639 if issubclass(tpwanted, unicode):
640 return tpwanted(rr.selection_fsr[0].FSRefMakePath(), 'utf8')
641 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
642
643def AskFileForSave(**args):
644 default_flags = 0x07
645 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
646 try:
647 rr = Nav.NavPutFile(args)
648 good = 1
649 except Nav.error, arg:
650 if arg[0] != -128: # userCancelledErr
651 raise Nav.error, arg
652 return None
653 if not rr.validRecord or not rr.selection:
654 return None
655 if issubclass(tpwanted, Carbon.File.FSRef):
656 raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave"
657 if issubclass(tpwanted, Carbon.File.FSSpec):
658 return tpwanted(rr.selection[0])
659 if issubclass(tpwanted, (str, unicode)):
660 # This is gross, and probably incorrect too
661 vrefnum, dirid, name = rr.selection[0].as_tuple()
662 pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, ''))
Jack Jansene58962a2003-01-17 23:13:03 +0000663 pardir_fsr = Carbon.File.FSRef(pardir_fss)
Jack Jansenf0d12da2003-01-17 16:04:39 +0000664 pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8
665 name_utf8 = unicode(name, 'macroman').encode('utf8')
666 fullpath = os.path.join(pardir_path, name_utf8)
667 if issubclass(tpwanted, unicode):
668 return unicode(fullpath, 'utf8')
669 return tpwanted(fullpath)
670 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
671
672def AskFolder(**args):
673 default_flags = 0x17
674 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
675 try:
676 rr = Nav.NavChooseFolder(args)
677 good = 1
678 except Nav.error, arg:
679 if arg[0] != -128: # userCancelledErr
680 raise Nav.error, arg
681 return None
682 if not rr.validRecord or not rr.selection:
683 return None
684 if issubclass(tpwanted, Carbon.File.FSRef):
685 return tpwanted(rr.selection_fsr[0])
686 if issubclass(tpwanted, Carbon.File.FSSpec):
687 return tpwanted(rr.selection[0])
688 if issubclass(tpwanted, str):
689 return tpwanted(rr.selection_fsr[0].FSRefMakePath())
690 if issubclass(tpwanted, unicode):
691 return tpwanted(rr.selection_fsr[0].FSRefMakePath(), 'utf8')
692 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
693
694
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000695def test():
Jack Jansen08a7a0d2003-01-21 13:56:34 +0000696 import time, sys, macfs
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000697
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000698 Message("Testing EasyDialogs.")
Jack Jansenf86eda52000-09-19 22:42:38 +0000699 optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'),
700 ('flags=', 'Valued option'), ('f:', 'Short valued option'))
701 commandlist = (('start', 'Start something'), ('stop', 'Stop something'))
702 argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
Jack Jansenf0d12da2003-01-17 16:04:39 +0000703 Message("Command line: %s"%' '.join(argv))
Jack Jansenf86eda52000-09-19 22:42:38 +0000704 for i in range(len(argv)):
705 print 'arg[%d] = %s'%(i, `argv[i]`)
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000706 ok = AskYesNoCancel("Do you want to proceed?")
Jack Jansen60429e01999-12-13 16:07:01 +0000707 ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000708 if ok > 0:
Jack Jansend61f92b1999-01-22 13:14:06 +0000709 s = AskString("Enter your first name", "Joe")
Jack Jansen60429e01999-12-13 16:07:01 +0000710 s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None")
711 if not s2:
712 Message("%s has no secret nickname"%s)
713 else:
714 Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2))
Jack Jansenf0d12da2003-01-17 16:04:39 +0000715 else:
716 s = 'Anonymous'
717 rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=macfs.FSSpec)
718 Message("rv: %s"%rv)
719 rv = AskFileForSave(wanted=macfs.FSSpec, savedFileName="%s.txt"%s)
720 Message("rv.as_pathname: %s"%rv.as_pathname())
721 rv = AskFolder()
722 Message("Folder name: %s"%rv)
Jack Jansen911e87d2001-08-27 15:24:07 +0000723 text = ( "Working Hard...", "Hardly Working..." ,
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000724 "So far, so good!", "Keep on truckin'" )
Jack Jansen911e87d2001-08-27 15:24:07 +0000725 bar = ProgressBar("Progress, progress...", 0, label="Ramping up...")
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000726 try:
Jack Janseneb308432001-09-09 00:36:01 +0000727 if hasattr(MacOS, 'SchedParams'):
728 appsw = MacOS.SchedParams(1, 0)
Jack Jansen911e87d2001-08-27 15:24:07 +0000729 for i in xrange(20):
730 bar.inc()
731 time.sleep(0.05)
732 bar.set(0,100)
733 for i in xrange(100):
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000734 bar.set(i)
Jack Jansen911e87d2001-08-27 15:24:07 +0000735 time.sleep(0.05)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000736 if i % 10 == 0:
737 bar.label(text[(i/10) % 4])
738 bar.label("Done.")
Jack Jansen911e87d2001-08-27 15:24:07 +0000739 time.sleep(1.0) # give'em a chance to see "Done."
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000740 finally:
741 del bar
Jack Janseneb308432001-09-09 00:36:01 +0000742 if hasattr(MacOS, 'SchedParams'):
743 apply(MacOS.SchedParams, appsw)
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000744
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000745if __name__ == '__main__':
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000746 try:
747 test()
748 except KeyboardInterrupt:
749 Message("Operation Canceled.")
750