font: generate glyph constraints based on nerd font patcher

This commit is contained in:
Qwerasd
2025-07-03 16:03:42 -06:00
parent e441094af0
commit 1775b75f2c
5 changed files with 3040 additions and 0 deletions

View File

@ -0,0 +1,349 @@
//! This is a generate file, produced by nerd_font_codegen.py
//! DO NOT EDIT BY HAND!
//!
//! This file provides info extracted from the nerd fonts patcher script,
//! specifying the scaling/positioning attributes of various glyphs.
const Constraint = @import("face.zig").RenderOptions.Constraint;
/// Get the a constraints for the provided codepoint.
pub fn getConstraint(cp: u21) Constraint {
return switch (cp) {
0x2500...0x259f,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .center,
.align_vertical = .center,
.pad_left = -0.02,
.pad_right = -0.02,
.pad_top = -0.01,
.pad_bottom = -0.01,
},
0x2630,
=> .{
.size_horizontal = .cover,
.size_vertical = .fit,
.align_horizontal = .center,
.align_vertical = .center,
.pad_left = 0.1,
.pad_right = 0.1,
.pad_top = 0.01,
.pad_bottom = 0.01,
},
0x276c...0x2771,
=> .{
.size_horizontal = .cover,
.size_vertical = .fit,
.align_horizontal = .center,
.align_vertical = .center,
},
0xe0b0,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.06,
.pad_right = -0.06,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0xe0b1,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.max_xy_ratio = 0.7,
},
0xe0b2,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.06,
.pad_right = -0.06,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0xe0b3,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.max_xy_ratio = 0.7,
},
0xe0b4,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.06,
.pad_right = -0.06,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.59,
},
0xe0b5,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.max_xy_ratio = 0.5,
},
0xe0b6,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.06,
.pad_right = -0.06,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.59,
},
0xe0b7,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.max_xy_ratio = 0.5,
},
0xe0b8,
0xe0bc,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
},
0xe0b9,
0xe0bd,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
},
0xe0ba,
0xe0be,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
},
0xe0bb,
0xe0bf,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
},
0xe0c0,
0xe0c8,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
},
0xe0c1,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
},
0xe0c2,
0xe0ca,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
},
0xe0c3,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
},
0xe0c4,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = 0.03,
.pad_right = 0.03,
.pad_top = 0.01,
.pad_bottom = 0.01,
.max_xy_ratio = 0.86,
},
0xe0c5,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = 0.03,
.pad_right = 0.03,
.pad_top = 0.01,
.pad_bottom = 0.01,
.max_xy_ratio = 0.86,
},
0xe0c6,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = 0.03,
.pad_right = 0.03,
.pad_top = 0.01,
.pad_bottom = 0.01,
.max_xy_ratio = 0.78,
},
0xe0c7,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = 0.03,
.pad_right = 0.03,
.pad_top = 0.01,
.pad_bottom = 0.01,
.max_xy_ratio = 0.78,
},
0xe0cc,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.02,
.pad_right = -0.02,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.85,
},
0xe0cd,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.max_xy_ratio = 0.865,
},
0xe0ce,
0xe0d0...0xe0d1,
=> .{
.size_horizontal = .cover,
.size_vertical = .cover,
.align_horizontal = .start,
.align_vertical = .center,
},
0xe0cf,
0xe0d3,
0xe0d5,
=> .{
.size_horizontal = .cover,
.size_vertical = .cover,
.align_horizontal = .center,
.align_vertical = .center,
},
0xe0d2,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.02,
.pad_right = -0.02,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0xe0d4,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.02,
.pad_right = -0.02,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0xe0d6,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .start,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0xe0d7,
=> .{
.size_horizontal = .stretch,
.size_vertical = .stretch,
.align_horizontal = .end,
.align_vertical = .center,
.pad_left = -0.05,
.pad_right = -0.05,
.pad_top = -0.01,
.pad_bottom = -0.01,
.max_xy_ratio = 0.7,
},
0x23fb...0x23fe,
0x2665,
0x26a1,
0x2b58,
0xe000...0xe0a9,
0xe4fa...0xe7ef,
0xea60...0xec1e,
0xed00...0xf847,
0xf0001...0xf1af0,
=> .{
.size_horizontal = .fit,
.size_vertical = .fit,
.align_horizontal = .center,
.align_vertical = .center,
},
else => .none,
};
}

View File

