Ejemplo n.º 1
0
def _load_font(font_path=_DEFAULT_FONT_PATH, spacing=0):
    """
    Returns font from LOADED_FONTS by name; if not loaded, loads it from file
    """
    global _LOADED_FONTS
    match_font = [font for font in _LOADED_FONTS if font['font_path'] == font_path]
    if match_font:
        return match_font[0]
    else:
        try:
            with open(font_path, 'rb') as handle:
                bdf_font = reader.read_bdf(handle)
                
            new_font = {
                'font_path': font_path,
                'font_obj': bdf_font,
                'spacing': spacing
            }
            _LOADED_FONTS.append(new_font)
            return new_font
        except:
            print('Font {} failed to load.'.format(font_path))
            if _LOADED_FONTS:
                return _LOADED_FONTS[0]
            else:
                return None
Ejemplo n.º 2
0
	def test_ignored_properties(self):
		"""
		Certain properties can't be set.

		These properties include:
		 - FACE_NAME: comes from FONT header.
		 - POINT_SIZE: comes from SIZE header.
		 - RESOLUTION_X: comes from SIZE header.
		 - RESOLUTION_Y: comes from SIZE header.
		 - PIXEL_SIZE: calculated from 3 previous properties.
		"""

		bdf_data = (
				"STARTFONT 2.1\n"
				"FONT TestFont\n"
				"SIZE 1 2 3\n"
				"FONTBOUNDINGBOX 0 0 0 0\n"
				"STARTPROPERTIES 5\n"
				"FACE_NAME \"NotATestFont\"\n"
				"POINT_SIZE 456\n"
				"PIXEL_SIZE 789\n"
				"RESOLUTION_X 012\n"
				"RESOLUTION_Y 345\n"
				"ENDPROPERTIES\n"
				"CHARS 0\n"
				"ENDFONT\n"
			)

		font = reader.read_bdf(StringIO(bdf_data))

		self.failUnlessEqual(font["FACE_NAME"], "TestFont")
		self.failUnlessEqual("%0.1f" % font["POINT_SIZE"], "1.0")
		self.failUnlessEqual(font["RESOLUTION_X"], 2)
		self.failUnlessEqual(font["RESOLUTION_Y"], 3)
		self.failIf("PIXEL_SIZE" in font)
Ejemplo n.º 3
0
def c8x8(rom, bdf, *iters):
    with open(bdf, 'rb') as fp:
        font = reader.read_bdf(fp)
        cp = font.codepoints()
        for c in itertools.chain(*iters):
            if c in cp:
                b = common.to_data(font[c], 8, 8)
                o = 249856 + c * 8
                rom[o:(o + len(b))] = b
Ejemplo n.º 4
0
def read_bdf_file(filename: str) -> Optional[Font]:
    font = None
    try:
        with open(filename, "rb") as f:
            font = reader.read_bdf(f)
    except (FileNotFoundError, StopIteration):
        pass

    return font
Ejemplo n.º 5
0
def singlebyte(rom, bdf, *iters):
    with open(bdf, 'rb') as fp:
        font = reader.read_bdf(fp)
        cp = font.codepoints()
        for c in itertools.chain(*iters):
            if c in cp:
                b = common.to_data(font[c], 8, 16)
                o = 251904 + c * 16
                rom[o:(o + len(b))] = b
Ejemplo n.º 6
0
def jisx0208(rom, bdf):
    with open(bdf, 'rb') as fp:
        font = reader.read_bdf(fp)
        cp = font.codepoints()
        for c1 in range(0x21, 0x7f):
            for c2 in range(0x21, 0x7f):
                c = c1 * 256 + c2
                i = krom_index(c1, c2)
                if c in cp and i is not None:
                    b = common.to_data(font[c], 16, 16)
                    o = i * 32
                    rom[o:(o + len(b))] = b
