converters.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. from __future__ import annotations
  2. from typing import Mapping, Any
  3. from collections.abc import Container
  4. from fontTools.annotations import KerningNested
  5. """
  6. Functions for converting UFO1 or UFO2 files into UFO3 format.
  7. Currently provides functionality for converting kerning rules
  8. and kerning groups. Conversion is only supported _from_ UFO1
  9. or UFO2, and _to_ UFO3.
  10. """
  11. # adapted from the UFO spec
  12. def convertUFO1OrUFO2KerningToUFO3Kerning(
  13. kerning: KerningNested, groups: dict[str, list[str]], glyphSet: Container[str] = ()
  14. ) -> tuple[KerningNested, dict[str, list[str]], dict[str, dict[str, str]]]:
  15. """Convert kerning data in UFO1 or UFO2 syntax into UFO3 syntax.
  16. Args:
  17. kerning:
  18. A dictionary containing the kerning rules defined in
  19. the UFO font, as used in :class:`.UFOReader` objects.
  20. groups:
  21. A dictionary containing the groups defined in the UFO
  22. font, as used in :class:`.UFOReader` objects.
  23. glyphSet:
  24. Optional; a set of glyph objects to skip (default: None).
  25. Returns:
  26. 1. A dictionary representing the converted kerning data.
  27. 2. A copy of the groups dictionary, with all groups renamed to UFO3 syntax.
  28. 3. A dictionary containing the mapping of old group names to new group names.
  29. """
  30. # gather known kerning groups based on the prefixes
  31. firstReferencedGroups, secondReferencedGroups = findKnownKerningGroups(groups)
  32. # Make lists of groups referenced in kerning pairs.
  33. for first, seconds in list(kerning.items()):
  34. if first in groups and first not in glyphSet:
  35. if not first.startswith("public.kern1."):
  36. firstReferencedGroups.add(first)
  37. for second in list(seconds.keys()):
  38. if second in groups and second not in glyphSet:
  39. if not second.startswith("public.kern2."):
  40. secondReferencedGroups.add(second)
  41. # Create new names for these groups.
  42. firstRenamedGroups: dict[str, str] = {}
  43. for first in firstReferencedGroups:
  44. # Make a list of existing group names.
  45. existingGroupNames = list(groups.keys()) + list(firstRenamedGroups.keys())
  46. # Remove the old prefix from the name
  47. newName = first.replace("@MMK_L_", "")
  48. # Add the new prefix to the name.
  49. newName = "public.kern1." + newName
  50. # Make a unique group name.
  51. newName = makeUniqueGroupName(newName, existingGroupNames)
  52. # Store for use later.
  53. firstRenamedGroups[first] = newName
  54. secondRenamedGroups: dict[str, str] = {}
  55. for second in secondReferencedGroups:
  56. # Make a list of existing group names.
  57. existingGroupNames = list(groups.keys()) + list(secondRenamedGroups.keys())
  58. # Remove the old prefix from the name
  59. newName = second.replace("@MMK_R_", "")
  60. # Add the new prefix to the name.
  61. newName = "public.kern2." + newName
  62. # Make a unique group name.
  63. newName = makeUniqueGroupName(newName, existingGroupNames)
  64. # Store for use later.
  65. secondRenamedGroups[second] = newName
  66. # Populate the new group names into the kerning dictionary as needed.
  67. newKerning = {}
  68. for first, seconds in list(kerning.items()):
  69. first = firstRenamedGroups.get(first, first)
  70. newSeconds = {}
  71. for second, value in list(seconds.items()):
  72. second = secondRenamedGroups.get(second, second)
  73. newSeconds[second] = value
  74. newKerning[first] = newSeconds
  75. # Make copies of the referenced groups and store them
  76. # under the new names in the overall groups dictionary.
  77. allRenamedGroups = list(firstRenamedGroups.items())
  78. allRenamedGroups += list(secondRenamedGroups.items())
  79. for oldName, newName in allRenamedGroups:
  80. group = list(groups[oldName])
  81. groups[newName] = group
  82. # Return the kerning and the groups.
  83. return newKerning, groups, dict(side1=firstRenamedGroups, side2=secondRenamedGroups)
  84. def findKnownKerningGroups(groups: Mapping[str, Any]) -> tuple[set[str], set[str]]:
  85. """Find all kerning groups in a UFO1 or UFO2 font that use known prefixes.
  86. In some cases, not all kerning groups will be referenced
  87. by the kerning pairs in a UFO. The algorithm for locating
  88. groups in :func:`convertUFO1OrUFO2KerningToUFO3Kerning` will
  89. miss these unreferenced groups. By scanning for known prefixes,
  90. this function will catch all of the prefixed groups.
  91. The prefixes and sides by this function are:
  92. @MMK_L_ - side 1
  93. @MMK_R_ - side 2
  94. as defined in the UFO1 specification.
  95. Args:
  96. groups:
  97. A dictionary containing the groups defined in the UFO
  98. font, as read by :class:`.UFOReader`.
  99. Returns:
  100. Two sets; the first containing the names of all
  101. first-side kerning groups identified in the ``groups``
  102. dictionary, and the second containing the names of all
  103. second-side kerning groups identified.
  104. "First-side" and "second-side" are with respect to the
  105. writing direction of the script.
  106. Example::
  107. >>> testGroups = {
  108. ... "@MMK_L_1" : None,
  109. ... "@MMK_L_2" : None,
  110. ... "@MMK_L_3" : None,
  111. ... "@MMK_R_1" : None,
  112. ... "@MMK_R_2" : None,
  113. ... "@MMK_R_3" : None,
  114. ... "@MMK_l_1" : None,
  115. ... "@MMK_r_1" : None,
  116. ... "@MMK_X_1" : None,
  117. ... "foo" : None,
  118. ... }
  119. >>> first, second = findKnownKerningGroups(testGroups)
  120. >>> sorted(first) == ['@MMK_L_1', '@MMK_L_2', '@MMK_L_3']
  121. True
  122. >>> sorted(second) == ['@MMK_R_1', '@MMK_R_2', '@MMK_R_3']
  123. True
  124. """
  125. knownFirstGroupPrefixes = ["@MMK_L_"]
  126. knownSecondGroupPrefixes = ["@MMK_R_"]
  127. firstGroups = set()
  128. secondGroups = set()
  129. for groupName in list(groups.keys()):
  130. for firstPrefix in knownFirstGroupPrefixes:
  131. if groupName.startswith(firstPrefix):
  132. firstGroups.add(groupName)
  133. break
  134. for secondPrefix in knownSecondGroupPrefixes:
  135. if groupName.startswith(secondPrefix):
  136. secondGroups.add(groupName)
  137. break
  138. return firstGroups, secondGroups
  139. def makeUniqueGroupName(name: str, groupNames: list[str], counter: int = 0) -> str:
  140. """Make a kerning group name that will be unique within the set of group names.
  141. If the requested kerning group name already exists within the set, this
  142. will return a new name by adding an incremented counter to the end
  143. of the requested name.
  144. Args:
  145. name:
  146. The requested kerning group name.
  147. groupNames:
  148. A list of the existing kerning group names.
  149. counter:
  150. Optional; a counter of group names already seen (default: 0). If
  151. :attr:`.counter` is not provided, the function will recurse,
  152. incrementing the value of :attr:`.counter` until it finds the
  153. first unused ``name+counter`` combination, and return that result.
  154. Returns:
  155. A unique kerning group name composed of the requested name suffixed
  156. by the smallest available integer counter.
  157. """
  158. # Add a number to the name if the counter is higher than zero.
  159. newName = name
  160. if counter > 0:
  161. newName = "%s%d" % (newName, counter)
  162. # If the new name is in the existing group names, recurse.
  163. if newName in groupNames:
  164. return makeUniqueGroupName(name, groupNames, counter + 1)
  165. # Otherwise send back the new name.
  166. return newName
  167. def test():
  168. """
  169. Tests for :func:`.convertUFO1OrUFO2KerningToUFO3Kerning`.
  170. No known prefixes.
  171. >>> testKerning = {
  172. ... "A" : {
  173. ... "A" : 1,
  174. ... "B" : 2,
  175. ... "CGroup" : 3,
  176. ... "DGroup" : 4
  177. ... },
  178. ... "BGroup" : {
  179. ... "A" : 5,
  180. ... "B" : 6,
  181. ... "CGroup" : 7,
  182. ... "DGroup" : 8
  183. ... },
  184. ... "CGroup" : {
  185. ... "A" : 9,
  186. ... "B" : 10,
  187. ... "CGroup" : 11,
  188. ... "DGroup" : 12
  189. ... },
  190. ... }
  191. >>> testGroups = {
  192. ... "BGroup" : ["B"],
  193. ... "CGroup" : ["C"],
  194. ... "DGroup" : ["D"],
  195. ... }
  196. >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning(
  197. ... testKerning, testGroups, [])
  198. >>> expected = {
  199. ... "A" : {
  200. ... "A": 1,
  201. ... "B": 2,
  202. ... "public.kern2.CGroup": 3,
  203. ... "public.kern2.DGroup": 4
  204. ... },
  205. ... "public.kern1.BGroup": {
  206. ... "A": 5,
  207. ... "B": 6,
  208. ... "public.kern2.CGroup": 7,
  209. ... "public.kern2.DGroup": 8
  210. ... },
  211. ... "public.kern1.CGroup": {
  212. ... "A": 9,
  213. ... "B": 10,
  214. ... "public.kern2.CGroup": 11,
  215. ... "public.kern2.DGroup": 12
  216. ... }
  217. ... }
  218. >>> kerning == expected
  219. True
  220. >>> expected = {
  221. ... "BGroup": ["B"],
  222. ... "CGroup": ["C"],
  223. ... "DGroup": ["D"],
  224. ... "public.kern1.BGroup": ["B"],
  225. ... "public.kern1.CGroup": ["C"],
  226. ... "public.kern2.CGroup": ["C"],
  227. ... "public.kern2.DGroup": ["D"],
  228. ... }
  229. >>> groups == expected
  230. True
  231. Known prefixes.
  232. >>> testKerning = {
  233. ... "A" : {
  234. ... "A" : 1,
  235. ... "B" : 2,
  236. ... "@MMK_R_CGroup" : 3,
  237. ... "@MMK_R_DGroup" : 4
  238. ... },
  239. ... "@MMK_L_BGroup" : {
  240. ... "A" : 5,
  241. ... "B" : 6,
  242. ... "@MMK_R_CGroup" : 7,
  243. ... "@MMK_R_DGroup" : 8
  244. ... },
  245. ... "@MMK_L_CGroup" : {
  246. ... "A" : 9,
  247. ... "B" : 10,
  248. ... "@MMK_R_CGroup" : 11,
  249. ... "@MMK_R_DGroup" : 12
  250. ... },
  251. ... }
  252. >>> testGroups = {
  253. ... "@MMK_L_BGroup" : ["B"],
  254. ... "@MMK_L_CGroup" : ["C"],
  255. ... "@MMK_L_XGroup" : ["X"],
  256. ... "@MMK_R_CGroup" : ["C"],
  257. ... "@MMK_R_DGroup" : ["D"],
  258. ... "@MMK_R_XGroup" : ["X"],
  259. ... }
  260. >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning(
  261. ... testKerning, testGroups, [])
  262. >>> expected = {
  263. ... "A" : {
  264. ... "A": 1,
  265. ... "B": 2,
  266. ... "public.kern2.CGroup": 3,
  267. ... "public.kern2.DGroup": 4
  268. ... },
  269. ... "public.kern1.BGroup": {
  270. ... "A": 5,
  271. ... "B": 6,
  272. ... "public.kern2.CGroup": 7,
  273. ... "public.kern2.DGroup": 8
  274. ... },
  275. ... "public.kern1.CGroup": {
  276. ... "A": 9,
  277. ... "B": 10,
  278. ... "public.kern2.CGroup": 11,
  279. ... "public.kern2.DGroup": 12
  280. ... }
  281. ... }
  282. >>> kerning == expected
  283. True
  284. >>> expected = {
  285. ... "@MMK_L_BGroup": ["B"],
  286. ... "@MMK_L_CGroup": ["C"],
  287. ... "@MMK_L_XGroup": ["X"],
  288. ... "@MMK_R_CGroup": ["C"],
  289. ... "@MMK_R_DGroup": ["D"],
  290. ... "@MMK_R_XGroup": ["X"],
  291. ... "public.kern1.BGroup": ["B"],
  292. ... "public.kern1.CGroup": ["C"],
  293. ... "public.kern1.XGroup": ["X"],
  294. ... "public.kern2.CGroup": ["C"],
  295. ... "public.kern2.DGroup": ["D"],
  296. ... "public.kern2.XGroup": ["X"],
  297. ... }
  298. >>> groups == expected
  299. True
  300. >>> from .validators import kerningValidator
  301. >>> kerningValidator(kerning)
  302. (True, None)
  303. Mixture of known prefixes and groups without prefixes.
  304. >>> testKerning = {
  305. ... "A" : {
  306. ... "A" : 1,
  307. ... "B" : 2,
  308. ... "@MMK_R_CGroup" : 3,
  309. ... "DGroup" : 4
  310. ... },
  311. ... "BGroup" : {
  312. ... "A" : 5,
  313. ... "B" : 6,
  314. ... "@MMK_R_CGroup" : 7,
  315. ... "DGroup" : 8
  316. ... },
  317. ... "@MMK_L_CGroup" : {
  318. ... "A" : 9,
  319. ... "B" : 10,
  320. ... "@MMK_R_CGroup" : 11,
  321. ... "DGroup" : 12
  322. ... },
  323. ... }
  324. >>> testGroups = {
  325. ... "BGroup" : ["B"],
  326. ... "@MMK_L_CGroup" : ["C"],
  327. ... "@MMK_R_CGroup" : ["C"],
  328. ... "DGroup" : ["D"],
  329. ... }
  330. >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning(
  331. ... testKerning, testGroups, [])
  332. >>> expected = {
  333. ... "A" : {
  334. ... "A": 1,
  335. ... "B": 2,
  336. ... "public.kern2.CGroup": 3,
  337. ... "public.kern2.DGroup": 4
  338. ... },
  339. ... "public.kern1.BGroup": {
  340. ... "A": 5,
  341. ... "B": 6,
  342. ... "public.kern2.CGroup": 7,
  343. ... "public.kern2.DGroup": 8
  344. ... },
  345. ... "public.kern1.CGroup": {
  346. ... "A": 9,
  347. ... "B": 10,
  348. ... "public.kern2.CGroup": 11,
  349. ... "public.kern2.DGroup": 12
  350. ... }
  351. ... }
  352. >>> kerning == expected
  353. True
  354. >>> expected = {
  355. ... "BGroup": ["B"],
  356. ... "@MMK_L_CGroup": ["C"],
  357. ... "@MMK_R_CGroup": ["C"],
  358. ... "DGroup": ["D"],
  359. ... "public.kern1.BGroup": ["B"],
  360. ... "public.kern1.CGroup": ["C"],
  361. ... "public.kern2.CGroup": ["C"],
  362. ... "public.kern2.DGroup": ["D"],
  363. ... }
  364. >>> groups == expected
  365. True
  366. """
  367. if __name__ == "__main__":
  368. import doctest
  369. doctest.testmod()