Exemplo n.º 1
0
    def testSetCreatorAndType(self):
        if not os.path.exists('/Developer/Tools/GetFileInfo'):
            return

        try:
            fp = open(test_support.TESTFN, 'w')
            fp.write('\n')
            fp.close()

            MacOS.SetCreatorAndType(test_support.TESTFN, 'ABCD', 'EFGH')

            cr, tp = MacOS.GetCreatorAndType(test_support.TESTFN)
            self.assertEquals(cr, 'ABCD')
            self.assertEquals(tp, 'EFGH')

            data = subprocess.Popen(
                ["/Developer/Tools/GetFileInfo", test_support.TESTFN],
                stdout=subprocess.PIPE).communicate()[0]

            tp = None
            cr = None
            for ln in data.splitlines():
                if ln.startswith('type:'):
                    tp = ln.split()[-1][1:-1]
                if ln.startswith('creator:'):
                    cr = ln.split()[-1][1:-1]

            self.assertEquals(cr, 'ABCD')
            self.assertEquals(tp, 'EFGH')

        finally:
            os.unlink(test_support.TESTFN)
Exemplo n.º 2
0
def setMacCreatorAndType(path, fileCreator, fileType):
    if MacOS is not None:
        if sys.byteorder == "little":
            # work around bug in MacOS.SetCreatorAndType() on intel:
            # http://bugs.python.org/issue1594
            fileCreator = _reverseString(fileCreator)
            fileType = _reverseString(fileType)
        MacOS.SetCreatorAndType(path, fileCreator, fileType)
Exemplo n.º 3
0
def setMacCreatorAndType(path, fileCreator, fileType):
    if xattr is not None:
        from fontTools.misc.textTools import pad
        if not all(len(s) == 4 for s in (fileCreator, fileType)):
            raise TypeError('arg must be string of 4 chars')
        finderInfo = pad(bytesjoin([fileType, fileCreator]), 32)
        xattr.setxattr(path, 'com.apple.FinderInfo', finderInfo)
    if MacOS is not None:
        MacOS.SetCreatorAndType(path, fileCreator, fileType)
Exemplo n.º 4
0
 def domenu_save_as(self, *args):
     filename = EasyDialogs.AskFileForSave(message='Save console text as:',
             savedFileName='console.txt')
     if not filename:
         return
     f = open(filename, 'wb')
     f.write(self.get())
     f.close()
     MacOS.SetCreatorAndType(filename, W._signature, 'TEXT')
Exemplo n.º 5
0
 def domenu_save_as(self, *args):
     title = self._parentwindow.gettitle()
     filename = EasyDialogs.AskFileForSave(message='Save %s text as:' % title,
             savedFileName=title + '.txt')
     if not filename:
         return
     f = open(filename, 'wb')
     f.write(self.get())
     f.close()
     MacOS.SetCreatorAndType(filename, W._signature, 'TEXT')
Exemplo n.º 6
0
def process(input, output, script, ramprefix, switched):
    print '%s:'%input
    data = open(input).read()

    parser = DcBuilder()
    parser.feed(data)

    if script:
        converter = BatchConverter(script, output)
    else:
        converter = G2UserConverter()
    if switched:
        transformer = G2SwitchTransformer(converter)
    else:
        transformer = G2OnlyTransformer(converter)

    document = transformer.transform(parser.document)

    outfile = open(output, 'w')
    if os.name == 'mac':
        import MacOS
        MacOS.SetCreatorAndType(output, 'PNst', 'TEXT') # This is a guess...
    writer = XmlWriter(outfile)
    writer.write(document)
    if ramprefix:
        basename, dummy = os.path.splitext(output)
        ramname = basename + '.ram'
        if ramprefix[-1] != '/':
            ramprefix = ramprefix + '/'
        url = urllib.basejoin(ramprefix, output)
        fp = open(ramname, 'w')
        if os.name == 'mac':
            import MacOS
            MacOS.SetCreatorAndType(ramname, 'PNst', 'PNRM')
        fp.write(url+'\n')
        fp.close()