Ejemplo n.º 7
0
    def __init__(self, bdf_filename):
        with open(bdf_filename, 'rb') as f:
            self.bdf = reader.read_bdf(f)
        self.codeconv = codeconv(self.bdf[b'CHARSET_REGISTRY'].decode('ascii'),
                                 self.bdf[b'CHARSET_ENCODING'].decode('ascii'))
        self.width = self.bdf[self.bdf[b'DEFAULT_CHAR']].bbW * SCALE + MARGIN * 2
        self.ascent = self.bdf[b'FONT_ASCENT'] * SCALE + MARGIN
        self.descent = -self.bdf[b'FONT_DESCENT'] * SCALE - MARGIN

        # For some reasons, IDEOGRAPHIC SPACE in jiskan24-2003-1.bdf is not
        # really a whitespace. Overwrite it.
        self.bdf[0x2121].data = map(lambda _: 0, self.bdf[0x2121].data)
Ejemplo n.º 8
0
def extract(filename):
    """extract bitmap data from bdf font"""
    from bdflib.reader import read_bdf
    with open(filename, 'r') as f:
        bdf = read_bdf(f)

    # flip both x and y ordering
    font = [[int(bin(row)[2:].rjust(6, '0')[::-1], 2)
             for row in bdf[codepoint].data[::-1]]
            for codepoint in bdf.codepoints()]
    assert len(set(len(data) for data in font)) == 1

    print '\n'.join(' ' * 4 + ' '.join('%2s,' % row for row in data) for data in font)
Ejemplo n.º 9
0
def getData():
    with open("ie9x14u.bdf", "rb") as handle:
        font = reader.read_bdf(handle)
        for i, char in enumerate(alphabet):
            charData.append([])
            char = font[ord(char)].get_data()
            for c in range(0, len(char)):
                ba = hex_to_binary(char[c])
                for j in range(0, len(ba)):
                    charData[i].append(int(ba[j]))
                charData[i].append(int(0))
            while (len(charData[i]) < 126):
                charData[i].append(0)

            #charData[i].append()
            solution = [0] * 26
            solution[i] = 1
            charSolutions.append(solution)
Ejemplo n.º 10
0
    def test_jis(self):
        with open('bdf/jiskan24-2003-1.bdf', 'rb') as f:
            bdf = reader.read_bdf(f)
        cconv = charset.JIS()

        single_cp = 0
        multi_cp = 0
        for cp in bdf.codepoints():
            unicode = cconv.unicode(cp)
            if unicode is None:
                pass
            elif len(unicode) == 1:
                single_cp += 1
            else:
                multi_cp += 1

        self.assertEqual(single_cp, 8772)
        self.assertEqual(multi_cp, 25)
Ejemplo n.º 11
0
    def __init__(self):
        from bdflib.reader import read_bdf
        self.fnt = read_bdf(SkipIter(sys.stdin))
        sizes = Counter(((glyph.advance, glyph.get_bounding_box())
                         for glyph in self.fnt.glyphs))
        self.advance, self.bb = sizes.most_common()[0][0]
        self.size = self.bb[2:]
        self.codepoints = set(self.fnt.codepoints())

        rowWidth, extraBits = divmod(self.size[0], 8)
        if extraBits > 0:
            rowWidth += 1
            paddingBits = 8 - extraBits
        else:
            paddingBits = 0

        def get_data_line(value):
            return "%0*X" % (rowWidth * 2, value << paddingBits)

        self.get_data_line = get_data_line
Ejemplo n.º 12
0
	def test_fractional_point_size(self):
		"""
		We should correctly interpret and store a fractional point size.
		"""
		bdf_data = (
				"STARTFONT 2.1\n"
				"FONT TestFont\n"
				"SIZE 12.2 100 100\n"
				"FONTBOUNDINGBOX 0 0 0 0\n"
				"STARTPROPERTIES 5\n"
				"FACE_NAME \"TestFont\"\n"
				"FONT_ASCENT 0\n"
				"FONT_DESCENT 0\n"
				"RESOLUTION_X 100\n"
				"RESOLUTION_Y 100\n"
				"ENDPROPERTIES\n"
				"CHARS 0\n"
				"ENDFONT\n"
			)

		font = reader.read_bdf(StringIO(bdf_data))

		self.failUnlessEqual("%0.1f" % font["POINT_SIZE"], "12.2")
