diff options
author | Raymond Hettinger <python@rcn.com> | 2003-04-06 09:01:11 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2003-04-06 09:01:11 (GMT) |
commit | ff41c48a77b7d1411ce97190c8b8405bdaa261e1 (patch) | |
tree | 94763135f421e0c32c6356e083c4d3521e43cd67 /Lib/plat-mac | |
parent | 50c61d5a6c2c551b31270d78b9e53ccef3fdf7a8 (diff) | |
download | cpython-ff41c48a77b7d1411ce97190c8b8405bdaa261e1.zip cpython-ff41c48a77b7d1411ce97190c8b8405bdaa261e1.tar.gz cpython-ff41c48a77b7d1411ce97190c8b8405bdaa261e1.tar.bz2 |
SF patch #701494: more apply removals
Diffstat (limited to 'Lib/plat-mac')
-rw-r--r-- | Lib/plat-mac/Carbon/MediaDescr.py | 144 | ||||
-rw-r--r-- | Lib/plat-mac/EasyDialogs.py | 1482 | ||||
-rw-r--r-- | Lib/plat-mac/FrameWork.py | 2018 | ||||
-rw-r--r-- | Lib/plat-mac/MiniAEFrame.py | 332 | ||||
-rw-r--r-- | Lib/plat-mac/argvemulator.py | 198 | ||||
-rw-r--r-- | Lib/plat-mac/icopen.py | 28 |
6 files changed, 2101 insertions, 2101 deletions
diff --git a/Lib/plat-mac/Carbon/MediaDescr.py b/Lib/plat-mac/Carbon/MediaDescr.py index 3c73820..acacfb1 100644 --- a/Lib/plat-mac/Carbon/MediaDescr.py +++ b/Lib/plat-mac/Carbon/MediaDescr.py @@ -4,94 +4,94 @@ import struct Error = 'MediaDescr.Error' class _MediaDescriptionCodec: - def __init__(self, trunc, size, names, fmt): - self.trunc = trunc - self.size = size - self.names = names - self.fmt = fmt - - def decode(self, data): - if self.trunc: - data = data[:self.size] - values = struct.unpack(self.fmt, data) - if len(values) != len(self.names): - raise Error, ('Format length does not match number of names', descr) - rv = {} - for i in range(len(values)): - name = self.names[i] - value = values[i] - if type(name) == type(()): - name, cod, dec = name - value = dec(value) - rv[name] = value - return rv - - def encode(dict): - list = [self.fmt] - for name in self.names: - if type(name) == type(()): - name, cod, dec = name - else: - cod = dec = None - value = dict[name] - if cod: - value = cod(value) - list.append(value) - rv = apply(struct.pack, tuple(list)) - return rv - + def __init__(self, trunc, size, names, fmt): + self.trunc = trunc + self.size = size + self.names = names + self.fmt = fmt + + def decode(self, data): + if self.trunc: + data = data[:self.size] + values = struct.unpack(self.fmt, data) + if len(values) != len(self.names): + raise Error, ('Format length does not match number of names', descr) + rv = {} + for i in range(len(values)): + name = self.names[i] + value = values[i] + if type(name) == type(()): + name, cod, dec = name + value = dec(value) + rv[name] = value + return rv + + def encode(dict): + list = [self.fmt] + for name in self.names: + if type(name) == type(()): + name, cod, dec = name + else: + cod = dec = None + value = dict[name] + if cod: + value = cod(value) + list.append(value) + rv = struct.pack(*list) + return rv + # Helper functions def _tofixed(float): - hi = int(float) - lo = int(float*0x10000) & 0xffff - return (hi<<16)|lo - + hi = int(float) + lo = int(float*0x10000) & 0xffff + return (hi<<16)|lo + def _fromfixed(fixed): - hi = (fixed >> 16) & 0xffff - lo = (fixed & 0xffff) - return hi + (lo / float(0x10000)) - + hi = (fixed >> 16) & 0xffff + lo = (fixed & 0xffff) + return hi + (lo / float(0x10000)) + def _tostr31(str): - return chr(len(str)) + str + '\0'*(31-len(str)) - + return chr(len(str)) + str + '\0'*(31-len(str)) + def _fromstr31(str31): - return str31[1:1+ord(str31[0])] + return str31[1:1+ord(str31[0])] SampleDescription = _MediaDescriptionCodec( - 1, # May be longer, truncate - 16, # size - ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex'), # Attributes - "l4slhh" # Format + 1, # May be longer, truncate + 16, # size + ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex'), # Attributes + "l4slhh" # Format ) SoundDescription = _MediaDescriptionCodec( - 1, - 36, - ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex', - 'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize', - 'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed)), - "l4slhhhh4shhhhl" # Format + 1, + 36, + ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex', + 'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize', + 'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed)), + "l4slhhhh4shhhhl" # Format ) SoundDescriptionV1 = _MediaDescriptionCodec( - 1, - 52, - ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex', - 'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize', - 'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed), 'samplesPerPacket', - 'bytesPerPacket', 'bytesPerFrame', 'bytesPerSample'), - "l4slhhhh4shhhhlllll" # Format + 1, + 52, + ('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex', + 'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize', + 'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed), 'samplesPerPacket', + 'bytesPerPacket', 'bytesPerFrame', 'bytesPerSample'), + "l4slhhhh4shhhhlllll" # Format ) ImageDescription = _MediaDescriptionCodec( - 1, # May be longer, truncate - 86, # size - ('idSize', 'cType', 'resvd1', 'resvd2', 'dataRefIndex', 'version', - 'revisionLevel', 'vendor', 'temporalQuality', 'spatialQuality', - 'width', 'height', ('hRes', _tofixed, _fromfixed), ('vRes', _tofixed, _fromfixed), - 'dataSize', 'frameCount', ('name', _tostr31, _fromstr31), - 'depth', 'clutID'), - 'l4slhhhh4sllhhlllh32shh', + 1, # May be longer, truncate + 86, # size + ('idSize', 'cType', 'resvd1', 'resvd2', 'dataRefIndex', 'version', + 'revisionLevel', 'vendor', 'temporalQuality', 'spatialQuality', + 'width', 'height', ('hRes', _tofixed, _fromfixed), ('vRes', _tofixed, _fromfixed), + 'dataSize', 'frameCount', ('name', _tostr31, _fromstr31), + 'depth', 'clutID'), + 'l4slhhhh4sllhhlllh32shh', ) # XXXX Others, like TextDescription and such, remain to be done. diff --git a/Lib/plat-mac/EasyDialogs.py b/Lib/plat-mac/EasyDialogs.py index 27219a2..4a92373 100644 --- a/Lib/plat-mac/EasyDialogs.py +++ b/Lib/plat-mac/EasyDialogs.py @@ -5,13 +5,13 @@ AskString(prompt, default) -- ask for a string, display OK and Cancel buttons. AskPassword(prompt, default) -- like AskString(), but shows text as bullets. AskYesNoCancel(question, default) -- display a question and Yes, No and Cancel buttons. GetArgv(optionlist, commandlist) -- fill a sys.argv-like list using a dialog -AskFileForOpen(...) -- Ask the user for an existing file +AskFileForOpen(...) -- Ask the user for an existing file AskFileForSave(...) -- Ask the user for an output file AskFolder(...) -- Ask the user to select a folder bar = Progress(label, maxvalue) -- Display a progress bar bar.set(value) -- Set value bar.inc( *amount ) -- increment value by amount (default=1) -bar.label( *newlabel ) -- get or set text label. +bar.label( *newlabel ) -- get or set text label. More documentation in each function. This module uses DLOG resources 260 and on. @@ -31,309 +31,309 @@ from Carbon import AE import Nav import MacOS import string -from Carbon.ControlAccessor import * # Also import Controls constants +from Carbon.ControlAccessor import * # Also import Controls constants import Carbon.File import macresource import os import sys __all__ = ['Message', 'AskString', 'AskPassword', 'AskYesNoCancel', - 'GetArgv', 'AskFileForOpen', 'AskFileForSave', 'AskFolder', - 'Progress'] - + 'GetArgv', 'AskFileForOpen', 'AskFileForSave', 'AskFolder', + 'Progress'] + _initialized = 0 def _initialize(): - global _initialized - if _initialized: return - macresource.need("DLOG", 260, "dialogs.rsrc", __name__) - + global _initialized + if _initialized: return + macresource.need("DLOG", 260, "dialogs.rsrc", __name__) + def _interact(): - """Make sure the application is in the foreground""" - AE.AEInteractWithUser(50000000) + """Make sure the application is in the foreground""" + AE.AEInteractWithUser(50000000) def cr2lf(text): - if '\r' in text: - text = string.join(string.split(text, '\r'), '\n') - return text + if '\r' in text: + text = string.join(string.split(text, '\r'), '\n') + return text def lf2cr(text): - if '\n' in text: - text = string.join(string.split(text, '\n'), '\r') - if len(text) > 253: - text = text[:253] + '\311' - return text + if '\n' in text: + text = string.join(string.split(text, '\n'), '\r') + if len(text) > 253: + text = text[:253] + '\311' + return text def Message(msg, id=260, ok=None): - """Display a MESSAGE string. - - Return when the user clicks the OK button or presses Return. - - The MESSAGE string can be at most 255 characters long. - """ - _initialize() - _interact() - d = GetNewDialog(id, -1) - if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" - return - h = d.GetDialogItemAsControl(2) - SetDialogItemText(h, lf2cr(msg)) - if ok != None: - h = d.GetDialogItemAsControl(1) - h.SetControlTitle(ok) - d.SetDialogDefaultItem(1) - d.AutoSizeDialog() - d.GetDialogWindow().ShowWindow() - while 1: - n = ModalDialog(None) - if n == 1: - return + """Display a MESSAGE string. + + Return when the user clicks the OK button or presses Return. + + The MESSAGE string can be at most 255 characters long. + """ + _initialize() + _interact() + d = GetNewDialog(id, -1) + if not d: + print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + return + h = d.GetDialogItemAsControl(2) + SetDialogItemText(h, lf2cr(msg)) + if ok != None: + h = d.GetDialogItemAsControl(1) + h.SetControlTitle(ok) + d.SetDialogDefaultItem(1) + d.AutoSizeDialog() + d.GetDialogWindow().ShowWindow() + while 1: + n = ModalDialog(None) + if n == 1: + return def AskString(prompt, default = "", id=261, ok=None, cancel=None): - """Display a PROMPT string and a text entry field with a DEFAULT string. - - Return the contents of the text entry field when the user clicks the - OK button or presses Return. - Return None when the user clicks the Cancel button. - - If omitted, DEFAULT is empty. - - The PROMPT and DEFAULT strings, as well as the return value, - can be at most 255 characters long. - """ - - _initialize() - _interact() - d = GetNewDialog(id, -1) - if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" - return - h = d.GetDialogItemAsControl(3) - SetDialogItemText(h, lf2cr(prompt)) - h = d.GetDialogItemAsControl(4) - SetDialogItemText(h, lf2cr(default)) - d.SelectDialogItemText(4, 0, 999) -# d.SetDialogItem(4, 0, 255) - if ok != None: - h = d.GetDialogItemAsControl(1) - h.SetControlTitle(ok) - if cancel != None: - h = d.GetDialogItemAsControl(2) - h.SetControlTitle(cancel) - d.SetDialogDefaultItem(1) - d.SetDialogCancelItem(2) - d.AutoSizeDialog() - d.GetDialogWindow().ShowWindow() - while 1: - n = ModalDialog(None) - if n == 1: - h = d.GetDialogItemAsControl(4) - return cr2lf(GetDialogItemText(h)) - if n == 2: return None - -def AskPassword(prompt, default='', id=264, ok=None, cancel=None): - """Display a PROMPT string and a text entry field with a DEFAULT string. - The string is displayed as bullets only. - - Return the contents of the text entry field when the user clicks the - OK button or presses Return. - Return None when the user clicks the Cancel button. - - If omitted, DEFAULT is empty. - - The PROMPT and DEFAULT strings, as well as the return value, - can be at most 255 characters long. - """ - _initialize() - _interact() - d = GetNewDialog(id, -1) - if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" - return - h = d.GetDialogItemAsControl(3) - SetDialogItemText(h, lf2cr(prompt)) - pwd = d.GetDialogItemAsControl(4) - bullets = '\245'*len(default) -## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets) - SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default) - d.SelectDialogItemText(4, 0, 999) - Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart) - if ok != None: - h = d.GetDialogItemAsControl(1) - h.SetControlTitle(ok) - if cancel != None: - h = d.GetDialogItemAsControl(2) - h.SetControlTitle(cancel) - d.SetDialogDefaultItem(Dialogs.ok) - d.SetDialogCancelItem(Dialogs.cancel) - d.AutoSizeDialog() - d.GetDialogWindow().ShowWindow() - while 1: - n = ModalDialog(None) - if n == 1: - h = d.GetDialogItemAsControl(4) - return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag)) - if n == 2: return None + """Display a PROMPT string and a text entry field with a DEFAULT string. + + Return the contents of the text entry field when the user clicks the + OK button or presses Return. + Return None when the user clicks the Cancel button. + + If omitted, DEFAULT is empty. + + The PROMPT and DEFAULT strings, as well as the return value, + can be at most 255 characters long. + """ + + _initialize() + _interact() + d = GetNewDialog(id, -1) + if not d: + print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + return + h = d.GetDialogItemAsControl(3) + SetDialogItemText(h, lf2cr(prompt)) + h = d.GetDialogItemAsControl(4) + SetDialogItemText(h, lf2cr(default)) + d.SelectDialogItemText(4, 0, 999) +# d.SetDialogItem(4, 0, 255) + if ok != None: + h = d.GetDialogItemAsControl(1) + h.SetControlTitle(ok) + if cancel != None: + h = d.GetDialogItemAsControl(2) + h.SetControlTitle(cancel) + d.SetDialogDefaultItem(1) + d.SetDialogCancelItem(2) + d.AutoSizeDialog() + d.GetDialogWindow().ShowWindow() + while 1: + n = ModalDialog(None) + if n == 1: + h = d.GetDialogItemAsControl(4) + return cr2lf(GetDialogItemText(h)) + if n == 2: return None + +def AskPassword(prompt, default='', id=264, ok=None, cancel=None): + """Display a PROMPT string and a text entry field with a DEFAULT string. + The string is displayed as bullets only. + + Return the contents of the text entry field when the user clicks the + OK button or presses Return. + Return None when the user clicks the Cancel button. + + If omitted, DEFAULT is empty. + + The PROMPT and DEFAULT strings, as well as the return value, + can be at most 255 characters long. + """ + _initialize() + _interact() + d = GetNewDialog(id, -1) + if not d: + print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + return + h = d.GetDialogItemAsControl(3) + SetDialogItemText(h, lf2cr(prompt)) + pwd = d.GetDialogItemAsControl(4) + bullets = '\245'*len(default) +## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets) + SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default) + d.SelectDialogItemText(4, 0, 999) + Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart) + if ok != None: + h = d.GetDialogItemAsControl(1) + h.SetControlTitle(ok) + if cancel != None: + h = d.GetDialogItemAsControl(2) + h.SetControlTitle(cancel) + d.SetDialogDefaultItem(Dialogs.ok) + d.SetDialogCancelItem(Dialogs.cancel) + d.AutoSizeDialog() + d.GetDialogWindow().ShowWindow() + while 1: + n = ModalDialog(None) + if n == 1: + h = d.GetDialogItemAsControl(4) + return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag)) + if n == 2: return None def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262): - """Display a QUESTION string which can be answered with Yes or No. - - Return 1 when the user clicks the Yes button. - Return 0 when the user clicks the No button. - Return -1 when the user clicks the Cancel button. - - When the user presses Return, the DEFAULT value is returned. - If omitted, this is 0 (No). - - The QUESTION string can be at most 255 characters. - """ - - _initialize() - _interact() - d = GetNewDialog(id, -1) - if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" - return - # Button assignments: - # 1 = default (invisible) - # 2 = Yes - # 3 = No - # 4 = Cancel - # The question string is item 5 - h = d.GetDialogItemAsControl(5) - SetDialogItemText(h, lf2cr(question)) - if yes != None: - if yes == '': - d.HideDialogItem(2) - else: - h = d.GetDialogItemAsControl(2) - h.SetControlTitle(yes) - if no != None: - if no == '': - d.HideDialogItem(3) - else: - h = d.GetDialogItemAsControl(3) - h.SetControlTitle(no) - if cancel != None: - if cancel == '': - d.HideDialogItem(4) - else: - h = d.GetDialogItemAsControl(4) - h.SetControlTitle(cancel) - d.SetDialogCancelItem(4) - if default == 1: - d.SetDialogDefaultItem(2) - elif default == 0: - d.SetDialogDefaultItem(3) - elif default == -1: - d.SetDialogDefaultItem(4) - d.AutoSizeDialog() - d.GetDialogWindow().ShowWindow() - while 1: - n = ModalDialog(None) - if n == 1: return default - if n == 2: return 1 - if n == 3: return 0 - if n == 4: return -1 - - - + """Display a QUESTION string which can be answered with Yes or No. + + Return 1 when the user clicks the Yes button. + Return 0 when the user clicks the No button. + Return -1 when the user clicks the Cancel button. + + When the user presses Return, the DEFAULT value is returned. + If omitted, this is 0 (No). + + The QUESTION string can be at most 255 characters. + """ + + _initialize() + _interact() + d = GetNewDialog(id, -1) + if not d: + print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + return + # Button assignments: + # 1 = default (invisible) + # 2 = Yes + # 3 = No + # 4 = Cancel + # The question string is item 5 + h = d.GetDialogItemAsControl(5) + SetDialogItemText(h, lf2cr(question)) + if yes != None: + if yes == '': + d.HideDialogItem(2) + else: + h = d.GetDialogItemAsControl(2) + h.SetControlTitle(yes) + if no != None: + if no == '': + d.HideDialogItem(3) + else: + h = d.GetDialogItemAsControl(3) + h.SetControlTitle(no) + if cancel != None: + if cancel == '': + d.HideDialogItem(4) + else: + h = d.GetDialogItemAsControl(4) + h.SetControlTitle(cancel) + d.SetDialogCancelItem(4) + if default == 1: + d.SetDialogDefaultItem(2) + elif default == 0: + d.SetDialogDefaultItem(3) + elif default == -1: + d.SetDialogDefaultItem(4) + d.AutoSizeDialog() + d.GetDialogWindow().ShowWindow() + while 1: + n = ModalDialog(None) + if n == 1: return default + if n == 2: return 1 + if n == 3: return 0 + if n == 4: return -1 + + + screenbounds = Qd.GetQDGlobalsScreenBits().bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ - screenbounds[2]-4, screenbounds[3]-4 + screenbounds[2]-4, screenbounds[3]-4 -kControlProgressBarIndeterminateTag = 'inde' # from Controls.py +kControlProgressBarIndeterminateTag = 'inde' # from Controls.py class ProgressBar: - def __init__(self, title="Working...", maxval=0, label="", id=263): - self.w = None - self.d = None - _initialize() - self.d = GetNewDialog(id, -1) - self.w = self.d.GetDialogWindow() - self.label(label) - self.title(title) - self.set(0, maxval) - self.d.AutoSizeDialog() - self.w.ShowWindow() - self.d.DrawDialog() - - def __del__( self ): - if self.w: - self.w.BringToFront() - self.w.HideWindow() - del self.w - del self.d - - def title(self, newstr=""): - """title(text) - Set title of progress window""" - self.w.BringToFront() - self.w.SetWTitle(newstr) - - def label( self, *newstr ): - """label(text) - Set text in progress box""" - self.w.BringToFront() - if newstr: - self._label = lf2cr(newstr[0]) - text_h = self.d.GetDialogItemAsControl(2) - SetDialogItemText(text_h, self._label) - - def _update(self, value): - maxval = self.maxval - if maxval == 0: # an indeterminate bar - Ctl.IdleControls(self.w) # spin the barber pole - else: # a determinate bar - if maxval > 32767: - value = int(value/(maxval/32767.0)) - maxval = 32767 - maxval = int(maxval) - value = int(value) - progbar = self.d.GetDialogItemAsControl(3) - progbar.SetControlMaximum(maxval) - progbar.SetControlValue(value) # set the bar length - - # Test for cancel button - ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 ) - if ready : - what,msg,when,where,mod = ev - part = Win.FindWindow(where)[0] - if Dlg.IsDialogEvent(ev): - ds = Dlg.DialogSelect(ev) - if ds[0] and ds[1] == self.d and ds[-1] == 1: - self.w.HideWindow() - self.w = None - self.d = None - raise KeyboardInterrupt, ev - else: - if part == 4: # inDrag - self.w.DragWindow(where, screenbounds) - else: - MacOS.HandleEvent(ev) - - - def set(self, value, max=None): - """set(value) - Set progress bar position""" - if max != None: - self.maxval = max - bar = self.d.GetDialogItemAsControl(3) - if max <= 0: # indeterminate bar - bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01') - else: # determinate bar - bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00') - if value < 0: - value = 0 - elif value > self.maxval: - value = self.maxval - self.curval = value - self._update(value) - - def inc(self, n=1): - """inc(amt) - Increment progress bar position""" - self.set(self.curval + n) + def __init__(self, title="Working...", maxval=0, label="", id=263): + self.w = None + self.d = None + _initialize() + self.d = GetNewDialog(id, -1) + self.w = self.d.GetDialogWindow() + self.label(label) + self.title(title) + self.set(0, maxval) + self.d.AutoSizeDialog() + self.w.ShowWindow() + self.d.DrawDialog() + + def __del__( self ): + if self.w: + self.w.BringToFront() + self.w.HideWindow() + del self.w + del self.d + + def title(self, newstr=""): + """title(text) - Set title of progress window""" + self.w.BringToFront() + self.w.SetWTitle(newstr) + + def label( self, *newstr ): + """label(text) - Set text in progress box""" + self.w.BringToFront() + if newstr: + self._label = lf2cr(newstr[0]) + text_h = self.d.GetDialogItemAsControl(2) + SetDialogItemText(text_h, self._label) + + def _update(self, value): + maxval = self.maxval + if maxval == 0: # an indeterminate bar + Ctl.IdleControls(self.w) # spin the barber pole + else: # a determinate bar + if maxval > 32767: + value = int(value/(maxval/32767.0)) + maxval = 32767 + maxval = int(maxval) + value = int(value) + progbar = self.d.GetDialogItemAsControl(3) + progbar.SetControlMaximum(maxval) + progbar.SetControlValue(value) # set the bar length + + # Test for cancel button + ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 ) + if ready : + what,msg,when,where,mod = ev + part = Win.FindWindow(where)[0] + if Dlg.IsDialogEvent(ev): + ds = Dlg.DialogSelect(ev) + if ds[0] and ds[1] == self.d and ds[-1] == 1: + self.w.HideWindow() + self.w = None + self.d = None + raise KeyboardInterrupt, ev + else: + if part == 4: # inDrag + self.w.DragWindow(where, screenbounds) + else: + MacOS.HandleEvent(ev) + + + def set(self, value, max=None): + """set(value) - Set progress bar position""" + if max != None: + self.maxval = max + bar = self.d.GetDialogItemAsControl(3) + if max <= 0: # indeterminate bar + bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01') + else: # determinate bar + bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00') + if value < 0: + value = 0 + elif value > self.maxval: + value = self.maxval + self.curval = value + self._update(value) + + def inc(self, n=1): + """inc(amt) - Increment progress bar position""" + self.set(self.curval + n) ARGV_ID=265 ARGV_ITEM_OK=1 @@ -352,488 +352,488 @@ ARGV_CMDLINE_GROUP=13 ARGV_CMDLINE_DATA=14 ##def _myModalDialog(d): -## while 1: -## ready, ev = Evt.WaitNextEvent(0xffff, -1) -## print 'DBG: WNE', ready, ev -## if ready : -## what,msg,when,where,mod = ev -## part, window = Win.FindWindow(where) -## if Dlg.IsDialogEvent(ev): -## didit, dlgdone, itemdone = Dlg.DialogSelect(ev) -## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d -## if didit and dlgdone == d: -## return itemdone -## elif window == d.GetDialogWindow(): -## d.GetDialogWindow().SelectWindow() -## if part == 4: # inDrag -## d.DragWindow(where, screenbounds) -## else: -## MacOS.HandleEvent(ev) -## else: -## MacOS.HandleEvent(ev) +## while 1: +## ready, ev = Evt.WaitNextEvent(0xffff, -1) +## print 'DBG: WNE', ready, ev +## if ready : +## what,msg,when,where,mod = ev +## part, window = Win.FindWindow(where) +## if Dlg.IsDialogEvent(ev): +## didit, dlgdone, itemdone = Dlg.DialogSelect(ev) +## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d +## if didit and dlgdone == d: +## return itemdone +## elif window == d.GetDialogWindow(): +## d.GetDialogWindow().SelectWindow() +## if part == 4: # inDrag +## d.DragWindow(where, screenbounds) +## else: +## MacOS.HandleEvent(ev) +## else: +## MacOS.HandleEvent(ev) ## def _setmenu(control, items): - mhandle = control.GetControlData_Handle(Controls.kControlMenuPart, - Controls.kControlPopupButtonMenuHandleTag) - menu = Menu.as_Menu(mhandle) - for item in items: - if type(item) == type(()): - label = item[0] - else: - label = item - if label[-1] == '=' or label[-1] == ':': - label = label[:-1] - menu.AppendMenu(label) -## mhandle, mid = menu.getpopupinfo() -## control.SetControlData_Handle(Controls.kControlMenuPart, -## Controls.kControlPopupButtonMenuHandleTag, mhandle) - control.SetControlMinimum(1) - control.SetControlMaximum(len(items)+1) - + mhandle = control.GetControlData_Handle(Controls.kControlMenuPart, + Controls.kControlPopupButtonMenuHandleTag) + menu = Menu.as_Menu(mhandle) + for item in items: + if type(item) == type(()): + label = item[0] + else: + label = item + if label[-1] == '=' or label[-1] == ':': + label = label[:-1] + menu.AppendMenu(label) +## mhandle, mid = menu.getpopupinfo() +## control.SetControlData_Handle(Controls.kControlMenuPart, +## Controls.kControlPopupButtonMenuHandleTag, mhandle) + control.SetControlMinimum(1) + control.SetControlMaximum(len(items)+1) + def _selectoption(d, optionlist, idx): - if idx < 0 or idx >= len(optionlist): - MacOS.SysBeep() - return - option = optionlist[idx] - if type(option) == type(()): - if len(option) == 4: - help = option[2] - elif len(option) > 1: - help = option[-1] - else: - help = '' - else: - help = '' - h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN) - if help and len(help) > 250: - help = help[:250] + '...' - Dlg.SetDialogItemText(h, help) - hasvalue = 0 - if type(option) == type(()): - label = option[0] - else: - label = option - if label[-1] == '=' or label[-1] == ':': - hasvalue = 1 - h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE) - Dlg.SetDialogItemText(h, '') - if hasvalue: - d.ShowDialogItem(ARGV_OPTION_VALUE) - d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0) - else: - d.HideDialogItem(ARGV_OPTION_VALUE) + if idx < 0 or idx >= len(optionlist): + MacOS.SysBeep() + return + option = optionlist[idx] + if type(option) == type(()): + if len(option) == 4: + help = option[2] + elif len(option) > 1: + help = option[-1] + else: + help = '' + else: + help = '' + h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN) + if help and len(help) > 250: + help = help[:250] + '...' + Dlg.SetDialogItemText(h, help) + hasvalue = 0 + if type(option) == type(()): + label = option[0] + else: + label = option + if label[-1] == '=' or label[-1] == ':': + hasvalue = 1 + h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE) + Dlg.SetDialogItemText(h, '') + if hasvalue: + d.ShowDialogItem(ARGV_OPTION_VALUE) + d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0) + else: + d.HideDialogItem(ARGV_OPTION_VALUE) def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfolder=1, id=ARGV_ID): - _initialize() - _interact() - d = GetNewDialog(id, -1) - if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" - return -# h = d.GetDialogItemAsControl(3) -# SetDialogItemText(h, lf2cr(prompt)) -# h = d.GetDialogItemAsControl(4) -# SetDialogItemText(h, lf2cr(default)) -# d.SelectDialogItemText(4, 0, 999) -# d.SetDialogItem(4, 0, 255) - if optionlist: - _setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist) - _selectoption(d, optionlist, 0) - else: - d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl() - if commandlist: - _setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist) - if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1: - help = commandlist[0][-1] - h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN) - Dlg.SetDialogItemText(h, help) - else: - d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl() - if not addoldfile: - d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl() - if not addnewfile: - d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl() - if not addfolder: - d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl() - d.SetDialogDefaultItem(ARGV_ITEM_OK) - d.SetDialogCancelItem(ARGV_ITEM_CANCEL) - d.GetDialogWindow().ShowWindow() - d.DrawDialog() - if hasattr(MacOS, 'SchedParams'): - appsw = MacOS.SchedParams(1, 0) - try: - while 1: - stringstoadd = [] - n = ModalDialog(None) - if n == ARGV_ITEM_OK: - break - elif n == ARGV_ITEM_CANCEL: - raise SystemExit - elif n == ARGV_OPTION_GROUP: - idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1 - _selectoption(d, optionlist, idx) - elif n == ARGV_OPTION_VALUE: - pass - elif n == ARGV_OPTION_ADD: - idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1 - if 0 <= idx < len(optionlist): - option = optionlist[idx] - if type(option) == type(()): - option = option[0] - if option[-1] == '=' or option[-1] == ':': - option = option[:-1] - h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE) - value = Dlg.GetDialogItemText(h) - else: - value = '' - if len(option) == 1: - stringtoadd = '-' + option - else: - stringtoadd = '--' + option - stringstoadd = [stringtoadd] - if value: - stringstoadd.append(value) - else: - MacOS.SysBeep() - elif n == ARGV_COMMAND_GROUP: - idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1 - if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \ - len(commandlist[idx]) > 1: - help = commandlist[idx][-1] - h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN) - Dlg.SetDialogItemText(h, help) - elif n == ARGV_COMMAND_ADD: - idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1 - if 0 <= idx < len(commandlist): - command = commandlist[idx] - if type(command) == type(()): - command = command[0] - stringstoadd = [command] - else: - MacOS.SysBeep() - elif n == ARGV_ADD_OLDFILE: - pathname = AskFileForOpen() - if pathname: - stringstoadd = [pathname] - elif n == ARGV_ADD_NEWFILE: - pathname = AskFileForSave() - if pathname: - stringstoadd = [pathname] - elif n == ARGV_ADD_FOLDER: - pathname = AskFolder() - if pathname: - stringstoadd = [pathname] - elif n == ARGV_CMDLINE_DATA: - pass # Nothing to do - else: - raise RuntimeError, "Unknown dialog item %d"%n - - for stringtoadd in stringstoadd: - if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd: - stringtoadd = `stringtoadd` - h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) - oldstr = GetDialogItemText(h) - if oldstr and oldstr[-1] != ' ': - oldstr = oldstr + ' ' - oldstr = oldstr + stringtoadd - if oldstr[-1] != ' ': - oldstr = oldstr + ' ' - SetDialogItemText(h, oldstr) - d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff) - h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) - oldstr = GetDialogItemText(h) - tmplist = string.split(oldstr) - newlist = [] - while tmplist: - item = tmplist[0] - del tmplist[0] - if item[0] == '"': - while item[-1] != '"': - if not tmplist: - raise RuntimeError, "Unterminated quoted argument" - item = item + ' ' + tmplist[0] - del tmplist[0] - item = item[1:-1] - if item[0] == "'": - while item[-1] != "'": - if not tmplist: - raise RuntimeError, "Unterminated quoted argument" - item = item + ' ' + tmplist[0] - del tmplist[0] - item = item[1:-1] - newlist.append(item) - return newlist - finally: - if hasattr(MacOS, 'SchedParams'): - apply(MacOS.SchedParams, appsw) - del d + _initialize() + _interact() + d = GetNewDialog(id, -1) + if not d: + print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + return +# h = d.GetDialogItemAsControl(3) +# SetDialogItemText(h, lf2cr(prompt)) +# h = d.GetDialogItemAsControl(4) +# SetDialogItemText(h, lf2cr(default)) +# d.SelectDialogItemText(4, 0, 999) +# d.SetDialogItem(4, 0, 255) + if optionlist: + _setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist) + _selectoption(d, optionlist, 0) + else: + d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl() + if commandlist: + _setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist) + if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1: + help = commandlist[0][-1] + h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN) + Dlg.SetDialogItemText(h, help) + else: + d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl() + if not addoldfile: + d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl() + if not addnewfile: + d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl() + if not addfolder: + d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl() + d.SetDialogDefaultItem(ARGV_ITEM_OK) + d.SetDialogCancelItem(ARGV_ITEM_CANCEL) + d.GetDialogWindow().ShowWindow() + d.DrawDialog() + if hasattr(MacOS, 'SchedParams'): + appsw = MacOS.SchedParams(1, 0) + try: + while 1: + stringstoadd = [] + n = ModalDialog(None) + if n == ARGV_ITEM_OK: + break + elif n == ARGV_ITEM_CANCEL: + raise SystemExit + elif n == ARGV_OPTION_GROUP: + idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1 + _selectoption(d, optionlist, idx) + elif n == ARGV_OPTION_VALUE: + pass + elif n == ARGV_OPTION_ADD: + idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1 + if 0 <= idx < len(optionlist): + option = optionlist[idx] + if type(option) == type(()): + option = option[0] + if option[-1] == '=' or option[-1] == ':': + option = option[:-1] + h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE) + value = Dlg.GetDialogItemText(h) + else: + value = '' + if len(option) == 1: + stringtoadd = '-' + option + else: + stringtoadd = '--' + option + stringstoadd = [stringtoadd] + if value: + stringstoadd.append(value) + else: + MacOS.SysBeep() + elif n == ARGV_COMMAND_GROUP: + idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1 + if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \ + len(commandlist[idx]) > 1: + help = commandlist[idx][-1] + h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN) + Dlg.SetDialogItemText(h, help) + elif n == ARGV_COMMAND_ADD: + idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1 + if 0 <= idx < len(commandlist): + command = commandlist[idx] + if type(command) == type(()): + command = command[0] + stringstoadd = [command] + else: + MacOS.SysBeep() + elif n == ARGV_ADD_OLDFILE: + pathname = AskFileForOpen() + if pathname: + stringstoadd = [pathname] + elif n == ARGV_ADD_NEWFILE: + pathname = AskFileForSave() + if pathname: + stringstoadd = [pathname] + elif n == ARGV_ADD_FOLDER: + pathname = AskFolder() + if pathname: + stringstoadd = [pathname] + elif n == ARGV_CMDLINE_DATA: + pass # Nothing to do + else: + raise RuntimeError, "Unknown dialog item %d"%n + + for stringtoadd in stringstoadd: + if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd: + stringtoadd = `stringtoadd` + h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) + oldstr = GetDialogItemText(h) + if oldstr and oldstr[-1] != ' ': + oldstr = oldstr + ' ' + oldstr = oldstr + stringtoadd + if oldstr[-1] != ' ': + oldstr = oldstr + ' ' + SetDialogItemText(h, oldstr) + d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff) + h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) + oldstr = GetDialogItemText(h) + tmplist = string.split(oldstr) + newlist = [] + while tmplist: + item = tmplist[0] + del tmplist[0] + if item[0] == '"': + while item[-1] != '"': + if not tmplist: + raise RuntimeError, "Unterminated quoted argument" + item = item + ' ' + tmplist[0] + del tmplist[0] + item = item[1:-1] + if item[0] == "'": + while item[-1] != "'": + if not tmplist: + raise RuntimeError, "Unterminated quoted argument" + item = item + ' ' + tmplist[0] + del tmplist[0] + item = item[1:-1] + newlist.append(item) + return newlist + finally: + if hasattr(MacOS, 'SchedParams'): + MacOS.SchedParams(*appsw) + del d def _process_Nav_args(dftflags, **args): - import aepack - import Carbon.AE - import Carbon.File - for k in args.keys(): - if args[k] is None: - del args[k] - # Set some defaults, and modify some arguments - if not args.has_key('dialogOptionFlags'): - args['dialogOptionFlags'] = dftflags - if args.has_key('defaultLocation') and \ - not isinstance(args['defaultLocation'], Carbon.AE.AEDesc): - defaultLocation = args['defaultLocation'] - if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)): - args['defaultLocation'] = aepack.pack(defaultLocation) - else: - defaultLocation = Carbon.File.FSRef(defaultLocation) - args['defaultLocation'] = aepack.pack(defaultLocation) - if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType): - typeList = args['typeList'][:] - # Workaround for OSX typeless files: - if 'TEXT' in typeList and not '\0\0\0\0' in typeList: - typeList = typeList + ('\0\0\0\0',) - data = 'Pyth' + struct.pack("hh", 0, len(typeList)) - for type in typeList: - data = data+type - args['typeList'] = Carbon.Res.Handle(data) - tpwanted = str - if args.has_key('wanted'): - tpwanted = args['wanted'] - del args['wanted'] - return args, tpwanted - + import aepack + import Carbon.AE + import Carbon.File + for k in args.keys(): + if args[k] is None: + del args[k] + # Set some defaults, and modify some arguments + if not args.has_key('dialogOptionFlags'): + args['dialogOptionFlags'] = dftflags + if args.has_key('defaultLocation') and \ + not isinstance(args['defaultLocation'], Carbon.AE.AEDesc): + defaultLocation = args['defaultLocation'] + if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)): + args['defaultLocation'] = aepack.pack(defaultLocation) + else: + defaultLocation = Carbon.File.FSRef(defaultLocation) + args['defaultLocation'] = aepack.pack(defaultLocation) + if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType): + typeList = args['typeList'][:] + # Workaround for OSX typeless files: + if 'TEXT' in typeList and not '\0\0\0\0' in typeList: + typeList = typeList + ('\0\0\0\0',) + data = 'Pyth' + struct.pack("hh", 0, len(typeList)) + for type in typeList: + data = data+type + args['typeList'] = Carbon.Res.Handle(data) + tpwanted = str + if args.has_key('wanted'): + tpwanted = args['wanted'] + del args['wanted'] + return args, tpwanted + def _dummy_Nav_eventproc(msg, data): - pass - + pass + _default_Nav_eventproc = _dummy_Nav_eventproc def SetDefaultEventProc(proc): - global _default_Nav_eventproc - rv = _default_Nav_eventproc - if proc is None: - proc = _dummy_Nav_eventproc - _default_Nav_eventproc = proc - return rv - + global _default_Nav_eventproc + rv = _default_Nav_eventproc + if proc is None: + proc = _dummy_Nav_eventproc + _default_Nav_eventproc = proc + return rv + def AskFileForOpen( - message=None, - typeList=None, - # From here on the order is not documented - version=None, - defaultLocation=None, - dialogOptionFlags=None, - location=None, - clientName=None, - windowTitle=None, - actionButtonLabel=None, - cancelButtonLabel=None, - preferenceKey=None, - popupExtension=None, - eventProc=_dummy_Nav_eventproc, - previewProc=None, - filterProc=None, - wanted=None, - multiple=None): - """Display a dialog asking the user for a file to open. - - wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) - the other arguments can be looked up in Apple's Navigation Services documentation""" - - default_flags = 0x56 # Or 0xe4? - args, tpwanted = _process_Nav_args(default_flags, version=version, - defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, - location=location,clientName=clientName,windowTitle=windowTitle, - actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, - message=message,preferenceKey=preferenceKey, - popupExtension=popupExtension,eventProc=eventProc,previewProc=previewProc, - filterProc=filterProc,typeList=typeList,wanted=wanted,multiple=multiple) - _interact() - try: - rr = Nav.NavChooseFile(args) - good = 1 - except Nav.error, arg: - if arg[0] != -128: # userCancelledErr - raise Nav.error, arg - return None - if not rr.validRecord or not rr.selection: - return None - if issubclass(tpwanted, Carbon.File.FSRef): - return tpwanted(rr.selection_fsr[0]) - if issubclass(tpwanted, Carbon.File.FSSpec): - return tpwanted(rr.selection[0]) - if issubclass(tpwanted, str): - return tpwanted(rr.selection_fsr[0].as_pathname()) - if issubclass(tpwanted, unicode): - return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8') - raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) + message=None, + typeList=None, + # From here on the order is not documented + version=None, + defaultLocation=None, + dialogOptionFlags=None, + location=None, + clientName=None, + windowTitle=None, + actionButtonLabel=None, + cancelButtonLabel=None, + preferenceKey=None, + popupExtension=None, + eventProc=_dummy_Nav_eventproc, + previewProc=None, + filterProc=None, + wanted=None, + multiple=None): + """Display a dialog asking the user for a file to open. + + wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) + the other arguments can be looked up in Apple's Navigation Services documentation""" + + default_flags = 0x56 # Or 0xe4? + args, tpwanted = _process_Nav_args(default_flags, version=version, + defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, + location=location,clientName=clientName,windowTitle=windowTitle, + actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, + message=message,preferenceKey=preferenceKey, + popupExtension=popupExtension,eventProc=eventProc,previewProc=previewProc, + filterProc=filterProc,typeList=typeList,wanted=wanted,multiple=multiple) + _interact() + try: + rr = Nav.NavChooseFile(args) + good = 1 + except Nav.error, arg: + if arg[0] != -128: # userCancelledErr + raise Nav.error, arg + return None + if not rr.validRecord or not rr.selection: + return None + if issubclass(tpwanted, Carbon.File.FSRef): + return tpwanted(rr.selection_fsr[0]) + if issubclass(tpwanted, Carbon.File.FSSpec): + return tpwanted(rr.selection[0]) + if issubclass(tpwanted, str): + return tpwanted(rr.selection_fsr[0].as_pathname()) + if issubclass(tpwanted, unicode): + return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8') + raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) def AskFileForSave( - message=None, - savedFileName=None, - # From here on the order is not documented - version=None, - defaultLocation=None, - dialogOptionFlags=None, - location=None, - clientName=None, - windowTitle=None, - actionButtonLabel=None, - cancelButtonLabel=None, - preferenceKey=None, - popupExtension=None, - eventProc=_dummy_Nav_eventproc, - fileType=None, - fileCreator=None, - wanted=None, - multiple=None): - """Display a dialog asking the user for a filename to save to. - - wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) - the other arguments can be looked up in Apple's Navigation Services documentation""" - - - default_flags = 0x07 - args, tpwanted = _process_Nav_args(default_flags, version=version, - defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, - location=location,clientName=clientName,windowTitle=windowTitle, - actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, - savedFileName=savedFileName,message=message,preferenceKey=preferenceKey, - popupExtension=popupExtension,eventProc=eventProc,fileType=fileType, - fileCreator=fileCreator,wanted=wanted,multiple=multiple) - _interact() - try: - rr = Nav.NavPutFile(args) - good = 1 - except Nav.error, arg: - if arg[0] != -128: # userCancelledErr - raise Nav.error, arg - return None - if not rr.validRecord or not rr.selection: - return None - if issubclass(tpwanted, Carbon.File.FSRef): - raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave" - if issubclass(tpwanted, Carbon.File.FSSpec): - return tpwanted(rr.selection[0]) - if issubclass(tpwanted, (str, unicode)): - if sys.platform == 'mac': - fullpath = rr.selection[0].as_pathname() - else: - # This is gross, and probably incorrect too - vrefnum, dirid, name = rr.selection[0].as_tuple() - pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, '')) - pardir_fsr = Carbon.File.FSRef(pardir_fss) - pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8 - name_utf8 = unicode(name, 'macroman').encode('utf8') - fullpath = os.path.join(pardir_path, name_utf8) - if issubclass(tpwanted, unicode): - return unicode(fullpath, 'utf8') - return tpwanted(fullpath) - raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) - + message=None, + savedFileName=None, + # From here on the order is not documented + version=None, + defaultLocation=None, + dialogOptionFlags=None, + location=None, + clientName=None, + windowTitle=None, + actionButtonLabel=None, + cancelButtonLabel=None, + preferenceKey=None, + popupExtension=None, + eventProc=_dummy_Nav_eventproc, + fileType=None, + fileCreator=None, + wanted=None, + multiple=None): + """Display a dialog asking the user for a filename to save to. + + wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) + the other arguments can be looked up in Apple's Navigation Services documentation""" + + + default_flags = 0x07 + args, tpwanted = _process_Nav_args(default_flags, version=version, + defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, + location=location,clientName=clientName,windowTitle=windowTitle, + actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, + savedFileName=savedFileName,message=message,preferenceKey=preferenceKey, + popupExtension=popupExtension,eventProc=eventProc,fileType=fileType, + fileCreator=fileCreator,wanted=wanted,multiple=multiple) + _interact() + try: + rr = Nav.NavPutFile(args) + good = 1 + except Nav.error, arg: + if arg[0] != -128: # userCancelledErr + raise Nav.error, arg + return None + if not rr.validRecord or not rr.selection: + return None + if issubclass(tpwanted, Carbon.File.FSRef): + raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave" + if issubclass(tpwanted, Carbon.File.FSSpec): + return tpwanted(rr.selection[0]) + if issubclass(tpwanted, (str, unicode)): + if sys.platform == 'mac': + fullpath = rr.selection[0].as_pathname() + else: + # This is gross, and probably incorrect too + vrefnum, dirid, name = rr.selection[0].as_tuple() + pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, '')) + pardir_fsr = Carbon.File.FSRef(pardir_fss) + pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8 + name_utf8 = unicode(name, 'macroman').encode('utf8') + fullpath = os.path.join(pardir_path, name_utf8) + if issubclass(tpwanted, unicode): + return unicode(fullpath, 'utf8') + return tpwanted(fullpath) + raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) + def AskFolder( - message=None, - # From here on the order is not documented - version=None, - defaultLocation=None, - dialogOptionFlags=None, - location=None, - clientName=None, - windowTitle=None, - actionButtonLabel=None, - cancelButtonLabel=None, - preferenceKey=None, - popupExtension=None, - eventProc=_dummy_Nav_eventproc, - filterProc=None, - wanted=None, - multiple=None): - """Display a dialog asking the user for select a folder. - - wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) - the other arguments can be looked up in Apple's Navigation Services documentation""" - - default_flags = 0x17 - args, tpwanted = _process_Nav_args(default_flags, version=version, - defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, - location=location,clientName=clientName,windowTitle=windowTitle, - actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, - message=message,preferenceKey=preferenceKey, - popupExtension=popupExtension,eventProc=eventProc,filterProc=filterProc, - wanted=wanted,multiple=multiple) - _interact() - try: - rr = Nav.NavChooseFolder(args) - good = 1 - except Nav.error, arg: - if arg[0] != -128: # userCancelledErr - raise Nav.error, arg - return None - if not rr.validRecord or not rr.selection: - return None - if issubclass(tpwanted, Carbon.File.FSRef): - return tpwanted(rr.selection_fsr[0]) - if issubclass(tpwanted, Carbon.File.FSSpec): - return tpwanted(rr.selection[0]) - if issubclass(tpwanted, str): - return tpwanted(rr.selection_fsr[0].as_pathname()) - if issubclass(tpwanted, unicode): - return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8') - raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) - + message=None, + # From here on the order is not documented + version=None, + defaultLocation=None, + dialogOptionFlags=None, + location=None, + clientName=None, + windowTitle=None, + actionButtonLabel=None, + cancelButtonLabel=None, + preferenceKey=None, + popupExtension=None, + eventProc=_dummy_Nav_eventproc, + filterProc=None, + wanted=None, + multiple=None): + """Display a dialog asking the user for select a folder. + + wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) + the other arguments can be looked up in Apple's Navigation Services documentation""" + + default_flags = 0x17 + args, tpwanted = _process_Nav_args(default_flags, version=version, + defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, + location=location,clientName=clientName,windowTitle=windowTitle, + actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, + message=message,preferenceKey=preferenceKey, + popupExtension=popupExtension,eventProc=eventProc,filterProc=filterProc, + wanted=wanted,multiple=multiple) + _interact() + try: + rr = Nav.NavChooseFolder(args) + good = 1 + except Nav.error, arg: + if arg[0] != -128: # userCancelledErr + raise Nav.error, arg + return None + if not rr.validRecord or not rr.selection: + return None + if issubclass(tpwanted, Carbon.File.FSRef): + return tpwanted(rr.selection_fsr[0]) + if issubclass(tpwanted, Carbon.File.FSSpec): + return tpwanted(rr.selection[0]) + if issubclass(tpwanted, str): + return tpwanted(rr.selection_fsr[0].as_pathname()) + if issubclass(tpwanted, unicode): + return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8') + raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted) + def test(): - import time - - Message("Testing EasyDialogs.") - optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), - ('flags=', 'Valued option'), ('f:', 'Short valued option')) - commandlist = (('start', 'Start something'), ('stop', 'Stop something')) - argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) - Message("Command line: %s"%' '.join(argv)) - for i in range(len(argv)): - print 'arg[%d] = %s'%(i, `argv[i]`) - ok = AskYesNoCancel("Do you want to proceed?") - ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") - if ok > 0: - s = AskString("Enter your first name", "Joe") - s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") - if not s2: - Message("%s has no secret nickname"%s) - else: - Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) - else: - s = 'Anonymous' - rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=Carbon.File.FSSpec) - Message("rv: %s"%rv) - rv = AskFileForSave(wanted=Carbon.File.FSRef, savedFileName="%s.txt"%s) - Message("rv.as_pathname: %s"%rv.as_pathname()) - rv = AskFolder() - Message("Folder name: %s"%rv) - text = ( "Working Hard...", "Hardly Working..." , - "So far, so good!", "Keep on truckin'" ) - bar = ProgressBar("Progress, progress...", 0, label="Ramping up...") - try: - if hasattr(MacOS, 'SchedParams'): - appsw = MacOS.SchedParams(1, 0) - for i in xrange(20): - bar.inc() - time.sleep(0.05) - bar.set(0,100) - for i in xrange(100): - bar.set(i) - time.sleep(0.05) - if i % 10 == 0: - bar.label(text[(i/10) % 4]) - bar.label("Done.") - time.sleep(1.0) # give'em a chance to see "Done." - finally: - del bar - if hasattr(MacOS, 'SchedParams'): - apply(MacOS.SchedParams, appsw) + import time + + Message("Testing EasyDialogs.") + optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'), + ('flags=', 'Valued option'), ('f:', 'Short valued option')) + commandlist = (('start', 'Start something'), ('stop', 'Stop something')) + argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) + Message("Command line: %s"%' '.join(argv)) + for i in range(len(argv)): + print 'arg[%d] = %s'%(i, `argv[i]`) + ok = AskYesNoCancel("Do you want to proceed?") + ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") + if ok > 0: + s = AskString("Enter your first name", "Joe") + s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") + if not s2: + Message("%s has no secret nickname"%s) + else: + Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2)) + else: + s = 'Anonymous' + rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=Carbon.File.FSSpec) + Message("rv: %s"%rv) + rv = AskFileForSave(wanted=Carbon.File.FSRef, savedFileName="%s.txt"%s) + Message("rv.as_pathname: %s"%rv.as_pathname()) + rv = AskFolder() + Message("Folder name: %s"%rv) + text = ( "Working Hard...", "Hardly Working..." , + "So far, so good!", "Keep on truckin'" ) + bar = ProgressBar("Progress, progress...", 0, label="Ramping up...") + try: + if hasattr(MacOS, 'SchedParams'): + appsw = MacOS.SchedParams(1, 0) + for i in xrange(20): + bar.inc() + time.sleep(0.05) + bar.set(0,100) + for i in xrange(100): + bar.set(i) + time.sleep(0.05) + if i % 10 == 0: + bar.label(text[(i/10) % 4]) + bar.label("Done.") + time.sleep(1.0) # give'em a chance to see "Done." + finally: + del bar + if hasattr(MacOS, 'SchedParams'): + MacOS.SchedParams(*appsw) if __name__ == '__main__': - try: - test() - except KeyboardInterrupt: - Message("Operation Canceled.") + try: + test() + except KeyboardInterrupt: + Message("Operation Canceled.") diff --git a/Lib/plat-mac/FrameWork.py b/Lib/plat-mac/FrameWork.py index f465d84..8eec4b8 100644 --- a/Lib/plat-mac/FrameWork.py +++ b/Lib/plat-mac/FrameWork.py @@ -29,12 +29,12 @@ import types import EasyDialogs try: - MyFrontWindow = FrontNonFloatingWindow + MyFrontWindow = FrontNonFloatingWindow except NameError: - MyFrontWindow = FrontWindow + MyFrontWindow = FrontWindow -kHighLevelEvent = 23 # Don't know what header file this should come from -SCROLLBARWIDTH = 16 # Again, not a clue... +kHighLevelEvent = 23 # Don't know what header file this should come from +SCROLLBARWIDTH = 16 # Again, not a clue... # Trick to forestall a set of SIOUX menus being added to our menubar SIOUX_APPLEMENU_ID=32000 @@ -67,1057 +67,1057 @@ partname[8] = 'inZoomOut' # # The useable portion of the screen -# ## but what happens with multiple screens? jvr +# ## but what happens with multiple screens? jvr screenbounds = GetQDGlobalsScreenBits().bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ - screenbounds[2]-4, screenbounds[3]-4 - -next_window_x = 16 # jvr -next_window_y = 44 # jvr + screenbounds[2]-4, screenbounds[3]-4 + +next_window_x = 16 # jvr +next_window_y = 44 # jvr def windowbounds(width, height): - "Return sensible window bounds" - global next_window_x, next_window_y - r, b = next_window_x+width, next_window_y+height - if r > screenbounds[2]: - next_window_x = 16 - if b > screenbounds[3]: - next_window_y = 44 - l, t = next_window_x, next_window_y - r, b = next_window_x+width, next_window_y+height - next_window_x, next_window_y = next_window_x + 8, next_window_y + 20 # jvr - return l, t, r, b + "Return sensible window bounds" + global next_window_x, next_window_y + r, b = next_window_x+width, next_window_y+height + if r > screenbounds[2]: + next_window_x = 16 + if b > screenbounds[3]: + next_window_y = 44 + l, t = next_window_x, next_window_y + r, b = next_window_x+width, next_window_y+height + next_window_x, next_window_y = next_window_x + 8, next_window_y + 20 # jvr + return l, t, r, b _watch = None def setwatchcursor(): - global _watch - - if _watch == None: - _watch = GetCursor(4).data - SetCursor(_watch) - + global _watch + + if _watch == None: + _watch = GetCursor(4).data + SetCursor(_watch) + def setarrowcursor(): - SetCursor(GetQDGlobalsArrow()) + SetCursor(GetQDGlobalsArrow()) class Application: - - "Application framework -- your application should be a derived class" - - def __init__(self, nomenubar=0): - self._doing_asyncevents = 0 - self.quitting = 0 - self.needmenubarredraw = 0 - self._windows = {} - self._helpmenu = None - if nomenubar: - self.menubar = None - else: - self.makemenubar() - - def __del__(self): - if self._doing_asyncevents: - self._doing_asyncevents = 0 - MacOS.SetEventHandler() - - def makemenubar(self): - self.menubar = MenuBar(self) - AppleMenu(self.menubar, self.getabouttext(), self.do_about) - self.makeusermenus() - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self._quititem = MenuItem(m, "Quit", "Q", self._quit) - - def gethelpmenu(self): - if self._helpmenu == None: - self._helpmenu = HelpMenu(self.menubar) - return self._helpmenu - - def _quit(self, *args): - self.quitting = 1 - - def cleanup(self): - for w in self._windows.values(): - w.do_close() - return self._windows == {} - - def appendwindow(self, wid, window): - self._windows[wid] = window - - def removewindow(self, wid): - del self._windows[wid] - - def getabouttext(self): - return "About %s..." % self.__class__.__name__ - - def do_about(self, id, item, window, event): - EasyDialogs.Message("Hello, world!" + "\015(%s)" % self.__class__.__name__) - - # The main event loop is broken up in several simple steps. - # This is done so you can override each individual part, - # if you have a need to do extra processing independent of the - # event type. - # Normally, however, you'd just define handlers for individual - # events. - - schedparams = (0, 0) # By default disable Python's event handling - default_wait = None # By default we wait GetCaretTime in WaitNextEvent - - def mainloop(self, mask = everyEvent, wait = None): - self.quitting = 0 - if hasattr(MacOS, 'SchedParams'): - saveparams = apply(MacOS.SchedParams, self.schedparams) - try: - while not self.quitting: - try: - self.do1event(mask, wait) - except (Application, SystemExit): - # Note: the raising of "self" is old-fashioned idiom to - # exit the mainloop. Calling _quit() is better for new - # applications. - break - finally: - if hasattr(MacOS, 'SchedParams'): - apply(MacOS.SchedParams, saveparams) - - def dopendingevents(self, mask = everyEvent): - """dopendingevents - Handle all pending events""" - while self.do1event(mask, wait=0): - pass - - def do1event(self, mask = everyEvent, wait = None): - ok, event = self.getevent(mask, wait) - if IsDialogEvent(event): - if self.do_dialogevent(event): - return - if ok: - self.dispatch(event) - else: - self.idle(event) - - def idle(self, event): - pass - - def getevent(self, mask = everyEvent, wait = None): - if self.needmenubarredraw: - DrawMenuBar() - self.needmenubarredraw = 0 - if wait is None: - wait = self.default_wait - if wait is None: - wait = GetCaretTime() - ok, event = WaitNextEvent(mask, wait) - return ok, event - - def dispatch(self, event): - # The following appears to be double work (already done in do1event) - # but we need it for asynchronous event handling - if IsDialogEvent(event): - if self.do_dialogevent(event): - return - (what, message, when, where, modifiers) = event - if eventname.has_key(what): - name = "do_" + eventname[what] - else: - name = "do_%d" % what - try: - handler = getattr(self, name) - except AttributeError: - handler = self.do_unknownevent - handler(event) - - def asyncevents(self, onoff): - """asyncevents - Set asynchronous event handling on or off""" - if MacOS.runtimemodel == 'macho': - raise 'Unsupported in MachoPython' - old = self._doing_asyncevents - if old: - MacOS.SetEventHandler() - apply(MacOS.SchedParams, self.schedparams) - if onoff: - MacOS.SetEventHandler(self.dispatch) - doint, dummymask, benice, howoften, bgyield = \ - self.schedparams - MacOS.SchedParams(doint, everyEvent, benice, - howoften, bgyield) - self._doing_asyncevents = onoff - return old - - def do_dialogevent(self, event): - gotone, dlg, item = DialogSelect(event) - if gotone: - window = dlg.GetDialogWindow() - if self._windows.has_key(window): - self._windows[window].do_itemhit(item, event) - else: - print 'Dialog event for unknown dialog' - return 1 - return 0 - - def do_mouseDown(self, event): - (what, message, when, where, modifiers) = event - partcode, wid = FindWindow(where) - - # - # Find the correct name. - # - if partname.has_key(partcode): - name = "do_" + partname[partcode] - else: - name = "do_%d" % partcode - - if wid == None: - # No window, or a non-python window - try: - handler = getattr(self, name) - except AttributeError: - # Not menubar or something, so assume someone - # else's window - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - return - elif self._windows.has_key(wid): - # It is a window. Hand off to correct window. - window = self._windows[wid] - try: - handler = getattr(window, name) - except AttributeError: - handler = self.do_unknownpartcode - else: - # It is a python-toolbox window, but not ours. - handler = self.do_unknownwindow - handler(partcode, wid, event) - - def do_inSysWindow(self, partcode, window, event): - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_inDesk(self, partcode, window, event): - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_inMenuBar(self, partcode, window, event): - if not self.menubar: - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - return - (what, message, when, where, modifiers) = event - result = MenuSelect(where) - id = (result>>16) & 0xffff # Hi word - if id >= 0x8000: - id = -65536 + id - item = result & 0xffff # Lo word - self.do_rawmenu(id, item, window, event) - - def do_rawmenu(self, id, item, window, event): - try: - self.do_menu(id, item, window, event) - finally: - HiliteMenu(0) - - def do_menu(self, id, item, window, event): - if hasattr(MacOS, 'OutputSeen'): - MacOS.OutputSeen() - self.menubar.dispatch(id, item, window, event) - - - def do_unknownpartcode(self, partcode, window, event): - (what, message, when, where, modifiers) = event - if DEBUG: print "Mouse down at global:", where - if DEBUG: print "\tUnknown part code:", partcode - if DEBUG: print "\tEvent:", self.printevent(event) - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_unknownwindow(self, partcode, window, event): - if DEBUG: print 'Unknown window:', window - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_keyDown(self, event): - self.do_key(event) - - def do_autoKey(self, event): - if not event[-1] & cmdKey: - self.do_key(event) - - def do_key(self, event): - (what, message, when, where, modifiers) = event - c = chr(message & charCodeMask) - if self.menubar: - result = MenuEvent(event) - id = (result>>16) & 0xffff # Hi word - item = result & 0xffff # Lo word - if id: - self.do_rawmenu(id, item, None, event) - return - # Otherwise we fall-through - if modifiers & cmdKey: - if c == '.': - raise self - else: - if not self.menubar: - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - return - else: - # See whether the front window wants it - w = MyFrontWindow() - if w and self._windows.has_key(w): - window = self._windows[w] - try: - do_char = window.do_char - except AttributeError: - do_char = self.do_char - do_char(c, event) - # else it wasn't for us, sigh... - - def do_char(self, c, event): - if DEBUG: print "Character", `c` - - def do_updateEvt(self, event): - (what, message, when, where, modifiers) = event - wid = WhichWindow(message) - if wid and self._windows.has_key(wid): - window = self._windows[wid] - window.do_rawupdate(wid, event) - else: - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_activateEvt(self, event): - (what, message, when, where, modifiers) = event - wid = WhichWindow(message) - if wid and self._windows.has_key(wid): - window = self._windows[wid] - window.do_activate(modifiers & 1, event) - else: - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - - def do_osEvt(self, event): - (what, message, when, where, modifiers) = event - which = (message >> 24) & 0xff - if which == 1: # suspend/resume - self.do_suspendresume(event) - else: - if DEBUG: - print 'unknown osEvt:', - self.printevent(event) - - def do_suspendresume(self, event): - (what, message, when, where, modifiers) = event - wid = MyFrontWindow() - if wid and self._windows.has_key(wid): - window = self._windows[wid] - window.do_activate(message & 1, event) - - def do_kHighLevelEvent(self, event): - (what, message, when, where, modifiers) = event - if DEBUG: - print "High Level Event:", - self.printevent(event) - try: - AEProcessAppleEvent(event) - except: - pass - #print "AEProcessAppleEvent error:" - #traceback.print_exc() - - def do_unknownevent(self, event): - if DEBUG: - print "Unhandled event:", - self.printevent(event) - - def printevent(self, event): - (what, message, when, where, modifiers) = event - nicewhat = `what` - if eventname.has_key(what): - nicewhat = eventname[what] - print nicewhat, - if what == kHighLevelEvent: - h, v = where - print `ostypecode(message)`, hex(when), `ostypecode(h | (v<<16))`, - else: - print hex(message), hex(when), where, - print hex(modifiers) + + "Application framework -- your application should be a derived class" + + def __init__(self, nomenubar=0): + self._doing_asyncevents = 0 + self.quitting = 0 + self.needmenubarredraw = 0 + self._windows = {} + self._helpmenu = None + if nomenubar: + self.menubar = None + else: + self.makemenubar() + + def __del__(self): + if self._doing_asyncevents: + self._doing_asyncevents = 0 + MacOS.SetEventHandler() + + def makemenubar(self): + self.menubar = MenuBar(self) + AppleMenu(self.menubar, self.getabouttext(), self.do_about) + self.makeusermenus() + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self._quititem = MenuItem(m, "Quit", "Q", self._quit) + + def gethelpmenu(self): + if self._helpmenu == None: + self._helpmenu = HelpMenu(self.menubar) + return self._helpmenu + + def _quit(self, *args): + self.quitting = 1 + + def cleanup(self): + for w in self._windows.values(): + w.do_close() + return self._windows == {} + + def appendwindow(self, wid, window): + self._windows[wid] = window + + def removewindow(self, wid): + del self._windows[wid] + + def getabouttext(self): + return "About %s..." % self.__class__.__name__ + + def do_about(self, id, item, window, event): + EasyDialogs.Message("Hello, world!" + "\015(%s)" % self.__class__.__name__) + + # The main event loop is broken up in several simple steps. + # This is done so you can override each individual part, + # if you have a need to do extra processing independent of the + # event type. + # Normally, however, you'd just define handlers for individual + # events. + + schedparams = (0, 0) # By default disable Python's event handling + default_wait = None # By default we wait GetCaretTime in WaitNextEvent + + def mainloop(self, mask = everyEvent, wait = None): + self.quitting = 0 + if hasattr(MacOS, 'SchedParams'): + saveparams = MacOS.SchedParams(*self.schedparams) + try: + while not self.quitting: + try: + self.do1event(mask, wait) + except (Application, SystemExit): + # Note: the raising of "self" is old-fashioned idiom to + # exit the mainloop. Calling _quit() is better for new + # applications. + break + finally: + if hasattr(MacOS, 'SchedParams'): + MacOS.SchedParams(*saveparams) + + def dopendingevents(self, mask = everyEvent): + """dopendingevents - Handle all pending events""" + while self.do1event(mask, wait=0): + pass + + def do1event(self, mask = everyEvent, wait = None): + ok, event = self.getevent(mask, wait) + if IsDialogEvent(event): + if self.do_dialogevent(event): + return + if ok: + self.dispatch(event) + else: + self.idle(event) + + def idle(self, event): + pass + + def getevent(self, mask = everyEvent, wait = None): + if self.needmenubarredraw: + DrawMenuBar() + self.needmenubarredraw = 0 + if wait is None: + wait = self.default_wait + if wait is None: + wait = GetCaretTime() + ok, event = WaitNextEvent(mask, wait) + return ok, event + + def dispatch(self, event): + # The following appears to be double work (already done in do1event) + # but we need it for asynchronous event handling + if IsDialogEvent(event): + if self.do_dialogevent(event): + return + (what, message, when, where, modifiers) = event + if eventname.has_key(what): + name = "do_" + eventname[what] + else: + name = "do_%d" % what + try: + handler = getattr(self, name) + except AttributeError: + handler = self.do_unknownevent + handler(event) + + def asyncevents(self, onoff): + """asyncevents - Set asynchronous event handling on or off""" + if MacOS.runtimemodel == 'macho': + raise 'Unsupported in MachoPython' + old = self._doing_asyncevents + if old: + MacOS.SetEventHandler() + MacOS.SchedParams(*self.schedparams) + if onoff: + MacOS.SetEventHandler(self.dispatch) + doint, dummymask, benice, howoften, bgyield = \ + self.schedparams + MacOS.SchedParams(doint, everyEvent, benice, + howoften, bgyield) + self._doing_asyncevents = onoff + return old + + def do_dialogevent(self, event): + gotone, dlg, item = DialogSelect(event) + if gotone: + window = dlg.GetDialogWindow() + if self._windows.has_key(window): + self._windows[window].do_itemhit(item, event) + else: + print 'Dialog event for unknown dialog' + return 1 + return 0 + + def do_mouseDown(self, event): + (what, message, when, where, modifiers) = event + partcode, wid = FindWindow(where) + + # + # Find the correct name. + # + if partname.has_key(partcode): + name = "do_" + partname[partcode] + else: + name = "do_%d" % partcode + + if wid == None: + # No window, or a non-python window + try: + handler = getattr(self, name) + except AttributeError: + # Not menubar or something, so assume someone + # else's window + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + return + elif self._windows.has_key(wid): + # It is a window. Hand off to correct window. + window = self._windows[wid] + try: + handler = getattr(window, name) + except AttributeError: + handler = self.do_unknownpartcode + else: + # It is a python-toolbox window, but not ours. + handler = self.do_unknownwindow + handler(partcode, wid, event) + + def do_inSysWindow(self, partcode, window, event): + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_inDesk(self, partcode, window, event): + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_inMenuBar(self, partcode, window, event): + if not self.menubar: + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + return + (what, message, when, where, modifiers) = event + result = MenuSelect(where) + id = (result>>16) & 0xffff # Hi word + if id >= 0x8000: + id = -65536 + id + item = result & 0xffff # Lo word + self.do_rawmenu(id, item, window, event) + + def do_rawmenu(self, id, item, window, event): + try: + self.do_menu(id, item, window, event) + finally: + HiliteMenu(0) + + def do_menu(self, id, item, window, event): + if hasattr(MacOS, 'OutputSeen'): + MacOS.OutputSeen() + self.menubar.dispatch(id, item, window, event) + + + def do_unknownpartcode(self, partcode, window, event): + (what, message, when, where, modifiers) = event + if DEBUG: print "Mouse down at global:", where + if DEBUG: print "\tUnknown part code:", partcode + if DEBUG: print "\tEvent:", self.printevent(event) + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_unknownwindow(self, partcode, window, event): + if DEBUG: print 'Unknown window:', window + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_keyDown(self, event): + self.do_key(event) + + def do_autoKey(self, event): + if not event[-1] & cmdKey: + self.do_key(event) + + def do_key(self, event): + (what, message, when, where, modifiers) = event + c = chr(message & charCodeMask) + if self.menubar: + result = MenuEvent(event) + id = (result>>16) & 0xffff # Hi word + item = result & 0xffff # Lo word + if id: + self.do_rawmenu(id, item, None, event) + return + # Otherwise we fall-through + if modifiers & cmdKey: + if c == '.': + raise self + else: + if not self.menubar: + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + return + else: + # See whether the front window wants it + w = MyFrontWindow() + if w and self._windows.has_key(w): + window = self._windows[w] + try: + do_char = window.do_char + except AttributeError: + do_char = self.do_char + do_char(c, event) + # else it wasn't for us, sigh... + + def do_char(self, c, event): + if DEBUG: print "Character", `c` + + def do_updateEvt(self, event): + (what, message, when, where, modifiers) = event + wid = WhichWindow(message) + if wid and self._windows.has_key(wid): + window = self._windows[wid] + window.do_rawupdate(wid, event) + else: + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_activateEvt(self, event): + (what, message, when, where, modifiers) = event + wid = WhichWindow(message) + if wid and self._windows.has_key(wid): + window = self._windows[wid] + window.do_activate(modifiers & 1, event) + else: + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + + def do_osEvt(self, event): + (what, message, when, where, modifiers) = event + which = (message >> 24) & 0xff + if which == 1: # suspend/resume + self.do_suspendresume(event) + else: + if DEBUG: + print 'unknown osEvt:', + self.printevent(event) + + def do_suspendresume(self, event): + (what, message, when, where, modifiers) = event + wid = MyFrontWindow() + if wid and self._windows.has_key(wid): + window = self._windows[wid] + window.do_activate(message & 1, event) + + def do_kHighLevelEvent(self, event): + (what, message, when, where, modifiers) = event + if DEBUG: + print "High Level Event:", + self.printevent(event) + try: + AEProcessAppleEvent(event) + except: + pass + #print "AEProcessAppleEvent error:" + #traceback.print_exc() + + def do_unknownevent(self, event): + if DEBUG: + print "Unhandled event:", + self.printevent(event) + + def printevent(self, event): + (what, message, when, where, modifiers) = event + nicewhat = `what` + if eventname.has_key(what): + nicewhat = eventname[what] + print nicewhat, + if what == kHighLevelEvent: + h, v = where + print `ostypecode(message)`, hex(when), `ostypecode(h | (v<<16))`, + else: + print hex(message), hex(when), where, + print hex(modifiers) class MenuBar: - """Represent a set of menus in a menu bar. - - Interface: - - - (constructor) - - (destructor) - - addmenu - - addpopup (normally used internally) - - dispatch (called from Application) - """ - - nextid = 1 # Necessarily a class variable - - def getnextid(self): - id = MenuBar.nextid - MenuBar.nextid = id+1 - return id - - def __init__(self, parent=None): - self.parent = parent - ClearMenuBar() - self.bar = GetMenuBar() - self.menus = {} - - # XXX necessary? - def close(self): - self.parent = None - self.bar = None - self.menus = None - - def addmenu(self, title, after = 0, id=None): - if id == None: - id = self.getnextid() - if DEBUG: print 'Newmenu', title, id # XXXX - m = NewMenu(id, title) - m.InsertMenu(after) - if after >= 0: - if self.parent: - self.parent.needmenubarredraw = 1 - else: - DrawMenuBar() - return id, m - - def delmenu(self, id): - if DEBUG: print 'Delmenu', id # XXXX - DeleteMenu(id) - - def addpopup(self, title = ''): - return self.addmenu(title, -1) - -# Useless: -# def install(self): -# if not self.bar: return -# SetMenuBar(self.bar) -# if self.parent: -# self.parent.needmenubarredraw = 1 -# else: -# DrawMenuBar() - - def fixmenudimstate(self): - for m in self.menus.keys(): - menu = self.menus[m] - if menu.__class__ == FrameWork.AppleMenu: - continue - for i in range(len(menu.items)): - label, shortcut, callback, kind = menu.items[i] - if type(callback) == types.StringType: - wid = MyFrontWindow() - if wid and self.parent._windows.has_key(wid): - window = self.parent._windows[wid] - if hasattr(window, "domenu_" + callback): - menu.menu.EnableMenuItem(i + 1) - elif hasattr(self.parent, "domenu_" + callback): - menu.menu.EnableMenuItem(i + 1) - else: - menu.menu.DisableMenuItem(i + 1) - elif hasattr(self.parent, "domenu_" + callback): - menu.menu.EnableMenuItem(i + 1) - else: - menu.menu.DisableMenuItem(i + 1) - elif callback: - pass - - def dispatch(self, id, item, window, event): - if self.menus.has_key(id): - self.menus[id].dispatch(id, item, window, event) - else: - if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ - (id, item, window, event) - + """Represent a set of menus in a menu bar. + + Interface: + + - (constructor) + - (destructor) + - addmenu + - addpopup (normally used internally) + - dispatch (called from Application) + """ + + nextid = 1 # Necessarily a class variable + + def getnextid(self): + id = MenuBar.nextid + MenuBar.nextid = id+1 + return id + + def __init__(self, parent=None): + self.parent = parent + ClearMenuBar() + self.bar = GetMenuBar() + self.menus = {} + + # XXX necessary? + def close(self): + self.parent = None + self.bar = None + self.menus = None + + def addmenu(self, title, after = 0, id=None): + if id == None: + id = self.getnextid() + if DEBUG: print 'Newmenu', title, id # XXXX + m = NewMenu(id, title) + m.InsertMenu(after) + if after >= 0: + if self.parent: + self.parent.needmenubarredraw = 1 + else: + DrawMenuBar() + return id, m + + def delmenu(self, id): + if DEBUG: print 'Delmenu', id # XXXX + DeleteMenu(id) + + def addpopup(self, title = ''): + return self.addmenu(title, -1) + +# Useless: +# def install(self): +# if not self.bar: return +# SetMenuBar(self.bar) +# if self.parent: +# self.parent.needmenubarredraw = 1 +# else: +# DrawMenuBar() + + def fixmenudimstate(self): + for m in self.menus.keys(): + menu = self.menus[m] + if menu.__class__ == FrameWork.AppleMenu: + continue + for i in range(len(menu.items)): + label, shortcut, callback, kind = menu.items[i] + if type(callback) == types.StringType: + wid = MyFrontWindow() + if wid and self.parent._windows.has_key(wid): + window = self.parent._windows[wid] + if hasattr(window, "domenu_" + callback): + menu.menu.EnableMenuItem(i + 1) + elif hasattr(self.parent, "domenu_" + callback): + menu.menu.EnableMenuItem(i + 1) + else: + menu.menu.DisableMenuItem(i + 1) + elif hasattr(self.parent, "domenu_" + callback): + menu.menu.EnableMenuItem(i + 1) + else: + menu.menu.DisableMenuItem(i + 1) + elif callback: + pass + + def dispatch(self, id, item, window, event): + if self.menus.has_key(id): + self.menus[id].dispatch(id, item, window, event) + else: + if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ + (id, item, window, event) + # XXX Need a way to get menus as resources and bind them to callbacks class Menu: - "One menu." - - def __init__(self, bar, title, after=0, id=None): - self.bar = bar - self.id, self.menu = self.bar.addmenu(title, after, id) - bar.menus[self.id] = self - self.items = [] - self._parent = None - - def delete(self): - self.bar.delmenu(self.id) - del self.bar.menus[self.id] - self.menu.DisposeMenu() - del self.bar - del self.items - del self.menu - del self.id - del self._parent - - def additem(self, label, shortcut=None, callback=None, kind=None): - self.menu.AppendMenu('x') # add a dummy string - self.items.append((label, shortcut, callback, kind)) - item = len(self.items) - if isinstance(label, unicode): - self.menu.SetMenuItemTextWithCFString(item, label) - else: - self.menu.SetMenuItemText(item, label) - if shortcut and type(shortcut) == type(()): - modifiers, char = shortcut[:2] - self.menu.SetItemCmd(item, ord(char)) - self.menu.SetMenuItemModifiers(item, modifiers) - if len(shortcut) > 2: - self.menu.SetMenuItemKeyGlyph(item, shortcut[2]) - elif shortcut: - self.menu.SetItemCmd(item, ord(shortcut)) - return item - - def delitem(self, item): - if item != len(self.items): - raise 'Can only delete last item of a menu' - self.menu.DeleteMenuItem(item) - del self.items[item-1] - - def addcheck(self, label, shortcut=None, callback=None): - return self.additem(label, shortcut, callback, 'check') - - def addradio(self, label, shortcut=None, callback=None): - return self.additem(label, shortcut, callback, 'radio') - - def addseparator(self): - self.menu.AppendMenu('(-') - self.items.append(('', None, None, 'separator')) - - def addsubmenu(self, label, title=''): - sub = Menu(self.bar, title, -1) - item = self.additem(label, '\x1B', None, 'submenu') - self.menu.SetItemMark(item, sub.id) - sub._parent = self - sub._parent_item = item - return sub - - def dispatch(self, id, item, window, event): - title, shortcut, callback, mtype = self.items[item-1] - if callback: - if not self.bar.parent or type(callback) <> types.StringType: - menuhandler = callback - else: - # callback is string - wid = MyFrontWindow() - if wid and self.bar.parent._windows.has_key(wid): - window = self.bar.parent._windows[wid] - if hasattr(window, "domenu_" + callback): - menuhandler = getattr(window, "domenu_" + callback) - elif hasattr(self.bar.parent, "domenu_" + callback): - menuhandler = getattr(self.bar.parent, "domenu_" + callback) - else: - # nothing we can do. we shouldn't have come this far - # since the menu item should have been disabled... - return - elif hasattr(self.bar.parent, "domenu_" + callback): - menuhandler = getattr(self.bar.parent, "domenu_" + callback) - else: - # nothing we can do. we shouldn't have come this far - # since the menu item should have been disabled... - return - menuhandler(id, item, window, event) - - def enable(self, onoff): - if onoff: - self.menu.EnableMenuItem(0) - if self._parent: - self._parent.menu.EnableMenuItem(self._parent_item) - else: - self.menu.DisableMenuItem(0) - if self._parent: - self._parent.menu.DisableMenuItem(self._parent_item) - if self.bar and self.bar.parent: - self.bar.parent.needmenubarredraw = 1 - + "One menu." + + def __init__(self, bar, title, after=0, id=None): + self.bar = bar + self.id, self.menu = self.bar.addmenu(title, after, id) + bar.menus[self.id] = self + self.items = [] + self._parent = None + + def delete(self): + self.bar.delmenu(self.id) + del self.bar.menus[self.id] + self.menu.DisposeMenu() + del self.bar + del self.items + del self.menu + del self.id + del self._parent + + def additem(self, label, shortcut=None, callback=None, kind=None): + self.menu.AppendMenu('x') # add a dummy string + self.items.append((label, shortcut, callback, kind)) + item = len(self.items) + if isinstance(label, unicode): + self.menu.SetMenuItemTextWithCFString(item, label) + else: + self.menu.SetMenuItemText(item, label) + if shortcut and type(shortcut) == type(()): + modifiers, char = shortcut[:2] + self.menu.SetItemCmd(item, ord(char)) + self.menu.SetMenuItemModifiers(item, modifiers) + if len(shortcut) > 2: + self.menu.SetMenuItemKeyGlyph(item, shortcut[2]) + elif shortcut: + self.menu.SetItemCmd(item, ord(shortcut)) + return item + + def delitem(self, item): + if item != len(self.items): + raise 'Can only delete last item of a menu' + self.menu.DeleteMenuItem(item) + del self.items[item-1] + + def addcheck(self, label, shortcut=None, callback=None): + return self.additem(label, shortcut, callback, 'check') + + def addradio(self, label, shortcut=None, callback=None): + return self.additem(label, shortcut, callback, 'radio') + + def addseparator(self): + self.menu.AppendMenu('(-') + self.items.append(('', None, None, 'separator')) + + def addsubmenu(self, label, title=''): + sub = Menu(self.bar, title, -1) + item = self.additem(label, '\x1B', None, 'submenu') + self.menu.SetItemMark(item, sub.id) + sub._parent = self + sub._parent_item = item + return sub + + def dispatch(self, id, item, window, event): + title, shortcut, callback, mtype = self.items[item-1] + if callback: + if not self.bar.parent or type(callback) <> types.StringType: + menuhandler = callback + else: + # callback is string + wid = MyFrontWindow() + if wid and self.bar.parent._windows.has_key(wid): + window = self.bar.parent._windows[wid] + if hasattr(window, "domenu_" + callback): + menuhandler = getattr(window, "domenu_" + callback) + elif hasattr(self.bar.parent, "domenu_" + callback): + menuhandler = getattr(self.bar.parent, "domenu_" + callback) + else: + # nothing we can do. we shouldn't have come this far + # since the menu item should have been disabled... + return + elif hasattr(self.bar.parent, "domenu_" + callback): + menuhandler = getattr(self.bar.parent, "domenu_" + callback) + else: + # nothing we can do. we shouldn't have come this far + # since the menu item should have been disabled... + return + menuhandler(id, item, window, event) + + def enable(self, onoff): + if onoff: + self.menu.EnableMenuItem(0) + if self._parent: + self._parent.menu.EnableMenuItem(self._parent_item) + else: + self.menu.DisableMenuItem(0) + if self._parent: + self._parent.menu.DisableMenuItem(self._parent_item) + if self.bar and self.bar.parent: + self.bar.parent.needmenubarredraw = 1 + class PopupMenu(Menu): - def __init__(self, bar): - Menu.__init__(self, bar, '(popup)', -1) - - def popup(self, x, y, event, default=1, window=None): - # NOTE that x and y are global coordinates, and they should probably - # be topleft of the button the user clicked (not mouse-coordinates), - # so the popup nicely overlaps. - reply = self.menu.PopUpMenuSelect(x, y, default) - if not reply: - return - id = (reply >> 16) & 0xffff - item = reply & 0xffff - if not window: - wid = MyFrontWindow() - try: - window = self.bar.parent._windows[wid] - except: - pass # If we can't find the window we pass None - self.dispatch(id, item, window, event) + def __init__(self, bar): + Menu.__init__(self, bar, '(popup)', -1) + + def popup(self, x, y, event, default=1, window=None): + # NOTE that x and y are global coordinates, and they should probably + # be topleft of the button the user clicked (not mouse-coordinates), + # so the popup nicely overlaps. + reply = self.menu.PopUpMenuSelect(x, y, default) + if not reply: + return + id = (reply >> 16) & 0xffff + item = reply & 0xffff + if not window: + wid = MyFrontWindow() + try: + window = self.bar.parent._windows[wid] + except: + pass # If we can't find the window we pass None + self.dispatch(id, item, window, event) class MenuItem: - def __init__(self, menu, title, shortcut=None, callback=None, kind=None): - self.item = menu.additem(title, shortcut, callback) - self.menu = menu - - def delete(self): - self.menu.delitem(self.item) - del self.menu - del self.item - - def check(self, onoff): - self.menu.menu.CheckMenuItem(self.item, onoff) - - def enable(self, onoff): - if onoff: - self.menu.menu.EnableMenuItem(self.item) - else: - self.menu.menu.DisableMenuItem(self.item) - - def settext(self, text): - self.menu.menu.SetMenuItemText(self.item, text) - - def setstyle(self, style): - self.menu.menu.SetItemStyle(self.item, style) - - def seticon(self, icon): - self.menu.menu.SetItemIcon(self.item, icon) - - def setcmd(self, cmd): - self.menu.menu.SetItemCmd(self.item, cmd) - - def setmark(self, cmd): - self.menu.menu.SetItemMark(self.item, cmd) - + def __init__(self, menu, title, shortcut=None, callback=None, kind=None): + self.item = menu.additem(title, shortcut, callback) + self.menu = menu + + def delete(self): + self.menu.delitem(self.item) + del self.menu + del self.item + + def check(self, onoff): + self.menu.menu.CheckMenuItem(self.item, onoff) + + def enable(self, onoff): + if onoff: + self.menu.menu.EnableMenuItem(self.item) + else: + self.menu.menu.DisableMenuItem(self.item) + + def settext(self, text): + self.menu.menu.SetMenuItemText(self.item, text) + + def setstyle(self, style): + self.menu.menu.SetItemStyle(self.item, style) + + def seticon(self, icon): + self.menu.menu.SetItemIcon(self.item, icon) + + def setcmd(self, cmd): + self.menu.menu.SetItemCmd(self.item, cmd) + + def setmark(self, cmd): + self.menu.menu.SetItemMark(self.item, cmd) + class RadioItem(MenuItem): - def __init__(self, menu, title, shortcut=None, callback=None): - MenuItem.__init__(self, menu, title, shortcut, callback, 'radio') + def __init__(self, menu, title, shortcut=None, callback=None): + MenuItem.__init__(self, menu, title, shortcut, callback, 'radio') class CheckItem(MenuItem): - def __init__(self, menu, title, shortcut=None, callback=None): - MenuItem.__init__(self, menu, title, shortcut, callback, 'check') + def __init__(self, menu, title, shortcut=None, callback=None): + MenuItem.__init__(self, menu, title, shortcut, callback, 'check') def Separator(menu): - menu.addseparator() + menu.addseparator() def SubMenu(menu, label, title=''): - return menu.addsubmenu(label, title) + return menu.addsubmenu(label, title) class AppleMenu(Menu): - - def __init__(self, bar, abouttext="About me...", aboutcallback=None): - Menu.__init__(self, bar, "\024", id=SIOUX_APPLEMENU_ID) - if MacOS.runtimemodel == 'ppc': - self.additem(abouttext, None, aboutcallback) - self.addseparator() - self.menu.AppendResMenu('DRVR') - else: - # Additem()'s tricks do not work for "apple" menu under Carbon - self.menu.InsertMenuItem(abouttext, 0) - self.items.append((abouttext, None, aboutcallback, None)) - - def dispatch(self, id, item, window, event): - if item == 1: - Menu.dispatch(self, id, item, window, event) - elif MacOS.runtimemodel == 'ppc': - name = self.menu.GetMenuItemText(item) - OpenDeskAcc(name) - + + def __init__(self, bar, abouttext="About me...", aboutcallback=None): + Menu.__init__(self, bar, "\024", id=SIOUX_APPLEMENU_ID) + if MacOS.runtimemodel == 'ppc': + self.additem(abouttext, None, aboutcallback) + self.addseparator() + self.menu.AppendResMenu('DRVR') + else: + # Additem()'s tricks do not work for "apple" menu under Carbon + self.menu.InsertMenuItem(abouttext, 0) + self.items.append((abouttext, None, aboutcallback, None)) + + def dispatch(self, id, item, window, event): + if item == 1: + Menu.dispatch(self, id, item, window, event) + elif MacOS.runtimemodel == 'ppc': + name = self.menu.GetMenuItemText(item) + OpenDeskAcc(name) + class HelpMenu(Menu): - def __init__(self, bar): - # Note we don't call Menu.__init__, we do the necessary things by hand - self.bar = bar - self.menu, index = HMGetHelpMenu() - self.id = self.menu.GetMenuID() - bar.menus[self.id] = self - # The next line caters for the entries the system already handles for us - self.items = [None]*(index-1) - self._parent = None - + def __init__(self, bar): + # Note we don't call Menu.__init__, we do the necessary things by hand + self.bar = bar + self.menu, index = HMGetHelpMenu() + self.id = self.menu.GetMenuID() + bar.menus[self.id] = self + # The next line caters for the entries the system already handles for us + self.items = [None]*(index-1) + self._parent = None + class Window: - """A single window belonging to an application""" - - def __init__(self, parent): - self.wid = None - self.parent = parent - - def open(self, bounds=(40, 40, 400, 400), resid=None): - if resid <> None: - self.wid = GetNewWindow(resid, -1) - else: - self.wid = NewWindow(bounds, self.__class__.__name__, 1, - 8, -1, 1, 0) # changed to proc id 8 to include zoom box. jvr - self.do_postopen() - - def do_postopen(self): - """Tell our parent we exist""" - self.parent.appendwindow(self.wid, self) - - def close(self): - self.do_postclose() - - def do_postclose(self): - self.parent.removewindow(self.wid) - self.parent = None - self.wid = None - - def SetPort(self): - # Convinience method - SetPort(self.wid) - - def GetWindow(self): - return self.wid - - def do_inDrag(self, partcode, window, event): - where = event[3] - window.DragWindow(where, self.draglimit) - - draglimit = screenbounds - - def do_inGoAway(self, partcode, window, event): - where = event[3] - if window.TrackGoAway(where): - self.close() - - def do_inZoom(self, partcode, window, event): - (what, message, when, where, modifiers) = event - if window.TrackBox(where, partcode): - window.ZoomWindow(partcode, 1) - rect = window.GetWindowUserState() # so that zoom really works... jvr - self.do_postresize(rect[2] - rect[0], rect[3] - rect[1], window) # jvr - - def do_inZoomIn(self, partcode, window, event): - SetPort(window) # !!! - self.do_inZoom(partcode, window, event) - - def do_inZoomOut(self, partcode, window, event): - SetPort(window) # !!! - self.do_inZoom(partcode, window, event) - - def do_inGrow(self, partcode, window, event): - (what, message, when, where, modifiers) = event - result = window.GrowWindow(where, self.growlimit) - if result: - height = (result>>16) & 0xffff # Hi word - width = result & 0xffff # Lo word - self.do_resize(width, height, window) - - growlimit = (50, 50, screenbounds[2] - screenbounds[0], screenbounds[3] - screenbounds[1]) # jvr - - def do_resize(self, width, height, window): - l, t, r, b = self.wid.GetWindowPort().GetPortBounds() # jvr, forGrowIcon - self.SetPort() # jvr - self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr - window.SizeWindow(width, height, 1) # changed updateFlag to true jvr - self.do_postresize(width, height, window) - - def do_postresize(self, width, height, window): - SetPort(window) - self.wid.InvalWindowRect(window.GetWindowPort().GetPortBounds()) - - def do_inContent(self, partcode, window, event): - # - # If we're not frontmost, select ourselves and wait for - # the activate event. - # - if MyFrontWindow() <> window: - window.SelectWindow() - return - # We are. Handle the event. - (what, message, when, where, modifiers) = event - SetPort(window) - local = GlobalToLocal(where) - self.do_contentclick(local, modifiers, event) - - def do_contentclick(self, local, modifiers, event): - if DEBUG: - print 'Click in contents at %s, modifiers %s'%(local, modifiers) - - def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window - SetPort(window) - window.BeginUpdate() - self.do_update(window, event) - window.EndUpdate() - - def do_update(self, window, event): - if DEBUG: - import time - for i in range(8): - time.sleep(0.1) - InvertRgn(window.GetWindowPort().visRgn) - FillRgn(window.GetWindowPort().visRgn, GetQDGlobalsGray()) - else: - EraseRgn(window.GetWindowPort().visRgn) - - def do_activate(self, activate, event): - if DEBUG: print 'Activate %d for %s'%(activate, self.wid) - + """A single window belonging to an application""" + + def __init__(self, parent): + self.wid = None + self.parent = parent + + def open(self, bounds=(40, 40, 400, 400), resid=None): + if resid <> None: + self.wid = GetNewWindow(resid, -1) + else: + self.wid = NewWindow(bounds, self.__class__.__name__, 1, + 8, -1, 1, 0) # changed to proc id 8 to include zoom box. jvr + self.do_postopen() + + def do_postopen(self): + """Tell our parent we exist""" + self.parent.appendwindow(self.wid, self) + + def close(self): + self.do_postclose() + + def do_postclose(self): + self.parent.removewindow(self.wid) + self.parent = None + self.wid = None + + def SetPort(self): + # Convinience method + SetPort(self.wid) + + def GetWindow(self): + return self.wid + + def do_inDrag(self, partcode, window, event): + where = event[3] + window.DragWindow(where, self.draglimit) + + draglimit = screenbounds + + def do_inGoAway(self, partcode, window, event): + where = event[3] + if window.TrackGoAway(where): + self.close() + + def do_inZoom(self, partcode, window, event): + (what, message, when, where, modifiers) = event + if window.TrackBox(where, partcode): + window.ZoomWindow(partcode, 1) + rect = window.GetWindowUserState() # so that zoom really works... jvr + self.do_postresize(rect[2] - rect[0], rect[3] - rect[1], window) # jvr + + def do_inZoomIn(self, partcode, window, event): + SetPort(window) # !!! + self.do_inZoom(partcode, window, event) + + def do_inZoomOut(self, partcode, window, event): + SetPort(window) # !!! + self.do_inZoom(partcode, window, event) + + def do_inGrow(self, partcode, window, event): + (what, message, when, where, modifiers) = event + result = window.GrowWindow(where, self.growlimit) + if result: + height = (result>>16) & 0xffff # Hi word + width = result & 0xffff # Lo word + self.do_resize(width, height, window) + + growlimit = (50, 50, screenbounds[2] - screenbounds[0], screenbounds[3] - screenbounds[1]) # jvr + + def do_resize(self, width, height, window): + l, t, r, b = self.wid.GetWindowPort().GetPortBounds() # jvr, forGrowIcon + self.SetPort() # jvr + self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr + window.SizeWindow(width, height, 1) # changed updateFlag to true jvr + self.do_postresize(width, height, window) + + def do_postresize(self, width, height, window): + SetPort(window) + self.wid.InvalWindowRect(window.GetWindowPort().GetPortBounds()) + + def do_inContent(self, partcode, window, event): + # + # If we're not frontmost, select ourselves and wait for + # the activate event. + # + if MyFrontWindow() <> window: + window.SelectWindow() + return + # We are. Handle the event. + (what, message, when, where, modifiers) = event + SetPort(window) + local = GlobalToLocal(where) + self.do_contentclick(local, modifiers, event) + + def do_contentclick(self, local, modifiers, event): + if DEBUG: + print 'Click in contents at %s, modifiers %s'%(local, modifiers) + + def do_rawupdate(self, window, event): + if DEBUG: print "raw update for", window + SetPort(window) + window.BeginUpdate() + self.do_update(window, event) + window.EndUpdate() + + def do_update(self, window, event): + if DEBUG: + import time + for i in range(8): + time.sleep(0.1) + InvertRgn(window.GetWindowPort().visRgn) + FillRgn(window.GetWindowPort().visRgn, GetQDGlobalsGray()) + else: + EraseRgn(window.GetWindowPort().visRgn) + + def do_activate(self, activate, event): + if DEBUG: print 'Activate %d for %s'%(activate, self.wid) + class ControlsWindow(Window): - def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window - SetPort(window) - window.BeginUpdate() - self.do_update(window, event) - #DrawControls(window) # jvr - UpdateControls(window, window.GetWindowPort().visRgn) # jvr - window.DrawGrowIcon() - window.EndUpdate() - - def do_controlhit(self, window, control, pcode, event): - if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode - - def do_inContent(self, partcode, window, event): - if MyFrontWindow() <> window: - window.SelectWindow() - return - (what, message, when, where, modifiers) = event - SetPort(window) # XXXX Needed? - local = GlobalToLocal(where) - pcode, control = FindControl(local, window) - if pcode and control: - self.do_rawcontrolhit(window, control, pcode, local, event) - else: - if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ - (local, window, pcode, control) - self.do_contentclick(local, modifiers, event) - - def do_rawcontrolhit(self, window, control, pcode, local, event): - pcode = control.TrackControl(local) - if pcode: - self.do_controlhit(window, control, pcode, event) - + def do_rawupdate(self, window, event): + if DEBUG: print "raw update for", window + SetPort(window) + window.BeginUpdate() + self.do_update(window, event) + #DrawControls(window) # jvr + UpdateControls(window, window.GetWindowPort().visRgn) # jvr + window.DrawGrowIcon() + window.EndUpdate() + + def do_controlhit(self, window, control, pcode, event): + if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode + + def do_inContent(self, partcode, window, event): + if MyFrontWindow() <> window: + window.SelectWindow() + return + (what, message, when, where, modifiers) = event + SetPort(window) # XXXX Needed? + local = GlobalToLocal(where) + pcode, control = FindControl(local, window) + if pcode and control: + self.do_rawcontrolhit(window, control, pcode, local, event) + else: + if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ + (local, window, pcode, control) + self.do_contentclick(local, modifiers, event) + + def do_rawcontrolhit(self, window, control, pcode, local, event): + pcode = control.TrackControl(local) + if pcode: + self.do_controlhit(window, control, pcode, event) + class ScrolledWindow(ControlsWindow): - def __init__(self, parent): - self.barx = self.bary = None - self.barx_enabled = self.bary_enabled = 1 - self.activated = 1 - ControlsWindow.__init__(self, parent) - - def scrollbars(self, wantx=1, wanty=1): - SetPort(self.wid) - self.barx = self.bary = None - self.barx_enabled = self.bary_enabled = 1 - x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds() - vx, vy = self.getscrollbarvalues() - if vx == None: self.barx_enabled, vx = 0, 0 - if vy == None: self.bary_enabled, vy = 0, 0 - if wantx: - rect = x0-1, y1-(SCROLLBARWIDTH-1), x1-(SCROLLBARWIDTH-2), y1+1 - self.barx = NewControl(self.wid, rect, "", 1, vx, 0, 32767, 16, 0) - if not self.barx_enabled: self.barx.HiliteControl(255) -## self.wid.InvalWindowRect(rect) - if wanty: - rect = x1-(SCROLLBARWIDTH-1), y0-1, x1+1, y1-(SCROLLBARWIDTH-2) - self.bary = NewControl(self.wid, rect, "", 1, vy, 0, 32767, 16, 0) - if not self.bary_enabled: self.bary.HiliteControl(255) -## self.wid.InvalWindowRect(rect) - - def do_postclose(self): - self.barx = self.bary = None - ControlsWindow.do_postclose(self) - - def do_activate(self, onoff, event): - self.activated = onoff - if onoff: - if self.barx and self.barx_enabled: - self.barx.ShowControl() # jvr - if self.bary and self.bary_enabled: - self.bary.ShowControl() # jvr - else: - if self.barx: - self.barx.HideControl() # jvr; An inactive window should have *hidden* - # scrollbars, not just dimmed (no matter what - # BBEdit does... look at the Finder) - if self.bary: - self.bary.HideControl() # jvr - self.wid.DrawGrowIcon() # jvr - - def do_postresize(self, width, height, window): - l, t, r, b = self.wid.GetWindowPort().GetPortBounds() - self.SetPort() - if self.barx: - self.barx.HideControl() # jvr - self.barx.MoveControl(l-1, b-(SCROLLBARWIDTH-1)) - self.barx.SizeControl((r-l)-(SCROLLBARWIDTH-3), SCROLLBARWIDTH) # jvr - if self.bary: - self.bary.HideControl() # jvr - self.bary.MoveControl(r-(SCROLLBARWIDTH-1), t-1) - self.bary.SizeControl(SCROLLBARWIDTH, (b-t)-(SCROLLBARWIDTH-3)) # jvr - if self.barx: - self.barx.ShowControl() # jvr - self.wid.ValidWindowRect((l, b - SCROLLBARWIDTH + 1, r - SCROLLBARWIDTH + 2, b)) # jvr - if self.bary: - self.bary.ShowControl() # jvr - self.wid.ValidWindowRect((r - SCROLLBARWIDTH + 1, t, r, b - SCROLLBARWIDTH + 2)) # jvr - self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr, growicon - - - def do_rawcontrolhit(self, window, control, pcode, local, event): - if control == self.barx: - which = 'x' - elif control == self.bary: - which = 'y' - else: - return 0 - if pcode in (inUpButton, inDownButton, inPageUp, inPageDown): - # We do the work for the buttons and grey area in the tracker - dummy = control.TrackControl(local, self.do_controltrack) - else: - # but the thumb is handled here - pcode = control.TrackControl(local) - if pcode == inThumb: - value = control.GetControlValue() - print 'setbars', which, value #DBG - self.scrollbar_callback(which, 'set', value) - self.updatescrollbars() - else: - print 'funny part', pcode #DBG - return 1 - - def do_controltrack(self, control, pcode): - if control == self.barx: - which = 'x' - elif control == self.bary: - which = 'y' - else: - return - - if pcode == inUpButton: - what = '-' - elif pcode == inDownButton: - what = '+' - elif pcode == inPageUp: - what = '--' - elif pcode == inPageDown: - what = '++' - else: - return - self.scrollbar_callback(which, what, None) - self.updatescrollbars() - - def updatescrollbars(self): - SetPort(self.wid) - vx, vy = self.getscrollbarvalues() - if self.barx: - if vx == None: - self.barx.HiliteControl(255) - self.barx_enabled = 0 - else: - if not self.barx_enabled: - self.barx_enabled = 1 - if self.activated: - self.barx.HiliteControl(0) - self.barx.SetControlValue(vx) - if self.bary: - if vy == None: - self.bary.HiliteControl(255) - self.bary_enabled = 0 - else: - if not self.bary_enabled: - self.bary_enabled = 1 - if self.activated: - self.bary.HiliteControl(0) - self.bary.SetControlValue(vy) - - # Auxiliary function: convert standard text/image/etc coordinate - # to something palatable as getscrollbarvalues() return - def scalebarvalue(self, absmin, absmax, curmin, curmax): - if curmin <= absmin and curmax >= absmax: - return None - if curmin <= absmin: - return 0 - if curmax >= absmax: - return 32767 - perc = float(curmin-absmin)/float(absmax-absmin) - return int(perc*32767) - - # To be overridden: - - def getscrollbarvalues(self): - return 0, 0 - - def scrollbar_callback(self, which, what, value): - print 'scroll', which, what, value - + def __init__(self, parent): + self.barx = self.bary = None + self.barx_enabled = self.bary_enabled = 1 + self.activated = 1 + ControlsWindow.__init__(self, parent) + + def scrollbars(self, wantx=1, wanty=1): + SetPort(self.wid) + self.barx = self.bary = None + self.barx_enabled = self.bary_enabled = 1 + x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds() + vx, vy = self.getscrollbarvalues() + if vx == None: self.barx_enabled, vx = 0, 0 + if vy == None: self.bary_enabled, vy = 0, 0 + if wantx: + rect = x0-1, y1-(SCROLLBARWIDTH-1), x1-(SCROLLBARWIDTH-2), y1+1 + self.barx = NewControl(self.wid, rect, "", 1, vx, 0, 32767, 16, 0) + if not self.barx_enabled: self.barx.HiliteControl(255) +## self.wid.InvalWindowRect(rect) + if wanty: + rect = x1-(SCROLLBARWIDTH-1), y0-1, x1+1, y1-(SCROLLBARWIDTH-2) + self.bary = NewControl(self.wid, rect, "", 1, vy, 0, 32767, 16, 0) + if not self.bary_enabled: self.bary.HiliteControl(255) +## self.wid.InvalWindowRect(rect) + + def do_postclose(self): + self.barx = self.bary = None + ControlsWindow.do_postclose(self) + + def do_activate(self, onoff, event): + self.activated = onoff + if onoff: + if self.barx and self.barx_enabled: + self.barx.ShowControl() # jvr + if self.bary and self.bary_enabled: + self.bary.ShowControl() # jvr + else: + if self.barx: + self.barx.HideControl() # jvr; An inactive window should have *hidden* + # scrollbars, not just dimmed (no matter what + # BBEdit does... look at the Finder) + if self.bary: + self.bary.HideControl() # jvr + self.wid.DrawGrowIcon() # jvr + + def do_postresize(self, width, height, window): + l, t, r, b = self.wid.GetWindowPort().GetPortBounds() + self.SetPort() + if self.barx: + self.barx.HideControl() # jvr + self.barx.MoveControl(l-1, b-(SCROLLBARWIDTH-1)) + self.barx.SizeControl((r-l)-(SCROLLBARWIDTH-3), SCROLLBARWIDTH) # jvr + if self.bary: + self.bary.HideControl() # jvr + self.bary.MoveControl(r-(SCROLLBARWIDTH-1), t-1) + self.bary.SizeControl(SCROLLBARWIDTH, (b-t)-(SCROLLBARWIDTH-3)) # jvr + if self.barx: + self.barx.ShowControl() # jvr + self.wid.ValidWindowRect((l, b - SCROLLBARWIDTH + 1, r - SCROLLBARWIDTH + 2, b)) # jvr + if self.bary: + self.bary.ShowControl() # jvr + self.wid.ValidWindowRect((r - SCROLLBARWIDTH + 1, t, r, b - SCROLLBARWIDTH + 2)) # jvr + self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr, growicon + + + def do_rawcontrolhit(self, window, control, pcode, local, event): + if control == self.barx: + which = 'x' + elif control == self.bary: + which = 'y' + else: + return 0 + if pcode in (inUpButton, inDownButton, inPageUp, inPageDown): + # We do the work for the buttons and grey area in the tracker + dummy = control.TrackControl(local, self.do_controltrack) + else: + # but the thumb is handled here + pcode = control.TrackControl(local) + if pcode == inThumb: + value = control.GetControlValue() + print 'setbars', which, value #DBG + self.scrollbar_callback(which, 'set', value) + self.updatescrollbars() + else: + print 'funny part', pcode #DBG + return 1 + + def do_controltrack(self, control, pcode): + if control == self.barx: + which = 'x' + elif control == self.bary: + which = 'y' + else: + return + + if pcode == inUpButton: + what = '-' + elif pcode == inDownButton: + what = '+' + elif pcode == inPageUp: + what = '--' + elif pcode == inPageDown: + what = '++' + else: + return + self.scrollbar_callback(which, what, None) + self.updatescrollbars() + + def updatescrollbars(self): + SetPort(self.wid) + vx, vy = self.getscrollbarvalues() + if self.barx: + if vx == None: + self.barx.HiliteControl(255) + self.barx_enabled = 0 + else: + if not self.barx_enabled: + self.barx_enabled = 1 + if self.activated: + self.barx.HiliteControl(0) + self.barx.SetControlValue(vx) + if self.bary: + if vy == None: + self.bary.HiliteControl(255) + self.bary_enabled = 0 + else: + if not self.bary_enabled: + self.bary_enabled = 1 + if self.activated: + self.bary.HiliteControl(0) + self.bary.SetControlValue(vy) + + # Auxiliary function: convert standard text/image/etc coordinate + # to something palatable as getscrollbarvalues() return + def scalebarvalue(self, absmin, absmax, curmin, curmax): + if curmin <= absmin and curmax >= absmax: + return None + if curmin <= absmin: + return 0 + if curmax >= absmax: + return 32767 + perc = float(curmin-absmin)/float(absmax-absmin) + return int(perc*32767) + + # To be overridden: + + def getscrollbarvalues(self): + return 0, 0 + + def scrollbar_callback(self, which, what, value): + print 'scroll', which, what, value + class DialogWindow(Window): - """A modeless dialog window""" - - def open(self, resid): - self.dlg = GetNewDialog(resid, -1) - self.wid = self.dlg.GetDialogWindow() - self.do_postopen() - - def close(self): - self.do_postclose() - - def do_postclose(self): - self.dlg = None - Window.do_postclose(self) - - def do_itemhit(self, item, event): - print 'Dialog %s, item %d hit'%(self.dlg, item) - - def do_rawupdate(self, window, event): - pass + """A modeless dialog window""" + + def open(self, resid): + self.dlg = GetNewDialog(resid, -1) + self.wid = self.dlg.GetDialogWindow() + self.do_postopen() + + def close(self): + self.do_postclose() + + def do_postclose(self): + self.dlg = None + Window.do_postclose(self) + + def do_itemhit(self, item, event): + print 'Dialog %s, item %d hit'%(self.dlg, item) + + def do_rawupdate(self, window, event): + pass def ostypecode(x): - "Convert a long int to the 4-character code it really is" - s = '' - for i in range(4): - x, c = divmod(x, 256) - s = chr(c) + s - return s + "Convert a long int to the 4-character code it really is" + s = '' + for i in range(4): + x, c = divmod(x, 256) + s = chr(c) + s + return s class TestApp(Application): - - "This class is used by the test() function" - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.saveitem = MenuItem(m, "Save", "S", self.save) - Separator(m) - self.optionsmenu = mm = SubMenu(m, "Options") - self.opt1 = CheckItem(mm, "Arguments", "A") - self.opt2 = CheckItem(mm, "Being hit on the head lessons", (kMenuOptionModifier, "A")) - self.opt3 = CheckItem(mm, "Complaints", (kMenuOptionModifier|kMenuNoCommandModifier, "A")) - Separator(m) - self.itemeh = MenuItem(m, "Enable Help", None, self.enablehelp) - self.itemdbg = MenuItem(m, "Debug", None, self.debug) - Separator(m) - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - def save(self, *args): - print "Save" - - def quit(self, *args): - raise self - - def enablehelp(self, *args): - hm = self.gethelpmenu() - self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp) - - def nohelp(self, *args): - print "I told you there isn't any!" - - def debug(self, *args): - import pdb - pdb.set_trace() + + "This class is used by the test() function" + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.saveitem = MenuItem(m, "Save", "S", self.save) + Separator(m) + self.optionsmenu = mm = SubMenu(m, "Options") + self.opt1 = CheckItem(mm, "Arguments", "A") + self.opt2 = CheckItem(mm, "Being hit on the head lessons", (kMenuOptionModifier, "A")) + self.opt3 = CheckItem(mm, "Complaints", (kMenuOptionModifier|kMenuNoCommandModifier, "A")) + Separator(m) + self.itemeh = MenuItem(m, "Enable Help", None, self.enablehelp) + self.itemdbg = MenuItem(m, "Debug", None, self.debug) + Separator(m) + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + def save(self, *args): + print "Save" + + def quit(self, *args): + raise self + + def enablehelp(self, *args): + hm = self.gethelpmenu() + self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp) + + def nohelp(self, *args): + print "I told you there isn't any!" + + def debug(self, *args): + import pdb + pdb.set_trace() def test(): - "Test program" - app = TestApp() - app.mainloop() + "Test program" + app = TestApp() + app.mainloop() if __name__ == '__main__': - test() + test() diff --git a/Lib/plat-mac/MiniAEFrame.py b/Lib/plat-mac/MiniAEFrame.py index ab54039..a44e6ae 100644 --- a/Lib/plat-mac/MiniAEFrame.py +++ b/Lib/plat-mac/MiniAEFrame.py @@ -1,9 +1,9 @@ """MiniAEFrame - A minimal AppleEvent Application framework. There are two classes: - AEServer -- a mixin class offering nice AE handling. - MiniApplication -- a very minimal alternative to FrameWork.py, - only suitable for the simplest of AppleEvent servers. + AEServer -- a mixin class offering nice AE handling. + MiniApplication -- a very minimal alternative to FrameWork.py, + only suitable for the simplest of AppleEvent servers. """ import sys @@ -21,179 +21,179 @@ from Carbon import Qd import aetools import EasyDialogs -kHighLevelEvent = 23 # Not defined anywhere for Python yet? +kHighLevelEvent = 23 # Not defined anywhere for Python yet? class MiniApplication: - - """A minimal FrameWork.Application-like class""" - - def __init__(self): - self.quitting = 0 - # Initialize menu - self.appleid = 1 - self.quitid = 2 - Menu.ClearMenuBar() - self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") - applemenu.AppendMenu("%s;(-" % self.getaboutmenutext()) - if MacOS.runtimemodel == 'ppc': - applemenu.AppendResMenu('DRVR') - applemenu.InsertMenu(0) - self.quitmenu = Menu.NewMenu(self.quitid, "File") - self.quitmenu.AppendMenu("Quit") - self.quitmenu.SetItemCmd(1, ord("Q")) - self.quitmenu.InsertMenu(0) - Menu.DrawMenuBar() - - def __del__(self): - self.close() - - def close(self): - pass - - def mainloop(self, mask = everyEvent, timeout = 60*60): - while not self.quitting: - self.dooneevent(mask, timeout) - - def _quit(self): - self.quitting = 1 - - def dooneevent(self, mask = everyEvent, timeout = 60*60): - got, event = Evt.WaitNextEvent(mask, timeout) - if got: - self.lowlevelhandler(event) - - def lowlevelhandler(self, event): - what, message, when, where, modifiers = event - h, v = where - if what == kHighLevelEvent: - msg = "High Level Event: %s %s" % \ - (`code(message)`, `code(h | (v<<16))`) - try: - AE.AEProcessAppleEvent(event) - except AE.Error, err: - print 'AE error: ', err - print 'in', msg - traceback.print_exc() - return - elif what == keyDown: - c = chr(message & charCodeMask) - if modifiers & cmdKey: - if c == '.': - raise KeyboardInterrupt, "Command-period" - if c == 'q': - if hasattr(MacOS, 'OutputSeen'): - MacOS.OutputSeen() - self.quitting = 1 - return - elif what == mouseDown: - partcode, window = Win.FindWindow(where) - if partcode == inMenuBar: - result = Menu.MenuSelect(where) - id = (result>>16) & 0xffff # Hi word - item = result & 0xffff # Lo word - if id == self.appleid: - if item == 1: - EasyDialogs.Message(self.getabouttext()) - elif item > 1 and hasattr(Menu, 'OpenDeskAcc'): - name = self.applemenu.GetMenuItemText(item) - Menu.OpenDeskAcc(name) - elif id == self.quitid and item == 1: - if hasattr(MacOS, 'OutputSeen'): - MacOS.OutputSeen() - self.quitting = 1 - Menu.HiliteMenu(0) - return - # Anything not handled is passed to Python/SIOUX - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - else: - print "Unhandled event:", event - - def getabouttext(self): - return self.__class__.__name__ - - def getaboutmenutext(self): - return "About %s\311" % self.__class__.__name__ + + """A minimal FrameWork.Application-like class""" + + def __init__(self): + self.quitting = 0 + # Initialize menu + self.appleid = 1 + self.quitid = 2 + Menu.ClearMenuBar() + self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") + applemenu.AppendMenu("%s;(-" % self.getaboutmenutext()) + if MacOS.runtimemodel == 'ppc': + applemenu.AppendResMenu('DRVR') + applemenu.InsertMenu(0) + self.quitmenu = Menu.NewMenu(self.quitid, "File") + self.quitmenu.AppendMenu("Quit") + self.quitmenu.SetItemCmd(1, ord("Q")) + self.quitmenu.InsertMenu(0) + Menu.DrawMenuBar() + + def __del__(self): + self.close() + + def close(self): + pass + + def mainloop(self, mask = everyEvent, timeout = 60*60): + while not self.quitting: + self.dooneevent(mask, timeout) + + def _quit(self): + self.quitting = 1 + + def dooneevent(self, mask = everyEvent, timeout = 60*60): + got, event = Evt.WaitNextEvent(mask, timeout) + if got: + self.lowlevelhandler(event) + + def lowlevelhandler(self, event): + what, message, when, where, modifiers = event + h, v = where + if what == kHighLevelEvent: + msg = "High Level Event: %s %s" % \ + (`code(message)`, `code(h | (v<<16))`) + try: + AE.AEProcessAppleEvent(event) + except AE.Error, err: + print 'AE error: ', err + print 'in', msg + traceback.print_exc() + return + elif what == keyDown: + c = chr(message & charCodeMask) + if modifiers & cmdKey: + if c == '.': + raise KeyboardInterrupt, "Command-period" + if c == 'q': + if hasattr(MacOS, 'OutputSeen'): + MacOS.OutputSeen() + self.quitting = 1 + return + elif what == mouseDown: + partcode, window = Win.FindWindow(where) + if partcode == inMenuBar: + result = Menu.MenuSelect(where) + id = (result>>16) & 0xffff # Hi word + item = result & 0xffff # Lo word + if id == self.appleid: + if item == 1: + EasyDialogs.Message(self.getabouttext()) + elif item > 1 and hasattr(Menu, 'OpenDeskAcc'): + name = self.applemenu.GetMenuItemText(item) + Menu.OpenDeskAcc(name) + elif id == self.quitid and item == 1: + if hasattr(MacOS, 'OutputSeen'): + MacOS.OutputSeen() + self.quitting = 1 + Menu.HiliteMenu(0) + return + # Anything not handled is passed to Python/SIOUX + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + else: + print "Unhandled event:", event + + def getabouttext(self): + return self.__class__.__name__ + + def getaboutmenutext(self): + return "About %s\311" % self.__class__.__name__ class AEServer: - - def __init__(self): - self.ae_handlers = {} - - def installaehandler(self, classe, type, callback): - AE.AEInstallEventHandler(classe, type, self.callback_wrapper) - self.ae_handlers[(classe, type)] = callback - - def close(self): - for classe, type in self.ae_handlers.keys(): - AE.AERemoveEventHandler(classe, type) - - def callback_wrapper(self, _request, _reply): - _parameters, _attributes = aetools.unpackevent(_request) - _class = _attributes['evcl'].type - _type = _attributes['evid'].type - - if self.ae_handlers.has_key((_class, _type)): - _function = self.ae_handlers[(_class, _type)] - elif self.ae_handlers.has_key((_class, '****')): - _function = self.ae_handlers[(_class, '****')] - elif self.ae_handlers.has_key(('****', '****')): - _function = self.ae_handlers[('****', '****')] - else: - raise 'Cannot happen: AE callback without handler', (_class, _type) - - # XXXX Do key-to-name mapping here - - _parameters['_attributes'] = _attributes - _parameters['_class'] = _class - _parameters['_type'] = _type - if _parameters.has_key('----'): - _object = _parameters['----'] - del _parameters['----'] - # The try/except that used to be here can mask programmer errors. - # Let the program crash, the programmer can always add a **args - # to the formal parameter list. - rv = apply(_function, (_object,), _parameters) - else: - #Same try/except comment as above - rv = apply(_function, (), _parameters) - - if rv == None: - aetools.packevent(_reply, {}) - else: - aetools.packevent(_reply, {'----':rv}) + + def __init__(self): + self.ae_handlers = {} + + def installaehandler(self, classe, type, callback): + AE.AEInstallEventHandler(classe, type, self.callback_wrapper) + self.ae_handlers[(classe, type)] = callback + + def close(self): + for classe, type in self.ae_handlers.keys(): + AE.AERemoveEventHandler(classe, type) + + def callback_wrapper(self, _request, _reply): + _parameters, _attributes = aetools.unpackevent(_request) + _class = _attributes['evcl'].type + _type = _attributes['evid'].type + + if self.ae_handlers.has_key((_class, _type)): + _function = self.ae_handlers[(_class, _type)] + elif self.ae_handlers.has_key((_class, '****')): + _function = self.ae_handlers[(_class, '****')] + elif self.ae_handlers.has_key(('****', '****')): + _function = self.ae_handlers[('****', '****')] + else: + raise 'Cannot happen: AE callback without handler', (_class, _type) + + # XXXX Do key-to-name mapping here + + _parameters['_attributes'] = _attributes + _parameters['_class'] = _class + _parameters['_type'] = _type + if _parameters.has_key('----'): + _object = _parameters['----'] + del _parameters['----'] + # The try/except that used to be here can mask programmer errors. + # Let the program crash, the programmer can always add a **args + # to the formal parameter list. + rv = _function(_object, **_parameters) + else: + #Same try/except comment as above + rv = _function(**_parameters) + + if rv == None: + aetools.packevent(_reply, {}) + else: + aetools.packevent(_reply, {'----':rv}) def code(x): - "Convert a long int to the 4-character code it really is" - s = '' - for i in range(4): - x, c = divmod(x, 256) - s = chr(c) + s - return s + "Convert a long int to the 4-character code it really is" + s = '' + for i in range(4): + x, c = divmod(x, 256) + s = chr(c) + s + return s class _Test(AEServer, MiniApplication): - """Mini test application, handles required events""" - - def __init__(self): - MiniApplication.__init__(self) - AEServer.__init__(self) - self.installaehandler('aevt', 'oapp', self.open_app) - self.installaehandler('aevt', 'quit', self.quit) - self.installaehandler('****', '****', self.other) - self.mainloop() - - def quit(self, **args): - self._quit() - - def open_app(self, **args): - pass - - def other(self, _object=None, _class=None, _type=None, **args): - print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args - + """Mini test application, handles required events""" + + def __init__(self): + MiniApplication.__init__(self) + AEServer.__init__(self) + self.installaehandler('aevt', 'oapp', self.open_app) + self.installaehandler('aevt', 'quit', self.quit) + self.installaehandler('****', '****', self.other) + self.mainloop() + + def quit(self, **args): + self._quit() + + def open_app(self, **args): + pass + + def other(self, _object=None, _class=None, _type=None, **args): + print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args + if __name__ == '__main__': - _Test() + _Test() diff --git a/Lib/plat-mac/argvemulator.py b/Lib/plat-mac/argvemulator.py index 5fad8d4..0516695 100644 --- a/Lib/plat-mac/argvemulator.py +++ b/Lib/plat-mac/argvemulator.py @@ -11,104 +11,104 @@ from Carbon.Events import * import aetools class ArgvCollector: - - """A minimal FrameWork.Application-like class""" - - def __init__(self): - self.quitting = 0 - self.ae_handlers = {} - # Remove the funny -psn_xxx_xxx argument - if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn': - del sys.argv[1] - self.installaehandler('aevt', 'oapp', self.open_app) - self.installaehandler('aevt', 'odoc', self.open_file) - - def installaehandler(self, classe, type, callback): - AE.AEInstallEventHandler(classe, type, self.callback_wrapper) - self.ae_handlers[(classe, type)] = callback - - def close(self): - for classe, type in self.ae_handlers.keys(): - AE.AERemoveEventHandler(classe, type) - - def mainloop(self, mask = highLevelEventMask, timeout = 1*60): - stoptime = Evt.TickCount() + timeout - while not self.quitting and Evt.TickCount() < stoptime: - self.dooneevent(mask, timeout) - self.close() - - def _quit(self): - self.quitting = 1 - - def dooneevent(self, mask = highLevelEventMask, timeout = 1*60): - got, event = Evt.WaitNextEvent(mask, timeout) - if got: - self.lowlevelhandler(event) - - def lowlevelhandler(self, event): - what, message, when, where, modifiers = event - h, v = where - if what == kHighLevelEvent: - try: - AE.AEProcessAppleEvent(event) - except AE.Error, err: - msg = "High Level Event: %s %s" % \ - (`hex(message)`, `hex(h | (v<<16))`) - print 'AE error: ', err - print 'in', msg - traceback.print_exc() - return - else: - print "Unhandled event:", event - - def callback_wrapper(self, _request, _reply): - _parameters, _attributes = aetools.unpackevent(_request) - _class = _attributes['evcl'].type - _type = _attributes['evid'].type - - if self.ae_handlers.has_key((_class, _type)): - _function = self.ae_handlers[(_class, _type)] - elif self.ae_handlers.has_key((_class, '****')): - _function = self.ae_handlers[(_class, '****')] - elif self.ae_handlers.has_key(('****', '****')): - _function = self.ae_handlers[('****', '****')] - else: - raise 'Cannot happen: AE callback without handler', (_class, _type) - - # XXXX Do key-to-name mapping here - - _parameters['_attributes'] = _attributes - _parameters['_class'] = _class - _parameters['_type'] = _type - if _parameters.has_key('----'): - _object = _parameters['----'] - del _parameters['----'] - # The try/except that used to be here can mask programmer errors. - # Let the program crash, the programmer can always add a **args - # to the formal parameter list. - rv = apply(_function, (_object,), _parameters) - else: - #Same try/except comment as above - rv = apply(_function, (), _parameters) - - if rv == None: - aetools.packevent(_reply, {}) - else: - aetools.packevent(_reply, {'----':rv}) - - def open_app(self, **args): - self._quit() - - def open_file(self, _object=None, **args): - for alias in _object: - fsr = alias.FSResolveAlias(None)[0] - pathname = fsr.as_pathname() - sys.argv.append(pathname) - self._quit() - - def other(self, _object=None, _class=None, _type=None, **args): - print 'Ignore AppleEvent', (_class, _type), 'for', _object, 'Other args:', args + + """A minimal FrameWork.Application-like class""" + + def __init__(self): + self.quitting = 0 + self.ae_handlers = {} + # Remove the funny -psn_xxx_xxx argument + if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn': + del sys.argv[1] + self.installaehandler('aevt', 'oapp', self.open_app) + self.installaehandler('aevt', 'odoc', self.open_file) + + def installaehandler(self, classe, type, callback): + AE.AEInstallEventHandler(classe, type, self.callback_wrapper) + self.ae_handlers[(classe, type)] = callback + + def close(self): + for classe, type in self.ae_handlers.keys(): + AE.AERemoveEventHandler(classe, type) + + def mainloop(self, mask = highLevelEventMask, timeout = 1*60): + stoptime = Evt.TickCount() + timeout + while not self.quitting and Evt.TickCount() < stoptime: + self.dooneevent(mask, timeout) + self.close() + + def _quit(self): + self.quitting = 1 + + def dooneevent(self, mask = highLevelEventMask, timeout = 1*60): + got, event = Evt.WaitNextEvent(mask, timeout) + if got: + self.lowlevelhandler(event) + + def lowlevelhandler(self, event): + what, message, when, where, modifiers = event + h, v = where + if what == kHighLevelEvent: + try: + AE.AEProcessAppleEvent(event) + except AE.Error, err: + msg = "High Level Event: %s %s" % \ + (`hex(message)`, `hex(h | (v<<16))`) + print 'AE error: ', err + print 'in', msg + traceback.print_exc() + return + else: + print "Unhandled event:", event + + def callback_wrapper(self, _request, _reply): + _parameters, _attributes = aetools.unpackevent(_request) + _class = _attributes['evcl'].type + _type = _attributes['evid'].type + + if self.ae_handlers.has_key((_class, _type)): + _function = self.ae_handlers[(_class, _type)] + elif self.ae_handlers.has_key((_class, '****')): + _function = self.ae_handlers[(_class, '****')] + elif self.ae_handlers.has_key(('****', '****')): + _function = self.ae_handlers[('****', '****')] + else: + raise 'Cannot happen: AE callback without handler', (_class, _type) + + # XXXX Do key-to-name mapping here + + _parameters['_attributes'] = _attributes + _parameters['_class'] = _class + _parameters['_type'] = _type + if _parameters.has_key('----'): + _object = _parameters['----'] + del _parameters['----'] + # The try/except that used to be here can mask programmer errors. + # Let the program crash, the programmer can always add a **args + # to the formal parameter list. + rv = _function(_object, **_parameters) + else: + #Same try/except comment as above + rv = _function(**_parameters) + + if rv == None: + aetools.packevent(_reply, {}) + else: + aetools.packevent(_reply, {'----':rv}) + + def open_app(self, **args): + self._quit() + + def open_file(self, _object=None, **args): + for alias in _object: + fsr = alias.FSResolveAlias(None)[0] + pathname = fsr.as_pathname() + sys.argv.append(pathname) + self._quit() + + def other(self, _object=None, _class=None, _type=None, **args): + print 'Ignore AppleEvent', (_class, _type), 'for', _object, 'Other args:', args if __name__ == '__main__': - ArgvCollector().mainloop() - print "sys.argv=", sys.argv + ArgvCollector().mainloop() + print "sys.argv=", sys.argv diff --git a/Lib/plat-mac/icopen.py b/Lib/plat-mac/icopen.py index d819159..99e866e 100644 --- a/Lib/plat-mac/icopen.py +++ b/Lib/plat-mac/icopen.py @@ -29,7 +29,7 @@ INSTALLATION Put this file in your Python path, and create a file named {Python}:sitecustomize.py that contains: - import icopen + import icopen (If {Python}:sitecustomizer.py already exists, just add the 'import' line to it.) @@ -42,18 +42,18 @@ import __builtin__ _builtin_open = globals().get('_builtin_open', __builtin__.open) def _open_with_typer(*args): - file = apply(_builtin_open, args) - filename = args[0] - mode = 'r' - if args[1:]: - mode = args[1] - if mode[0] == 'w': - from ic import error, settypecreator - try: - settypecreator(filename) - except error: - pass - return file + file = _builtin_open(*args) + filename = args[0] + mode = 'r' + if args[1:]: + mode = args[1] + if mode[0] == 'w': + from ic import error, settypecreator + try: + settypecreator(filename) + except error: + pass + return file __builtin__.open = _open_with_typer @@ -63,4 +63,4 @@ _open_with_typer('test.py', 'w') _open_with_typer('test.txt', 'w') _open_with_typer('test.html', 'w') _open_with_typer('test.foo', 'w') -"""
\ No newline at end of file +""" |