boldgen 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- boldgen/__init__.py +27 -0
- boldgen/__main__.py +10 -0
- boldgen/alias.py +217 -0
- boldgen/builder.py +251 -0
- boldgen/cjk.py +64 -0
- boldgen/cli.py +802 -0
- boldgen/discover.py +398 -0
- boldgen/geometry.py +394 -0
- boldgen/glyf.py +411 -0
- boldgen/install.py +189 -0
- boldgen/mktest.py +146 -0
- boldgen/report.py +147 -0
- boldgen/sfnt.py +477 -0
- boldgen/ui.py +333 -0
- boldgen/verify.py +263 -0
- boldgen-0.1.0.dist-info/METADATA +281 -0
- boldgen-0.1.0.dist-info/RECORD +22 -0
- boldgen-0.1.0.dist-info/WHEEL +5 -0
- boldgen-0.1.0.dist-info/entry_points.txt +2 -0
- boldgen-0.1.0.dist-info/licenses/LICENSE +21 -0
- boldgen-0.1.0.dist-info/licenses/NOTICE +37 -0
- boldgen-0.1.0.dist-info/top_level.txt +1 -0
boldgen/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""boldgen —— 为缺少粗体的字体家族烘焙真正的 Bold face。
|
|
2
|
+
|
|
3
|
+
背景
|
|
4
|
+
----
|
|
5
|
+
很多中文字体(宋体、黑体、楷体、仿宋、方正系列、华文系列……)只提供
|
|
6
|
+
Regular 一个字重。当文档要求加粗时,应用必须自己做"合成粗体"
|
|
7
|
+
(synthetic bold)——即把字形轮廓向外扩张。
|
|
8
|
+
|
|
9
|
+
各家应用的合成粗体实现质量参差不齐。WPS Office for Linux 的 Writer
|
|
10
|
+
渲染器(``libkso.so``)自己实现了一套轮廓扩张,半径被放大了数倍,
|
|
11
|
+
中文加粗会渲染成一团涂抹状的黑块。
|
|
12
|
+
|
|
13
|
+
本工具的做法很直接:**离线把粗体烘焙进字体文件**。生成出来的 Bold face
|
|
14
|
+
是真正的字重 700 的字体,任何应用匹配到它都不会再走自己的假粗逻辑。
|
|
15
|
+
|
|
16
|
+
用法::
|
|
17
|
+
|
|
18
|
+
boldgen scan # 看看哪些中文字体家族缺粗体
|
|
19
|
+
boldgen interactive # 交互式勾选并生成
|
|
20
|
+
boldgen generate --family 宋体 --family 黑体
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
__all__ = ["__version__"]
|
boldgen/__main__.py
ADDED
boldgen/alias.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""fontconfig 别名模式。
|
|
2
|
+
|
|
3
|
+
**别名模式**与**生成器模式**是两种互补的思路:
|
|
4
|
+
|
|
5
|
+
* 生成器模式:离线烘焙出真正的 Bold 字体文件。字形不变,只是变粗。
|
|
6
|
+
效果最好,但每个家族都要多占一份磁盘(中文大字体动辄几十 MB)。
|
|
7
|
+
* 别名模式:写一条 fontconfig 规则,把"该家族 + 加粗"的请求重定向到
|
|
8
|
+
另一个**已经**有粗体的家族。零额外磁盘占用,但字形会变成目标字体的。
|
|
9
|
+
|
|
10
|
+
别名规则只影响**加粗请求**,常规字重完全不受影响::
|
|
11
|
+
|
|
12
|
+
<match target="pattern">
|
|
13
|
+
<test name="family" compare="eq"><string>SimSun</string></test>
|
|
14
|
+
<test name="weight" compare="more_eq"><const>bold</const></test>
|
|
15
|
+
<edit name="family" mode="assign"><string>Noto Serif CJK SC</string></edit>
|
|
16
|
+
</match>
|
|
17
|
+
|
|
18
|
+
注意 fontconfig 的 ``%{weight}`` 是**缩放刻度**(Regular=80、SemiBold=180、
|
|
19
|
+
Bold=200、ExtraBold=205、Black=210),``<const>bold</const>`` 会被解析成 200,
|
|
20
|
+
因此 ``more_eq`` 能正确命中"粗体及以上"。
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
29
|
+
|
|
30
|
+
from .discover import FamilyInfo
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"AliasRule",
|
|
34
|
+
"ALIAS_CONF_NAME",
|
|
35
|
+
"alias_conf_path",
|
|
36
|
+
"build_alias_xml",
|
|
37
|
+
"load_rules",
|
|
38
|
+
"save_rules",
|
|
39
|
+
"classify_family",
|
|
40
|
+
"recommend_target",
|
|
41
|
+
"CATEGORY_KEYWORDS",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
#: 生成的别名配置文件名(放在用户级 ``conf.d`` 里,编号 99 保证最后生效)。
|
|
45
|
+
ALIAS_CONF_NAME = "99-boldgen-aliases.conf"
|
|
46
|
+
|
|
47
|
+
#: 字体类别关键词 → 类别名。按顺序匹配,先匹配到的优先。
|
|
48
|
+
CATEGORY_KEYWORDS: Tuple[Tuple[str, Tuple[str, ...]], ...] = (
|
|
49
|
+
("kai", ("楷", "Kai", "楷体")),
|
|
50
|
+
("fangsong", ("仿宋", "FangSong", "Fang")),
|
|
51
|
+
("xiaobiaosong", ("小标宋", "XiaoBiaoSong")),
|
|
52
|
+
("lishu", ("隶书", "LiSu", "Lishu")),
|
|
53
|
+
("xingshu", ("行楷", "行书", "Xingkai", "XingKai")),
|
|
54
|
+
("weibei", ("魏碑", "XinWei")),
|
|
55
|
+
("hupo", ("琥珀", "Hupo")),
|
|
56
|
+
("caiyun", ("彩云", "Caiyun", "CaiYun")),
|
|
57
|
+
("yuan", ("圆", "Yuan")),
|
|
58
|
+
("hei", ("黑体", "Hei", "Sans", "Gothic", "雅黑", "YaHei", "Sans CJK", "HeiTi")),
|
|
59
|
+
("song", ("宋", "Song", "Ming", "明朝", "Sun", "Sung", "MingLiU", "Serif")),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
#: 各类别对应的推荐目标(家族名关键字)。第一个能被匹配上的就用。
|
|
63
|
+
_CATEGORY_TARGETS: Dict[str, Tuple[str, ...]] = {
|
|
64
|
+
"song": ("Noto Serif CJK SC", "AR PL UMing CN", "Source Han Serif"),
|
|
65
|
+
"hei": ("Noto Sans CJK SC", "WenQuanYi Zen Hei", "Source Han Sans"),
|
|
66
|
+
"kai": ("Noto Serif CJK SC", "AR PL UKai CN"),
|
|
67
|
+
"fangsong": ("Noto Serif CJK SC",),
|
|
68
|
+
"xiaobiaosong": ("Noto Serif CJK SC",),
|
|
69
|
+
"lishu": ("Noto Serif CJK SC",),
|
|
70
|
+
"xingshu": ("Noto Serif CJK SC",),
|
|
71
|
+
"weibei": ("Noto Serif CJK SC",),
|
|
72
|
+
"hupo": ("Noto Serif CJK SC",),
|
|
73
|
+
"caiyun": ("Noto Serif CJK SC",),
|
|
74
|
+
"yuan": ("Noto Sans CJK SC",),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
#: 兜底目标。
|
|
78
|
+
_FALLBACK_TARGETS = ("Noto Serif CJK SC", "Noto Sans CJK SC")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class AliasRule:
|
|
83
|
+
"""一条别名规则。"""
|
|
84
|
+
|
|
85
|
+
source_family: str
|
|
86
|
+
target_family: str
|
|
87
|
+
comment: str = ""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def alias_conf_path() -> str:
|
|
91
|
+
"""用户级 fontconfig 别名配置文件的路径。"""
|
|
92
|
+
return os.path.join(
|
|
93
|
+
os.path.expanduser("~"), ".config", "fontconfig", "conf.d", ALIAS_CONF_NAME
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def build_alias_xml(rules: Sequence[AliasRule]) -> str:
|
|
98
|
+
"""把规则渲染成 fontconfig 配置。"""
|
|
99
|
+
lines = [
|
|
100
|
+
'<?xml version="1.0"?>',
|
|
101
|
+
'<!DOCTYPE fontconfig SYSTEM "fonts.dtd">',
|
|
102
|
+
"<!-- 由 boldgen 生成;删除本文件即可全部撤销。 -->",
|
|
103
|
+
"<fontconfig>",
|
|
104
|
+
]
|
|
105
|
+
for rule in rules:
|
|
106
|
+
if rule.comment:
|
|
107
|
+
lines.append(f" <!-- {rule.comment} -->")
|
|
108
|
+
lines.append(' <match target="pattern">')
|
|
109
|
+
lines.append(' <test name="family" compare="eq">')
|
|
110
|
+
lines.append(f" <string>{_xml_escape(rule.source_family)}</string>")
|
|
111
|
+
lines.append(" </test>")
|
|
112
|
+
lines.append(' <test name="weight" compare="more_eq">')
|
|
113
|
+
lines.append(" <const>bold</const>")
|
|
114
|
+
lines.append(" </test>")
|
|
115
|
+
lines.append(' <edit name="family" mode="assign">')
|
|
116
|
+
lines.append(f" <string>{_xml_escape(rule.target_family)}</string>")
|
|
117
|
+
lines.append(" </edit>")
|
|
118
|
+
lines.append(" </match>")
|
|
119
|
+
lines.append("</fontconfig>")
|
|
120
|
+
return "\n".join(lines) + "\n"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _xml_escape(text: str) -> str:
|
|
124
|
+
return (
|
|
125
|
+
text.replace("&", "&")
|
|
126
|
+
.replace("<", "<")
|
|
127
|
+
.replace(">", ">")
|
|
128
|
+
.replace('"', """)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
_RULE_RE = re.compile(
|
|
133
|
+
r'<test name="family" compare="eq">\s*<string>([^<]*)</string>\s*</test>.*?'
|
|
134
|
+
r'<edit name="family" mode="assign">\s*<string>([^<]*)</string>\s*</edit>',
|
|
135
|
+
re.DOTALL,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def load_rules(path: Optional[str] = None) -> List[AliasRule]:
|
|
140
|
+
"""读回已生成的别名规则。"""
|
|
141
|
+
target = path or alias_conf_path()
|
|
142
|
+
try:
|
|
143
|
+
with open(target, "r", encoding="utf-8") as handle:
|
|
144
|
+
content = handle.read()
|
|
145
|
+
except OSError:
|
|
146
|
+
return []
|
|
147
|
+
rules: List[AliasRule] = []
|
|
148
|
+
for match in _RULE_RE.finditer(content):
|
|
149
|
+
rules.append(AliasRule(source_family=match.group(1), target_family=match.group(2)))
|
|
150
|
+
return rules
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def save_rules(rules: Sequence[AliasRule], path: Optional[str] = None) -> str:
|
|
154
|
+
"""写入别名规则。"""
|
|
155
|
+
target = path or alias_conf_path()
|
|
156
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
157
|
+
with open(target, "w", encoding="utf-8") as handle:
|
|
158
|
+
handle.write(build_alias_xml(rules))
|
|
159
|
+
return target
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def classify_family(name: str) -> str:
|
|
163
|
+
"""判断字体类别(song/hei/kai/fangsong/…)。"""
|
|
164
|
+
for category, keywords in CATEGORY_KEYWORDS:
|
|
165
|
+
for keyword in keywords:
|
|
166
|
+
if keyword in name:
|
|
167
|
+
return category
|
|
168
|
+
return "other"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def recommend_target(
|
|
172
|
+
source: FamilyInfo,
|
|
173
|
+
families: Sequence[FamilyInfo],
|
|
174
|
+
) -> Optional[FamilyInfo]:
|
|
175
|
+
"""给一个家族推荐目标粗体家族。
|
|
176
|
+
|
|
177
|
+
评分规则:
|
|
178
|
+
|
|
179
|
+
1. 目标必须有真粗体;
|
|
180
|
+
2. 类别相同优先(宋体 → 宋体类粗体,楷体 → 楷体类粗体);
|
|
181
|
+
3. 同类别没有合适的,退到该类别的默认目标(Noto Serif/Sans CJK SC);
|
|
182
|
+
4. 目标也必须是中文字体。
|
|
183
|
+
"""
|
|
184
|
+
category = classify_family(source.key)
|
|
185
|
+
for name in source.names:
|
|
186
|
+
other = classify_family(name)
|
|
187
|
+
if other != "other":
|
|
188
|
+
category = other
|
|
189
|
+
break
|
|
190
|
+
|
|
191
|
+
candidates = [
|
|
192
|
+
info
|
|
193
|
+
for info in families
|
|
194
|
+
if info.has_real_bold and info.is_cjk and info.key != source.key
|
|
195
|
+
]
|
|
196
|
+
if not candidates:
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
def score(info: FamilyInfo) -> tuple:
|
|
200
|
+
same_category = 0 if classify_family(info.key) == category else 1
|
|
201
|
+
preferred = _CATEGORY_TARGETS.get(category, ())
|
|
202
|
+
preferred_rank = len(preferred)
|
|
203
|
+
for index, name in enumerate(preferred):
|
|
204
|
+
if name.lower() in info.key.lower() or info.key.lower() in name.lower():
|
|
205
|
+
preferred_rank = index
|
|
206
|
+
break
|
|
207
|
+
return (same_category, preferred_rank, info.key.lower())
|
|
208
|
+
|
|
209
|
+
candidates.sort(key=score)
|
|
210
|
+
best = candidates[0]
|
|
211
|
+
# 同类别完全没有候选时,退到类别默认目标
|
|
212
|
+
if classify_family(best.key) != category:
|
|
213
|
+
for name in _CATEGORY_TARGETS.get(category, ()) + _FALLBACK_TARGETS:
|
|
214
|
+
for info in candidates:
|
|
215
|
+
if info.key.lower() == name.lower():
|
|
216
|
+
return info
|
|
217
|
+
return best
|
boldgen/builder.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""构建合成粗体 face。
|
|
2
|
+
|
|
3
|
+
流程:
|
|
4
|
+
|
|
5
|
+
1. 读取源字体(支持 TTC 的指定 face);
|
|
6
|
+
2. 把每个**简单字形**的轮廓向外偏移 ``r = round(upem * strength)``;
|
|
7
|
+
3. 复合字形原样保留(其分量字形各自加粗后自动继承效果);
|
|
8
|
+
4. 更新 ``head`` / ``OS/2`` / ``name`` 表,剥掉不再适用的表;
|
|
9
|
+
5. 重新打包并计算校验和。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import struct
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Dict, List, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
from . import __version__, glyf as glyf_mod
|
|
20
|
+
from .geometry import Glyph, embolden
|
|
21
|
+
from .sfnt import (
|
|
22
|
+
NAME_FAMILY,
|
|
23
|
+
NAME_POSTSCRIPT,
|
|
24
|
+
Font,
|
|
25
|
+
ascii_fold,
|
|
26
|
+
build_name_table,
|
|
27
|
+
read_name_table,
|
|
28
|
+
write_sfnt,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"BuildOptions",
|
|
33
|
+
"BuildResult",
|
|
34
|
+
"UnsupportedFontError",
|
|
35
|
+
"build_bold",
|
|
36
|
+
"STRIPPED_TABLES",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
#: 会被剥掉的表:旧 hinting(会把加粗后的笔画又削细)、内嵌位图(未加粗的位图)、
|
|
40
|
+
#: 数字签名(改过字体后签名即失效)。
|
|
41
|
+
STRIPPED_TABLES = ("fpgm", "prep", "cvt ", "EBDT", "EBLC", "DSIG")
|
|
42
|
+
|
|
43
|
+
#: OS/2 fsSelection 位。
|
|
44
|
+
_FS_BOLD = 0x0020
|
|
45
|
+
_FS_REGULAR = 0x0040
|
|
46
|
+
|
|
47
|
+
#: head.macStyle 位。
|
|
48
|
+
_MACSTYLE_BOLD = 0x0001
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UnsupportedFontError(Exception):
|
|
52
|
+
"""字体格式不受支持(例如 CFF/OTF 轮廓)。"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class BuildOptions:
|
|
57
|
+
"""构建参数。"""
|
|
58
|
+
|
|
59
|
+
#: 加粗系数:外扩半径 = ``round(unitsPerEm * strength)``。
|
|
60
|
+
strength: float = 0.015
|
|
61
|
+
#: 写入 OS/2 的字重值。
|
|
62
|
+
weight: int = 700
|
|
63
|
+
#: 样式名后缀(用于 PostScript 名)。
|
|
64
|
+
suffix: str = "Bold"
|
|
65
|
+
#: 是否把隐含 on-curve 中点物化为显式点(几何更准,文件略大)。
|
|
66
|
+
materialize: bool = True
|
|
67
|
+
#: 斜接长度上限倍数,超过则退化为斜切。
|
|
68
|
+
miter_limit: float = 4.0
|
|
69
|
+
#: 是否剥掉 hinting / 位图 / 签名表。
|
|
70
|
+
strip_hint: bool = True
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class BuildResult:
|
|
75
|
+
"""构建结果。"""
|
|
76
|
+
|
|
77
|
+
output: str
|
|
78
|
+
num_glyphs: int = 0
|
|
79
|
+
changed: int = 0
|
|
80
|
+
radius: int = 0
|
|
81
|
+
size: int = 0
|
|
82
|
+
family: str = ""
|
|
83
|
+
style: str = "Bold"
|
|
84
|
+
postscript_name: str = ""
|
|
85
|
+
source: str = ""
|
|
86
|
+
face_index: int = 0
|
|
87
|
+
warnings: List[str] = field(default_factory=list)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _family_of(font: Font) -> str:
|
|
91
|
+
for rec in font.names():
|
|
92
|
+
if rec.name_id == NAME_FAMILY and rec.text.strip():
|
|
93
|
+
return rec.text.strip()
|
|
94
|
+
return os.path.splitext(os.path.basename(font.data[:0] or ""))[0] or "Untitled"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _postscript_base(font: Font) -> str:
|
|
98
|
+
"""取源字体的 PostScript 名(没有就用 family 名)。"""
|
|
99
|
+
for rec in font.names():
|
|
100
|
+
if rec.name_id == NAME_POSTSCRIPT and rec.text.strip():
|
|
101
|
+
return rec.text.strip()
|
|
102
|
+
for rec in font.names():
|
|
103
|
+
if rec.name_id == NAME_FAMILY and rec.text.strip():
|
|
104
|
+
return rec.text.strip()
|
|
105
|
+
return "Untitled"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def build_bold(
|
|
109
|
+
src_path: str,
|
|
110
|
+
out_path: str,
|
|
111
|
+
face_index: int = 0,
|
|
112
|
+
options: Optional[BuildOptions] = None,
|
|
113
|
+
) -> BuildResult:
|
|
114
|
+
"""从 ``src_path`` 生成粗体 face,写入 ``out_path``。
|
|
115
|
+
|
|
116
|
+
Raises:
|
|
117
|
+
UnsupportedFontError: 源字体没有 ``glyf`` 表(CFF/OTF 等)。
|
|
118
|
+
ValueError: 字体结构异常。
|
|
119
|
+
"""
|
|
120
|
+
options = options or BuildOptions()
|
|
121
|
+
|
|
122
|
+
with open(src_path, "rb") as handle:
|
|
123
|
+
data = handle.read()
|
|
124
|
+
font = Font(data, face_index)
|
|
125
|
+
|
|
126
|
+
if not font.has_table("glyf"):
|
|
127
|
+
raise UnsupportedFontError(
|
|
128
|
+
f"{src_path} 没有 glyf 表(可能是 CFF/OTF 轮廓)。"
|
|
129
|
+
"本工具的内置引擎只处理 TrueType 轮廓;"
|
|
130
|
+
"CFF 支持正在开发中,欢迎贡献。"
|
|
131
|
+
)
|
|
132
|
+
if not font.has_table("head") or not font.has_table("maxp"):
|
|
133
|
+
raise ValueError(f"{src_path} 缺少 head/maxp 表,不是有效的 TrueType 字体")
|
|
134
|
+
|
|
135
|
+
head = font.table_bytes("head")
|
|
136
|
+
maxp = font.table_bytes("maxp")
|
|
137
|
+
units_per_em = struct.unpack_from(">H", head, 18)[0] or 1000
|
|
138
|
+
index_to_loc_format = struct.unpack_from(">h", head, 50)[0]
|
|
139
|
+
num_glyphs = struct.unpack_from(">H", maxp, 4)[0]
|
|
140
|
+
|
|
141
|
+
radius = max(1, int(round(units_per_em * options.strength)))
|
|
142
|
+
style = options.suffix
|
|
143
|
+
|
|
144
|
+
# --- glyf / loca ---
|
|
145
|
+
glyf_raw = font.table_bytes("glyf")
|
|
146
|
+
loca_offsets = glyf_mod.parse_loca(font.table_bytes("loca"), index_to_loc_format, num_glyphs)
|
|
147
|
+
|
|
148
|
+
new_glyphs: List[bytes] = []
|
|
149
|
+
changed = 0
|
|
150
|
+
for gid in range(num_glyphs):
|
|
151
|
+
start = loca_offsets[gid]
|
|
152
|
+
end = loca_offsets[gid + 1] if gid + 1 < len(loca_offsets) else len(glyf_raw)
|
|
153
|
+
length = max(0, end - start)
|
|
154
|
+
parsed = glyf_mod.parse_glyph(glyf_raw, start, length)
|
|
155
|
+
if parsed is None:
|
|
156
|
+
new_glyphs.append(b"")
|
|
157
|
+
continue
|
|
158
|
+
if parsed.is_composite or parsed.glyph is None:
|
|
159
|
+
# 复合字形原样保留
|
|
160
|
+
new_glyphs.append(parsed.raw)
|
|
161
|
+
continue
|
|
162
|
+
bolded = embolden(
|
|
163
|
+
parsed.glyph, radius, miter_limit=options.miter_limit,
|
|
164
|
+
materialize=options.materialize,
|
|
165
|
+
)
|
|
166
|
+
blob = glyf_mod.build_glyph(bolded)
|
|
167
|
+
if blob != parsed.raw:
|
|
168
|
+
changed += 1
|
|
169
|
+
new_glyphs.append(blob)
|
|
170
|
+
|
|
171
|
+
# 重建 glyf + loca(统一用 long 格式)
|
|
172
|
+
glyf_out = bytearray()
|
|
173
|
+
loca_out = bytearray()
|
|
174
|
+
for blob in new_glyphs:
|
|
175
|
+
loca_out += struct.pack(">I", len(glyf_out))
|
|
176
|
+
glyf_out += blob
|
|
177
|
+
pad = (-len(blob)) % 4
|
|
178
|
+
glyf_out += b"\x00" * pad
|
|
179
|
+
loca_out += struct.pack(">I", len(glyf_out))
|
|
180
|
+
|
|
181
|
+
# --- head ---
|
|
182
|
+
head_out = bytearray(head)
|
|
183
|
+
struct.pack_into(">h", head_out, 50, 1) # indexToLocFormat = long
|
|
184
|
+
mac_style = struct.unpack_from(">H", head_out, 44)[0]
|
|
185
|
+
struct.pack_into(">H", head_out, 44, mac_style | _MACSTYLE_BOLD)
|
|
186
|
+
|
|
187
|
+
# --- OS/2 ---
|
|
188
|
+
os2_out = bytearray(font.table_bytes("OS/2"))
|
|
189
|
+
if len(os2_out) >= 64:
|
|
190
|
+
struct.pack_into(">H", os2_out, 4, options.weight)
|
|
191
|
+
# fsSelection 在 OS/2 v0 里同样位于偏移 62,不需要按版本区分
|
|
192
|
+
fs_selection = struct.unpack_from(">H", os2_out, 62)[0]
|
|
193
|
+
fs_selection = (fs_selection & ~_FS_REGULAR) | _FS_BOLD
|
|
194
|
+
struct.pack_into(">H", os2_out, 62, fs_selection)
|
|
195
|
+
# PANOSE[2] = Weight → Bold(8)
|
|
196
|
+
os2_out[34] = 8
|
|
197
|
+
|
|
198
|
+
# --- name ---
|
|
199
|
+
name_records = read_name_table(font.table_bytes("name"))
|
|
200
|
+
ps_base = ascii_fold(_postscript_base(font))
|
|
201
|
+
postscript_name = f"{ps_base}-{ascii_fold(style)}" if ps_base else ascii_fold(style)
|
|
202
|
+
# 某些字体的授权(例如 Arphic Public License)要求"在每个修改过的文件里
|
|
203
|
+
# 插入显著的修改声明"。TrueType 里唯一合适的落点是 nameID 5(版本字符串)。
|
|
204
|
+
modification_note = (
|
|
205
|
+
f"Modified by boldgen {__version__}: synthetic bold, "
|
|
206
|
+
f"glyph outlines dilated by {radius} font units "
|
|
207
|
+
f"(strength {options.strength}, unitsPerEm {units_per_em})"
|
|
208
|
+
)
|
|
209
|
+
name_out = build_name_table(
|
|
210
|
+
name_records,
|
|
211
|
+
style=style,
|
|
212
|
+
postscript_name=postscript_name,
|
|
213
|
+
modification_note=modification_note,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# --- 组装 ---
|
|
217
|
+
tables: Dict[str, bytes] = {}
|
|
218
|
+
for tag, blob in font.tables.items():
|
|
219
|
+
tables[tag] = font.table_bytes(tag)
|
|
220
|
+
tables["head"] = bytes(head_out)
|
|
221
|
+
tables["glyf"] = bytes(glyf_out)
|
|
222
|
+
tables["loca"] = bytes(loca_out)
|
|
223
|
+
tables["name"] = name_out
|
|
224
|
+
if len(os2_out) >= 64:
|
|
225
|
+
tables["OS/2"] = bytes(os2_out)
|
|
226
|
+
|
|
227
|
+
if options.strip_hint:
|
|
228
|
+
for tag in STRIPPED_TABLES:
|
|
229
|
+
tables.pop(tag, None)
|
|
230
|
+
|
|
231
|
+
# glyf/loca 变化后,其它表里的 checksum 会失效——write_sfnt 会统一重算。
|
|
232
|
+
out = write_sfnt(tables)
|
|
233
|
+
|
|
234
|
+
out_dir = os.path.dirname(os.path.abspath(out_path))
|
|
235
|
+
if out_dir:
|
|
236
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
237
|
+
with open(out_path, "wb") as handle:
|
|
238
|
+
handle.write(out)
|
|
239
|
+
|
|
240
|
+
return BuildResult(
|
|
241
|
+
output=out_path,
|
|
242
|
+
num_glyphs=num_glyphs,
|
|
243
|
+
changed=changed,
|
|
244
|
+
radius=radius,
|
|
245
|
+
size=len(out),
|
|
246
|
+
family=_family_of(font),
|
|
247
|
+
style=style,
|
|
248
|
+
postscript_name=postscript_name,
|
|
249
|
+
source=src_path,
|
|
250
|
+
face_index=face_index,
|
|
251
|
+
)
|
boldgen/cjk.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""中文字体的识别。
|
|
2
|
+
|
|
3
|
+
两条判据(任一命中即视为"中文字体"):
|
|
4
|
+
|
|
5
|
+
1. 字体覆盖了 CJK 统一表意文字区(U+4E00–U+9FA5 起的常用汉字);
|
|
6
|
+
2. 家族名里含有中日韩文字。
|
|
7
|
+
|
|
8
|
+
第 1 条由 fontconfig 的 ``:charset=`` 查询直接给出,第 2 条由本模块判断。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"CJK_NAME_RANGES",
|
|
17
|
+
"CJK_SAMPLE_CODEPOINTS",
|
|
18
|
+
"has_cjk_char",
|
|
19
|
+
"is_cjk_name",
|
|
20
|
+
"is_cjk_face",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
#: 判定"名字里有中日韩文字"的字符区间。
|
|
24
|
+
CJK_NAME_RANGES = (
|
|
25
|
+
(0x2E80, 0x2EFF), # CJK 部首补充
|
|
26
|
+
(0x3000, 0x303F), # CJK 标点
|
|
27
|
+
(0x3040, 0x30FF), # 假名
|
|
28
|
+
(0x3100, 0x312F), # 注音
|
|
29
|
+
(0x3130, 0x318F), # 谚文兼容字母
|
|
30
|
+
(0x3400, 0x4DBF), # CJK 扩展 A
|
|
31
|
+
(0x4E00, 0x9FFF), # CJK 统一表意文字
|
|
32
|
+
(0xA960, 0xA97F), # 谚文扩展 A
|
|
33
|
+
(0xAC00, 0xD7AF), # 谚文音节
|
|
34
|
+
(0xF900, 0xFAFF), # CJK 兼容表意文字
|
|
35
|
+
(0xFF00, 0xFFEF), # 全角字符
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
#: 用来查询 fontconfig charset 的样例码位。
|
|
39
|
+
CJK_SAMPLE_CODEPOINTS = (0x4E00, 0x9FA5)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def has_cjk_char(text: str) -> bool:
|
|
43
|
+
"""文本里是否含有中日韩文字。"""
|
|
44
|
+
for ch in text:
|
|
45
|
+
code = ord(ch)
|
|
46
|
+
for low, high in CJK_NAME_RANGES:
|
|
47
|
+
if low <= code <= high:
|
|
48
|
+
return True
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_cjk_name(*names: str) -> bool:
|
|
53
|
+
"""任一名字里有中日韩文字即返回 True。"""
|
|
54
|
+
return any(has_cjk_char(name) for name in names if name)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_cjk_face(covers_han: bool, *names: str) -> bool:
|
|
58
|
+
"""综合判断一个 face 是否算"中文字体"。"""
|
|
59
|
+
return bool(covers_han) or is_cjk_name(*names)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def cjk_family_names(names: Iterable[str]) -> list:
|
|
63
|
+
"""挑出名字里含中日韩文字的那几个。"""
|
|
64
|
+
return [name for name in names if has_cjk_char(name)]
|