def copyres(input, output, *args, **kwargs): openedin = openedout = 0 if type(input) == types.StringType: input = Res.FSpOpenResFile(input, 1) openedin = 1 if type(output) == types.StringType: output = Res.FSpOpenResFile(output, 3) openedout = 1 try: apply(buildtools.copyres, (input, output) + args, kwargs) finally: if openedin: Res.CloseResFile(input) if openedout: Res.CloseResFile(output)
def mergecfmfiles(srclist, dst, architecture='fat'): 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)
def close(self): if self.resref <> None: try: Res.CloseResFile(self.resref) except Res.Error: pass self.resref = None
def menu_save(self): if not self.path: self.menu_save_as() return # Will call us recursively # # First save data # dhandle = self.ted.WEGetText() data = dhandle.data fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line fp.write(data) if data[-1] <> '\r': fp.write('\r') fp.close() # # Now save style and soup # oldresfile = Res.CurResFile() try: rf = Res.FSpOpenResFile(self.path, 3) except Res.Error: Res.FSpCreateResFile(self.path, '????', 'TEXT', macfs.smAllScripts) rf = Res.FSpOpenResFile(self.path, 3) styles = Res.Resource('') soup = Res.Resource('') self.ted.WECopyRange(0, 0x3fffffff, None, styles, soup) styles.AddResource('styl', 128, '') soup.AddResource('SOUP', 128, '') Res.CloseResFile(rf) Res.UseResFile(oldresfile) self.ted.WEResetModCount()
def readLWFN(path, onlyHeader=0): """reads an LWFN font file, returns raw data""" resRef = Res.FSOpenResFile(path, 1) # read-only try: Res.UseResFile(resRef) n = Res.Count1Resources('POST') data = [] for i in range(501, 501 + n): res = Res.Get1Resource('POST', i) code = ord(res.data[0]) if ord(res.data[1]) <> 0: raise T1Error, 'corrupt LWFN file' if code in [1, 2]: if onlyHeader and code == 2: break data.append(res.data[2:]) elif code in [3, 5]: break elif code == 4: f = open(path, "rb") data.append(f.read()) f.close() elif code == 0: pass # comment, ignore else: raise T1Error, 'bad chunk code: ' + ` code ` finally: Res.CloseResFile(resRef) data = string.join(data, '') assertType1(data) return data
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)
def mkalias(src, dst, relative=None): """Create a finder alias""" srcfsr = File.FSRef(src) # The next line will fail under unix-Python if the destination # doesn't exist yet. We should change this code to be fsref-based. dstdir, dstname = os.path.split(dst) if not dstdir: dstdir = os.curdir dstdirfsr = File.FSRef(dstdir) if relative: relativefsr = File.FSRef(relative) # ik mag er geen None in stoppen :-( alias = File.FSNewAlias(relativefsr, srcfsr) else: alias = srcfsr.FSNewAliasMinimal() dstfsr, dstfss = Res.FSCreateResourceFile(dstdirfsr, unicode(dstname), File.FSGetResourceForkName()) h = Res.FSOpenResourceFile(dstfsr, File.FSGetResourceForkName(), 3) resource = Res.Resource(alias.data) resource.AddResource('alis', 0, '') Res.CloseResFile(h) dstfinfo = dstfss.FSpGetFInfo() dstfinfo.Flags = dstfinfo.Flags | 0x8000 # Alias flag dstfss.FSpSetFInfo(dstfinfo)
def getSFNTResIndices(path): """Determine whether a file has a resource fork or not.""" try: resref = MyOpenResFile(path) except Res.Error: return [] Res.UseResFile(resref) numSFNTs = Res.Count1Resources('sfnt') Res.CloseResFile(resref) return list(range(1, numSFNTs + 1))
def __init__(self, path, res_name_or_index): resref = MyOpenResFile(path) Res.UseResFile(resref) if isinstance(res_name_or_index, basestring): res = Res.Get1NamedResource('sfnt', res_name_or_index) else: res = Res.Get1IndResource('sfnt', res_name_or_index) self.file = StringIO(res.data) Res.CloseResFile(resref) self.name = path
def __init__(self, path, res_name_or_index): resref = MyOpenResFile(path) Res.UseResFile(resref) if type(res_name_or_index) == type(""): res = Res.Get1NamedResource('sfnt', res_name_or_index) else: res = Res.Get1IndResource('sfnt', res_name_or_index) self.file = cStringIO.StringIO(res.data) Res.CloseResFile(resref) self.name = path
def readPlistFromResource(path, restype='plst', resid=0): warnings.warnpy3k('In 3.x, readPlistFromResource is removed.', stacklevel=2) from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdPerm from Carbon import Res fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm) Res.UseResFile(resNum) plistData = Res.Get1Resource(restype, resid).data Res.CloseResFile(resNum) return readPlistFromString(plistData)
def readPlistFromResource(path, restype='plst', resid=0): """Read plst resource from the resource fork of path. """ from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdPerm from Carbon import Res fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm) Res.UseResFile(resNum) plistData = Res.Get1Resource(restype, resid).data Res.CloseResFile(resNum) return readPlistFromString(plistData)
def writeestr(dst, edict): """Create Estr resource file given a dictionary of errors.""" os.unlink(dst.as_pathname()) Res.FSpCreateResFile(dst, 'RSED', 'rsrc', smAllScripts) output = Res.FSpOpenResFile(dst, WRITE) Res.UseResFile(output) for num in edict.keys(): res = Res.Resource(Pstring(edict[num][0])) res.AddResource('Estr', num, '') res.WriteResource() Res.CloseResFile(output)
def readwindowsettings(self): try: resref = Res.FSpOpenResFile(self.path, 1) except Res.Error: return try: Res.UseResFile(resref) data = Res.Get1Resource('PyWS', 128) self.settings = marshal.loads(data.data) except: pass Res.CloseResFile(resref)
def dataFromFile(pathOrFSSpec, nameOrID="", resType='NFNT'): from Carbon import Res resref = Res.FSOpenResFile(pathOrFSSpec, 1) # readonly try: Res.UseResFile(resref) if not nameOrID: # just take the first in the file res = Res.Get1IndResource(resType, 1) elif type(nameOrID) == types.IntType: res = Res.Get1Resource(resType, nameOrID) else: res = Res.Get1NamedResource(resType, nameOrID) theID, theType, name = res.GetResInfo() data = res.data finally: Res.CloseResFile(resref) return data
def writePlistToResource(rootObject, path, restype='plst', resid=0): warnings.warnpy3k('In 3.x, writePlistToResource is removed.', stacklevel=2) from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdWrPerm from Carbon import Res plistData = writePlistToString(rootObject) fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm) Res.UseResFile(resNum) try: Res.Get1Resource(restype, resid).RemoveResource() except Res.Error: pass res = Res.Resource(plistData) res.AddResource(restype, resid, '') res.WriteResource() Res.CloseResFile(resNum)
def writePlistToResource(rootObject, path, restype='plst', resid=0): """Write 'rootObject' as a plst resource to the resource fork of path. """ from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdWrPerm from Carbon import Res plistData = writePlistToString(rootObject) fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm) Res.UseResFile(resNum) try: Res.Get1Resource(restype, resid).RemoveResource() except Res.Error: pass res = Res.Resource(plistData) res.AddResource(restype, resid, '') res.WriteResource() Res.CloseResFile(resNum)
def writewindowsettings(self): try: resref = Res.FSpOpenResFile(self.path, 3) except Res.Error: Res.FSpCreateResFile(self.path, self._creator, 'TEXT', smAllScripts) resref = Res.FSpOpenResFile(self.path, 3) try: data = Res.Resource(marshal.dumps(self.settings)) Res.UseResFile(resref) try: temp = Res.Get1Resource('PyWS', 128) temp.RemoveResource() except Res.Error: pass data.AddResource('PyWS', 128, "window settings") finally: Res.UpdateResFile(resref) Res.CloseResFile(resref)
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 mkalias(src, dst, relative=None): srcfsr = File.FSRef(src) dstdir, dstname = os.path.split(dst) if not dstdir: dstdir = os.curdir dstdirfsr = File.FSRef(dstdir) if relative: relativefsr = File.FSRef(relative) alias = File.FSNewAlias(relativefsr, srcfsr) else: alias = srcfsr.FSNewAliasMinimal() dstfsr, dstfss = Res.FSCreateResourceFile(dstdirfsr, unicode(dstname), File.FSGetResourceForkName()) h = Res.FSOpenResourceFile(dstfsr, File.FSGetResourceForkName(), 3) resource = Res.Resource(alias.data) resource.AddResource('alis', 0, '') Res.CloseResFile(h) dstfinfo = dstfss.FSpGetFInfo() dstfinfo.Flags = dstfinfo.Flags | 32768 dstfss.FSpSetFInfo(dstfinfo)
def writeLWFN(path, data): Res.FSpCreateResFile(path, "just", "LWFN", 0) resRef = Res.FSpOpenResFile(path, 2) # write-only try: Res.UseResFile(resRef) resID = 501 chunks = findEncryptedChunks(data) for isEncrypted, chunk in chunks: if isEncrypted: code = 2 else: code = 1 while chunk: res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2]) res.AddResource('POST', resID, '') chunk = chunk[LWFNCHUNKSIZE - 2:] resID = resID + 1 res = Res.Resource(chr(5) + '\0') res.AddResource('POST', resID, '') finally: Res.CloseResFile(resRef)
def getstylesoup(self, pathname): if not pathname: return None, None oldrf = Res.CurResFile() try: rf = Res.FSpOpenResFile(self.path, 1) except Res.Error: return None, None try: hstyle = Res.Get1Resource('styl', 128) hstyle.DetachResource() except Res.Error: hstyle = None try: hsoup = Res.Get1Resource('SOUP', 128) hsoup.DetachResource() except Res.Error: hsoup = None Res.CloseResFile(rf) Res.UseResFile(oldrf) return hstyle, hsoup
def close(self): if self.closed: return Res.UseResFile(self.resref) try: res = Res.Get1NamedResource('sfnt', self.fullname) except Res.Error: pass else: res.RemoveResource() res = Res.Resource(self.file.getvalue()) if self.res_id is None: self.res_id = Res.Unique1ID('sfnt') res.AddResource('sfnt', self.res_id, self.fullname) res.ChangedResource() self.createFond() del self.ttFont Res.CloseResFile(self.resref) self.file.close() self.closed = 1
def resource_pathname(pathname, verbose=0): """Return the pathname for a resource file (either DF or RF based). If the pathname given already refers to such a file simply return it, otherwise first decode it.""" try: refno = Res.FSpOpenResFile(pathname, 1) Res.CloseResFile(refno) except Res.Error, arg: if arg[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) except Res.Error, arg: if arg[0] != -199: # -199 is "bad resource map" raise else: return refno # Finally try decoding an AppleSingle file pathname = _decode(pathname, verbose=verbose)
def generate(output, module_dict, debug=0, preload=1): fsid = py_resource.create(output) for name, module in module_dict.items(): mtype = module.gettype() if mtype not in ['module', 'package']: continue location = module.__file__ 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=preload, ispackage=mtype == 'package') if debug > 0: print 'PYC resource %5d\t%s\t%s' % (id, name, location) Res.CloseResFile(fsid)
def writeLWFN(path, data): named, namef = os.path.split(self.name) Res.FSCreateResourceFile(named, namef, u'') MacOS.SetCreatorAndType(path, "just", "LWFN") resRef = Res.FSOpenResourceFile(path, u'rsrc', 2) # write-only try: Res.UseResFile(resRef) resID = 501 chunks = findEncryptedChunks(data) for isEncrypted, chunk in chunks: if isEncrypted: code = 2 else: code = 1 while chunk: res = Res.Resource( chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2]) res.AddResource('POST', resID, '') chunk = chunk[LWFNCHUNKSIZE - 2:] resID = resID + 1 res = Res.Resource(chr(5) + '\0') res.AddResource('POST', resID, '') finally: Res.CloseResFile(resRef)
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[], filename=None, destroot=""): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others, filename, destroot) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + [ 'BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#' ] if not copy_codefragment: skiptypes.append('cfrg') ## skipowner = (ownertype <> None) # Copy the resources from the template input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) ## if ownertype == None: ## raise BuildError, "No owner resource found in either resource file or template" # Make sure we're manipulating the output resource file now Res.UseResFile(output) if ownertype == None: # No owner resource in the template. We have skipped the # Python owner resource, so we have to add our own. The relevant # bundle stuff is already included in the interpret/applet template. newres = Res.Resource('\0') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, "Owner resource") ownertype = DEFAULT_APPLET_CREATOR if code: # Delete any existing 'PYC ' resource named __main__ try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass # Create the raw data for the resource from the code object if progress: progress.label("Write PYC resource...") progress.set(120) data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 0x04 # set preload res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() # Close the output file Res.CloseResFile(output) # Now set the creator, type and bundle bit of the destination. # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited dest_fss.FSpSetFInfo(dest_finfo) macostools.touched(destname) if progress: progress.label("Done.") progress.inc(0)
# # Create attrdefs resource file # import os import sys import string import macfs from Carbon import Res import py_resource # For now: progdir = os.path.split(sys.argv[0])[0] CMIFDIR = os.path.split(progdir)[0] ATTRDEFPATH = CMIFDIR + ':lib:Attrdefs.atc' fp = open(ATTRDEFPATH, 'rb') data = fp.read() fp.close() fss, ok = macfs.StandardPutFile('Attrdef resource output file:') if not ok: sys.exit(0) fsid = py_resource.create(fss.as_pathname(), creator='RSED') py_resource.writemodule('Attrdefs', 512, data, 'CMat') Res.CloseResFile(fsid) print 'Wrote', ATTRDEFPATH, 'to', fss.as_pathname() sys.exit(1)
"""macgen_bin - Generate application from shared libraries"""
# A minimal text editor.