PcfFontFile.py 6.8 KB

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