chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,242 @@
|
||||
from collections.abc import Sequence
|
||||
from enum import Enum, IntEnum, auto
|
||||
from typing import TYPE_CHECKING, Literal, NamedTuple, TypedDict, Union
|
||||
|
||||
from kitty.fast_data_types import ParsedFontFeature
|
||||
from kitty.types import run_once
|
||||
from kitty.typing_compat import CoreTextFont, FontConfigPattern
|
||||
from kitty.utils import shlex_split
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import re
|
||||
|
||||
|
||||
class ListedFont(TypedDict):
|
||||
family: str
|
||||
style: str
|
||||
full_name: str
|
||||
postscript_name: str
|
||||
is_monospace: bool
|
||||
is_variable: bool
|
||||
descriptor: FontConfigPattern | CoreTextFont
|
||||
|
||||
|
||||
class VariableAxis(TypedDict):
|
||||
minimum: float
|
||||
maximum: float
|
||||
default: float
|
||||
hidden: bool
|
||||
tag: str
|
||||
strid: str # Can be empty string when not present
|
||||
|
||||
|
||||
class NamedStyle(TypedDict):
|
||||
axis_values: dict[str, float]
|
||||
name: str
|
||||
psname: str # can be empty string when not present
|
||||
|
||||
|
||||
class DesignValue1(TypedDict):
|
||||
format: Literal[1]
|
||||
flags: int
|
||||
name: str
|
||||
value: float
|
||||
|
||||
|
||||
class DesignValue2(TypedDict):
|
||||
format: Literal[2]
|
||||
flags: int
|
||||
name: str
|
||||
value: float
|
||||
minimum: float
|
||||
maximum: float
|
||||
|
||||
|
||||
class DesignValue3(TypedDict):
|
||||
format: Literal[3]
|
||||
flags: int
|
||||
name: str
|
||||
value: float
|
||||
linked_value: float
|
||||
|
||||
|
||||
DesignValue = Union[DesignValue1, DesignValue2, DesignValue3]
|
||||
|
||||
|
||||
class DesignAxis(TypedDict):
|
||||
name: str
|
||||
ordering: int
|
||||
tag: str
|
||||
values: list[DesignValue]
|
||||
|
||||
|
||||
class AxisValue(TypedDict):
|
||||
design_index: int
|
||||
value: float
|
||||
|
||||
|
||||
class MultiAxisStyle(TypedDict):
|
||||
flags: int
|
||||
name: str
|
||||
values: tuple[AxisValue, ...]
|
||||
|
||||
|
||||
class VariableData(TypedDict):
|
||||
axes: tuple[VariableAxis, ...]
|
||||
named_styles: tuple[NamedStyle, ...]
|
||||
variations_postscript_name_prefix: str
|
||||
elided_fallback_name: str
|
||||
design_axes: tuple[DesignAxis, ...]
|
||||
multi_axis_styles: tuple[MultiAxisStyle, ...]
|
||||
|
||||
|
||||
class ModificationType(Enum):
|
||||
underline_position = auto()
|
||||
underline_thickness = auto()
|
||||
strikethrough_position = auto()
|
||||
strikethrough_thickness = auto()
|
||||
cell_width = auto()
|
||||
cell_height = auto()
|
||||
baseline = auto()
|
||||
size = auto()
|
||||
|
||||
|
||||
class ModificationUnit(IntEnum):
|
||||
pt = 0
|
||||
percent = 1
|
||||
pixel = 2
|
||||
|
||||
|
||||
class ModificationValue(NamedTuple):
|
||||
val: float
|
||||
unit: ModificationUnit
|
||||
|
||||
def __repr__(self) -> str:
|
||||
u = '%' if self.unit is ModificationUnit.percent else ''
|
||||
return f'{self.val:g}{u}'
|
||||
|
||||
|
||||
class FontModification(NamedTuple):
|
||||
mod_type: ModificationType
|
||||
mod_value: ModificationValue
|
||||
font_name: str = ''
|
||||
|
||||
def __repr__(self) -> str:
|
||||
fn = f' {self.font_name}' if self.font_name else ''
|
||||
return f'{self.mod_type.name}{fn} {self.mod_value}'
|
||||
|
||||
|
||||
class FontSpec(NamedTuple):
|
||||
family: str | None = None
|
||||
style: str | None = None
|
||||
postscript_name: str | None = None
|
||||
full_name: str | None = None
|
||||
system: str | None = None
|
||||
axes: tuple[tuple[str, float], ...] = ()
|
||||
variable_name: str | None = None
|
||||
features: tuple[ParsedFontFeature, ...] = ()
|
||||
created_from_string: str = ''
|
||||
|
||||
@classmethod
|
||||
def from_setting(cls, spec: str) -> 'FontSpec':
|
||||
if spec == 'auto':
|
||||
return FontSpec(system='auto', created_from_string=spec)
|
||||
items = tuple(shlex_split(spec))
|
||||
if '=' not in items[0]:
|
||||
return FontSpec(system=spec, created_from_string=spec)
|
||||
axes = {}
|
||||
defined = {}
|
||||
features: tuple[ParsedFontFeature, ...] = ()
|
||||
for item in items:
|
||||
k, sep, v = item.partition('=')
|
||||
if sep != '=':
|
||||
raise ValueError(f'The font specification: {spec} is not valid as {item} does not contain an =')
|
||||
if k in ('family', 'style', 'full_name', 'postscript_name', 'variable_name'):
|
||||
defined[k] = v
|
||||
elif k == 'features':
|
||||
features += tuple(ParsedFontFeature(x) for x in v.split())
|
||||
else:
|
||||
try:
|
||||
axes[k] = float(v)
|
||||
except Exception:
|
||||
raise ValueError(f'The font specification: {spec} is not valid as {v} is not a number')
|
||||
return FontSpec(axes=tuple(axes.items()), created_from_string=spec, features=features, **defined)
|
||||
|
||||
@property
|
||||
def is_system(self) -> bool:
|
||||
return bool(self.system)
|
||||
|
||||
@property
|
||||
def is_auto(self) -> bool:
|
||||
return self.system == 'auto'
|
||||
|
||||
@property
|
||||
def as_setting(self) -> str:
|
||||
if self.created_from_string:
|
||||
return self.created_from_string
|
||||
if self.system:
|
||||
return self.system
|
||||
ans = []
|
||||
from shlex import quote
|
||||
|
||||
def a(key: str, val: str) -> None:
|
||||
ans.append(f'{key}={quote(val)}')
|
||||
|
||||
if self.family is not None:
|
||||
a('family', self.family)
|
||||
if self.postscript_name is not None:
|
||||
a('postscript_name', self.postscript_name)
|
||||
if self.full_name is not None:
|
||||
a('full_name', self.full_name)
|
||||
if self.variable_name is not None:
|
||||
a('variable_name', self.variable_name)
|
||||
if self.style is not None:
|
||||
a('style', self.style)
|
||||
if self.features:
|
||||
a('features', ' '.join(str(f) for f in self.features))
|
||||
if self.axes:
|
||||
for key, val in self.axes:
|
||||
a(key, f'{val:g}')
|
||||
return ' '.join(ans)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.as_setting
|
||||
|
||||
# Cannot change __repr__ as it will break config generation
|
||||
|
||||
|
||||
Descriptor = Union[FontConfigPattern, CoreTextFont]
|
||||
|
||||
|
||||
class Score(NamedTuple):
|
||||
variable_score: int
|
||||
style_score: float
|
||||
monospace_score: int
|
||||
width_score: int
|
||||
|
||||
|
||||
class Scorer[T]:
|
||||
def __init__(self, bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> None:
|
||||
self.bold = bold
|
||||
self.italic = italic
|
||||
self.monospaced = monospaced
|
||||
self.prefer_variable = prefer_variable
|
||||
|
||||
def sorted_candidates(self, candidates: Sequence[T], dump: bool = False) -> list[T]:
|
||||
raise NotImplementedError()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'{self.__class__.__name__}(bold={self.bold}, italic={self.italic}, monospaced={self.monospaced}, prefer_variable={self.prefer_variable})'
|
||||
|
||||
__str__ = __repr__
|
||||
|
||||
|
||||
@run_once
|
||||
def fnname_pat() -> 're.Pattern[str]':
|
||||
import re
|
||||
|
||||
return re.compile(r'\s+')
|
||||
|
||||
|
||||
def family_name_to_key(family: str) -> str:
|
||||
return fnname_pat().sub(' ', family).strip().lower()
|
||||
@@ -0,0 +1,579 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import copy
|
||||
from typing import TYPE_CHECKING, Any, Literal, TypedDict, Union, cast
|
||||
|
||||
from kitty.constants import is_macos
|
||||
from kitty.fast_data_types import ParsedFontFeature
|
||||
from kitty.fonts import Descriptor, DesignAxis, FontSpec, NamedStyle, Scorer, VariableAxis, VariableData, family_name_to_key
|
||||
from kitty.options.types import Options
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.fast_data_types import CoreTextFont, CTFace, FontConfigPattern
|
||||
from kitty.fast_data_types import Face as FT_Face
|
||||
|
||||
FontCollectionMapType = Literal['family_map', 'ps_map', 'full_map', 'variable_map']
|
||||
FontMap = dict[FontCollectionMapType, dict[str, list[Descriptor]]]
|
||||
Face = Union[FT_Face, CTFace]
|
||||
|
||||
def all_fonts_map(monospaced: bool) -> FontMap: ...
|
||||
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer: ...
|
||||
def find_best_match(
|
||||
family: str,
|
||||
bold: bool = False,
|
||||
italic: bool = False,
|
||||
monospaced: bool = True,
|
||||
ignore_face: Descriptor | None = None,
|
||||
prefer_variable: bool = False,
|
||||
) -> Descriptor: ...
|
||||
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> Descriptor: ...
|
||||
def face_from_descriptor(descriptor: Descriptor, font_sz_in_pts: float | None = None, dpi_x: float | None = None, dpi_y: float | None = None) -> Face: ...
|
||||
def is_monospace(descriptor: Descriptor) -> bool: ...
|
||||
def is_variable(descriptor: Descriptor) -> bool: ...
|
||||
def set_named_style(name: str, font: Descriptor, vd: VariableData) -> bool: ...
|
||||
def set_axis_values(tag_map: dict[str, float], font: Descriptor, vd: VariableData) -> bool: ...
|
||||
def get_axis_values(font: Descriptor, vd: VariableData) -> dict[str, float]: ...
|
||||
else:
|
||||
FontCollectionMapType = FontMap = None
|
||||
from kitty.fast_data_types import specialize_font_descriptor
|
||||
|
||||
if is_macos:
|
||||
from kitty.fast_data_types import CTFace as Face
|
||||
from kitty.fonts.core_text import (
|
||||
all_fonts_map,
|
||||
create_scorer,
|
||||
find_best_match,
|
||||
find_last_resort_text_font,
|
||||
get_axis_values,
|
||||
is_monospace,
|
||||
is_variable,
|
||||
set_axis_values,
|
||||
set_named_style,
|
||||
)
|
||||
else:
|
||||
from kitty.fast_data_types import Face
|
||||
from kitty.fonts.fontconfig import (
|
||||
all_fonts_map,
|
||||
create_scorer,
|
||||
find_best_match,
|
||||
find_last_resort_text_font,
|
||||
get_axis_values,
|
||||
is_monospace,
|
||||
is_variable,
|
||||
set_axis_values,
|
||||
set_named_style,
|
||||
)
|
||||
|
||||
def face_from_descriptor(descriptor: Descriptor, font_sz_in_pts: float | None = None, dpi_x: float | None = None, dpi_y: float | None = None) -> Face:
|
||||
if font_sz_in_pts is not None:
|
||||
descriptor = specialize_font_descriptor(descriptor, font_sz_in_pts, dpi_x, dpi_y)
|
||||
return Face(descriptor=descriptor)
|
||||
|
||||
|
||||
cache_for_variable_data_by_path: dict[str, VariableData] = {}
|
||||
|
||||
|
||||
def clear_caches() -> None:
|
||||
cache_for_variable_data_by_path.clear()
|
||||
actually_variable_cache.clear()
|
||||
|
||||
|
||||
attr_map = {(False, False): 'font_family', (True, False): 'bold_font', (False, True): 'italic_font', (True, True): 'bold_italic_font'}
|
||||
|
||||
|
||||
class Event:
|
||||
is_set: bool = False
|
||||
|
||||
|
||||
class FamilyAxisValues:
|
||||
regular_weight: float | None = None
|
||||
regular_slant: float | None = None
|
||||
regular_ital: float | None = None
|
||||
regular_width: float | None = None
|
||||
|
||||
bold_weight: float | None = None
|
||||
|
||||
italic_slant: float | None = None
|
||||
italic_ital: float | None = None
|
||||
|
||||
def get_wght(self, bold: bool, italic: bool) -> float | None:
|
||||
return self.bold_weight if bold else self.regular_weight
|
||||
|
||||
def get_ital(self, bold: bool, italic: bool) -> float | None:
|
||||
return self.italic_ital if italic else self.regular_ital
|
||||
|
||||
def get_slnt(self, bold: bool, italic: bool) -> float | None:
|
||||
return self.italic_slant if italic else self.regular_slant
|
||||
|
||||
def get_wdth(self, bold: bool, italic: bool) -> float | None:
|
||||
return self.regular_width
|
||||
|
||||
def get(self, tag: str, bold: bool, italic: bool) -> float | None:
|
||||
f = getattr(self, f'get_{tag}', None)
|
||||
return None if f is None else f(bold, italic)
|
||||
|
||||
def set_regular_values(self, axis_values: dict[str, float]) -> None:
|
||||
self.regular_weight = axis_values.get('wght')
|
||||
self.regular_width = axis_values.get('wdth')
|
||||
self.regular_ital = axis_values.get('ital')
|
||||
self.regular_slant = axis_values.get('slnt')
|
||||
|
||||
def set_bold_values(self, axis_values: dict[str, float]) -> None:
|
||||
self.bold_weight = axis_values.get('wght')
|
||||
|
||||
def set_italic_values(self, axis_values: dict[str, float]) -> None:
|
||||
self.italic_ital = axis_values.get('ital')
|
||||
self.italic_slant = axis_values.get('slnt')
|
||||
|
||||
|
||||
def get_variable_data_for_descriptor(d: Descriptor) -> VariableData:
|
||||
if not d['path']:
|
||||
return face_from_descriptor(d).get_variable_data()
|
||||
ans = cache_for_variable_data_by_path.get(d['path'])
|
||||
if ans is None:
|
||||
ans = cache_for_variable_data_by_path[d['path']] = face_from_descriptor(d).get_variable_data()
|
||||
return ans
|
||||
|
||||
|
||||
def get_variable_data_for_face(d: Face) -> VariableData:
|
||||
path = d.path
|
||||
if not path:
|
||||
return d.get_variable_data()
|
||||
ans = cache_for_variable_data_by_path.get(path)
|
||||
if ans is None:
|
||||
ans = cache_for_variable_data_by_path[path] = d.get_variable_data()
|
||||
return ans
|
||||
|
||||
|
||||
def find_best_match_in_candidates[T](candidates: list[T], scorer: Scorer[T], is_medium_face: bool, ignore_face: T | None = None) -> T | None:
|
||||
if candidates:
|
||||
for x in scorer.sorted_candidates(candidates):
|
||||
if ignore_face is None or x != ignore_face:
|
||||
return x
|
||||
return None
|
||||
|
||||
|
||||
def pprint(*a: Any, **kw: Any) -> None:
|
||||
from pprint import pprint
|
||||
|
||||
pprint(*a, **kw)
|
||||
|
||||
|
||||
def find_medium_variant[T: (CoreTextFont | FontConfigPattern)](font: T) -> T:
|
||||
font = copy.copy(font)
|
||||
vd = get_variable_data_for_descriptor(font)
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['name'] == 'Regular':
|
||||
set_named_style(ns['psname'] or ns['name'], font, vd)
|
||||
return font
|
||||
axis_values = {}
|
||||
for i, ax in enumerate(vd['axes']):
|
||||
tag = ax['tag']
|
||||
for dax in vd['design_axes']:
|
||||
if dax['tag'] == tag:
|
||||
for x in dax['values']:
|
||||
if x['format'] in (1, 2):
|
||||
if x['name'] == 'Regular':
|
||||
axis_values[tag] = x['value']
|
||||
break
|
||||
if axis_values:
|
||||
set_axis_values(axis_values, font, vd)
|
||||
return font
|
||||
|
||||
|
||||
def get_bold_design_weight(dax: DesignAxis, ax: VariableAxis, regular_weight: float) -> float:
|
||||
ans = regular_weight
|
||||
candidates = []
|
||||
for x in dax['values']:
|
||||
if x['format'] in (1, 2):
|
||||
if x['value'] > regular_weight:
|
||||
candidates.append(x['value'])
|
||||
if candidates:
|
||||
ans = min(candidates)
|
||||
return ans
|
||||
|
||||
|
||||
def get_design_value_for(dax: DesignAxis, ax: VariableAxis, bold: bool, italic: bool, family_axis_values: FamilyAxisValues) -> float:
|
||||
family_val = family_axis_values.get(ax['tag'], bold, italic)
|
||||
if family_val is not None and ax['minimum'] <= family_val <= ax['maximum']:
|
||||
return family_val
|
||||
default = ax['default']
|
||||
if dax['tag'] == 'wght':
|
||||
keys = ('semibold', 'bold', 'heavy', 'black') if bold else ('regular', 'medium')
|
||||
elif dax['tag'] in ('ital', 'slnt'):
|
||||
keys = ('italic', 'oblique', 'slanted', 'slant') if italic else ('regular', 'normal', 'medium', 'upright')
|
||||
else:
|
||||
return default
|
||||
priorities = {}
|
||||
for x in dax['values']:
|
||||
if x['format'] in (1, 2):
|
||||
q = x['name'].lower()
|
||||
try:
|
||||
idx = keys.index(q)
|
||||
except ValueError:
|
||||
continue
|
||||
priorities[x['value']] = idx
|
||||
ans = default
|
||||
if priorities:
|
||||
ans = sorted(priorities, key=priorities.__getitem__)[0]
|
||||
if bold and ax['tag'] == 'wght' and family_axis_values.regular_weight is not None and ans <= family_axis_values.regular_weight:
|
||||
ans = get_bold_design_weight(dax, ax, family_axis_values.regular_weight)
|
||||
return ans
|
||||
|
||||
|
||||
def find_bold_italic_variant(medium: Descriptor, bold: bool, italic: bool, family_axis_values: FamilyAxisValues) -> Descriptor:
|
||||
# we first pick the best font file for bold/italic if there are more than
|
||||
# one. For example SourceCodeVF has Italic and Upright faces with variable
|
||||
# weights in each, so we rely on the OS font matcher to give us the best
|
||||
# font file.
|
||||
monospaced = is_monospace(medium)
|
||||
unsorted = all_fonts_map(monospaced)['variable_map'][family_name_to_key(medium['family'])]
|
||||
fonts = create_scorer(bold, italic, monospaced).sorted_candidates(unsorted)
|
||||
vd = get_variable_data_for_descriptor(fonts[0])
|
||||
ans = fonts[0].copy()
|
||||
# now we need to specialise all axes in ans
|
||||
axis_values = {}
|
||||
dax_map = {dax['tag']: dax for dax in vd['design_axes']}
|
||||
for ax in vd['axes']:
|
||||
tag = ax['tag']
|
||||
dax = dax_map.get(tag)
|
||||
if dax is not None:
|
||||
axis_values[tag] = get_design_value_for(dax, ax, bold, italic, family_axis_values)
|
||||
if axis_values:
|
||||
set_axis_values(axis_values, ans, vd)
|
||||
return ans
|
||||
|
||||
|
||||
def find_best_variable_face(spec: FontSpec, bold: bool, italic: bool, monospaced: bool, candidates: list[Descriptor]) -> Descriptor:
|
||||
if spec.variable_name is not None:
|
||||
q = spec.variable_name.lower()
|
||||
for font in candidates:
|
||||
vd = get_variable_data_for_descriptor(font)
|
||||
if vd['variations_postscript_name_prefix'].lower() == q:
|
||||
return font
|
||||
if spec.style:
|
||||
q = spec.style.lower()
|
||||
for font in candidates:
|
||||
vd = get_variable_data_for_descriptor(font)
|
||||
for x in vd['named_styles']:
|
||||
if x['psname'].lower() == q:
|
||||
return font
|
||||
for x in vd['named_styles']:
|
||||
if x['name'].lower() == q:
|
||||
return font
|
||||
return create_scorer(bold, italic, monospaced).sorted_candidates(candidates)[0]
|
||||
|
||||
|
||||
def get_fine_grained_font(
|
||||
spec: FontSpec,
|
||||
bold: bool = False,
|
||||
italic: bool = False,
|
||||
family_axis_values: FamilyAxisValues = FamilyAxisValues(),
|
||||
resolved_medium_font: Descriptor | None = None,
|
||||
monospaced: bool = True,
|
||||
match_is_more_specific_than_family: Event = Event(),
|
||||
) -> Descriptor:
|
||||
font_map = all_fonts_map(monospaced)
|
||||
is_medium_face = resolved_medium_font is None
|
||||
scorer = create_scorer(bold, italic, monospaced)
|
||||
if spec.postscript_name:
|
||||
q = find_best_match_in_candidates(font_map['ps_map'].get(family_name_to_key(spec.postscript_name), []), scorer, is_medium_face)
|
||||
if q:
|
||||
match_is_more_specific_than_family.is_set = True
|
||||
return q
|
||||
if spec.full_name:
|
||||
q = find_best_match_in_candidates(font_map['full_map'].get(family_name_to_key(spec.full_name), []), scorer, is_medium_face)
|
||||
if q:
|
||||
match_is_more_specific_than_family.is_set = True
|
||||
return q
|
||||
if spec.family:
|
||||
key = family_name_to_key(spec.family)
|
||||
# First look for a variable font
|
||||
candidates = font_map['variable_map'].get(key, [])
|
||||
if candidates:
|
||||
q = candidates[0] if len(candidates) == 1 else find_best_variable_face(spec, bold, italic, monospaced, candidates)
|
||||
q, applied = apply_variation_to_pattern(q, spec)
|
||||
if applied:
|
||||
match_is_more_specific_than_family.is_set = True
|
||||
return q
|
||||
return find_medium_variant(q) if resolved_medium_font is None else find_bold_italic_variant(resolved_medium_font, bold, italic, family_axis_values)
|
||||
# Now look for any font
|
||||
candidates = font_map['family_map'].get(key, [])
|
||||
if candidates:
|
||||
if spec.style:
|
||||
qs = spec.style.lower()
|
||||
candidates = [x for x in candidates if x['style'].lower() == qs]
|
||||
q = find_best_match_in_candidates(candidates, scorer, is_medium_face)
|
||||
if q:
|
||||
return q
|
||||
|
||||
return find_last_resort_text_font(bold, italic, monospaced)
|
||||
|
||||
|
||||
def apply_variation_to_pattern(pat: Descriptor, spec: FontSpec) -> tuple[Descriptor, bool]:
|
||||
vd = face_from_descriptor(pat).get_variable_data()
|
||||
pat = pat.copy()
|
||||
if spec.style:
|
||||
if set_named_style(spec.style, pat, vd):
|
||||
return pat, True
|
||||
tag_map, name_map = {}, {}
|
||||
for i, ax in enumerate(vd['axes']):
|
||||
tag_map[ax['tag']] = i
|
||||
if ax['strid']:
|
||||
name_map[ax['strid'].lower()] = ax['tag']
|
||||
axis_values = {}
|
||||
for axspec in spec.axes:
|
||||
qname = axspec[0]
|
||||
if qname in tag_map:
|
||||
axis_values[qname] = axspec[1]
|
||||
continue
|
||||
tag = name_map.get(qname.lower())
|
||||
if tag:
|
||||
axis_values[tag] = axspec[1]
|
||||
return pat, set_axis_values(axis_values, pat, vd)
|
||||
|
||||
|
||||
def get_font_from_spec(
|
||||
spec: FontSpec,
|
||||
bold: bool = False,
|
||||
italic: bool = False,
|
||||
family_axis_values: FamilyAxisValues = FamilyAxisValues(),
|
||||
resolved_medium_font: Descriptor | None = None,
|
||||
match_is_more_specific_than_family: Event = Event(),
|
||||
) -> Descriptor:
|
||||
if not spec.is_system:
|
||||
ans = get_fine_grained_font(
|
||||
spec,
|
||||
bold,
|
||||
italic,
|
||||
resolved_medium_font=resolved_medium_font,
|
||||
family_axis_values=family_axis_values,
|
||||
match_is_more_specific_than_family=match_is_more_specific_than_family,
|
||||
)
|
||||
if spec.features:
|
||||
ans = ans.copy()
|
||||
ans['features'] = spec.features
|
||||
return ans
|
||||
family = spec.system or ''
|
||||
if family == 'auto':
|
||||
if bold or italic:
|
||||
assert resolved_medium_font is not None
|
||||
family = resolved_medium_font['family']
|
||||
if is_variable(resolved_medium_font) or is_actually_variable_despite_fontconfigs_lies(resolved_medium_font):
|
||||
v = find_bold_italic_variant(resolved_medium_font, bold, italic, family_axis_values=family_axis_values)
|
||||
if v is not None:
|
||||
return v
|
||||
else:
|
||||
family = 'monospace'
|
||||
return find_best_match(family, bold, italic, ignore_face=resolved_medium_font)
|
||||
|
||||
|
||||
class FontFiles(TypedDict):
|
||||
medium: Descriptor
|
||||
bold: Descriptor
|
||||
italic: Descriptor
|
||||
bi: Descriptor
|
||||
|
||||
|
||||
actually_variable_cache: dict[str, bool] = {}
|
||||
|
||||
|
||||
def is_actually_variable_despite_fontconfigs_lies(d: Descriptor) -> bool:
|
||||
if d['descriptor_type'] != 'fontconfig':
|
||||
return False
|
||||
path = d['path']
|
||||
ans = actually_variable_cache.get(path)
|
||||
if ans is not None:
|
||||
return ans
|
||||
m = all_fonts_map(is_monospace(d))['variable_map']
|
||||
for x in m.get(family_name_to_key(d['family']), ()):
|
||||
if x['path'] == path:
|
||||
actually_variable_cache[path] = True
|
||||
return True
|
||||
actually_variable_cache[path] = False
|
||||
return False
|
||||
|
||||
|
||||
def get_font_files(opts: Options) -> FontFiles:
|
||||
ans: dict[str, Descriptor] = {}
|
||||
match_is_more_specific_than_family = Event()
|
||||
medium_font = get_font_from_spec(opts.font_family, match_is_more_specific_than_family=match_is_more_specific_than_family)
|
||||
medium_font_is_variable = is_variable(medium_font) or is_actually_variable_despite_fontconfigs_lies(medium_font)
|
||||
if not match_is_more_specific_than_family.is_set and medium_font_is_variable:
|
||||
medium_font = find_medium_variant(medium_font)
|
||||
family_axis_values = FamilyAxisValues()
|
||||
if medium_font_is_variable:
|
||||
family_axis_values.set_regular_values(get_axis_values(medium_font, get_variable_data_for_descriptor(medium_font)))
|
||||
kd = {(False, False): 'medium', (True, False): 'bold', (False, True): 'italic', (True, True): 'bi'}
|
||||
for (bold, italic), attr in attr_map.items():
|
||||
if bold or italic:
|
||||
spec: FontSpec = getattr(opts, attr)
|
||||
font = get_font_from_spec(spec, bold, italic, resolved_medium_font=medium_font, family_axis_values=family_axis_values)
|
||||
# Set family axis values based on the values in font
|
||||
if not (bold and italic) and (is_variable(medium_font) or is_actually_variable_despite_fontconfigs_lies(medium_font)):
|
||||
av = get_axis_values(font, get_variable_data_for_descriptor(font))
|
||||
(family_axis_values.set_italic_values if italic else family_axis_values.set_bold_values)(av)
|
||||
if spec.is_auto and not font.get('features') and medium_font.get('features'):
|
||||
# Set font features based on medium face features
|
||||
font = font.copy()
|
||||
font['features'] = medium_font['features']
|
||||
else:
|
||||
font = medium_font
|
||||
key = kd[(bold, italic)]
|
||||
ans[key] = font
|
||||
|
||||
def apply_synthetic_matrix(font: Descriptor, bold: bool, italic: bool) -> Descriptor:
|
||||
# fontconfig's FcFontList (used by find_best_match) omits FC_MATRIX from
|
||||
# its object set, so a roman font found there carries no synthetic-italic
|
||||
# shear and its "italic" renders upright. Fira Code is the case (it ships
|
||||
# no italic), in both its static and variable builds. The italic intent
|
||||
# exists only here at selection finalize, not at face construction, so
|
||||
# recover the matrix now: for an italic slot whose chosen face is upright
|
||||
# (no slant) and has no matrix yet, ask fc_match what fontconfig would do.
|
||||
# fc_match returns a synthetic matrix only when there is no real italic to
|
||||
# use (no italic face and no slanted named instance or variable slant
|
||||
# axis); when a real italic exists it returns no matrix, so a font that is
|
||||
# already italic, static or variable, is never double-slanted. Face construction applies the matrix
|
||||
# via FT_Set_Transform; specialize_font_descriptor preserves it when the
|
||||
# descriptor is sized for rendering. Only the matrix is taken, so
|
||||
# selection is unchanged. Covers the four configured faces; fc_match
|
||||
# re-matches by family name (see commit message).
|
||||
if italic and font['descriptor_type'] == 'fontconfig' and not font.get('matrix') and not font.get('slant'):
|
||||
from kitty.fast_data_types import FC_MONO
|
||||
from kitty.fonts.fontconfig import fc_match
|
||||
|
||||
mtx = fc_match(font['family'], bold, italic, FC_MONO if is_monospace(font) else -1).get('matrix')
|
||||
if mtx:
|
||||
new_font = font.copy()
|
||||
new_font['matrix'] = mtx
|
||||
return new_font
|
||||
return font
|
||||
|
||||
return {
|
||||
'medium': ans['medium'],
|
||||
'bold': ans['bold'],
|
||||
'italic': apply_synthetic_matrix(ans['italic'], False, True),
|
||||
'bi': apply_synthetic_matrix(ans['bi'], True, True),
|
||||
}
|
||||
|
||||
|
||||
def axis_values_are_equal(defaults: dict[str, float], a: dict[str, float], b: dict[str, float]) -> bool:
|
||||
ad, bd = defaults.copy(), defaults.copy()
|
||||
ad.update(a)
|
||||
bd.update(b)
|
||||
return ad == bd
|
||||
|
||||
|
||||
def _get_named_style(axis_map: dict[str, float], vd: VariableData) -> NamedStyle | None:
|
||||
defaults = {ax['tag']: ax['default'] for ax in vd['axes']}
|
||||
for ns in vd['named_styles']:
|
||||
if axis_values_are_equal(defaults, ns['axis_values'], axis_map):
|
||||
return ns
|
||||
return None
|
||||
|
||||
|
||||
def get_named_style(face_or_descriptor: Face | Descriptor) -> NamedStyle | None:
|
||||
if isinstance(face_or_descriptor, dict):
|
||||
d = cast(Descriptor, face_or_descriptor)
|
||||
vd = get_variable_data_for_descriptor(d)
|
||||
if d['descriptor_type'] == 'fontconfig':
|
||||
ns = d.get('named_style', -1)
|
||||
if ns > -1 and ns < len(vd['named_styles']):
|
||||
return vd['named_styles'][ns]
|
||||
axis_map = {}
|
||||
axes = vd['axes']
|
||||
for i, val in enumerate(d.get('axes', ())):
|
||||
if i < len(axes):
|
||||
axis_map[axes[i]['tag']] = val
|
||||
else:
|
||||
axis_map = d.get('axis_map', {}).copy()
|
||||
else:
|
||||
face = cast(Face, face_or_descriptor)
|
||||
vd = get_variable_data_for_face(face)
|
||||
q = face.get_variation()
|
||||
if q is None:
|
||||
return None
|
||||
axis_map = q
|
||||
return _get_named_style(axis_map, vd)
|
||||
|
||||
|
||||
def get_axis_map(face_or_descriptor: Face | Descriptor) -> dict[str, float]:
|
||||
base_axis_map = {}
|
||||
axis_map: dict[str, float] = {}
|
||||
if isinstance(face_or_descriptor, dict):
|
||||
d = cast(Descriptor, face_or_descriptor)
|
||||
vd = get_variable_data_for_descriptor(d)
|
||||
if d['descriptor_type'] == 'fontconfig':
|
||||
ns = d.get('named_style', -1)
|
||||
if ns > -1 and ns < len(vd['named_styles']):
|
||||
base_axis_map = vd['named_styles'][ns]['axis_values'].copy()
|
||||
axis_map = {}
|
||||
axes = vd['axes']
|
||||
for i, val in enumerate(d.get('axes', ())):
|
||||
if i < len(axes):
|
||||
axis_map[axes[i]['tag']] = val
|
||||
|
||||
else:
|
||||
axis_map = d.get('axis_map', {}).copy()
|
||||
else:
|
||||
face = cast(Face, face_or_descriptor)
|
||||
q = face.get_variation()
|
||||
if q is not None:
|
||||
axis_map = q
|
||||
base_axis_map.update(axis_map)
|
||||
return base_axis_map
|
||||
|
||||
|
||||
def spec_for_face(family: str, face: Face) -> FontSpec:
|
||||
v = face.get_variation()
|
||||
features = tuple(map(ParsedFontFeature, face.applied_features().values()))
|
||||
if v is None:
|
||||
return FontSpec(family=family, postscript_name=face.postscript_name(), features=features)
|
||||
vd = face.get_variable_data()
|
||||
varname = vd['variations_postscript_name_prefix']
|
||||
ns = get_named_style(face)
|
||||
if ns is None:
|
||||
axes = []
|
||||
for key, val in get_axis_map(face).items():
|
||||
axes.append((key, val))
|
||||
return FontSpec(family=family, variable_name=varname, axes=tuple(axes), features=features)
|
||||
return FontSpec(family=family, variable_name=varname, style=ns['psname'] or ns['name'], features=features)
|
||||
|
||||
|
||||
def develop(family: str = '') -> None:
|
||||
import sys
|
||||
|
||||
family = family or sys.argv[-1]
|
||||
from kitty.options.utils import parse_font_spec
|
||||
|
||||
opts = Options()
|
||||
opts.font_family = parse_font_spec(family)
|
||||
ff = get_font_files(opts)
|
||||
|
||||
def s(name: str, d: Descriptor) -> None:
|
||||
f = face_from_descriptor(d)
|
||||
print(name, str(f))
|
||||
features = f.get_features()
|
||||
print(' Features :', features)
|
||||
|
||||
s('Medium :', ff['medium'])
|
||||
print()
|
||||
s('Bold :', ff['bold'])
|
||||
print()
|
||||
s('Italic :', ff['italic'])
|
||||
print()
|
||||
s('Bold-Italic:', ff['bi'])
|
||||
|
||||
|
||||
def list_fonts(monospaced: bool = True) -> dict[str, list[dict[str, str]]]:
|
||||
ans: dict[str, list[dict[str, str]]] = {}
|
||||
for key, descriptors in all_fonts_map(monospaced)['family_map'].items():
|
||||
entries = ans.setdefault(key, [])
|
||||
for d in descriptors:
|
||||
entries.append({'family': d['family'], 'psname': d['postscript_name'], 'path': d['path'], 'style': d['style']})
|
||||
return ans
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
develop()
|
||||
@@ -0,0 +1,274 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import itertools
|
||||
import operator
|
||||
from collections import defaultdict
|
||||
from collections.abc import Generator, Iterable, Sequence
|
||||
from functools import lru_cache
|
||||
from typing import NamedTuple
|
||||
|
||||
from kitty.fast_data_types import CTFace, coretext_all_fonts
|
||||
from kitty.typing_compat import CoreTextFont
|
||||
from kitty.utils import log_error
|
||||
|
||||
from . import Descriptor, ListedFont, Score, Scorer, VariableData, family_name_to_key
|
||||
|
||||
attr_map = {(False, False): 'font_family', (True, False): 'bold_font', (False, True): 'italic_font', (True, True): 'bold_italic_font'}
|
||||
|
||||
|
||||
FontMap = dict[str, dict[str, list[CoreTextFont]]]
|
||||
|
||||
|
||||
def create_font_map(all_fonts: Iterable[CoreTextFont]) -> FontMap:
|
||||
ans: FontMap = {'family_map': {}, 'ps_map': {}, 'full_map': {}, 'variable_map': {}}
|
||||
vmap: dict[str, list[CoreTextFont]] = defaultdict(list)
|
||||
for x in all_fonts:
|
||||
f = family_name_to_key(x['family'])
|
||||
s = family_name_to_key(x['style'])
|
||||
ps = family_name_to_key(x['postscript_name'])
|
||||
ans['family_map'].setdefault(f, []).append(x)
|
||||
ans['ps_map'].setdefault(ps, []).append(x)
|
||||
ans['full_map'].setdefault(f'{f} {s}', []).append(x)
|
||||
if x['variation'] is not None:
|
||||
vmap[f].append(x)
|
||||
# CoreText makes a separate descriptor for each named style in each
|
||||
# variable font file. Keep only the default style descriptor, which has an
|
||||
# empty variation dictionary. If no default exists, pick the one with the
|
||||
# smallest variation dictionary size.
|
||||
keyfunc = operator.itemgetter('path')
|
||||
for k, v in vmap.items():
|
||||
v.sort(key=keyfunc)
|
||||
uniq_per_path = []
|
||||
for _, g in itertools.groupby(v, keyfunc):
|
||||
uniq_per_path.append(sorted(g, key=lambda x: len(x['variation'] or ()))[0])
|
||||
ans['variable_map'][k] = uniq_per_path
|
||||
return ans
|
||||
|
||||
|
||||
def clear_caches() -> None:
|
||||
all_fonts_map.cache_clear()
|
||||
weight_range_for_family.cache_clear()
|
||||
|
||||
|
||||
@lru_cache(maxsize=2)
|
||||
def all_fonts_map(monospaced: bool = True) -> FontMap:
|
||||
return create_font_map(coretext_all_fonts(monospaced))
|
||||
|
||||
|
||||
def is_monospace(descriptor: CoreTextFont) -> bool:
|
||||
return descriptor['monospace']
|
||||
|
||||
|
||||
def is_variable(descriptor: CoreTextFont) -> bool:
|
||||
return descriptor['variation'] is not None
|
||||
|
||||
|
||||
def list_fonts() -> Generator[ListedFont, None, None]:
|
||||
for fd in coretext_all_fonts(False):
|
||||
f = fd['family']
|
||||
if f:
|
||||
fn = fd['display_name']
|
||||
if not fn:
|
||||
fn = f'{f} {fd["style"]}'.strip()
|
||||
yield {
|
||||
'family': f,
|
||||
'full_name': fn,
|
||||
'postscript_name': fd['postscript_name'] or '',
|
||||
'is_monospace': fd['monospace'],
|
||||
'is_variable': is_variable(fd),
|
||||
'descriptor': fd,
|
||||
'style': fd['style'],
|
||||
}
|
||||
|
||||
|
||||
class WeightRange(NamedTuple):
|
||||
minimum: float = 99999
|
||||
maximum: float = -99999
|
||||
medium: float = -99999
|
||||
bold: float = -99999
|
||||
|
||||
@property
|
||||
def is_valid(self) -> bool:
|
||||
return self.minimum != wr.minimum and self.maximum != wr.maximum and self.medium != wr.medium and self.bold != wr.bold
|
||||
|
||||
|
||||
wr = WeightRange()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def weight_range_for_family(family: str) -> WeightRange:
|
||||
faces = all_fonts_map(True)['family_map'].get(family_name_to_key(family), ())
|
||||
mini, maxi, medium, bold = wr.minimum, wr.maximum, wr.medium, wr.bold
|
||||
for face in faces:
|
||||
w = face['weight']
|
||||
mini, maxi = min(w, mini), max(w, maxi)
|
||||
s = face['style'].lower()
|
||||
if not s:
|
||||
continue
|
||||
s = s.split()[0]
|
||||
if s == 'semibold':
|
||||
bold = w
|
||||
elif s == 'bold' and bold == wr.bold:
|
||||
bold = w
|
||||
elif s == 'regular':
|
||||
medium = w
|
||||
elif s == 'medium' and medium == wr.medium:
|
||||
medium = w
|
||||
return WeightRange(mini, maxi, medium, bold)
|
||||
|
||||
|
||||
class CTScorer(Scorer[CoreTextFont]):
|
||||
weight_range: WeightRange | None = None
|
||||
|
||||
def score(self, candidate: Descriptor) -> Score:
|
||||
assert candidate['descriptor_type'] == 'core_text'
|
||||
variable_score = 0 if self.prefer_variable and candidate['variation'] is not None else 1
|
||||
bold_score = candidate['weight'] # -1 to 1 with 0 being normal
|
||||
if self.weight_range is None:
|
||||
if bold_score < 0: # thinner than normal, reject
|
||||
bold_score = 2.0
|
||||
else:
|
||||
if self.bold:
|
||||
# prefer semibold=0.3 to full bold = 0.4
|
||||
bold_score = abs(bold_score - 0.3)
|
||||
else:
|
||||
anchor = self.weight_range.bold if self.bold else self.weight_range.medium
|
||||
bold_score = abs(bold_score - anchor)
|
||||
italic_score = candidate['slant'] # -1 to 1 with 0 being upright < 0 being backward slant, abs(slant) == 1 implies 30 deg rotation
|
||||
if self.italic:
|
||||
if italic_score < 0:
|
||||
italic_score = 2.0
|
||||
else:
|
||||
italic_score = abs(1 - italic_score)
|
||||
monospace_match = 0 if candidate['monospace'] else 1
|
||||
is_regular_width = not candidate['expanded'] and not candidate['condensed']
|
||||
return Score(variable_score, bold_score + italic_score, monospace_match, 0 if is_regular_width else 1)
|
||||
|
||||
def sorted_candidates(self, candidates: Sequence[CoreTextFont], dump: bool = False) -> list[CoreTextFont]:
|
||||
self.weight_range = None
|
||||
families = {x['family'] for x in candidates}
|
||||
if len(families) == 1:
|
||||
wr = weight_range_for_family(next(iter(families)))
|
||||
if wr.is_valid and wr.medium < 0: # Operator Mono is an example of this craziness
|
||||
self.weight_range = wr
|
||||
candidates = sorted(candidates, key=self.score)
|
||||
if dump:
|
||||
print(self)
|
||||
if self.weight_range:
|
||||
print(self.weight_range)
|
||||
for x in candidates:
|
||||
assert x['descriptor_type'] == 'core_text'
|
||||
print(
|
||||
CTFace(descriptor=x).postscript_name(), f'bold={x["bold"]}', f'italic={x["italic"]}', f'weight={x["weight"]:.2f}', f'slant={x["slant"]:.2f}'
|
||||
)
|
||||
print(' ', self.score(x))
|
||||
print()
|
||||
return candidates
|
||||
|
||||
|
||||
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer:
|
||||
return CTScorer(bold, italic, monospaced, prefer_variable)
|
||||
|
||||
|
||||
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> CoreTextFont:
|
||||
font_map = all_fonts_map(monospaced)
|
||||
candidates = font_map['family_map']['menlo']
|
||||
return create_scorer(bold, italic, monospaced).sorted_candidates(candidates)[0]
|
||||
|
||||
|
||||
def find_best_match(
|
||||
family: str, bold: bool = False, italic: bool = False, monospaced: bool = True, ignore_face: CoreTextFont | None = None, prefer_variable: bool = False
|
||||
) -> CoreTextFont:
|
||||
q = family_name_to_key(family)
|
||||
font_map = all_fonts_map(monospaced)
|
||||
scorer = create_scorer(bold, italic, monospaced, prefer_variable=prefer_variable)
|
||||
|
||||
# First look for an exact match
|
||||
for selector in ('ps_map', 'full_map'):
|
||||
candidates = font_map[selector].get(q)
|
||||
if candidates:
|
||||
candidates = scorer.sorted_candidates(candidates)
|
||||
possible = candidates[0]
|
||||
if possible != ignore_face:
|
||||
return possible
|
||||
|
||||
# See if we have a variable font
|
||||
if not bold and not italic and font_map['variable_map'].get(q):
|
||||
candidates = font_map['variable_map'][q]
|
||||
candidates = scorer.sorted_candidates(candidates)
|
||||
possible = candidates[0]
|
||||
if possible != ignore_face:
|
||||
from .common import find_medium_variant
|
||||
|
||||
return find_medium_variant(possible)
|
||||
|
||||
# Let CoreText choose the font if the family exists, otherwise
|
||||
# fallback to Menlo
|
||||
if q not in font_map['family_map']:
|
||||
if family.lower() not in ('monospace', 'symbols nerd font mono'):
|
||||
log_error(f'The font {family} was not found, falling back to Menlo')
|
||||
q = 'menlo'
|
||||
candidates = scorer.sorted_candidates(font_map['family_map'][q])
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def font_for_family(family: str) -> tuple[CoreTextFont, bool, bool]:
|
||||
ans = find_best_match(family, monospaced=False)
|
||||
return ans, ans['bold'], ans['italic']
|
||||
|
||||
|
||||
def descriptor(f: ListedFont) -> CoreTextFont:
|
||||
d = f['descriptor']
|
||||
assert d['descriptor_type'] == 'core_text'
|
||||
return d
|
||||
|
||||
|
||||
def prune_family_group(g: list[ListedFont]) -> list[ListedFont]:
|
||||
# CoreText returns a separate font for every style in the variable font, so
|
||||
# merge them.
|
||||
variable_paths = {descriptor(f)['path']: False for f in g if f['is_variable']}
|
||||
if not variable_paths:
|
||||
return g
|
||||
|
||||
def is_ok(d: CoreTextFont) -> bool:
|
||||
if d['path'] not in variable_paths:
|
||||
return True
|
||||
if not variable_paths[d['path']]:
|
||||
variable_paths[d['path']] = True
|
||||
return True
|
||||
return False
|
||||
|
||||
return [x for x in g if is_ok(descriptor(x))]
|
||||
|
||||
|
||||
def set_axis_values(tag_map: dict[str, float], font: CoreTextFont, vd: VariableData) -> bool:
|
||||
known_axes = {ax['tag'] for ax in vd['axes']}
|
||||
previous = font.get('axis_map', {})
|
||||
new = previous.copy()
|
||||
for tag in known_axes:
|
||||
val = tag_map.get(tag)
|
||||
if val is not None:
|
||||
new[tag] = val
|
||||
font['axis_map'] = new
|
||||
return new != previous
|
||||
|
||||
|
||||
def set_named_style(name: str, font: CoreTextFont, vd: VariableData) -> bool:
|
||||
q = name.lower()
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['psname'].lower() == q:
|
||||
return set_axis_values(ns['axis_values'], font, vd)
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['name'].lower() == q:
|
||||
return set_axis_values(ns['axis_values'], font, vd)
|
||||
if vd['elided_fallback_name']:
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
eq = ' '.join(ns['name'].replace(vd['elided_fallback_name'], '').strip().split()).lower()
|
||||
if q == eq:
|
||||
return set_axis_values(ns['axis_values'], font, vd)
|
||||
return False
|
||||
|
||||
|
||||
def get_axis_values(font: CoreTextFont, vd: VariableData) -> dict[str, float]:
|
||||
return font.get('axis_map', {})
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from enum import IntEnum
|
||||
from typing import NamedTuple
|
||||
|
||||
|
||||
class Type(IntEnum):
|
||||
boolean = 1
|
||||
index = 2
|
||||
hidden = 3
|
||||
|
||||
|
||||
class FeatureDefinition(NamedTuple):
|
||||
name: str
|
||||
type: Type
|
||||
|
||||
|
||||
# From: https://learn.microsoft.com/en-ca/typography/opentype/spec/featurelist
|
||||
known_features: dict[str, FeatureDefinition] = { # {{{
|
||||
'aalt': FeatureDefinition('Access All Alternates', Type.index),
|
||||
'abvf': FeatureDefinition('Above-base Forms', Type.hidden),
|
||||
'abvm': FeatureDefinition('Above-base Mark Positioning', Type.hidden),
|
||||
'abvs': FeatureDefinition('Above-base Substitutions', Type.hidden),
|
||||
'afrc': FeatureDefinition('Alternative Fractions', Type.boolean),
|
||||
'akhn': FeatureDefinition('Akhand', Type.hidden),
|
||||
'blwf': FeatureDefinition('Below-base Forms', Type.hidden),
|
||||
'blwm': FeatureDefinition('Below-base Mark Positioning', Type.hidden),
|
||||
'blws': FeatureDefinition('Below-base Substitutions', Type.hidden),
|
||||
'calt': FeatureDefinition('Contextual Alternates', Type.boolean),
|
||||
'case': FeatureDefinition('Case-Sensitive Forms', Type.hidden),
|
||||
'ccmp': FeatureDefinition('Glyph Composition / Decomposition', Type.hidden),
|
||||
'cfar': FeatureDefinition('Conjunct Form After Ro', Type.hidden),
|
||||
'chws': FeatureDefinition('Contextual Half-width Spacing', Type.boolean),
|
||||
'cjct': FeatureDefinition('Conjunct Forms', Type.hidden),
|
||||
'clig': FeatureDefinition('Contextual Ligatures', Type.boolean),
|
||||
'cpct': FeatureDefinition('Centered CJK Punctuation', Type.boolean),
|
||||
'cpsp': FeatureDefinition('Capital Spacing', Type.boolean),
|
||||
'cswh': FeatureDefinition('Contextual Swash', Type.boolean),
|
||||
'curs': FeatureDefinition('Cursive Positioning', Type.hidden),
|
||||
'c2pc': FeatureDefinition('Petite Capitals From Capitals', Type.boolean),
|
||||
'c2sc': FeatureDefinition('Small Capitals From Capitals', Type.boolean),
|
||||
'dist': FeatureDefinition('Distances', Type.hidden),
|
||||
'dlig': FeatureDefinition('Discretionary Ligatures', Type.boolean),
|
||||
'dnom': FeatureDefinition('Denominators', Type.hidden),
|
||||
'dtls': FeatureDefinition('Dotless Forms', Type.hidden),
|
||||
'expt': FeatureDefinition('Expert Forms', Type.boolean),
|
||||
'falt': FeatureDefinition('Final Glyph on Line Alternates', Type.boolean),
|
||||
'fin2': FeatureDefinition('Terminal Forms #2', Type.hidden),
|
||||
'fin3': FeatureDefinition('Terminal Forms #3', Type.hidden),
|
||||
'fina': FeatureDefinition('Terminal Forms', Type.hidden),
|
||||
'flac': FeatureDefinition('Flattened accent forms', Type.hidden),
|
||||
'frac': FeatureDefinition('Fractions', Type.boolean),
|
||||
'fwid': FeatureDefinition('Full Widths', Type.boolean),
|
||||
'half': FeatureDefinition('Half Forms', Type.hidden),
|
||||
'haln': FeatureDefinition('Halant Forms', Type.hidden),
|
||||
'halt': FeatureDefinition('Alternate Half Widths', Type.boolean),
|
||||
'hist': FeatureDefinition('Historical Forms', Type.boolean),
|
||||
'hkna': FeatureDefinition('Horizontal Kana Alternates', Type.boolean),
|
||||
'hlig': FeatureDefinition('Historical Ligatures', Type.boolean),
|
||||
'hngl': FeatureDefinition('Hangul', Type.boolean),
|
||||
'hojo': FeatureDefinition('Hojo Kanji Forms (JIS X 0212-1990 Kanji Forms)', Type.boolean),
|
||||
'hwid': FeatureDefinition('Half Widths', Type.boolean),
|
||||
'init': FeatureDefinition('Initial Forms', Type.hidden),
|
||||
'isol': FeatureDefinition('Isolated Forms', Type.hidden),
|
||||
'ital': FeatureDefinition('Italics', Type.boolean),
|
||||
'jalt': FeatureDefinition('Justification Alternates', Type.boolean),
|
||||
'jp78': FeatureDefinition('JIS78 Forms', Type.boolean),
|
||||
'jp83': FeatureDefinition('JIS83 Forms', Type.boolean),
|
||||
'jp90': FeatureDefinition('JIS90 Forms', Type.boolean),
|
||||
'jp04': FeatureDefinition('JIS2004 Forms', Type.boolean),
|
||||
'kern': FeatureDefinition('Kerning', Type.boolean),
|
||||
'lfbd': FeatureDefinition('Left Bounds', Type.boolean),
|
||||
'liga': FeatureDefinition('Standard Ligatures', Type.boolean),
|
||||
'ljmo': FeatureDefinition('Leading Jamo Forms', Type.hidden),
|
||||
'lnum': FeatureDefinition('Lining Figures', Type.boolean),
|
||||
'locl': FeatureDefinition('Localized Forms', Type.hidden),
|
||||
'ltra': FeatureDefinition('Left-to-right alternates', Type.hidden),
|
||||
'ltrm': FeatureDefinition('Left-to-right mirrored forms', Type.hidden),
|
||||
'mark': FeatureDefinition('Mark Positioning', Type.hidden),
|
||||
'med2': FeatureDefinition('Medial Forms #2', Type.hidden),
|
||||
'medi': FeatureDefinition('Medial Forms', Type.hidden),
|
||||
'mgrk': FeatureDefinition('Mathematical Greek', Type.boolean),
|
||||
'mkmk': FeatureDefinition('Mark to Mark Positioning', Type.hidden),
|
||||
'mset': FeatureDefinition('Mark Positioning via Substitution', Type.hidden),
|
||||
'nalt': FeatureDefinition('Alternate Annotation Forms', Type.index),
|
||||
'nlck': FeatureDefinition('NLC Kanji Forms', Type.boolean),
|
||||
'nukt': FeatureDefinition('Nukta Forms', Type.hidden),
|
||||
'numr': FeatureDefinition('Numerators', Type.hidden),
|
||||
'onum': FeatureDefinition('Oldstyle Figures', Type.boolean),
|
||||
'opbd': FeatureDefinition('Optical Bounds', Type.boolean),
|
||||
'ordn': FeatureDefinition('Ordinals', Type.boolean),
|
||||
'ornm': FeatureDefinition('Ornaments', Type.index),
|
||||
'palt': FeatureDefinition('Proportional Alternate Widths', Type.boolean),
|
||||
'pcap': FeatureDefinition('Petite Capitals', Type.boolean),
|
||||
'pkna': FeatureDefinition('Proportional Kana', Type.boolean),
|
||||
'pnum': FeatureDefinition('Proportional Figures', Type.boolean),
|
||||
'pref': FeatureDefinition('Pre-Base Forms', Type.hidden),
|
||||
'pres': FeatureDefinition('Pre-base Substitutions', Type.hidden),
|
||||
'pstf': FeatureDefinition('Post-base Forms', Type.hidden),
|
||||
'psts': FeatureDefinition('Post-base Substitutions', Type.hidden),
|
||||
'pwid': FeatureDefinition('Proportional Widths', Type.boolean),
|
||||
'qwid': FeatureDefinition('Quarter Widths', Type.boolean),
|
||||
'rand': FeatureDefinition('Randomize', Type.boolean),
|
||||
'rclt': FeatureDefinition('Required Contextual Alternates', Type.hidden),
|
||||
'rkrf': FeatureDefinition('Rakar Forms', Type.hidden),
|
||||
'rlig': FeatureDefinition('Required Ligatures', Type.hidden),
|
||||
'rphf': FeatureDefinition('Reph Forms', Type.hidden),
|
||||
'rtbd': FeatureDefinition('Right Bounds', Type.boolean),
|
||||
'rtla': FeatureDefinition('Right-to-left alternates', Type.hidden),
|
||||
'rtlm': FeatureDefinition('Right-to-left mirrored forms', Type.hidden),
|
||||
'ruby': FeatureDefinition('Ruby Notation Forms', Type.boolean),
|
||||
'rvrn': FeatureDefinition('Required Variation Alternates', Type.hidden),
|
||||
'salt': FeatureDefinition('Stylistic Alternates', Type.index),
|
||||
'sinf': FeatureDefinition('Scientific Inferiors', Type.boolean),
|
||||
'size': FeatureDefinition('Optical size', Type.hidden),
|
||||
'smcp': FeatureDefinition('Small Capitals', Type.boolean),
|
||||
'smpl': FeatureDefinition('Simplified Forms', Type.boolean),
|
||||
'ssty': FeatureDefinition('Math script style alternates', Type.hidden),
|
||||
'stch': FeatureDefinition('Stretching Glyph Decomposition', Type.hidden),
|
||||
'subs': FeatureDefinition('Subscript', Type.boolean),
|
||||
'sups': FeatureDefinition('Superscript', Type.boolean),
|
||||
'swsh': FeatureDefinition('Swash', Type.index),
|
||||
'titl': FeatureDefinition('Titling', Type.boolean),
|
||||
'tjmo': FeatureDefinition('Trailing Jamo Forms', Type.hidden),
|
||||
'tnam': FeatureDefinition('Traditional Name Forms', Type.boolean),
|
||||
'tnum': FeatureDefinition('Tabular Figures', Type.boolean),
|
||||
'trad': FeatureDefinition('Traditional Forms', Type.index),
|
||||
'twid': FeatureDefinition('Third Widths', Type.boolean),
|
||||
'unic': FeatureDefinition('Unicase', Type.boolean),
|
||||
'valt': FeatureDefinition('Alternate Vertical Metrics', Type.boolean),
|
||||
'vatu': FeatureDefinition('Vattu Variants', Type.hidden),
|
||||
'vchw': FeatureDefinition('Vertical Contextual Half-width Spacing', Type.hidden),
|
||||
'vert': FeatureDefinition('Vertical Writing', Type.boolean),
|
||||
'vhal': FeatureDefinition('Alternate Vertical Half Metrics', Type.boolean),
|
||||
'vjmo': FeatureDefinition('Vowel Jamo Forms', Type.hidden),
|
||||
'vkna': FeatureDefinition('Vertical Kana Alternates', Type.boolean),
|
||||
'vkrn': FeatureDefinition('Vertical Kerning', Type.boolean),
|
||||
'vpal': FeatureDefinition('Proportional Alternate Vertical Metrics', Type.boolean),
|
||||
'vrt2': FeatureDefinition('Vertical Alternates and Rotation', Type.boolean),
|
||||
'vrtr': FeatureDefinition('Vertical Alternates for Rotation', Type.boolean),
|
||||
'zero': FeatureDefinition('Slashed Zero', Type.boolean),
|
||||
}
|
||||
for i in range(1, 100):
|
||||
known_features[f'cv{i:02d}'] = FeatureDefinition(f'Character Variant {i}', Type.index)
|
||||
for i in range(1, 20):
|
||||
known_features[f'ss{i:02d}'] = FeatureDefinition(f'Stylistic Set {i}', Type.boolean)
|
||||
# }}}
|
||||
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
from collections.abc import Generator, Sequence
|
||||
from functools import lru_cache
|
||||
from typing import Literal, NamedTuple, Optional, cast
|
||||
|
||||
from kitty.fast_data_types import (
|
||||
FC_DUAL,
|
||||
FC_MONO,
|
||||
FC_SLANT_ITALIC,
|
||||
FC_SLANT_ROMAN,
|
||||
FC_WEIGHT_REGULAR,
|
||||
FC_WIDTH_NORMAL,
|
||||
Face,
|
||||
clear_fallback_font_cache,
|
||||
fc_list,
|
||||
)
|
||||
from kitty.fast_data_types import (
|
||||
FC_WEIGHT_SEMIBOLD as FC_WEIGHT_BOLD,
|
||||
)
|
||||
from kitty.fast_data_types import fc_match as fc_match_impl
|
||||
from kitty.typing_compat import FontConfigPattern
|
||||
|
||||
from . import Descriptor, ListedFont, Score, Scorer, VariableData, family_name_to_key
|
||||
|
||||
FontCollectionMapType = Literal['family_map', 'ps_map', 'full_map', 'variable_map']
|
||||
FontMap = dict[FontCollectionMapType, dict[str, list[FontConfigPattern]]]
|
||||
|
||||
|
||||
def create_font_map(all_fonts: tuple[FontConfigPattern, ...]) -> FontMap:
|
||||
ans: FontMap = {'family_map': {}, 'ps_map': {}, 'full_map': {}, 'variable_map': {}}
|
||||
for x in all_fonts:
|
||||
if not x.get('path'):
|
||||
continue
|
||||
f = family_name_to_key(x['family'])
|
||||
full = family_name_to_key(x['full_name'])
|
||||
ps = family_name_to_key(x['postscript_name'])
|
||||
ans['family_map'].setdefault(f, []).append(x)
|
||||
ans['ps_map'].setdefault(ps, []).append(x)
|
||||
ans['full_map'].setdefault(full, []).append(x)
|
||||
if x['variable']:
|
||||
ans['variable_map'].setdefault(f, []).append(x)
|
||||
return ans
|
||||
|
||||
|
||||
def clear_caches() -> None:
|
||||
all_fonts_map.cache_clear()
|
||||
fc_match.cache_clear()
|
||||
weight_range_for_family.cache_clear()
|
||||
clear_fallback_font_cache()
|
||||
|
||||
|
||||
@lru_cache(maxsize=2)
|
||||
def all_fonts_map(monospaced: bool = True) -> FontMap:
|
||||
if monospaced:
|
||||
ans = fc_list(spacing=FC_DUAL) + fc_list(spacing=FC_MONO)
|
||||
else:
|
||||
# allow non-monospaced and bitmapped fonts as these are used for
|
||||
# symbol_map
|
||||
ans = fc_list(allow_bitmapped_fonts=True)
|
||||
return create_font_map(ans)
|
||||
|
||||
|
||||
def is_monospace(descriptor: FontConfigPattern) -> bool:
|
||||
return descriptor['spacing'] in ('MONO', 'DUAL')
|
||||
|
||||
|
||||
def is_variable(descriptor: FontConfigPattern) -> bool:
|
||||
return descriptor['variable']
|
||||
|
||||
|
||||
def list_fonts(only_variable: bool = False) -> Generator[ListedFont, None, None]:
|
||||
for fd in fc_list(only_variable=only_variable):
|
||||
f = fd.get('family')
|
||||
if f and isinstance(f, str):
|
||||
fn_ = fd.get('full_name')
|
||||
if fn_:
|
||||
fn = str(fn_)
|
||||
else:
|
||||
fn = f'{f} {fd.get("style", "")}'.strip()
|
||||
yield {
|
||||
'family': f,
|
||||
'full_name': fn,
|
||||
'postscript_name': str(fd.get('postscript_name', '')),
|
||||
'is_monospace': is_monospace(fd),
|
||||
'descriptor': fd,
|
||||
'is_variable': is_variable(fd),
|
||||
'style': fd['style'],
|
||||
}
|
||||
|
||||
|
||||
@lru_cache
|
||||
def fc_match(family: str, bold: bool, italic: bool, spacing: int = FC_MONO) -> FontConfigPattern:
|
||||
return fc_match_impl(family, bold, italic, spacing)
|
||||
|
||||
|
||||
class WeightRange(NamedTuple):
|
||||
minimum: int = sys.maxsize
|
||||
maximum: int = -1
|
||||
medium: int = -1
|
||||
bold: int = -1
|
||||
|
||||
@property
|
||||
def is_valid(self) -> bool:
|
||||
return self.minimum != wr.minimum and self.maximum != wr.maximum and self.medium != wr.medium and self.bold != wr.bold
|
||||
|
||||
|
||||
wr = WeightRange()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def weight_range_for_family(family: str) -> WeightRange:
|
||||
faces = all_fonts_map(True)['family_map'].get(family_name_to_key(family), ())
|
||||
mini, maxi, medium, bold = wr.minimum, wr.maximum, wr.medium, wr.bold
|
||||
seen_weights = set()
|
||||
for face in faces:
|
||||
w = face['weight']
|
||||
mini, maxi = min(w, mini), max(w, maxi)
|
||||
seen_weights.add(w)
|
||||
s = face['style'].lower()
|
||||
if not s:
|
||||
continue
|
||||
s = s.split()[0]
|
||||
if s == 'semibold':
|
||||
bold = w
|
||||
elif s == 'bold' and bold == wr.bold:
|
||||
bold = w
|
||||
elif s == 'regular':
|
||||
medium = w
|
||||
elif s == 'medium' and medium == wr.medium:
|
||||
medium = w
|
||||
if len(seen_weights) < 2:
|
||||
return wr
|
||||
return WeightRange(mini, maxi, medium, bold)
|
||||
|
||||
|
||||
class FCScorer(Scorer[FontConfigPattern]):
|
||||
weight_range: WeightRange | None = None
|
||||
|
||||
def score(self, candidate: Descriptor) -> Score:
|
||||
assert candidate['descriptor_type'] == 'fontconfig'
|
||||
variable_score = 0 if self.prefer_variable and candidate['variable'] else 1
|
||||
if self.weight_range is None:
|
||||
bold_score = abs((FC_WEIGHT_BOLD if self.bold else FC_WEIGHT_REGULAR) - candidate['weight'])
|
||||
else:
|
||||
bold_score = abs((self.weight_range.bold if self.bold else self.weight_range.medium) - candidate['weight'])
|
||||
italic_score = abs((FC_SLANT_ITALIC if self.italic else FC_SLANT_ROMAN) - candidate['slant'])
|
||||
monospace_match = 0
|
||||
if self.monospaced:
|
||||
monospace_match = 0 if candidate.get('spacing') == 'MONO' else 1
|
||||
width_score = abs(candidate['width'] - FC_WIDTH_NORMAL)
|
||||
return Score(variable_score, bold_score / 1000 + italic_score / 110, monospace_match, width_score)
|
||||
|
||||
def sorted_candidates(self, candidates: Sequence[FontConfigPattern], dump: bool = False) -> list[FontConfigPattern]:
|
||||
self.weight_range = None
|
||||
families = {x['family'] for x in candidates}
|
||||
if len(families) == 1:
|
||||
wr = weight_range_for_family(next(iter(families)))
|
||||
if wr.is_valid and wr.medium < 100: # Operator Mono and Cascadia Code are examples
|
||||
self.weight_range = wr
|
||||
candidates = sorted(candidates, key=self.score)
|
||||
if dump:
|
||||
print(self)
|
||||
if self.weight_range:
|
||||
print(self.weight_range)
|
||||
for x in candidates:
|
||||
assert x['descriptor_type'] == 'fontconfig'
|
||||
print(Face(descriptor=x).postscript_name(), f'weight={x["weight"]}', f'slant={x["slant"]}')
|
||||
print(' ', self.score(x))
|
||||
print()
|
||||
return candidates
|
||||
|
||||
|
||||
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer:
|
||||
return FCScorer(bold, italic, monospaced, prefer_variable)
|
||||
|
||||
|
||||
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> FontConfigPattern:
|
||||
# Use fc-match with a generic family
|
||||
family = 'monospace' if monospaced else 'sans-serif'
|
||||
return fc_match(family, bold, italic)
|
||||
|
||||
|
||||
def find_best_match(
|
||||
family: str,
|
||||
bold: bool = False,
|
||||
italic: bool = False,
|
||||
monospaced: bool = True,
|
||||
ignore_face: FontConfigPattern | None = None,
|
||||
prefer_variable: bool = False,
|
||||
) -> FontConfigPattern:
|
||||
from .common import find_best_match_in_candidates
|
||||
|
||||
q = family_name_to_key(family)
|
||||
font_map = all_fonts_map(monospaced)
|
||||
scorer = create_scorer(bold, italic, monospaced, prefer_variable=prefer_variable)
|
||||
is_medium_face = not bold and not italic
|
||||
# First look for an exact match
|
||||
groups: tuple[FontCollectionMapType, ...] = ('ps_map', 'full_map', 'family_map')
|
||||
for which in groups:
|
||||
m = font_map[which]
|
||||
cq = m.get(q, [])
|
||||
if cq:
|
||||
if which == 'full_map' and cq[0]['family'] == cq[0]['full_name']:
|
||||
continue # IBM Plex Mono has fullname of regular face == family_name under fontconfig
|
||||
exact_match = find_best_match_in_candidates(cq, scorer, is_medium_face, ignore_face=ignore_face)
|
||||
if exact_match:
|
||||
return exact_match
|
||||
|
||||
# Use fc-match to see if we can find a monospaced font that matches family
|
||||
# When aliases are defined, spacing can cause the incorrect font to be
|
||||
# returned, so check with and without spacing and use the one that matches.
|
||||
mono_possibility = fc_match(family, False, False, FC_MONO)
|
||||
dual_possibility = fc_match(family, False, False, FC_DUAL)
|
||||
any_possibility = fc_match(family, False, False, 0)
|
||||
tries = (dual_possibility, mono_possibility) if any_possibility == dual_possibility else (mono_possibility, dual_possibility)
|
||||
for possibility in tries:
|
||||
for key, map_key in (('postscript_name', 'ps_map'), ('full_name', 'full_map'), ('family', 'family_map')):
|
||||
map_key = cast(FontCollectionMapType, map_key)
|
||||
val: str | None = cast(Optional[str], possibility.get(key))
|
||||
if val:
|
||||
candidates = font_map[map_key].get(family_name_to_key(val))
|
||||
if candidates:
|
||||
if len(candidates) == 1:
|
||||
# happens if the family name is an alias, so we search with
|
||||
# the actual family name to see if we can find all the
|
||||
# fonts in the family.
|
||||
family_name_candidates = font_map['family_map'].get(family_name_to_key(candidates[0]['family']))
|
||||
if family_name_candidates and len(family_name_candidates) > 1:
|
||||
candidates = family_name_candidates
|
||||
return scorer.sorted_candidates(candidates)[0]
|
||||
return find_last_resort_text_font(bold, italic, monospaced)
|
||||
|
||||
|
||||
def font_for_family(family: str) -> tuple[FontConfigPattern, bool, bool]:
|
||||
ans = find_best_match(family, monospaced=False)
|
||||
return ans, ans.get('weight', 0) >= FC_WEIGHT_BOLD, ans.get('slant', FC_SLANT_ROMAN) != FC_SLANT_ROMAN
|
||||
|
||||
|
||||
def descriptor(f: ListedFont) -> FontConfigPattern:
|
||||
d = f['descriptor']
|
||||
assert d['descriptor_type'] == 'fontconfig'
|
||||
return d
|
||||
|
||||
|
||||
def prune_family_group(g: list[ListedFont]) -> list[ListedFont]:
|
||||
# fontconfig creates dummy entries for named styles in variable fonts, prune them
|
||||
variable_paths = {descriptor(f)['path'] for f in g if f['is_variable']}
|
||||
if not variable_paths:
|
||||
return g
|
||||
|
||||
def is_ok(d: FontConfigPattern) -> bool:
|
||||
return d['variable'] or d['path'] not in variable_paths
|
||||
|
||||
return [x for x in g if is_ok(descriptor(x))]
|
||||
|
||||
|
||||
def set_named_style(name: str, font: FontConfigPattern, vd: VariableData) -> bool:
|
||||
q = name.lower()
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['psname'].lower() == q:
|
||||
font['named_style'] = i
|
||||
return True
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['name'].lower() == q:
|
||||
font['named_style'] = i
|
||||
return True
|
||||
if vd['elided_fallback_name']:
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
eq = ' '.join(ns['name'].replace(vd['elided_fallback_name'], '').strip().split()).lower()
|
||||
if q == eq:
|
||||
font['named_style'] = i
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def lift_axes_to_named_style_if_possible(font: FontConfigPattern, vd: VariableData) -> bool:
|
||||
axes = font.get('axes', tuple(ax['default'] for ax in vd['axes']))
|
||||
q = {vd['axes'][i]['tag']: val for i, val in enumerate(axes)}
|
||||
for i, ns in enumerate(vd['named_styles']):
|
||||
if ns['axis_values'] == q:
|
||||
font.pop('axes', None)
|
||||
font['named_style'] = i
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def set_axis_values(tag_map: dict[str, float], font: FontConfigPattern, vd: VariableData) -> bool:
|
||||
axes = list(font.get('axes', ())) or [ax['default'] for ax in vd['axes']]
|
||||
changed = False
|
||||
for i, ax in enumerate(vd['axes']):
|
||||
val = tag_map.get(ax['tag'])
|
||||
if val is not None:
|
||||
changed = True
|
||||
axes[i] = val
|
||||
if changed:
|
||||
font['axes'] = tuple(axes)
|
||||
lift_axes_to_named_style_if_possible(font, vd)
|
||||
return changed
|
||||
|
||||
|
||||
def get_axis_values(font: FontConfigPattern, vd: VariableData) -> dict[str, float]:
|
||||
ans: dict[str, float] = {}
|
||||
ns = font.get('named_style')
|
||||
if ns is not None:
|
||||
if ns > -1 and ns < len(vd['named_styles']):
|
||||
ans = vd['named_styles'][ns]['axis_values']
|
||||
|
||||
axis_values = font.get('axes', ())
|
||||
for i, ax in enumerate(vd['axes']):
|
||||
tag = ax['tag']
|
||||
if i < len(axis_values):
|
||||
ans[tag] = axis_values[i]
|
||||
else:
|
||||
if tag not in ans:
|
||||
ans[tag] = ax['default']
|
||||
return ans
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from kitty.constants import is_macos
|
||||
|
||||
from . import ListedFont
|
||||
from .common import get_variable_data_for_descriptor
|
||||
|
||||
if is_macos:
|
||||
from .core_text import list_fonts, prune_family_group
|
||||
else:
|
||||
from .fontconfig import list_fonts, prune_family_group
|
||||
|
||||
|
||||
def create_family_groups(monospaced: bool = True) -> dict[str, list[ListedFont]]:
|
||||
g: dict[str, list[ListedFont]] = {}
|
||||
for f in list_fonts():
|
||||
if not monospaced or f['is_monospace']:
|
||||
g.setdefault(f['family'], []).append(f)
|
||||
return {k: prune_family_group(v) for k, v in g.items()}
|
||||
|
||||
|
||||
def as_json(indent: int | None = None) -> str:
|
||||
import json
|
||||
|
||||
groups = create_family_groups()
|
||||
for v in groups.values():
|
||||
for f in v:
|
||||
f['variable_data'] = get_variable_data_for_descriptor(f['descriptor']) # type: ignore
|
||||
return json.dumps(groups, indent=indent)
|
||||
|
||||
|
||||
def main(argv: Sequence[str]) -> None:
|
||||
import os
|
||||
|
||||
from kitty.constants import kitten_exe, kitty_exe
|
||||
|
||||
argv = list(argv)
|
||||
if '--psnames' in argv:
|
||||
argv.remove('--psnames')
|
||||
os.environ['KITTY_PATH_TO_KITTY_EXE'] = kitty_exe()
|
||||
os.execlp(kitten_exe(), 'kitten', 'choose-fonts')
|
||||
@@ -0,0 +1,388 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Callable, Generator
|
||||
from typing import TYPE_CHECKING, Any, Literal, Union
|
||||
|
||||
from kitty.constants import fonts_dir, is_macos
|
||||
from kitty.fast_data_types import (
|
||||
Screen,
|
||||
concat_cells,
|
||||
create_test_font_group,
|
||||
current_fonts,
|
||||
get_fallback_font,
|
||||
render_decoration,
|
||||
set_builtin_nerd_font,
|
||||
set_font_data,
|
||||
set_options,
|
||||
set_send_sprite_to_gpu,
|
||||
sprite_idx_to_pos,
|
||||
sprite_map_set_limits,
|
||||
test_render_line,
|
||||
test_shape,
|
||||
)
|
||||
from kitty.options.types import Options, defaults
|
||||
from kitty.options.utils import parse_font_spec
|
||||
from kitty.typing_compat import CoreTextFont, FontConfigPattern
|
||||
from kitty.utils import log_error
|
||||
|
||||
from . import family_name_to_key
|
||||
from .common import get_font_files
|
||||
|
||||
if is_macos:
|
||||
from .core_text import font_for_family as font_for_family_macos
|
||||
else:
|
||||
from .fontconfig import font_for_family as font_for_family_fontconfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.fast_data_types import CTFace, DecorationTypes, Face
|
||||
else:
|
||||
DecorationTypes = str
|
||||
|
||||
FontObject = Union[CoreTextFont, FontConfigPattern]
|
||||
current_faces: list[tuple[FontObject, bool, bool]] = []
|
||||
builtin_nerd_font_descriptor: FontObject | None = None
|
||||
|
||||
|
||||
def font_for_family(family: str) -> tuple[FontObject, bool, bool]:
|
||||
if is_macos:
|
||||
return font_for_family_macos(family)
|
||||
return font_for_family_fontconfig(family)
|
||||
|
||||
|
||||
def merge_ranges[_T](
|
||||
a: tuple[tuple[int, int], _T], b: tuple[tuple[int, int], _T], priority_map: dict[tuple[int, int], int]
|
||||
) -> Generator[tuple[tuple[int, int], _T], None, None]:
|
||||
a_start, a_end = a[0]
|
||||
b_start, b_end = b[0]
|
||||
a_val, b_val = a[1], b[1]
|
||||
a_prio, b_prio = priority_map[a[0]], priority_map[b[0]]
|
||||
if b_start > a_end:
|
||||
if b_start == a_end + 1 and a_val == b_val:
|
||||
# ranges can be coalesced
|
||||
r = ((a_start, b_end), a_val)
|
||||
priority_map[r[0]] = max(a_prio, b_prio)
|
||||
yield r
|
||||
return
|
||||
# disjoint ranges
|
||||
yield a
|
||||
yield b
|
||||
return
|
||||
if a_val == b_val:
|
||||
# mergeable ranges
|
||||
r = ((a_start, max(a_end, b_end)), a_val)
|
||||
priority_map[r[0]] = max(a_prio, b_prio)
|
||||
yield r
|
||||
return
|
||||
before_range = mid_range = after_range = None
|
||||
before_range_prio = mid_range_prio = after_range_prio = 0
|
||||
if b_start > a_start:
|
||||
before_range = ((a_start, b_start - 1), a_val)
|
||||
before_range_prio = a_prio
|
||||
mid_end = min(a_end, b_end)
|
||||
if mid_end >= b_start:
|
||||
# overlap range
|
||||
mid_range = ((b_start, mid_end), a_val if priority_map[a[0]] >= priority_map[b[0]] else b_val)
|
||||
mid_range_prio = max(a_prio, b_prio)
|
||||
# after range
|
||||
if mid_end is a_end:
|
||||
if b_end > a_end:
|
||||
after_range = ((a_end + 1, b_end), b_val)
|
||||
after_range_prio = b_prio
|
||||
else:
|
||||
if a_end > b_end:
|
||||
after_range = ((b_end + 1, a_end), a_val)
|
||||
after_range_prio = a_prio
|
||||
# check if the before, mid and after ranges can be coalesced
|
||||
ranges: list[tuple[tuple[int, int], _T]] = []
|
||||
priorities: list[int] = []
|
||||
for rq, prio in ((before_range, before_range_prio), (mid_range, mid_range_prio), (after_range, after_range_prio)):
|
||||
if rq is None:
|
||||
continue
|
||||
r = rq
|
||||
if ranges:
|
||||
x = ranges[-1]
|
||||
if x[0][1] + 1 == r[0][0] and x[1] == r[1]:
|
||||
ranges[-1] = ((x[0][0], r[0][1]), x[1])
|
||||
priorities[-1] = max(priorities[-1], prio)
|
||||
else:
|
||||
ranges.append(r)
|
||||
priorities.append(prio)
|
||||
else:
|
||||
ranges.append(r)
|
||||
priorities.append(prio)
|
||||
for r, p in zip(ranges, priorities):
|
||||
priority_map[r[0]] = p
|
||||
yield from ranges
|
||||
|
||||
|
||||
def coalesce_symbol_maps[_T](maps: dict[tuple[int, int], _T]) -> dict[tuple[int, int], _T]:
|
||||
if not maps:
|
||||
return maps
|
||||
priority_map = {r: i for i, r in enumerate(maps.keys())}
|
||||
ranges = tuple((r, maps[r]) for r in sorted(maps))
|
||||
ans = [ranges[0]]
|
||||
|
||||
for i in range(1, len(ranges)):
|
||||
r = ranges[i]
|
||||
new_ranges = merge_ranges(ans[-1], r, priority_map)
|
||||
if ans:
|
||||
del ans[-1]
|
||||
if not ans:
|
||||
ans = list(new_ranges)
|
||||
else:
|
||||
for r in new_ranges:
|
||||
prev = ans[-1]
|
||||
if prev[0][1] + 1 == r[0][0] and prev[1] == r[1]:
|
||||
ans[-1] = (prev[0][0], r[0][1]), prev[1]
|
||||
else:
|
||||
ans.append(r)
|
||||
return dict(ans)
|
||||
|
||||
|
||||
def create_symbol_map(opts: Options) -> tuple[tuple[int, int, int], ...]:
|
||||
val = coalesce_symbol_maps(opts.symbol_map)
|
||||
family_map: dict[str, int] = {}
|
||||
count = 0
|
||||
for family in val.values():
|
||||
if family not in family_map:
|
||||
font, bold, italic = font_for_family(family)
|
||||
fkey = family_name_to_key(family)
|
||||
if fkey in ('symbolsnfm', 'symbols nerd font mono') and font['postscript_name'] != 'SymbolsNFM' and builtin_nerd_font_descriptor:
|
||||
font = builtin_nerd_font_descriptor
|
||||
bold = italic = False
|
||||
family_map[family] = count
|
||||
count += 1
|
||||
current_faces.append((font, bold, italic))
|
||||
sm = tuple((a, b, family_map[f]) for (a, b), f in val.items())
|
||||
return sm
|
||||
|
||||
|
||||
def create_narrow_symbols(opts: Options) -> tuple[tuple[int, int, int], ...]:
|
||||
return tuple((a, b, v) for (a, b), v in coalesce_symbol_maps(opts.narrow_symbols).items())
|
||||
|
||||
|
||||
descriptor_overrides: dict[int, tuple[str, bool, bool]] = {}
|
||||
|
||||
|
||||
def descriptor_for_idx(idx: int) -> tuple[FontObject | str, bool, bool]:
|
||||
ans = descriptor_overrides.get(idx)
|
||||
if ans is None:
|
||||
return current_faces[idx]
|
||||
return ans
|
||||
|
||||
|
||||
def dump_font_debug() -> None:
|
||||
cf = current_fonts()
|
||||
log_error('Text fonts:')
|
||||
for key, text in {'medium': 'Normal', 'bold': 'Bold', 'italic': 'Italic', 'bi': 'Bold-Italic'}.items():
|
||||
log_error(f' {text}:', cf[key].identify_for_debug())
|
||||
ss = cf['symbol']
|
||||
if ss:
|
||||
log_error('Symbol map fonts:')
|
||||
for s in ss:
|
||||
log_error(' ' + s.identify_for_debug())
|
||||
|
||||
|
||||
def clear_font_caches() -> None:
|
||||
from .common import clear_caches as clear_common_caches
|
||||
|
||||
clear_common_caches()
|
||||
if is_macos:
|
||||
from .core_text import clear_caches as clear_platform_caches
|
||||
else:
|
||||
from .fontconfig import clear_caches as clear_platform_caches
|
||||
clear_platform_caches()
|
||||
|
||||
|
||||
def set_font_family(opts: Options | None = None, override_font_size: float | None = None, add_builtin_nerd_font: bool = False) -> None:
|
||||
global current_faces, builtin_nerd_font_descriptor
|
||||
opts = opts or defaults
|
||||
sz = override_font_size or opts.font_size
|
||||
font_map = get_font_files(opts)
|
||||
current_faces = [(font_map['medium'], False, False)]
|
||||
ftypes: list[Literal['bold', 'italic', 'bi']] = ['bold', 'italic', 'bi']
|
||||
indices = {k: 0 for k in ftypes}
|
||||
for k in ftypes:
|
||||
if k in font_map:
|
||||
indices[k] = len(current_faces)
|
||||
current_faces.append((font_map[k], 'b' in k, 'i' in k))
|
||||
before = len(current_faces)
|
||||
if add_builtin_nerd_font:
|
||||
builtin_nerd_font_path = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf')
|
||||
if os.path.exists(builtin_nerd_font_path):
|
||||
builtin_nerd_font_descriptor = set_builtin_nerd_font(builtin_nerd_font_path)
|
||||
else:
|
||||
log_error(f'No builtin NERD font found in {fonts_dir}')
|
||||
sm = create_symbol_map(opts)
|
||||
ns = create_narrow_symbols(opts)
|
||||
num_symbol_fonts = len(current_faces) - before
|
||||
set_font_data(descriptor_for_idx, indices['bold'], indices['italic'], indices['bi'], num_symbol_fonts, sm, sz, ns)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import ctypes
|
||||
|
||||
CBufType = ctypes.Array[ctypes.c_ubyte]
|
||||
else:
|
||||
CBufType = None
|
||||
UnderlineCallback = Callable[[CBufType, int, int, int, int], None]
|
||||
|
||||
|
||||
class setup_for_testing:
|
||||
xnum = 100000
|
||||
ynum = 100
|
||||
baseline = 0
|
||||
|
||||
def __init__(self, family: str = 'monospace', size: float = 11.0, dpi: float = 96.0, main_face_path: str = ''):
|
||||
self.family, self.size, self.dpi = family, size, dpi
|
||||
self.main_face_path = main_face_path
|
||||
|
||||
def __enter__(self) -> tuple[dict[tuple[int, int, int], bytes], int, int]:
|
||||
global descriptor_overrides
|
||||
opts = defaults._replace(font_family=parse_font_spec(self.family), font_size=self.size)
|
||||
set_options(opts)
|
||||
sprites = {}
|
||||
|
||||
def send_to_gpu(x: int, y: int, z: int, data: bytes) -> None:
|
||||
sprites[(x, y, z)] = data
|
||||
|
||||
sprite_map_set_limits(self.xnum, self.ynum)
|
||||
set_send_sprite_to_gpu(send_to_gpu)
|
||||
self.orig_desc_overrides = descriptor_overrides
|
||||
descriptor_overrides = {}
|
||||
if self.main_face_path:
|
||||
descriptor_overrides[0] = self.main_face_path, False, False
|
||||
try:
|
||||
set_font_family(opts)
|
||||
cell_width, cell_height, self.baseline = create_test_font_group(self.size, self.dpi, self.dpi)
|
||||
return sprites, cell_width, cell_height
|
||||
except Exception:
|
||||
set_send_sprite_to_gpu(None)
|
||||
raise
|
||||
|
||||
def __exit__(self, *args: Any) -> None:
|
||||
global descriptor_overrides
|
||||
descriptor_overrides = self.orig_desc_overrides
|
||||
set_send_sprite_to_gpu(None)
|
||||
|
||||
|
||||
def render_string(text: str, family: str = 'monospace', size: float = 11.0, dpi: float = 96.0) -> tuple[int, int, list[bytes]]:
|
||||
with setup_for_testing(family, size, dpi) as (sprites, cell_width, cell_height):
|
||||
s = Screen(None, 1, len(text) * 2)
|
||||
line = s.line(0)
|
||||
s.draw(text)
|
||||
test_render_line(line)
|
||||
cells = []
|
||||
found_content = False
|
||||
for i in reversed(range(s.columns)):
|
||||
sp = line.sprite_at(i)
|
||||
sp &= 0x7FFFFFFF
|
||||
if not sp and not found_content:
|
||||
continue
|
||||
found_content = True
|
||||
cells.append(sprites[sprite_idx_to_pos(sp, setup_for_testing.xnum, setup_for_testing.ynum)])
|
||||
return cell_width, cell_height, list(reversed(cells))
|
||||
|
||||
|
||||
def shape_string(
|
||||
text: str = 'abcd', family: str = 'monospace', size: float = 11.0, dpi: float = 96.0, path: str | None = None
|
||||
) -> list[tuple[int, int, int, tuple[int, ...]]]:
|
||||
with setup_for_testing(family, size, dpi) as (sprites, cell_width, cell_height):
|
||||
s = Screen(None, 1, len(text) * 2)
|
||||
line = s.line(0)
|
||||
s.draw(text)
|
||||
return test_shape(line, path)
|
||||
|
||||
|
||||
def show(rgba_data: bytes | memoryview, width: int, height: int, fmt: int = 32) -> None:
|
||||
from base64 import standard_b64encode
|
||||
|
||||
from kittens.tui.images import GraphicsCommand
|
||||
|
||||
data = memoryview(standard_b64encode(rgba_data))
|
||||
cmd = GraphicsCommand()
|
||||
cmd.a = 'T'
|
||||
cmd.f = fmt
|
||||
cmd.s = width
|
||||
cmd.v = height
|
||||
|
||||
sys.stdout.flush()
|
||||
while data:
|
||||
chunk, data = data[:4096], data[4096:]
|
||||
cmd.m = 1 if data else 0
|
||||
sys.stdout.buffer.write(cmd.serialize(chunk))
|
||||
cmd.clear()
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
|
||||
def display_bitmap(rgb_data: bytes, width: int, height: int) -> None:
|
||||
assert len(rgb_data) == 4 * width * height
|
||||
show(rgb_data, width, height)
|
||||
|
||||
|
||||
def test_render_string(text: str = 'Hello, world!', family: str = 'monospace', size: float = 64.0, dpi: float = 96.0) -> None:
|
||||
|
||||
cell_width, cell_height, cells = render_string(text, family, size, dpi)
|
||||
rgb_data = concat_cells(cell_width, cell_height, True, tuple(cells))
|
||||
cf = current_fonts()
|
||||
fonts = [cf['medium'].postscript_name()]
|
||||
fonts.extend(f.postscript_name() for f in cf['fallback'])
|
||||
msg = 'Rendered string {} below, with fonts: {}\n'.format(text, ', '.join(fonts))
|
||||
try:
|
||||
print(msg)
|
||||
except UnicodeEncodeError:
|
||||
sys.stdout.buffer.write(msg.encode('utf-8') + b'\n')
|
||||
display_bitmap(rgb_data, cell_width * len(cells), cell_height)
|
||||
print('\n')
|
||||
|
||||
|
||||
def test_fallback_font(qtext: str | None = None, bold: bool = False, italic: bool = False) -> None:
|
||||
with setup_for_testing():
|
||||
if qtext:
|
||||
trials = [qtext]
|
||||
else:
|
||||
trials = ['你', 'He\u0347\u0305', '\U0001f929']
|
||||
for text in trials:
|
||||
f = get_fallback_font(text, bold, italic)
|
||||
try:
|
||||
print(text, f)
|
||||
except UnicodeEncodeError:
|
||||
sys.stdout.buffer.write(f'{text} {f}\n'.encode())
|
||||
|
||||
|
||||
def showcase() -> None:
|
||||
f = 'monospace' if is_macos else 'Liberation Mono'
|
||||
test_render_string('He\u0347\u0305llo\u0337, w\u0302or\u0306l\u0354d!', family=f)
|
||||
test_render_string('你好,世界', family=f)
|
||||
test_render_string('│😁│🙏│😺│', family=f)
|
||||
test_render_string('A=>>B!=C', family='Fira Code')
|
||||
|
||||
|
||||
def create_face(path: str) -> 'Union[CTFace, Face]':
|
||||
if is_macos:
|
||||
from kitty.fast_data_types import CTFace
|
||||
|
||||
return CTFace(path=path)
|
||||
from kitty.fast_data_types import Face
|
||||
|
||||
return Face(path=path)
|
||||
|
||||
|
||||
def test_render_codepoint(chars: str = '😺', path: str = '/t/Noto-COLRv1.ttf', font_size: float = 160.0) -> None:
|
||||
f = create_face(path=path)
|
||||
f.set_size(font_size, 96, 96)
|
||||
for char in chars:
|
||||
bitmap, w, h = f.render_codepoint(ord(char))
|
||||
print('Rendered:', char)
|
||||
display_bitmap(bitmap, w, h)
|
||||
print('\n')
|
||||
|
||||
|
||||
def test_render_decoration(which: DecorationTypes, cell_width: int, cell_height: int, underline_position: int, underline_thickness: int) -> None:
|
||||
buf = render_decoration(which, cell_width, cell_height, underline_position, underline_thickness)
|
||||
cells = buf, buf, buf, buf, buf
|
||||
rgb_data = concat_cells(cell_width, cell_height, False, cells)
|
||||
display_bitmap(rgb_data, cell_width * len(cells), cell_height)
|
||||
Reference in new issue
Block a user