@ -0,0 +1,259 @@
"""
This file is mostly vibe coded because I don't like Python. It extracts the
patch sets from the nerd fonts font patcher file in order to extract scaling
rules and attributes for different codepoint ranges which it then codegens
in to a Zig file with a function that switches over codepoints and returns
the attributes and scaling rules.
This does include an `eval` call! This is spooky, but we trust
the nerd fonts code to be safe and not malicious or anything.
"""
import ast
import math
from pathlib import Path
from collections import defaultdict
class PatchSetExtractor(ast.NodeVisitor):
def __init__(self):
self.symbol_table = {}
self.patch_set_values = []
def visit_ClassDef(self, node):
if node.name == "font_patcher":
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name == "setup_patch_set":
self.visit_setup_patch_set(item)
def visit_setup_patch_set(self, node):
# First pass: gather variable assignments
for stmt in node.body:
if isinstance(stmt, ast.Assign):
# Store simple variable assignments in the symbol table
if len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name):
var_name = stmt.targets[0].id
self.symbol_table[var_name] = stmt.value
# Second pass: process self.patch_set
for stmt in node.body:
if isinstance(stmt, ast.Assign):
for target in stmt.targets:
if isinstance(target, ast.Attribute) and target.attr == "patch_set":
if isinstance(stmt.value, ast.List):
for elt in stmt.value.elts:
if isinstance(elt, ast.Dict):
self.process_patch_entry(elt)
def resolve_symbol(self, node):
"""Resolve named variables to their actual values from the symbol table."""
if isinstance(node, ast.Name) and node.id in self.symbol_table:
return self.safe_literal_eval(self.symbol_table[node.id])
return self.safe_literal_eval(node)
def safe_literal_eval(self, node):
"""Try to evaluate or stringify an AST node."""
try:
return ast.literal_eval(node)
except Exception:
# Spooky eval! But we trust nerd fonts to be safe...
if hasattr(ast, "unparse"):
return eval(
ast.unparse(node), {"box_keep": True}, {"self": SpoofSelf()}
)
else:
return f"<cannot eval: {type(node).__name__}>"
def process_patch_entry(self, dict_node):
entry = {}
for key_node, value_node in zip(dict_node.keys, dict_node.values):
if isinstance(key_node, ast.Constant) and key_node.value in (
"Enabled",
"Name",
"Filename",
"Exact",
):
continue
key = ast.literal_eval(key_node)
value = self.resolve_symbol(value_node)
entry[key] = value
self.patch_set_values.append(entry)
def extract_patch_set_values(source_code):
tree = ast.parse(source_code)
extractor = PatchSetExtractor()
extractor.visit(tree)
return extractor.patch_set_values
# We have to spoof `self` and `self.args` for the eval.
class SpoofArgs:
careful = True
class SpoofSelf:
args = SpoofArgs()
def parse_alignment(val):
return {
"l": ".start",
"r": ".end",
"c": ".center",
"": None,
}.get(val, ".none")
def get_param(d, key, default):
return float(d.get(key, default))
def attr_key(attr):
"""Convert attributes to a hashable key for grouping."""
stretch = attr.get("stretch", "")
return (
parse_alignment(attr.get("align", "")),
parse_alignment(attr.get("valign", "")),
stretch,
float(attr.get("params", {}).get("overlap", 0.0)),
float(attr.get("params", {}).get("xy-ratio", -1.0)),
float(attr.get("params", {}).get("ypadding", 0.0)),
)
def coalesce_codepoints_to_ranges(codepoints):
"""Convert a sorted list of integers to a list of single values and ranges."""
ranges = []
cp_iter = iter(sorted(codepoints))
try:
start = prev = next(cp_iter)
for cp in cp_iter:
if cp == prev + 1:
prev = cp
else:
ranges.append((start, prev))
start = prev = cp
ranges.append((start, prev))
except StopIteration:
pass
return ranges
def emit_zig_entry_multikey(codepoints, attr):
align = parse_alignment(attr.get("align", ""))
valign = parse_alignment(attr.get("valign", ""))
stretch = attr.get("stretch", "")
params = attr.get("params", {})
overlap = get_param(params, "overlap", 0.0)
xy_ratio = get_param(params, "xy-ratio", -1.0)
y_padding = get_param(params, "ypadding", 0.0)
ranges = coalesce_codepoints_to_ranges(codepoints)
keys = "\n".join(
f" 0x{start:x}...0x{end:x}," if start != end else f" 0x{start:x},"
for start, end in ranges
)
s = f"""{keys}
=> .{{\n"""
# These translations don't quite capture the way
# the actual patcher does scaling, but they're a
# good enough compromise.
if ("xy" in stretch):
s += " .size_horizontal = .stretch,\n"
s += " .size_vertical = .stretch,\n"
elif ("!" in stretch):
s += " .size_horizontal = .cover,\n"
s += " .size_vertical = .fit,\n"
elif ("^" in stretch):
s += " .size_horizontal = .cover,\n"
s += " .size_vertical = .cover,\n"
else:
s += " .size_horizontal = .fit,\n"
s += " .size_vertical = .fit,\n"
if (align is not None):
s += f" .align_horizontal = {align},\n"
if (valign is not None):
s += f" .align_vertical = {valign},\n"
if (overlap != 0.0):
pad = -overlap
s += f" .pad_left = {pad},\n"
s += f" .pad_right = {pad},\n"
v_pad = y_padding - math.copysign(min(0.01, abs(overlap)), overlap)
s += f" .pad_top = {v_pad},\n"
s += f" .pad_bottom = {v_pad},\n"
if (xy_ratio > 0):
s += f" .max_xy_ratio = {xy_ratio},\n"
s += " },"
return s
def generate_zig_switch_arms(patch_set):
entries = {}
for entry in patch_set:
attributes = entry["Attributes"]
for cp in range(entry["SymStart"], entry["SymEnd"] + 1):
entries[cp] = attributes["default"]
for k, v in attributes.items():
if isinstance(k, int):
entries[k] = v
del entries[0]
# Group codepoints by attribute key
grouped = defaultdict(list)
for cp, attr in entries.items():
grouped[attr_key(attr)].append(cp)
# Emit zig switch arms
result = []
for _, codepoints in sorted(grouped.items(), key=lambda x: x[1]):
# Use one of the attrs in the group to emit the value
attr = entries[codepoints[0]]
result.append(emit_zig_entry_multikey(codepoints, attr))
return "\n".join(result)
if __name__ == "__main__":
path = (
Path(__file__).resolve().parent
/ ".."
/ ".."
/ "vendor"
/ "nerd-fonts"
/ "font-patcher.py"
)
with open(path, "r", encoding="utf-8") as f:
source = f.read()
patch_set = extract_patch_set_values(source)
out_path = Path(__file__).resolve().parent / "nerd_font_attributes.zig"
with open(out_path, "w", encoding="utf-8") as f:
f.write("""//! This is a generate file, produced by nerd_font_codegen.py
//! DO NOT EDIT BY HAND!
//!
//! This file provides info extracted from the nerd fonts patcher script,
//! specifying the scaling/positioning attributes of various glyphs.
const Constraint = @import("face.zig").RenderOptions.Constraint;
/// Get the a constraints for the provided codepoint.
pub fn getConstraint(cp: u21) Constraint {
return switch (cp) {
""")
f.write(generate_zig_switch_arms(patch_set))
f.write("\n")
f.write(" else => .none,\n };\n}\n")

