1 """Easy to use dialogs.
3 Message(msg) -- display a message and an OK button.
4 AskString(prompt, default) -- ask for a string, display OK and Cancel buttons.
5 AskPassword(prompt, default) -- like AskString(), but shows text as bullets.
6 AskYesNoCancel(question, default) -- display a question and Yes, No and Cancel buttons.
7 GetArgv(optionlist, commandlist) -- fill a sys.argv-like list using a dialog
8 AskFileForOpen(...) -- Ask the user for an existing file
9 AskFileForSave(...) -- Ask the user for an output file
10 AskFolder(...) -- Ask the user to select a folder
11 bar = Progress(label, maxvalue) -- Display a progress bar
12 bar.set(value) -- Set value
13 bar.inc( *amount ) -- increment value by amount (default=1)
14 bar.label( *newlabel ) -- get or set text label.
16 More documentation in each function.
17 This module uses DLOG resources 260 and on.
18 Based upon STDWIN dialogs with the same names and functions.
21 from Carbon
.Dlg
import GetNewDialog
, SetDialogItemText
, GetDialogItemText
, ModalDialog
23 from Carbon
import QuickDraw
24 from Carbon
import Dialogs
25 from Carbon
import Windows
26 from Carbon
import Dlg
,Win
,Evt
,Events
# sdm7g
27 from Carbon
import Ctl
28 from Carbon
import Controls
29 from Carbon
import Menu
34 from Carbon
.ControlAccessor
import * # Also import Controls constants
40 __all__
= ['Message', 'AskString', 'AskPassword', 'AskYesNoCancel',
41 'GetArgv', 'AskFileForOpen', 'AskFileForSave', 'AskFolder',
48 if _initialized
: return
49 macresource
.need("DLOG", 260, "dialogs.rsrc", __name__
)
52 """Make sure the application is in the foreground"""
53 AE
.AEInteractWithUser(50000000)
57 text
= string
.join(string
.split(text
, '\r'), '\n')
62 text
= string
.join(string
.split(text
, '\n'), '\r')
64 text
= text
[:253] + '\311'
67 def Message(msg
, id=260, ok
=None):
68 """Display a MESSAGE string.
70 Return when the user clicks the OK button or presses Return.
72 The MESSAGE string can be at most 255 characters long.
76 d
= GetNewDialog(id, -1)
78 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
80 h
= d
.GetDialogItemAsControl(2)
81 SetDialogItemText(h
, lf2cr(msg
))
83 h
= d
.GetDialogItemAsControl(1)
85 d
.SetDialogDefaultItem(1)
87 d
.GetDialogWindow().ShowWindow()
94 def AskString(prompt
, default
= "", id=261, ok
=None, cancel
=None):
95 """Display a PROMPT string and a text entry field with a DEFAULT string.
97 Return the contents of the text entry field when the user clicks the
98 OK button or presses Return.
99 Return None when the user clicks the Cancel button.
101 If omitted, DEFAULT is empty.
103 The PROMPT and DEFAULT strings, as well as the return value,
104 can be at most 255 characters long.
109 d
= GetNewDialog(id, -1)
111 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
113 h
= d
.GetDialogItemAsControl(3)
114 SetDialogItemText(h
, lf2cr(prompt
))
115 h
= d
.GetDialogItemAsControl(4)
116 SetDialogItemText(h
, lf2cr(default
))
117 d
.SelectDialogItemText(4, 0, 999)
118 # d.SetDialogItem(4, 0, 255)
120 h
= d
.GetDialogItemAsControl(1)
121 h
.SetControlTitle(ok
)
123 h
= d
.GetDialogItemAsControl(2)
124 h
.SetControlTitle(cancel
)
125 d
.SetDialogDefaultItem(1)
126 d
.SetDialogCancelItem(2)
128 d
.GetDialogWindow().ShowWindow()
130 n
= ModalDialog(None)
132 h
= d
.GetDialogItemAsControl(4)
133 return cr2lf(GetDialogItemText(h
))
134 if n
== 2: return None
136 def AskPassword(prompt
, default
='', id=264, ok
=None, cancel
=None):
137 """Display a PROMPT string and a text entry field with a DEFAULT string.
138 The string is displayed as bullets only.
140 Return the contents of the text entry field when the user clicks the
141 OK button or presses Return.
142 Return None when the user clicks the Cancel button.
144 If omitted, DEFAULT is empty.
146 The PROMPT and DEFAULT strings, as well as the return value,
147 can be at most 255 characters long.
151 d
= GetNewDialog(id, -1)
153 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
155 h
= d
.GetDialogItemAsControl(3)
156 SetDialogItemText(h
, lf2cr(prompt
))
157 pwd
= d
.GetDialogItemAsControl(4)
158 bullets
= '\245'*len(default
)
159 ## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets)
160 SetControlData(pwd
, kControlEditTextPart
, kControlEditTextPasswordTag
, default
)
161 d
.SelectDialogItemText(4, 0, 999)
162 Ctl
.SetKeyboardFocus(d
.GetDialogWindow(), pwd
, kControlEditTextPart
)
164 h
= d
.GetDialogItemAsControl(1)
165 h
.SetControlTitle(ok
)
167 h
= d
.GetDialogItemAsControl(2)
168 h
.SetControlTitle(cancel
)
169 d
.SetDialogDefaultItem(Dialogs
.ok
)
170 d
.SetDialogCancelItem(Dialogs
.cancel
)
172 d
.GetDialogWindow().ShowWindow()
174 n
= ModalDialog(None)
176 h
= d
.GetDialogItemAsControl(4)
177 return cr2lf(GetControlData(pwd
, kControlEditTextPart
, kControlEditTextPasswordTag
))
178 if n
== 2: return None
180 def AskYesNoCancel(question
, default
= 0, yes
=None, no
=None, cancel
=None, id=262):
181 """Display a QUESTION string which can be answered with Yes or No.
183 Return 1 when the user clicks the Yes button.
184 Return 0 when the user clicks the No button.
185 Return -1 when the user clicks the Cancel button.
187 When the user presses Return, the DEFAULT value is returned.
188 If omitted, this is 0 (No).
190 The QUESTION string can be at most 255 characters.
195 d
= GetNewDialog(id, -1)
197 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
199 # Button assignments:
200 # 1 = default (invisible)
204 # The question string is item 5
205 h
= d
.GetDialogItemAsControl(5)
206 SetDialogItemText(h
, lf2cr(question
))
211 h
= d
.GetDialogItemAsControl(2)
212 h
.SetControlTitle(yes
)
217 h
= d
.GetDialogItemAsControl(3)
218 h
.SetControlTitle(no
)
223 h
= d
.GetDialogItemAsControl(4)
224 h
.SetControlTitle(cancel
)
225 d
.SetDialogCancelItem(4)
227 d
.SetDialogDefaultItem(2)
229 d
.SetDialogDefaultItem(3)
231 d
.SetDialogDefaultItem(4)
233 d
.GetDialogWindow().ShowWindow()
235 n
= ModalDialog(None)
236 if n
== 1: return default
244 screenbounds
= Qd
.GetQDGlobalsScreenBits().bounds
245 screenbounds
= screenbounds
[0]+4, screenbounds
[1]+4, \
246 screenbounds
[2]-4, screenbounds
[3]-4
248 kControlProgressBarIndeterminateTag
= 'inde' # from Controls.py
252 def __init__(self
, title
="Working...", maxval
=0, label
="", id=263):
256 self
.d
= GetNewDialog(id, -1)
257 self
.w
= self
.d
.GetDialogWindow()
261 self
.d
.AutoSizeDialog()
267 self
.w
.BringToFront()
272 def title(self
, newstr
=""):
273 """title(text) - Set title of progress window"""
274 self
.w
.BringToFront()
275 self
.w
.SetWTitle(newstr
)
277 def label(self
, *newstr
):
278 """label(text) - Set text in progress box"""
279 self
.w
.BringToFront()
281 self
._label
= lf2cr(newstr
[0])
282 text_h
= self
.d
.GetDialogItemAsControl(2)
283 SetDialogItemText(text_h
, self
._label
)
285 def _update(self
, value
):
287 if maxval
== 0: # an indeterminate bar
288 Ctl
.IdleControls(self
.w
) # spin the barber pole
289 else: # a determinate bar
291 value
= int(value
/(maxval
/32767.0))
295 progbar
= self
.d
.GetDialogItemAsControl(3)
296 progbar
.SetControlMaximum(maxval
)
297 progbar
.SetControlValue(value
) # set the bar length
299 # Test for cancel button
300 ready
, ev
= Evt
.WaitNextEvent( Events
.mDownMask
, 1 )
302 what
,msg
,when
,where
,mod
= ev
303 part
= Win
.FindWindow(where
)[0]
304 if Dlg
.IsDialogEvent(ev
):
305 ds
= Dlg
.DialogSelect(ev
)
306 if ds
[0] and ds
[1] == self
.d
and ds
[-1] == 1:
310 raise KeyboardInterrupt, ev
312 if part
== 4: # inDrag
313 self
.w
.DragWindow(where
, screenbounds
)
315 MacOS
.HandleEvent(ev
)
318 def set(self
, value
, max=None):
319 """set(value) - Set progress bar position"""
322 bar
= self
.d
.GetDialogItemAsControl(3)
323 if max <= 0: # indeterminate bar
324 bar
.SetControlData(0,kControlProgressBarIndeterminateTag
,'\x01')
325 else: # determinate bar
326 bar
.SetControlData(0,kControlProgressBarIndeterminateTag
,'\x00')
329 elif value
> self
.maxval
:
335 """inc(amt) - Increment progress bar position"""
336 self
.set(self
.curval
+ n
)
342 ARGV_OPTION_EXPLAIN
=4
346 ARGV_COMMAND_EXPLAIN
=8
351 ARGV_CMDLINE_GROUP
=13
354 ##def _myModalDialog(d):
356 ## ready, ev = Evt.WaitNextEvent(0xffff, -1)
357 ## print 'DBG: WNE', ready, ev
359 ## what,msg,when,where,mod = ev
360 ## part, window = Win.FindWindow(where)
361 ## if Dlg.IsDialogEvent(ev):
362 ## didit, dlgdone, itemdone = Dlg.DialogSelect(ev)
363 ## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d
364 ## if didit and dlgdone == d:
366 ## elif window == d.GetDialogWindow():
367 ## d.GetDialogWindow().SelectWindow()
368 ## if part == 4: # inDrag
369 ## d.DragWindow(where, screenbounds)
371 ## MacOS.HandleEvent(ev)
373 ## MacOS.HandleEvent(ev)
375 def _setmenu(control
, items
):
376 mhandle
= control
.GetControlData_Handle(Controls
.kControlMenuPart
,
377 Controls
.kControlPopupButtonMenuHandleTag
)
378 menu
= Menu
.as_Menu(mhandle
)
380 if type(item
) == type(()):
384 if label
[-1] == '=' or label
[-1] == ':':
386 menu
.AppendMenu(label
)
387 ## mhandle, mid = menu.getpopupinfo()
388 ## control.SetControlData_Handle(Controls.kControlMenuPart,
389 ## Controls.kControlPopupButtonMenuHandleTag, mhandle)
390 control
.SetControlMinimum(1)
391 control
.SetControlMaximum(len(items
)+1)
393 def _selectoption(d
, optionlist
, idx
):
394 if idx
< 0 or idx
>= len(optionlist
):
397 option
= optionlist
[idx
]
398 if type(option
) == type(()):
401 elif len(option
) > 1:
407 h
= d
.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN
)
408 if help and len(help) > 250:
409 help = help[:250] + '...'
410 Dlg
.SetDialogItemText(h
, help)
412 if type(option
) == type(()):
416 if label
[-1] == '=' or label
[-1] == ':':
418 h
= d
.GetDialogItemAsControl(ARGV_OPTION_VALUE
)
419 Dlg
.SetDialogItemText(h
, '')
421 d
.ShowDialogItem(ARGV_OPTION_VALUE
)
422 d
.SelectDialogItemText(ARGV_OPTION_VALUE
, 0, 0)
424 d
.HideDialogItem(ARGV_OPTION_VALUE
)
427 def GetArgv(optionlist
=None, commandlist
=None, addoldfile
=1, addnewfile
=1, addfolder
=1, id=ARGV_ID
):
430 d
= GetNewDialog(id, -1)
432 print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
434 # h = d.GetDialogItemAsControl(3)
435 # SetDialogItemText(h, lf2cr(prompt))
436 # h = d.GetDialogItemAsControl(4)
437 # SetDialogItemText(h, lf2cr(default))
438 # d.SelectDialogItemText(4, 0, 999)
439 # d.SetDialogItem(4, 0, 255)
441 _setmenu(d
.GetDialogItemAsControl(ARGV_OPTION_GROUP
), optionlist
)
442 _selectoption(d
, optionlist
, 0)
444 d
.GetDialogItemAsControl(ARGV_OPTION_GROUP
).DeactivateControl()
446 _setmenu(d
.GetDialogItemAsControl(ARGV_COMMAND_GROUP
), commandlist
)
447 if type(commandlist
[0]) == type(()) and len(commandlist
[0]) > 1:
448 help = commandlist
[0][-1]
449 h
= d
.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN
)
450 Dlg
.SetDialogItemText(h
, help)
452 d
.GetDialogItemAsControl(ARGV_COMMAND_GROUP
).DeactivateControl()
454 d
.GetDialogItemAsControl(ARGV_ADD_OLDFILE
).DeactivateControl()
456 d
.GetDialogItemAsControl(ARGV_ADD_NEWFILE
).DeactivateControl()
458 d
.GetDialogItemAsControl(ARGV_ADD_FOLDER
).DeactivateControl()
459 d
.SetDialogDefaultItem(ARGV_ITEM_OK
)
460 d
.SetDialogCancelItem(ARGV_ITEM_CANCEL
)
461 d
.GetDialogWindow().ShowWindow()
463 if hasattr(MacOS
, 'SchedParams'):
464 appsw
= MacOS
.SchedParams(1, 0)
468 n
= ModalDialog(None)
469 if n
== ARGV_ITEM_OK
:
471 elif n
== ARGV_ITEM_CANCEL
:
473 elif n
== ARGV_OPTION_GROUP
:
474 idx
= d
.GetDialogItemAsControl(ARGV_OPTION_GROUP
).GetControlValue()-1
475 _selectoption(d
, optionlist
, idx
)
476 elif n
== ARGV_OPTION_VALUE
:
478 elif n
== ARGV_OPTION_ADD
:
479 idx
= d
.GetDialogItemAsControl(ARGV_OPTION_GROUP
).GetControlValue()-1
480 if 0 <= idx
< len(optionlist
):
481 option
= optionlist
[idx
]
482 if type(option
) == type(()):
484 if option
[-1] == '=' or option
[-1] == ':':
486 h
= d
.GetDialogItemAsControl(ARGV_OPTION_VALUE
)
487 value
= Dlg
.GetDialogItemText(h
)
491 stringtoadd
= '-' + option
493 stringtoadd
= '--' + option
494 stringstoadd
= [stringtoadd
]
496 stringstoadd
.append(value
)
499 elif n
== ARGV_COMMAND_GROUP
:
500 idx
= d
.GetDialogItemAsControl(ARGV_COMMAND_GROUP
).GetControlValue()-1
501 if 0 <= idx
< len(commandlist
) and type(commandlist
[idx
]) == type(()) and \
502 len(commandlist
[idx
]) > 1:
503 help = commandlist
[idx
][-1]
504 h
= d
.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN
)
505 Dlg
.SetDialogItemText(h
, help)
506 elif n
== ARGV_COMMAND_ADD
:
507 idx
= d
.GetDialogItemAsControl(ARGV_COMMAND_GROUP
).GetControlValue()-1
508 if 0 <= idx
< len(commandlist
):
509 command
= commandlist
[idx
]
510 if type(command
) == type(()):
512 stringstoadd
= [command
]
515 elif n
== ARGV_ADD_OLDFILE
:
516 pathname
= AskFileForOpen()
518 stringstoadd
= [pathname
]
519 elif n
== ARGV_ADD_NEWFILE
:
520 pathname
= AskFileForSave()
522 stringstoadd
= [pathname
]
523 elif n
== ARGV_ADD_FOLDER
:
524 pathname
= AskFolder()
526 stringstoadd
= [pathname
]
527 elif n
== ARGV_CMDLINE_DATA
:
530 raise RuntimeError, "Unknown dialog item %d"%n
532 for stringtoadd
in stringstoadd
:
533 if '"' in stringtoadd
or "'" in stringtoadd
or " " in stringtoadd
:
534 stringtoadd
= repr(stringtoadd
)
535 h
= d
.GetDialogItemAsControl(ARGV_CMDLINE_DATA
)
536 oldstr
= GetDialogItemText(h
)
537 if oldstr
and oldstr
[-1] != ' ':
538 oldstr
= oldstr
+ ' '
539 oldstr
= oldstr
+ stringtoadd
540 if oldstr
[-1] != ' ':
541 oldstr
= oldstr
+ ' '
542 SetDialogItemText(h
, oldstr
)
543 d
.SelectDialogItemText(ARGV_CMDLINE_DATA
, 0x7fff, 0x7fff)
544 h
= d
.GetDialogItemAsControl(ARGV_CMDLINE_DATA
)
545 oldstr
= GetDialogItemText(h
)
546 tmplist
= string
.split(oldstr
)
552 while item
[-1] != '"':
554 raise RuntimeError, "Unterminated quoted argument"
555 item
= item
+ ' ' + tmplist
[0]
559 while item
[-1] != "'":
561 raise RuntimeError, "Unterminated quoted argument"
562 item
= item
+ ' ' + tmplist
[0]
568 if hasattr(MacOS
, 'SchedParams'):
569 MacOS
.SchedParams(*appsw
)
572 def _process_Nav_args(dftflags
, **args
):
576 for k
in args
.keys():
579 # Set some defaults, and modify some arguments
580 if not args
.has_key('dialogOptionFlags'):
581 args
['dialogOptionFlags'] = dftflags
582 if args
.has_key('defaultLocation') and \
583 not isinstance(args
['defaultLocation'], Carbon
.AE
.AEDesc
):
584 defaultLocation
= args
['defaultLocation']
585 if isinstance(defaultLocation
, (Carbon
.File
.FSSpec
, Carbon
.File
.FSRef
)):
586 args
['defaultLocation'] = aepack
.pack(defaultLocation
)
588 defaultLocation
= Carbon
.File
.FSRef(defaultLocation
)
589 args
['defaultLocation'] = aepack
.pack(defaultLocation
)
590 if args
.has_key('typeList') and not isinstance(args
['typeList'], Carbon
.Res
.ResourceType
):
591 typeList
= args
['typeList'][:]
592 # Workaround for OSX typeless files:
593 if 'TEXT' in typeList
and not '\0\0\0\0' in typeList
:
594 typeList
= typeList
+ ('\0\0\0\0',)
595 data
= 'Pyth' + struct
.pack("hh", 0, len(typeList
))
596 for type in typeList
:
598 args
['typeList'] = Carbon
.Res
.Handle(data
)
600 if args
.has_key('wanted'):
601 tpwanted
= args
['wanted']
603 return args
, tpwanted
605 def _dummy_Nav_eventproc(msg
, data
):
608 _default_Nav_eventproc
= _dummy_Nav_eventproc
610 def SetDefaultEventProc(proc
):
611 global _default_Nav_eventproc
612 rv
= _default_Nav_eventproc
614 proc
= _dummy_Nav_eventproc
615 _default_Nav_eventproc
= proc
621 # From here on the order is not documented
623 defaultLocation
=None,
624 dialogOptionFlags
=None,
628 actionButtonLabel
=None,
629 cancelButtonLabel
=None,
632 eventProc
=_dummy_Nav_eventproc
,
637 """Display a dialog asking the user for a file to open.
639 wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
640 the other arguments can be looked up in Apple's Navigation Services documentation"""
642 default_flags
= 0x56 # Or 0xe4?
643 args
, tpwanted
= _process_Nav_args(default_flags
, version
=version
,
644 defaultLocation
=defaultLocation
, dialogOptionFlags
=dialogOptionFlags
,
645 location
=location
,clientName
=clientName
,windowTitle
=windowTitle
,
646 actionButtonLabel
=actionButtonLabel
,cancelButtonLabel
=cancelButtonLabel
,
647 message
=message
,preferenceKey
=preferenceKey
,
648 popupExtension
=popupExtension
,eventProc
=eventProc
,previewProc
=previewProc
,
649 filterProc
=filterProc
,typeList
=typeList
,wanted
=wanted
,multiple
=multiple
)
652 rr
= Nav
.NavChooseFile(args
)
654 except Nav
.error
, arg
:
655 if arg
[0] != -128: # userCancelledErr
658 if not rr
.validRecord
or not rr
.selection
:
660 if issubclass(tpwanted
, Carbon
.File
.FSRef
):
661 return tpwanted(rr
.selection_fsr
[0])
662 if issubclass(tpwanted
, Carbon
.File
.FSSpec
):
663 return tpwanted(rr
.selection
[0])
664 if issubclass(tpwanted
, str):
665 return tpwanted(rr
.selection_fsr
[0].as_pathname())
666 if issubclass(tpwanted
, unicode):
667 return tpwanted(rr
.selection_fsr
[0].as_pathname(), 'utf8')
668 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted
)
673 # From here on the order is not documented
675 defaultLocation
=None,
676 dialogOptionFlags
=None,
680 actionButtonLabel
=None,
681 cancelButtonLabel
=None,
684 eventProc
=_dummy_Nav_eventproc
,
689 """Display a dialog asking the user for a filename to save to.
691 wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
692 the other arguments can be looked up in Apple's Navigation Services documentation"""
696 args
, tpwanted
= _process_Nav_args(default_flags
, version
=version
,
697 defaultLocation
=defaultLocation
, dialogOptionFlags
=dialogOptionFlags
,
698 location
=location
,clientName
=clientName
,windowTitle
=windowTitle
,
699 actionButtonLabel
=actionButtonLabel
,cancelButtonLabel
=cancelButtonLabel
,
700 savedFileName
=savedFileName
,message
=message
,preferenceKey
=preferenceKey
,
701 popupExtension
=popupExtension
,eventProc
=eventProc
,fileType
=fileType
,
702 fileCreator
=fileCreator
,wanted
=wanted
,multiple
=multiple
)
705 rr
= Nav
.NavPutFile(args
)
707 except Nav
.error
, arg
:
708 if arg
[0] != -128: # userCancelledErr
711 if not rr
.validRecord
or not rr
.selection
:
713 if issubclass(tpwanted
, Carbon
.File
.FSRef
):
714 raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave"
715 if issubclass(tpwanted
, Carbon
.File
.FSSpec
):
716 return tpwanted(rr
.selection
[0])
717 if issubclass(tpwanted
, (str, unicode)):
718 if sys
.platform
== 'mac':
719 fullpath
= rr
.selection
[0].as_pathname()
721 # This is gross, and probably incorrect too
722 vrefnum
, dirid
, name
= rr
.selection
[0].as_tuple()
723 pardir_fss
= Carbon
.File
.FSSpec((vrefnum
, dirid
, ''))
724 pardir_fsr
= Carbon
.File
.FSRef(pardir_fss
)
725 pardir_path
= pardir_fsr
.FSRefMakePath() # This is utf-8
726 name_utf8
= unicode(name
, 'macroman').encode('utf8')
727 fullpath
= os
.path
.join(pardir_path
, name_utf8
)
728 if issubclass(tpwanted
, unicode):
729 return unicode(fullpath
, 'utf8')
730 return tpwanted(fullpath
)
731 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted
)
735 # From here on the order is not documented
737 defaultLocation
=None,
738 dialogOptionFlags
=None,
742 actionButtonLabel
=None,
743 cancelButtonLabel
=None,
746 eventProc
=_dummy_Nav_eventproc
,
750 """Display a dialog asking the user for select a folder.
752 wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
753 the other arguments can be looked up in Apple's Navigation Services documentation"""
756 args
, tpwanted
= _process_Nav_args(default_flags
, version
=version
,
757 defaultLocation
=defaultLocation
, dialogOptionFlags
=dialogOptionFlags
,
758 location
=location
,clientName
=clientName
,windowTitle
=windowTitle
,
759 actionButtonLabel
=actionButtonLabel
,cancelButtonLabel
=cancelButtonLabel
,
760 message
=message
,preferenceKey
=preferenceKey
,
761 popupExtension
=popupExtension
,eventProc
=eventProc
,filterProc
=filterProc
,
762 wanted
=wanted
,multiple
=multiple
)
765 rr
= Nav
.NavChooseFolder(args
)
767 except Nav
.error
, arg
:
768 if arg
[0] != -128: # userCancelledErr
771 if not rr
.validRecord
or not rr
.selection
:
773 if issubclass(tpwanted
, Carbon
.File
.FSRef
):
774 return tpwanted(rr
.selection_fsr
[0])
775 if issubclass(tpwanted
, Carbon
.File
.FSSpec
):
776 return tpwanted(rr
.selection
[0])
777 if issubclass(tpwanted
, str):
778 return tpwanted(rr
.selection_fsr
[0].as_pathname())
779 if issubclass(tpwanted
, unicode):
780 return tpwanted(rr
.selection_fsr
[0].as_pathname(), 'utf8')
781 raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted
)
787 Message("Testing EasyDialogs.")
788 optionlist
= (('v', 'Verbose'), ('verbose', 'Verbose as long option'),
789 ('flags=', 'Valued option'), ('f:', 'Short valued option'))
790 commandlist
= (('start', 'Start something'), ('stop', 'Stop something'))
791 argv
= GetArgv(optionlist
=optionlist
, commandlist
=commandlist
, addoldfile
=0)
792 Message("Command line: %s"%' '.join(argv
))
793 for i
in range(len(argv
)):
794 print 'arg[%d] = %r' % (i
, argv
[i
])
795 ok
= AskYesNoCancel("Do you want to proceed?")
796 ok
= AskYesNoCancel("Do you want to identify?", yes
="Identify", no
="No")
798 s
= AskString("Enter your first name", "Joe")
799 s2
= AskPassword("Okay %s, tell us your nickname"%s, s
, cancel
="None")
801 Message("%s has no secret nickname"%s)
803 Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s
, s2
))
806 rv
= AskFileForOpen(message
="Gimme a file, %s"%s, wanted
=Carbon
.File
.FSSpec
)
808 rv
= AskFileForSave(wanted
=Carbon
.File
.FSRef
, savedFileName
="%s.txt"%s)
809 Message("rv.as_pathname: %s"%rv
.as_pathname())
811 Message("Folder name: %s"%rv
)
812 text
= ( "Working Hard...", "Hardly Working..." ,
813 "So far, so good!", "Keep on truckin'" )
814 bar
= ProgressBar("Progress, progress...", 0, label
="Ramping up...")
816 if hasattr(MacOS
, 'SchedParams'):
817 appsw
= MacOS
.SchedParams(1, 0)
822 for i
in xrange(100):
826 bar
.label(text
[(i
/10) % 4])
828 time
.sleep(1.0) # give'em a chance to see "Done."
831 if hasattr(MacOS
, 'SchedParams'):
832 MacOS
.SchedParams(*appsw
)
834 if __name__
== '__main__':
837 except KeyboardInterrupt:
838 Message("Operation Canceled.")