查看原始文件

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env bash

set -euo pipefail

usage() {
    cat <<'EOF'
用法:
  ./ttc2otf.sh
  ./ttc2otf.sh /path/to/PingFang.ttc
  ./ttc2otf.sh /path/to/PingFang.ttc /path/to/output

参数:
  第一个参数:可选,指定 PingFang.ttc 路径
  第二个参数:可选,指定输出目录,默认 ./PingFang-Split

示例:
  ./ttc2otf.sh
  ./ttc2otf.sh "/System/Library/Fonts/PingFang.ttc"
  ./ttc2otf.sh ./PingFang.ttc ./output
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
    usage
    exit 0
fi

INPUT="${1:-}"
OUTPUT="${2:-$PWD/PingFang-Split}"

# 自动查找 PingFang.ttc
if [[ -z "$INPUT" ]]; then
    echo "正在搜索 PingFang.ttc……"

    SEARCH_DIRS=(
        "/System/Library/Fonts"
        "/System/Library/AssetsV2"
        "/Library/Fonts"
        "$HOME/Library/Fonts"
    )

    FOUND=()

    for dir in "${SEARCH_DIRS[@]}"; do
        [[ -d "$dir" ]] || continue

        while IFS= read -r -d '' file; do
            FOUND+=("$file")
        done < <(
            find "$dir" \
                -type f \
                \( -iname 'PingFang.ttc' -o -iname '*PingFang*.ttc' \) \
                -print0 2>/dev/null
        )
    done

    if [[ ${#FOUND[@]} -eq 0 ]]; then
        echo "错误:没有找到 PingFang.ttc。" >&2
        echo "请先在“字体册”中下载或启用苹方,或者手动传入文件路径。" >&2
        exit 1
    fi

    if [[ ${#FOUND[@]} -eq 1 ]]; then
        INPUT="${FOUND[0]}"
    else
        echo
        echo "发现多个候选文件:"

        for i in "${!FOUND[@]}"; do
            printf '  [%d] %s\n' "$((i + 1))" "${FOUND[$i]}"
        done

        echo
        read -r -p "请选择文件编号 [1]: " choice
        choice="${choice:-1}"

        if ! [[ "$choice" =~ ^[0-9]+$ ]] ||
            ((choice < 1 || choice > ${#FOUND[@]})); then
            echo "错误:无效编号。" >&2
            exit 1
        fi

        INPUT="${FOUND[$((choice - 1))]}"
    fi
fi

if [[ ! -f "$INPUT" ]]; then
    echo "错误:文件不存在:$INPUT" >&2
    exit 1
fi

# 优先使用当前环境中的 Python 3
if ! command -v python3 >/dev/null 2>&1; then
    echo "错误:没有找到 python3。" >&2
    exit 1
fi

# 检查 FontTools
if ! python3 -c 'import fontTools' >/dev/null 2>&1; then
    echo "未安装 FontTools。"
    echo
    echo "可以执行以下任意一条命令安装:"
    echo "  python3 -m pip install --user fonttools"
    echo "  uv pip install fonttools"
    echo
    exit 1
fi

mkdir -p "$OUTPUT"

echo
echo "输入文件:$INPUT"
echo "输出目录:$OUTPUT"
echo

python3 - "$INPUT" "$OUTPUT" <<'PY'
from __future__ import annotations

import re
import sys
from pathlib import Path

from fontTools.ttLib import TTCollection, TTFont


input_path = Path(sys.argv[1]).expanduser().resolve()
output_root = Path(sys.argv[2]).expanduser().resolve()

# OpenType name table 中常用的名称 ID
NAME_COPYRIGHT = 0
NAME_FAMILY = 1
NAME_SUBFAMILY = 2
NAME_FULL = 4
NAME_POSTSCRIPT = 6
NAME_TYPO_FAMILY = 16
NAME_TYPO_SUBFAMILY = 17


def decode_name(record) -> str | None:
    """尽可能可靠地解码 name 表记录。"""
    try:
        value = record.toUnicode()
    except Exception:
        try:
            value = record.string.decode("utf-16-be")
        except Exception:
            try:
                value = record.string.decode("utf-8")
            except Exception:
                return None

    value = value.strip()
    return value or None


def get_name(font: TTFont, name_id: int) -> str | None:
    """优先获取英文名称,找不到时返回任意可解码名称。"""
    name_table = font.get("name")

    if name_table is None:
        return None

    candidates: list[tuple[int, str]] = []

    for record in name_table.names:
        if record.nameID != name_id:
            continue

        value = decode_name(record)
        if not value:
            continue

        # Windows 英文和 Macintosh 英文优先
        priority = 10

        if record.platformID == 3 and record.langID in (0x0409, 0):
            priority = 0
        elif record.platformID == 1 and record.langID == 0:
            priority = 1
        elif record.platformID == 0:
            priority = 2

        candidates.append((priority, value))

    if not candidates:
        return None

    candidates.sort(key=lambda item: item[0])
    return candidates[0][1]


def sanitize_filename(value: str) -> str:
    """将字体名称转换为适合作为文件名的形式。"""
    value = value.strip()

    replacements = {
        "苹方-简": "PingFang-SC",
        "蘋方-繁": "PingFang-TC",
        "蘋方-港": "PingFang-HK",
        "苹方": "PingFang",
        "蘋方": "PingFang",
    }

    for source, target in replacements.items():
        value = value.replace(source, target)

    value = re.sub(r"\s+", "-", value)
    value = value.replace("/", "-")
    value = value.replace("\\", "-")
    value = value.replace(":", "-")
    value = re.sub(r'[<>:"|?*\x00-\x1f]', "", value)
    value = re.sub(r"-+", "-", value)

    return value.strip("-. ") or "Unnamed-Font"


def detect_region(*names: str | None) -> str:
    combined = " ".join(name for name in names if name).lower()

    if (
        "pingfang sc" in combined
        or "pingfang-sc" in combined
        or "苹方-简" in combined
        or "简体" in combined
    ):
        return "SC"

    if (
        "pingfang tc" in combined
        or "pingfang-tc" in combined
        or "蘋方-繁" in combined
        or "繁體" in combined
    ):
        return "TC"

    if (
        "pingfang hk" in combined
        or "pingfang-hk" in combined
        or "蘋方-港" in combined
        or "香港" in combined
    ):
        return "HK"

    return "Other"


def normalize_weight(value: str | None) -> str:
    if not value:
        return "Regular"

    lowered = value.lower().replace(" ", "").replace("-", "")

    mapping = (
        ("ultralight", "Ultralight"),
        ("extralight", "Ultralight"),
        ("thin", "Thin"),
        ("light", "Light"),
        ("regular", "Regular"),
        ("normal", "Regular"),
        ("medium", "Medium"),
        ("semibold", "Semibold"),
        ("demibold", "Semibold"),
        ("bold", "Bold"),
    )

    for token, normalized in mapping:
        if token in lowered:
            return normalized

    return sanitize_filename(value)


def output_extension(font: TTFont) -> str:
    # OTTO 通常表示 CFF/CFF2 轮廓,应该保存为 OTF。
    if font.sfntVersion == "OTTO":
        return ".otf"

    return ".ttf"


def unique_path(path: Path) -> Path:
    if not path.exists():
        return path

    counter = 2

    while True:
        candidate = path.with_name(
            f"{path.stem}-{counter}{path.suffix}"
        )

        if not candidate.exists():
            return candidate

        counter += 1


def split_collection(path: Path) -> int:
    collection = TTCollection(str(path), lazy=False)
    count = 0

    try:
        total = len(collection.fonts)
        print(f"字体集合中包含 {total} 个字体成员。\n")

        for index, font in enumerate(collection.fonts):
            family = (
                get_name(font, NAME_TYPO_FAMILY)
                or get_name(font, NAME_FAMILY)
            )

            subfamily = (
                get_name(font, NAME_TYPO_SUBFAMILY)
                or get_name(font, NAME_SUBFAMILY)
            )

            full_name = get_name(font, NAME_FULL)
            postscript_name = get_name(font, NAME_POSTSCRIPT)

            region = detect_region(
                family,
                subfamily,
                full_name,
                postscript_name,
            )

            weight = normalize_weight(subfamily)

            if region == "Other":
                base_name = (
                    postscript_name
                    or full_name
                    or f"PingFang-{index:02d}"
                )
                filename = sanitize_filename(base_name)
            else:
                filename = f"PingFang-{region}-{weight}"

            extension = output_extension(font)

            region_dir = output_root / region
            region_dir.mkdir(parents=True, exist_ok=True)

            output_path = unique_path(region_dir / f"{filename}{extension}")

            # 重新计算校验和,避免保留旧的 checksumAdjustment。
            font.recalcTimestamp = False
            font.recalcBBoxes = True

            font.save(str(output_path), reorderTables=True)
            count += 1

            relative = output_path.relative_to(output_root)

            print(f"[{index + 1:02d}/{total:02d}] {relative}")
            print(f"       family:     {family or '-'}")
            print(f"       subfamily:  {subfamily or '-'}")
            print(f"       full name:  {full_name or '-'}")
            print(f"       PostScript: {postscript_name or '-'}")
            print()

    finally:
        collection.close()

    return count


def extract_single_font(path: Path) -> int:
    """兼容用户传入单个 TTF/OTF 的情况。"""
    font = TTFont(str(path), lazy=False)

    try:
        family = (
            get_name(font, NAME_TYPO_FAMILY)
            or get_name(font, NAME_FAMILY)
        )
        subfamily = (
            get_name(font, NAME_TYPO_SUBFAMILY)
            or get_name(font, NAME_SUBFAMILY)
        )
        full_name = get_name(font, NAME_FULL)
        postscript_name = get_name(font, NAME_POSTSCRIPT)

        region = detect_region(
            family,
            subfamily,
            full_name,
            postscript_name,
        )
        weight = normalize_weight(subfamily)

        if region == "Other":
            filename = sanitize_filename(
                postscript_name or full_name or path.stem
            )
        else:
            filename = f"PingFang-{region}-{weight}"

        region_dir = output_root / region
        region_dir.mkdir(parents=True, exist_ok=True)

        extension = output_extension(font)
        output_path = unique_path(region_dir / f"{filename}{extension}")

        font.save(str(output_path), reorderTables=True)
        print(output_path.relative_to(output_root))

    finally:
        font.close()

    return 1


output_root.mkdir(parents=True, exist_ok=True)

try:
    extracted = split_collection(input_path)
except Exception as collection_error:
    try:
        extracted = extract_single_font(input_path)
    except Exception:
        print(
            f"无法读取字体文件:{input_path}\n"
            f"TTC 读取错误:{collection_error}",
            file=sys.stderr,
        )
        raise

print(f"\n完成,共导出 {extracted} 个字体文件。")
print(f"输出目录:{output_root}")
PY

echo
echo "字体文件列表:"
find "$OUTPUT" -type f \( -iname '*.ttf' -o -iname '*.otf' \) \
    -print | sort