#!/usr/bin/env python # License: GPL v3 Copyright: 2017, Kovid Goyal import array import os import sys import tempfile import unittest from collections.abc import Iterable from functools import lru_cache, partial from itertools import repeat from math import ceil from kitty.constants import is_macos, read_kitty_resource from kitty.fast_data_types import ( DECAWM, ParsedFontFeature, Screen, get_fallback_font, render_decoration, set_allow_use_of_box_fonts, sprite_idx_to_pos, sprite_map_set_layout, sprite_map_set_limits, test_render_line, test_shape, test_sprite_position_increment, test_sprite_tracker_ynum, wcwidth, ) from kitty.fonts import family_name_to_key from kitty.fonts.common import FontSpec, all_fonts_map, face_from_descriptor, get_font_files, get_named_style, spec_for_face from kitty.fonts.render import coalesce_symbol_maps, create_face, render_string, setup_for_testing, shape_string from kitty.options.types import Options from .base import BaseTest, draw_multicell def parse_font_spec(spec): return FontSpec.from_setting(spec) @lru_cache(maxsize=64) def testing_font_data(name): return read_kitty_resource(name, __name__.rpartition('.')[0]) class Selection(BaseTest): def test_font_selection(self): self.set_options({'font_features': {'LiberationMono': (ParsedFontFeature('-dlig'),)}}) opts = Options() fonts_map = all_fonts_map(True) names = set(fonts_map['family_map']) | set(fonts_map['variable_map']) del fonts_map def s(family: str, *expected: str, alternate=None) -> None: opts.font_family = parse_font_spec(family) ff = get_font_files(opts) actual = tuple(face_from_descriptor(ff[x]).postscript_name() for x in ('medium', 'bold', 'italic', 'bi')) # type: ignore del ff for x in actual: if '/' in x: # Old FreeType failed to generate postscript name for a variable font probably return with self.subTest(spec=family): try: self.ae(expected, actual) except AssertionError: if alternate: self.ae(alternate, actual) else: raise def both(family: str, *expected: str, alternate=None) -> None: for family in (family, f'family="{family}"'): s(family, *expected, alternate=alternate) def has(family, allow_missing_in_ci=False): ans = family_name_to_key(family) in names if self.is_ci and not allow_missing_in_ci and not ans: raise AssertionError(f'The family: {family} is not available') return ans def t(family, psprefix, bold='Bold', italic='Italic', bi='', reg='Regular', allow_missing_in_ci=False, alternate=None): if has(family, allow_missing_in_ci=allow_missing_in_ci): bi = bi or bold + italic if reg: reg = '-' + reg both(family, f'{psprefix}{reg}', f'{psprefix}-{bold}', f'{psprefix}-{italic}', f'{psprefix}-{bi}', alternate=alternate) t('Source Code Pro', 'SourceCodePro', 'Semibold', 'It') t('sourcecodeVf', 'SourceCodeVF', 'Semibold') # The Arch ttf-fira-code package excludes the variable fonts for some reason t( 'fira code', 'FiraCodeRoman', 'SemiBold', 'Regular', 'SemiBold', alternate=('FiraCode-Regular', 'FiraCode-SemiBold', 'FiraCode-Retina', 'FiraCode-SemiBold'), ) t('hack', 'Hack') # some ubuntu systems (such as the build VM) have only the regular and # bold faces of DejaVu Sans Mono installed. # t('DejaVu Sans Mono', 'DejaVuSansMono', reg='', italic='Oblique') t('ubuntu mono', 'UbuntuMono') t('liberation mono', 'LiberationMono', reg='') t('ibm plex mono', 'IBMPlexMono', 'SmBld', reg='') t('iosevka fixed', 'Iosevka-Fixed', 'Semibold', reg='', bi='Semibold-Italic', allow_missing_in_ci=True) t('iosevka term', 'Iosevka-Term', 'Semibold', reg='', bi='Semibold-Italic', allow_missing_in_ci=True) t('fantasque sans mono', 'FantasqueSansMono') t('jetbrains mono', 'JetBrainsMono', 'SemiBold') t('consolas', 'Consolas', reg='', allow_missing_in_ci=True) if has('cascadia code'): if is_macos: both('cascadia code', 'CascadiaCode-Regular', 'CascadiaCode-Regular_SemiBold', 'CascadiaCode-Italic', 'CascadiaCode-Italic_SemiBold-Italic') else: both('cascadia code', 'CascadiaCodeRoman-Regular', 'CascadiaCodeRoman-SemiBold', 'CascadiaCode-Italic', 'CascadiaCode-SemiBoldItalic') if has('cascadia mono'): if is_macos: both('cascadia mono', 'CascadiaMono-Regular', 'CascadiaMono-Regular_SemiBold', 'CascadiaMono-Italic', 'CascadiaMono-Italic_SemiBold-Italic') else: both('cascadia mono', 'CascadiaMonoRoman-Regular', 'CascadiaMonoRoman-SemiBold', 'CascadiaMono-Italic', 'CascadiaMono-SemiBoldItalic') if has('operator mono', allow_missing_in_ci=True): both('operator mono', 'OperatorMono-Medium', 'OperatorMono-Bold', 'OperatorMono-MediumItalic', 'OperatorMono-BoldItalic') # Test variable font selection if has('SourceCodeVF'): opts = Options() opts.font_family = parse_font_spec('family="SourceCodeVF" variable_name="SourceCodeUpright" style="Bold"') ff = get_font_files(opts) face = face_from_descriptor(ff['medium']) self.ae(get_named_style(face)['name'], 'Bold') face = face_from_descriptor(ff['italic']) self.ae(get_named_style(face)['name'], 'Bold Italic') face = face_from_descriptor(ff['bold']) self.ae(get_named_style(face)['name'], 'Black') face = face_from_descriptor(ff['bi']) self.ae(get_named_style(face)['name'], 'Black Italic') opts.font_family = parse_font_spec('family=SourceCodeVF variable_name=SourceCodeUpright wght=470') opts.italic_font = parse_font_spec('family=SourceCodeVF variable_name=SourceCodeItalic style=Black') ff = get_font_files(opts) self.assertFalse(get_named_style(ff['medium'])) self.ae(get_named_style(ff['italic'])['name'], 'Black Italic') if has('cascadia code'): opts = Options() opts.font_family = parse_font_spec('family="cascadia code"') opts.italic_font = parse_font_spec('family="cascadia code" variable_name= style="Light Italic"') ff = get_font_files(opts) def t(x, **kw): if 'spec' in kw: fs = FontSpec.from_setting('family="Cascadia Code" ' + kw['spec'])._replace(created_from_string='') else: kw['family'] = 'Cascadia Code' fs = FontSpec(**kw) face = face_from_descriptor(ff[x]) self.ae(fs.as_setting, spec_for_face('Cascadia Code', face).as_setting) t('medium', variable_name='CascadiaCodeRoman', style='Regular') t('italic', variable_name='', style='Light Italic') opts = Options() opts.font_family = parse_font_spec('family="cascadia code" variable_name=CascadiaCodeRoman wght=455') opts.italic_font = parse_font_spec('family="cascadia code" variable_name= wght=405') opts.bold_font = parse_font_spec('family="cascadia code" variable_name=CascadiaCodeRoman wght=603') ff = get_font_files(opts) t('medium', spec='variable_name=CascadiaCodeRoman wght=455') t('italic', spec='variable_name= wght=405') t('bold', spec='variable_name=CascadiaCodeRoman wght=603') t('bi', spec='variable_name= wght=603') # Test font features if has('liberation mono'): opts = Options() opts.font_family = parse_font_spec('family="liberation mono"') ff = get_font_files(opts) self.ae(face_from_descriptor(ff['medium']).applied_features(), {'dlig': '-dlig'}) self.ae(face_from_descriptor(ff['bold']).applied_features(), {}) opts.font_family = parse_font_spec('family="liberation mono" features="dlig test=3"') ff = get_font_files(opts) self.ae(face_from_descriptor(ff['medium']).applied_features(), {'dlig': 'dlig', 'test': 'test=3'}) self.ae(face_from_descriptor(ff['bold']).applied_features(), {'dlig': 'dlig', 'test': 'test=3'}) def test_invalid_font_feature(self): with self.assertRaises(ValueError) as cm: ParsedFontFeature('!!bad!!') self.assertIn('!!bad!!', str(cm.exception)) def test_render_decoration(self): w, h = 10, 20 for which in ('curl', 'dashed', 'dotted', 'double', 'straight', 'strikethrough'): data = render_decoration(which, w, h, 15, 2) self.assertIsInstance(data, bytes) self.ae(len(data), w * h) # Strikethrough metrics default to zero if which != 'strikethrough': self.assertTrue(any(data), f'{which} decoration is empty') with self.assertRaises(KeyError): render_decoration('nonexistent', w, h, 15, 2) def test_synthetic_italic_matrix(self): # A roman-only font that find_best_match finds (e.g. Fira Code, which ships # no italic face) must get fontconfig's synthetic-italic FC_MATRIX # (90-synthetic.conf) attached, so its italic renders slanted rather than # upright; real-italic faces must not. The shear value is fontconfig's, not # ours, so assert the invariant (a non-identity matrix is present), not the # exact tuple, for cross-config stability. if is_macos: self.skipTest('synthetic-italic FC_MATRIX is a fontconfig feature') from kitty.fonts.fontconfig import FC_MONO, fc_match names = set(all_fonts_map(True)['family_map']) | set(all_fonts_map(True)['variable_map']) if family_name_to_key('fira code') not in names: self.skipTest('Fira Code not installed') # Probe fc_match directly so we can tell "environment lacks the rule" (skip) # from "code did not attach the matrix" (fail). if fc_match('Fira Code', False, True, FC_MONO).get('matrix') is None: self.skipTest('fontconfig 90-synthetic.conf not active; no synthetic-italic matrix') opts = Options() opts.font_family = parse_font_spec('Fira Code') ff = get_font_files(opts) self.assertIsNone(ff['medium'].get('matrix')) # upright stays upright mi = ff['italic'].get('matrix') self.assertIsNotNone(mi) # roman, no italic -> sheared self.assertNotEqual(mi[1], 0.0) # actually slanted, not identity # Faces are built from a size-specialized descriptor at render time; the # matrix must survive specialize_font_descriptor or the glyphs render # upright despite the descriptor above being correct. from kitty.fast_data_types import specialize_font_descriptor sd = specialize_font_descriptor(dict(ff['italic']), 12.0, 96.0, 96.0) self.ae(sd.get('matrix'), mi) if family_name_to_key('liberation mono') in names: # real-italic control opts.font_family = parse_font_spec('Liberation Mono') self.assertIsNone(get_font_files(opts)['italic'].get('matrix')) def block_helpers(s, sprites, cell_width, cell_height): mr = {} actual = b'' block_size = cell_width * cell_height * 4 def full_block(): return b'\xff' * block_size def empty_block(): return b'\0' * block_size def half_block(first=b'\xff', second=b'\0', swap=False): frac = 0.5 height = ceil(frac * cell_height) rest = cell_height - height if swap: height, rest = rest, height first, second = second, first return (first * (height * cell_width * 4)) + (second * rest * cell_width * 4) def quarter_block(): frac = 0.5 height = ceil(frac * cell_height) width = ceil(frac * cell_width) ans = array.array('I', b'\0' * block_size) for y in range(height): pos = cell_width * y for x in range(width): ans[pos + x] = 0xFFFFFFFF return ans.tobytes() def upper_half_block(): return half_block() def lower_half_block(): return half_block(swap=True) def block_as_str(a): pixels = array.array('I', a) def row(y): pos = y * cell_width return ' '.join(f'{int(pixels[pos + x] != 0)}' for x in range(cell_width)) return '\n'.join(row(y) for y in range(cell_height)) def assert_blocks(a, b, msg=''): nonlocal mr, actual, full_block, half_block, quarter_block, block_test, empty_block if a != b: del mr, actual, full_block, half_block, quarter_block, block_test, empty_block msg = msg or 'block not equal' if len(a) != len(b): assert_blocks.__msg = msg + f' block lengths not equal: {len(a) / 4} != {len(b) / 4}' else: assert_blocks.__msg = msg + '\n' + block_as_str(a) + '\n\n' + block_as_str(b) del a, b raise AssertionError(assert_blocks.__msg) def multiline_render(text, scale=1, width=1, **kw): s.reset() draw_multicell(s, text, scale=scale, width=width, **kw) ans = [] for y in range(scale): line = s.line(y) test_render_line(line) for x in range(width * scale): ans.append(sprites[sprite_idx_to_pos(line.sprite_at(x), setup_for_testing.xnum, setup_for_testing.ynum)]) return ans def block_test(*expected, **kw): nonlocal mr, actual mr = multiline_render(kw.pop('text', '█'), **kw) try: z = zip(expected, mr, strict=True) except TypeError: z = zip(expected, mr) for i, (expected, actual) in enumerate(z): assert_blocks(expected(), actual, f'Block {i} expected != actual') return full_block, empty_block, upper_half_block, lower_half_block, quarter_block, block_as_str, block_test class FontBaseTest(BaseTest): font_size = 16.0 dpi = 72.0 font_name = 'FiraCode-Medium.otf' def path_for_font(self, name): if name not in self.font_path_cache: with open(os.path.join(self.tdir, name), 'wb') as f: self.font_path_cache[name] = f.name f.write(testing_font_data(name)) return self.font_path_cache[name] def setUp(self): super().setUp() self.font_path_cache = {} self.tdir = tempfile.mkdtemp() self.addCleanup(self.rmtree_ignoring_errors, self.tdir) path = self.path_for_font(self.font_name) if self.font_name else '' tc = setup_for_testing(size=self.font_size, dpi=self.dpi, main_face_path=path) self.sprites, self.cell_width, self.cell_height = tc.__enter__() self.addCleanup(tc.__exit__) self.assertEqual([k[0] for k in self.sprites], list(range(11))) def tearDown(self): del self.sprites, self.cell_width, self.cell_height self.font_path_cache = {} super().tearDown() class Rendering(FontBaseTest): def test_decorations_map_growth(self): from kitty.fast_data_types import decorations_map_new_size as size m = 4096 self.ae(size(0, 0, m), (4096, 1)) self.ae(size(5000, 4096, m), (4096, 2)) cap, reallocs = 0, 0 for count in range(100000): if count >= cap: w, h = size(count, cap, m) cap, reallocs = w * h, reallocs + 1 self.assertLess(reallocs, 10) full = m * m self.ae(size(m * (m - 1), m * (m - 1), m), (m, m)) self.ae(size(full - 1, full // 2, m), (m, m)) self.assertIsNone(size(full, full, m)) def test_sprite_map(self): sprite_map_set_limits(10, 3) sprite_map_set_layout(5, 4) # 4 because of underline_exclusion row self.ae(test_sprite_position_increment(), (0, 0, 0)) self.ae(test_sprite_position_increment(), (1, 0, 0)) self.ae(test_sprite_position_increment(), (0, 1, 0)) self.ae(test_sprite_position_increment(), (1, 1, 0)) self.ae(test_sprite_position_increment(), (0, 0, 1)) self.ae(test_sprite_position_increment(), (1, 0, 1)) self.ae(test_sprite_position_increment(), (0, 1, 1)) self.ae(test_sprite_position_increment(), (1, 1, 1)) self.ae(test_sprite_position_increment(), (0, 0, 2)) self.ae(test_sprite_position_increment(), (1, 0, 2)) def test_sprite_map_ynum_growth(self): sprite_map_set_limits(10, 3) sprite_map_set_layout(1, 1) self.ae(test_sprite_tracker_ynum(), 1) seen = [1] for i in range(10 * 5 * 2 + 3): self.ae(test_sprite_position_increment(), (i % 10, (i // 10) % 5, i // 50)) ynum = test_sprite_tracker_ynum() self.assertLessEqual(ynum, 5) if ynum != seen[-1]: seen.append(ynum) self.ae(seen, [1, 2, 4, 5]) def test_box_drawing(self): s = self.create_screen(cols=len(box_chars) + 1, lines=1, scrollback=0) prerendered = len(self.sprites) s.draw(''.join(box_chars)) line = s.line(0) test_render_line(line) self.assertEqual(len(self.sprites) - prerendered, len(box_chars)) def test_line_thickness_scales_with_font_size(self): from kitty.fast_data_types import create_test_font_group, render_box_char from kitty.fonts.render import set_font_family options = {'font_size': self.font_size} opts = self.set_options(options) chars = '─│╭┃' def check(factor): set_font_family(opts) # resets font groups so that the first one is at the specified size cell_width, cell_height, _ = create_test_font_group(factor * self.font_size, self.dpi, self.dpi) s = self.create_screen(cols=len(chars) + 1, lines=1, scrollback=0, options=options) s.draw(chars) line = s.line(0) test_render_line(line) def alpha(sprite_idx): pixels = array.array('I', self.sprites[sprite_idx_to_pos(sprite_idx, setup_for_testing.xnum, setup_for_testing.ynum)]) return bytes(p & 0xFF for p in pixels) for i, ch in enumerate(chars): expected = render_box_char(ord(ch), cell_width, cell_height, factor, self.dpi, self.dpi) self.ae(alpha(line.sprite_at(i)), expected, f'{ch!r} not rendered with line thickness scale: {factor}') beam = alpha(2) mid = (cell_height // 2) * cell_width # dpi is 72 so 1pt == 1px self.ae(sum(1 for x in range(cell_width) if beam[mid + x]), round(factor * opts.cursor_beam_thickness)) check(1) check(2) check(4) def test_scaled_box_drawing(self): self.scaled_drawing_test() def test_scaled_font_drawing(self): set_allow_use_of_box_fonts(False) try: self.scaled_drawing_test() finally: set_allow_use_of_box_fonts(True) def scaled_drawing_test(self): s = self.create_screen(cols=8, lines=8, scrollback=0) full_block, empty_block, upper_half_block, lower_half_block, quarter_block, block_as_str, block_test = block_helpers( s, self.sprites, self.cell_width, self.cell_height ) block_test(full_block) block_test(full_block, full_block, full_block, full_block, scale=2) block_test(full_block, empty_block, empty_block, empty_block, scale=2, subscale_n=1, subscale_d=2) block_test(empty_block, full_block, empty_block, empty_block, scale=2, subscale_n=1, subscale_d=2, horizontal_align=1) block_test(full_block, full_block, empty_block, empty_block, scale=2, subscale_n=1, subscale_d=2, text='██') block_test(empty_block, empty_block, full_block, empty_block, scale=2, subscale_n=1, subscale_d=2, vertical_align=1) block_test(quarter_block, scale=1, subscale_n=1, subscale_d=2) block_test(upper_half_block, scale=1, subscale_n=1, subscale_d=2, text='██') block_test(lower_half_block, scale=1, subscale_n=1, subscale_d=2, text='██', vertical_align=1) def test_font_rendering(self): render_string('ab\u0347\u0305你好|\U0001f601|\U0001f64f|\U0001f63a|') text = 'He\u0347\u0305llo\u0341, w\u0302or\u0306l\u0354d!' # macOS has no fonts capable of rendering combining chars if is_macos: text = text.encode('ascii', 'ignore').decode('ascii') cells = render_string(text)[-1] self.ae(len(cells), len(text.encode('ascii', 'ignore'))) text = '你好,世界' sz = sum(map(lambda x: wcwidth(ord(x)), text)) cells = render_string(text)[-1] self.ae(len(cells), sz) @unittest.skipIf(is_macos, 'COLRv1 is only supported on Linux') def test_rendering_colrv1(self): f = create_face(self.path_for_font('twemoji_smiley-cff2_colr_1.otf')) f.set_size(64, 96, 96) for char in '😁😇😈': _, w, h = f.render_codepoint(ord(char)) self.assertGreater(w, 64) self.assertGreater(h, 64) def test_color_emoji_not_shrunk(self): # Regression test for https://github.com/kovidgoyal/kitty/issues/10144. # fontconfig gives fixed-size color faces (e.g. Noto Color Emoji) a # pixel-size fixup encoded as FC_MATRIX. That scale must not reach the # cairo font matrix used for color glyphs; applying it shrinks color emoji # to a dot (ee937bdd1b). Render the same font two ways at the same size: # from its fontconfig descriptor, which carries the fixup matrix, and from # its file path, which does not. A correct build renders both at the same # size; the bug shrinks the descriptor one. Comparing the two is # environment-independent since only the matrix differs. if is_macos: self.skipTest('FC_MATRIX is a fontconfig feature, not used on macOS') from kitty.fonts.fontconfig import fc_match desc = dict(fc_match('emoji', False, False, 0)) if not (desc.get('color') and desc.get('matrix')): self.skipTest('no fixed-size color emoji font with a fontconfig fixup matrix') with_matrix = face_from_descriptor(desc) with_matrix.set_size(64, 96, 96) without_matrix = create_face(desc['path']) without_matrix.set_size(64, 96, 96) _, mw, mh = with_matrix.render_codepoint(0x1F40D) _, rw, rh = without_matrix.render_codepoint(0x1F40D) self.assertGreater(mh, 0.5 * rh, f'color emoji shrunk by FC_MATRIX: {mh}px vs {rh}px (#10144)') def test_concat_cells(self): from kitty.fast_data_types import concat_cells # sprite pixels are 0xRRGGBBAA and the result is opaque RGBA bytes cell = array.array('I', (0xFF000080, 0xFFFFFF00, 0x00FF00FF)).tobytes() self.ae(concat_cells(3, 1, True, (cell,)), bytes((0x80, 0, 0, 0xFF, 0, 0, 0, 0xFF, 0, 0xFF, 0, 0xFF))) self.ae(concat_cells(1, 1, True, (cell[:4], cell[4:8])), bytes((0x80, 0, 0, 0xFF, 0, 0, 0, 0xFF))) self.ae(concat_cells(2, 1, True, (cell[:8],), 0x0000FF), bytes((0x80, 0, 0x7F, 0xFF, 0, 0, 0xFF, 0xFF))) # alpha mask pixels are white text and the result is RGBA bytes, as above self.ae(concat_cells(2, 1, False, (bytes((0xFF, 0)),), 0x0000FF), bytes((0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0xFF, 0xFF))) self.ae(concat_cells(1, 1, False, (bytes((0x80,)),), 0x102030), bytes((0x87, 0x8F, 0x97, 0xFF))) self.ae(concat_cells(0, 1, True, (b'',)), b'') def cell_alpha(self, font_name, text, ppem): "The alpha of the pixels of the first cell of text, and the cell width and height" with setup_for_testing(size=ppem, dpi=72.0, main_face_path=self.path_for_font(font_name)) as (sprites, cell_width, cell_height): s = Screen(None, 1, 4) s.draw(text) line = s.line(0) test_render_line(line) pos = sprite_idx_to_pos(line.sprite_at(0) & 0x7FFFFFFF, setup_for_testing.xnum, setup_for_testing.ynum) # the low byte of each pixel is its alpha, the color bits are set even for empty pixels on macOS return bytes(p & 0xFF for p in array.array('I', sprites[pos])), cell_width, cell_height def glyph_ink(self, font_name, char, ppem): "The number of pixel rows and columns char occupies when drawn in a single cell, and the cell width" alpha, cell_width, cell_height = self.cell_alpha(font_name, char, ppem) rows = [y for y in range(cell_height) if any(alpha[y * cell_width : (y + 1) * cell_width])] cols = [x for x in range(cell_width) if any(alpha[x::cell_width])] height = rows[-1] - rows[0] + 1 if rows else 0 width = cols[-1] - cols[0] + 1 if cols else 0 return height, width, cell_width def test_small_glyph_overhang_is_not_rescaled(self): # Fonts have glyphs whose outlines overhang their advance a little, such # as the texture healing alternates of Monaspace and 0xProto. These must # be drawn at full size, not shrunk to fit the cell, and cropped to # it, which they then fill. The expected height is the height of the # glyph's bounding box in font units, times ppem / units per em, # rounded down. Cropping removes ink, so it is only done for glyphs # at most 2/10 wider than the cell. for font_name, char, ppem, full_height in ( ('CascadiaCode-Regular.otf', 'ď', 40, 31), # 1588 * 40 / 2048, outline is 7% wider than the cell ('LiberationMono-Regular.ttf', 'Ƴ', 32, 21), # 1370 * 32 / 2048, 10% wider ('FiraCode-Medium.otf', 'œ', 64, 36), # 1111 * 64 / 1950, 3% wider # 935 * 120 / 1000, 15% wider, like the widest texture healing alternates of Monaspace ('iosevka-regular.ttf', 'ꭦ', 120, 112), ): with self.subTest(font=font_name, char=char): height, width, cell_width = self.glyph_ink(font_name, char, ppem) self.assertGreaterEqual(height, full_height) self.assertEqual(width, cell_width) def test_large_glyph_overhang_is_rescaled(self): # Ὦ has its breathing mark and accent to the left of the letter, outside # its cell, so cropping would cut them off. Its outline is 1594 units # wide and 1766 tall with an advance of 1229, so scaled to fit the cell # it is at most 1766 * (1229 / 1594) * 32 / 2048 = 21.3 pixels tall, # which, depending on where it falls relative to the pixel grid, covers # at most 23 rows. Drawn at full size it covers at least 27. height, width, cell_width = self.glyph_ink('LiberationMono-Regular.ttf', 'Ὦ', 32) self.assertLessEqual(height, 23) # The rescaled glyph is moved into the cell so that the marks are # not cut off and it spans the whole cell. self.assertGreaterEqual(width, cell_width - 1) def test_marks_move_with_rescaled_glyph(self): # When Ὦ is rescaled and moved into its cell, a combining dot below it # must move with it, so that it stays centered under the letter font = 'LiberationMono-Regular.ttf' base, cell_width, cell_height = self.cell_alpha(font, 'Ὦ', 32) combined = self.cell_alpha(font, 'Ὦ\u0323', 32)[0] def ink_columns(alpha, rows): return [x for x in range(cell_width) if any(alpha[y * cell_width + x] for y in rows)] def center(cols): return (cols[0] + cols[-1]) / 2 rows_with_ink = [y for y in range(cell_height) if any(base[y * cell_width : (y + 1) * cell_width])] # the bottom row of Ω spans its width letter = ink_columns(base, rows_with_ink[-1:]) dot = ink_columns(combined, range(rows_with_ink[-1] + 1, cell_height)) self.assertTrue(dot) self.assertLessEqual(abs(center(dot) - center(letter)), cell_width / 8, f'dot: {dot} letter: {letter}') def test_shaping(self): def ss(text, font=None): path = self.path_for_font(font) if font else None return shape_string(text, path=path) def groups(text, font=None): return [x[:2] for x in ss(text, font)] for font in ('FiraCode-Medium.otf', 'CascadiaCode-Regular.otf', 'iosevka-regular.ttf'): g = partial(groups, font=font) self.ae(g('abcd'), [(1, 1) for i in range(4)]) self.ae(g('A===B!=C'), [(1, 1), (3, 3), (1, 1), (2, 2), (1, 1)]) self.ae(g('A=>>B!=C'), [(1, 1), (3, 3), (1, 1), (2, 2), (1, 1)]) self.ae(g('->'), [(2, 2)]) self.ae(g('<-'), [(2, 2)]) self.ae(g('==>'), [(3, 3)]) self.ae(g('<=='), [(3, 3)]) self.ae(g('a->b'), [(1, 1), (2, 2), (1, 1)]) self.ae(g('a<-b'), [(1, 1), (2, 2), (1, 1)]) self.ae(g('a==>b'), [(1, 1), (3, 3), (1, 1)]) self.ae(g('a<==b'), [(1, 1), (3, 3), (1, 1)]) if 'iosevka' in font: self.ae(g('--->'), [(4, 4)]) self.ae(g('-' * 12 + '>'), [(13, 13)]) self.ae(g('<~~~'), [(4, 4)]) self.ae(g('a<~~~b'), [(1, 1), (4, 4), (1, 1)]) else: self.ae(g('----'), [(4, 4)]) self.ae(g('F--a--'), [(1, 1), (2, 2), (1, 1), (2, 2)]) self.ae(g('===--<>=='), [(3, 3), (2, 2), (2, 2), (2, 2)]) self.ae(g('==!=<>==<><><>'), [(4, 4), (2, 2), (2, 2), (2, 2), (2, 2), (2, 2)]) self.ae(g('-' * 18), [(18, 18)]) self.ae(g('<==>'), [(4, 4)]) self.ae(g('