Ejemplo n.º 13
0
 def setup_font(self):
     f = open(self.fontpath)
     content = f.readlines()
     f.close()
     self.font = reader.read_bdf(iter(content))
Ejemplo n.º 14
0
def hex_to_str(num):
    s = ""
    for i in range(0, 8):
        if (num & (0x80 >> i)):
            s += "X"
        else:
            s += "_"
    return s


parser = argparse.ArgumentParser()
parser.add_argument('bdfin')
parser.add_argument('hexout')
args = parser.parse_args()
font = reader.read_bdf(open(args.bdfin, 'rb'))

fontbytes = []
for idx in range(0, 256):
    print("char 0x{:02x} {}".format(idx, idx))
    try:
        glyph = font[idx]
    except KeyError:
        print("(undefined in font)")
        for i in range(0, 8):
            print("    {},".format(hex_to_str(0xff)))
        continue

    (left, bottom, width, height) = glyph.get_bounding_box()

    reversed_data = []
Ejemplo n.º 15
0
        # get the bits in each line
        glh = int(gl, 16)
        bits = bin(glh)[2:]
        double_bits = []
        for bit in bits:
            # output two bits for each bit in the line
            double_bits.append(bit)
            double_bits.append(bit)
        double_bits = ''.join(double_bits)
        double_glh = int(double_bits, 2)
        double_gl = hex(double_glh)[2:].upper()
        # must 0-pad to two times the length of the original lines
        double_gl = "0" * (len(gl) * 2 - len(double_gl)) + double_gl
        # output the line two times
        ret.append(double_gl)
        ret.append(double_gl)
    return ret


bdf = reader.read_bdf(sys.stdin)

double_bdf = model.Font(bdf['FACE_NAME'], bdf['POINT_SIZE'],
                        bdf['RESOLUTION_X'], bdf['RESOLUTION_Y'])

for g in bdf.glyphs_by_codepoint.values():
    double_bdf.new_glyph_from_data(g.name, double_glyph_data(g.get_data()),
                                   g.bbX * 2, g.bbY * 2, g.bbW * 2, g.bbH * 2,
                                   g.advance * 2, g.codepoint)

writer.write_bdf(double_bdf, sys.stdout)
Ejemplo n.º 16
0
Archivo: bdf.py Proyecto: dmd/clack
 def __init__(self, fontfilename):
     self.bdffont = reader.read_bdf(open(fontfilename, 'rb'))
Ejemplo n.º 17
0
def OpenBDF(path):
    with open(path, "rb") as handle:
        return reader.read_bdf(handle)
Ejemplo n.º 18
0
if len(sys.argv) < 2:
    sys.stderr.write ("usage: %s fontfile.bdf\n" % sys.argv[0])
    sys.exit (1)

fname = sys.argv [1]
rx = re.search (r"^(.*)\.[Bb][Dd][Ff]$", fname)
if not rx:
    sys.stderr.write ("filename '%s' does not looks as bdf-file\n" % fname)
    sys.exit (1)
name = rx.group (1)
outname = name + ".png"
metaname = name + ".meta"

print "load font from file %s" % fname
font = reader.read_bdf (file (fname, "rt"))

