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

Detabbed.

üst 058a84f3
...@@ -3,119 +3,119 @@ error='Audio_mac.error' ...@@ -3,119 +3,119 @@ error='Audio_mac.error'
class Play_Audio_mac: class Play_Audio_mac:
def __init__(self, qsize=QSIZE): def __init__(self, qsize=QSIZE):
self._chan = None self._chan = None
self._qsize = qsize self._qsize = qsize
self._outrate = 22254 self._outrate = 22254
self._sampwidth = 1 self._sampwidth = 1
self._nchannels = 1 self._nchannels = 1
self._gc = [] self._gc = []
self._usercallback = None self._usercallback = None
def __del__(self): def __del__(self):
self.stop() self.stop()
self._usercallback = None self._usercallback = None
def wait(self): def wait(self):
import time import time
while self.getfilled(): while self.getfilled():
time.sleep(0.1) time.sleep(0.1)
self._chan = None self._chan = None
self._gc = [] self._gc = []
def stop(self, quietNow = 1): def stop(self, quietNow = 1):
##chan = self._chan ##chan = self._chan
self._chan = None self._chan = None
##chan.SndDisposeChannel(1) ##chan.SndDisposeChannel(1)
self._gc = [] self._gc = []
def setoutrate(self, outrate): def setoutrate(self, outrate):
self._outrate = outrate self._outrate = outrate
def setsampwidth(self, sampwidth): def setsampwidth(self, sampwidth):
self._sampwidth = sampwidth self._sampwidth = sampwidth
def setnchannels(self, nchannels): def setnchannels(self, nchannels):
self._nchannels = nchannels self._nchannels = nchannels
def writeframes(self, data): def writeframes(self, data):
import time import time
from Carbon.Sound import bufferCmd, callBackCmd, extSH from Carbon.Sound import bufferCmd, callBackCmd, extSH
import struct import struct
import MacOS import MacOS
if not self._chan: if not self._chan:
from Carbon import Snd from Carbon import Snd
self._chan = Snd.SndNewChannel(5, 0, self._callback) self._chan = Snd.SndNewChannel(5, 0, self._callback)
nframes = len(data) / self._nchannels / self._sampwidth nframes = len(data) / self._nchannels / self._sampwidth
if len(data) != nframes * self._nchannels * self._sampwidth: if len(data) != nframes * self._nchannels * self._sampwidth:
raise error, 'data is not a whole number of frames' raise error, 'data is not a whole number of frames'
while self._gc and \ while self._gc and \
self.getfilled() + nframes > \ self.getfilled() + nframes > \
self._qsize / self._nchannels / self._sampwidth: self._qsize / self._nchannels / self._sampwidth:
time.sleep(0.1) time.sleep(0.1)
if self._sampwidth == 1: if self._sampwidth == 1:
import audioop import audioop
data = audioop.add(data, '\x80'*len(data), 1) data = audioop.add(data, '\x80'*len(data), 1)
h1 = struct.pack('llHhllbbl', h1 = struct.pack('llHhllbbl',
id(data)+MacOS.string_id_to_buffer, id(data)+MacOS.string_id_to_buffer,
self._nchannels, self._nchannels,
self._outrate, 0, self._outrate, 0,
0, 0,
0, 0,
extSH, extSH,
60, 60,
nframes) nframes)
h2 = 22*'\0' h2 = 22*'\0'
h3 = struct.pack('hhlll', h3 = struct.pack('hhlll',
self._sampwidth*8, self._sampwidth*8,
0, 0,
0, 0,
0, 0,
0) 0)
header = h1+h2+h3 header = h1+h2+h3
self._gc.append((header, data)) self._gc.append((header, data))
self._chan.SndDoCommand((bufferCmd, 0, header), 0) self._chan.SndDoCommand((bufferCmd, 0, header), 0)
self._chan.SndDoCommand((callBackCmd, 0, 0), 0) self._chan.SndDoCommand((callBackCmd, 0, 0), 0)
def _callback(self, *args): def _callback(self, *args):
del self._gc[0] del self._gc[0]
if self._usercallback: if self._usercallback:
self._usercallback() self._usercallback()
def setcallback(self, callback): def setcallback(self, callback):
self._usercallback = callback self._usercallback = callback
def getfilled(self): def getfilled(self):
filled = 0 filled = 0
for header, data in self._gc: for header, data in self._gc:
filled = filled + len(data) filled = filled + len(data)
return filled / self._nchannels / self._sampwidth return filled / self._nchannels / self._sampwidth
def getfillable(self): def getfillable(self):
return (self._qsize / self._nchannels / self._sampwidth) - self.getfilled() return (self._qsize / self._nchannels / self._sampwidth) - self.getfilled()
def ulaw2lin(self, data): def ulaw2lin(self, data):
import audioop import audioop
return audioop.ulaw2lin(data, 2) return audioop.ulaw2lin(data, 2)
def test(): def test():
import aifc import aifc
import EasyDialogs import EasyDialogs
fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",)) fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",))
if not fn: return if not fn: return
af = aifc.open(fn, 'r') af = aifc.open(fn, 'r')
print af.getparams() print af.getparams()
p = Play_Audio_mac() p = Play_Audio_mac()
p.setoutrate(af.getframerate()) p.setoutrate(af.getframerate())
p.setsampwidth(af.getsampwidth()) p.setsampwidth(af.getsampwidth())
p.setnchannels(af.getnchannels()) p.setnchannels(af.getnchannels())
BUFSIZ = 10000 BUFSIZ = 10000
while 1: while 1:
data = af.readframes(BUFSIZ) data = af.readframes(BUFSIZ)
if not data: break if not data: break
p.writeframes(data) p.writeframes(data)
print 'wrote', len(data), 'space', p.getfillable() print 'wrote', len(data), 'space', p.getfillable()
p.wait() p.wait()
if __name__ == '__main__': if __name__ == '__main__':
test() test()
...@@ -5,53 +5,53 @@ import struct ...@@ -5,53 +5,53 @@ import struct
# These needn't go through this module, but are here for completeness # These needn't go through this module, but are here for completeness
def SetControlData_Handle(control, part, selector, data): def SetControlData_Handle(control, part, selector, data):
control.SetControlData_Handle(part, selector, data) control.SetControlData_Handle(part, selector, data)
def GetControlData_Handle(control, part, selector): def GetControlData_Handle(control, part, selector):
return control.GetControlData_Handle(part, selector) return control.GetControlData_Handle(part, selector)
_accessdict = { _accessdict = {
kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle), kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle),
} }
_codingdict = { _codingdict = {
kControlPushButtonDefaultTag : ("b", None, None), kControlPushButtonDefaultTag : ("b", None, None),
kControlEditTextTextTag: (None, None, None), kControlEditTextTextTag: (None, None, None),
kControlEditTextPasswordTag: (None, None, None), kControlEditTextPasswordTag: (None, None, None),
kControlPopupButtonMenuIDTag: ("h", None, None), kControlPopupButtonMenuIDTag: ("h", None, None),
kControlListBoxDoubleClickTag: ("b", None, None), kControlListBoxDoubleClickTag: ("b", None, None),
} }
def SetControlData(control, part, selector, data): def SetControlData(control, part, selector, data):
if _accessdict.has_key(selector): if _accessdict.has_key(selector):
setfunc, getfunc = _accessdict[selector] setfunc, getfunc = _accessdict[selector]
setfunc(control, part, selector, data) setfunc(control, part, selector, data)
return return
if not _codingdict.has_key(selector): if not _codingdict.has_key(selector):
raise KeyError, ('Unknown control selector', selector) raise KeyError, ('Unknown control selector', selector)
structfmt, coder, decoder = _codingdict[selector] structfmt, coder, decoder = _codingdict[selector]
if coder: if coder:
data = coder(data) data = coder(data)
if structfmt: if structfmt:
data = struct.pack(structfmt, data) data = struct.pack(structfmt, data)
control.SetControlData(part, selector, data) control.SetControlData(part, selector, data)
def GetControlData(control, part, selector): def GetControlData(control, part, selector):
if _accessdict.has_key(selector): if _accessdict.has_key(selector):
setfunc, getfunc = _accessdict[selector] setfunc, getfunc = _accessdict[selector]
return getfunc(control, part, selector, data) return getfunc(control, part, selector, data)
if not _codingdict.has_key(selector): if not _codingdict.has_key(selector):
raise KeyError, ('Unknown control selector', selector) raise KeyError, ('Unknown control selector', selector)
structfmt, coder, decoder = _codingdict[selector] structfmt, coder, decoder = _codingdict[selector]
data = control.GetControlData(part, selector) data = control.GetControlData(part, selector)
if structfmt: if structfmt:
data = struct.unpack(structfmt, data) data = struct.unpack(structfmt, data)
if decoder: if decoder:
data = decoder(data) data = decoder(data)
if type(data) == type(()) and len(data) == 1: if type(data) == type(()) and len(data) == 1:
data = data[0] data = data[0]
return data return data
try: try:
from OverrideFrom23._Res import * from OverrideFrom23._Res import *
except ImportError: except ImportError:
from _Res import * from _Res import *
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -24,77 +24,77 @@ AS_RESOURCEFORK=2 ...@@ -24,77 +24,77 @@ AS_RESOURCEFORK=2
AS_IGNORE=(3,4,5,6,8,9,10,11,12,13,14,15) AS_IGNORE=(3,4,5,6,8,9,10,11,12,13,14,15)
def decode(input, output, resonly=0): def decode(input, output, resonly=0):
if type(input) == type(''): if type(input) == type(''):
input = open(input, 'rb') input = open(input, 'rb')
# Should we also test for FSSpecs or FSRefs? # Should we also test for FSSpecs or FSRefs?
header = input.read(AS_HEADER_LENGTH) header = input.read(AS_HEADER_LENGTH)
try: try:
magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header)
except ValueError, arg: except ValueError, arg:
raise Error, "Unpack header error: %s"%arg raise Error, "Unpack header error: %s"%arg
if verbose: if verbose:
print 'Magic: 0x%8.8x'%magic print 'Magic: 0x%8.8x'%magic
print 'Version: 0x%8.8x'%version print 'Version: 0x%8.8x'%version
print 'Entries: %d'%nentry print 'Entries: %d'%nentry
if magic != AS_MAGIC: if magic != AS_MAGIC:
raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic
if version != AS_VERSION: if version != AS_VERSION:
raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version
if nentry <= 0: if nentry <= 0:
raise Error, "AppleSingle file contains no forks" raise Error, "AppleSingle file contains no forks"
headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)]
didwork = 0 didwork = 0
for hdr in headers: for hdr in headers:
try: try:
id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr)
except ValueError, arg: except ValueError, arg:
raise Error, "Unpack entry error: %s"%arg raise Error, "Unpack entry error: %s"%arg
if verbose: if verbose:
print 'Fork %d, offset %d, length %d'%(id, offset, length) print 'Fork %d, offset %d, length %d'%(id, offset, length)
input.seek(offset) input.seek(offset)
if length == 0: if length == 0:
data = '' data = ''
else: else:
data = input.read(length) data = input.read(length)
if len(data) != length: if len(data) != length:
raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) raise Error, 'Short read: expected %d bytes got %d'%(length, len(data))
if id == AS_DATAFORK: if id == AS_DATAFORK:
if verbose: if verbose:
print ' (data fork)' print ' (data fork)'
if not resonly: if not resonly:
didwork = 1 didwork = 1
fp = open(output, 'wb') fp = open(output, 'wb')
fp.write(data) fp.write(data)
fp.close() fp.close()
elif id == AS_RESOURCEFORK: elif id == AS_RESOURCEFORK:
didwork = 1 didwork = 1
if verbose: if verbose:
print ' (resource fork)' print ' (resource fork)'
if resonly: if resonly:
fp = open(output, 'wb') fp = open(output, 'wb')
else: else:
fp = MacOS.openrf(output, 'wb') fp = MacOS.openrf(output, 'wb')
fp.write(data) fp.write(data)
fp.close() fp.close()
elif id in AS_IGNORE: elif id in AS_IGNORE:
if verbose: if verbose:
print ' (ignored)' print ' (ignored)'
else: else:
raise Error, 'Unknown fork type %d'%id raise Error, 'Unknown fork type %d'%id
if not didwork: if not didwork:
raise Error, 'No useful forks found' raise Error, 'No useful forks found'
def _test(): def _test():
if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
print 'Usage: applesingle.py [-r] applesinglefile decodedfile' print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
sys.exit(1) sys.exit(1)
if sys.argv[1] == '-r': if sys.argv[1] == '-r':
resonly = 1 resonly = 1
del sys.argv[1] del sys.argv[1]
else: else:
resonly = 0 resonly = 0
decode(sys.argv[1], sys.argv[2], resonly=resonly) decode(sys.argv[1], sys.argv[2], resonly=resonly)
if __name__ == '__main__': if __name__ == '__main__':
_test() _test()
\ No newline at end of file \ No newline at end of file
...@@ -14,13 +14,13 @@ import marshal ...@@ -14,13 +14,13 @@ import marshal
# directory. # directory.
# #
if not sys.argv or sys.argv[0][:1] == '-': if not sys.argv or sys.argv[0][:1] == '-':
# Insert our (guessed) name. # Insert our (guessed) name.
_dir = os.path.split(sys.executable)[0] # removes "python" _dir = os.path.split(sys.executable)[0] # removes "python"
_dir = os.path.split(_dir)[0] # Removes "MacOS" _dir = os.path.split(_dir)[0] # Removes "MacOS"
_dir = os.path.join(_dir, 'Resources') _dir = os.path.join(_dir, 'Resources')
sys.argv.insert(0, '__rawmain__') sys.argv.insert(0, '__rawmain__')
else: else:
_dir = os.path.split(sys.argv[0])[0] _dir = os.path.split(sys.argv[0])[0]
# #
# Add the Resources directory to the path. This is where files installed # Add the Resources directory to the path. This is where files installed
# by BuildApplet.py with the --extra option show up, and if those files are # by BuildApplet.py with the --extra option show up, and if those files are
...@@ -36,28 +36,28 @@ argvemulator.ArgvCollector().mainloop() ...@@ -36,28 +36,28 @@ argvemulator.ArgvCollector().mainloop()
# #
__file__ = os.path.join(_dir, '__main__.py') __file__ = os.path.join(_dir, '__main__.py')
if os.path.exists(__file__): if os.path.exists(__file__):
# #
# Setup something resembling a normal environment and go. # Setup something resembling a normal environment and go.
# #
sys.argv[0] = __file__ sys.argv[0] = __file__
del argvemulator, os, sys, _dir del argvemulator, os, sys, _dir
execfile(__file__) execfile(__file__)
else: else:
__file__ = os.path.join(_dir, '__main__.pyc') __file__ = os.path.join(_dir, '__main__.pyc')
if os.path.exists(__file__): if os.path.exists(__file__):
# #
# If we have only a .pyc file we read the code object from that # If we have only a .pyc file we read the code object from that
# #
sys.argv[0] = __file__ sys.argv[0] = __file__
_fp = open(__file__, 'rb') _fp = open(__file__, 'rb')
_fp.read(8) _fp.read(8)
__code__ = marshal.load(_fp) __code__ = marshal.load(_fp)
# #
# Again, we create an almost-normal environment (only __code__ is # Again, we create an almost-normal environment (only __code__ is
# funny) and go. # funny) and go.
# #
del argvemulator, os, sys, marshal, _dir, _fp del argvemulator, os, sys, marshal, _dir, _fp
exec __code__ exec __code__
else: else:
sys.stderr.write("%s: neither __main__.py nor __main__.pyc found\n"%sys.argv[0]) sys.stderr.write("%s: neither __main__.py nor __main__.pyc found\n"%sys.argv[0])
sys.exit(1) sys.exit(1)
...@@ -6,12 +6,12 @@ ...@@ -6,12 +6,12 @@
import os import os
import sys import sys
for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]: for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]:
realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])),
"Resources", name) "Resources", name)
if os.path.exists(realmain): if os.path.exists(realmain):
break break
else: else:
sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0]) sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0])
sys.exit(1) sys.exit(1)
sys.argv.insert(1, realmain) sys.argv.insert(1, realmain)
os.execve(sys.executable, sys.argv, os.environ) os.execve(sys.executable, sys.argv, os.environ)
...@@ -12,12 +12,12 @@ Error = "bgenlocations.Error" ...@@ -12,12 +12,12 @@ Error = "bgenlocations.Error"
# Where bgen is. For unix-Python bgen isn't installed, so you have to refer to # Where bgen is. For unix-Python bgen isn't installed, so you have to refer to
# the source tree here. # the source tree here.
if sys.platform == 'mac': if sys.platform == 'mac':
# For MacPython we know where it is # For MacPython we know where it is
def _pardir(p): return os.path.split(p)[0] def _pardir(p): return os.path.split(p)[0]
BGENDIR=os.path.join(sys.prefix, "Tools", "bgen", "bgen") BGENDIR=os.path.join(sys.prefix, "Tools", "bgen", "bgen")
else: else:
# for unix-Python we don't know, please set it yourself. # for unix-Python we don't know, please set it yourself.
BGENDIR="/Users/jack/src/python/Tools/bgen/bgen" BGENDIR="/Users/jack/src/python/Tools/bgen/bgen"
# #
# Where to find the Universal Header include files. If you have CodeWarrior # Where to find the Universal Header include files. If you have CodeWarrior
...@@ -26,9 +26,9 @@ else: ...@@ -26,9 +26,9 @@ else:
# end of lines, so don't worry about that. # end of lines, so don't worry about that.
# #
if sys.platform == 'mac': if sys.platform == 'mac':
_MWERKSDIR="Sap:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" _MWERKSDIR="Sap:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior"
else: else:
_MWERKSDIR="/Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" _MWERKSDIR="/Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/"
INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes") INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes")
# #
...@@ -37,25 +37,25 @@ INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", ...@@ -37,25 +37,25 @@ INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces",
# your source directory, not your installed directory. # your source directory, not your installed directory.
# #
if sys.platform == 'mac': if sys.platform == 'mac':
TOOLBOXDIR=os.path.join(sys.prefix, "Lib", "plat-mac", "Carbon") TOOLBOXDIR=os.path.join(sys.prefix, "Lib", "plat-mac", "Carbon")
else: else:
TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon" TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
# Creator for C files: # Creator for C files:
CREATOR="CWIE" CREATOR="CWIE"
if not os.path.exists(BGENDIR): if not os.path.exists(BGENDIR):
raise Error, "Please fix bgenlocations.py, BGENDIR does not exist: %s" % BGENDIR raise Error, "Please fix bgenlocations.py, BGENDIR does not exist: %s" % BGENDIR
if not os.path.exists(INCLUDEDIR): if not os.path.exists(INCLUDEDIR):
raise Error, "Please fix bgenlocations.py, INCLUDEDIR does not exist: %s" % INCLUDEDIR raise Error, "Please fix bgenlocations.py, INCLUDEDIR does not exist: %s" % INCLUDEDIR
if not os.path.exists(TOOLBOXDIR): if not os.path.exists(TOOLBOXDIR):
raise Error, "Please fix bgenlocations.py, TOOLBOXDIR does not exist: %s" % TOOLBOXDIR raise Error, "Please fix bgenlocations.py, TOOLBOXDIR does not exist: %s" % TOOLBOXDIR
# Sigh, due to the way these are used make sure they end with : or /. # Sigh, due to the way these are used make sure they end with : or /.
if BGENDIR[-1] != os.sep: if BGENDIR[-1] != os.sep:
BGENDIR = BGENDIR + os.sep BGENDIR = BGENDIR + os.sep
if INCLUDEDIR[-1] != os.sep: if INCLUDEDIR[-1] != os.sep:
INCLUDEDIR = INCLUDEDIR + os.sep INCLUDEDIR = INCLUDEDIR + os.sep
if TOOLBOXDIR[-1] != os.sep: if TOOLBOXDIR[-1] != os.sep:
TOOLBOXDIR = TOOLBOXDIR + os.sep TOOLBOXDIR = TOOLBOXDIR + os.sep
This diff is collapsed.
This diff is collapsed.
...@@ -18,167 +18,167 @@ error = "cfm.error" ...@@ -18,167 +18,167 @@ error = "cfm.error"
BUFSIZE = 0x80000 BUFSIZE = 0x80000
def mergecfmfiles(srclist, dst, architecture = 'fat'): def mergecfmfiles(srclist, dst, architecture = 'fat'):
"""Merge all files in srclist into a new file dst. """Merge all files in srclist into a new file dst.
If architecture is given, only code fragments of that type will be used: If architecture is given, only code fragments of that type will be used:
"pwpc" for PPC, "m68k" for cfm68k. This does not work for "classic" "pwpc" for PPC, "m68k" for cfm68k. This does not work for "classic"
68k code, since it does not use code fragments to begin with. 68k code, since it does not use code fragments to begin with.
If architecture is None, all fragments will be used, enabling FAT binaries. If architecture is None, all fragments will be used, enabling FAT binaries.
""" """
srclist = list(srclist) srclist = list(srclist)
for i in range(len(srclist)): for i in range(len(srclist)):
srclist[i] = Carbon.File.pathname(srclist[i]) srclist[i] = Carbon.File.pathname(srclist[i])
dst = Carbon.File.pathname(dst) dst = Carbon.File.pathname(dst)
dstfile = open(dst, "wb") dstfile = open(dst, "wb")
rf = Res.FSpOpenResFile(dst, 3) rf = Res.FSpOpenResFile(dst, 3)
try: try:
dstcfrg = CfrgResource() dstcfrg = CfrgResource()
for src in srclist: for src in srclist:
srccfrg = CfrgResource(src) srccfrg = CfrgResource(src)
for frag in srccfrg.fragments: for frag in srccfrg.fragments:
if frag.architecture == 'pwpc' and architecture == 'm68k': if frag.architecture == 'pwpc' and architecture == 'm68k':
continue continue
if frag.architecture == 'm68k' and architecture == 'pwpc': if frag.architecture == 'm68k' and architecture == 'pwpc':
continue continue
dstcfrg.append(frag) dstcfrg.append(frag)
frag.copydata(dstfile) frag.copydata(dstfile)
cfrgres = Res.Resource(dstcfrg.build()) cfrgres = Res.Resource(dstcfrg.build())
Res.UseResFile(rf) Res.UseResFile(rf)
cfrgres.AddResource('cfrg', 0, "") cfrgres.AddResource('cfrg', 0, "")
finally: finally:
dstfile.close() dstfile.close()
rf = Res.CloseResFile(rf) rf = Res.CloseResFile(rf)
class CfrgResource: class CfrgResource:
def __init__(self, path = None): def __init__(self, path = None):
self.version = 1 self.version = 1
self.fragments = [] self.fragments = []
self.path = path self.path = path
if path is not None and os.path.exists(path): if path is not None and os.path.exists(path):
currentresref = Res.CurResFile() currentresref = Res.CurResFile()
resref = Res.FSpOpenResFile(path, 1) resref = Res.FSpOpenResFile(path, 1)
Res.UseResFile(resref) Res.UseResFile(resref)
try: try:
try: try:
data = Res.Get1Resource('cfrg', 0).data data = Res.Get1Resource('cfrg', 0).data
except Res.Error: except Res.Error:
raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback
finally: finally:
Res.CloseResFile(resref) Res.CloseResFile(resref)
Res.UseResFile(currentresref) Res.UseResFile(currentresref)
self.parse(data) self.parse(data)
if self.version <> 1: if self.version <> 1:
raise error, "unknown 'cfrg' resource format" raise error, "unknown 'cfrg' resource format"
def parse(self, data): def parse(self, data):
(res1, res2, self.version, (res1, res2, self.version,
res3, res4, res5, res6, res3, res4, res5, res6,
self.memberCount) = struct.unpack("8l", data[:32]) self.memberCount) = struct.unpack("8l", data[:32])
data = data[32:] data = data[32:]
while data: while data:
frag = FragmentDescriptor(self.path, data) frag = FragmentDescriptor(self.path, data)
data = data[frag.memberSize:] data = data[frag.memberSize:]
self.fragments.append(frag) self.fragments.append(frag)
def build(self): def build(self):
self.memberCount = len(self.fragments) self.memberCount = len(self.fragments)
data = struct.pack("8l", 0, 0, self.version, 0, 0, 0, 0, self.memberCount) data = struct.pack("8l", 0, 0, self.version, 0, 0, 0, 0, self.memberCount)
for frag in self.fragments: for frag in self.fragments:
data = data + frag.build() data = data + frag.build()
return data return data
def append(self, frag): def append(self, frag):
self.fragments.append(frag) self.fragments.append(frag)
class FragmentDescriptor: class FragmentDescriptor:
def __init__(self, path, data = None): def __init__(self, path, data = None):
self.path = path self.path = path
if data is not None: if data is not None:
self.parse(data) self.parse(data)
def parse(self, data): def parse(self, data):
self.architecture = data[:4] self.architecture = data[:4]
( self.updatelevel, ( self.updatelevel,
self.currentVersion, self.currentVersion,
self.oldDefVersion, self.oldDefVersion,
self.stacksize, self.stacksize,
self.applibdir, self.applibdir,
self.fragtype, self.fragtype,
self.where, self.where,
self.offset, self.offset,
self.length, self.length,
self.res1, self.res2, self.res1, self.res2,
self.memberSize,) = struct.unpack("4lhBB4lh", data[4:42]) self.memberSize,) = struct.unpack("4lhBB4lh", data[4:42])
pname = data[42:self.memberSize] pname = data[42:self.memberSize]
self.name = pname[1:1+ord(pname[0])] self.name = pname[1:1+ord(pname[0])]
def build(self): def build(self):
data = self.architecture data = self.architecture
data = data + struct.pack("4lhBB4l", data = data + struct.pack("4lhBB4l",
self.updatelevel, self.updatelevel,
self.currentVersion, self.currentVersion,
self.oldDefVersion, self.oldDefVersion,
self.stacksize, self.stacksize,
self.applibdir, self.applibdir,
self.fragtype, self.fragtype,
self.where, self.where,
self.offset, self.offset,
self.length, self.length,
self.res1, self.res2) self.res1, self.res2)
self.memberSize = len(data) + 2 + 1 + len(self.name) self.memberSize = len(data) + 2 + 1 + len(self.name)
# pad to 4 byte boundaries # pad to 4 byte boundaries
if self.memberSize % 4: if self.memberSize % 4:
self.memberSize = self.memberSize + 4 - (self.memberSize % 4) self.memberSize = self.memberSize + 4 - (self.memberSize % 4)
data = data + struct.pack("hb", self.memberSize, len(self.name)) data = data + struct.pack("hb", self.memberSize, len(self.name))
data = data + self.name data = data + self.name
data = data + '\000' * (self.memberSize - len(data)) data = data + '\000' * (self.memberSize - len(data))
return data return data
def getfragment(self): def getfragment(self):
if self.where <> 1: if self.where <> 1:
raise error, "can't read fragment, unsupported location" raise error, "can't read fragment, unsupported location"
f = open(self.path, "rb") f = open(self.path, "rb")
f.seek(self.offset) f.seek(self.offset)
if self.length: if self.length:
frag = f.read(self.length) frag = f.read(self.length)
else: else:
frag = f.read() frag = f.read()
f.close() f.close()
return frag return frag
def copydata(self, outfile): def copydata(self, outfile):
if self.where <> 1: if self.where <> 1:
raise error, "can't read fragment, unsupported location" raise error, "can't read fragment, unsupported location"
infile = open(self.path, "rb") infile = open(self.path, "rb")
if self.length == 0: if self.length == 0:
infile.seek(0, 2) infile.seek(0, 2)
self.length = infile.tell() self.length = infile.tell()
# Position input file and record new offset from output file # Position input file and record new offset from output file
infile.seek(self.offset) infile.seek(self.offset)
# pad to 16 byte boundaries # pad to 16 byte boundaries
offset = outfile.tell() offset = outfile.tell()
if offset % 16: if offset % 16:
offset = offset + 16 - (offset % 16) offset = offset + 16 - (offset % 16)
outfile.seek(offset) outfile.seek(offset)
self.offset = offset self.offset = offset
l = self.length l = self.length
while l: while l:
if l > BUFSIZE: if l > BUFSIZE:
outfile.write(infile.read(BUFSIZE)) outfile.write(infile.read(BUFSIZE))
l = l - BUFSIZE l = l - BUFSIZE
else: else:
outfile.write(infile.read(l)) outfile.write(infile.read(l))
l = 0 l = 0
infile.close() infile.close()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -28,25 +28,25 @@ smAllScripts = -3 ...@@ -28,25 +28,25 @@ smAllScripts = -3
# Find the epoch conversion for file dates in a way that works on OS9 and OSX # Find the epoch conversion for file dates in a way that works on OS9 and OSX
import time import time
if time.gmtime(0)[0] == 1970: if time.gmtime(0)[0] == 1970:
_EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000L _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000L
def _utc2time(utc): def _utc2time(utc):
t = utc[1] + _EPOCHCONVERT t = utc[1] + _EPOCHCONVERT
return int(t) return int(t)
def _time2utc(t): def _time2utc(t):
t = int(t) - _EPOCHCONVERT t = int(t) - _EPOCHCONVERT
if t < -0x7fffffff: if t < -0x7fffffff:
t = t + 0x10000000L t = t + 0x10000000L
return (0, int(t), 0) return (0, int(t), 0)
else: else:
def _utc2time(utc): def _utc2time(utc):
t = utc[1] t = utc[1]
if t < 0: if t < 0:
t = t + 0x100000000L t = t + 0x100000000L
return t return t
def _time2utc(t): def _time2utc(t):
if t > 0x7fffffff: if t > 0x7fffffff:
t = t - 0x100000000L t = t - 0x100000000L
return (0, int(t), 0) return (0, int(t), 0)
# The old name of the error object: # The old name of the error object:
error = Carbon.File.Error error = Carbon.File.Error
...@@ -56,60 +56,60 @@ error = Carbon.File.Error ...@@ -56,60 +56,60 @@ error = Carbon.File.Error
# of the method names are subtly different. # of the method names are subtly different.
# #
class FSSpec(Carbon.File.FSSpec): class FSSpec(Carbon.File.FSSpec):
def as_fsref(self): def as_fsref(self):
return FSRef(self) return FSRef(self)
def NewAlias(self, src=None): def NewAlias(self, src=None):
return Alias(Carbon.File.NewAlias(src, self)) return Alias(Carbon.File.NewAlias(src, self))
def GetCreatorType(self): def GetCreatorType(self):
finfo = self.FSpGetFInfo() finfo = self.FSpGetFInfo()
return finfo.Creator, finfo.Type return finfo.Creator, finfo.Type
def SetCreatorType(self, ctor, tp): def SetCreatorType(self, ctor, tp):
finfo = self.FSpGetFInfo() finfo = self.FSpGetFInfo()
finfo.Creator = ctor finfo.Creator = ctor
finfo.Type = tp finfo.Type = tp
self.FSpSetFInfo(finfo) self.FSpSetFInfo(finfo)
def GetFInfo(self): def GetFInfo(self):
return self.FSpGetFInfo() return self.FSpGetFInfo()
def SetFInfo(self, info): def SetFInfo(self, info):
return self.FSpSetFInfo(info) return self.FSpSetFInfo(info)
def GetDates(self): def GetDates(self):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags) catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
cdate = catinfo.createDate cdate = catinfo.createDate
mdate = catinfo.contentModDate mdate = catinfo.contentModDate
bdate = catinfo.backupDate bdate = catinfo.backupDate
return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate) return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
def SetDates(self, cdate, mdate, bdate): def SetDates(self, cdate, mdate, bdate):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo = Carbon.File.FSCatalogInfo( catinfo = Carbon.File.FSCatalogInfo(
createDate = _time2utc(cdate), createDate = _time2utc(cdate),
contentModDate = _time2utc(mdate), contentModDate = _time2utc(mdate),
backupDate = _time2utc(bdate)) backupDate = _time2utc(bdate))
FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo) FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
class FSRef(Carbon.File.FSRef): class FSRef(Carbon.File.FSRef):
def as_fsspec(self): def as_fsspec(self):
return FSSpec(self) return FSSpec(self)
class Alias(Carbon.File.Alias): class Alias(Carbon.File.Alias):
def GetInfo(self, index): def GetInfo(self, index):
return self.GetAliasInfo(index) return self.GetAliasInfo(index)
def Update(self, *args): def Update(self, *args):
pass # print "Alias.Update not yet implemented" pass # print "Alias.Update not yet implemented"
def Resolve(self, src=None): def Resolve(self, src=None):
fss, changed = self.ResolveAlias(src) fss, changed = self.ResolveAlias(src)
return FSSpec(fss), changed return FSSpec(fss), changed
from Carbon.File import FInfo from Carbon.File import FInfo
# Backward-compatible type names: # Backward-compatible type names:
...@@ -120,21 +120,21 @@ FInfoType = FInfo ...@@ -120,21 +120,21 @@ FInfoType = FInfo
# Global functions: # Global functions:
def ResolveAliasFile(fss, chain=1): def ResolveAliasFile(fss, chain=1):
fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain) fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
return FSSpec(fss), isdir, isalias return FSSpec(fss), isdir, isalias
def RawFSSpec(data): def RawFSSpec(data):
return FSSpec(rawdata=data) return FSSpec(rawdata=data)
def RawAlias(data): def RawAlias(data):
return Alias(rawdata=data) return Alias(rawdata=data)
def FindApplication(*args): def FindApplication(*args):
raise NotImplementedError, "FindApplication no longer implemented" raise NotImplementedError, "FindApplication no longer implemented"
def NewAliasMinimalFromFullPath(path): def NewAliasMinimalFromFullPath(path):
return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', '')) return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
# Another global function: # Another global function:
from Carbon.Folder import FindFolder from Carbon.Folder import FindFolder
...@@ -145,54 +145,54 @@ from Carbon.Folder import FindFolder ...@@ -145,54 +145,54 @@ from Carbon.Folder import FindFolder
_curfolder = None _curfolder = None
def StandardGetFile(*typelist): def StandardGetFile(*typelist):
"""Ask for an input file, optionally specifying 4-char file types that are """Ask for an input file, optionally specifying 4-char file types that are
allowable""" allowable"""
return PromptGetFile('', *typelist) return PromptGetFile('', *typelist)
def PromptGetFile(prompt, *typelist): def PromptGetFile(prompt, *typelist):
"""Ask for an input file giving the user a prompt message. Optionally you can """Ask for an input file giving the user a prompt message. Optionally you can
specifying 4-char file types that are allowable""" specifying 4-char file types that are allowable"""
import EasyDialogs import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen", warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
if not typelist: if not typelist:
typelist = None typelist = None
fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec, fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
typeList=typelist, defaultLocation=_handleSetFolder()) typeList=typelist, defaultLocation=_handleSetFolder())
return fss, not fss is None return fss, not fss is None
def StandardPutFile(prompt, default=None): def StandardPutFile(prompt, default=None):
"""Ask the user for an output file, with a prompt. Optionally you cn supply a """Ask the user for an output file, with a prompt. Optionally you cn supply a
default output filename""" default output filename"""
import EasyDialogs import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen", warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt, fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
savedFileName=default, defaultLocation=_handleSetFolder()) savedFileName=default, defaultLocation=_handleSetFolder())
return fss, not fss is None return fss, not fss is None
def SetFolder(folder): def SetFolder(folder):
global _curfolder global _curfolder
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen", warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
if _curfolder: if _curfolder:
rv = FSSpec(_curfolder) rv = FSSpec(_curfolder)
else: else:
rv = None rv = None
_curfolder = folder _curfolder = folder
return rv return rv
def _handleSetFolder(): def _handleSetFolder():
global _curfolder global _curfolder
rv = _curfolder rv = _curfolder
_curfolder = None _curfolder = None
return rv return rv
def GetDirectory(prompt=None): def GetDirectory(prompt=None):
"""Ask the user to select a folder. Optionally you can give a prompt.""" """Ask the user to select a folder. Optionally you can give a prompt."""
import EasyDialogs import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen", warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec, fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
defaultLocation=_handleSetFolder()) defaultLocation=_handleSetFolder())
return fss, not fss is None return fss, not fss is None
This diff is collapsed.
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