def make_makefile(platform, project): ## FIX pncrt madness if project.getTargetType() in [ 'dll' , 'exe' ]: fix_pncrt(project) ## Create Applescript mprj = ProjectToMacCWProjectData(platform, project) applescript_path = macfs.FSSpec(project.makefile_name).as_pathname() ASMakefile(mprj).script.CompileAndSave(applescript_path) ## Create Uber XML file generate_uberxml(platform, project, mprj) ## Create an applescript stub file for reading the Uber XML file # this needs better handling/reporting of build errors script = ascript.CreateAppleScript() script.Append( 'tell application %s' % (os.environ["BUILD_SW"]), ' with timeout of 99999 seconds', ' try', ' make new (project document) as "%s" with data ("%s")' % ( macpath.join(os.getcwd(),project.makefile_name+"_uber.prj"), macpath.join(os.getcwd(),project.makefile_name+"_uber.xml")), ' set cwErrorList to Make Project with ExternalEditor', ' Close Project', ' on error errText number errnum', ' return errText & return', ' end try', ' end timeout', 'end tell') uber_ascript = macfs.FSSpec(project.makefile_name+"_uber").as_pathname() script.CompileAndSave(uber_ascript) ## Pretend like everything went well return None
def copy(src, dst, createpath=0): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = open(srcfss.as_pathname(), '*rb') ofp = open(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type = sf.Creator, sf.Type df.Flags = ( sf.Flags & (kIsStationary | kNameLocked | kHasBundle | kIsInvisible | kIsAlias)) dstfss.SetFInfo(df)
def _platform_cp(self, source_path, destination_path): ## copy file data source = self._open(source_path, 'rb') destination = self._open(destination_path, 'wb') self._raw_copy(source, destination) source.close() destination.close() ## copy resource file data source = MacOS.openrf(source_path, '*rb') destination = MacOS.openrf(destination_path, '*wb') self._raw_copy(source, destination) source.close() destination.close() ## set creator/type on the Macintosh source_spec = macfs.FSSpec(source_path) (creator, type) = source_spec.GetCreatorType() destination_spec = macfs.FSSpec(destination_path) destination_spec.SetCreatorType(creator, type) ## copy file mode/time bits st = os.stat(source_path) mtime = st[stat.ST_MTIME] destination_spec.SetDates(mtime, mtime, mtime)
def handle_xml_file(self, path): prefs = getprefs() makesuitcase = int(prefs.get("makesuitcases", 0)) dstfolder = prefs.get("ttoutput", DEFAULTTTOUTPUT) if not os.path.exists(dstfolder): os.mkdir(dstfolder) srcfilename = dstfilename = os.path.basename(path) if dstfilename[-4:] in (".ttx", ".xml"): dstfilename = dstfilename[:-4] if dstfilename[-4:] not in (".TTF", ".ttf"): dstfilename = dstfilename + ".TTF" dst = os.path.join(dstfolder, dstfilename) if makesuitcase: try: # see if the destination file is writable, # otherwise we'll get an error waaay at the end of # the parse procedure testref = Res.FSpOpenResFile(macfs.FSSpec(dst), 3) # read-write except Res.Error, why: if why[0] <> -43: # file not found EasyDialogs.Message( "Can't create '%s'; file already open" % dst) return else: Res.CloseResFile(testref)
def handle_resource_file(self, path): prefs = getprefs() dstfolder = prefs.get("xmloutput", DEFAULTXMLOUTPUT) if not os.path.exists(dstfolder): os.mkdir(dstfolder) filename = os.path.basename(path) fss = macfs.FSSpec(path) try: resref = Res.FSpOpenResFile(fss, 1) # read-only except: return "unknown" Res.UseResFile(resref) pb = None try: n = Res.Count1Resources("sfnt") for i in range(1, n + 1): res = Res.Get1IndResource('sfnt', i) resid, restype, resname = res.GetResInfo() if not resname: resname = filename + ` i ` pb = ProgressBar("Dumping '%s' to XML..." % resname) dst = os.path.join(dstfolder, resname + ".ttx") try: tt = ttLib.TTFont(path, i) tt.saveXML(dst, pb) finally: pb.close() finally: Res.CloseResFile(resref)
def test_dates(self): import time fss = macfs.FSSpec(test_support.TESTFN) now = int(time.time()) fss.SetDates(now, now+1, now+2) dates = fss.GetDates() self.assertEqual(dates, (now, now+1, now+2))
def save(self, file, makeSuitcase=0): """Save the font to disk. Similarly to the constructor, the 'file' argument can be either a pathname or a writable file object. On the Mac, if makeSuitcase is true, a suitcase (resource fork) file will we made instead of a flat .ttf file. """ from kiva.fonttools.fontTools.ttLib import sfnt if isinstance(file, basestring): closeStream = 1 if os.name == "mac" and makeSuitcase: import macUtils file = macUtils.SFNTResourceWriter(file, self) else: file = open(file, "wb") if os.name == "mac": import macfs fss = macfs.FSSpec(file.name) fss.SetCreatorType('mdos', 'BINA') else: # assume "file" is a writable file object closeStream = 0 tags = self.keys() tags.remove("GlyphOrder") numTables = len(tags) writer = sfnt.SFNTWriter(file, numTables, self.sfntVersion) done = [] for tag in tags: self._writeTable(tag, writer, done) writer.close(closeStream)
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems d = ifp.read() ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc() if d: ofp = openrsrc(out, 'wb') ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close()
def rundir(self, path, destprefix, doit): files = os.listdir(path) todo = [] rv = 1 for f in files: if self.exc.match(f): continue fullname = os.path.join(path, f) if os.path.isdir(fullname): todo.append(fullname) else: dest = self.inc.match(fullname) if dest == None: print 'Not yet resolved:', fullname rv = 0 if dest: if doit: print 'COPY ', fullname print ' -> ', os.path.join(destprefix, dest) try: macostools.copy(fullname, os.path.join(destprefix, dest), 1) except: #DBG print '*** Copy failed mysteriously, try again' print '*** cwd', os.getcwd() #DBG print '*** fsspec', macfs.FSSpec(fullname) #DBG # Get rid of open files try: i = 1 / 0 except: pass macostools.copy(fullname, os.path.join(destprefix, dest), 1) for d in todo: if not self.rundir(d, destprefix, doit): rv = 0 return rv
def copycwproject(path, name): """Copy CW project (if needed) and remember for hexbinning""" global project_files dstdir = os.path.join(TOP, CWDIR) if not os.path.exists(dstdir): print dstdir print 'No CW-project dir, skip', name return dstfile = os.path.join(dstdir, name) # Check that we're not in the dest directory if dstfile == path: return # If the destination doesn't exists or is older that the source # we copy and remember it if os.path.exists(dstfile) and \ os.stat(dstfile)[8] > os.stat(path)[8]: print 'Not copying', path, '- Up-to-date' else: print 'Copy', path macostools.copy(path, dstfile) fss = macfs.FSSpec(dstfile) creator = fss.GetCreatorType()[0] if project_files.has_key(creator): project_files[creator].append(fss) else: project_files[creator] = [fss]
def writenode(node, evallicense = 0, tostring = 0, silent = 0): if not hasattr(node, 'tmpfile') and not tostring: return import realsupport data = realsupport.writeRP(None, node.slideshow.rp, node, savecaptions=1, tostring = 1, silent = silent) if tostring: return data url = MMAttrdefs.getattr(node, 'file') url = node.GetContext().findurl(url) utype, host, path, params, query, tag = urlparse.urlparse(url) if (not utype or utype == 'file') and \ (not host or host == 'localhost'): try: localpathname = MMurl.url2pathname(path) f = open(localpathname, 'w') f.write(data) f.close() except: windowinterface.showmessage("cannot write `%s' for node `%s'" % (url, MMAttrdefs.getattr(node, 'name') or '<unnamed>')) else: if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(localpathname) fss.SetCreatorType('PNst', 'PNRA') macostools.touched(fss) del node.tmpfile else: windowinterface.showmessage("cannot write remote file for node `%s'" % (MMAttrdefs.getattr(node, 'name') or '<unnamed>'))
def find_rcfile_location(name): """Execute $UMAKERC, $HOME/.umakerc, %HOMEDRIVE%HOMEPATH/umakerc.py or %preferencesfolder%:umakerc""" f = os.environ.get(string.upper(name), "") if f and os.path.isdir(os.path.dirname(f)): return f home = os.environ.get("HOME", "") if home and os.path.isdir(home): return os.path.join(home, "." + name) homedrive = os.environ.get("HOMEDRIVE", "") homepath = os.environ.get("HOMEPATH", "") if homedrive and homepath: f = os.path.join(homedrive + homepath, "." + name) if os.path.isdir(os.path.dirname(f)): return f if sys.platform == "mac": import macfs import MACFS vrefnum, curdir = macfs.FindFolder(MACFS.kOnAppropriateDisk, MACFS.kPreferencesFolderType, 0) fss = macfs.FSSpec((vrefnum, curdir, name)) return fss.as_pathname() return None
def mkalias(src, dst): """Create a finder alias""" srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) alias = srcfss.NewAlias() srcfinfo = srcfss.GetFInfo() Res.FSpCreateResFile(dstfss, srcfinfo.Creator, srcfinfo.Type, -1) h = Res.FSpOpenResFile(dstfss, 3) resource = Res.Resource(alias.data) resource.AddResource('alis', 0, '') Res.CloseResFile(h) dstfinfo = dstfss.GetFInfo() dstfinfo.Flags = dstfinfo.Flags | 0x8000 # Alias flag dstfss.SetFInfo(dstfinfo)
def main(): # Ask the user for the plugins directory dir, ok = macfs.GetDirectory('Where is the PlugIns folder?') if not ok: sys.exit(0) os.chdir(dir.as_pathname()) # Remove old .slb aliases and collect a list of .slb files if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f) print LibFiles # Create the new aliases. if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: macostools.mkalias(src, dst) else: EasyDialogs.Message(dst + ' not created: ' + src + ' not found') EasyDialogs.Message('All done!')
def _candidate_tempdir_list(): """Generate a list of candidate temporary directories which _get_default_tempdir will try.""" dirlist = [] # First, try the environment. for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = _os.getenv(envname) if dirname: dirlist.append(dirname) # Failing that, try OS-specific locations. if _os.name == 'mac': try: refnum, dirid = _macfs.FindFolder(_MACFS.kOnSystemDisk, _MACFS.kTemporaryFolderType, 1) dirname = _macfs.FSSpec((refnum, dirid, '')).as_pathname() dirlist.append(dirname) except _macfs.error: pass elif _os.name == 'riscos': dirname = _os.getenv('Wimp$ScrapDir') if dirname: dirlist.append(dirname) elif _os.name == 'nt': dirlist.extend([r'c:\temp', r'c:\tmp', r'\temp', r'\tmp']) else: dirlist.extend(['/tmp', '/var/tmp', '/usr/tmp']) # As a last resort, the current directory. try: dirlist.append(_os.getcwd()) except (AttributeError, _os.error): dirlist.append(_os.curdir) return dirlist
def test_coercion(self): fss = macfs.FSSpec(test_support.TESTFN) fsr = macfs.FSRef(test_support.TESTFN) fss2 = fsr.as_fsspec() fsr2 = fss.as_fsref() self.assertEqual(fss.as_pathname(), fss2.as_pathname()) self.assertEqual(fsr.as_pathname(), fsr2.as_pathname())
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): """Makes a one-page PDF with just the drawing. If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.""" d = renderScaledDrawing(d) c = Canvas(fn) if msg: c.setFont(rl_config.defaultGraphicsFontName, 36) c.drawString(80, 750, msg) c.setTitle(msg) if autoSize: c.setPageSize((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) else: #show with a title c.setFont(rl_config.defaultGraphicsFontName, 12) y = 740 i = 1 y = y - d.height draw(d, c, 80, y, showBoundary=showBoundary) c.showPage() c.save() if sys.platform == 'mac' and not hasattr(fn, "write"): try: import macfs, macostools macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") macostools.touched(fn) except: pass
def _gettempdir_inner(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass elif os.name == 'riscos': scrapdir = os.getenv('Wimp$ScrapDir') if scrapdir: attempdirs.insert(0, scrapdir) for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + ` attempdirs ` raise IOError, msg return tempdir
def SaveToFileObject(self, fileobj): """Open a file, and ask each object in turn to write itself to the file. Keep track of the file position at each point for use in the index at the end""" f = fileobj i = 1 self.xref = [] f.write("%PDF-1.2" + LINEEND) # for CID support f.write("%í춾" + LINEEND) for obj in self.objects: pos = f.tell() self.xref.append(pos) f.write(str(i) + ' 0 obj' + LINEEND) obj.save(f) f.write('endobj' + LINEEND) i = i + 1 self.writeXref(f) self.writeTrailer(f) f.write('%%EOF') # no lineend needed on this one! # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass
def touched(dst): """Tell the finder a file has changed. No-op on MacOSX.""" if sys.platform != 'mac': return import warnings warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__) import macfs file_fss = macfs.FSSpec(dst) vRefNum, dirID, name = file_fss.as_tuple() dir_fss = macfs.FSSpec((vRefNum, dirID, '')) crdate, moddate, bkdate = dir_fss.GetDates() now = time.time() if now == moddate: now = now + 1 try: dir_fss.SetDates(crdate, now, bkdate) except macfs.error: pass
def compile(file, cfile=None): import os, marshal, __builtin__ f = open(file) codestring = f.read() f.close() timestamp = os.stat(file)[8] codeobject = __builtin__.compile(codestring, file, 'exec') if not cfile: cfile = file + 'c' fc = open(cfile, 'wb') fc.write(MAGIC) wr_long(fc, timestamp) marshal.dump(codeobject, fc) fc.close() if os.name == 'mac': import macfs macfs.FSSpec(cfile).SetCreatorType('PYTH', 'PYC ') macfs.FSSpec(file).SetCreatorType('PYTH', 'TEXT')
def utime(path, atime, mtime): try: _mac_second_diff = 2082816000.0 fsp = macfs.FSSpec(self.FP(mac_path(filename))) mt = mtime + _mac_second_diff at = atime + _mac_second_diff fsp.SetDates(mt, mt, at) except MacOS.Error: raise error, "utime(%s,%d,%d) failed" % (path, atime, mtime)
def open_new_file(path): # On the Mac, try to preserve Finder position # of previously existing file. fsspec = macfs.FSSpec(path) try: old_finfo = fsspec.GetFInfo() except MacOS.Error, e: #print "MacUtils.open_new_file:", e ### old_finfo = None
def WriteExportFile(mprj): ## write the file and set creator/type if len(mprj.export_file): fil = open(mprj.export_file, 'w') for exported_func in mprj.export_list: fil.write("%s\n" % (exported_func)) fil.close() fsspec = macfs.FSSpec(mprj.export_file) fsspec.SetCreatorType('CWIE', 'TEXT')
def markfilename(filename, creatorcode=None, filetype=None, ext='PDF'): try: if creatorcode is None or filetype is None and ext is not None: try: creatorcode, filetype = _KNOWN_MAC_EXT[ext.upper()] except: return macfs.FSSpec(filename).SetCreatorType(creatorcode, filetype) macostools.touched(filename) except: pass
def getprefdir(package, home=None): if os.name == "nt": return win32_getprefdir(package, appname, home) if os.name == "mac": vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kPreferencesFolderType, 0) fss = macfs.FSSpec((vrefnum, dirid, ":" + appname)) return fss.as_pathname() if home is None: home = gethomedir() return os.path.join(home, "." + string.lower(package))
def getfileinfo(name): finfo = macfs.FSSpec(name).GetFInfo() dir, file = os.path.split(name) # XXXX Get resource/data sizes fp = open(name, 'rb') fp.seek(0, 2) dlen = fp.tell() fp = openrf(name, '*rb') fp.seek(0, 2) rlen = fp.tell() return file, finfo, dlen, rlen
def make_makefile(platform, project): ## FIX pncrt madness if project.getTargetType() in [ 'dll' , 'exe' ]: fix_pncrt(project) ## Create Applescript mprj = ProjectToMacCWProjectData(platform, project) applescript_path = macfs.FSSpec(project.makefile_name).as_pathname() ASMakefile(mprj).script.CompileAndSave(applescript_path) ## Pretend like everything went well return None
def _getSystemDir(kind): if (kind == AG_LOGS_DIR): return os.path.join(getSystemDir(AG_SYSTEM_DIR), "logs") elif (kind == AG_DEMOS_DIR): return os.path.join(getSystemDir(AG_SYSTEM_DIR), "demos") else: path = "" if (sysutils.isServer()): path = os.getenv("ACTIVEGRID_SERVER_HOME") if ((path is None) or (len(path) < 1)): path = sysutils.mainModuleDir else: path = os.getenv("AG_DOCUMENTS_DIR") if ((path is None) or (len(path) < 1)): if sysutils.isWindows(): ifDefPy() try: from win32com.shell import shell, shellcon path = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) except: pass endIfDef() if ((path is None) or (len(path) < 1)): homedrive = asString(os.getenv("HOMEDRIVE")) homepath = os.getenv("HOMEPATH") ## if ((homedrive is not None) and (len(homedrive) > 0) and (homepath is not None) and (len(homepath) > 0)): path = os.path.join(homedrive, homepath, "MYDOCU~1") else: ifDefPy() if sys.platform == "darwin": try: import macfs import MACFS fsspec_disk, fsspec_desktop = macfs.FindFolder( MACFS.kOnSystemDisk, MACFS.kDocumentsFolderType, 0) path = macfs.FSSpec((fsspec_disk, fsspec_desktop, '')).as_pathname() except: pass endIfDef() ifDefPy() if ((path is None) or (len(path) < 1)): path = os.path.expanduser("~") endIfDef() if ((path is None) or (len(path) < 1)): path = "/" path = os.path.join(path, "ActiveGrid") return path
def rsrcGetCreator(path): if drawer.isCarbon(): import Carbon.File fss = Carbon.File.FSSpec(path) finfo = fss.FSpGetFInfo() creator = finfo.Creator type = finfo.Type else: import macfs f = macfs.FSSpec(path) creator, type = f.GetCreatorType() return creator, type