glyph.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import pathlib
  2. import lxml.etree as etree
  3. from validate.svg import isSVGValid
  4. from validate.codepoints import testZWJSanity, testRestrictedCodepoints
  5. from transform.svg import compensateSVG
  6. # glyph.py
  7. # -------------------------------
  8. #
  9. # The entire process of importing, compiling and validating glyphs.
  10. def simpleHex(int):
  11. """
  12. returns a hexadecimal number as a string without the '0x' prefix.
  13. """
  14. return f"{int:x}"
  15. class Img:
  16. """
  17. Class representing a single glyph image.
  18. """
  19. def __init__(self, type, strike, m, path, nusc=False, afsc=False):
  20. if not path.exists():
  21. raise ValueError(f"Image object couldn't be built because the path given ('{path}') doesn't exist.'")
  22. self.type = type
  23. self.strike = strike
  24. if type == "svg":
  25. # try parsing the SVG
  26. try:
  27. svgImage = etree.parse(path.as_uri())
  28. except ValueError:
  29. raise ValueError(f"Image object couldn't be built because there was a problem in retrieving or processing the image '{path}'. {e}")
  30. # test for SVG compatibility.
  31. try:
  32. isSVGValid(svgImage, nusc)
  33. except ValueError as e:
  34. raise ValueError(f"Image object couldn't be built due to compatibility issues with the SVG image '{path}'. → {e}")
  35. # do all the compensation stuff on it and make it the data.
  36. self.data = compensateSVG(svgImage, m, afsc)
  37. if type == "png":
  38. self.path = path
  39. # take the PNG and use it for later.
  40. def getHexDump(self):
  41. """
  42. Loads and returns a hexdump of the image object's file on-demand.
  43. """
  44. if self.type is "svg":
  45. raise ValueError(f"Hexdump of an SVG image was attempted. You can't hexdump SVG images in forc.")
  46. try:
  47. with open(self.path, "rb") as read_file:
  48. return read_file.read().hex()
  49. except ValueError as e:
  50. raise ValueError(f"Image object {self} couldn't be hexdumped. → {e}")
  51. def getBytes(self):
  52. """
  53. Loads and returns a byte dump of the image object's file on-demand.
  54. """
  55. try:
  56. with open(self.path, "rb") as read_file:
  57. return read_file.read()
  58. except ValueError as e:
  59. raise ValueError(f"Bytes couldn't be retrieved from the file of image object {self}. → {e}")
  60. def __str__(self):
  61. return f"img: [{self.type}-{str(self.strike)}] {self.path.name}|"
  62. def __repr__(self):
  63. return str(self)
  64. class CodepointSeq:
  65. """
  66. Class representing a sequence of Unicode codepoints.
  67. """
  68. def __init__(self, sequence, delim, userInput=True):
  69. # create a suitable structure based on the input type.
  70. # ------------------------------------------------------
  71. if type(sequence) is str:
  72. try:
  73. seq = [int(c, 16) for c in sequence.split(delim)]
  74. except ValueError as e:
  75. raise ValueError("Codepoint sequence isn't named correctly. Make sure your codepoint sequence consists only of hexadecimal numbers and are separated by the right delimiter.")
  76. elif type(sequence) is list:
  77. try:
  78. seq = [int(c, 16) for c in sequence]
  79. except ValueError as e:
  80. raise ValueError("Codepoint sequence isn't named correctly. Make sure each component of your list is a hexadecimal number.")
  81. # handle fe0f
  82. # ------------------------------------------------------
  83. if len(seq) > 1:
  84. self.seq = [c for c in seq if c != 0xfe0f]
  85. self.vs16 = 0xfe0f in seq and len(self.seq) == 1
  86. else:
  87. self.seq = seq
  88. self.vs16 = False
  89. # test the codepoints
  90. # # ------------------------------------------------------
  91. try:
  92. if userInput: testRestrictedCodepoints(self.seq)
  93. testZWJSanity(self.seq)
  94. except ValueError as e:
  95. raise ValueError(f"'{sequence}' is not a valid codepoint sequence. → {e}")
  96. def name(self):
  97. """
  98. Generates a TTX 'name' for the glyph based on it's codepoint sequence.
  99. The way this is named is important and it makes the TTX compiler happy.
  100. DO NOT CHANGE IT!
  101. eg. ['1f44d', '101601']
  102. -> u1f44d_101601
  103. """
  104. return 'u' + '_'.join(map(simpleHex, self.seq))
  105. def __str__(self):
  106. return '-'.join(map(simpleHex, self.seq))
  107. def __repr__(self):
  108. return str(self)
  109. def __eq__(self, other):
  110. return self.seq == other.seq
  111. def __lt__(self, other):
  112. """
  113. Sorts by codepoint sequence length, then the value of the first codepoint.
  114. This is incredibly crucial to the functioning of font compilation because
  115. (once a list of these are sorted) it determines the glyphID in the
  116. glyphOrder table.
  117. Single codepoint seqs have to be first and they have to be ordered
  118. lowest to highest because if they aren't, their glyphID can be out
  119. of range of low-bit cmap subtables. If glyphIDs are out of range of
  120. cmap subtables like this, the font won't compile.
  121. """
  122. if len(self.seq) < len(other.seq):
  123. return True
  124. elif len(self.seq) == len(other.seq):
  125. return self.seq < other.seq
  126. return False
  127. def __len__(self):
  128. return len(self.seq)
  129. class Glyph:
  130. """
  131. Class representing a font glyph.
  132. """
  133. def __init__(self, codepoints, imgDict=None, alias=None, delim="-", userInput=True):
  134. try:
  135. self.codepoints = CodepointSeq(codepoints, delim, userInput=userInput)
  136. except ValueError as e:
  137. raise ValueError(f"A codepoint sequence object for ('{codepoints}') couldn't be created. → {e}")
  138. if alias is None:
  139. self.alias = None
  140. else:
  141. if imgDict:
  142. raise ValueError(f"Tried to make glyph object '{name}' but it has both an alias AND an image. It can't have both.")
  143. else:
  144. try:
  145. self.alias = CodepointSeq(alias, delim)
  146. self.glyphType = "alias"
  147. except ValueError as e:
  148. raise Exception(f"The alias destination ('{alias}') for {self.codepoints} is not named correctly. → {e}")
  149. self.imgDict = imgDict
  150. if imgDict is not None:
  151. self.glyphType = "img"
  152. if imgDict is None and alias is None:
  153. self.glyphType = "empty"
  154. # the way that glyph classes get compared/equated is
  155. # simply by their codepointseq.
  156. def __str__(self):
  157. return str(self.codepoints)
  158. def __repr__(self):
  159. return str(self.codepoints) + f" - {self.glyphType}"
  160. def __eq__(self, other):
  161. return self.codepoints == other.codepoints
  162. def __lt__(self, other):
  163. return self.codepoints < other.codepoints
  164. def __len__(self):
  165. return len(self.codepoints)
  166. def name(self):
  167. return self.codepoints.name()