fonts.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/usr/bin/env python
  2. # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
  3. import os
  4. import sys
  5. import tempfile
  6. import unittest
  7. from functools import partial
  8. from kitty.constants import is_macos, read_kitty_resource
  9. from kitty.fast_data_types import (
  10. DECAWM,
  11. ParsedFontFeature,
  12. get_fallback_font,
  13. sprite_map_set_layout,
  14. sprite_map_set_limits,
  15. test_render_line,
  16. test_sprite_position_for,
  17. wcwidth,
  18. )
  19. from kitty.fonts import family_name_to_key
  20. from kitty.fonts.box_drawing import box_chars
  21. from kitty.fonts.common import FontSpec, all_fonts_map, face_from_descriptor, get_font_files, get_named_style, spec_for_face
  22. from kitty.fonts.render import coalesce_symbol_maps, render_string, setup_for_testing, shape_string
  23. from kitty.options.types import Options
  24. from . import BaseTest
  25. def parse_font_spec(spec):
  26. return FontSpec.from_setting(spec)
  27. class Selection(BaseTest):
  28. def test_font_selection(self):
  29. self.set_options({'font_features': {'LiberationMono': (ParsedFontFeature('-dlig'),)}})
  30. opts = Options()
  31. fonts_map = all_fonts_map(True)
  32. names = set(fonts_map['family_map']) | set(fonts_map['variable_map'])
  33. del fonts_map
  34. def s(family: str, *expected: str, alternate=None) -> None:
  35. opts.font_family = parse_font_spec(family)
  36. ff = get_font_files(opts)
  37. actual = tuple(face_from_descriptor(ff[x]).postscript_name() for x in ('medium', 'bold', 'italic', 'bi')) # type: ignore
  38. del ff
  39. for x in actual:
  40. if '/' in x: # Old FreeType failed to generate postscript name for a variable font probably
  41. return
  42. with self.subTest(spec=family):
  43. try:
  44. self.ae(expected, actual)
  45. except AssertionError:
  46. if alternate:
  47. self.ae(tuple(map(alternate, expected)), actual)
  48. else:
  49. raise
  50. def both(family: str, *expected: str, alternate=None) -> None:
  51. for family in (family, f'family="{family}"'):
  52. s(family, *expected, alternate=alternate)
  53. def has(family, allow_missing_in_ci=False):
  54. ans = family_name_to_key(family) in names
  55. if self.is_ci and not allow_missing_in_ci and not ans:
  56. raise AssertionError(f'The family: {family} is not available')
  57. return ans
  58. def t(family, psprefix, bold='Bold', italic='Italic', bi='', reg='Regular', allow_missing_in_ci=False, alternate=None):
  59. if has(family, allow_missing_in_ci=allow_missing_in_ci):
  60. bi = bi or bold + italic
  61. if reg:
  62. reg = '-' + reg
  63. both(family, f'{psprefix}{reg}', f'{psprefix}-{bold}', f'{psprefix}-{italic}', f'{psprefix}-{bi}', alternate=alternate)
  64. t('Source Code Pro', 'SourceCodePro', 'Semibold', 'It')
  65. t('sourcecodeVf', 'SourceCodeVF', 'Semibold')
  66. t('fira code', 'FiraCodeRoman', 'SemiBold', 'Regular', 'SemiBold')
  67. t('hack', 'Hack')
  68. t('DejaVu Sans Mono', 'DejaVuSansMono', reg='', italic='Oblique')
  69. t('ubuntu mono', 'UbuntuMono')
  70. t('liberation mono', 'LiberationMono', reg='')
  71. t('ibm plex mono', 'IBMPlexMono', 'SmBld', reg='')
  72. t('iosevka fixed', 'Iosevka-Fixed', 'Semibold', reg='', bi='Semibold-Italic', allow_missing_in_ci=True)
  73. t('iosevka term', 'Iosevka-Term', 'Semibold', reg='', bi='Semibold-Italic', allow_missing_in_ci=True)
  74. t('fantasque sans mono', 'FantasqueSansMono')
  75. t('jetbrains mono', 'JetBrainsMono', 'SemiBold')
  76. t('consolas', 'Consolas', reg='', allow_missing_in_ci=True)
  77. if has('cascadia code'):
  78. if is_macos:
  79. both('cascadia code', 'CascadiaCode-Regular', 'CascadiaCode-Regular_SemiBold', 'CascadiaCode-Italic', 'CascadiaCode-Italic_SemiBold-Italic')
  80. else:
  81. both('cascadia code', 'CascadiaCodeRoman-Regular', 'CascadiaCodeRoman-SemiBold', 'CascadiaCode-Italic', 'CascadiaCode-SemiBoldItalic')
  82. if has('cascadia mono'):
  83. if is_macos:
  84. both('cascadia mono', 'CascadiaMono-Regular', 'CascadiaMono-Regular_SemiBold', 'CascadiaMono-Italic', 'CascadiaMono-Italic_SemiBold-Italic')
  85. else:
  86. both('cascadia mono', 'CascadiaMonoRoman-Regular', 'CascadiaMonoRoman-SemiBold', 'CascadiaMono-Italic', 'CascadiaMono-SemiBoldItalic')
  87. if has('operator mono', allow_missing_in_ci=True):
  88. both('operator mono', 'OperatorMono-Medium', 'OperatorMono-Bold', 'OperatorMono-MediumItalic', 'OperatorMono-BoldItalic')
  89. # Test variable font selection
  90. if has('SourceCodeVF'):
  91. opts = Options()
  92. opts.font_family = parse_font_spec('family="SourceCodeVF" variable_name="SourceCodeUpright" style="Bold"')
  93. ff = get_font_files(opts)
  94. face = face_from_descriptor(ff['medium'])
  95. self.ae(get_named_style(face)['name'], 'Bold')
  96. face = face_from_descriptor(ff['italic'])
  97. self.ae(get_named_style(face)['name'], 'Bold Italic')
  98. face = face_from_descriptor(ff['bold'])
  99. self.ae(get_named_style(face)['name'], 'Black')
  100. face = face_from_descriptor(ff['bi'])
  101. self.ae(get_named_style(face)['name'], 'Black Italic')
  102. opts.font_family = parse_font_spec('family=SourceCodeVF variable_name=SourceCodeUpright wght=470')
  103. opts.italic_font = parse_font_spec('family=SourceCodeVF variable_name=SourceCodeItalic style=Black')
  104. ff = get_font_files(opts)
  105. self.assertFalse(get_named_style(ff['medium']))
  106. self.ae(get_named_style(ff['italic'])['name'], 'Black Italic')
  107. if has('cascadia code'):
  108. opts = Options()
  109. opts.font_family = parse_font_spec('family="cascadia code"')
  110. opts.italic_font = parse_font_spec('family="cascadia code" variable_name= style="Light Italic"')
  111. ff = get_font_files(opts)
  112. def t(x, **kw):
  113. if 'spec' in kw:
  114. fs = FontSpec.from_setting('family="Cascadia Code" ' + kw['spec'])._replace(created_from_string='')
  115. else:
  116. kw['family'] = 'Cascadia Code'
  117. fs = FontSpec(**kw)
  118. face = face_from_descriptor(ff[x])
  119. self.ae(fs.as_setting, spec_for_face('Cascadia Code', face).as_setting)
  120. t('medium', variable_name='CascadiaCodeRoman', style='Regular')
  121. t('italic', variable_name='', style='Light Italic')
  122. opts = Options()
  123. opts.font_family = parse_font_spec('family="cascadia code" variable_name=CascadiaCodeRoman wght=455')
  124. opts.italic_font = parse_font_spec('family="cascadia code" variable_name= wght=405')
  125. opts.bold_font = parse_font_spec('family="cascadia code" variable_name=CascadiaCodeRoman wght=603')
  126. ff = get_font_files(opts)
  127. t('medium', spec='variable_name=CascadiaCodeRoman wght=455')
  128. t('italic', spec='variable_name= wght=405')
  129. t('bold', spec='variable_name=CascadiaCodeRoman wght=603')
  130. t('bi', spec='variable_name= wght=603')
  131. # Test font features
  132. if has('liberation mono'):
  133. opts = Options()
  134. opts.font_family = parse_font_spec('family="liberation mono"')
  135. ff = get_font_files(opts)
  136. self.ae(face_from_descriptor(ff['medium']).applied_features(), {'dlig': '-dlig'})
  137. self.ae(face_from_descriptor(ff['bold']).applied_features(), {})
  138. opts.font_family = parse_font_spec('family="liberation mono" features="dlig test=3"')
  139. ff = get_font_files(opts)
  140. self.ae(face_from_descriptor(ff['medium']).applied_features(), {'dlig': 'dlig', 'test': 'test=3'})
  141. self.ae(face_from_descriptor(ff['bold']).applied_features(), {'dlig': 'dlig', 'test': 'test=3'})
  142. class Rendering(BaseTest):
  143. def setUp(self):
  144. super().setUp()
  145. self.test_ctx = setup_for_testing()
  146. self.test_ctx.__enter__()
  147. self.sprites, self.cell_width, self.cell_height = self.test_ctx.__enter__()
  148. try:
  149. self.assertEqual([k[0] for k in self.sprites], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  150. except Exception:
  151. self.test_ctx.__exit__()
  152. del self.test_ctx
  153. raise
  154. self.tdir = tempfile.mkdtemp()
  155. def tearDown(self):
  156. self.test_ctx.__exit__()
  157. del self.sprites, self.cell_width, self.cell_height, self.test_ctx
  158. self.rmtree_ignoring_errors(self.tdir)
  159. super().tearDown()
  160. def test_sprite_map(self):
  161. sprite_map_set_limits(10, 2)
  162. sprite_map_set_layout(5, 5)
  163. self.ae(test_sprite_position_for(0), (0, 0, 0))
  164. self.ae(test_sprite_position_for(1), (1, 0, 0))
  165. self.ae(test_sprite_position_for(2), (0, 1, 0))
  166. self.ae(test_sprite_position_for(3), (1, 1, 0))
  167. self.ae(test_sprite_position_for(4), (0, 0, 1))
  168. self.ae(test_sprite_position_for(5), (1, 0, 1))
  169. self.ae(test_sprite_position_for(6), (0, 1, 1))
  170. self.ae(test_sprite_position_for(7), (1, 1, 1))
  171. self.ae(test_sprite_position_for(0, 1), (0, 0, 2))
  172. self.ae(test_sprite_position_for(0, 2), (1, 0, 2))
  173. def test_box_drawing(self):
  174. prerendered = len(self.sprites)
  175. s = self.create_screen(cols=len(box_chars) + 1, lines=1, scrollback=0)
  176. s.draw(''.join(box_chars))
  177. line = s.line(0)
  178. test_render_line(line)
  179. self.assertEqual(len(self.sprites) - prerendered, len(box_chars))
  180. def test_font_rendering(self):
  181. render_string('ab\u0347\u0305你好|\U0001F601|\U0001F64f|\U0001F63a|')
  182. text = 'He\u0347\u0305llo\u0341, w\u0302or\u0306l\u0354d!'
  183. # macOS has no fonts capable of rendering combining chars
  184. if is_macos:
  185. text = text.encode('ascii', 'ignore').decode('ascii')
  186. cells = render_string(text)[-1]
  187. self.ae(len(cells), len(text.encode('ascii', 'ignore')))
  188. text = '你好,世界'
  189. sz = sum(map(lambda x: wcwidth(ord(x)), text))
  190. cells = render_string(text)[-1]
  191. self.ae(len(cells), sz)
  192. def test_shaping(self):
  193. font_path_cache = {}
  194. def path_for_font(name):
  195. if name not in font_path_cache:
  196. with open(os.path.join(self.tdir, name), 'wb') as f:
  197. font_path_cache[name] = f.name
  198. data = read_kitty_resource(name, __name__.rpartition('.')[0])
  199. f.write(data)
  200. return font_path_cache[name]
  201. def ss(text, font=None):
  202. path = path_for_font(font) if font else None
  203. return shape_string(text, path=path)
  204. def groups(text, font=None):
  205. return [x[:2] for x in ss(text, font)]
  206. for font in ('FiraCode-Medium.otf', 'CascadiaCode-Regular.otf', 'iosevka-regular.ttf'):
  207. g = partial(groups, font=font)
  208. self.ae(g('abcd'), [(1, 1) for i in range(4)])
  209. self.ae(g('A===B!=C'), [(1, 1), (3, 3), (1, 1), (2, 2), (1, 1)])
  210. self.ae(g('A=>>B!=C'), [(1, 1), (3, 3), (1, 1), (2, 2), (1, 1)])
  211. if 'iosevka' in font:
  212. self.ae(g('--->'), [(4, 4)])
  213. self.ae(g('-' * 12 + '>'), [(13, 13)])
  214. self.ae(g('<~~~'), [(4, 4)])
  215. self.ae(g('a<~~~b'), [(1, 1), (4, 4), (1, 1)])
  216. else:
  217. self.ae(g('----'), [(4, 4)])
  218. self.ae(g('F--a--'), [(1, 1), (2, 2), (1, 1), (2, 2)])
  219. self.ae(g('===--<>=='), [(3, 3), (2, 2), (2, 2), (2, 2)])
  220. self.ae(g('==!=<>==<><><>'), [(4, 4), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2)])
  221. self.ae(g('-' * 18), [(18, 18)])
  222. self.ae(g('a>\u2060<b'), [(1, 1), (1, 2), (1, 1), (1, 1)])
  223. colon_glyph = ss('9:30', font='FiraCode-Medium.otf')[1][2]
  224. self.assertNotEqual(colon_glyph, ss(':', font='FiraCode-Medium.otf')[0][2])
  225. self.ae(colon_glyph, 1031)
  226. self.ae(groups('9:30', font='FiraCode-Medium.otf'), [(1, 1), (1, 1), (1, 1), (1, 1)])
  227. self.ae(groups('|\U0001F601|\U0001F64f|\U0001F63a|'), [(1, 1), (2, 1), (1, 1), (2, 1), (1, 1), (2, 1), (1, 1)])
  228. self.ae(groups('He\u0347\u0305llo\u0337,', font='LiberationMono-Regular.ttf'),
  229. [(1, 1), (1, 3), (1, 1), (1, 1), (1, 2), (1, 1)])
  230. self.ae(groups('i\u0332\u0308', font='LiberationMono-Regular.ttf'), [(1, 2)])
  231. self.ae(groups('u\u0332 u\u0332\u0301', font='LiberationMono-Regular.ttf'), [(1, 2), (1, 1), (1, 2)])
  232. def test_emoji_presentation(self):
  233. s = self.create_screen()
  234. s.draw('\u2716\u2716\ufe0f')
  235. self.ae((s.cursor.x, s.cursor.y), (3, 0))
  236. s.draw('\u2716\u2716')
  237. self.ae((s.cursor.x, s.cursor.y), (5, 0))
  238. s.draw('\ufe0f')
  239. self.ae((s.cursor.x, s.cursor.y), (2, 1))
  240. self.ae(str(s.line(0)), '\u2716\u2716\ufe0f\u2716')
  241. self.ae(str(s.line(1)), '\u2716\ufe0f')
  242. s.draw('\u2716' * 3)
  243. self.ae((s.cursor.x, s.cursor.y), (5, 1))
  244. self.ae(str(s.line(1)), '\u2716\ufe0f\u2716\u2716\u2716')
  245. self.ae((s.cursor.x, s.cursor.y), (5, 1))
  246. s.reset_mode(DECAWM)
  247. s.draw('\ufe0f')
  248. s.set_mode(DECAWM)
  249. self.ae((s.cursor.x, s.cursor.y), (5, 1))
  250. self.ae(str(s.line(1)), '\u2716\ufe0f\u2716\u2716\ufe0f')
  251. s.cursor.y = s.lines - 1
  252. s.draw('\u2716' * s.columns)
  253. self.ae((s.cursor.x, s.cursor.y), (5, 4))
  254. s.draw('\ufe0f')
  255. self.ae((s.cursor.x, s.cursor.y), (2, 4))
  256. self.ae(str(s.line(s.cursor.y)), '\u2716\ufe0f')
  257. @unittest.skipUnless(is_macos, 'Only macOS has a Last Resort font')
  258. def test_fallback_font_not_last_resort(self):
  259. # Ensure that the LastResort font is not reported as a fallback font on
  260. # macOS. See https://github.com/kovidgoyal/kitty/issues/799
  261. from io import StringIO
  262. orig, buf = sys.stderr, StringIO()
  263. sys.stderr = buf
  264. try:
  265. self.assertRaises(ValueError, get_fallback_font, '\U0010FFFF', False, False)
  266. finally:
  267. sys.stderr = orig
  268. self.assertIn('LastResort', buf.getvalue())
  269. def test_coalesce_symbol_maps(self):
  270. q = {(2, 3): 'a', (4, 6): 'b', (5, 5): 'b', (7, 7): 'b', (9, 9): 'b', (1, 1): 'a'}
  271. self.ae(coalesce_symbol_maps(q), {(1, 3): 'a', (4, 7): 'b', (9, 9): 'b'})
  272. q = {(1, 4): 'a', (2, 3): 'b'}
  273. self.ae(coalesce_symbol_maps(q), {(1, 1): 'a', (2, 3): 'b', (4, 4): 'a'})
  274. q = {(2, 3): 'b', (1, 4): 'a'}
  275. self.ae(coalesce_symbol_maps(q), {(1, 4): 'a'})
  276. q = {(1, 4): 'a', (2, 5): 'b'}
  277. self.ae(coalesce_symbol_maps(q), {(1, 1): 'a', (2, 5): 'b'})
  278. q = {(2, 5): 'b', (1, 4): 'a'}
  279. self.ae(coalesce_symbol_maps(q), {(1, 4): 'a', (5, 5): 'b'})
  280. q = {(1, 4): 'a', (2, 5): 'a'}
  281. self.ae(coalesce_symbol_maps(q), {(1, 5): 'a'})
  282. q = {(1, 4): 'a', (4, 5): 'b'}
  283. self.ae(coalesce_symbol_maps(q), {(1, 3): 'a', (4, 5): 'b'})
  284. q = {(4, 5): 'b', (1, 4): 'a'}
  285. self.ae(coalesce_symbol_maps(q), {(1, 4): 'a', (5, 5): 'b'})
  286. q = {(0, 30): 'a', (10, 10): 'b', (11, 11): 'b', (2, 2): 'c', (1, 1): 'c'}
  287. self.ae(coalesce_symbol_maps(q), {
  288. (0, 0): 'a', (1, 2): 'c', (3, 9): 'a', (10, 11): 'b', (12, 30): 'a'})