changed 8-space indentation to 4

This commit is contained in:
Just van Rossum 2003-06-21 14:41:32 +00:00
parent 9e9a7c3dd7
commit 35b50e2683
4 changed files with 1790 additions and 1790 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
"""MiniAEFrame - A minimal AppleEvent Application framework. """MiniAEFrame - A minimal AppleEvent Application framework.
There are two classes: There are two classes:
AEServer -- a mixin class offering nice AE handling. AEServer -- a mixin class offering nice AE handling.
MiniApplication -- a very minimal alternative to FrameWork.py, MiniApplication -- a very minimal alternative to FrameWork.py,
only suitable for the simplest of AppleEvent servers. only suitable for the simplest of AppleEvent servers.
""" """
import sys import sys
@ -21,179 +21,179 @@ from Carbon import Qd
import aetools import aetools
import EasyDialogs import EasyDialogs
kHighLevelEvent = 23 # Not defined anywhere for Python yet? kHighLevelEvent = 23 # Not defined anywhere for Python yet?
class MiniApplication: class MiniApplication:
"""A minimal FrameWork.Application-like class""" """A minimal FrameWork.Application-like class"""
def __init__(self): def __init__(self):
self.quitting = 0 self.quitting = 0
# Initialize menu # Initialize menu
self.appleid = 1 self.appleid = 1
self.quitid = 2 self.quitid = 2
Menu.ClearMenuBar() Menu.ClearMenuBar()
self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024")
applemenu.AppendMenu("%s;(-" % self.getaboutmenutext()) applemenu.AppendMenu("%s;(-" % self.getaboutmenutext())
if MacOS.runtimemodel == 'ppc': if MacOS.runtimemodel == 'ppc':
applemenu.AppendResMenu('DRVR') applemenu.AppendResMenu('DRVR')
applemenu.InsertMenu(0) applemenu.InsertMenu(0)
self.quitmenu = Menu.NewMenu(self.quitid, "File") self.quitmenu = Menu.NewMenu(self.quitid, "File")
self.quitmenu.AppendMenu("Quit") self.quitmenu.AppendMenu("Quit")
self.quitmenu.SetItemCmd(1, ord("Q")) self.quitmenu.SetItemCmd(1, ord("Q"))
self.quitmenu.InsertMenu(0) self.quitmenu.InsertMenu(0)
Menu.DrawMenuBar() Menu.DrawMenuBar()
def __del__(self): def __del__(self):
self.close() self.close()
def close(self): def close(self):
pass pass
def mainloop(self, mask = everyEvent, timeout = 60*60): def mainloop(self, mask = everyEvent, timeout = 60*60):
while not self.quitting: while not self.quitting:
self.dooneevent(mask, timeout) self.dooneevent(mask, timeout)
def _quit(self): def _quit(self):
self.quitting = 1 self.quitting = 1
def dooneevent(self, mask = everyEvent, timeout = 60*60): def dooneevent(self, mask = everyEvent, timeout = 60*60):
got, event = Evt.WaitNextEvent(mask, timeout) got, event = Evt.WaitNextEvent(mask, timeout)
if got: if got:
self.lowlevelhandler(event) self.lowlevelhandler(event)
def lowlevelhandler(self, event): def lowlevelhandler(self, event):
what, message, when, where, modifiers = event what, message, when, where, modifiers = event
h, v = where h, v = where
if what == kHighLevelEvent: if what == kHighLevelEvent:
msg = "High Level Event: %s %s" % \ msg = "High Level Event: %s %s" % \
(`code(message)`, `code(h | (v<<16))`) (`code(message)`, `code(h | (v<<16))`)
try: try:
AE.AEProcessAppleEvent(event) AE.AEProcessAppleEvent(event)
except AE.Error, err: except AE.Error, err:
print 'AE error: ', err print 'AE error: ', err
print 'in', msg print 'in', msg
traceback.print_exc() traceback.print_exc()
return return
elif what == keyDown: elif what == keyDown:
c = chr(message & charCodeMask) c = chr(message & charCodeMask)
if modifiers & cmdKey: if modifiers & cmdKey:
if c == '.': if c == '.':
raise KeyboardInterrupt, "Command-period" raise KeyboardInterrupt, "Command-period"
if c == 'q': if c == 'q':
if hasattr(MacOS, 'OutputSeen'): if hasattr(MacOS, 'OutputSeen'):
MacOS.OutputSeen() MacOS.OutputSeen()
self.quitting = 1 self.quitting = 1
return return
elif what == mouseDown: elif what == mouseDown:
partcode, window = Win.FindWindow(where) partcode, window = Win.FindWindow(where)
if partcode == inMenuBar: if partcode == inMenuBar:
result = Menu.MenuSelect(where) result = Menu.MenuSelect(where)
id = (result>>16) & 0xffff # Hi word id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word item = result & 0xffff # Lo word
if id == self.appleid: if id == self.appleid:
if item == 1: if item == 1:
EasyDialogs.Message(self.getabouttext()) EasyDialogs.Message(self.getabouttext())
elif item > 1 and hasattr(Menu, 'OpenDeskAcc'): elif item > 1 and hasattr(Menu, 'OpenDeskAcc'):
name = self.applemenu.GetMenuItemText(item) name = self.applemenu.GetMenuItemText(item)
Menu.OpenDeskAcc(name) Menu.OpenDeskAcc(name)
elif id == self.quitid and item == 1: elif id == self.quitid and item == 1:
if hasattr(MacOS, 'OutputSeen'): if hasattr(MacOS, 'OutputSeen'):
MacOS.OutputSeen() MacOS.OutputSeen()
self.quitting = 1 self.quitting = 1
Menu.HiliteMenu(0) Menu.HiliteMenu(0)
return return
# Anything not handled is passed to Python/SIOUX # Anything not handled is passed to Python/SIOUX
if hasattr(MacOS, 'HandleEvent'): if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event) MacOS.HandleEvent(event)
else: else:
print "Unhandled event:", event print "Unhandled event:", event
def getabouttext(self): def getabouttext(self):
return self.__class__.__name__ return self.__class__.__name__
def getaboutmenutext(self): def getaboutmenutext(self):
return "About %s\311" % self.__class__.__name__ return "About %s\311" % self.__class__.__name__
class AEServer: class AEServer:
def __init__(self): def __init__(self):
self.ae_handlers = {} self.ae_handlers = {}
def installaehandler(self, classe, type, callback): def installaehandler(self, classe, type, callback):
AE.AEInstallEventHandler(classe, type, self.callback_wrapper) AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
self.ae_handlers[(classe, type)] = callback self.ae_handlers[(classe, type)] = callback
def close(self): def close(self):
for classe, type in self.ae_handlers.keys(): for classe, type in self.ae_handlers.keys():
AE.AERemoveEventHandler(classe, type) AE.AERemoveEventHandler(classe, type)
def callback_wrapper(self, _request, _reply): def callback_wrapper(self, _request, _reply):
_parameters, _attributes = aetools.unpackevent(_request) _parameters, _attributes = aetools.unpackevent(_request)
_class = _attributes['evcl'].type _class = _attributes['evcl'].type
_type = _attributes['evid'].type _type = _attributes['evid'].type
if self.ae_handlers.has_key((_class, _type)): if self.ae_handlers.has_key((_class, _type)):
_function = self.ae_handlers[(_class, _type)] _function = self.ae_handlers[(_class, _type)]
elif self.ae_handlers.has_key((_class, '****')): elif self.ae_handlers.has_key((_class, '****')):
_function = self.ae_handlers[(_class, '****')] _function = self.ae_handlers[(_class, '****')]
elif self.ae_handlers.has_key(('****', '****')): elif self.ae_handlers.has_key(('****', '****')):
_function = self.ae_handlers[('****', '****')] _function = self.ae_handlers[('****', '****')]
else: else:
raise 'Cannot happen: AE callback without handler', (_class, _type) raise 'Cannot happen: AE callback without handler', (_class, _type)
# XXXX Do key-to-name mapping here # XXXX Do key-to-name mapping here
_parameters['_attributes'] = _attributes _parameters['_attributes'] = _attributes
_parameters['_class'] = _class _parameters['_class'] = _class
_parameters['_type'] = _type _parameters['_type'] = _type
if _parameters.has_key('----'): if _parameters.has_key('----'):
_object = _parameters['----'] _object = _parameters['----']
del _parameters['----'] del _parameters['----']
# The try/except that used to be here can mask programmer errors. # The try/except that used to be here can mask programmer errors.
# Let the program crash, the programmer can always add a **args # Let the program crash, the programmer can always add a **args
# to the formal parameter list. # to the formal parameter list.
rv = _function(_object, **_parameters) rv = _function(_object, **_parameters)
else: else:
#Same try/except comment as above #Same try/except comment as above
rv = _function(**_parameters) rv = _function(**_parameters)
if rv == None: if rv == None:
aetools.packevent(_reply, {}) aetools.packevent(_reply, {})
else: else:
aetools.packevent(_reply, {'----':rv}) aetools.packevent(_reply, {'----':rv})
def code(x): def code(x):
"Convert a long int to the 4-character code it really is" "Convert a long int to the 4-character code it really is"
s = '' s = ''
for i in range(4): for i in range(4):
x, c = divmod(x, 256) x, c = divmod(x, 256)
s = chr(c) + s s = chr(c) + s
return s return s
class _Test(AEServer, MiniApplication): class _Test(AEServer, MiniApplication):
"""Mini test application, handles required events""" """Mini test application, handles required events"""
def __init__(self): def __init__(self):
MiniApplication.__init__(self) MiniApplication.__init__(self)
AEServer.__init__(self) AEServer.__init__(self)
self.installaehandler('aevt', 'oapp', self.open_app) self.installaehandler('aevt', 'oapp', self.open_app)
self.installaehandler('aevt', 'quit', self.quit) self.installaehandler('aevt', 'quit', self.quit)
self.installaehandler('****', '****', self.other) self.installaehandler('****', '****', self.other)
self.mainloop() self.mainloop()
def quit(self, **args): def quit(self, **args):
self._quit() self._quit()
def open_app(self, **args): def open_app(self, **args):
pass pass
def other(self, _object=None, _class=None, _type=None, **args): def other(self, _object=None, _class=None, _type=None, **args):
print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
if __name__ == '__main__': if __name__ == '__main__':
_Test() _Test()

