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 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 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 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(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)
"""codefragments.py -- wrapper to modify code fragments."""
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) else: if others: raise BuildError, 'Extra files only allowed for MachoPython applets' template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() 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 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) typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): 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) 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') input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) Res.UseResFile(output) if ownertype is None: newres = Res.Resource('\x00') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, 'Owner resource') ownertype = DEFAULT_APPLET_CREATOR if code: try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass if progress: progress.label('Write PYC resource...') progress.set(120) data = marshal.dumps(code) del code data = MAGIC + '\x00\x00\x00\x00' + data id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 4 res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() Res.CloseResFile(output) 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) return
def generate(input, output, module_dict=None, architecture='fat', debug=0): # try to remove old file try: os.remove(output) except: pass if module_dict is None: import macmodulefinder print "Searching for modules..." module_dict, missing = macmodulefinder.process(input, [], [], 1) if missing: import EasyDialogs missing.sort() answer = EasyDialogs.AskYesNoCancel( "Some modules could not be found; continue anyway?\n(%s)" % string.join(missing, ", ")) if answer <> 1: sys.exit(0) applettemplatepath = buildtools.findtemplate() corepath = findpythoncore() dynamicmodules, dynamicfiles, extraresfiles = findfragments( module_dict, architecture) print 'Adding "__main__"' buildtools.process(applettemplatepath, input, output, 0) outputref = Res.FSpOpenResFile(output, 3) try: Res.UseResFile(outputref) print "Adding Python modules" addpythonmodules(module_dict) print "Adding PythonCore resources" copyres(corepath, outputref, ['cfrg', 'Popt', 'GU\267I'], 1) print "Adding resources from shared libraries" for ppcpath, cfm68kpath in extraresfiles: if os.path.exists(ppcpath): copyres(ppcpath, outputref, ['cfrg'], 1) elif os.path.exists(cfm68kpath): copyres(cfm68kpath, outputref, ['cfrg'], 1) print "Fixing sys.path prefs" Res.UseResFile(outputref) try: res = Res.Get1Resource('STR#', 228) # from PythonCore except Res.Error: pass else: res.RemoveResource() # setting pref file name to empty string res = Res.Get1NamedResource('STR ', "PythonPreferenceFileName") res.data = Pstring("") res.ChangedResource() syspathpref = "$(APPLICATION)" res = Res.Resource("\000\001" + Pstring(syspathpref)) res.AddResource("STR#", 229, "sys.path preference") print "Creating 'PYD ' resources" for modname, (ppcfrag, cfm68kfrag) in dynamicmodules.items(): res = Res.Resource(Pstring(ppcfrag) + Pstring(cfm68kfrag)) id = 0 while id < 128: id = Res.Unique1ID('PYD ') res.AddResource('PYD ', id, modname) finally: Res.CloseResFile(outputref) print "Merging code fragments" cfmfile.mergecfmfiles([applettemplatepath, corepath] + dynamicfiles.keys(), output, architecture) print "done!"
print 'Test cdll_N_bb' rv = cdll_N_bb(-100) if rv == -100: print 'ok.' else: print 'Failed, returned', rv print 'Test cdll_N_hh' rv = cdll_N_hh(-100) if rv == -100: print 'ok.' else: print 'Failed, returned', rv print 'Test cdll_N_ll' rv = cdll_N_ll(-100) if rv == -100: print 'ok.' else: print 'Failed, returned', rv print 'Test cdll_N_sH' h = Res.Resource('xyz') rv = cdll_N_sH('new data', h) if rv == None and h.data == 'new data': print 'ok.' else: print 'Failed, rv is', rv, 'and handle data is', `rv.data` sys.exit(1)
"""Test icglue module by printing all preferences. Note that the ic module, not the icglue module, is what you should normally use.""" import icglue from Carbon import Res ici = icglue.ICStart('Pyth') #ici.ICFindConfigFile() h = Res.Resource("") ici.ICBegin(1) numprefs = ici.ICCountPref() print "Number of preferences:", numprefs for i in range(1, numprefs+1): key = ici.ICGetIndPref(i) print "Key: ", key h.data = "" attrs = ici.ICFindPrefHandle(key, h) print "Attr: ", attrs print "Data: ", `h.data[:64]` ici.ICEnd() del ici import sys sys.exit(1)
"""Parse sys/errno.h and Errors.h and create Estr resource"""
# A minimal text editor.
# A minimal text editor.
def createFond(self): fond_res = Res.Resource("") fond_res.AddResource('FOND', self.res_id, self.fullname) from fontTools import fondLib fond = fondLib.FontFamily(fond_res, "w") fond.ffFirstChar = 0 fond.ffLastChar = 255 fond.fondClass = 0 fond.fontAssoc = [(0, 0, self.res_id)] fond.ffFlags = 20480 # XXX ??? fond.ffIntl = (0, 0) fond.ffLeading = 0 fond.ffProperty = (0, 0, 0, 0, 0, 0, 0, 0, 0) fond.ffVersion = 0 fond.glyphEncoding = {} if self.familyname == self.psname: fond.styleIndices = (1, ) * 48 # uh-oh, fondLib is too dumb. else: fond.styleIndices = (2, ) * 48 fond.styleStrings = [] fond.boundingBoxes = None fond.ffFamID = self.res_id fond.changed = 1 fond.glyphTableOffset = 0 fond.styleMappingReserved = 0 # calc: scale = 4096 / self.ttFont['head'].unitsPerEm fond.ffAscent = scale * self.ttFont['hhea'].ascent fond.ffDescent = scale * self.ttFont['hhea'].descent fond.ffWidMax = scale * self.ttFont['hhea'].advanceWidthMax fond.ffFamilyName = self.familyname fond.psNames = {0: self.psname} fond.widthTables = {} fond.kernTables = {} cmap = self.ttFont['cmap'].getcmap(1, 0) if cmap: names = {} for code, name in cmap.cmap.items(): names[name] = code if 'kern' in self.ttFont: kern = self.ttFont['kern'].getkern(0) if kern: fondkerning = [] for (left, right), value in kern.kernTable.items(): if left in names and right in names: fondkerning.append( (names[left], names[right], scale * value)) fondkerning.sort() fond.kernTables = {0: fondkerning} if 'hmtx' in self.ttFont: hmtx = self.ttFont['hmtx'] fondwidths = [2048] * 256 + [ 0, 0 ] # default width, + plus two zeros. for name, (width, lsb) in hmtx.metrics.items(): if name in names: fondwidths[names[name]] = scale * width fond.widthTables = {0: fondwidths} fond.save()
import calldll import macfs import sys import MacOS from Carbon import Res fss, ok = macfs.PromptGetFile("Show me calldll.ppc.slb") lib = calldll.getdiskfragment(fss, 'calldll.ppc.slb') cdll_b_bbbbbbbb = calldll.newcall(lib.cdll_b_bbbbbbbb, 'Byte', 'InByte', 'InByte', 'InByte', 'InByte', 'InByte', 'InByte', 'InByte', 'InByte') cdll_h_hhhhhhhh = calldll.newcall(lib.cdll_h_hhhhhhhh, 'Short', 'InShort', 'InShort', 'InShort', 'InShort', 'InShort', 'InShort', 'InShort', 'InShort') cdll_l_llllllll = calldll.newcall(lib.cdll_l_llllllll, 'Long', 'InLong', 'InLong', 'InLong', 'InLong', 'InLong', 'InLong', 'InLong', 'InLong') cdll_N_ssssssss = calldll.newcall(lib.cdll_N_ssssssss, 'None', 'InString', 'InString', 'InString', 'InString', 'InString', 'InString', 'InString', 'InString') cdll_o_l = calldll.newcall(lib.cdll_o_l, 'OSErr', 'InLong') cdll_N_pp = calldll.newcall(lib.cdll_N_pp, 'None', 'InPstring', 'OutPstring') cdll_N_bb = calldll.newcall(lib.cdll_N_bb, 'None', 'InByte', 'OutByte') cdll_N_hh = calldll.newcall(lib.cdll_N_hh, 'None', 'InShort', 'OutShort') cdll_N_ll = calldll.newcall(lib.cdll_N_ll, 'None', 'InLong', 'OutLong') cdll_N_sH = calldll.newcall(lib.cdll_N_sH, 'None', 'InString', 'InHandle') print 'Test cdll_b_bbbbbbbb' rv = cdll_b_bbbbbbbb(1, 2, 3, 4, 5, 6, 7, 8) if rv == 36: print 'ok.'
"""IC wrapper module, based on Internet Config 1.3"""
def send_hor_rule(self, *args, **kw): # Ignore ruler options, for now self.delayed_para_send() self.delayed_name_send() dummydata = Res.Resource('') self.ted.WEInsertObject('rulr', dummydata, (0, 0))
"""tools for BuildApplet and BuildApplication"""
#
"""Creation of PYC resources"""
"""macgen_bin - Generate application from shared libraries"""
"""macostools - Various utility functions for MacOS.
import Printing
import FrameWork import Wbase, Wcontrols from Carbon import Ctl, Controls, Qd, Res from types import * import Wapplication #_arrowright = Qd.GetPicture(472) #_arrowdown = Qd.GetPicture(473) _arrowright = Res.Resource( '\x00I\x00\x00\x00\x00\x00\n\x00\n\x11\x01\x01\x00\n\x00\x00\x00' '\x00\x00\n\x00\n\x90\x00\x02\x00\x00\x00\x00\x00\n\x00\n\x00\x00' '\x00\x00\x00\n\x00\n\x00\x00\x00\x00\x00\n\x00\n\x00\x00\x10\x00' '\x18\x00\x1c\x00\x1e\x00\x1f\x00\x1f\x00\x1e\x00\x1c\x00\x18\x00' '\x10\x00\xff') class PopupControl(Wcontrols.ControlWidget): def __init__(self, possize, items=None, callback=None): if items is None: items = [] procID = Controls.popupMenuProc|Controls.popupFixedWidth|Controls.useWFont Wcontrols.ControlWidget.__init__(self, possize, "", procID, callback, 0, 0, 0) self._items = items[:] def set(self, value): self._control.SetControlValue(value+1) def get(self): return self._control.GetControlValue() - 1
def send_hor_rule(self, *args, **kw): # Ignore ruler options, for now dummydata = Res.Resource('') self.ted.WEInsertObject('rulr', dummydata, (0, 0))
"""cmtest - List all components in the system"""
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)
def clearbuffer(self): from Carbon import Res self.consoletext.ted.WEUseText(Res.Resource('')) self.consoletext.write(sys.ps1) self.consoletext.flush()