Exemplo n.º 7
0
def _test():
    import EasyDialogs
    try:
        from PIL import Image
    except ImportError:
        Image = None

    import MacOS
    Qt.EnterMovies()
    path = EasyDialogs.AskFileForOpen(message='Video to convert')
    if not path:
        sys.exit(0)
    rdr = reader(path)
    if not rdr:
        sys.exit(1)
    dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
    if not dstdir:
        sys.exit(0)
    num = 0
    os.mkdir(dstdir)
    videofmt = rdr.GetVideoFormat()
    imgfmt = videofmt.getformat()
    imgw, imgh = videofmt.getsize()
    timestamp, data = rdr.ReadVideo()
    while data:
        fname = 'frame%04.4d.jpg' % num
        num = num + 1
        pname = os.path.join(dstdir, fname)
        if not Image:
            print 'Not',
        print 'Writing %s, size %dx%d, %d bytes' % (fname,
         imgw,
         imgh,
         len(data))
        if Image:
            img = Image.fromstring('RGBA', (imgw, imgh), data)
            img.save(pname, 'JPEG')
            timestamp, data = rdr.ReadVideo()
            MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
            if num > 20:
                print 'stopping at 20 frames so your disk does not fill up:-)'
                break

    print 'Total frames:', num
    return
Exemplo n.º 8
0
def main():
    inputs, output, commands, ramprefix, switched = getargs(sys.argv)
    if commands:
        cfp = open(commands, 'w')
        if os.name == 'mac':
            import MacOS
            MacOS.SetCreatorAndType(commands, 'ToyS', 'TEXT')
    else:
        cfp = None
    for iname in inputs:
        if output:
            oname = output
        else:
            dirname, filename = os.path.split(iname)
            filename = 'g2_' + filename
            oname = os.path.join(dirname, filename)
        process(iname, oname, cfp, ramprefix, switched)
    cfp.close()
    if os.name == 'mac':
        sys.exit(1)             # So user can see the output
Exemplo n.º 9
0
def setMacCreatorAndType(path, fileCreator, fileType):
	"""Set file creator and file type codes for a path.

	Note that if the ``xattr`` module is not installed, no action is
	taken but no error is raised.

	Args:
		path (str): A file path.
		fileCreator: A four-character file creator tag.
		fileType: A four-character file type tag.

	"""
	if xattr is not None:
		from fontTools.misc.textTools import pad
		if not all(len(s) == 4 for s in (fileCreator, fileType)):
			raise TypeError('arg must be string of 4 chars')
		finderInfo = pad(bytesjoin([fileType, fileCreator]), 32)
		xattr.setxattr(path, 'com.apple.FinderInfo', finderInfo)
	if MacOS is not None:
		MacOS.SetCreatorAndType(path, fileCreator, fileType)
Exemplo n.º 10
0
 def domenu_save(self, *args):
     if not self.path:
         # Will call us recursively
         return self.domenu_save_as()
     data = self.editgroup.editor.get()
     if self._eoln != '\r':
         data = string.replace(data, '\r', self._eoln)
     fp = open(self.path, 'wb')  # open file in binary mode, data has '\r' line-endings
     fp.write(data)
     fp.close()
     MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT')
     self.getsettings()
     self.writewindowsettings()
     self.editgroup.editor.changed = 0
     self.editgroup.editor.selchanged = 0
     import linecache
     if linecache.cache.has_key(self.path):
         del linecache.cache[self.path]
     import macostools
     macostools.touched(self.path)
     self.addrecentfile(self.path)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 def setfiletype(self, filename):
     if MacOS and (self.filecreator or self.filetype):
         creator, type = MacOS.GetCreatorAndType(filename)
         if self.filecreator: creator = self.filecreator
         if self.filetype: type = self.filetype
         MacOS.SetCreatorAndType(filename, creator, type)
