def writePlistToResource(rootObject, path, restype='plst', resid=0): """Write 'rootObject' as a plst resource to the resource fork of path. """ 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 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 resource_pathname(pathname, verbose=0): try: refno = Res.FSOpenResourceFile(pathname, u'', 1) except Res.Error as arg: if arg[0] != -199: raise else: return refno pathname = _decode(pathname, verbose=verbose) return pathname
def open_pathname(pathname, verbose=0): """Open a resource file given by pathname, possibly decoding an AppleSingle file""" try: refno = Res.FSpOpenResFile(pathname, 1) 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) refno = Res.FSOpenResourceFile(pathname, u'', 1)
def new(self, url): if self.dict.has_key(url): self.dict[url][0] = self.dict[url][0] + 1 return self.dict[url][1] fname = MMurl.urlretrieve(url)[0] image = img.reader(PIXELFORMAT, fname) data = image.read() pixmap = mac_image.mkpixmap(image.width, image.height, PIXELFORMAT, data) handle = Res.Resource(url) self.dict[url] = [1, handle, pixmap, data, image.width, image.height] return handle
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 open_pathname(pathname, verbose=0): """Open a resource file given by pathname, possibly decoding an AppleSingle file""" # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or an 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
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 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.FSOpenResourceFile(pathname, u'', 1) except Res.Error as arg: if arg[0] != -199: raise else: return refno pathname = _decode(pathname, verbose=verbose) return pathname
def set(self, fontsettings): font, style, size, color = fontsettings if type(font) <> types.StringType: from Carbon import Res res = Res.GetResource('FOND', font) font = res.GetResInfo()[2] self.w.fontname.set(font) self.w.sizeedit.set(str(size)) if style: for i in range(1, len(_stylenames)): self.w[i].set(style & 0x01) style = style >> 1 else: self.w[0].set(1)
def copyres(input, output, skiptypes, skipowner, progress=None): ctor = None alltypes = [] Res.UseResFile(input) ntypes = Res.Count1Types() progress_type_inc = 50 / ntypes for itype in range(1, 1 + ntypes): type = Res.Get1IndType(itype) if type in skiptypes: continue alltypes.append(type) nresources = Res.Count1Resources(type) progress_cur_inc = progress_type_inc / nresources for ires in range(1, 1 + nresources): res = Res.Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if lcname == OWNERNAME and id == 0: if skipowner: continue else: ctor = type size = res.size attrs = res.GetResAttrs() if progress: progress.label('Copy %s %d %s' % (type, id, name)) progress.inc(progress_cur_inc) res.LoadResource() res.DetachResource() Res.UseResFile(output) try: res2 = Res.Get1Resource(type, id) except MacOS.Error: res2 = None if res2: if progress: progress.label('Overwrite %s %d %s' % (type, id, name)) progress.inc(0) res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() res.SetResAttrs(attrs) Res.UseResFile(input) return (alltypes, ctor)
def set(self, text): if not self.ted: self.temptext = text else: self.ted.WEUseText(Res.Resource(text)) self.ted.WECalText() self.SetPort() viewrect, destrect = self._calctextbounds() self.ted.WESetViewRect(viewrect) self.ted.WESetDestRect(destrect) rgn = Qd.NewRgn() Qd.RectRgn(rgn, viewrect) Qd.EraseRect(viewrect) self.draw(rgn) self.updatescrollbars() self.textchanged(1)
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 listresources(): ntypes = Res.CountTypes() for itype in range(1, 1 + ntypes): type = Res.GetIndType(itype) print "Type:", ` type ` nresources = Res.CountResources(type) for i in range(1, 1 + nresources): Res.SetResLoad(0) res = Res.GetIndResource(type, i) Res.SetResLoad(1) info(res)
def list1resources(): ntypes = Res.Count1Types() for itype in range(1, 1+ntypes): type = Res.Get1IndType(itype) print "Type:", repr(type) nresources = Res.Count1Resources(type) for i in range(1, 1 + nresources): Res.SetResLoad(0) res = Res.Get1IndResource(type, i) Res.SetResLoad(1) info(res)
def open(self, path, name, data): self.path = path self.name = name r = windowbounds(400, 400) w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) self.wid = w vr = 0, 0, r[2] - r[0] - 15, r[3] - r[1] - 15 dr = (0, 0, 10240, 0) Qd.SetPort(w) Qd.TextFont(4) Qd.TextSize(9) flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ WASTEconst.weDoMonoStyled | WASTEconst.weDoUndo self.ted = waste.WENew(dr, vr, flags) self.tedtexthandle = Res.Resource(data) self.ted.WEUseText(self.tedtexthandle) self.ted.WECalText() w.DrawGrowIcon() self.scrollbars() self.changed = 0 self.do_postopen() self.do_activate(1, None)
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 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 __init__(self, url): path = MMurl.urlretrieve(url)[0] fsspec = macfs.FSSpec(path) fd = Qt.OpenMovieFile(fsspec, 0) self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0) self.movietimescale = self.movie.GetMovieTimeScale() try: self.audiotrack = self.movie.GetMovieIndTrackType( 1, QuickTime.AudioMediaCharacteristic, QuickTime.movieTrackCharacteristic) self.audiomedia = self.audiotrack.GetTrackMedia() except Qt.Error: self.audiotrack = self.audiomedia = None self.audiodescr = {} else: handle = Res.Handle('') n = self.audiomedia.GetMediaSampleDescriptionCount() self.audiomedia.GetMediaSampleDescription(1, handle) self.audiodescr = MediaDescr.SoundDescription.decode(handle.data) self.audiotimescale = self.audiomedia.GetMediaTimeScale() del handle try: self.videotrack = self.movie.GetMovieIndTrackType( 1, QuickTime.VisualMediaCharacteristic, QuickTime.movieTrackCharacteristic) self.videomedia = self.videotrack.GetTrackMedia() except Qt.Error: self.videotrack = self.videomedia = self.videotimescale = None if self.videotrack: self.videotimescale = self.videomedia.GetMediaTimeScale() x0, y0, x1, y1 = self.movie.GetMovieBox() self.videodescr = {'width': (x1 - x0), 'height': (y1 - y0)} self._initgworld() self.videocurtime = None self.audiocurtime = None
def __init__(self, path): fd = Qt.OpenMovieFile(path, 0) self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0) self.movietimescale = self.movie.GetMovieTimeScale() try: self.audiotrack = self.movie.GetMovieIndTrackType( 1, QuickTime.AudioMediaCharacteristic, QuickTime.movieTrackCharacteristic) self.audiomedia = self.audiotrack.GetTrackMedia() except Qt.Error: self.audiotrack = self.audiomedia = None self.audiodescr = {} else: handle = Res.Handle('') n = self.audiomedia.GetMediaSampleDescriptionCount() self.audiomedia.GetMediaSampleDescription(1, handle) self.audiodescr = _audiodescr(handle.data) self.audiotimescale = self.audiomedia.GetMediaTimeScale() del handle try: self.videotrack = self.movie.GetMovieIndTrackType( 1, QuickTime.VisualMediaCharacteristic, QuickTime.movieTrackCharacteristic) self.videomedia = self.videotrack.GetTrackMedia() except Qt.Error: self.videotrack = self.videomedia = self.videotimescale = None if self.videotrack: self.videotimescale = self.videomedia.GetMediaTimeScale() x0, y0, x1, y1 = self.movie.GetMovieBox() self.videodescr = {'width': x1 - x0, 'height': y1 - y0} self._initgworld() self.videocurtime = None self.audiocurtime = None return
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 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 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 need(restype, resid, filename=None, modname=None): """Open a resource file, if needed. restype and resid are required parameters, and identify the resource for which to test. If it is available we are done. If it is not available we look for a file filename (default: modname with .rsrc appended) either in the same folder as where modname was loaded from, or otherwise across sys.path. Returns the refno of the resource file opened (or None)""" if modname is None and filename is None: raise ArgumentError, "Either filename or modname argument (or both) must be given" if type(resid) is type(1): try: h = Res.GetResource(restype, resid) except Res.Error: pass else: return None else: try: h = Res.GetNamedResource(restype, resid) except Res.Error: pass else: return None # Construct a filename if we don't have one if not filename: if '.' in modname: filename = modname.split('.')[-1] + '.rsrc' else: filename = modname + '.rsrc' # Now create a list of folders to search searchdirs = [] if modname == '__main__': # If we're main we look in the current directory searchdirs = [os.curdir] if sys.modules.has_key(modname): mod = sys.modules[modname] if hasattr(mod, '__file__'): searchdirs = [os.path.dirname(mod.__file__)] searchdirs.extend(sys.path) # And look for the file for dir in searchdirs: pathname = os.path.join(dir, filename) if os.path.exists(pathname): break else: raise ResourceFileNotFoundError, filename refno = open_pathname(pathname) # And check that the resource exists now if type(resid) is type(1): h = Res.GetResource(restype, resid) else: h = Res.GetNamedResource(restype, resid) return refno
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)
import sys import macfs from Carbon import Res from Carbon import Ctl from Carbon import Dlg # Find macfreeze directory FREEZEDIR=os.path.join(sys.prefix, ":Mac:Tools:macfreeze") sys.path.append(FREEZEDIR) import macfreeze # # Resources for the dialog # RESFILE="macbuild.rsrc" h = Res.FSpOpenResFile(RESFILE, 0) DIALOG_ID=512 I_OK=1 I_CANCEL=2 I_G2PRO_FREEZE=4 I_G2PRO_BUILD=5 I_G2LITE_FREEZE=7 I_G2LITE_BUILD=8 I_PLAYER_FREEZE=10 I_PLAYER_BUILD=11 I_SMILPRO_FREEZE=13 I_SMILPRO_BUILD=14
"""browsepict - Display all "cicn" resources found"""
# A minimal text editor.