Kaydet (Commit) bb653772 authored tarafından Jack Jansen's avatar Jack Jansen

Oops... I Inadvertently lost their cvs files...

üst 0f7af3f7
"""AEservertest - Test AppleEvent server interface
(adapted from Guido's 'echo' program).
Build an applet from this source, and include the aete resource that you
want to test. Use the AEservertest script to try things.
"""
import addpack
addpack.addpack('Tools')
addpack.addpack('bgen')
addpack.addpack('ae')
addpack.addpack('evt')
#addpack.addpack('menu')
addpack.addpack('win')
import sys
sys.stdout = sys.stderr
import traceback
import MacOS
import AE
from AppleEvents import *
import Evt
from Events import *
import Menu
import Dlg
import Win
from Windows import *
import Qd
import macfs
import aetools
import EasyDialogs
kHighLevelEvent = 23 # Not defined anywhere for Python yet?
Quit='Quit'
def mymessage(str):
err = AE.AEInteractWithUser(kAEDefaultTimeout)
if err:
print str
EasyDialogs.Message(str)
def myaskstring(str, default=''):
err = AE.AEInteractWithUser(kAEDefaultTimeout)
if err:
return default
return EasyDialogs.AskString(str, default)
def main():
echo = EchoServer()
yield = MacOS.EnableAppswitch(-1) # Disable Python's own "event handling"
try:
try:
echo.mainloop(everyEvent, 0)
except Quit:
pass
finally:
MacOS.EnableAppswitch(yield) # Let Python have a go at events
echo.close()
class EchoServer:
suites = ['aevt', 'core', 'reqd']
def __init__(self):
self.active = 0
#
# Install the handlers
#
for suite in self.suites:
AE.AEInstallEventHandler(suite, typeWildCard, self.aehandler)
print (suite, typeWildCard, self.aehandler)
self.active = 1
#
# Setup the apple menu and file/quit
#
self.appleid = 1
self.fileid = 2
Menu.ClearMenuBar()
self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024")
applemenu.AppendMenu("All about echo...;(-")
applemenu.AppendResMenu('DRVR')
applemenu.InsertMenu(0)
self.filemenu = Menu.NewMenu(self.fileid, 'File')
self.filemenu.AppendMenu("Quit/Q")
self.filemenu.InsertMenu(0)
Menu.DrawMenuBar()
#
# Set interaction allowed (for the return values)
#
AE.AESetInteractionAllowed(kAEInteractWithAll)
def __del__(self):
self.close()
def close(self):
if self.active:
self.active = 0
for suite in self.suites:
AE.AERemoveEventHandler(suite, typeWildCard)
def mainloop(self, mask = everyEvent, timeout = 60*60):
while 1:
self.dooneevent(mask, timeout)
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))`)
self.handled_by_us = 0
try:
AE.AEProcessAppleEvent(event)
except AE.Error, err:
mymessage(msg + "\015AEProcessAppleEvent error: %s" % str(err))
traceback.print_exc()
else:
if self.handled_by_us == 0:
print msg, "Handled by AE, somehow"
else:
print msg, 'Handled by us.'
elif what == keyDown:
c = chr(message & charCodeMask)
if modifiers & cmdKey:
if c == '.':
raise KeyboardInterrupt, "Command-period"
else:
self.menuhit(Menu.MenuKey(message&charCodeMask))
##MacOS.HandleEvent(event)
elif what == mouseDown:
partcode, window = Win.FindWindow(where)
if partcode == inMenuBar:
result = Menu.MenuSelect(where)
self.menuhit(result)
elif what <> autoKey:
print "Event:", (eventname(what), message, when, (h, v), modifiers)
## MacOS.HandleEvent(event)
def menuhit(self, result):
id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word
if id == self.appleid:
if item == 1:
mymessage("Echo -- echo AppleEvents")
elif item > 1:
name = self.applemenu.GetItem(item)
Qd.OpenDeskAcc(name)
elif id == self.fileid:
if item == 1:
raise Quit
def aehandler(self, request, reply):
print "Apple Event!"
self.handled_by_us = 1
parameters, attributes = aetools.unpackevent(request)
print "class =", `attributes['evcl'].type`,
print "id =", `attributes['evid'].type`
print "Parameters:"
keys = parameters.keys()
keys.sort()
for key in keys:
print "%s: %.150s" % (`key`, `parameters[key]`)
print " :", str(parameters[key])
print "Attributes:"
keys = attributes.keys()
keys.sort()
for key in keys:
print "%s: %.150s" % (`key`, `attributes[key]`)
parameters['----'] = self.askreplyvalue()
aetools.packevent(reply, parameters)
def askreplyvalue(self):
while 1:
str = myaskstring('Reply value to send (python-style)', 'None')
try:
rv = eval(str)
break
except:
pass
return rv
_eventnames = {
keyDown: 'keyDown',
autoKey: 'autoKey',
mouseDown: 'mouseDown',
mouseUp: 'mouseUp',
updateEvt: 'updateEvt',
diskEvt: 'diskEvt',
activateEvt: 'activateEvt',
osEvt: 'osEvt',
}
def eventname(what):
if _eventnames.has_key(what): return _eventnames[what]
else: return `what`
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
if __name__ == '__main__':
main()
This diff is collapsed.
# The oldest AppleEvent test program.
# Its function has been overtaken by echo.py and tell.py.
import AE
from AppleEvents import *
import Evt
from Events import *
import struct
import aetools
import macfs
import sys
import MacOS
MacOS.EnableAppswitch(0)
def aehandler(request, reply):
tosend = []
print 'request:', aetools.unpackevent(request)
param = request.AEGetParamDesc(keyDirectObject, typeWildCard)
if param.type == typeAEList:
n = param.AECountItems()
print 'List has', n, 'items'
for i in range(1, 1+n):
type, item = param.AEGetNthDesc(i, typeFSS)
data = item.data
print 'item', i, ':', type, item.type, len(data), 'bytes'
vol, dir, fnlen = struct.unpack('hlb', data[:7])
filename = data[7:7+fnlen]
print 'vol:', vol, '; dir:', dir, '; filename:', `filename`
print 'full path:', macfs.FSSpec((vol,dir,filename)).as_pathname()
tosend.append(item)
else:
pass
print 'param:', (param.type, param.data[:20]), param.data[20:] and '...'
if tosend:
passtothink(tosend)
def passtothink(list):
target = AE.AECreateDesc(typeApplSignature, 'KAHL')
event = AE.AECreateAppleEvent(kCoreEventClass,
kAEOpenDocuments,
target,
kAutoGenerateReturnID,
kAnyTransactionID)
aetools.packevent(event, {keyDirectObject: list})
reply = event.AESend(kAENoReply | kAEAlwaysInteract | kAECanSwitchLayer,
kAENormalPriority,
kAEDefaultTimeout)
#print "Reply:", aetools.unpackevent(reply)
return
event = AE.AECreateAppleEvent(kCoreEventClass,
kAEOpenApplication,
target,
kAutoGenerateReturnID,
kAnyTransactionID)
reply = event.AESend(kAENoReply | kAEAlwaysInteract | kAECanSwitchLayer,
kAENormalPriority,
kAEDefaultTimeout)
def unihandler(req, rep):
print 'unihandler'
aehandler(req, rep)
quit = 0
def quithandler(req, rep):
global quit
quit = 1
def corehandler(req, rep):
print 'core event!'
parameters, attributes = aetools.unpackevent(req)
print "event class =", attributes['evcl']
print "event id =", attributes['evid']
print 'parameters:', parameters
# echo the arguments, to see how Script Editor formats them
aetools.packevent(rep, parameters)
def wildhandler(req, rep):
print 'wildcard event!'
parameters, attributes = aetools.unpackevent(req)
print "event class =", attributes['evcl']
print "event id =", attributes['evid']
print 'parameters:', parameters
AE.AEInstallEventHandler(typeAppleEvent, kAEOpenApplication, aehandler)
AE.AEInstallEventHandler(typeAppleEvent, kAEOpenDocuments, aehandler)
AE.AEInstallEventHandler(typeAppleEvent, kAEPrintDocuments, aehandler)
AE.AEInstallEventHandler(typeAppleEvent, kAEQuitApplication, quithandler)
AE.AEInstallEventHandler(typeAppleEvent, typeWildCard, unihandler)
AE.AEInstallEventHandler('core', typeWildCard, corehandler)
#AE.AEInstallEventHandler(typeWildCard, typeWildCard, wildhandler)
def main():
global quit
quit = 0
while not quit:
ok, e = Evt.WaitNextEvent(-1, 60)
if ok:
print 'Event:', e
if e[0] == 23: # kHighLevelEvent
AE.AEProcessAppleEvent(e)
elif e[0] == keyDown and chr(e[1]&0xff) == '.' and e[4]&cmdKey:
raise KeyboardInterrupt, "Command-Period"
else:
MacOS.HandleEvent(e)
if __name__ == '__main__':
main()
print "This module is obsolete -- use echo.py or tell.py ..."
# (Slightly less) primitive operations for sending Apple Events to applications.
# This could be the basis of a Script Editor like application.
from AE import *
from AppleEvents import *
import aetools
import types
class TalkTo:
def __init__(self, signature):
"""Create a communication channel with a particular application.
For now, the application must be given by its 4-character signature
(because I don't know yet how to do other target types).
"""
if type(signature) != types.StringType or len(signature) != 4:
raise TypeError, "signature should be 4-char string"
self.target = AECreateDesc(typeApplSignature, signature)
self.send_flags = kAEWaitReply
self.send_priority = kAENormalPriority
self.send_timeout = kAEDefaultTimeout
def newevent(self, code, subcode, parameters = {}, attributes = {}):
event = AECreateAppleEvent(code, subcode, self.target,
kAutoGenerateReturnID, kAnyTransactionID)
aetools.packevent(event, parameters, attributes)
return event
def sendevent(self, event):
reply = event.AESend(self.send_flags, self.send_priority,
self.send_timeout)
parameters, attributes = aetools.unpackevent(reply)
return reply, parameters, attributes
def send(self, code, subcode, parameters = {}, attributes = {}):
return self.sendevent(self.newevent(code, subcode, parameters, attributes))
def activate(self):
# Send undocumented but easily reverse engineered 'activate' command
self.send('misc', 'actv')
# This object is equivalent to "selection" in AppleScript
# (in the core suite, if that makes a difference):
get_selection = aetools.Property('sele', None)
# Test program. You can make it do what you want by passing parameters.
# The default gets the selection from Quill (Scriptable Text Editor).
def test(app = 'quil', suite = 'core', id = 'getd', arg = get_selection):
t = TalkTo(app)
t.activate()
if arg:
dict = {'----': arg}
else:
dict = {}
reply, parameters, attributes = t.send(suite, id, dict)
print reply, parameters
if parameters.has_key('----'): print "returns:", str(parameters['----'])
test()
# So we can see it:
import sys
sys.exit(1)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment