def toXML(self, writer, ttFont):
		if self.version == 1:
			format = OS2_format_1
		elif self.version in (2, 3, 4):
			format = OS2_format_2
		else:
			format = OS2_format_0
		formatstring, names, fixes = sstruct.getformat(format)
		for name in names:
			value = getattr(self, name)
			if type(value) == type(0):
				value = int(value)
			if name=="panose":
				writer.begintag("panose")
				writer.newline()
				value.toXML(writer, ttFont)
				writer.endtag("panose")
			elif name in ("ulUnicodeRange1", "ulUnicodeRange2", 
					"ulUnicodeRange3", "ulUnicodeRange4",
					"ulCodePageRange1", "ulCodePageRange2"):
				writer.simpletag(name, value=num2binary(value))
			elif name in ("fsType", "fsSelection"):
				writer.simpletag(name, value=num2binary(value, 16))
			elif name == "achVendID":
				writer.simpletag(name, value=repr(value)[1:-1])
			else:
				writer.simpletag(name, value=value)
			writer.newline()
Exemple #2
0
	def toXML(self, writer, ttFont):
		writer.comment(
			"The fields 'usFirstCharIndex' and 'usLastCharIndex'\n"
			"will be recalculated by the compiler")
		writer.newline()
		if self.version == 1:
			format = OS2_format_1
		elif self.version in (2, 3, 4):
			format = OS2_format_2
		elif self.version == 5:
			format = OS2_format_5
		else:
			format = OS2_format_0
		formatstring, names, fixes = sstruct.getformat(format)
		for name in names:
			value = getattr(self, name)
			if name=="panose":
				writer.begintag("panose")
				writer.newline()
				value.toXML(writer, ttFont)
				writer.endtag("panose")
			elif name in ("ulUnicodeRange1", "ulUnicodeRange2",
					"ulUnicodeRange3", "ulUnicodeRange4",
					"ulCodePageRange1", "ulCodePageRange2"):
				writer.simpletag(name, value=num2binary(value))
			elif name in ("fsType", "fsSelection"):
				writer.simpletag(name, value=num2binary(value, 16))
			elif name == "achVendID":
				writer.simpletag(name, value=repr(value)[1:-1])
			else:
				writer.simpletag(name, value=value)
			writer.newline()
Exemple #3
0
def binaryToIntList(value, start=0):
    string = num2binary(value)
    all = []
    for index, v in enumerate(reversed(string)):
        if v == "1":
            all.append(start + index)
    return all
	def toXML(self, xmlWriter):
		from fontTools.misc.textTools import num2binary
		if self.bytecode is not None:
			xmlWriter.dumphex(self.bytecode)
		else:
			index = 0
			args = []
			while True:
				token, isOperator, index = self.getToken(index)
				if token is None:
					break
				if isOperator:
					args = [str(arg) for arg in args]
					if token in ('hintmask', 'cntrmask'):
						hintMask, isOperator, index = self.getToken(index)
						bits = []
						for byte in hintMask:
							bits.append(num2binary(byteord(byte), 8))
						hintMask = strjoin(bits)
						line = ' '.join(args + [token, hintMask])
					else:
						line = ' '.join(args + [token])
					xmlWriter.write(line)
					xmlWriter.newline()
					args = []
				else:
					args.append(token)
			if args:
				if self.isCFF2:
					# CFF2Subr's can have numeric arguments on the stack after the last operator.
					args = [str(arg) for arg in args]
					line = ' '.join(args)
					xmlWriter.write(line)
				else:
					assert 0, "T2Charstring or Subr has items on the stack after last operator."
	def toXML(self, xmlWriter):
		from fontTools.misc.textTools import num2binary
		if self.bytecode is not None:
			xmlWriter.dumphex(self.bytecode)
		else:
			index = 0
			args = []
			while 1:
				token, isOperator, index = self.getToken(index)
				if token is None:
					break
				if isOperator:
					args = list(map(str, args))
					if token in ('hintmask', 'cntrmask'):
						hintMask, isOperator, index = self.getToken(index)
						bits = []
						for byte in hintMask:
							bits.append(num2binary(ord(byte), 8))
						hintMask = string.join(bits, "")
						line = string.join(args + [token, hintMask], " ")
					else:
						line = string.join(args + [token], " ")
					xmlWriter.write(line)
					xmlWriter.newline()
					args = []
				else:
					args.append(token)
Exemple #6
0
	def toXML(self, xmlWriter):
		from fontTools.misc.textTools import num2binary
		if self.bytecode is not None:
			xmlWriter.dumphex(self.bytecode)
		else:
			index = 0
			args = []
			while True:
				token, isOperator, index = self.getToken(index)
				if token is None:
					break
				if isOperator:
					args = [str(arg) for arg in args]
					if token in ('hintmask', 'cntrmask'):
						hintMask, isOperator, index = self.getToken(index)
						bits = []
						for byte in hintMask:
							bits.append(num2binary(byteord(byte), 8))
						hintMask = strjoin(bits)
						line = ' '.join(args + [token, hintMask])
					else:
						line = ' '.join(args + [token])
					xmlWriter.write(line)
					xmlWriter.newline()
					args = []
				else:
					args.append(token)
			if args:
				# NOTE: only CFF2 charstrings/subrs can have numeric arguments on
				# the stack after the last operator. Compiling this would fail if
				# this is part of CFF 1.0 table.
				args = [str(arg) for arg in args]
				line = ' '.join(args)
				xmlWriter.write(line)
Exemple #7
0
	def toXML(self, xmlWriter):
		from fontTools.misc.textTools import num2binary
		if self.bytecode is not None:
			xmlWriter.dumphex(self.bytecode)
		else:
			index = 0
			args = []
			while True:
				token, isOperator, index = self.getToken(index)
				if token is None:
					break
				if isOperator:
					args = [str(arg) for arg in args]
					if token in ('hintmask', 'cntrmask'):
						hintMask, isOperator, index = self.getToken(index)
						bits = []
						for byte in hintMask:
							bits.append(num2binary(byteord(byte), 8))
						hintMask = strjoin(bits)
						line = ' '.join(args + [token, hintMask])
					else:
						line = ' '.join(args + [token])
					xmlWriter.write(line)
					xmlWriter.newline()
					args = []
				else:
					args.append(token)
Exemple #8
0
	def toXML(self, xmlWriter, ttFont):
		xmlWriter.simpletag("version", value=self.version)
		xmlWriter.newline()
		xmlWriter.simpletag("flags", value=num2binary(self.flags, 16))
		xmlWriter.newline()
		for i in sorted(self.strikes.keys()):
			self.strikes[i].toXML(xmlWriter, ttFont)
Exemple #9
0
	def _disassemble(self, preserve=False):
		assembly = []
		i = 0
		bytecode = self.bytecode
		numBytecode = len(bytecode)
		while i < numBytecode:
			op = bytecode[i]
			try:
				mnemonic, argBits, argoffset = opcodeDict[op]
			except KeyError:
				if op in streamOpcodeDict:
					values = []

					# Merge consecutive PUSH operations
					while bytecode[i] in streamOpcodeDict:
						op = bytecode[i]
						mnemonic, argBits, argoffset = streamOpcodeDict[op]
						words = mnemonic[-1] == "W"
						if argBits:
							nValues = op - argoffset + 1
						else:
							i = i + 1
							nValues = bytecode[i]
						i = i + 1
						assert nValues > 0
						if not words:
							for j in range(nValues):
								value = bytecode[i]
								values.append(repr(value))
								i = i + 1
						else:
							for j in range(nValues):
								# cast to signed int16
								value = (bytecode[i] << 8) | bytecode[i+1]
								if value >= 0x8000:
									value = value - 0x10000
								values.append(repr(value))
								i = i + 2
						if preserve:
							break

					if not preserve:
						mnemonic = "PUSH"
					nValues = len(values)
					if nValues == 1:
						assembly.append("%s[ ]" % mnemonic)
					else:
						assembly.append("%s[ ]  /* %s values pushed */" % (mnemonic, nValues))
					assembly.extend(values)
				else:
					assembly.append("INSTR%d[ ]" % op)
					i = i + 1
			else:
				if argBits:
					assembly.append(mnemonic + "[%s]" % num2binary(op - argoffset, argBits))
				else:
					assembly.append(mnemonic + "[ ]")
				i = i + 1
		self.assembly = assembly
Exemple #10
0
	def _disassemble(self):
		assembly = []
		i = 0
		bytecode = self.bytecode
		numBytecode = len(bytecode)
		while i < numBytecode:
			op = bytecode[i]
			arg = 0
			try:
				mnemonic, argBits, argoffset, name = opcodeDict[op]
			except KeyError:
				try:
					mnemonic, argBits, argoffset, name = streamOpcodeDict[op]
				except KeyError:
					raise tt_instructions_error, "illegal opcode: 0x%.2x" % op
				pushBytes = pushWords = 0
				if argBits:
					if mnemonic == "PUSHB":
						pushBytes = op - argoffset + 1
					else:
						pushWords = op - argoffset + 1
				else:
					i = i + 1
					if mnemonic == "NPUSHB":
						pushBytes = bytecode[i]
					else:
						pushWords = bytecode[i]
				i = i + 1
				nValues = pushBytes or pushWords
				assert nValues > 0
				if nValues == 1:
					assembly.append("%s[ ]  /* %s value pushed */" % (mnemonic, nValues))
				else:
					assembly.append("%s[ ]  /* %s values pushed */" % (mnemonic, nValues))
				for j in range(pushBytes):
					value = bytecode[i]
					assembly.append(`value`)
					i = i + 1
				for j in range(pushWords):
					# cast to signed int16
					value = (bytecode[i] << 8) | bytecode[i+1]
					if value >= 0x8000:
						value = value - 0x10000
					assembly.append(`value`)
					i = i + 2
			else:
				if argBits:
					assembly.append(mnemonic + "[%s]" % num2binary(op - argoffset, argBits))
				else:
					assembly.append(mnemonic + "[ ]")
				i = i + 1
		self.assembly = assembly
Exemple #11
0
 def toXML(self, writer, ttFont):
     name = ttFont["name"].getDebugName(self.nameID)
     if name is not None:
         writer.newline()
         writer.comment(name)
         writer.newline()
     writer.begintag("NamedInstance", nameID=self.nameID,
                     flags=num2binary(self.flags, 16))
     writer.newline()
     for axis in ttFont["fvar"].axes:
         writer.simpletag("coord", axis=axis.axisTag,
                          value=self.coordinates[axis.axisTag])
         writer.newline()
     writer.endtag("NamedInstance")
     writer.newline()
Exemple #12
0
 def toXML(self, writer, ttFont):
     writer.comment("Most of this table will be recalculated by the compiler")
     writer.newline()
     formatstring, names, fixes = sstruct.getformat(headFormat)
     for name in names:
         value = getattr(self, name)
         if name in ("magicNumber", "checkSumAdjustment"):
             if value < 0:
                 value = value + 0x100000000
             value = hex(value)
             if value[-1:] == "L":
                 value = value[:-1]
         elif name in ("macStyle", "flags"):
             value = num2binary(value, 16)
         writer.simpletag(name, value=value)
         writer.newline()
Exemple #13
0
 def toXML(self, writer, ttFont):
     name = ttFont["name"].getDebugName(self.nameID)
     if name is not None:
         writer.newline()
         writer.comment(name)
         writer.newline()
     writer.begintag("Axis")
     writer.newline()
     for tag, value in [("AxisTag", self.axisTag),
                        ("MinValue", str(self.minValue)),
                        ("DefaultValue", str(self.defaultValue)),
                        ("MaxValue", str(self.maxValue)),
                        ("Flags", num2binary(self.flags, 16)),
                        ("NameID", str(self.nameID))]:
         writer.begintag(tag)
         writer.write(value)
         writer.endtag(tag)
         writer.newline()
     writer.endtag("Axis")
     writer.newline()
Exemple #14
0
 def toXML(self, writer, ttFont):
     writer.comment("Most of this table will be recalculated by the compiler")
     writer.newline()
     formatstring, names, fixes = sstruct.getformat(headFormat)
     for name in names:
         value = getattr(self, name)
         if name in ("created", "modified"):
             try:
                 value = time.asctime(time.gmtime(max(0, value + mac_epoch_diff)))
             except ValueError:
                 value = time.asctime(time.gmtime(0))
         if name in ("magicNumber", "checkSumAdjustment"):
             if value < 0:
                 value = value + 0x100000000
             value = hex(value)
             if value[-1:] == "L":
                 value = value[:-1]
         elif name in ("macStyle", "flags"):
             value = num2binary(value, 16)
         writer.simpletag(name, value=value)
         writer.newline()
