Aluode/PerceptionLabPortable
0
1#
2# THIS IS WORK IN PROGRESS
3#
4# The Python Imaging Library
5# $Id$
6#
7# portable compiled font file parser
8#
9# history:
10# 1997-08-19 fl created
11# 2003-09-13 fl fixed loading of unicode fonts
12#
13# Copyright (c) 1997-2003 by Secret Labs AB.
14# Copyright (c) 1997-2003 by Fredrik Lundh.
15#
16# See the README file for information on usage and redistribution.
17#
18from __future__ import annotations
19
20import io
21
22from . import FontFile, Image
23from ._binary import i8
24from ._binary import i16be as b16
25from ._binary import i16le as l16
26from ._binary import i32be as b32
27from ._binary import i32le as l32
28
29TYPE_CHECKING = False
30if TYPE_CHECKING:
31 from collections.abc import Callable
32 from typing import BinaryIO
33
34# --------------------------------------------------------------------
35# declarations
36
37PCF_MAGIC = 0x70636601 # "\x01fcp"
38
39PCF_PROPERTIES = 1 << 0
40PCF_ACCELERATORS = 1 << 1
41PCF_METRICS = 1 << 2
42PCF_BITMAPS = 1 << 3
43PCF_INK_METRICS = 1 << 4
44PCF_BDF_ENCODINGS = 1 << 5
45PCF_SWIDTHS = 1 << 6
46PCF_GLYPH_NAMES = 1 << 7
47PCF_BDF_ACCELERATORS = 1 << 8
48
49BYTES_PER_ROW: list[Callable[[int], int]] = [
50 lambda bits: ((bits + 7) >> 3),
51 lambda bits: ((bits + 15) >> 3) & ~1,
52 lambda bits: ((bits + 31) >> 3) & ~3,
53 lambda bits: ((bits + 63) >> 3) & ~7,
54]
55
56
57def sz(s: bytes, o: int) -> bytes:
58 return s[o : s.index(b"\0", o)]
59
60
61class PcfFontFile(FontFile.FontFile):
62 """Font file plugin for the X11 PCF format."""
63
64 name = "name"
65
66 def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
67 self.charset_encoding = charset_encoding
68
69 magic = l32(fp.read(4))
70 if magic != PCF_MAGIC:
71 msg = "not a PCF file"
72 raise SyntaxError(msg)
73
74 super().__init__()
75
76 count = l32(fp.read(4))
77 self.toc = {}
78 for i in range(count):
79 type = l32(fp.read(4))
80 self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
81
82 self.fp = fp
83
84 self.info = self._load_properties()
85
86 metrics = self._load_metrics()
87 bitmaps = self._load_bitmaps(metrics)
88 encoding = self._load_encoding()
89
90 #
91 # create glyph structure
92
93 for ch, ix in enumerate(encoding):
94 if ix is not None:
95 (
96 xsize,
97 ysize,
98 left,
99 right,
100 width,
101 ascent,
102 descent,
103 attributes,
104 ) = metrics[ix]
105 self.glyph[ch] = (
106 (width, 0),
107 (left, descent - ysize, xsize + left, descent),
108 (0, 0, xsize, ysize),
109 bitmaps[ix],
110 )
111
112 def _getformat(
113 self, tag: int
114 ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
115 format, size, offset = self.toc[tag]
116
117 fp = self.fp
118 fp.seek(offset)
119
120 format = l32(fp.read(4))
121
122 if format & 4:
123 i16, i32 = b16, b32
124 else:
125 i16, i32 = l16, l32
126
127 return fp, format, i16, i32
128
129 def _load_properties(self) -> dict[bytes, bytes | int]:
130 #
131 # font properties
132
133 properties = {}
134
135 fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
136
137 nprops = i32(fp.read(4))
138
139 # read property description
140 p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
141
142 if nprops & 3:
143 fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
144
145 data = fp.read(i32(fp.read(4)))
146
147 for k, s, v in p:
148 property_value: bytes | int = sz(data, v) if s else v
149 properties[sz(data, k)] = property_value
150
151 return properties
152
153 def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
154 #
155 # font metrics
156
157 metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
158
159 fp, format, i16, i32 = self._getformat(PCF_METRICS)
160
161 append = metrics.append
162
163 if (format & 0xFF00) == 0x100:
164 # "compressed" metrics
165 for i in range(i16(fp.read(2))):
166 left = i8(fp.read(1)) - 128
167 right = i8(fp.read(1)) - 128
168 width = i8(fp.read(1)) - 128
169 ascent = i8(fp.read(1)) - 128
170 descent = i8(fp.read(1)) - 128
171 xsize = right - left
172 ysize = ascent + descent
173 append((xsize, ysize, left, right, width, ascent, descent, 0))
174
175 else:
176 # "jumbo" metrics
177 for i in range(i32(fp.read(4))):
178 left = i16(fp.read(2))
179 right = i16(fp.read(2))
180 width = i16(fp.read(2))
181 ascent = i16(fp.read(2))
182 descent = i16(fp.read(2))
183 attributes = i16(fp.read(2))
184 xsize = right - left
185 ysize = ascent + descent
186 append((xsize, ysize, left, right, width, ascent, descent, attributes))
187
188 return metrics
189
190 def _load_bitmaps(
191 self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
192 ) -> list[Image.Image]:
193 #
194 # bitmap data
195
196 fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
197
198 nbitmaps = i32(fp.read(4))
199
200 if nbitmaps != len(metrics):
201 msg = "Wrong number of bitmaps"
202 raise OSError(msg)
203
204 offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
205
206 bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
207
208 # byteorder = format & 4 # non-zero => MSB
209 bitorder = format & 8 # non-zero => MSB
210 padindex = format & 3
211
212 bitmapsize = bitmap_sizes[padindex]
213 offsets.append(bitmapsize)
214
215 data = fp.read(bitmapsize)
216
217 pad = BYTES_PER_ROW[padindex]
218 mode = "1;R"
219 if bitorder:
220 mode = "1"
221
222 bitmaps = []
223 for i in range(nbitmaps):
224 xsize, ysize = metrics[i][:2]
225 b, e = offsets[i : i + 2]
226 bitmaps.append(
227 Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
228 )
229
230 return bitmaps
231
232 def _load_encoding(self) -> list[int | None]:
233 fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
234
235 first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
236 first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
237
238 i16(fp.read(2)) # default
239
240 nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
241
242 # map character code to bitmap index
243 encoding: list[int | None] = [None] * min(256, nencoding)
244
245 encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
246
247 for i in range(first_col, len(encoding)):
248 try:
249 encoding_offset = encoding_offsets[
250 ord(bytearray([i]).decode(self.charset_encoding))
251 ]
252 if encoding_offset != 0xFFFF:
253 encoding[i] = encoding_offset
254 except UnicodeDecodeError:
255 # character is not supported in selected encoding
256 pass
257
258 return encoding
259 