if colored:
  if big_palette:
      print "create palette"
      palette = [(0x00,0x00,0x00,0x00),]
      for r in nums:
          for g in nums:
              for b in nums:
                  palette.append((r, g, b, 0xFF))
  else:
      palette = [(0x00,0x00,0x00,0x00),
                 (0x00,0x00,0x00,0xFF), 
                 (0x00,0x00,0x7F,0xFF), 
                 (0x00,0x7F,0x00,0xFF), 
                 (0x00,0x7F,0x7F,0xFF), 
Ejemplo n.º 19
0

def _translate(data, dxdy):
    dx, dy = dxdy
    if dx > 0:
        data = [row >> dx for row in data]
    if dx < 0:
        data = [row << -dx for row in data]
    if dy > 0:
        dy -= len(data)
    if dy < 0:
        data = data[-dy:] + data[:-dy]
    return data


if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        bdf = reader.read_bdf(f)

    out = model.Font('vertical', bdf['POINT_SIZE'], bdf['RESOLUTION_X'],
                     bdf['RESOLUTION_Y'])

    for cp in bdf.codepoints():
        vg = vertical_glyph(bdf[cp])
        if vg is None:
            continue
        out.glyphs.append(vg)
        out.glyphs_by_codepoint[cp] = vg

    writer.write_bdf(out, sys.stdout)
Ejemplo n.º 20
0
def hex_to_str(num):
    s = ""
    for i in range(0, 8):
        if (num & (0x80 >> i)):
            s += "X"
        else:
            s += "_"
    return s


print("// allow human readable font files")
for i in range(256):
    print("#define {} 0x{:02x}".format(hex_to_str(i), i))

with open("cpufont", "rb") as f:
    font = reader.read_bdf(f)

print("static const unsigned char __font_bitmap__[] = {")
for idx in range(0, 256):
    print("// char 0x{:02x} {}".format(idx, idx))
    try:
        glyph = font[idx]
    except KeyError:
        print("// (undefined in font)")
        for i in range(0, 8):
            print("    {},".format(hex_to_str(0xff)))
        continue

    (left, bottom, width, height) = glyph.get_bounding_box()

    reversed_data = []
def read_bdf_font(filename):
    with open(filename, "rb") as handle:
        font = reader.read_bdf(handle)
        return font
Ejemplo n.º 22
0
	def test_basic_operation(self):
		testFontData = StringIO(SAMPLE_FONT)
		testFont = reader.read_bdf(testFontData)

		self._check_font(testFont)
Ejemplo n.º 23
0
#-------------------------------------------------------------------------------
# font download

fontname = sys.argv[1]
filename = "%s.bdf" % fontname
if not os.path.isfile(filename):
    response = urllib.urlopen(
        'https://raw.githubusercontent.com/olikraus/u8glib/master/tools/font/bdf/%s'
        % filename)
    src_bdf = response.read()
else:
    with open(filename, 'r') as bdf_file:
        src_bdf = bdf_file.read()
        src_bdf.close()

font = reader.read_bdf(iter(src_bdf.splitlines()))


def asc(s):
    return ord(s.decode('utf-8').encode('iso-8859-1'))


#-------------------------------------------------------------------------------
# copy one glyph over another


def replace(t, f):
    fr = font[asc(f)]
    to = font[asc(t)]
    #font.glyphs_by_codepoint[to] = font.glyphs_by_codepoint[fr]
    to.name = fr.name
Ejemplo n.º 24
0
mode = sys.argv[2]

#-------------------------------------------------------------------------------
# font download

fontname = sys.argv[1]
filename = "%s.bdf" % fontname
if not os.path.isfile(filename):
    response = urllib.urlopen('https://raw.githubusercontent.com/olikraus/u8glib/master/tools/font/bdf/%s' % filename)
    src_bdf = response.read()
else:
    with open(filename, 'r') as bdf_file:
        src_bdf=bdf_file.read()
        src_bdf.close()

font = reader.read_bdf(iter(src_bdf.splitlines()))

def asc(s):
    return ord(s.decode('utf-8').encode('iso-8859-1'))

#-------------------------------------------------------------------------------
# copy one glyph over another

def replace(t, f):
    fr = font[asc(f)]
    to = font[asc(t)]
    #font.glyphs_by_codepoint[to] = font.glyphs_by_codepoint[fr]
    to.name = fr.name
    to.bbX = fr.bbX
    to.bbY = fr.bbY
    to.bbW = fr.bbW
Ejemplo n.º 25
0
from curses import color_content
from bdflib import reader
from setup import matrix, settings
from rgbmatrix import graphics
import time
import numpy as np

with open('./fonts/tom-thumb.bdf', 'rb') as filehandle:
    font = reader.read_bdf(filehandle)

color_matrix = np.ndarray((matrix.width, matrix.height, 3), dtype=int)


# Creates a linear color gradient
def create_color_grad(cm, start_color, end_color):
    # Initially this is assuming moving from the far left of the grid to the right. Angles will be added later
    width, height, _ = cm.shape
    cm_copy = np.copy(cm)

    for i in range(width):
        new_color = ((end_color - start_color) * (i / width) +
                     start_color).astype(int)
        cm_copy[i, :] = new_color

    return cm_copy


def draw_glyph(canvas, x, y, cm, font, glyph):
    for i, row in enumerate(glyph.iter_pixels()):
        for j, pixel, in enumerate(row):
            pixel_x = x + j
Ejemplo n.º 26
0
 def setup_font(self):
     f = open(self.fontpath)
     content = f.readlines()
     f.close()
     self.font = reader.read_bdf(iter(content))
Ejemplo n.º 27
0
def _load_bdf_font(path):
    with open(path, 'rb') as f:
        font = bdfreader.read_bdf(f)
        #ascent, descent = font[b'FONT_ASCENT'], font[b'FONT_DESCENT']
        for glyph in font.glyphs():
            bitmap = glyph.bitmap
Ejemplo n.º 28
0
def cjkFont():
    from bdflib import reader as bdfreader

    with open(os.path.join(HERE, "wqy-bitmapsong/wenquanyi_9pt.bdf"),
              "rb") as f:
        return bdfreader.read_bdf(f)
Ejemplo n.º 29
0
#!/usr/bin/env python3

from bdflib import reader
from sys import argv
import struct

if len(argv) != 3:
    print("usage: convert_font.py <input> <output>")
    exit(-1)

with open(argv[1], "rb") as handle:
    font = reader.read_bdf(handle)

# this part sucks. bdflib doesn't provide this information
height = 0
width = 0
with open(argv[1], "rb") as handle:
    for line in handle:
        if line.startswith(b"FONTBOUNDINGBOX"):
            parts = line.split(b" ")
            height = int(parts[2])
            width = int(parts[2])

MAGIC = 0x464f4e54

cmap = struct.pack("")
dmap = struct.pack("")

count = len(font.codepoints())
i = 0
for cp in font.codepoints():
Ejemplo n.º 30
0
def cjk_font() -> Font:
    with open(os.path.join(HERE, "wqy-bitmapsong/wenquanyi_9pt.bdf"),
              "rb") as f:
        return bdfreader.read_bdf(f)
Ejemplo n.º 31
0
def read_bdf_font(font_filename):
    font_path = pathlib.Path(__file__).parents[0] / font_filename
    with font_path.open("rb") as f:
        return reader.read_bdf(f)
Ejemplo n.º 32
0
	def load_font(self, path):
		logging.debug('loading font {}'.format(path))
		with open(path, 'rb') as filehandle:
			font = reader.read_bdf(filehandle)
		return font
Ejemplo n.º 33
0
import sys
import fontTables
import re
import subprocess
from bdflib import reader as bdfreader

HERE = os.path.dirname(__file__)

try:
    to_unicode = unicode
except NameError:
    to_unicode = str

with open(os.path.join(HERE, "wqy-bitmapsong/wenquanyi_9pt.bdf"),
          "rb") as handle:
    cjkFont = bdfreader.read_bdf(handle)


def log(message):
    print(message, file=sys.stdout)


# Loading a single JSON file
def loadJson(fileName, skipFirstLine):
    with io.open(fileName, mode="r", encoding="utf-8") as f:
        if skipFirstLine:
            f.readline()

        obj = json.loads(f.read())

    return obj