Exemple #15
0
    def __repr__(self):
        """
        Print the instructions from the bytecode in the current stream starting
        at the beginning.
        """
        self.rewind()

        asm = ""
        indent = 0

        while True:
            opcode = self.io.read(1)
            if not opcode:
                return asm.strip()

            opcode = int.from_bytes(opcode, byteorder="big", signed=False)
            cmd_info = streamOpcodeDict.get(opcode, None)
            if cmd_info is None:
                cmd_info = opcodeDict.get(opcode, None)
            if cmd_info is None:
                print(asm + "\n"
                      "Illegal opcode 0x%02x at offset 0x%04x." % (
                          int(opcode),
                          self.io.tell(),
                      ))
                raise KeyError
            cmd_name, arg_bits, base_opcode, name = cmd_info

            args = []
            if cmd_name in ("EIF", "ELSE", "ENDF"):
                indent -= 1

            if cmd_name in ("NPUSHB", "NPUSHW", "PUSHB", "PUSHW"):
                # PUSH instructions read their arguments from the stream
                if cmd_name.startswith("PUSH"):
                    # Take number of arguments from the opcode
                    num_args = opcode - base_opcode + 1
                else:
                    # Take number of arguments from the stream
                    _, num_args = self.read_byte()
                if cmd_name.endswith("B"):
                    for n in range(num_args):
                        _, i = self.read_byte()
                        args.append(str(i))
                else:
                    for n in range(num_args):
                        _, i = self.read_word()
                        args.append(str(i))
                arg_bits = 0  # Don't output bits for push instructions

            if arg_bits == 0:
                arg_bitstring = " "
            else:
                arg_bitstring = num2binary(opcode - base_opcode, arg_bits)

            if cmd_name in ("NPUSHB", "NPUSHW", "PUSHB", "PUSHW"):
                num_args = len(args)
                val = "value" if num_args == 1 else "values"
                asm += f"\n{'  ' * indent}{cmd_name}[{arg_bitstring}]\t/* {num_args} {val} pushed */"
            else:
                asm += f"\n{'  ' * indent}{cmd_name}[{arg_bitstring}]\t/* {name} */"

            if args:
                asm += f"\n{'  ' * indent}{' '.join(args)}"

            if cmd_name in ("ELSE", "FDEF", "IF"):
                indent += 1
Exemple #16
0
    def _disassemble(self, preserve=False):
        assembly = []
        i = 0
        bytecode = self.bytecode
        numBytecode = len(bytecode)
        while i < numBytecode:
            op = bytecode[i]
            try:
                mnemonic, argBits, argoffset, name = opcodeDict[op]
            except KeyError:
                if op in streamOpcodeDict:
                    values = []

                    # Merge consecutive PUSH operations
                    while bytecode[i] in streamOpcodeDict:
                        op = bytecode[i]
                        mnemonic, argBits, argoffset, name = streamOpcodeDict[
                            op]
                        words = mnemonic[-1] == "W"
                        if argBits:
                            nValues = op - argoffset + 1
                        else:
                            i = i + 1
                            nValues = bytecode[i]
                        i = i + 1
                        assert nValues > 0
                        if not words:
                            for j in range(nValues):
                                value = bytecode[i]
                                values.append(repr(value))
                                i = i + 1
                        else:
                            for j in range(nValues):
                                # cast to signed int16
                                value = (bytecode[i] << 8) | bytecode[i + 1]
                                if value >= 0x8000:
                                    value = value - 0x10000
                                values.append(repr(value))
                                i = i + 2
                        if preserve:
                            break

                    if not preserve:
                        mnemonic = "PUSH"
                    nValues = len(values)
                    if nValues == 1:
                        assembly.append("%s[ ]	/* 1 value pushed */" %
                                        mnemonic)
                    else:
                        assembly.append("%s[ ]	/* %s values pushed */" %
                                        (mnemonic, nValues))
                    assembly.extend(values)
                else:
                    assembly.append("INSTR%d[ ]" % op)
                    i = i + 1
            else:
                if argBits:
                    assembly.append(
                        mnemonic + "[%s]	/* %s */" %
                        (num2binary(op - argoffset, argBits), name))
                else:
                    assembly.append(mnemonic + "[ ]	/* %s */" % name)
                i = i + 1
        self.assembly = assembly
Exemple #17
0
def bin_to_int_list(value):
    string = num2binary(value)
    string = string.replace(' ', '')  # num2binary add a space every 8 digits
    return [i for i, v in enumerate(reversed(string)) if v == "1"]
Exemple #18
0
def bin_to_int_list(value):
    string = num2binary(value)
    return [i for i, v in enumerate(reversed(string)) if v == "1"]