Bump version to 0.9.1.
[python/dscho.git] / Mac / Lib / lib-toolbox / MiniAEFrame.py
blob307715048365eb1a737b9f758735ccbacc71682a
1 """MiniAEFrame - A minimal AppleEvent Application framework.
3 There are two classes:
4 AEServer -- a mixin class offering nice AE handling.
5 MiniApplication -- a very minimal alternative to FrameWork.py,
6 only suitable for the simplest of AppleEvent servers.
7 """
9 import sys
10 import traceback
11 import MacOS
12 import AE
13 from AppleEvents import *
14 import Evt
15 from Events import *
16 import Menu
17 import Win
18 from Windows import *
19 import Qd
21 import aetools
22 import EasyDialogs
24 kHighLevelEvent = 23 # Not defined anywhere for Python yet?
27 class MiniApplication:
29 """A minimal FrameWork.Application-like class"""
31 def __init__(self):
32 self.quitting = 0
33 # Initialize menu
34 self.appleid = 1
35 self.quitid = 2
36 Menu.ClearMenuBar()
37 self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024")
38 applemenu.AppendMenu("%s;(-" % self.getaboutmenutext())
39 applemenu.AppendResMenu('DRVR')
40 applemenu.InsertMenu(0)
41 self.quitmenu = Menu.NewMenu(self.quitid, "File")
42 self.quitmenu.AppendMenu("Quit")
43 self.quitmenu.SetItemCmd(1, ord("Q"))
44 self.quitmenu.InsertMenu(0)
45 Menu.DrawMenuBar()
47 def __del__(self):
48 self.close()
50 def close(self):
51 pass
53 def mainloop(self, mask = everyEvent, timeout = 60*60):
54 while not self.quitting:
55 self.dooneevent(mask, timeout)
57 def _quit(self):
58 self.quitting = 1
60 def dooneevent(self, mask = everyEvent, timeout = 60*60):
61 got, event = Evt.WaitNextEvent(mask, timeout)
62 if got:
63 self.lowlevelhandler(event)
65 def lowlevelhandler(self, event):
66 what, message, when, where, modifiers = event
67 h, v = where
68 if what == kHighLevelEvent:
69 msg = "High Level Event: %s %s" % \
70 (`code(message)`, `code(h | (v<<16))`)
71 try:
72 AE.AEProcessAppleEvent(event)
73 except AE.Error, err:
74 print 'AE error: ', err
75 print 'in', msg
76 traceback.print_exc()
77 return
78 elif what == keyDown:
79 c = chr(message & charCodeMask)
80 if modifiers & cmdKey:
81 if c == '.':
82 raise KeyboardInterrupt, "Command-period"
83 if c == 'q':
84 self.quitting = 1
85 return
86 elif what == mouseDown:
87 partcode, window = Win.FindWindow(where)
88 if partcode == inMenuBar:
89 result = Menu.MenuSelect(where)
90 id = (result>>16) & 0xffff # Hi word
91 item = result & 0xffff # Lo word
92 if id == self.appleid:
93 if item == 1:
94 EasyDialogs.Message(self.getabouttext())
95 elif item > 1:
96 name = self.applemenu.GetMenuItemText(item)
97 Menu.OpenDeskAcc(name)
98 elif id == self.quitid and item == 1:
99 self.quitting = 1
100 Menu.HiliteMenu(0)
101 return
102 # Anything not handled is passed to Python/SIOUX
103 MacOS.HandleEvent(event)
105 def getabouttext(self):
106 return self.__class__.__name__
108 def getaboutmenutext(self):
109 return "About %s\311" % self.__class__.__name__
112 class AEServer:
114 def __init__(self):
115 self.ae_handlers = {}
117 def installaehandler(self, classe, type, callback):
118 AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
119 self.ae_handlers[(classe, type)] = callback
121 def close(self):
122 for classe, type in self.ae_handlers.keys():
123 AE.AERemoveEventHandler(classe, type)
125 def callback_wrapper(self, _request, _reply):
126 _parameters, _attributes = aetools.unpackevent(_request)
127 _class = _attributes['evcl'].type
128 _type = _attributes['evid'].type
130 if self.ae_handlers.has_key((_class, _type)):
131 _function = self.ae_handlers[(_class, _type)]
132 elif self.ae_handlers.has_key((_class, '****')):
133 _function = self.ae_handlers[(_class, '****')]
134 elif self.ae_handlers.has_key(('****', '****')):
135 _function = self.ae_handlers[('****', '****')]
136 else:
137 raise 'Cannot happen: AE callback without handler', (_class, _type)
139 # XXXX Do key-to-name mapping here
141 _parameters['_attributes'] = _attributes
142 _parameters['_class'] = _class
143 _parameters['_type'] = _type
144 if _parameters.has_key('----'):
145 _object = _parameters['----']
146 del _parameters['----']
147 try:
148 rv = apply(_function, (_object,), _parameters)
149 except TypeError, name:
150 raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name)
151 else:
152 try:
153 rv = apply(_function, (), _parameters)
154 except TypeError, name:
155 raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name)
157 if rv == None:
158 aetools.packevent(_reply, {})
159 else:
160 aetools.packevent(_reply, {'----':rv})
163 def code(x):
164 "Convert a long int to the 4-character code it really is"
165 s = ''
166 for i in range(4):
167 x, c = divmod(x, 256)
168 s = chr(c) + s
169 return s
171 class _Test(AEServer, MiniApplication):
172 """Mini test application, handles required events"""
174 def __init__(self):
175 MiniApplication.__init__(self)
176 AEServer.__init__(self)
177 self.installaehandler('aevt', 'oapp', self.open_app)
178 self.installaehandler('aevt', 'quit', self.quit)
179 self.installaehandler('aevt', '****', self.other)
180 self.mainloop()
182 def quit(self, **args):
183 self._quit()
185 def open_app(self, **args):
186 pass
188 def other(self, _object=None, _class=None, _type=None, **args):
189 print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
192 if __name__ == '__main__':
193 _Test()