blob: 25a791a395b738e02e4499fd00e857dcb18917ae [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 Jansenf86eda52000-09-19 22:42:38 +000031import macfs
Jack Jansendde800e2002-11-07 23:07:05 +000032import macresource
Jack Jansene58962a2003-01-17 23:13:03 +000033import os
Jack Jansendde800e2002-11-07 23:07:05 +000034
35_initialized = 0
36
37def _initialize():
38 global _initialized
39 if _initialized: return
40 macresource.need("DLOG", 260, "dialogs.rsrc", __name__)
41
Jack Jansena5a49811998-07-01 15:47:44 +000042
43def cr2lf(text):
44 if '\r' in text:
45 text = string.join(string.split(text, '\r'), '\n')
46 return text
47
48def lf2cr(text):
49 if '\n' in text:
50 text = string.join(string.split(text, '\n'), '\r')
Jack Jansend5af7bd1998-09-28 10:37:08 +000051 if len(text) > 253:
52 text = text[:253] + '\311'
Jack Jansena5a49811998-07-01 15:47:44 +000053 return text
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000054
Jack Jansencc386881999-12-12 22:57:51 +000055def Message(msg, id=260, ok=None):
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000056 """Display a MESSAGE string.
57
58 Return when the user clicks the OK button or presses Return.
59
60 The MESSAGE string can be at most 255 characters long.
61 """
Jack Jansendde800e2002-11-07 23:07:05 +000062 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000063 d = GetNewDialog(id, -1)
64 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +000065 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000066 return
Jack Jansencc386881999-12-12 22:57:51 +000067 h = d.GetDialogItemAsControl(2)
Jack Jansena5a49811998-07-01 15:47:44 +000068 SetDialogItemText(h, lf2cr(msg))
Jack Jansen208c15a1999-02-16 16:06:39 +000069 if ok != None:
Jack Jansencc386881999-12-12 22:57:51 +000070 h = d.GetDialogItemAsControl(1)
71 h.SetControlTitle(ok)
Jack Jansen3a87f5b1995-11-14 10:13:49 +000072 d.SetDialogDefaultItem(1)
Jack Jansenfca049d2000-01-18 13:36:02 +000073 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +000074 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000075 while 1:
76 n = ModalDialog(None)
77 if n == 1:
78 return
79
80
Jack Jansencc386881999-12-12 22:57:51 +000081def AskString(prompt, default = "", id=261, ok=None, cancel=None):
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000082 """Display a PROMPT string and a text entry field with a DEFAULT string.
83
84 Return the contents of the text entry field when the user clicks the
85 OK button or presses Return.
86 Return None when the user clicks the Cancel button.
87
88 If omitted, DEFAULT is empty.
89
90 The PROMPT and DEFAULT strings, as well as the return value,
91 can be at most 255 characters long.
92 """
93
Jack Jansendde800e2002-11-07 23:07:05 +000094 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000095 d = GetNewDialog(id, -1)
96 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +000097 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +000098 return
Jack Jansencc386881999-12-12 22:57:51 +000099 h = d.GetDialogItemAsControl(3)
Jack Jansena5a49811998-07-01 15:47:44 +0000100 SetDialogItemText(h, lf2cr(prompt))
Jack Jansencc386881999-12-12 22:57:51 +0000101 h = d.GetDialogItemAsControl(4)
Jack Jansena5a49811998-07-01 15:47:44 +0000102 SetDialogItemText(h, lf2cr(default))
Jack Jansend61f92b1999-01-22 13:14:06 +0000103 d.SelectDialogItemText(4, 0, 999)
Jack Jansene4b40381995-07-17 13:25:15 +0000104# d.SetDialogItem(4, 0, 255)
Jack Jansen208c15a1999-02-16 16:06:39 +0000105 if ok != None:
Jack Jansencc386881999-12-12 22:57:51 +0000106 h = d.GetDialogItemAsControl(1)
107 h.SetControlTitle(ok)
Jack Jansen208c15a1999-02-16 16:06:39 +0000108 if cancel != None:
Jack Jansencc386881999-12-12 22:57:51 +0000109 h = d.GetDialogItemAsControl(2)
110 h.SetControlTitle(cancel)
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000111 d.SetDialogDefaultItem(1)
112 d.SetDialogCancelItem(2)
Jack Jansenfca049d2000-01-18 13:36:02 +0000113 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000114 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000115 while 1:
116 n = ModalDialog(None)
117 if n == 1:
Jack Jansencc386881999-12-12 22:57:51 +0000118 h = d.GetDialogItemAsControl(4)
Jack Jansena5a49811998-07-01 15:47:44 +0000119 return cr2lf(GetDialogItemText(h))
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000120 if n == 2: return None
121
Jack Jansen60429e01999-12-13 16:07:01 +0000122def AskPassword(prompt, default='', id=264, ok=None, cancel=None):
Jack Jansenb92268a1999-02-10 22:38:44 +0000123 """Display a PROMPT string and a text entry field with a DEFAULT string.
124 The string is displayed as bullets only.
125
126 Return the contents of the text entry field when the user clicks the
127 OK button or presses Return.
128 Return None when the user clicks the Cancel button.
129
130 If omitted, DEFAULT is empty.
131
132 The PROMPT and DEFAULT strings, as well as the return value,
133 can be at most 255 characters long.
134 """
Jack Jansendde800e2002-11-07 23:07:05 +0000135 _initialize()
Jack Jansenb92268a1999-02-10 22:38:44 +0000136 d = GetNewDialog(id, -1)
137 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000138 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Jack Jansenb92268a1999-02-10 22:38:44 +0000139 return
Jack Jansen60429e01999-12-13 16:07:01 +0000140 h = d.GetDialogItemAsControl(3)
Jack Jansenb92268a1999-02-10 22:38:44 +0000141 SetDialogItemText(h, lf2cr(prompt))
Jack Jansen60429e01999-12-13 16:07:01 +0000142 pwd = d.GetDialogItemAsControl(4)
Jack Jansenb92268a1999-02-10 22:38:44 +0000143 bullets = '\245'*len(default)
Jack Jansen60429e01999-12-13 16:07:01 +0000144## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets)
145 SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default)
146 d.SelectDialogItemText(4, 0, 999)
Jack Jansen0c1836f2000-08-25 22:06:19 +0000147 Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart)
Jack Jansen60429e01999-12-13 16:07:01 +0000148 if ok != None:
149 h = d.GetDialogItemAsControl(1)
150 h.SetControlTitle(ok)
151 if cancel != None:
152 h = d.GetDialogItemAsControl(2)
153 h.SetControlTitle(cancel)
Jack Jansenb92268a1999-02-10 22:38:44 +0000154 d.SetDialogDefaultItem(Dialogs.ok)
155 d.SetDialogCancelItem(Dialogs.cancel)
Jack Jansenfca049d2000-01-18 13:36:02 +0000156 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000157 d.GetDialogWindow().ShowWindow()
Jack Jansenb92268a1999-02-10 22:38:44 +0000158 while 1:
Jack Jansen60429e01999-12-13 16:07:01 +0000159 n = ModalDialog(None)
160 if n == 1:
161 h = d.GetDialogItemAsControl(4)
162 return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag))
163 if n == 2: return None
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000164
Jack Jansencc386881999-12-12 22:57:51 +0000165def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262):
Jack Jansencf2efc61999-02-25 22:05:45 +0000166 """Display a QUESTION string which can be answered with Yes or No.
167
168 Return 1 when the user clicks the Yes button.
169 Return 0 when the user clicks the No button.
170 Return -1 when the user clicks the Cancel button.
171
172 When the user presses Return, the DEFAULT value is returned.
173 If omitted, this is 0 (No).
174
Just van Rossum639a7402001-06-26 06:57:12 +0000175 The QUESTION string can be at most 255 characters.
Jack Jansencf2efc61999-02-25 22:05:45 +0000176 """
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000177
Jack Jansendde800e2002-11-07 23:07:05 +0000178 _initialize()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000179 d = GetNewDialog(id, -1)
180 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000181 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000182 return
183 # Button assignments:
184 # 1 = default (invisible)
185 # 2 = Yes
186 # 3 = No
187 # 4 = Cancel
188 # The question string is item 5
Jack Jansencc386881999-12-12 22:57:51 +0000189 h = d.GetDialogItemAsControl(5)
Jack Jansena5a49811998-07-01 15:47:44 +0000190 SetDialogItemText(h, lf2cr(question))
Jack Jansen3f5aef71997-06-20 16:23:37 +0000191 if yes != None:
Jack Jansen85743782000-02-10 16:15:53 +0000192 if yes == '':
193 d.HideDialogItem(2)
194 else:
195 h = d.GetDialogItemAsControl(2)
196 h.SetControlTitle(yes)
Jack Jansen3f5aef71997-06-20 16:23:37 +0000197 if no != None:
Jack Jansen85743782000-02-10 16:15:53 +0000198 if no == '':
199 d.HideDialogItem(3)
200 else:
201 h = d.GetDialogItemAsControl(3)
202 h.SetControlTitle(no)
Jack Jansen3f5aef71997-06-20 16:23:37 +0000203 if cancel != None:
Jack Jansen208c15a1999-02-16 16:06:39 +0000204 if cancel == '':
205 d.HideDialogItem(4)
206 else:
Jack Jansencc386881999-12-12 22:57:51 +0000207 h = d.GetDialogItemAsControl(4)
208 h.SetControlTitle(cancel)
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000209 d.SetDialogCancelItem(4)
Jack Jansen0b690db1996-04-10 14:49:41 +0000210 if default == 1:
211 d.SetDialogDefaultItem(2)
212 elif default == 0:
213 d.SetDialogDefaultItem(3)
214 elif default == -1:
215 d.SetDialogDefaultItem(4)
Jack Jansenfca049d2000-01-18 13:36:02 +0000216 d.AutoSizeDialog()
Jack Jansen0c1836f2000-08-25 22:06:19 +0000217 d.GetDialogWindow().ShowWindow()
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000218 while 1:
219 n = ModalDialog(None)
220 if n == 1: return default
221 if n == 2: return 1
222 if n == 3: return 0
223 if n == 4: return -1
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000224
225
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000226
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000227
Jack Jansen362c7cd02002-11-30 00:01:29 +0000228screenbounds = Qd.GetQDGlobalsScreenBits().bounds
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000229screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
230 screenbounds[2]-4, screenbounds[3]-4
231
Jack Jansen911e87d2001-08-27 15:24:07 +0000232kControlProgressBarIndeterminateTag = 'inde' # from Controls.py
233
234
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000235class ProgressBar:
Jack Jansen911e87d2001-08-27 15:24:07 +0000236 def __init__(self, title="Working...", maxval=0, label="", id=263):
Jack Jansen5dd73622001-02-23 22:18:27 +0000237 self.w = None
238 self.d = None
Jack Jansendde800e2002-11-07 23:07:05 +0000239 _initialize()
Jack Jansen3f5aef71997-06-20 16:23:37 +0000240 self.d = GetNewDialog(id, -1)
Jack Jansen784c6112001-02-09 15:57:01 +0000241 self.w = self.d.GetDialogWindow()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000242 self.label(label)
Jack Jansenab48e902000-07-24 14:07:15 +0000243 self.title(title)
Jack Jansen911e87d2001-08-27 15:24:07 +0000244 self.set(0, maxval)
245 self.d.AutoSizeDialog()
Jack Jansen784c6112001-02-09 15:57:01 +0000246 self.w.ShowWindow()
Jack Jansencc386881999-12-12 22:57:51 +0000247 self.d.DrawDialog()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000248
249 def __del__( self ):
Jack Jansen5dd73622001-02-23 22:18:27 +0000250 if self.w:
251 self.w.BringToFront()
252 self.w.HideWindow()
Jack Jansen784c6112001-02-09 15:57:01 +0000253 del self.w
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000254 del self.d
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000255
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000256 def title(self, newstr=""):
257 """title(text) - Set title of progress window"""
Jack Jansen784c6112001-02-09 15:57:01 +0000258 self.w.BringToFront()
259 self.w.SetWTitle(newstr)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000260
261 def label( self, *newstr ):
262 """label(text) - Set text in progress box"""
Jack Jansen784c6112001-02-09 15:57:01 +0000263 self.w.BringToFront()
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000264 if newstr:
Jack Jansena5a49811998-07-01 15:47:44 +0000265 self._label = lf2cr(newstr[0])
Jack Jansencc386881999-12-12 22:57:51 +0000266 text_h = self.d.GetDialogItemAsControl(2)
Jack Jansen911e87d2001-08-27 15:24:07 +0000267 SetDialogItemText(text_h, self._label)
268
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000269 def _update(self, value):
Jack Jansen58fa8181999-11-05 15:53:10 +0000270 maxval = self.maxval
Jack Jansen911e87d2001-08-27 15:24:07 +0000271 if maxval == 0: # an indeterminate bar
272 Ctl.IdleControls(self.w) # spin the barber pole
273 else: # a determinate bar
274 if maxval > 32767:
275 value = int(value/(maxval/32767.0))
276 maxval = 32767
277 progbar = self.d.GetDialogItemAsControl(3)
278 progbar.SetControlMaximum(maxval)
279 progbar.SetControlValue(value) # set the bar length
280
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000281 # Test for cancel button
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000282 ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 )
Jack Jansen911e87d2001-08-27 15:24:07 +0000283 if ready :
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000284 what,msg,when,where,mod = ev
285 part = Win.FindWindow(where)[0]
286 if Dlg.IsDialogEvent(ev):
287 ds = Dlg.DialogSelect(ev)
288 if ds[0] and ds[1] == self.d and ds[-1] == 1:
Jack Jansen5dd73622001-02-23 22:18:27 +0000289 self.w.HideWindow()
290 self.w = None
291 self.d = None
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000292 raise KeyboardInterrupt, ev
293 else:
294 if part == 4: # inDrag
Jack Jansen8d2f3d62001-07-27 09:21:28 +0000295 self.w.DragWindow(where, screenbounds)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000296 else:
297 MacOS.HandleEvent(ev)
298
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000299
Jack Jansen58fa8181999-11-05 15:53:10 +0000300 def set(self, value, max=None):
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000301 """set(value) - Set progress bar position"""
Jack Jansen58fa8181999-11-05 15:53:10 +0000302 if max != None:
303 self.maxval = max
Jack Jansen911e87d2001-08-27 15:24:07 +0000304 bar = self.d.GetDialogItemAsControl(3)
305 if max <= 0: # indeterminate bar
306 bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01')
307 else: # determinate bar
308 bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00')
309 if value < 0:
310 value = 0
311 elif value > self.maxval:
312 value = self.maxval
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000313 self.curval = value
Jack Jansen3a87f5b1995-11-14 10:13:49 +0000314 self._update(value)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000315
316 def inc(self, n=1):
317 """inc(amt) - Increment progress bar position"""
318 self.set(self.curval + n)
319
Jack Jansenf86eda52000-09-19 22:42:38 +0000320ARGV_ID=265
321ARGV_ITEM_OK=1
322ARGV_ITEM_CANCEL=2
323ARGV_OPTION_GROUP=3
324ARGV_OPTION_EXPLAIN=4
325ARGV_OPTION_VALUE=5
326ARGV_OPTION_ADD=6
327ARGV_COMMAND_GROUP=7
328ARGV_COMMAND_EXPLAIN=8
329ARGV_COMMAND_ADD=9
330ARGV_ADD_OLDFILE=10
331ARGV_ADD_NEWFILE=11
332ARGV_ADD_FOLDER=12
333ARGV_CMDLINE_GROUP=13
334ARGV_CMDLINE_DATA=14
335
336##def _myModalDialog(d):
337## while 1:
338## ready, ev = Evt.WaitNextEvent(0xffff, -1)
339## print 'DBG: WNE', ready, ev
340## if ready :
341## what,msg,when,where,mod = ev
342## part, window = Win.FindWindow(where)
343## if Dlg.IsDialogEvent(ev):
344## didit, dlgdone, itemdone = Dlg.DialogSelect(ev)
345## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d
346## if didit and dlgdone == d:
347## return itemdone
348## elif window == d.GetDialogWindow():
349## d.GetDialogWindow().SelectWindow()
350## if part == 4: # inDrag
351## d.DragWindow(where, screenbounds)
352## else:
353## MacOS.HandleEvent(ev)
354## else:
355## MacOS.HandleEvent(ev)
356##
357def _setmenu(control, items):
Jack Jansene7bfc912001-01-09 22:22:58 +0000358 mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
Jack Jansenf86eda52000-09-19 22:42:38 +0000359 Controls.kControlPopupButtonMenuHandleTag)
360 menu = Menu.as_Menu(mhandle)
361 for item in items:
362 if type(item) == type(()):
363 label = item[0]
364 else:
365 label = item
366 if label[-1] == '=' or label[-1] == ':':
367 label = label[:-1]
368 menu.AppendMenu(label)
369## mhandle, mid = menu.getpopupinfo()
Jack Jansene7bfc912001-01-09 22:22:58 +0000370## control.SetControlData_Handle(Controls.kControlMenuPart,
Jack Jansenf86eda52000-09-19 22:42:38 +0000371## Controls.kControlPopupButtonMenuHandleTag, mhandle)
372 control.SetControlMinimum(1)
373 control.SetControlMaximum(len(items)+1)
374
375def _selectoption(d, optionlist, idx):
376 if idx < 0 or idx >= len(optionlist):
377 MacOS.SysBeep()
378 return
379 option = optionlist[idx]
Jack Jansen09c73432002-06-26 15:14:48 +0000380 if type(option) == type(()):
381 if len(option) == 4:
382 help = option[2]
383 elif len(option) > 1:
384 help = option[-1]
385 else:
386 help = ''
Jack Jansenf86eda52000-09-19 22:42:38 +0000387 else:
388 help = ''
389 h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN)
Jack Jansen09c73432002-06-26 15:14:48 +0000390 if help and len(help) > 250:
391 help = help[:250] + '...'
Jack Jansenf86eda52000-09-19 22:42:38 +0000392 Dlg.SetDialogItemText(h, help)
393 hasvalue = 0
394 if type(option) == type(()):
395 label = option[0]
396 else:
397 label = option
398 if label[-1] == '=' or label[-1] == ':':
399 hasvalue = 1
400 h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
401 Dlg.SetDialogItemText(h, '')
402 if hasvalue:
403 d.ShowDialogItem(ARGV_OPTION_VALUE)
404 d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0)
405 else:
406 d.HideDialogItem(ARGV_OPTION_VALUE)
407
408
409def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfolder=1, id=ARGV_ID):
Jack Jansendde800e2002-11-07 23:07:05 +0000410 _initialize()
Jack Jansenf86eda52000-09-19 22:42:38 +0000411 d = GetNewDialog(id, -1)
412 if not d:
Jack Jansend05e1812002-08-02 11:03:19 +0000413 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
Jack Jansenf86eda52000-09-19 22:42:38 +0000414 return
415# h = d.GetDialogItemAsControl(3)
416# SetDialogItemText(h, lf2cr(prompt))
417# h = d.GetDialogItemAsControl(4)
418# SetDialogItemText(h, lf2cr(default))
419# d.SelectDialogItemText(4, 0, 999)
420# d.SetDialogItem(4, 0, 255)
421 if optionlist:
422 _setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist)
423 _selectoption(d, optionlist, 0)
424 else:
425 d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl()
426 if commandlist:
427 _setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist)
Jack Jansen0bb0a902000-09-21 22:01:08 +0000428 if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1:
Jack Jansenf86eda52000-09-19 22:42:38 +0000429 help = commandlist[0][-1]
430 h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
431 Dlg.SetDialogItemText(h, help)
432 else:
433 d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl()
434 if not addoldfile:
435 d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl()
436 if not addnewfile:
437 d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl()
438 if not addfolder:
439 d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl()
440 d.SetDialogDefaultItem(ARGV_ITEM_OK)
441 d.SetDialogCancelItem(ARGV_ITEM_CANCEL)
442 d.GetDialogWindow().ShowWindow()
443 d.DrawDialog()
Jack Janseneb308432001-09-09 00:36:01 +0000444 if hasattr(MacOS, 'SchedParams'):
445 appsw = MacOS.SchedParams(1, 0)
Jack Jansenf86eda52000-09-19 22:42:38 +0000446 try:
447 while 1:
448 stringstoadd = []
449 n = ModalDialog(None)
450 if n == ARGV_ITEM_OK:
451 break
452 elif n == ARGV_ITEM_CANCEL:
453 raise SystemExit
454 elif n == ARGV_OPTION_GROUP:
455 idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
456 _selectoption(d, optionlist, idx)
457 elif n == ARGV_OPTION_VALUE:
458 pass
459 elif n == ARGV_OPTION_ADD:
460 idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
461 if 0 <= idx < len(optionlist):
Jack Jansen0bb0a902000-09-21 22:01:08 +0000462 option = optionlist[idx]
463 if type(option) == type(()):
464 option = option[0]
Jack Jansenf86eda52000-09-19 22:42:38 +0000465 if option[-1] == '=' or option[-1] == ':':
466 option = option[:-1]
467 h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
468 value = Dlg.GetDialogItemText(h)
469 else:
470 value = ''
471 if len(option) == 1:
472 stringtoadd = '-' + option
473 else:
474 stringtoadd = '--' + option
475 stringstoadd = [stringtoadd]
476 if value:
477 stringstoadd.append(value)
478 else:
479 MacOS.SysBeep()
480 elif n == ARGV_COMMAND_GROUP:
481 idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
Jack Jansen0bb0a902000-09-21 22:01:08 +0000482 if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \
Jack Jansenf86eda52000-09-19 22:42:38 +0000483 len(commandlist[idx]) > 1:
484 help = commandlist[idx][-1]
485 h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
486 Dlg.SetDialogItemText(h, help)
487 elif n == ARGV_COMMAND_ADD:
488 idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
489 if 0 <= idx < len(commandlist):
Jack Jansen0bb0a902000-09-21 22:01:08 +0000490 command = commandlist[idx]
491 if type(command) == type(()):
492 command = command[0]
493 stringstoadd = [command]
Jack Jansenf86eda52000-09-19 22:42:38 +0000494 else:
495 MacOS.SysBeep()
496 elif n == ARGV_ADD_OLDFILE:
497 fss, ok = macfs.StandardGetFile()
498 if ok:
499 stringstoadd = [fss.as_pathname()]
500 elif n == ARGV_ADD_NEWFILE:
501 fss, ok = macfs.StandardPutFile('')
502 if ok:
503 stringstoadd = [fss.as_pathname()]
504 elif n == ARGV_ADD_FOLDER:
505 fss, ok = macfs.GetDirectory()
506 if ok:
507 stringstoadd = [fss.as_pathname()]
508 elif n == ARGV_CMDLINE_DATA:
509 pass # Nothing to do
510 else:
511 raise RuntimeError, "Unknown dialog item %d"%n
512
513 for stringtoadd in stringstoadd:
514 if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd:
515 stringtoadd = `stringtoadd`
516 h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
517 oldstr = GetDialogItemText(h)
518 if oldstr and oldstr[-1] != ' ':
519 oldstr = oldstr + ' '
520 oldstr = oldstr + stringtoadd
521 if oldstr[-1] != ' ':
522 oldstr = oldstr + ' '
523 SetDialogItemText(h, oldstr)
524 d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
525 h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
526 oldstr = GetDialogItemText(h)
527 tmplist = string.split(oldstr)
528 newlist = []
529 while tmplist:
530 item = tmplist[0]
531 del tmplist[0]
532 if item[0] == '"':
533 while item[-1] != '"':
534 if not tmplist:
535 raise RuntimeError, "Unterminated quoted argument"
536 item = item + ' ' + tmplist[0]
537 del tmplist[0]
538 item = item[1:-1]
539 if item[0] == "'":
540 while item[-1] != "'":
541 if not tmplist:
542 raise RuntimeError, "Unterminated quoted argument"
543 item = item + ' ' + tmplist[0]
544 del tmplist[0]
545 item = item[1:-1]
546 newlist.append(item)
547 return newlist
548 finally:
Jack Janseneb308432001-09-09 00:36:01 +0000549 if hasattr(MacOS, 'SchedParams'):
550 apply(MacOS.SchedParams, appsw)
Jack Jansen0bb0a902000-09-21 22:01:08 +0000551 del d
Jack Jansenf0d12da2003-01-17 16:04:39 +0000552
553def _mktypelist(typelist):
554 # Workaround for OSX typeless files:
555 if 'TEXT' in typelist and not '\0\0\0\0' in typelist:
556 typelist = typelist + ('\0\0\0\0',)
557 if not typelist:
558 return None
559 data = 'Pyth' + struct.pack("hh", 0, len(typelist))
560 for type in typelist:
561 data = data+type
562 return Carbon.Res.Handle(data)
Jack Jansenf86eda52000-09-19 22:42:38 +0000563
Jack Jansenf0d12da2003-01-17 16:04:39 +0000564_ALLOWED_KEYS = {
565 'version':1,
566 'defaultLocation':1,
567 'dialogOptionFlags':1,
568 'location':1,
569 'clientName':1,
570 'windowTitle':1,
571 'actionButtonLabel':1,
572 'cancelButtonLabel':1,
573 'savedFileName':1,
574 'message':1,
575 'preferenceKey':1,
576 'popupExtension':1,
577 'eventProc':1,
578 'previewProc':1,
579 'filterProc':1,
580 'typeList':1,
581 'fileType':1,
582 'fileCreator':1,
583 # Our extension:
584 'wanted':1,
585 'multiple':1,
586}
587
588def _process_Nav_args(argsargs, allowed, dftflags):
589 import aepack
590 import Carbon.AE
591 import Carbon.File
592 args = argsargs.copy()
593 for k in args.keys():
594 if not allowed.has_key(k):
595 raise TypeError, "Unknown keyword argument: %s" % repr(k)
596 # Set some defaults, and modify some arguments
597 if not args.has_key('dialogOptionFlags'):
598 args['dialogOptionFlags'] = dftflags
599 if args.has_key('defaultLocation') and \
600 not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
601 defaultLocation = args['defaultLocation']
602 if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)):
603 args['defaultLocation'] = aepack.pack(defaultLocation)
604 else:
605 defaultLocation = Carbon.File.FSRef(defaultLocation)
606 args['defaultLocation'] = aepack.pack(defaultLocation)
607 if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType):
608 typeList = args['typeList'].copy()
609 # Workaround for OSX typeless files:
610 if 'TEXT' in typeList and not '\0\0\0\0' in typeList:
611 typeList = typeList + ('\0\0\0\0',)
612 data = 'Pyth' + struct.pack("hh", 0, len(typeList))
613 for type in typeList:
614 data = data+type
615 args['typeList'] = Carbon.Res.Handle(data)
616 tpwanted = str
617 if args.has_key('wanted'):
618 tpwanted = args['wanted']
619 del args['wanted']
620 return args, tpwanted
621
622def AskFileForOpen(**args):
623 default_flags = 0x56 # Or 0xe4?
624 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
625 try:
626 rr = Nav.NavChooseFile(args)
627 good = 1
628 except Nav.error, arg:
629 if arg[0] != -128: # userCancelledErr
630 raise Nav.error, arg
631 return None
632 if not rr.validRecord or not rr.selection:
633 return None
634 if issubclass(tpwanted, Carbon.File.FSRef):
635 return tpwanted(rr.selection_fsr[0])
636 if issubclass(tpwanted, Carbon.File.FSSpec):
637 return tpwanted(rr.selection[0])
638 if issubclass(tpwanted, str):
639 return tpwanted(rr.selection_fsr[0].FSRefMakePath())
640 if issubclass(tpwanted, unicode):
641 return tpwanted(rr.selection_fsr[0].FSRefMakePath(), 'utf8')
642 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
643
644def AskFileForSave(**args):
645 default_flags = 0x07
646 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
647 try:
648 rr = Nav.NavPutFile(args)
649 good = 1
650 except Nav.error, arg:
651 if arg[0] != -128: # userCancelledErr
652 raise Nav.error, arg
653 return None
654 if not rr.validRecord or not rr.selection:
655 return None
656 if issubclass(tpwanted, Carbon.File.FSRef):
657 raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave"
658 if issubclass(tpwanted, Carbon.File.FSSpec):
659 return tpwanted(rr.selection[0])
660 if issubclass(tpwanted, (str, unicode)):
661 # This is gross, and probably incorrect too
662 vrefnum, dirid, name = rr.selection[0].as_tuple()
663 pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, ''))
Jack Jansene58962a2003-01-17 23:13:03 +0000664 pardir_fsr = Carbon.File.FSRef(pardir_fss)
Jack Jansenf0d12da2003-01-17 16:04:39 +0000665 pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8
666 name_utf8 = unicode(name, 'macroman').encode('utf8')
667 fullpath = os.path.join(pardir_path, name_utf8)
668 if issubclass(tpwanted, unicode):
669 return unicode(fullpath, 'utf8')
670 return tpwanted(fullpath)
671 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
672
673def AskFolder(**args):
674 default_flags = 0x17
675 args, tpwanted = _process_Nav_args(args, _ALLOWED_KEYS, default_flags)
676 try:
677 rr = Nav.NavChooseFolder(args)
678 good = 1
679 except Nav.error, arg:
680 if arg[0] != -128: # userCancelledErr
681 raise Nav.error, arg
682 return None
683 if not rr.validRecord or not rr.selection:
684 return None
685 if issubclass(tpwanted, Carbon.File.FSRef):
686 return tpwanted(rr.selection_fsr[0])
687 if issubclass(tpwanted, Carbon.File.FSSpec):
688 return tpwanted(rr.selection[0])
689 if issubclass(tpwanted, str):
690 return tpwanted(rr.selection_fsr[0].FSRefMakePath())
691 if issubclass(tpwanted, unicode):
692 return tpwanted(rr.selection_fsr[0].FSRefMakePath(), 'utf8')
693 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
694
695
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000696def test():
Jack Jansenf86eda52000-09-19 22:42:38 +0000697 import time, sys
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000698
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000699 Message("Testing EasyDialogs.")
Jack Jansenf86eda52000-09-19 22:42:38 +0000700 optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'),
701 ('flags=', 'Valued option'), ('f:', 'Short valued option'))
702 commandlist = (('start', 'Start something'), ('stop', 'Stop something'))
703 argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
Jack Jansenf0d12da2003-01-17 16:04:39 +0000704 Message("Command line: %s"%' '.join(argv))
Jack Jansenf86eda52000-09-19 22:42:38 +0000705 for i in range(len(argv)):
706 print 'arg[%d] = %s'%(i, `argv[i]`)
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000707 ok = AskYesNoCancel("Do you want to proceed?")
Jack Jansen60429e01999-12-13 16:07:01 +0000708 ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000709 if ok > 0:
Jack Jansend61f92b1999-01-22 13:14:06 +0000710 s = AskString("Enter your first name", "Joe")
Jack Jansen60429e01999-12-13 16:07:01 +0000711 s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None")
712 if not s2:
713 Message("%s has no secret nickname"%s)
714 else:
715 Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2))
Jack Jansenf0d12da2003-01-17 16:04:39 +0000716 else:
717 s = 'Anonymous'
718 rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=macfs.FSSpec)
719 Message("rv: %s"%rv)
720 rv = AskFileForSave(wanted=macfs.FSSpec, savedFileName="%s.txt"%s)
721 Message("rv.as_pathname: %s"%rv.as_pathname())
722 rv = AskFolder()
723 Message("Folder name: %s"%rv)
Jack Jansen911e87d2001-08-27 15:24:07 +0000724 text = ( "Working Hard...", "Hardly Working..." ,
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000725 "So far, so good!", "Keep on truckin'" )
Jack Jansen911e87d2001-08-27 15:24:07 +0000726 bar = ProgressBar("Progress, progress...", 0, label="Ramping up...")
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000727 try:
Jack Janseneb308432001-09-09 00:36:01 +0000728 if hasattr(MacOS, 'SchedParams'):
729 appsw = MacOS.SchedParams(1, 0)
Jack Jansen911e87d2001-08-27 15:24:07 +0000730 for i in xrange(20):
731 bar.inc()
732 time.sleep(0.05)
733 bar.set(0,100)
734 for i in xrange(100):
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000735 bar.set(i)
Jack Jansen911e87d2001-08-27 15:24:07 +0000736 time.sleep(0.05)
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000737 if i % 10 == 0:
738 bar.label(text[(i/10) % 4])
739 bar.label("Done.")
Jack Jansen911e87d2001-08-27 15:24:07 +0000740 time.sleep(1.0) # give'em a chance to see "Done."
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000741 finally:
742 del bar
Jack Janseneb308432001-09-09 00:36:01 +0000743 if hasattr(MacOS, 'SchedParams'):
744 apply(MacOS.SchedParams, appsw)
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000745
Guido van Rossum8f4b6ad1995-04-05 09:18:35 +0000746if __name__ == '__main__':
Jack Jansen1d63d8c1997-05-12 15:44:14 +0000747 try:
748 test()
749 except KeyboardInterrupt:
750 Message("Operation Canceled.")
751