Commit 8bf053fe authored by Jack Jansen's avatar Jack Jansen

It was an old MacPython artefact that these files were still in the source

tree. Removed them, anyone really desparate to recover them can get them
from the CVS repository.
parent bb3e4cb1
This diff is collapsed.
These modules no longer work under Carbon. If you are trying to revive
non-carbon builds of MacPython you may want to revive them.
This diff is collapsed.
#
# FixCreator - Search for files with PYTH creator
# and set it to Pyth.
#
import os
import macfs
import sys
import macostools
OLD='PYTH'
NEW='Pyth'
def walktree(name, change):
if os.path.isfile(name):
fs = macfs.FSSpec(name)
cur_cr, cur_tp = fs.GetCreatorType()
if cur_cr == OLD:
fs.SetCreatorType(NEW, cur_tp)
macostools.touched(fs)
print 'Fixed ', name
elif os.path.isdir(name):
print '->', name
files = os.listdir(name)
for f in files:
walktree(os.path.join(name, f), change)
def run(change):
fss, ok = macfs.GetDirectory('Folder to search:')
if not ok:
sys.exit(0)
walktree(fss.as_pathname(), change)
if __name__ == '__main__':
run(1)
#
# Turn a pyc file into a resource file containing it in 'PYC ' resource form
from Carbon.Res import *
from Carbon import Res
from Carbon.Resources import *
import os
import macfs
import sys
import py_resource
error = 'mkpycresourcefile.error'
def mkpycresourcefile(src, dst):
"""Copy pyc file/dir src to resource file dst."""
if not os.path.isdir(src) and src[-4:] <> '.pyc':
raise error, 'I can only handle .pyc files or directories'
fsid = py_resource.create(dst)
if os.path.isdir(src):
handlesubdir(src)
else:
id, name = py_resource.frompycfile(src)
print 'Wrote %d: %s %s'%(id, name, src)
CloseResFile(fsid)
def handlesubdir(srcdir):
"""Recursively scan a directory for pyc files and copy to resources"""
src = os.listdir(srcdir)
for file in src:
file = os.path.join(srcdir, file)
if os.path.isdir(file):
handlesubdir(file)
elif file[-4:] == '.pyc':
id, name = py_resource.frompycfile(file)
print 'Wrote %d: %s %s'%(id, name, file)
if __name__ == '__main__':
args = sys.argv[1:]
if not args:
ifss, ok = macfs.GetDirectory('Select root of tree to pack:')
if not ok:
sys.exit(0)
args = [ifss.as_pathname()]
for ifn in args:
ofss, ok = macfs.StandardPutFile('Output for '+os.path.split(ifn)[1])
if not ok:
sys.exit(0)
mkpycresourcefile(ifn, ofss.as_pathname())
sys.exit(1) # So we can see something...
'''
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
from Carbon 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 *
from Carbon import AE
from Carbon 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 Carbon.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()
"""Import a module while pretending its name is __main__. This
can be used to run scripts from the PackedLib resource file while pretending
they have been double-clicked."""
import imp
import sys
import os
import string
from Carbon import Dlg
import macfs
DIALOG_ID = 512
OK = 1
CANCEL = 2
SCRIPTNAME=3
ARGV=4
STDIN_CONS=5
STDIN_FILE=6
STDOUT_CONS=7
STDOUT_FILE=8
WORKING_DIR=9
PAUSE=10
def import_as_main(name):
fp, path, (suffix, mode, type) = imp.find_module(name)
if type == imp.PY_SOURCE:
imp.load_source('__main__', path, fp)
elif type == imp.PY_COMPILED:
imp.load_compiled('__main__', path, fp)
elif type == imp.PY_RESOURCE:
imp.load_resource('__main__', path)
def interact():
d = Dlg.GetNewDialog(DIALOG_ID, -1)
wdir = stdin = stdout = None
pause = 0
tp, in_c_h, rect = d.GetDialogItem(STDIN_CONS)
tp, in_f_h, rect = d.GetDialogItem(STDIN_FILE)
tp, out_c_h, rect = d.GetDialogItem(STDOUT_CONS)
tp, out_f_h, rect = d.GetDialogItem(STDOUT_FILE)
tp, pause_h, rect = d.GetDialogItem(PAUSE)
in_c_h = in_c_h.as_Control()
in_f_h = in_f_h.as_Control()
out_c_h = out_c_h.as_Control()
out_f_h = out_f_h.as_Control()
pause_h = pause_h.as_Control()
while 1:
in_c_h.SetControlValue(not stdin)
in_f_h.SetControlValue(not not stdin)
out_c_h.SetControlValue(not stdout)
out_f_h.SetControlValue(not not stdout)
pause_h.SetControlValue(pause)
n = Dlg.ModalDialog(None)
if n == OK:
break
elif n == CANCEL:
sys.exit(0)
elif n == STDIN_CONS:
stdin = None
elif n == STDIN_FILE:
fss, ok = macfs.StandardGetFile('TEXT')
if ok:
stdin = fss
elif n == STDOUT_FILE:
fss, ok = macfs.StandardPutFile('stdout:')
if ok:
stdout = fss
elif n == WORKING_DIR:
fss, ok = macfs.GetDirectory()
if ok:
wdir = fss
elif n == PAUSE:
pause = (not pause)
tp, h, rect = d.GetDialogItem(SCRIPTNAME)
name = Dlg.GetDialogItemText(h)
tp, h, rect = d.GetDialogItem(ARGV)
argv = Dlg.GetDialogItemText(h)
return name, argv, stdin, stdout, wdir, pause
def main():
curdir = os.getcwd()
from Carbon import Res
try:
Res.FSpOpenResFile('RunLibScript.rsrc', 1)
except:
pass # Assume we're an applet already
name, argv, stdin, stdout, wdir, pause = interact()
if not name:
sys.exit(0)
sys.argv = [name] + string.split(argv)
if stdin:
sys.stdin = open(stdin.as_pathname())
if stdout:
sys.stdout = open(stdout.as_pathname(), 'w')
if wdir:
os.chdir(wdir.as_pathname())
else:
os.chdir(curdir)
import_as_main(name)
if pause:
sys.exit(1)
if __name__ == '__main__':
main()
#
# binhextree - Recursively descend a directory and
# pack all resource files.
#
# Actually it doesn't binhex anymore, it only copies projects.
#
# Jack Jansen, CWI, August 1995.
#
import os
import binhex
import sys
import macostools
import macfs
import aetools
from Metrowerks_Shell_Suite import Metrowerks_Shell_Suite
from Required_Suite import Required_Suite
class MwShell(aetools.TalkTo, Metrowerks_Shell_Suite, Required_Suite):
pass
# Top-level directory
TOP=''
# Where to put CW projects, relative to TOP
CWDIR=':Mac:mwerks:projects'
# From which folders to put projects there
CWDIRDIRS=['build.mac', 'build.macstand', 'build.macfreeze', 'PlugIns']
# Helper routines
def binhexit(path, name):
dstfile = path + '.hqx'
if os.path.exists(dstfile):
print 'Compare', path,'...',
if binhexcompare(path, dstfile):
print 'Identical, skipped.'
return
else:
print 'Not up-to-date.'
print 'Binhexing', path
binhex.binhex(path, dstfile)
def binhexcompare(source, hqxfile):
"""(source, hqxfile) - Check whether the two files match (forks only)"""
ifp = binhex.HexBin(hqxfile)
sfp = open(source, 'rb')
while 1:
d = ifp.read(128000)
d2 = sfp.read(128000)
if d <> d2:
return 0
if not d: break
sfp.close()
ifp.close_data()
d = ifp.read_rsrc(128000)
if d:
sfp = binhex.openrsrc(source, 'rb')
d2 = sfp.read(128000)
if d <> d2:
return 0
while 1:
d = ifp.read_rsrc(128000)
d2 = sfp.read(128000)
if d <> d2:
return 0
if not d: break
return 1
# Project files to handle
project_files = {}
def hexbincwprojects(creator):
"""Compact and hexbin all files remembered with a given creator"""
cw_running = 0
for fss in project_files[creator]:
srcfile = fss.as_pathname()
old_style = 0
if srcfile[-1] == '':
dstfile = srcfile[:-1]+'mu.hqx'
old_style = 1
elif srcfile[-3] == '.mu':
dstfile = srcfile + '.hqx'
elif ord(srcfile[-1]) >= 128:
dstfile = srcfile[:-1]+`ord(srcfile[-1])`+'.hqx'
else:
dstfile = srcfile + '.hqx'
if os.path.exists(dstfile) and \
os.stat(dstfile)[8] >= os.stat(srcfile)[8]:
print 'Skip', dstfile,'- Up-to-date'
continue
print 'Compacting', dstfile
if old_style:
if not cw_running:
try:
mgr = MwShell(creator, start=1)
except 'foo':
print 'Not handled:', creator
return
cw_running = 1
mgr.open(fss)
mgr.Reset_File_Paths()
mgr.Remove_Binaries()
mgr.Close_Project()
print 'Binhexing', dstfile
binhex.binhex(srcfile, dstfile)
if cw_running:
mgr.quit()
def copycwproject(path, name):
"""Copy CW project (if needed) and remember for hexbinning"""
global project_files
dstdir = os.path.join(TOP, CWDIR)
if path[:len(dstdir)] == dstdir:
return
srcdir = os.path.split(path)[0]
srcdir = os.path.split(srcdir)[1]
if srcdir in CWDIRDIRS:
if not os.path.exists(dstdir):
print dstdir
print 'No CW-project dir, skip', name
return
dstfile = os.path.join(dstdir, os.path.join(srcdir, name))
else:
if path[-2:] == '.':
dstfile = path[:-2]+ '.mu'
elif path[-4:] == '.prj':
dstfile = None
else:
return
if dstfile:
# If the destination doesn't exists or is older that the source
# we copy and remember it
if os.path.exists(dstfile) and \
os.stat(dstfile)[8] >= os.stat(path)[8]:
print 'Not copying', path,'- Up-to-date'
else:
print 'Copy', path
macostools.copy(path, dstfile)
else:
dstfile = path
fss = macfs.FSSpec(dstfile)
creator = fss.GetCreatorType()[0]
if project_files.has_key(creator):
project_files[creator].append(fss)
else:
project_files[creator] = [fss]
def copycwexpfile(path, name):
"""Copy CW export file"""
global project_files
dstdir = os.path.join(TOP, CWDIR)
if path[:len(dstdir)] == dstdir:
return
srcdir = os.path.split(path)[0]
srcdir = os.path.split(srcdir)[1]
if srcdir in CWDIRDIRS:
if not os.path.exists(dstdir):
print dstdir
print 'No CW-project dir, skip', name
return
dstfile = os.path.join(dstdir, os.path.join(srcdir, name))
else:
if path[-6:] != '..exp':
return
dstfile = path[:-6] + '.mu.exp'
if dstfile[-6:] == '..exp':
dstfile = dstfile[:-6]+'.mu.exp'
# If the destination doesn't exists or is older that the source
# we copy and remember it
if os.path.exists(dstfile) and \
os.stat(dstfile)[8] >= os.stat(path)[8]:
print 'Not copying', path,'- Up-to-date'
else:
print 'Copy', path
macostools.copy(path, dstfile)
extensions = [
## ('.rsrc', binhexit),
## ('.gif', binhexit),
('.', copycwproject),
('.prj', copycwproject),
('.prj.exp', copycwexpfile),
('..exp', copycwexpfile)
]
def walker(arg, top, names):
lnames = names[:]
for n in lnames:
if n[0] == '(' and n[-1] == ')':
names.remove(n)
continue
for ext, handler in extensions:
if n[-len(ext):] == ext:
name = os.path.join(top, n)
handler(name, n)
def dodir(name):
global TOP, project_files
TOP = name
os.path.walk(name, walker, None)
## for creator in project_files.keys():
## hexbincwprojects(creator)
project_files = {}
def main():
if len(sys.argv) > 1:
for dir in sys.argv[1:]:
dodir(dir)
elif os.name == 'mac':
import macfs
dir, ok = macfs.GetDirectory('Folder to search:')
if not ok:
sys.exit(0)
dodir(dir.as_pathname())
else:
print 'Usage: hexbintree dir ...'
sys.exit(1)
if os.name == 'mac':
sys.exit(1) # Keep window
else:
sys.exit(0)
if __name__ == '__main__':
main()
"""Findmodulefiles - Find out where modules are loaded from.
Run findmodulefiles() after running a program with "python -i". The
resulting file list can be given to mkfrozenresources or to a
(non-existent) freeze-like application.
findmodulefiles will create a file listing all modules and where they have
been imported from.
findunusedbuiltins takes a list of (modules, file) and prints all builtin modules
that are _not_ in the list. The list is created by opening the findmodulefiles
output, reading it and eval()ing that.
mkpycresource takes a list of (module, file) and creates a resourcefile with all those
modules and (optionally) a main module.
"""
def findmodulefiles(output=None):
"""Produce a file containing a list of (modulename, filename-or-None)
tuples mapping module names to source files"""
# Immedeately grab the names
import sys
module_names = sys.modules.keys()[:]
import os
if not output:
if os.name == 'mac':
import macfs
output, ok = macfs.StandardPutFile('Module file listing output:')
if not ok: sys.exit(0)
output = output.as_pathname()
if not output:
output = sys.stdout
elif type(output) == type(''):
output = open(output, 'w')
output.write('[\n')
for name in module_names:
try:
source = sys.modules[name].__file__
except AttributeError:
source = None
else:
source = `source`
output.write('\t(%s,\t%s),\n' % (`name`, source))
output.write(']\n')
del output
def findunusedbuiltins(list):
"""Produce (on stdout) a list of unused builtin modules"""
import sys
dict = {}
for name, location in list:
if location == None:
dict[name] = 1
for name in sys.builtin_module_names:
if not dict.has_key(name):
print 'Unused builtin module:', name
def mkpycresourcefile(list, main='', dst=None):
"""Copy list-of-modules to resource file dst."""
import py_resource
from Carbon import Res
import sys
if dst == None:
import macfs
fss, ok = macfs.StandardPutFile("PYC Resource output file")
if not ok: sys.exit(0)
dst = fss.as_pathname()
if main == '':
import macfs
fss, ok = macfs.PromptGetFile("Main program:", "TEXT")
if ok:
main = fss.as_pathname()
fsid = py_resource.create(dst)
if main:
id, name = py_resource.frompyfile(main, '__main__', preload=1)
print '%5d\t%s\t%s'%(id, name, main)
for name, location in list:
if not location: continue
if location[-4:] == '.pyc':
# Attempt corresponding .py
location = location[:-1]
if location[-3:] != '.py':
print '*** skipping', location
continue
id, name = py_resource.frompyfile(location, name, preload=1)
print '%5d\t%s\t%s'%(id, name, location)
Res.CloseResFile(fsid)
# fixgusidir - Modify filenames in the CWGUSI source tree, so
# that it can be put under CVS. Needed because there are files with slashes
# in their name, which CVS does not approve of.
#
# Usage:
# - On importing gusi in cvs:
# - Run the script after unpacking the gusi distribution. This creates
# _s_ files for all / files.
# - Remove all / files with "find file" or some such.
# - import the tree
# - On checking out gusi:
# - After checkout, run the script to create / files for all _s_ files.
# - After modifying stuff, or later checkouts:
# - Run the script. Conflicts between / and _s_ files will be reported.
# - Fix the problems by removing the outdated / or _s_ file.
# - Run the script again. Possibly do a cvs checkin.
import macfs
import os
import sys
import re
# Substitution for slashes in filenames
SUBST = '_s_'
# Program to find those substitutions
SUBSTPROG = re.compile(SUBST)
def main():
if len(sys.argv) > 1:
gusidir = sys.argv[1]
else:
fss, ok = macfs.GetDirectory("CWGUSI source folder?")
if not ok: sys.exit(0)
gusidir = fss.as_pathname()
fixgusifolder(gusidir)
sys.exit(1)
def fixgusifolder(gusidir):
"""Synchronize files with / in their name with their _s_ counterparts"""
os.path.walk(gusidir, gusiwalk, None)
def gusiwalk(dummy, top, names):
"""Helper for fixgusifolder: convert a single directory full of files"""
# First remember names with slashes and with our slash-substitution
macnames = []
codenames = []
for name in names:
if '/' in name:
macnames.append(name)
if SUBSTPROG.search(name):
codenames.append(name)
# Next, check whether we need to copy any slash-files to subst-files
for name in macnames:
if os.path.isdir(name):
print '** Folder with slash in name cannot be handled!'
sys.exit(1)
othername = mac2codename(name)
if len(othername) > 31:
print '** Converted filename too long:', othername
sys.exit(1)
if othername in codenames:
codenames.remove(othername)
sync(os.path.join(top, name), os.path.join(top, othername))
# Now codenames contains only files that have no / equivalent
for name in codenames:
othername = code2macname(name)
sync(os.path.join(top, name), os.path.join(top, othername))
def mac2codename(name):
return re.sub('/', SUBST, name)
def code2macname(name):
return re.sub(SUBST, '/', name)
def sync(old, new):
if os.path.exists(new):
# Both exist. Check that they are indentical
d1 = open(old, 'rb').read()
d2 = open(new, 'rb').read()
if d1 == d2:
print '-- OK ', old
return
print '** OUT-OF-SYNC', old
fp = open(new, 'wb')
fp.write(open(old, 'rb').read())
print '-- COPIED ', old
if __name__ == '__main__':
main()
#
# Given a module-list generated by findmodulefiles
# generate the resource file with all needed modules
#
import macfs
import py_resource
from Carbon import Res
import sys
def main():
fss, ok = macfs.PromptGetFile('Module sources listing:', 'TEXT')
if not ok:
sys.exit(0)
ofss, ok = macfs.StandardPutFile('PYC resource output file:')
if not ok:
sys.exit(0)
mfss, ok = macfs.PromptGetFile('Source for __main__ (or cancel):')
if ok:
mainfile = mfss.as_pathname()
else:
mainfile = None
fp = open(fss.as_pathname())
data = fp.read()
modules = eval(data)
fsid = py_resource.create(ofss.as_pathname(), creator='RSED')
if mainfile:
id, name = py_resource.frompyfile(mainfile, '__main__')
for module, source in modules:
if source:
id, name = py_resource.frompyfile(source)
print 'Wrote %d %s: %s'%(id, name, source)
Res.CloseResFile(fsid)
if __name__ == '__main__':
main()
sys.exit(1)
# Script (applet) to run any Python command
def main():
import sys
sys.stdout = sys.stderr
del sys.argv[:1]
if not sys.argv:
import macfs
srcfss, ok = macfs.StandardGetFile('TEXT')
if not ok:
return
filename = srcfss.as_pathname()
sys.argv.append(filename)
import __main__
try:
execfile(sys.argv[0], __main__.__dict__)
except SystemExit, msg:
if msg:
message("Exit status: %s" % str(msg))
print "exit", `msg`
#sys.exit(msg)
except:
etype = sys.exc_type
if hasattr(etype, "__name__"): etype = etype.__name__
message("%s: %s" % (etype, sys.exc_value))
print "exit 1"
#sys.exit(1)
def message(str = "Hello, world!", id = 256):
from Carbon import Dlg
d = Dlg.GetNewDialog(id, -1)
if not d:
print str
return
tp, h, rect = d.GetDItem(2)
Dlg.SetIText(h, str)
while 1:
n = Dlg.ModalDialog(None)
if n == 1: break
main()
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