View file

@ -12,103 +12,103 @@ import aetools
class ArgvCollector: class ArgvCollector:
"""A minimal FrameWork.Application-like class""" """A minimal FrameWork.Application-like class"""
def __init__(self): def __init__(self):
self.quitting = 0 self.quitting = 0
self.ae_handlers = {} self.ae_handlers = {}
# Remove the funny -psn_xxx_xxx argument # Remove the funny -psn_xxx_xxx argument
if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn': if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn':
del sys.argv[1] del sys.argv[1]
self.installaehandler('aevt', 'oapp', self.open_app) self.installaehandler('aevt', 'oapp', self.open_app)
self.installaehandler('aevt', 'odoc', self.open_file) self.installaehandler('aevt', 'odoc', self.open_file)
def installaehandler(self, classe, type, callback): def installaehandler(self, classe, type, callback):
AE.AEInstallEventHandler(classe, type, self.callback_wrapper) AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
self.ae_handlers[(classe, type)] = callback self.ae_handlers[(classe, type)] = callback
def close(self): def close(self):
for classe, type in self.ae_handlers.keys(): for classe, type in self.ae_handlers.keys():
AE.AERemoveEventHandler(classe, type) AE.AERemoveEventHandler(classe, type)
def mainloop(self, mask = highLevelEventMask, timeout = 1*60): def mainloop(self, mask = highLevelEventMask, timeout = 1*60):
stoptime = Evt.TickCount() + timeout stoptime = Evt.TickCount() + timeout
while not self.quitting and Evt.TickCount() < stoptime: while not self.quitting and Evt.TickCount() < stoptime:
self.dooneevent(mask, timeout) self.dooneevent(mask, timeout)
self.close() self.close()
def _quit(self): def _quit(self):
self.quitting = 1 self.quitting = 1
def dooneevent(self, mask = highLevelEventMask, timeout = 1*60): def dooneevent(self, mask = highLevelEventMask, timeout = 1*60):
got, event = Evt.WaitNextEvent(mask, timeout) got, event = Evt.WaitNextEvent(mask, timeout)
if got: if got:
self.lowlevelhandler(event) self.lowlevelhandler(event)
def lowlevelhandler(self, event): def lowlevelhandler(self, event):
what, message, when, where, modifiers = event what, message, when, where, modifiers = event
h, v = where h, v = where
if what == kHighLevelEvent: if what == kHighLevelEvent:
try: try:
AE.AEProcessAppleEvent(event) AE.AEProcessAppleEvent(event)
except AE.Error, err: except AE.Error, err:
msg = "High Level Event: %s %s" % \ msg = "High Level Event: %s %s" % \
(`hex(message)`, `hex(h | (v<<16))`) (`hex(message)`, `hex(h | (v<<16))`)
print 'AE error: ', err print 'AE error: ', err
print 'in', msg print 'in', msg
traceback.print_exc() traceback.print_exc()
return return
else: else:
print "Unhandled event:", event print "Unhandled event:", event
def callback_wrapper(self, _request, _reply): def callback_wrapper(self, _request, _reply):
_parameters, _attributes = aetools.unpackevent(_request) _parameters, _attributes = aetools.unpackevent(_request)
_class = _attributes['evcl'].type _class = _attributes['evcl'].type
_type = _attributes['evid'].type _type = _attributes['evid'].type
if self.ae_handlers.has_key((_class, _type)): if self.ae_handlers.has_key((_class, _type)):
_function = self.ae_handlers[(_class, _type)] _function = self.ae_handlers[(_class, _type)]
elif self.ae_handlers.has_key((_class, '****')): elif self.ae_handlers.has_key((_class, '****')):
_function = self.ae_handlers[(_class, '****')] _function = self.ae_handlers[(_class, '****')]
elif self.ae_handlers.has_key(('****', '****')): elif self.ae_handlers.has_key(('****', '****')):
_function = self.ae_handlers[('****', '****')] _function = self.ae_handlers[('****', '****')]
else: else:
raise 'Cannot happen: AE callback without handler', (_class, _type) raise 'Cannot happen: AE callback without handler', (_class, _type)
# XXXX Do key-to-name mapping here # XXXX Do key-to-name mapping here
_parameters['_attributes'] = _attributes _parameters['_attributes'] = _attributes
_parameters['_class'] = _class _parameters['_class'] = _class
_parameters['_type'] = _type _parameters['_type'] = _type
if _parameters.has_key('----'): if _parameters.has_key('----'):
_object = _parameters['----'] _object = _parameters['----']
del _parameters['----'] del _parameters['----']
# The try/except that used to be here can mask programmer errors. # The try/except that used to be here can mask programmer errors.
# Let the program crash, the programmer can always add a **args # Let the program crash, the programmer can always add a **args
# to the formal parameter list. # to the formal parameter list.
rv = _function(_object, **_parameters) rv = _function(_object, **_parameters)
else: else:
#Same try/except comment as above #Same try/except comment as above
rv = _function(**_parameters) rv = _function(**_parameters)
if rv == None: if rv == None:
aetools.packevent(_reply, {}) aetools.packevent(_reply, {})
else: else:
aetools.packevent(_reply, {'----':rv}) aetools.packevent(_reply, {'----':rv})
def open_app(self, **args): def open_app(self, **args):
self._quit() self._quit()
def open_file(self, _object=None, **args): def open_file(self, _object=None, **args):
for alias in _object: for alias in _object:
fsr = alias.FSResolveAlias(None)[0] fsr = alias.FSResolveAlias(None)[0]
pathname = fsr.as_pathname() pathname = fsr.as_pathname()
sys.argv.append(pathname) sys.argv.append(pathname)
self._quit() self._quit()
def other(self, _object=None, _class=None, _type=None, **args): def other(self, _object=None, _class=None, _type=None, **args):
print 'Ignore AppleEvent', (_class, _type), 'for', _object, 'Other args:', args print 'Ignore AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
if __name__ == '__main__': if __name__ == '__main__':
ArgvCollector().mainloop() ArgvCollector().mainloop()
print "sys.argv=", sys.argv print "sys.argv=", sys.argv