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

Detabbed.

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