Exemplo n.º 13
0
# Video file reader, using QuickTime
Exemplo n.º 14
0
"""\
Exemplo n.º 15
0
    def compilesuite(self, major, minor, language, script, fname, precompinfo):
        """Generate code for a single suite"""
        [name, desc, code, level, version, events, classes, comps,
         enums] = self.suite

        # Sort various lists, so re-generated source is easier compared
        def class_sorter(k1, k2):
            """Sort classes by code, and make sure main class sorts before synonyms"""
            # [name, code, desc, properties, elements] = cls
            if k1[1] < k2[1]: return -1
            if k1[1] > k2[1]: return 1
            if not k2[3] or k2[3][0][1] == 'c@#!':
                # This is a synonym, the other one is better
                return -1
            if not k1[3] or k1[3][0][1] == 'c@#!':
                # This is a synonym, the other one is better
                return 1
            return 0

        events.sort()
        classes.sort(class_sorter)
        comps.sort()
        enums.sort()

        self.fp = fp = open(self.pathname, 'w')
        MacOS.SetCreatorAndType(self.pathname, 'Pyth', 'TEXT')

        fp.write('"""Suite %s: %s\n' % (ascii(name), ascii(desc)))
        fp.write("Level %d, version %d\n\n" % (level, version))
        fp.write("Generated from %s\n" % ascii(fname))
        fp.write("AETE/AEUT resource version %d/%d, language %d, script %d\n" % \
            (major, minor, language, script))
        fp.write('"""\n\n')

        fp.write('import aetools\n')
        fp.write('import MacOS\n\n')
        fp.write("_code = %r\n\n" % (code, ))
        if self.basepackage and self.basepackage._code_to_module.has_key(code):
            # We are an extension of a baseclass (usually an application extending
            # Standard_Suite or so). Import everything from our base module
            fp.write('from %s import *\n' %
                     self.basepackage._code_to_fullname[code][0])
            basemodule = self.basepackage._code_to_module[code]
        elif self.basepackage and self.basepackage._code_to_module.has_key(
                code.lower()):
            # This is needed by CodeWarrior and some others.
            fp.write('from %s import *\n' %
                     self.basepackage._code_to_fullname[code.lower()][0])
            basemodule = self.basepackage._code_to_module[code.lower()]
        else:
            # We are not an extension.
            basemodule = None
        self.basemodule = basemodule
        self.compileclassheader()

        self.enumsneeded = {}
        if events:
            for event in events:
                self.compileevent(event)
        else:
            fp.write("    pass\n\n")

        objc = ObjectCompiler(fp,
                              self.modname,
                              basemodule,
                              precompinfo,
                              interact=(self.edit_modnames is None),
                              verbose=self.verbose)
        for cls in classes:
            objc.compileclass(cls)
        for cls in classes:
            objc.fillclasspropsandelems(cls)
        for comp in comps:
            objc.compilecomparison(comp)
        for enum in enums:
            objc.compileenumeration(enum)

        for enum in self.enumsneeded.keys():
            objc.checkforenum(enum)

        objc.dumpindex()
Exemplo n.º 16
0
 def set_creator_type(file):
     MacOS.SetCreatorAndType(file, 'Pyth', 'PYC ')
