PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/plat-mac/EasyDialogs.py

https://bitbucket.org/dac_io/pypy
Python | 841 lines | 803 code | 12 blank | 26 comment | 18 complexity | 6e7618f3e14e116d7acd3b5ce0594000 MD5 | raw file
  1. """Easy to use dialogs.
  2. Message(msg) -- display a message and an OK button.
  3. AskString(prompt, default) -- ask for a string, display OK and Cancel buttons.
  4. AskPassword(prompt, default) -- like AskString(), but shows text as bullets.
  5. AskYesNoCancel(question, default) -- display a question and Yes, No and Cancel buttons.
  6. GetArgv(optionlist, commandlist) -- fill a sys.argv-like list using a dialog
  7. AskFileForOpen(...) -- Ask the user for an existing file
  8. AskFileForSave(...) -- Ask the user for an output file
  9. AskFolder(...) -- Ask the user to select a folder
  10. bar = Progress(label, maxvalue) -- Display a progress bar
  11. bar.set(value) -- Set value
  12. bar.inc( *amount ) -- increment value by amount (default=1)
  13. bar.label( *newlabel ) -- get or set text label.
  14. More documentation in each function.
  15. This module uses DLOG resources 260 and on.
  16. Based upon STDWIN dialogs with the same names and functions.
  17. """
  18. from warnings import warnpy3k
  19. warnpy3k("In 3.x, the EasyDialogs module is removed.", stacklevel=2)
  20. from Carbon.Dlg import GetNewDialog, SetDialogItemText, GetDialogItemText, ModalDialog
  21. from Carbon import Qd
  22. from Carbon import QuickDraw
  23. from Carbon import Dialogs
  24. from Carbon import Windows
  25. from Carbon import Dlg,Win,Evt,Events # sdm7g
  26. from Carbon import Ctl
  27. from Carbon import Controls
  28. from Carbon import Menu
  29. from Carbon import AE
  30. import Nav
  31. import MacOS
  32. import string
  33. from Carbon.ControlAccessor import * # Also import Controls constants
  34. import Carbon.File
  35. import macresource
  36. import os
  37. import sys
  38. __all__ = ['Message', 'AskString', 'AskPassword', 'AskYesNoCancel',
  39. 'GetArgv', 'AskFileForOpen', 'AskFileForSave', 'AskFolder',
  40. 'ProgressBar']
  41. _initialized = 0
  42. def _initialize():
  43. global _initialized
  44. if _initialized: return
  45. macresource.need("DLOG", 260, "dialogs.rsrc", __name__)
  46. def _interact():
  47. """Make sure the application is in the foreground"""
  48. AE.AEInteractWithUser(50000000)
  49. def cr2lf(text):
  50. if '\r' in text:
  51. text = string.join(string.split(text, '\r'), '\n')
  52. return text
  53. def lf2cr(text):
  54. if '\n' in text:
  55. text = string.join(string.split(text, '\n'), '\r')
  56. if len(text) > 253:
  57. text = text[:253] + '\311'
  58. return text
  59. def Message(msg, id=260, ok=None):
  60. """Display a MESSAGE string.
  61. Return when the user clicks the OK button or presses Return.
  62. The MESSAGE string can be at most 255 characters long.
  63. """
  64. _initialize()
  65. _interact()
  66. d = GetNewDialog(id, -1)
  67. if not d:
  68. print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
  69. return
  70. h = d.GetDialogItemAsControl(2)
  71. SetDialogItemText(h, lf2cr(msg))
  72. if ok is not None:
  73. h = d.GetDialogItemAsControl(1)
  74. h.SetControlTitle(ok)
  75. d.SetDialogDefaultItem(1)
  76. d.AutoSizeDialog()
  77. d.GetDialogWindow().ShowWindow()
  78. while 1:
  79. n = ModalDialog(None)
  80. if n == 1:
  81. return
  82. def AskString(prompt, default = "", id=261, ok=None, cancel=None):
  83. """Display a PROMPT string and a text entry field with a DEFAULT string.
  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. If omitted, DEFAULT is empty.
  88. The PROMPT and DEFAULT strings, as well as the return value,
  89. can be at most 255 characters long.
  90. """
  91. _initialize()
  92. _interact()
  93. d = GetNewDialog(id, -1)
  94. if not d:
  95. print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
  96. return
  97. h = d.GetDialogItemAsControl(3)
  98. SetDialogItemText(h, lf2cr(prompt))
  99. h = d.GetDialogItemAsControl(4)
  100. SetDialogItemText(h, lf2cr(default))
  101. d.SelectDialogItemText(4, 0, 999)
  102. # d.SetDialogItem(4, 0, 255)
  103. if ok is not None:
  104. h = d.GetDialogItemAsControl(1)
  105. h.SetControlTitle(ok)
  106. if cancel is not None:
  107. h = d.GetDialogItemAsControl(2)
  108. h.SetControlTitle(cancel)
  109. d.SetDialogDefaultItem(1)
  110. d.SetDialogCancelItem(2)
  111. d.AutoSizeDialog()
  112. d.GetDialogWindow().ShowWindow()
  113. while 1:
  114. n = ModalDialog(None)
  115. if n == 1:
  116. h = d.GetDialogItemAsControl(4)
  117. return cr2lf(GetDialogItemText(h))
  118. if n == 2: return None
  119. def AskPassword(prompt, default='', id=264, ok=None, cancel=None):
  120. """Display a PROMPT string and a text entry field with a DEFAULT string.
  121. The string is displayed as bullets only.
  122. Return the contents of the text entry field when the user clicks the
  123. OK button or presses Return.
  124. Return None when the user clicks the Cancel button.
  125. If omitted, DEFAULT is empty.
  126. The PROMPT and DEFAULT strings, as well as the return value,
  127. can be at most 255 characters long.
  128. """
  129. _initialize()
  130. _interact()
  131. d = GetNewDialog(id, -1)
  132. if not d:
  133. print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
  134. return
  135. h = d.GetDialogItemAsControl(3)
  136. SetDialogItemText(h, lf2cr(prompt))
  137. pwd = d.GetDialogItemAsControl(4)
  138. bullets = '\245'*len(default)
  139. ## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets)
  140. SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default)
  141. d.SelectDialogItemText(4, 0, 999)
  142. Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart)
  143. if ok is not None:
  144. h = d.GetDialogItemAsControl(1)
  145. h.SetControlTitle(ok)
  146. if cancel is not None:
  147. h = d.GetDialogItemAsControl(2)
  148. h.SetControlTitle(cancel)
  149. d.SetDialogDefaultItem(Dialogs.ok)
  150. d.SetDialogCancelItem(Dialogs.cancel)
  151. d.AutoSizeDialog()
  152. d.GetDialogWindow().ShowWindow()
  153. while 1:
  154. n = ModalDialog(None)
  155. if n == 1:
  156. h = d.GetDialogItemAsControl(4)
  157. return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag))
  158. if n == 2: return None
  159. def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262):
  160. """Display a QUESTION string which can be answered with Yes or No.
  161. Return 1 when the user clicks the Yes button.
  162. Return 0 when the user clicks the No button.
  163. Return -1 when the user clicks the Cancel button.
  164. When the user presses Return, the DEFAULT value is returned.
  165. If omitted, this is 0 (No).
  166. The QUESTION string can be at most 255 characters.
  167. """
  168. _initialize()
  169. _interact()
  170. d = GetNewDialog(id, -1)
  171. if not d:
  172. print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
  173. return
  174. # Button assignments:
  175. # 1 = default (invisible)
  176. # 2 = Yes
  177. # 3 = No
  178. # 4 = Cancel
  179. # The question string is item 5
  180. h = d.GetDialogItemAsControl(5)
  181. SetDialogItemText(h, lf2cr(question))
  182. if yes is not None:
  183. if yes == '':
  184. d.HideDialogItem(2)
  185. else:
  186. h = d.GetDialogItemAsControl(2)
  187. h.SetControlTitle(yes)
  188. if no is not None:
  189. if no == '':
  190. d.HideDialogItem(3)
  191. else:
  192. h = d.GetDialogItemAsControl(3)
  193. h.SetControlTitle(no)
  194. if cancel is not None:
  195. if cancel == '':
  196. d.HideDialogItem(4)
  197. else:
  198. h = d.GetDialogItemAsControl(4)
  199. h.SetControlTitle(cancel)
  200. d.SetDialogCancelItem(4)
  201. if default == 1:
  202. d.SetDialogDefaultItem(2)
  203. elif default == 0:
  204. d.SetDialogDefaultItem(3)
  205. elif default == -1:
  206. d.SetDialogDefaultItem(4)
  207. d.AutoSizeDialog()
  208. d.GetDialogWindow().ShowWindow()
  209. while 1:
  210. n = ModalDialog(None)
  211. if n == 1: return default
  212. if n == 2: return 1
  213. if n == 3: return 0
  214. if n == 4: return -1
  215. screenbounds = Qd.GetQDGlobalsScreenBits().bounds
  216. screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
  217. screenbounds[2]-4, screenbounds[3]-4
  218. kControlProgressBarIndeterminateTag = 'inde' # from Controls.py
  219. class ProgressBar:
  220. def __init__(self, title="Working...", maxval=0, label="", id=263):
  221. self.w = None
  222. self.d = None
  223. _initialize()
  224. self.d = GetNewDialog(id, -1)
  225. self.w = self.d.GetDialogWindow()
  226. self.label(label)
  227. self.title(title)
  228. self.set(0, maxval)
  229. self.d.AutoSizeDialog()
  230. self.w.ShowWindow()
  231. self.d.DrawDialog()
  232. def __del__(self):
  233. if self.w:
  234. self.w.BringToFront()
  235. self.w.HideWindow()
  236. del self.w
  237. del self.d
  238. def title(self, newstr=""):
  239. """title(text) - Set title of progress window"""
  240. self.w.BringToFront()
  241. self.w.SetWTitle(newstr)
  242. def label(self, *newstr):
  243. """label(text) - Set text in progress box"""
  244. self.w.BringToFront()
  245. if newstr:
  246. self._label = lf2cr(newstr[0])
  247. text_h = self.d.GetDialogItemAsControl(2)
  248. SetDialogItemText(text_h, self._label)
  249. def _update(self, value):
  250. maxval = self.maxval
  251. if maxval == 0: # an indeterminate bar
  252. Ctl.IdleControls(self.w) # spin the barber pole
  253. else: # a determinate bar
  254. if maxval > 32767:
  255. value = int(value/(maxval/32767.0))
  256. maxval = 32767
  257. maxval = int(maxval)
  258. value = int(value)
  259. progbar = self.d.GetDialogItemAsControl(3)
  260. progbar.SetControlMaximum(maxval)
  261. progbar.SetControlValue(value) # set the bar length
  262. # Test for cancel button
  263. ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 )
  264. if ready :
  265. what,msg,when,where,mod = ev
  266. part = Win.FindWindow(where)[0]
  267. if Dlg.IsDialogEvent(ev):
  268. ds = Dlg.DialogSelect(ev)
  269. if ds[0] and ds[1] == self.d and ds[-1] == 1:
  270. self.w.HideWindow()
  271. self.w = None
  272. self.d = None
  273. raise KeyboardInterrupt, ev
  274. else:
  275. if part == 4: # inDrag
  276. self.w.DragWindow(where, screenbounds)
  277. else:
  278. MacOS.HandleEvent(ev)
  279. def set(self, value, max=None):
  280. """set(value) - Set progress bar position"""
  281. if max is not None:
  282. self.maxval = max
  283. bar = self.d.GetDialogItemAsControl(3)
  284. if max <= 0: # indeterminate bar
  285. bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01')
  286. else: # determinate bar
  287. bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00')
  288. if value < 0:
  289. value = 0
  290. elif value > self.maxval:
  291. value = self.maxval
  292. self.curval = value
  293. self._update(value)
  294. def inc(self, n=1):
  295. """inc(amt) - Increment progress bar position"""
  296. self.set(self.curval + n)
  297. ARGV_ID=265
  298. ARGV_ITEM_OK=1
  299. ARGV_ITEM_CANCEL=2
  300. ARGV_OPTION_GROUP=3
  301. ARGV_OPTION_EXPLAIN=4
  302. ARGV_OPTION_VALUE=5
  303. ARGV_OPTION_ADD=6
  304. ARGV_COMMAND_GROUP=7
  305. ARGV_COMMAND_EXPLAIN=8
  306. ARGV_COMMAND_ADD=9
  307. ARGV_ADD_OLDFILE=10
  308. ARGV_ADD_NEWFILE=11
  309. ARGV_ADD_FOLDER=12
  310. ARGV_CMDLINE_GROUP=13
  311. ARGV_CMDLINE_DATA=14
  312. ##def _myModalDialog(d):
  313. ## while 1:
  314. ## ready, ev = Evt.WaitNextEvent(0xffff, -1)
  315. ## print 'DBG: WNE', ready, ev
  316. ## if ready :
  317. ## what,msg,when,where,mod = ev
  318. ## part, window = Win.FindWindow(where)
  319. ## if Dlg.IsDialogEvent(ev):
  320. ## didit, dlgdone, itemdone = Dlg.DialogSelect(ev)
  321. ## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d
  322. ## if didit and dlgdone == d:
  323. ## return itemdone
  324. ## elif window == d.GetDialogWindow():
  325. ## d.GetDialogWindow().SelectWindow()
  326. ## if part == 4: # inDrag
  327. ## d.DragWindow(where, screenbounds)
  328. ## else:
  329. ## MacOS.HandleEvent(ev)
  330. ## else:
  331. ## MacOS.HandleEvent(ev)
  332. ##
  333. def _setmenu(control, items):
  334. mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
  335. Controls.kControlPopupButtonMenuHandleTag)
  336. menu = Menu.as_Menu(mhandle)
  337. for item in items:
  338. if type(item) == type(()):
  339. label = item[0]
  340. else:
  341. label = item
  342. if label[-1] == '=' or label[-1] == ':':
  343. label = label[:-1]
  344. menu.AppendMenu(label)
  345. ## mhandle, mid = menu.getpopupinfo()
  346. ## control.SetControlData_Handle(Controls.kControlMenuPart,
  347. ## Controls.kControlPopupButtonMenuHandleTag, mhandle)
  348. control.SetControlMinimum(1)
  349. control.SetControlMaximum(len(items)+1)
  350. def _selectoption(d, optionlist, idx):
  351. if idx < 0 or idx >= len(optionlist):
  352. MacOS.SysBeep()
  353. return
  354. option = optionlist[idx]
  355. if type(option) == type(()):
  356. if len(option) == 4:
  357. help = option[2]
  358. elif len(option) > 1:
  359. help = option[-1]
  360. else:
  361. help = ''
  362. else:
  363. help = ''
  364. h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN)
  365. if help and len(help) > 250:
  366. help = help[:250] + '...'
  367. Dlg.SetDialogItemText(h, help)
  368. hasvalue = 0
  369. if type(option) == type(()):
  370. label = option[0]
  371. else:
  372. label = option
  373. if label[-1] == '=' or label[-1] == ':':
  374. hasvalue = 1
  375. h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
  376. Dlg.SetDialogItemText(h, '')
  377. if hasvalue:
  378. d.ShowDialogItem(ARGV_OPTION_VALUE)
  379. d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0)
  380. else:
  381. d.HideDialogItem(ARGV_OPTION_VALUE)
  382. def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfolder=1, id=ARGV_ID):
  383. _initialize()
  384. _interact()
  385. d = GetNewDialog(id, -1)
  386. if not d:
  387. print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
  388. return
  389. # h = d.GetDialogItemAsControl(3)
  390. # SetDialogItemText(h, lf2cr(prompt))
  391. # h = d.GetDialogItemAsControl(4)
  392. # SetDialogItemText(h, lf2cr(default))
  393. # d.SelectDialogItemText(4, 0, 999)
  394. # d.SetDialogItem(4, 0, 255)
  395. if optionlist:
  396. _setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist)
  397. _selectoption(d, optionlist, 0)
  398. else:
  399. d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl()
  400. if commandlist:
  401. _setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist)
  402. if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1:
  403. help = commandlist[0][-1]
  404. h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
  405. Dlg.SetDialogItemText(h, help)
  406. else:
  407. d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl()
  408. if not addoldfile:
  409. d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl()
  410. if not addnewfile:
  411. d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl()
  412. if not addfolder:
  413. d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl()
  414. d.SetDialogDefaultItem(ARGV_ITEM_OK)
  415. d.SetDialogCancelItem(ARGV_ITEM_CANCEL)
  416. d.GetDialogWindow().ShowWindow()
  417. d.DrawDialog()
  418. if hasattr(MacOS, 'SchedParams'):
  419. appsw = MacOS.SchedParams(1, 0)
  420. try:
  421. while 1:
  422. stringstoadd = []
  423. n = ModalDialog(None)
  424. if n == ARGV_ITEM_OK:
  425. break
  426. elif n == ARGV_ITEM_CANCEL:
  427. raise SystemExit
  428. elif n == ARGV_OPTION_GROUP:
  429. idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
  430. _selectoption(d, optionlist, idx)
  431. elif n == ARGV_OPTION_VALUE:
  432. pass
  433. elif n == ARGV_OPTION_ADD:
  434. idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
  435. if 0 <= idx < len(optionlist):
  436. option = optionlist[idx]
  437. if type(option) == type(()):
  438. option = option[0]
  439. if option[-1] == '=' or option[-1] == ':':
  440. option = option[:-1]
  441. h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
  442. value = Dlg.GetDialogItemText(h)
  443. else:
  444. value = ''
  445. if len(option) == 1:
  446. stringtoadd = '-' + option
  447. else:
  448. stringtoadd = '--' + option
  449. stringstoadd = [stringtoadd]
  450. if value:
  451. stringstoadd.append(value)
  452. else:
  453. MacOS.SysBeep()
  454. elif n == ARGV_COMMAND_GROUP:
  455. idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
  456. if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \
  457. len(commandlist[idx]) > 1:
  458. help = commandlist[idx][-1]
  459. h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
  460. Dlg.SetDialogItemText(h, help)
  461. elif n == ARGV_COMMAND_ADD:
  462. idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
  463. if 0 <= idx < len(commandlist):
  464. command = commandlist[idx]
  465. if type(command) == type(()):
  466. command = command[0]
  467. stringstoadd = [command]
  468. else:
  469. MacOS.SysBeep()
  470. elif n == ARGV_ADD_OLDFILE:
  471. pathname = AskFileForOpen()
  472. if pathname:
  473. stringstoadd = [pathname]
  474. elif n == ARGV_ADD_NEWFILE:
  475. pathname = AskFileForSave()
  476. if pathname:
  477. stringstoadd = [pathname]
  478. elif n == ARGV_ADD_FOLDER:
  479. pathname = AskFolder()
  480. if pathname:
  481. stringstoadd = [pathname]
  482. elif n == ARGV_CMDLINE_DATA:
  483. pass # Nothing to do
  484. else:
  485. raise RuntimeError, "Unknown dialog item %d"%n
  486. for stringtoadd in stringstoadd:
  487. if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd:
  488. stringtoadd = repr(stringtoadd)
  489. h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
  490. oldstr = GetDialogItemText(h)
  491. if oldstr and oldstr[-1] != ' ':
  492. oldstr = oldstr + ' '
  493. oldstr = oldstr + stringtoadd
  494. if oldstr[-1] != ' ':
  495. oldstr = oldstr + ' '
  496. SetDialogItemText(h, oldstr)
  497. d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
  498. h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
  499. oldstr = GetDialogItemText(h)
  500. tmplist = string.split(oldstr)
  501. newlist = []
  502. while tmplist:
  503. item = tmplist[0]
  504. del tmplist[0]
  505. if item[0] == '"':
  506. while item[-1] != '"':
  507. if not tmplist:
  508. raise RuntimeError, "Unterminated quoted argument"
  509. item = item + ' ' + tmplist[0]
  510. del tmplist[0]
  511. item = item[1:-1]
  512. if item[0] == "'":
  513. while item[-1] != "'":
  514. if not tmplist:
  515. raise RuntimeError, "Unterminated quoted argument"
  516. item = item + ' ' + tmplist[0]
  517. del tmplist[0]
  518. item = item[1:-1]
  519. newlist.append(item)
  520. return newlist
  521. finally:
  522. if hasattr(MacOS, 'SchedParams'):
  523. MacOS.SchedParams(*appsw)
  524. del d
  525. def _process_Nav_args(dftflags, **args):
  526. import Carbon.AppleEvents
  527. import Carbon.AE
  528. import Carbon.File
  529. for k in args.keys():
  530. if args[k] is None:
  531. del args[k]
  532. # Set some defaults, and modify some arguments
  533. if 'dialogOptionFlags' not in args:
  534. args['dialogOptionFlags'] = dftflags
  535. if 'defaultLocation' in args and \
  536. not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
  537. defaultLocation = args['defaultLocation']
  538. if isinstance(defaultLocation, Carbon.File.FSSpec):
  539. args['defaultLocation'] = Carbon.AE.AECreateDesc(
  540. Carbon.AppleEvents.typeFSS, defaultLocation.data)
  541. else:
  542. if not isinstance(defaultLocation, Carbon.File.FSRef):
  543. defaultLocation = Carbon.File.FSRef(defaultLocation)
  544. args['defaultLocation'] = Carbon.AE.AECreateDesc(
  545. Carbon.AppleEvents.typeFSRef, defaultLocation.data)
  546. if 'typeList' in args and not isinstance(args['typeList'], Carbon.Res.ResourceType):
  547. typeList = args['typeList'][:]
  548. # Workaround for OSX typeless files:
  549. if 'TEXT' in typeList and not '\0\0\0\0' in typeList:
  550. typeList = typeList + ('\0\0\0\0',)
  551. data = 'Pyth' + struct.pack("hh", 0, len(typeList))
  552. for type in typeList:
  553. data = data+type
  554. args['typeList'] = Carbon.Res.Handle(data)
  555. tpwanted = str
  556. if 'wanted' in args:
  557. tpwanted = args['wanted']
  558. del args['wanted']
  559. return args, tpwanted
  560. def _dummy_Nav_eventproc(msg, data):
  561. pass
  562. _default_Nav_eventproc = _dummy_Nav_eventproc
  563. def SetDefaultEventProc(proc):
  564. global _default_Nav_eventproc
  565. rv = _default_Nav_eventproc
  566. if proc is None:
  567. proc = _dummy_Nav_eventproc
  568. _default_Nav_eventproc = proc
  569. return rv
  570. def AskFileForOpen(
  571. message=None,
  572. typeList=None,
  573. # From here on the order is not documented
  574. version=None,
  575. defaultLocation=None,
  576. dialogOptionFlags=None,
  577. location=None,
  578. clientName=None,
  579. windowTitle=None,
  580. actionButtonLabel=None,
  581. cancelButtonLabel=None,
  582. preferenceKey=None,
  583. popupExtension=None,
  584. eventProc=_dummy_Nav_eventproc,
  585. previewProc=None,
  586. filterProc=None,
  587. wanted=None,
  588. multiple=None):
  589. """Display a dialog asking the user for a file to open.
  590. wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
  591. the other arguments can be looked up in Apple's Navigation Services documentation"""
  592. default_flags = 0x56 # Or 0xe4?
  593. args, tpwanted = _process_Nav_args(default_flags, version=version,
  594. defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags,
  595. location=location,clientName=clientName,windowTitle=windowTitle,
  596. actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel,
  597. message=message,preferenceKey=preferenceKey,
  598. popupExtension=popupExtension,eventProc=eventProc,previewProc=previewProc,
  599. filterProc=filterProc,typeList=typeList,wanted=wanted,multiple=multiple)
  600. _interact()
  601. try:
  602. rr = Nav.NavChooseFile(args)
  603. good = 1
  604. except Nav.error, arg:
  605. if arg[0] != -128: # userCancelledErr
  606. raise Nav.error, arg
  607. return None
  608. if not rr.validRecord or not rr.selection:
  609. return None
  610. if issubclass(tpwanted, Carbon.File.FSRef):
  611. return tpwanted(rr.selection_fsr[0])
  612. if issubclass(tpwanted, Carbon.File.FSSpec):
  613. return tpwanted(rr.selection[0])
  614. if issubclass(tpwanted, str):
  615. return tpwanted(rr.selection_fsr[0].as_pathname())
  616. if issubclass(tpwanted, unicode):
  617. return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8')
  618. raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
  619. def AskFileForSave(
  620. message=None,
  621. savedFileName=None,
  622. # From here on the order is not documented
  623. version=None,
  624. defaultLocation=None,
  625. dialogOptionFlags=None,
  626. location=None,
  627. clientName=None,
  628. windowTitle=None,
  629. actionButtonLabel=None,
  630. cancelButtonLabel=None,
  631. preferenceKey=None,
  632. popupExtension=None,
  633. eventProc=_dummy_Nav_eventproc,
  634. fileType=None,
  635. fileCreator=None,
  636. wanted=None,
  637. multiple=None):
  638. """Display a dialog asking the user for a filename to save to.
  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"""
  641. default_flags = 0x07
  642. args, tpwanted = _process_Nav_args(default_flags, version=version,
  643. defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags,
  644. location=location,clientName=clientName,windowTitle=windowTitle,
  645. actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel,
  646. savedFileName=savedFileName,message=message,preferenceKey=preferenceKey,
  647. popupExtension=popupExtension,eventProc=eventProc,fileType=fileType,
  648. fileCreator=fileCreator,wanted=wanted,multiple=multiple)
  649. _interact()
  650. try:
  651. rr = Nav.NavPutFile(args)
  652. good = 1
  653. except Nav.error, arg:
  654. if arg[0] != -128: # userCancelledErr
  655. raise Nav.error, arg
  656. return None
  657. if not rr.validRecord or not rr.selection:
  658. return None
  659. if issubclass(tpwanted, Carbon.File.FSRef):
  660. raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave"
  661. if issubclass(tpwanted, Carbon.File.FSSpec):
  662. return tpwanted(rr.selection[0])
  663. if issubclass(tpwanted, (str, unicode)):
  664. # This is gross, and probably incorrect too
  665. vrefnum, dirid, name = rr.selection[0].as_tuple()
  666. pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, ''))
  667. pardir_fsr = Carbon.File.FSRef(pardir_fss)
  668. pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8
  669. name_utf8 = unicode(name, 'macroman').encode('utf8')
  670. fullpath = os.path.join(pardir_path, name_utf8)
  671. if issubclass(tpwanted, unicode):
  672. return unicode(fullpath, 'utf8')
  673. return tpwanted(fullpath)
  674. raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
  675. def AskFolder(
  676. message=None,
  677. # From here on the order is not documented
  678. version=None,
  679. defaultLocation=None,
  680. dialogOptionFlags=None,
  681. location=None,
  682. clientName=None,
  683. windowTitle=None,
  684. actionButtonLabel=None,
  685. cancelButtonLabel=None,
  686. preferenceKey=None,
  687. popupExtension=None,
  688. eventProc=_dummy_Nav_eventproc,
  689. filterProc=None,
  690. wanted=None,
  691. multiple=None):
  692. """Display a dialog asking the user for select a folder.
  693. wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
  694. the other arguments can be looked up in Apple's Navigation Services documentation"""
  695. default_flags = 0x17
  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. message=message,preferenceKey=preferenceKey,
  701. popupExtension=popupExtension,eventProc=eventProc,filterProc=filterProc,
  702. wanted=wanted,multiple=multiple)
  703. _interact()
  704. try:
  705. rr = Nav.NavChooseFolder(args)
  706. good = 1
  707. except Nav.error, arg:
  708. if arg[0] != -128: # userCancelledErr
  709. raise Nav.error, arg
  710. return None
  711. if not rr.validRecord or not rr.selection:
  712. return None
  713. if issubclass(tpwanted, Carbon.File.FSRef):
  714. return tpwanted(rr.selection_fsr[0])
  715. if issubclass(tpwanted, Carbon.File.FSSpec):
  716. return tpwanted(rr.selection[0])
  717. if issubclass(tpwanted, str):
  718. return tpwanted(rr.selection_fsr[0].as_pathname())
  719. if issubclass(tpwanted, unicode):
  720. return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8')
  721. raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
  722. def test():
  723. import time
  724. Message("Testing EasyDialogs.")
  725. optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'),
  726. ('flags=', 'Valued option'), ('f:', 'Short valued option'))
  727. commandlist = (('start', 'Start something'), ('stop', 'Stop something'))
  728. argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
  729. Message("Command line: %s"%' '.join(argv))
  730. for i in range(len(argv)):
  731. print 'arg[%d] = %r' % (i, argv[i])
  732. ok = AskYesNoCancel("Do you want to proceed?")
  733. ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
  734. if ok > 0:
  735. s = AskString("Enter your first name", "Joe")
  736. s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None")
  737. if not s2:
  738. Message("%s has no secret nickname"%s)
  739. else:
  740. Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2))
  741. else:
  742. s = 'Anonymous'
  743. rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=Carbon.File.FSSpec)
  744. Message("rv: %s"%rv)
  745. rv = AskFileForSave(wanted=Carbon.File.FSRef, savedFileName="%s.txt"%s)
  746. Message("rv.as_pathname: %s"%rv.as_pathname())
  747. rv = AskFolder()
  748. Message("Folder name: %s"%rv)
  749. text = ( "Working Hard...", "Hardly Working..." ,
  750. "So far, so good!", "Keep on truckin'" )
  751. bar = ProgressBar("Progress, progress...", 0, label="Ramping up...")
  752. try:
  753. if hasattr(MacOS, 'SchedParams'):
  754. appsw = MacOS.SchedParams(1, 0)
  755. for i in xrange(20):
  756. bar.inc()
  757. time.sleep(0.05)
  758. bar.set(0,100)
  759. for i in xrange(100):
  760. bar.set(i)
  761. time.sleep(0.05)
  762. if i % 10 == 0:
  763. bar.label(text[(i/10) % 4])
  764. bar.label("Done.")
  765. time.sleep(1.0) # give'em a chance to see "Done."
  766. finally:
  767. del bar
  768. if hasattr(MacOS, 'SchedParams'):
  769. MacOS.SchedParams(*appsw)
  770. if __name__ == '__main__':
  771. try:
  772. test()
  773. except KeyboardInterrupt:
  774. Message("Operation Canceled.")