PcfFontFile.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. #
  18. from __future__ import annotations
  19. import io
  20. from typing import BinaryIO, Callable
  21. from . import FontFile, Image
  22. from ._binary import i8
  23. from ._binary import i16be as b16
  24. from ._binary import i16le as l16
  25. from ._binary import i32be as b32
  26. from ._binary import i32le as l32
  27. # --------------------------------------------------------------------
  28. # declarations
  29. PCF_MAGIC = 0x70636601 # "\x01fcp"
  30. PCF_PROPERTIES = 1 << 0
  31. PCF_ACCELERATORS = 1 << 1
  32. PCF_METRICS = 1 << 2
  33. PCF_BITMAPS = 1 << 3
  34. PCF_INK_METRICS = 1 << 4
  35. PCF_BDF_ENCODINGS = 1 << 5
  36. PCF_SWIDTHS = 1 << 6
  37. PCF_GLYPH_NAMES = 1 << 7
  38. PCF_BDF_ACCELERATORS = 1 << 8
  39. BYTES_PER_ROW: list[Callable[[int], int]] = [
  40. lambda bits: ((bits + 7) >> 3),
  41. lambda bits: ((bits + 15) >> 3) & ~1,
  42. lambda bits: ((bits + 31) >> 3) & ~3,
  43. lambda bits: ((bits + 63) >> 3) & ~7,
  44. ]
  45. def sz(s: bytes, o: int) -> bytes:
  46. return s[o : s.index(b"\0", o)]
  47. class PcfFontFile(FontFile.FontFile):
  48. """Font file plugin for the X11 PCF format."""
  49. name = "name"
  50. def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
  51. self.charset_encoding = charset_encoding
  52. magic = l32(fp.read(4))
  53. if magic != PCF_MAGIC:
  54. msg = "not a PCF file"
  55. raise SyntaxError(msg)
  56. super().__init__()
  57. count = l32(fp.read(4))
  58. self.toc = {}
  59. for i in range(count):
  60. type = l32(fp.read(4))
  61. self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
  62. self.fp = fp
  63. self.info = self._load_properties()
  64. metrics = self._load_metrics()
  65. bitmaps = self._load_bitmaps(metrics)
  66. encoding = self._load_encoding()
  67. #
  68. # create glyph structure
  69. for ch, ix in enumerate(encoding):
  70. if ix is not None:
  71. (
  72. xsize,
  73. ysize,
  74. left,
  75. right,
  76. width,
  77. ascent,
  78. descent,
  79. attributes,
  80. ) = metrics[ix]
  81. self.glyph[ch] = (
  82. (width, 0),
  83. (left, descent - ysize, xsize + left, descent),
  84. (0, 0, xsize, ysize),
  85. bitmaps[ix],
  86. )
  87. def _getformat(
  88. self, tag: int
  89. ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
  90. format, size, offset = self.toc[tag]
  91. fp = self.fp
  92. fp.seek(offset)
  93. format = l32(fp.read(4))
  94. if format & 4:
  95. i16, i32 = b16, b32
  96. else:
  97. i16, i32 = l16, l32
  98. return fp, format, i16, i32
  99. def _load_properties(self) -> dict[bytes, bytes | int]:
  100. #
  101. # font properties
  102. properties = {}
  103. fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
  104. nprops = i32(fp.read(4))
  105. # read property description
  106. p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
  107. if nprops & 3:
  108. fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
  109. data = fp.read(i32(fp.read(4)))
  110. for k, s, v in p:
  111. property_value: bytes | int = sz(data, v) if s else v
  112. properties[sz(data, k)] = property_value
  113. return properties
  114. def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
  115. #
  116. # font metrics
  117. metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
  118. fp, format, i16, i32 = self._getformat(PCF_METRICS)
  119. append = metrics.append
  120. if (format & 0xFF00) == 0x100:
  121. # "compressed" metrics
  122. for i in range(i16(fp.read(2))):
  123. left = i8(fp.read(1)) - 128
  124. right = i8(fp.read(1)) - 128
  125. width = i8(fp.read(1)) - 128
  126. ascent = i8(fp.read(1)) - 128
  127. descent = i8(fp.read(1)) - 128
  128. xsize = right - left
  129. ysize = ascent + descent
  130. append((xsize, ysize, left, right, width, ascent, descent, 0))
  131. else:
  132. # "jumbo" metrics
  133. for i in range(i32(fp.read(4))):
  134. left = i16(fp.read(2))
  135. right = i16(fp.read(2))
  136. width = i16(fp.read(2))
  137. ascent = i16(fp.read(2))
  138. descent = i16(fp.read(2))
  139. attributes = i16(fp.read(2))
  140. xsize = right - left
  141. ysize = ascent + descent
  142. append((xsize, ysize, left, right, width, ascent, descent, attributes))
  143. return metrics
  144. def _load_bitmaps(
  145. self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
  146. ) -> list[Image.Image]:
  147. #
  148. # bitmap data
  149. fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
  150. nbitmaps = i32(fp.read(4))
  151. if nbitmaps != len(metrics):
  152. msg = "Wrong number of bitmaps"
  153. raise OSError(msg)
  154. offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
  155. bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
  156. # byteorder = format & 4 # non-zero => MSB
  157. bitorder = format & 8 # non-zero => MSB
  158. padindex = format & 3
  159. bitmapsize = bitmap_sizes[padindex]
  160. offsets.append(bitmapsize)
  161. data = fp.read(bitmapsize)
  162. pad = BYTES_PER_ROW[padindex]
  163. mode = "1;R"
  164. if bitorder:
  165. mode = "1"
  166. bitmaps = []
  167. for i in range(nbitmaps):
  168. xsize, ysize = metrics[i][:2]
  169. b, e = offsets[i : i + 2]
  170. bitmaps.append(
  171. Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
  172. )
  173. return bitmaps
  174. def _load_encoding(self) -> list[int | None]:
  175. fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
  176. first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
  177. first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
  178. i16(fp.read(2)) # default
  179. nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
  180. # map character code to bitmap index
  181. encoding: list[int | None] = [None] * min(256, nencoding)
  182. encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
  183. for i in range(first_col, len(encoding)):
  184. try:
  185. encoding_offset = encoding_offsets[
  186. ord(bytearray([i]).decode(self.charset_encoding))
  187. ]
  188. if encoding_offset != 0xFFFF:
  189. encoding[i] = encoding_offset
  190. except UnicodeDecodeError:
  191. # character is not supported in selected encoding
  192. pass
  193. return encoding