Exemplo n.º 17
0
"""\
Exemplo n.º 18
0
 def _setCreatorType(file):
     MacOS.SetCreatorAndType(file, 'Pyth', 'PYC ')
Exemplo n.º 19
0
def SetOutputFileName(file=None):
    "Set the output file name and set its creator&type to CWIE&TEXT"
    _SetOutputFileName(file)
    if file:
        import MacOS
        MacOS.SetCreatorAndType(file, 'CWIE', 'TEXT')
Exemplo n.º 20
0
def compileaete(aete, resinfo, fname, output = None, basepkgname = None, edit_modnames = None, creatorsignature = None, verbose = None):
    """Generate code for a full aete resource. fname passed for doc purposes"""
    version, language, script, suites = aete
    major, minor = divmod(version, 256)
    if not creatorsignature:
        creatorsignature, dummy = MacOS.GetCreatorAndType(fname)
    packagename = identify(os.path.splitext(os.path.basename(fname))[0])
    if language:
        packagename = packagename + '_lang%d' % language
    if script:
        packagename = packagename + '_script%d' % script
    if len(packagename) > 27:
        packagename = packagename[:27]
    if output:
        if not os.path.exists(output):
            os.mkdir(output)
        pathname = output
    else:
        pathname = EasyDialogs.AskFolder(message='Create and select package folder for %s' % packagename, defaultLocation=DEFAULT_USER_PACKAGEFOLDER)
        output = pathname
    if not pathname:
        return
    else:
        packagename = os.path.split(os.path.normpath(pathname))[1]
        if not basepkgname:
            basepkgname = EasyDialogs.AskFolder(message='Package folder for base suite (usually StdSuites)', defaultLocation=DEFAULT_STANDARD_PACKAGEFOLDER)
        if basepkgname:
            dirname, basepkgname = os.path.split(os.path.normpath(basepkgname))
            if dirname and dirname not in sys.path:
                sys.path.insert(0, dirname)
            basepackage = __import__(basepkgname)
        else:
            basepackage = None
        suitelist = []
        allprecompinfo = []
        allsuites = []
        for suite in suites:
            compiler = SuiteCompiler(suite, basepackage, output, edit_modnames, verbose)
            code, modname, precompinfo = compiler.precompilesuite()
            if not code:
                continue
            allprecompinfo = allprecompinfo + precompinfo
            suiteinfo = (suite, pathname, modname)
            suitelist.append((code, modname))
            allsuites.append(compiler)

        for compiler in allsuites:
            compiler.compilesuite(major, minor, language, script, fname, allprecompinfo)

        initfilename = os.path.join(output, '__init__.py')
        fp = open(initfilename, 'w')
        MacOS.SetCreatorAndType(initfilename, 'Pyth', 'TEXT')
        fp.write('"""\n')
        fp.write('Package generated from %s\n' % ascii(fname))
        if resinfo:
            fp.write('Resource %s resid %d %s\n' % (ascii(resinfo[1]), resinfo[0], ascii(resinfo[2])))
        fp.write('"""\n')
        fp.write('import aetools\n')
        fp.write('Error = aetools.Error\n')
        suitelist.sort()
        for code, modname in suitelist:
            fp.write('import %s\n' % modname)

        fp.write('\n\n_code_to_module = {\n')
        for code, modname in suitelist:
            fp.write("    '%s' : %s,\n" % (ascii(code), modname))

        fp.write('}\n\n')
        fp.write('\n\n_code_to_fullname = {\n')
        for code, modname in suitelist:
            fp.write("    '%s' : ('%s.%s', '%s'),\n" % (ascii(code),
             packagename,
             modname,
             modname))

        fp.write('}\n\n')
        for code, modname in suitelist:
            fp.write('from %s import *\n' % modname)

        fp.write('\ndef getbaseclasses(v):\n')
        fp.write("    if not getattr(v, '_propdict', None):\n")
        fp.write('        v._propdict = {}\n')
        fp.write('        v._elemdict = {}\n')
        fp.write("        for superclassname in getattr(v, '_superclassnames', []):\n")
        fp.write('            superclass = eval(superclassname)\n')
        fp.write('            getbaseclasses(superclass)\n')
        fp.write("            v._propdict.update(getattr(superclass, '_propdict', {}))\n")
        fp.write("            v._elemdict.update(getattr(superclass, '_elemdict', {}))\n")
        fp.write("        v._propdict.update(getattr(v, '_privpropdict', {}))\n")
        fp.write("        v._elemdict.update(getattr(v, '_privelemdict', {}))\n")
        fp.write('\n')
        fp.write('import StdSuites\n')
        allprecompinfo.sort()
        if allprecompinfo:
            fp.write('\n#\n# Set property and element dictionaries now that all classes have been defined\n#\n')
            for codenamemapper in allprecompinfo:
                for k, v in codenamemapper.getall('class'):
                    fp.write('getbaseclasses(%s)\n' % v)

        application_class = None
        if allprecompinfo:
            fp.write('\n#\n# Indices of types declared in this module\n#\n')
            fp.write('_classdeclarations = {\n')
            for codenamemapper in allprecompinfo:
                for k, v in codenamemapper.getall('class'):
                    fp.write('    %r : %s,\n' % (k, v))
                    if k == 'capp':
                        application_class = v

            fp.write('}\n')
        if suitelist:
            fp.write('\n\nclass %s(%s_Events' % (packagename, suitelist[0][1]))
            for code, modname in suitelist[1:]:
                fp.write(',\n        %s_Events' % modname)

            fp.write(',\n        aetools.TalkTo):\n')
            fp.write('    _signature = %r\n\n' % (creatorsignature,))
            fp.write("    _moduleName = '%s'\n\n" % packagename)
            if application_class:
                fp.write('    _elemdict = %s._elemdict\n' % application_class)
                fp.write('    _propdict = %s._propdict\n' % application_class)
        fp.close()
        return