126
vendor/nerd-fonts/LICENSE vendored Normal file
View File

@ -0,0 +1,126 @@
# Nerd Fonts Licensing
There are various sources used under various licenses:
* Nerd Fonts source fonts, patched fonts, and folders with explict OFL SIL files are licensed under SIL OPEN FONT LICENSE Version 1.1 (see below).
* Nerd Fonts original source code files (such as `.sh`, `.py`, `font-patcher` and others) are licensed under the MIT License (MIT) (see below).
* Many other licenses are present in this project for even more detailed breakdown see: [License Audit](https://github.com/ryanoasis/nerd-fonts/blob/-/license-audit.md).
## Source files not in folders containing an explicit license are using the MIT License (MIT)
The MIT License (MIT)
Copyright (c) 2014 Ryan L McIntyre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Various Fonts, Patched Fonts, SVGs, Glyph Fonts, and any files in a folder with explicit SIL OFL 1.1 License
Copyright (c) 2014, Ryan L McIntyre (https://ryanlmcintyre.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

10
vendor/nerd-fonts/README.md vendored Normal file
View File

@ -0,0 +1,10 @@
We have a copy of the `font-patcher` file from `nerd-fonts` here, fetched from
https://github.com/ryanoasis/nerd-fonts/blob/master/font-patcher.
This is MIT licensed, see `LICENSE` in this directory.
We use parse a section of this file to codegen a lookup table of the nerd font
scaling rules. See `src/font/nerd_font_codegen.py` in the main Ghostty source
tree for more info.
Last fetched commit: ebc376cbd43f609d8084f47dd348646595ce066e

2296
vendor/nerd-fonts/font-patcher.py vendored Normal file

File diff suppressed because it is too large Load Diff