-
Notifications
You must be signed in to change notification settings - Fork 70
/
c_to_python_font.py
executable file
·164 lines (146 loc) · 5.4 KB
/
c_to_python_font.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Released under the MIT License (MIT). See LICENSE.
# Copyright (c) 2022 Peter Hinch
import sys
from font_to_py import ByteWriter, var_write, write_func, STR02, STR02H
STR01 = """# Code generated by c_to_python_font.py.
# Char set: {}
# Cmd: {}
version = '0.10'
"""
class Glyph:
dstart = 0 # Start index of next glyph
def __init__(self):
self.width = 0
self.height = 0
def populate(self, fn, data, idx):
try:
with open(fn, "r") as f:
s = f.readline()
elements = s.split(" ")
if elements[1].endswith("width"):
self.width = int(elements[2])
data.extend((self.width).to_bytes(2, 'little'))
else:
return False
s = f.readline()
elements = s.split(" ")
if elements[1].endswith("height"):
self.height = int(elements[2])
else:
return False
s = f.readline()
if not s.startswith("static"):
return False
while s := f.readline():
if (lb := s.find("}")) != -1:
s = s[:lb] # Strip trailing };
p = s.strip().split(',')
if not p[-1]:
p = p[: -1]
z = [int(x, 16) for x in p]
data.extend(bytearray(z))
# index points to start of current data block
idx.extend((Glyph.dstart).to_bytes(2, 'little'))
Glyph.dstart += ((self.width - 1)//8 + 1) * self.height + 2
except OSError:
return False
return True
class Font:
def __init__(self):
self.glyphs = []
self.height = 0
self.max_width = 0
self.data = bytearray()
self.index = bytearray()
def __getitem__(self, glyph_index):
return self.glyphs[glyph_index]
def populate(self, filename="filenames.txt"):
try:
with open(filename, "r") as f:
while fn := f.readline().strip(): # Get current C file
if (lc := fn.find("#")) != -1:
if (fn := fn[:lc].strip()) == "":
continue
g = Glyph()
if g.populate(fn, self.data, self.index):
if ht := self.height:
if ht != g.height:
print(f"Fatal: file {fn} height is {g.height} while font height is {ht}")
return False
else:
self.height = g.height
self.glyphs.append(g)
self.max_width = max(self.max_width, g.width)
else:
print('Failed to read', fn)
return False
except OSError:
print("Failed to read", filename)
return False
return True
def output(self, stream):
minchar = ord("A")
nglyphs = len(self.glyphs) - 1 # Number less default glyph
maxchar = minchar + nglyphs - 1
st = ""
for z in range(nglyphs):
st = "".join((st, chr(minchar + z)))
cl = ' '.join(sys.argv)
stream.write(STR01.format(st, cl))
write_func(stream, 'height', self.height)
write_func(stream, 'baseline', self.height)
write_func(stream, 'max_width', self.max_width)
write_func(stream, 'hmap', True)
write_func(stream, 'reverse', True) # ????
write_func(stream, 'monospaced', False)
write_func(stream, 'min_ch', minchar)
write_func(stream, 'max_ch', maxchar)
bw_font = ByteWriter(stream, '_font')
bw_font.odata(self.data)
bw_font.eot()
bw_index = ByteWriter(stream, '_index')
bw_index.odata(self.index)
bw_index.eot()
stream.write(STR02.format(minchar, maxchar))
stream.write(STR02H.format(self.height))
def make_font(infile="filenames.txt", outfile="icofont.py"):
try:
with open(outfile, "w") as f:
font = Font()
if font.populate(infile):
font.output(f)
else:
return # Failed
except OSError:
print(f"Failed to open {outfile} for writing.")
print(f"{outfile} successfully written.")
def version_check():
n = sys.implementation.name
v = sys.implementation.version
if n == "cpython":
if v[0] == 3:
return v[1] >= 8
return v[0] > 3
return False # Requires CPython
usage = """Convert a set of C bitmaps to a Python font file. Usage:
c_to_python_font.py [infile [outfile]]
infile contains a list of C bitmap files, one per line.
outfile is the name of the output Python font.
Default args:
infile: filenames.txt
outfile: icofont.py
e.g.
$ ./c_to_python_font.py my_file_list.txt my_font.py
"""
if __name__ == "__main__":
a = sys.argv
if len(a) >= 2 and a[1] in ("--help", "-h", "help"):
print(usage)
elif not version_check():
print("This script requires Python 3.8 or above.")
else:
infile = a[1] if len(a) >= 2 else "filenames.txt"
outfile = a[2] if len(a) >= 3 else "icofont.py"
make_font(infile, outfile)