Exemplo n.º 21
0
def setMacCreatorAndType(path, fileCreator, fileType):
	if MacOS is not None:
		MacOS.SetCreatorAndType(path, fileCreator, fileType)
Exemplo n.º 22
0
"""macgen_info - Generate CodeWarrior project, config source, resource file"""
Exemplo n.º 23
0
    def compilesuite(self, major, minor, language, script, fname, precompinfo):
        """Generate code for a single suite"""
        name, desc, code, level, version, events, classes, comps, enums = self.suite

        def class_sorter(k1, k2):
            """Sort classes by code, and make sure main class sorts before synonyms"""
            if k1[1] < k2[1]:
                return -1
            if k1[1] > k2[1]:
                return 1
            if not k2[3] or k2[3][0][1] == 'c@#!':
                return -1
            if not k1[3] or k1[3][0][1] == 'c@#!':
                return 1
            return 0

        events.sort()
        classes.sort(class_sorter)
        comps.sort()
        enums.sort()
        self.fp = fp = open(self.pathname, 'w')
        MacOS.SetCreatorAndType(self.pathname, 'Pyth', 'TEXT')
        fp.write('"""Suite %s: %s\n' % (ascii(name), ascii(desc)))
        fp.write('Level %d, version %d\n\n' % (level, version))
        fp.write('Generated from %s\n' % ascii(fname))
        fp.write('AETE/AEUT resource version %d/%d, language %d, script %d\n' % (major,
         minor,
         language,
         script))
        fp.write('"""\n\n')
        fp.write('import aetools\n')
        fp.write('import MacOS\n\n')
        fp.write('_code = %r\n\n' % (code,))
        if self.basepackage and code in self.basepackage._code_to_module:
            fp.write('from %s import *\n' % self.basepackage._code_to_fullname[code][0])
            basemodule = self.basepackage._code_to_module[code]
        elif self.basepackage and code.lower() in self.basepackage._code_to_module:
            fp.write('from %s import *\n' % self.basepackage._code_to_fullname[code.lower()][0])
            basemodule = self.basepackage._code_to_module[code.lower()]
        else:
            basemodule = None
        self.basemodule = basemodule
        self.compileclassheader()
        self.enumsneeded = {}
        if events:
            for event in events:
                self.compileevent(event)

        else:
            fp.write('    pass\n\n')
        objc = ObjectCompiler(fp, self.modname, basemodule, precompinfo, interact=self.edit_modnames is None, verbose=self.verbose)
        for cls in classes:
            objc.compileclass(cls)

        for cls in classes:
            objc.fillclasspropsandelems(cls)

        for comp in comps:
            objc.compilecomparison(comp)

        for enum in enums:
            objc.compileenumeration(enum)

        for enum in self.enumsneeded.keys():
            objc.checkforenum(enum)

        objc.dumpindex()
        return
Exemplo n.º 24
0
 def setcreatorandtype(path, creator, type):
     return MacOS.SetCreatorAndType(path, creator, type)