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

Initial revision

üst 1d6a6ea1
"""PythonSlave.py
An application that responds to three types of apple event:
'pyth'/'EXEC': execute direct parameter as Python
'aevt', 'quit': quit
'aevt', 'odoc': perform python scripts
Copyright 1996, Just van Rossum, Letterror
"""
__version__ = "0.1.3"
import FrameWork
import sys
import traceback
import aetools
import string
import AE
import EasyDialogs
import os
import Qd
from Types import *
from Events import charCodeMask, cmdKey
import MacOS
import Evt
def dummyfunc(): pass
modulefilename = dummyfunc.func_code.co_filename
def Interact(timeout = 50000000): # timeout after 10 days...
AE.AEInteractWithUser(timeout)
class PythonSlave(FrameWork.Application):
def __init__(self):
FrameWork.Application.__init__(self)
AE.AEInstallEventHandler('pyth', 'EXEC', ExecHandler)
AE.AEInstallEventHandler('aevt', 'quit', QuitHandler)
AE.AEInstallEventHandler('aevt', 'odoc', OpenDocumentHandler)
def makeusermenus(self):
self.filemenu = m = FrameWork.Menu(self.menubar, "File")
self._quititem = FrameWork.MenuItem(m, "Quit", "Q", self._quit)
def do_kHighLevelEvent(self, event):
(what, message, when, where, modifiers) = event
try:
AE.AEProcessAppleEvent(event)
except AE.Error, detail:
print "Apple Event was not handled, error:", detail
def do_key(self, event):
(what, message, when, where, modifiers) = event
c = chr(message & charCodeMask)
if modifiers & cmdKey and c == '.':
return
FrameWork.Application.do_key(self, event)
def idle(self, event):
Qd.InitCursor()
def quit(self, *args):
raise self
def getabouttext(self):
return "About PythonSlave"
def do_about(self, id, item, window, event):
EasyDialogs.Message("PythonSlave " + __version__ + "\rCopyright 1996, Letterror, JvR")
def ExecHandler(theAppleEvent, theReply):
parameters, args = aetools.unpackevent(theAppleEvent)
if parameters.has_key('----'):
if parameters.has_key('NAME'):
print '--- executing "' + parameters['NAME'] + '" ---'
else:
print '--- executing "<unknown>" ---'
stuff = parameters['----']
MyExec(stuff + "\n") # execute input
print '--- done ---'
return 0
def MyExec(stuff):
stuff = string.splitfields(stuff, '\r') # convert return chars
stuff = string.joinfields(stuff, '\n') # to newline chars
Interact()
saveyield = MacOS.EnableAppswitch(1)
try:
exec stuff in {}
except:
MacOS.EnableAppswitch(saveyield)
traceback.print_exc()
MacOS.EnableAppswitch(saveyield)
def OpenDocumentHandler(theAppleEvent, theReply):
parameters, args = aetools.unpackevent(theAppleEvent)
docs = parameters['----']
if type(docs) <> ListType:
docs = [docs]
for doc in docs:
fss, a = doc.Resolve()
path = fss.as_pathname()
if path <> modulefilename:
MyExecFile(path)
return 0
def MyExecFile(path):
saveyield = MacOS.EnableAppswitch(1)
savewd = os.getcwd()
os.chdir(os.path.split(path)[0])
print '--- Executing file "' + os.path.split(path)[1] + '"'
try:
execfile(path, {"__name__": "__main__"})
except:
traceback.print_exc()
MacOS.EnableAppswitch(saveyield)
MacOS.EnableAppswitch(saveyield)
os.chdir(savewd)
print "--- done ---"
def QuitHandler(theAppleEvent, theReply):
slave.quit()
return 0
slave = PythonSlave()
print "PythonSlave", __version__, "ready."
slave.mainloop()
"Run as Python" -- a BBEdit extension to make the Python interpreter execute the
contents of the current window.
version 0.2.3, 18 september 1996
contents:
- "Run as Python" -- the extension
- PythonSlave.py -- the "slave" script that handles the AppleEvents
- source -- source code & CW9 project for the extension
quickstart:
- drop "Run as Python" in BBEdit extensions folder
- double-click PythonSlave.py
- start BBEdit
- type some code
- go to Extensions menu: "Run as Python"
- be happy
warning:
since PythonSlave.py runs its own event loop and we have no interface
to SIOUX you *cannot* copy from the console. Duh.
extra feature:
while PythonSlave.py is running you can still double-click Python
documents, they will get executed as if Python was not already running.
bugs:
perhaps
acknowledgements:
- Thanks to Joseph Strout for valuable input and beta testing.
- Thanks to Mark Roseman for providing code that can launch
PythonSlave.py from BBEdit.
Have fun with it!
Please report bugs, or fix 'em. Suggestions are always welcome.
Just van Rossum, Letterror
<just@knoware.nl>
/* BBPython
A simple menu command to send the contents of a window to the Python interpreter
copyright 1996 Just van Rossum, Letterror: just@knoware.nl
All Rights Reserved
*/
#include <MacHeaders68K>
#include <A4Stuff.h>
#include <SetUpA4.h> // for global variables, multiple segments, etc.
#include "ExternalInterface.h"
#include <Memory.h>
extern OSErr SendTextAsAE(ExternalCallbackBlock *callbacks, Ptr theText, long theSize, Str255 windowTitle);
extern OSErr LaunchPythonSlave(FSSpec * docSpec);
extern Boolean GetPythonSlaveSpec(FSSpec * docSpec);
(This file must be converted with BinHex 4.0)
:#8*#8(NZFR0bB`"bFh*M8P0&4!#3#!*eepN!N!3"!!!!!I-!!!$c!!!!JJ$l!&`
"6F!#!!X!N!@N!$3!a!"N"J#3"U3!I!P#3P"j,R*cFQ0ZG'9bCQ&MC5jSF(*U,QK
aH(PiHA0X!!"3BA*d8dP8)3#3',&VJKm!N!B#G@jMC@`!N!8j!%i!63#H"!T%Efl
9G#"6BACP!*!&$!"1!#`"GBJh8f&fC5"MD'&ZCf9c)(4[)(4SC5"0CA4bEhGPFQY
c)%4[Bh9YC@jd)0*H-0-JBQ9QEh*P)&ia2`)!N!8-!"F!,!!hS!)!!J#3$)%%!!%
!!!!1!#J!+!#-!C!!!)"996!+!!!!"!!!!N%!!!#!!!-!N!9!!33!9!&8"!0CCA-
!N!C!!+S!9!$k"!*1E`#3"3J!2!!f!95)2Y*3HA4SEfj6E'&fC5j`HG-JDA-JEQp
d)(*eEQjTEQFX)!ehEh9XC#"jEh8JE'PVC5"dEb"XEf0KG'8JDA3r!*!&#!!+!#J
!+U!#!!%!!!!'!3!!8J#3"8F!)b!!!!!'GM!Z-Lic1AB`,M)Z-b#T)%TeFh3JGQ&
Z)&*[Fh0eE5![)%aPG(4PFR*[FL`J2'TeFh4!E'9dG'9bFQpb,QjX2J!!!3!!!!(
c!!!!m`!!!)))r"0%*d`!!!!F!))!"(CPFR-!!!!U4%P86!!!!$C"6&*8!!!!3N*
#@%B!!!"13N*B5`!!!&S!!Irr!!!!U!Mm%I`!J2rr!!!!'J#3"B$rr`#3#B$rr`!
!!")!N!@!rrm!!!#H!*!%red:
/*
* Launch the PythonSlave.py script.
* This works exactly as if you'd double clicked on the file in the Finder, which
* not surprisingly is how its implemented (via the AppleEvents route of course).
*
* Largely based on code submitted by Mark Roseman <roseman@cpsc.ucalgary.ca>
* Thanks!
*/
#include "BBPy.h"
pascal Boolean MyFileFilter(CInfoPBPtr PB);
FileFilterUPP gMyFileFilterUPP = NULL;
Boolean GetPythonSlaveSpec(FSSpec * docSpec) {
StandardFileReply reply;
SFTypeList typeList;
typeList[0] = 'TEXT';
//if (!gMyFileFilterUPP)
gMyFileFilterUPP = NewFileFilterProc( MyFileFilter );
StandardGetFile(gMyFileFilterUPP, 0, typeList, &reply);
DisposePtr((Ptr)gMyFileFilterUPP);
if(!reply.sfGood)
return 0; /* user cancelled */
docSpec->vRefNum = reply.sfFile.vRefNum;
docSpec->parID = reply.sfFile.parID;
BlockMove(reply.sfFile.name, docSpec->name, 64);
return 1;
}
pascal Boolean MyFileFilter(CInfoPBPtr PB) {
OSType fType; /* file type */
OSType fCreator; /* file creator */
fType =((HParmBlkPtr)PB)->fileParam.ioFlFndrInfo.fdType;
fCreator = ((HParmBlkPtr)PB)->fileParam.ioFlFndrInfo.fdCreator;
if (fType == 'TEXT' &&
fCreator == 'Pyth')
return 0;
return 1;
}
OSErr LaunchPythonSlave(FSSpec * docSpec) {
OSErr err;
FSSpec dirSpec;
AEAddressDesc finderAddress;
AppleEvent theEvent, theReply;
OSType finderSig = 'MACS';
AliasHandle DirAlias, FileAlias;
AEDesc fileList;
AEDesc aeDirDesc, listElem;
err = AECreateDesc(typeApplSignature, (Ptr)&finderSig, 4, &finderAddress);
if(err != noErr) return err;
err = AECreateAppleEvent('FNDR', 'sope', &finderAddress,
kAutoGenerateReturnID, kAnyTransactionID, &theEvent);
if(err != noErr) return err;
FSMakeFSSpec(docSpec->vRefNum, docSpec->parID, NULL, &dirSpec);
NewAlias(NULL, &dirSpec, &DirAlias);
NewAlias(NULL, docSpec, &FileAlias);
err = AECreateList(NULL, 0, 0, &fileList);
HLock((Handle)DirAlias);
AECreateDesc(typeAlias, (Ptr)*DirAlias, GetHandleSize((Handle)DirAlias), &aeDirDesc);
HUnlock((Handle)DirAlias);
if ((err = AEPutParamDesc(&theEvent, keyDirectObject, &aeDirDesc)) == noErr) {
AEDisposeDesc(&aeDirDesc);
HLock((Handle)FileAlias);
AECreateDesc(typeAlias, (Ptr)*FileAlias, GetHandleSize((Handle)FileAlias), &listElem);
HLock((Handle)FileAlias);
err = AEPutDesc(&fileList, 0, &listElem);
}
AEDisposeDesc(&listElem);
err = AEPutParamDesc(&theEvent, 'fsel', &fileList);
AEDisposeDesc(&fileList);
err = AESend(&theEvent, &theReply, kAENoReply+kAENeverInteract,
kAENormalPriority, kAEDefaultTimeout, 0L, 0L);
if(err != noErr) return err;
err = AEDisposeDesc(&theEvent);
if(err != noErr) return err;
err = AEDisposeDesc(&theReply);
return err;
}
/*
* Launch the PythonSlave.py script.
* This works exactly as if you'd double clicked on the file in the Finder, which
* not surprisingly is how its implemented (via the AppleEvents route of course).
*
* Largely based on code submitted by Mark Roseman <roseman@cpsc.ucalgary.ca>
* Thanks!
*/
#include "BBPy.h"
pascal Boolean MyFileFilter(CInfoPBPtr PB);
FileFilterUPP gMyFileFilterUPP = NULL;
Boolean GetPythonSlaveSpec(FSSpec * docSpec) {
StandardFileReply reply;
SFTypeList typeList;
typeList[0] = 'TEXT';
//if (!gMyFileFilterUPP)
gMyFileFilterUPP = NewFileFilterProc( MyFileFilter );
StandardGetFile(gMyFileFilterUPP, 0, typeList, &reply);
DisposePtr((Ptr)gMyFileFilterUPP);
if(!reply.sfGood)
return 0; /* user cancelled */
docSpec->vRefNum = reply.sfFile.vRefNum;
docSpec->parID = reply.sfFile.parID;
BlockMove(reply.sfFile.name, docSpec->name, 64);
return 1;
}
pascal Boolean MyFileFilter(CInfoPBPtr PB) {
OSType fType; /* file type */
OSType fCreator; /* file creator */
fType =((HParmBlkPtr)PB)->fileParam.ioFlFndrInfo.fdType;
fCreator = ((HParmBlkPtr)PB)->fileParam.ioFlFndrInfo.fdCreator;
if (fType == 'TEXT' &&
fCreator == 'Pyth')
return 0;
return 1;
}
OSErr LaunchPythonSlave(FSSpec * docSpec) {
OSErr err;
FSSpec dirSpec;
AEAddressDesc finderAddress;
AppleEvent theEvent, theReply;
OSType finderSig = 'MACS';
AliasHandle DirAlias, FileAlias;
AEDesc fileList;
AEDesc aeDirDesc, listElem;
err = AECreateDesc(typeApplSignature, (Ptr)&finderSig, 4, &finderAddress);
if(err != noErr) return err;
err = AECreateAppleEvent('FNDR', 'sope', &finderAddress,
kAutoGenerateReturnID, kAnyTransactionID, &theEvent);
if(err != noErr) return err;
FSMakeFSSpec(docSpec->vRefNum, docSpec->parID, NULL, &dirSpec);
NewAlias(NULL, &dirSpec, &DirAlias);
NewAlias(NULL, docSpec, &FileAlias);
err = AECreateList(NULL, 0, 0, &fileList);
HLock((Handle)DirAlias);
AECreateDesc(typeAlias, (Ptr)*DirAlias, GetHandleSize((Handle)DirAlias), &aeDirDesc);
HUnlock((Handle)DirAlias);
if ((err = AEPutParamDesc(&theEvent, keyDirectObject, &aeDirDesc)) == noErr) {
AEDisposeDesc(&aeDirDesc);
HLock((Handle)FileAlias);
AECreateDesc(typeAlias, (Ptr)*FileAlias, GetHandleSize((Handle)FileAlias), &listElem);
HLock((Handle)FileAlias);
err = AEPutDesc(&fileList, 0, &listElem);
}
AEDisposeDesc(&listElem);
err = AEPutParamDesc(&theEvent, 'fsel', &fileList);
AEDisposeDesc(&fileList);
err = AESend(&theEvent, &theReply, kAENoReply+kAENeverInteract,
kAENormalPriority, kAEDefaultTimeout, 0L, 0L);
if(err != noErr) return err;
err = AEDisposeDesc(&theEvent);
if(err != noErr) return err;
err = AEDisposeDesc(&theReply);
return err;
}
/* BBPython
A simple menu command to send the contents of a window to the Python interpreter
copyright 1996 Just van Rossum, Letterror: just@knoware.nl
All Rights Reserved
*/
#include "BBPy.h"
OSErr SendTextAsAE(ExternalCallbackBlock *callbacks, Ptr theText, long theSize, Str255 windowTitle)
{
OSErr err;
AEDesc theEvent;
AEAddressDesc theTarget;
AppleEvent theReply;
AEDesc theTextDesc;
AEDesc theNameDesc;
OSType pythonSig = 'Pyth';
FSSpec docSpec;
short itemHit;
long time;
EventRecord theDummyEvent;
/* initialize AE descriptor for python's signature */
err = AECreateDesc (typeApplSignature, &pythonSig, sizeof(OSType), &theTarget);
if(err != noErr) return err;
/* initialize AE descriptor for the title of our window */
err = AECreateDesc (typeChar, &windowTitle[1], windowTitle[0], &theNameDesc);
if(err != noErr) return err;
/* initialize AE descriptor for the content of our window */
err = AECreateDesc ('TEXT', theText, theSize, &theTextDesc);
if(err != noErr) return err;
/* initialize AppleEvent */
err = AECreateAppleEvent ('pyth', 'EXEC', &theTarget, kAutoGenerateReturnID, kAnyTransactionID, &theEvent);
if(err != noErr) return err;
/* add the content of our window to the AppleEvent */
err = AEPutParamDesc (&theEvent, keyDirectObject, &theTextDesc);
if(err != noErr) return err;
/* add the title of our window to the AppleEvent */
err = AEPutParamDesc (&theEvent, 'NAME', &theNameDesc);
if(err != noErr) return err;
/* send the AppleEvent */
err = AESend (&theEvent, &theReply, kAEWaitReply, kAEHighPriority, kNoTimeOut, NULL, NULL);
if(err == connectionInvalid) {
// launch PythonSlave.py
itemHit = Alert(128, NULL);
if(itemHit == 2) return noErr; /* user cancelled */
if( ! GetPythonSlaveSpec(&docSpec) )
return noErr; /* user cancelled */
err = LaunchPythonSlave(&docSpec);
if(err != noErr) return err;
} else if(err != noErr)
return err;
/* clean up */
err = AEDisposeDesc (&theTarget);
if(err != noErr) return err;
err = AEDisposeDesc (&theNameDesc);
if(err != noErr) return err;
err = AEDisposeDesc (&theTextDesc);
if(err != noErr) return err;
err = AEDisposeDesc (&theEvent);
if(err != noErr) return err;
err = AEDisposeDesc (&theReply);
if(err != noErr) return err;
/* everything is cool */
return noErr;
}
pascal void main(ExternalCallbackBlock *callbacks, WindowPtr theWindow)
{
long oldA4;
OSErr err;
Handle windowContents;
Str255 windowTitle;
//RememberA0(); /* Can't find header file for this. Seems to work anyway. */
oldA4 = SetUpA4();
GetWTitle(theWindow, windowTitle);
windowContents = callbacks->GetWindowContents(theWindow);
HLock(windowContents);
err = SendTextAsAE(callbacks, *windowContents, GetHandleSize(windowContents), windowTitle);
if(err != noErr) callbacks->ReportOSError(err);
HUnlock(windowContents);
RestoreA4(oldA4);
}
'''
Minimal test module
'''#
import sys
import PythonScript
SIGNATURE = 'MACS'
TIMEOUT = 10*60*60
PythonScript.PsScript(SIGNATURE, TIMEOUT)
p = PythonScript.PyScript
ev = PythonScript.PsEvents
pc = PythonScript.PsClass
pp = PythonScript.PsProperties
startup = str(p(ev.Get, pc.Desktopobject(1).Startup_disk().Name()))
print 'startup',startup, type(startup)
print p(ev.Get, pc.Disk(startup).Folder(7).File(1).Name())
print p(ev.Get, pc.Disk(1).Name())
print p(ev.Get, pc.Disk('every').Name())
print p(ev.Make, None, New='Alias_file', At=pp.Desktop(''), To=pp.System_folder(1))
sys.exit(1)
"""
Python script a module to comunicate with apple events
v 0.1a2
v.0.2 16 april 1998
"""
import sys
import getaete
import baetools
import baetypes
import AE
import AppleEvents
import macfs
from types import *
#from aetypes import InstanceType
from aepack import AEDescType
ordinal = {
'every': 'all ',
'first' : 'firs',
'last' : 'last',
'any' : 'any ',
'middle' : 'midd'}
Error = 'PythonScript.Error'
class PsEvents:
pass
class PsClasses:
def __getattr__(self, name):
try:
return DCItem(name, self)
except:
pass
def __repr__(self):
if self.form != 'prop':
t = type(self.seld)
if t == StringType:
self.form = 'name'
elif baetypes.IsRange(self.seld):
self.form = 'rang'
elif baetypes.IsComparison(self.seld) or baetypes.IsLogical(self.seld):
self.form = 'test'
elif t == TupleType:
# Breakout: specify both form and seld in a tuple
# (if you want ID or rele or somesuch)
self.form, self.seld = self.seld
elif t == IntType:
self.form = 'indx'
else:
pass
if self.seld in ordinal.keys():
self.seld = baetypes.Ordinal(ordinal[self.seld])
self.form = 'indx'
s = "baetypes.ObjectSpecifier(%s, %s, %s" % (`self.want`, `self.form`, `self.seld`)
if `self.fr`:
s = s + ", %s)" % `self.fr`
else:
s = s + ")"
return s
def __str__(self):
return self.want
def template(self, seld=None, fr=None):
self.seld = seld
self.fr = fr
def template1(self, which, fr=None):
self.want = 'prop'
self.form = 'prop'
self.fr = fr
class DCItem:
def __init__(self, comp, fr):
self.compclass = comp
self.fr = fr
def __call__(self, which=None):
if which:
self.compclass = eval('PsClass.%s' % self.compclass)
else:
try:
self.compclass = eval('PsProperties.%s' % self.compclass)
except AttributeError:
self.compclass = eval('PsClass.%s' % self.compclass)
return self.compclass(which, self.fr)
class PsClass:
pass
class PsProperties:
pass
class PsEnumerations:
pass
def PsScript(sig=None, Timeout=0, Ignoring=0):
elements = {}
if sig:
target, sig = Signature(sig)
pyscript = getaete.Getaete(sig)
else:
target, sig = Signature('Pyth')
pyscript = getaete.Getaete()
setattr(PyScript, 'timeout', Timeout)
setattr(PyScript, 'ignoring', Ignoring)
setattr(PyScript, 'target', target)
for key, value in pyscript[0].items():
setattr(PsEvents, key, value)
for key, value in pyscript[1].items():
CreateClass(key, 'PsClasses', value)
for val in value[2]:
CreateProperty(val[0], 'PsClasses', `val[1]`)
if value[3]:
for val in value[3]:
if val[0] not in elements.keys():
elements[val[0]] = val[1]
elif len(val[1]) > len(elements[val[0]]):
elements[val[0]] = val[1]
for key, value in pyscript[2].items():
for val in value:
setattr(PsEnumerations, val[0], val[1])
def CreateClass(newClassName, superClassName, value):
parentDict = PsClass.__dict__
exec "class %s(%s): pass" % (newClassName, superClassName) in \
globals(), parentDict
newClassObj = parentDict[newClassName]
newClassObj.__init__ = template
exec "setattr(newClassObj, 'want', %s)" % `value[0]`
if value[2] and value[2][0][0] == 'every':
exec "setattr(newClassObj, 'plur', 1)"
def CreateProperty(newClassName, superClassName, value):
parentDict = PsProperties.__dict__
exec "class %s(%s): pass" % (newClassName, superClassName) in \
globals(), parentDict
newClassObj = parentDict[newClassName]
if newClassName == 'Every':
value = "baetypes.mkOrdinal('every')"
newClassObj.__init__ = template1
exec "setattr(newClassObj, 'seld', %s)" % value
def Signature(signature):
if type(signature) == AEDescType:
target = signature
elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
target = signature.__aepack__()
elif type(signature) == StringType:
if len(signature) == 4:
target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
target_signature = signature
else:
#This should ready be made persistant, so PythonScript 'remembered' where applications were
fss, ok = macfs.PromptGetFile('Find the aplication %s' % signature, 'APPL')
if ok:
target_signature = fss.GetCreatorType()[0]
target = AE.AECreateDesc(AppleEvents.typeApplSignature, target_signature)
else:
raise TypeError, "signature should be 4-char string or AEDesc"
return target, target_signature
class PyScript(PsEvents):
def __init__(self, name, obj=None, **args):
desc, code, subcode, rply, message, keywds = name
# print 'code', code
# print 'subcode', subcode
# print 'rply', rply
# print 'message', message
# print 'keywds', keywds
# print 'name', name
# print 'obj', obj
# print 'args', args
self.code = code
self.subcode = subcode
self.attributes ={}
self.arguments = {}
if keywds:
self.arguments = self.keyargs(keywds, args)
self.arguments['----'] = self.keyfms(message[0], obj)
##XXXX Eudora needs this XXXX##
if self.arguments['----'] == None:
del self.arguments['----']
# print 'arguments', self.arguments
if self.ignoring or rply[0] == 'null':
self.send_flags = AppleEvents.kAENoReply
else:
self.send_flags = AppleEvents.kAEWaitReply
self.send_priority = AppleEvents.kAENormalPriority
if self.timeout:
self.send_timeout = self.timeout
else:
self.send_timeout = AppleEvents.kAEDefaultTimeout
def keyargs(self, ats, args):
# print 'keyargs', ats, args
output = {}
for arg in args.keys():
for at in ats:
if at[0] == arg:
output[at[1]] = self.keyfms(at[2][0], args[arg])
return output
def keyfms(self, key, value):
# print 'keyfms', 'key', key, `value`
if key == 'obj ' or key == 'insl':
return eval(`value`)
elif key == 'TEXT':
return value
elif key == 'null':
return
elif key == 'bool':
return baetypes.mkboolean(value)
elif key == 'type':
try:
val = eval('PsClass.%s()' % value)
return baetypes.mktype(str(val))
except:
return baetypes.mktype(value)
else:
print "I don't know what to put here -- script.keyargs"
print key, `value`
sys.exit[1]
def newevent(self, code, subcode, parameters = {}, attributes = {}):
"""Create a complete structure for an apple event"""
# print code, subcode, parameters, attributes
event = AE.AECreateAppleEvent(code, subcode, self.target,
AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
baetools.packevent(event, parameters, attributes)
return event
def sendevent(self, event):
"""Send a pre-created appleevent, await the reply and unpack it"""
reply = event.AESend(self.send_flags, self.send_priority,
self.send_timeout)
parameters, attributes = baetools.unpackevent(reply)
return reply, parameters, attributes
def send(self, code, subcode, parameters = {}, attributes = {}):
"""Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
# print code, subcode, parameters, attributes
return self.sendevent(self.newevent(code, subcode, parameters, attributes))
def __str__(self):
_reply, _arguments, _attributes = self.send(self.code, self.subcode, self.arguments, self.attributes)
if _arguments.has_key('errn'):
raise baetools.Error, baetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return str(_arguments['----'])
else:
return
def test():
Simp = 'Hermit:Applications:SimpleText'
PsScript('MACS', Timeout=60*60*3)
# PsScript('CSOm', Timeout=60*60*3)
# PsScript('', Timeout=60*60*3)
# PyScript('macsoup')
ev = PsEvents
ps = PsClass
# print PsProperties.__dict__
# y = script(ev.Open, File('Hermit:Desktop Folder:Lincolnshire Imp'), using=Application_file(Simp))
# print baetypes.NProperty('prop', 'prop', 'pnam', baetypes.ObjectSpecifier('cdis', 'indx', 1, None))
# y = PyScript(ev.Get, Disk("Hermit").Folder(7).File(1).Name())
# y = PyScript(ev.Get, Disk("Hermit").Size(), As='Integer')
# y = PyScript(ev.Get, ps.Desktopobject(1).Startup_disk())
# y = PyScript(ev.Get, Mailbox(1).File(), as='TEXT')
# print 'y', y, type(y)
if __name__ == '__main__':
test()
# sys.exit(1)
PythonScript
------------
v0.5 beta 1 24/04/98
author: Bill Bedford, <billb@mousa.demon.co.uk>
This suite of modules is a first attempt at writing a more user friendly
python/appleevent interface. The files in the suite are:
PythonScript
------------
Loads three dictionaries generated by getaete into __dict__'s of three
classes and thus gives us direct assess to all the methods in the aete.
Each method now contains all the information needed to build apple events.
The general usage is
>>>PythonScript.PsScript(SIGNATURE, TIMEOUT, IGNORING)
where
SIGNATURE is the target application
TIMEOUT is in ticks
and IGNORING is a boolean and determines whether the script waits for a reply
from the target before going on to the next event
>>>PythonScript.PyScript(Event, Object, keywdarg1..., keywdarg2...etc)
Object is a appleevent object specifier and is of the form
PythonScript.PsClass.Class1(arg).Class2(arg)Š.Property()
All applescript event, class and property names are capitalised to
distinguish them from python methods.
getaete
-------
Reads the aete of the target application and returns it as a list of three
dictionaries, which represent all the events, properties and enumeration in
the aete. (the fourth dictionary, comparisons, has never been implemented
in applescript so I have not used it) It also reads the applescript aeut
and adds any suites that are missing (ie where the application author has
set his suite to inherit from the aeut.) and the applescript suite, which
gives the language methods
printaete
---------
Produces a text file with the aete set out in a human readable form,
similar to the Open Dictionary command in the applescript editor.
baetools, baepack, baetypes
---------------------------
These are direct equivalents of aetools, aepack, aetypes in the standard
distribution. Some methods and classes have been enhanced others are
redundant
PyScriptTest, testeudora
------------------------
A couple of test scripts. Testeudora is an updated version of the one in
the standard distribution.
Still To Do (in no particular order)
-----------
These modules are much slower than applescript. I believe they could be
made faster by rewriting the aete parser in getaete and/or by putting in
some form of persistent storage so that the class dictionaries can be cached.
The parsing of the appleevent replies need rewriting.
Support for the use of scripting additions.
A Python aeut needs to be written, much of the applescript one is redundant
in python.
Probably a few other things I haven't thought of yet.
This diff is collapsed.
"""Tools for use in AppleEvent clients and servers.
pack(x) converts a Python object to an AEDesc object
unpack(desc) does the reverse
packevent(event, parameters, attributes) sets params and attrs in an AEAppleEvent record
unpackevent(event) returns the parameters and attributes from an AEAppleEvent record
Plus... Lots of classes and routines that help representing AE objects,
ranges, conditionals, logicals, etc., so you can write, e.g.:
x = Character(1, Document("foobar"))
and pack(x) will create an AE object reference equivalent to AppleScript's
character 1 of document "foobar"
Some of the stuff that appears to be exported from this module comes from other
files: the pack stuff from aepack, the objects from aetypes.
"""
from types import *
import AE
import AppleEvents
import MacOS
import sys
from baetypes import *
from baepack import pack, unpack, coerce, AEDescType
Error = 'baetools.Error'
# Special code to unpack an AppleEvent (which is *not* a disguised record!)
# Note by Jack: No??!? If I read the docs correctly it *is*....
aekeywords = [
'tran',
'rtid',
'evcl',
'evid',
'addr',
'optk',
'timo',
'inte', # this attribute is read only - will be set in AESend
'esrc', # this attribute is read only
'miss', # this attribute is read only
'from' # new in 1.0.1
]
def missed(ae):
try:
desc = ae.AEGetAttributeDesc('miss', 'keyw')
except AE.Error, msg:
return None
return desc.data
def unpackevent(ae):
parameters = {}
while 1:
key = missed(ae)
if not key: break
parameters[key] = unpack(ae.AEGetParamDesc(key, '****'))
attributes = {}
for key in aekeywords:
try:
desc = ae.AEGetAttributeDesc(key, '****')
except (AE.Error, MacOS.Error), msg:
if msg[0] != -1701 and msg[0] != -1704:
raise sys.exc_type, sys.exc_value
continue
attributes[key] = unpack(desc)
return parameters, attributes
def packevent(ae, parameters = {}, attributes = {}):
for key, value in parameters.items():
ae.AEPutParamDesc(key, pack(value))
for key, value in attributes.items():
ae.AEPutAttributeDesc(key, pack(value))
#
# Support routine for automatically generated Suite interfaces
# These routines are also useable for the reverse function.
#
def keysubst(arguments, keydict):
"""Replace long name keys by their 4-char counterparts, and check"""
ok = keydict.values()
for k in arguments.keys():
if keydict.has_key(k):
v = arguments[k]
del arguments[k]
arguments[keydict[k]] = v
elif k != '----' and k not in ok:
raise TypeError, 'Unknown keyword argument: %s'%k
def enumsubst(arguments, key, edict):
"""Substitute a single enum keyword argument, if it occurs"""
if not arguments.has_key(key):
return
v = arguments[key]
ok = edict.values()
if edict.has_key(v):
arguments[key] = edict[v]
elif not v in ok:
raise TypeError, 'Unknown enumerator: %s'%v
def decodeerror(arguments):
"""Create the 'best' argument for a raise MacOS.Error"""
errn = arguments['errn']
err_a1 = errn
if arguments.has_key('errs'):
err_a2 = arguments['errs']
else:
err_a2 = MacOS.GetErrorString(errn)
if arguments.has_key('erob'):
err_a3 = arguments['erob']
else:
err_a3 = None
return (err_a1, err_a2, err_a3)
class TalkTo:
"""An AE connection to an application"""
def __init__(self, signature, start=0, timeout=0):
"""Create a communication channel with a particular application.
Addressing the application is done by specifying either a
4-byte signature, an AEDesc or an object that will __aepack__
to an AEDesc.
"""
self.target_signature = None
if type(signature) == AEDescType:
self.target = signature
elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
self.target = signature.__aepack__()
elif type(signature) == StringType and len(signature) == 4:
self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
self.target_signature = signature
else:
raise TypeError, "signature should be 4-char string or AEDesc"
self.send_flags = AppleEvents.kAEWaitReply
self.send_priority = AppleEvents.kAENormalPriority
if timeout:
self.send_timeout = timeout
else:
self.send_timeout = AppleEvents.kAEDefaultTimeout
if start:
self.start()
def start(self):
"""Start the application, if it is not running yet"""
self.send_flags = AppleEvents.kAENoReply
_launch(self.target_signature)
def newevent(self, code, subcode, parameters = {}, attributes = {}):
"""Create a complete structure for an apple event"""
event = AE.AECreateAppleEvent(code, subcode, self.target,
AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
# print parameters, attributes
packevent(event, parameters, attributes)
return event
def sendevent(self, event):
"""Send a pre-created appleevent, await the reply and unpack it"""
reply = event.AESend(self.send_flags, self.send_priority,
self.send_timeout)
parameters, attributes = unpackevent(reply)
return reply, parameters, attributes
def send(self, code, subcode, parameters = {}, attributes = {}):
"""Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
return self.sendevent(self.newevent(code, subcode, parameters, attributes))
#
# The following events are somehow "standard" and don't seem to appear in any
# suite...
#
def activate(self):
"""Send 'activate' command"""
self.send('misc', 'actv')
def _get(self, _object, as=None, _attributes={}):
"""_get: get data from an object
Required argument: the object
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the data
"""
_code = 'core'
_subcode = 'getd'
_arguments = {'----':_object}
if as:
_arguments['rtyp'] = mktype(as)
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise Error, decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
# Tiny Finder class, for local use only
class _miniFinder(TalkTo):
def open(self, _object, _attributes={}, **_arguments):
"""open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
#pass
_finder = _miniFinder('MACS')
def _launch(appfile):
"""Open a file thru the finder. Specify file by name or fsspec"""
_finder.open(_application_file(('ID ', appfile)))
class _application_file(ComponentItem):
"""application file - An application's file on disk"""
want = 'appf'
_application_file._propdict = {
}
_application_file._elemdict = {
}
# Test program
# XXXX Should test more, really...
def test():
target = AE.AECreateDesc('sign', 'quil')
ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
print unpackevent(ae)
raw_input(":")
ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
obj = Character(2, Word(1, Document(1)))
print obj
print repr(obj)
packevent(ae, {'----': obj})
params, attrs = unpackevent(ae)
print params['----']
raw_input(":")
if __name__ == '__main__':
test()
sys.exit(1)
This diff is collapsed.
This diff is collapsed.
"""
Produces a human readable file of an application's aete
v.02 january 29, 1998 bug fix Main()
v.03 january 31, 1998 added support for inheriting suites from aeut
v.04 april 16, 1998 Changed identify to match getaete
"""
import aetools
import sys
import MacOS
import StringIO
import types
import macfs
import string
import macpath
from Res import *
# for testing only
app = 'MACS'#CSOm'#'nwSP'#'ezVu'#
#Dialect file hard coded as a tempoary measure
DIALECT = 'Hermit:System Folder:Scripting Additions:Dialects:English Dialect'
#Restrict the application suites to the dialect we want to use.
LANG = 0 # 0 = English, 1 = French, 11 = Japanese
#The following are neaded to open the application aete
kASAppleScriptSuite = 'ascr'
kGetAETE = 'gdte'
attributes = {}
arguments = {}
class AETE(aetools.TalkTo):
pass
def Main(appl):
fss, ok = macfs.PromptGetFile('Application to work on', 'FNDR', 'APPL')#
if not ok:
return
app = fss.GetCreatorType()[0]
path = macpath.split(sys.argv[0])[0]
appname = macpath.split(fss.as_pathname())[1]
appname = appname + '.aete'
appname = macpath.join(path, appname)
try:
data = Getaete(app)
except MacOS.Error, msg:
if msg[0] == -609:
_launch(app)
data = Getaete(app)
# print data
data = decode(data['----'].data)
data = compileaete(data, appname)
def decode(data):
"""Decode an aete into a python data structure"""
f = StringIO.StringIO(data)
aete = generic(getaete, f)
aete = simplify(aete)
return aete
def simplify(item):
"""Recursively replace singleton tuples by their constituent item"""
if type(item) is types.ListType:
return map(simplify, item)
elif type(item) == types.TupleType and len(item) == 2:
return simplify(item[1])
else:
return item
## Here follows the aete resource decoder.
## It is presented bottom-up instead of top-down because there are direct
## references to the lower-level part-decoders from the high-level part-decoders.
#
def getbyte(f, *args):
c = f.read(1)
if not c:
raise EOFError, 'in getbyte' + str(args)
return ord(c)
def getword(f, *args):
getalign(f)
s = f.read(2)
if len(s) < 2:
raise EOFError, 'in getword' + str(args)
return (ord(s[0])<<8) | ord(s[1])
def getlong(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getlong' + str(args)
return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
def getostype(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getostype' + str(args)
return s
def getpstr(f, *args):
c = f.read(1)
if len(c) < 1:
raise EOFError, 'in getpstr[1]' + str(args)
nbytes = ord(c)
if nbytes == 0: return ''
s = f.read(nbytes)
if len(s) < nbytes:
raise EOFError, 'in getpstr[2]' + str(args)
return s
def getalign(f):
if f.tell() & 1:
c = f.read(1)
##if c <> '\0':
## print 'align:', `c`
def getlist(f, description, getitem):
count = getword(f)
list = []
for i in range(count):
list.append(generic(getitem, f))
getalign(f)
return list
def alt_generic(what, f, *args):
print "generic", `what`, args
res = vageneric(what, f, args)
print '->', `res`
return res
def generic(what, f, *args):
if type(what) == types.FunctionType:
return apply(what, (f,) + args)
if type(what) == types.ListType:
record = []
for thing in what:
# print thing
item = apply(generic, thing[:1] + (f,) + thing[1:])
record.append((thing[1], item))
return record
return "BAD GENERIC ARGS: %s" % `what`
getdata = [
(getostype, "type"),
(getpstr, "description"),
(getword, "flags")
]
getargument = [
(getpstr, "name"),
(getostype, "keyword"),
(getdata, "what")
]
getevent = [
(getpstr, "name"),
(getpstr, "description"),
(getostype, "suite code"),
(getostype, "event code"),
(getdata, "returns"),
(getdata, "accepts"),
(getlist, "optional arguments", getargument)
]
getproperty = [
(getpstr, "name"),
(getostype, "code"),
(getdata, "what")
]
getelement = [
(getostype, "type"),
(getlist, "keyform", getostype)
]
getclass = [
(getpstr, "name"),
(getostype, "class code"),
(getpstr, "description"),
(getlist, "properties", getproperty),
(getlist, "elements", getelement)
]
getcomparison = [
(getpstr, "operator name"),
(getostype, "operator ID"),
(getpstr, "operator comment"),
]
getenumerator = [
(getpstr, "enumerator name"),
(getostype, "enumerator ID"),
(getpstr, "enumerator comment")
]
getenumeration = [
(getostype, "enumeration ID"),
(getlist, "enumerator", getenumerator)
]
getsuite = [
(getpstr, "suite name"),
(getpstr, "suite description"),
(getostype, "suite ID"),
(getword, "suite level"),
(getword, "suite version"),
(getlist, "events", getevent),
(getlist, "classes", getclass),
(getlist, "comparisons", getcomparison),
(getlist, "enumerations", getenumeration)
]
getaete = [
(getword, "major/minor version in BCD"),
(getword, "language code"),
(getword, "script code"),
(getlist, "suites", getsuite)
]
def compileaete(aete, appname):
"""Generate dictionary file for a full aete resource."""
[version, language, script, suites] = aete
major, minor = divmod(version, 256)
fp = open(appname, 'w')
fp.write('%s:\n' % (appname))
fp.write("AETE resource version %d/%d, language %d, script %d\n" % \
(major, minor, language, script))
fp.write('\n\n')
gsuites = openaeut()
for suite in suites:
if language == LANG:
suitecode = suite[2]
if suite[5] == []:
for gsuite in gsuites:
if suitecode == gsuite[2]:
suite = gsuite
[name, desc, code, level, version, events, classes, comps, enums] = suite
fp.write('\n%s Suite: %s\n' % (name, desc))
fp.write('\n\tEvents:\n')
for event in events:
fp.write('\n\t%s: %s\n' % (identify(event[0]), event[1]))
fp.write('\t\t%s: %s -- %s\n' % (identify(event[0]), event[5][1], event[5][0]))
fp.write('\t\tResult: %s -- %s\n' % (event[4][1], event[4][0]))
for ev in event[6]:
fp.write('\t\t\t%s: %s -- %s\n' % (identify(ev[0]), ev[2][0], ev[2][1]))
fp.write('\n\tClasses')
for klass in classes:
fp.write('\n\t%s: %s\n' % (identify(klass[0]), klass[2]))
if klass[3]:
if not klass[3][0][0]: continue
fp.write('\t\tProperties\n')
for cl in klass[3]:
fp.write('\t\t\t%s: %s -- %s\n' % (identify(cl[0]), cl[2][1], cl[2][0]))#,, cl[3][3][1]))
if klass[4]:
fp.write('\n\t\t\tElements\n')
for cl in klass[4]:
fp.write('\t\t\t\t%s: %s\n' % (identify(cl[0]), cl[1]))
illegal_ids = [ "for", "in", "from", "and", "or", "not", "print", "class", "return",
"def", "name" ]
def identify(str):
"""Turn any string into an identifier:
- replace space by _
- prepend _ if the result is a python keyword
"""
rv = string.replace(str, ' ', '_')
rv = string.replace(rv, '-', '')
rv = string.replace(rv, ',', '')
rv = string.capitalize(rv)
return rv
def Getaete(app):
'''Read the target aete'''
arguments['----'] = LANG
_aete = AETE(app)
_reply, _arguments, _attributes = _aete.send('ascr', 'gdte', arguments, attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
return _arguments
def openaeut():
"""Open and read a aeut file.
XXXXX This has been temporarily hard coded until a Python aeut is written XXXX"""
fullname = DIALECT
rf = OpenRFPerm(fullname, 0, 1)
try:
UseResFile(rf)
resources = []
for i in range(Count1Resources('aeut')):
res = Get1IndResource('aeut', 1+i)
resources.append(res)
for res in resources:
data = res.data
data = decode(data)[3]
finally:
CloseResFile(rf)
return data
#The following should be replaced by direct access to a python 'aeut'
class _miniFinder(aetools.TalkTo):
def open(self, _object, _attributes={}, **_arguments):
"""open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
_finder = _miniFinder('MACS')
def _launch(appfile):
"""Open a file thru the finder. Specify file by name or fsspec"""
_finder.open(_application_file(('ID ', appfile)))
class _application_file(aetools.ComponentItem):
"""application file - An application's file on disk"""
want = 'appf'
_application_file._propdict = {
}
_application_file._elemdict = {
}
Main(app)
sys.exit(1)
"""A test program that allows us to control Eudora"""
import sys
import MacOS
import PythonScript
# The Creator signature of eudora:
SIGNATURE="CSOm"
TIMEOUT = 10*60*60
def main():
PythonScript.PsScript(SIGNATURE, TIMEOUT)
talker = PythonScript.PyScript
ev = PythonScript.PsEvents
pc = PythonScript.PsClass
while 1:
print 'get, put, name (of first folder), list (foldernames), quit (eudora) or exit (this program) ?'
line = sys.stdin.readline()
try:
if line[0] == 'g':
print 'check'
print talker(ev.Activate)
print talker(ev.Connect, Checking=1)
elif line[0] == 'p':
print talker(ev.Connect, Sending=1)
elif line[0] == 'n':
id = talker(ev.Get, pc.Mail_folder("").Mailbox(1).Name())
print "It is called", id, "\n"
elif line[0] == 'l':
id = talker(ev.Count, pc.Mail_folder(""), Each='Mailbox')
print "There are", id, "mailboxes"
elif line[0] == 'q':
print talker(ev.Quit)
elif line[0] == 'e':
break
except MacOS.Error, arg:
if arg[0] == -609:
print 'Connection invalid, is eudora running?'
else:
print 'MacOS Error:', arg[1]
main()
/*
*
* This is a simple module to allow the
* user to compile and execute an applescript
* which is passed in as a text item.
*
* Sean Hummel <seanh@prognet.com>
* 1/20/98
* RealNetworks
*
* Jay Painter <jpaint@serv.net> <jpaint@gimp.org> <jpaint@real.com>
*
*
*/
#include "OSAm.h"
#include "ScriptRunner.h"
#include <AppleEvents.h>
/*
* Boiler plate generated from "genmodule.py"
*/
static PyObject *ErrorObject;
static char OSAm_DoCommand__doc__[] = "";
static PyObject *
OSAm_RunCompiledScript (self, args)
PyObject *self;
PyObject *args;
{
char *commandStr = NULL;
char *outpath = NULL;
OSErr myErr;
AEDesc temp;
EventRecord event;
temp.dataHandle = NULL;
if (!PyArg_ParseTuple (args, "s", &commandStr))
return NULL;
myErr = ExecuteScriptFile (commandStr, NULL, &temp);
if (temp.dataHandle != NULL && temp.descriptorType == 'TEXT')
{
char *line;
DescType typeCode;
long dataSize = 0;
HLock (temp.dataHandle);
dataSize = GetHandleSize (temp.dataHandle);
if (dataSize > 0)
{
PyObject *result = PyString_FromStringAndSize ((*temp.dataHandle),
dataSize);
AEDisposeDesc (&temp);
if (!result)
{
printf ("OSAm.error Out of memory.\n");
Py_INCREF (Py_None);
return Py_None;
}
return result;
}
}
if (myErr != noErr)
{
PyErr_Mac (ErrorObject, myErr);
return NULL;
}
Py_INCREF (Py_None);
return Py_None;
}
static PyObject *
OSAm_CompileAndSave (self, args)
PyObject *self;
PyObject *args;
{
char *commandStr = NULL;
char *outpath = NULL;
OSErr myErr;
AEDesc temp;
EventRecord event;
temp.dataHandle = NULL;
if (!PyArg_ParseTuple (args, "ss", &commandStr, &outpath))
return NULL;
myErr = CompileAndSave (commandStr, outpath, NULL, &temp);
if (temp.dataHandle != NULL && temp.descriptorType == 'TEXT')
{
char *line;
DescType typeCode;
long dataSize = 0;
HLock (temp.dataHandle);
dataSize = GetHandleSize (temp.dataHandle);
if (dataSize > 0)
{
PyObject *result = PyString_FromStringAndSize ((*temp.dataHandle),
dataSize);
AEDisposeDesc (&temp);
if (!result)
{
printf ("OSAm.error Out of memory.\n");
Py_INCREF (Py_None);
return Py_None;
}
return result;
}
}
if (myErr != noErr)
{
PyErr_Mac (ErrorObject, myErr);
return NULL;
}
Py_INCREF (Py_None);
return Py_None;
}
static PyObject *
OSAm_CompileAndExecute (self, args)
PyObject *self;
PyObject *args;
{
char *commandStr;
OSErr myErr;
AEDesc temp;
EventRecord event;
temp.dataHandle = NULL;
if (!PyArg_ParseTuple (args, "s", &commandStr))
return NULL;
myErr = CompileAndExecute (commandStr, &temp, NULL);
if (temp.dataHandle != NULL && temp.descriptorType == 'TEXT')
{
char *line;
DescType typeCode;
long dataSize = 0;
HLock (temp.dataHandle);
dataSize = GetHandleSize (temp.dataHandle);
if (dataSize > 0)
{
PyObject *result = PyString_FromStringAndSize ((*temp.dataHandle),
dataSize);
AEDisposeDesc (&temp);
if (!result)
{
printf ("OSAm.error Out of memory.\n");
Py_INCREF (Py_None);
return Py_None;
}
return result;
}
}
if (myErr != noErr)
{
PyErr_Mac (ErrorObject, myErr);
return NULL;
}
Py_INCREF (Py_None);
return Py_None;
}
/*
* List of methods defined in the module
*/
static struct PyMethodDef OSAm_methods[] =
{
{"CompileAndExecute",
(PyCFunction) OSAm_CompileAndExecute,
METH_VARARGS,
OSAm_DoCommand__doc__},
{"CompileAndSave",
(PyCFunction) OSAm_CompileAndSave,
METH_VARARGS,
OSAm_DoCommand__doc__},
{"RunCompiledScript",
(PyCFunction) OSAm_RunCompiledScript,
METH_VARARGS,
OSAm_DoCommand__doc__},
{NULL, (PyCFunction) NULL, 0, NULL}
};
static char OSAm_module_documentation[] = "";
/*
* PYTHON Module Initalization
*/
void
initOSAm ()
{
PyObject *m, *d;
/* Create the module and add the functions */
m = Py_InitModule4 ("OSAm",
OSAm_methods,
OSAm_module_documentation,
(PyObject *) NULL, PYTHON_API_VERSION);
/* Add some symbolic constants to the module */
d = PyModule_GetDict (m);
ErrorObject = PyString_FromString ("OSAm.error");
PyDict_SetItemString (d, "error", ErrorObject);
/* Check for errors */
if (PyErr_Occurred ())
Py_FatalError ("can't initialize module OSAm");
}
/*
*
* This is a simple module to allow the
* user to compile and execute an applescript
* which is passed in as a text item.
*
* Sean Hummel <seanh@prognet.com>
* 1/20/98
* RealNetworks
*
* Jay Painter <jpaint@serv.net> <jpaint@gimp.org> <jpaint@real.com>
*
*
*/
#pragma once
/* Python API */
#include "Python.h"
#include "macglue.h"
/* Macintosh API */
#include <Types.h>
#include <AppleEvents.h>
#include <Processes.h>
#include <Files.h>
#include <Gestalt.h>
#include <Events.h>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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