MacOS与Windows的字体对齐

• 本文约 3525 字,阅读大致需要 17 分钟 • Sysadmin

近日来,由于工作设备由Windows迁移至MacOS,发现同一份文档在Windows中字体、排版均正常,但是一旦放到MacOS中,就会出现字体丢失,版式异常等问题,即便将对应的字体文件和默认模版更新到MacOS中,依然出现字体缺失或显示异常等问题。

经过一段时间的琢磨,发现主要问题是Windows和MacOS对字体的name表读取是有明显差异的,两个系统各自偏爱不同的nameID和platformID。Windows系统在读取字体时,主要取nameID的1(家族名)和2(子家族名)作为字体名称显示,优先读取platformID = 3(windows unicode)的记录;MacOS系统在读取字体时,主要取nameID 4(Full font name)作为字体名称显示,取platformID = 1(Macintosh)的记录,当然也兼容platformID = 3的记录;PostScript主要取nameID 6的记录。

因此具体在使用上,同一个字体的文档在Windows和MacOS的Office软件中显示的字体会出现明显差异,造成混乱。为了文档在不同系统的一致性显示,基于目前Windows的用户更多,最简单的办法是修正个人设备中字体在MacOS中的namespace信息,保持其解析与Windows中的一致性。

为一次性解决问题,实现(预编译包下载:https://aibsd.lanzouq.com/irmjS4bpsotc 密码:mfna)如下:

  • Golang实现:
  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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// -*- coding: utf-8 -*-
package main

import (
	"encoding/binary"
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"unicode/utf16"
)

type nameRec struct {
	platformID, encID, langID, nameID uint16
	raw                               []byte
}
type table struct {
	tag  string
	data []byte
}
type fontInfo struct {
	base   uint32
	tables []table
}

func readTables(data []byte, base uint32) []table {
	if int(base)+12 > len(data) {
		return nil
	}
	nt := int(binary.BigEndian.Uint16(data[base+4:]))
	out := make([]table, 0, nt)
	for i := 0; i < nt; i++ {
		d := int(base) + 12 + i*16
		if d+16 > len(data) {
			break
		}
		tag := string(data[d : d+4])
		off := binary.BigEndian.Uint32(data[d+8:])
		l := binary.BigEndian.Uint32(data[d+12:])
		if int(off)+int(l) > len(data) { // 越界保护, 避免slice panic
			continue
		}
		out = append(out, table{tag, data[off : off+l]})
	}
	return out
}

// loadFonts返回字体列表(含各自base偏移)与是否TTC
func loadFonts(data []byte) ([]fontInfo, bool) {
	if len(data) >= 4 && string(data[:4]) == "ttcf" {
		num := binary.BigEndian.Uint32(data[8:12])
		fis := make([]fontInfo, 0, num)
		for i := uint32(0); i < num; i++ {
			base := binary.BigEndian.Uint32(data[12+i*4:])
			if int(base) > len(data) { // 越界保护
				continue
			}
			fis = append(fis, fontInfo{base, readTables(data, base)})
		}
		return fis, true
	}
	return []fontInfo{{0, readTables(data, 0)}}, false
}

func findNameTable(fi *fontInfo) ([]nameRec, bool) {
	for _, t := range fi.tables {
		if t.tag == "name" {
			return parseName(t.data), true
		}
	}
	return nil, false
}

func parseName(tbl []byte) []nameRec {
	if len(tbl) < 6 {
		return nil
	}
	count := binary.BigEndian.Uint16(tbl[2:4])
	strOff := binary.BigEndian.Uint16(tbl[4:6])
	recs := make([]nameRec, 0, count)
	for i := 0; i < int(count); i++ {
		b := 6 + i*12
		if b+12 > len(tbl) {
			break
		}
		l := binary.BigEndian.Uint16(tbl[b+8:])
		o := binary.BigEndian.Uint16(tbl[b+10:])
		so := int(strOff) + int(o)
		if so+int(l) > len(tbl) {
			continue
		}
		recs = append(recs, nameRec{
			binary.BigEndian.Uint16(tbl[b:]), binary.BigEndian.Uint16(tbl[b+2:]),
			binary.BigEndian.Uint16(tbl[b+4:]), binary.BigEndian.Uint16(tbl[b+6:]),
			tbl[so : so+int(l)],
		})
	}
	return recs
}

func decode(r nameRec) string {
	switch r.platformID {
	case 0, 3:
		u := make([]uint16, 0, len(r.raw)/2)
		for i := 0; i+1 < len(r.raw); i += 2 {
			u = append(u, binary.BigEndian.Uint16(r.raw[i:]))
		}
		return string(utf16.Decode(u))
	case 1:
		if len(r.raw) >= 2 && r.raw[0] == 0x00 && r.raw[1] != 0x00 {
			u := make([]uint16, 0, len(r.raw)/2)
			for i := 0; i+1 < len(r.raw); i += 2 {
				u = append(u, binary.BigEndian.Uint16(r.raw[i:]))
			}
			return string(utf16.Decode(u))
		}
		var sb strings.Builder
		for _, c := range r.raw {
			if c >= 0x20 && c < 0x80 {
				sb.WriteByte(c)
			}
		}
		return sb.String()
	}
	return fmt.Sprintf("<p%d?>", r.platformID)
}

func encode(s string, platformID, encID uint16) []byte {
	switch platformID {
	case 0, 3:
		u := utf16.Encode([]rune(s))
		b := make([]byte, len(u)*2)
		for i, r := range u {
			binary.BigEndian.PutUint16(b[i*2:], r)
		}
		return b
	case 1:
		if encID == 0 {
			out := make([]byte, 0, len(s))
			for i := 0; i < len(s); i++ {
				if s[i] < 0x80 {
					out = append(out, s[i])
				}
			}
			return out
		}
		u := utf16.Encode([]rune(s))
		b := make([]byte, len(u)*2)
		for i, r := range u {
			binary.BigEndian.PutUint16(b[i*2:], r)
		}
		return b
	}
	return []byte(s)
}

func cmdDump(path string, fontIndex int) {
	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "读取失败:", err)
		os.Exit(1)
	}
	fis, isttc := loadFonts(data)
	if fontIndex >= 0 {
		if fontIndex >= len(fis) {
			fmt.Fprintln(os.Stderr, "索引超出范围:", fontIndex, "/", len(fis))
			os.Exit(1)
		}
		dumpOne(path, &fis[fontIndex], fontIndex, isttc)
		return
	}
	for i := range fis {
		dumpOne(path, &fis[i], i, isttc)
	}
}

func dumpOne(path string, fi *fontInfo, idx int, isttc bool) {
	recs, ok := findNameTable(fi)
	pre := fmt.Sprintf("  [字体#%d] ", idx)
	if !ok {
		fmt.Printf("== %s :: 字体#%d无name表\n", filepath.Base(path), idx)
		return
	}
	fmt.Printf("== %s :: 字体#%d %s name表 ==\n", filepath.Base(path), idx, map[bool]string{true: "(TTC)", false: "(单字体)"}[isttc])
	sort.Slice(recs, func(i, j int) bool { return recs[i].nameID < recs[j].nameID })
	for _, r := range recs {
		fmt.Printf("%snameID=%-2d plat=%d enc=%d lang=0x%04x: %q\n",
			pre, r.nameID, r.platformID, r.encID, r.langID, decode(r))
	}
}

var macEn = [2]uint16{0, 0x0000}
var macZh = [2]uint16{25, 0x0021}

func find(recs []nameRec, nameID, platformID, enc, lang uint16) string {
	for _, r := range recs {
		if r.nameID == nameID && r.platformID == platformID && r.encID == enc && r.langID == lang {
			return decode(r)
		}
	}
	return ""
}

func isRegular(s string) bool {
	s = strings.ToLower(s)
	return s == "regular" || s == "normal" || s == ""
}

// alignTables重写给定字体的name表, 返回新表(slice或nil表示需跳过)与原因描述
func alignTables(recs []nameRec, langs []string, withTypo bool) ([]byte, string) {
	base := map[string][2]string{}
	for _, lang := range langs {
		var fam, sub string
		if lang == "zh" {
			fam = find(recs, 1, 3, 1, 0x0804)
			sub = find(recs, 2, 3, 1, 0x0804)
		} else {
			fam = find(recs, 1, 3, 1, 0x0409)
			sub = find(recs, 2, 3, 1, 0x0409)
		}
		if fam == "" {
			fam = find(recs, 1, 3, 0, 0)
		}
		if sub == "" {
			sub = "Regular"
		}
		if fam == "" {
			return nil, fmt.Sprintf("缺少可用的Windows family记录(lang=%s)", lang)
		}
		base[lang] = [2]string{fam, sub}
	}
	var keep []nameRec
	for _, r := range recs {
		if r.platformID == 3 {
			keep = append(keep, r)
			continue
		}
		if r.nameID == 16 || r.nameID == 17 {
			continue
		}
		if (r.platformID == 0 || r.platformID == 1) && (r.nameID == 1 || r.nameID == 2 || r.nameID == 4) {
			continue
		}
		keep = append(keep, r)
	}
	for _, lang := range langs {
		fam, sub := base[lang][0], base[lang][1]
		full := fam
		if !isRegular(sub) {
			full = fam + " " + sub
		}
		for _, plat := range []uint16{1, 0} {
			if plat == 1 && lang != "en" {
				continue
			}
			var enc, lid uint16
			if plat == 0 {
				enc, lid = 3, 0x0409
				if lang == "zh" {
					enc, lid = 3, 0x0804
				}
			} else {
				if lang == "zh" {
					enc, lid = macZh[0], macZh[1]
				} else {
					enc, lid = macEn[0], macEn[1]
				}
			}
			keep = append(keep, nameRec{plat, enc, lid, 1, encode(fam, plat, enc)})
			keep = append(keep, nameRec{plat, enc, lid, 2, encode(sub, plat, enc)})
			keep = append(keep, nameRec{plat, enc, lid, 4, encode(full, plat, enc)})
			if withTypo {
				keep = append(keep, nameRec{plat, enc, lid, 16, encode(fam, plat, enc)})
				keep = append(keep, nameRec{plat, enc, lid, 17, encode(sub, plat, enc)})
			}
		}
	}
	return buildNameTable(keep), "ok"
}

func buildNameTable(recs []nameRec) []byte {
	count := len(recs)
	stringOff := 6 + 12*count
	var sb []byte
	type e struct {
		r   nameRec
		off uint16
	}
	ents := make([]e, 0, count)
	for _, r := range recs {
		ents = append(ents, e{r, uint16(len(sb))})
		sb = append(sb, r.raw...)
	}
	out := make([]byte, stringOff+len(sb))
	binary.BigEndian.PutUint16(out[2:], uint16(count))
	binary.BigEndian.PutUint16(out[4:], uint16(stringOff))
	for i, x := range ents {
		b := 6 + i*12
		binary.BigEndian.PutUint16(out[b:], x.r.platformID)
		binary.BigEndian.PutUint16(out[b+2:], x.r.encID)
		binary.BigEndian.PutUint16(out[b+4:], x.r.langID)
		binary.BigEndian.PutUint16(out[b+6:], x.r.nameID)
		binary.BigEndian.PutUint16(out[b+8:], uint16(len(x.r.raw)))
		// 记录偏移相对字符串区起始; 字符串实际位置 = header.stringOffset + 此值 (与fontTools语义一致)
		binary.BigEndian.PutUint16(out[b+10:], x.off)
	}
	copy(out[stringOff:], sb)
	return out
}

func u32sum(b []byte) uint32 {
	var s uint32
	i := 0
	for ; i+4 <= len(b); i += 4 {
		s += binary.BigEndian.Uint32(b[i:])
	}
	if i < len(b) {
		var t [4]byte
		copy(t[:], b[i:])
		s += binary.BigEndian.Uint32(t[:])
	}
	return s
}

func align4(n int) int { return (n + 3) &^ 3 }

// writeFont序列化单个字体(offset table + tables), 返回字节; head表adjustment按"该字体字节"重算
func writeFont(offsetTable []byte, tables []table) []byte {
	nt := len(tables)
	dirSize := align4(len(offsetTable) + nt*16)
	total := dirSize
	for _, t := range tables {
		total += align4(len(t.data))
	}
	out := make([]byte, total)
	copy(out, offsetTable)
	// 表数据必须从目录区(dirSize)之后开始, 否则会覆盖目录导致字体损坏
	cursor := dirSize
	offsets := make([]uint32, nt)
	sums := make([]uint32, nt)
	for i, t := range tables {
		offsets[i] = uint32(cursor)
		sums[i] = u32sum(t.data)
		copy(out[cursor:], t.data)
		cursor += align4(len(t.data))
	}
	for i, t := range tables {
		d := len(offsetTable) + i*16
		copy(out[d:d+4], t.tag)
		binary.BigEndian.PutUint32(out[d+4:], sums[i])
		binary.BigEndian.PutUint32(out[d+8:], offsets[i])
		binary.BigEndian.PutUint32(out[d+12:], uint32(len(t.data)))
	}
	// head checkSumAdjustment: 该字体所有字节求和(head+8置0)
	if headIdx := findTableIdx(tables, "head"); headIdx >= 0 {
		st := int(offsets[headIdx]) + 8
		work := make([]byte, len(out))
		copy(work, out)
		work[st], work[st+1], work[st+2], work[st+3] = 0, 0, 0, 0
		adj := 0xB1B0AFBA - u32sum(work)
		binary.BigEndian.PutUint32(out[st:st+4], adj)
	}
	return out
}

func findTableIdx(tables []table, tag string) int {
	for i, t := range tables {
		if t.tag == tag {
			return i
		}
	}
	return -1
}

func cmdAlign(path, out string, langs []string, fontIndex int, withTypo bool) {
	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "读取失败:", err)
		os.Exit(1)
	}
	fis, isttc := loadFonts(data)
	// 处理字体: 默认(-1)处理全部; 否则处理指定索引
	if fontIndex >= 0 && fontIndex >= len(fis) {
		fmt.Fprintln(os.Stderr, "索引超出范围:", fontIndex, "/", len(fis))
		os.Exit(1)
	}
	newNames := make([][]byte, len(fis))
	changed := make([]bool, len(fis))
	idxs := make([]int, 0)
	if fontIndex < 0 {
		for i := range fis {
			idxs = append(idxs, i)
		}
	} else {
		idxs = append(idxs, fontIndex)
	}
	processed := 0
	for _, i := range idxs {
		recs, ok := findNameTable(&fis[i])
		if !ok {
			fmt.Fprintf(os.Stderr, "  ⚠ 字体#%d: 无name表, 已跳过\n", i)
			continue
		}
		nb, reason := alignTables(recs, langs, withTypo)
		if nb == nil {
			fmt.Fprintf(os.Stderr, "  ⚠ 字体#%d: %s, 已跳过(其余正常处理)\n", i, reason)
			continue
		}
		newNames[i], changed[i] = nb, true
		processed++
	}
	if processed == 0 {
		fmt.Fprintln(os.Stderr, "!!! 没有任何字体可对齐, 不产生输出文件")
		os.Exit(3)
	}

	// 重建文件
	var outData []byte
	if isttc {
		outData = rebuildTTC(data, fis, changed, newNames)
	} else {
		outData = rebuildSingle(data, &fis[0], changed[0], newNames[0])
	}
	if err := os.WriteFile(out, outData, 0644); err != nil {
		fmt.Fprintln(os.Stderr, "写入失败:", err)
		os.Exit(1)
	}
	fmt.Printf("已生成: %s\n", out)
}

func rebuildSingle(src []byte, fi *fontInfo, changed bool, newName []byte) []byte {
	offTbl := append([]byte{}, src[fi.base:fi.base+12]...)
	tables := make([]table, 0, len(fi.tables))
	for _, t := range fi.tables {
		if changed && t.tag == "name" {
			t = table{"name", newName}
		}
		tables = append(tables, t)
	}
	binary.BigEndian.PutUint16(offTbl[4:6], uint16(len(tables)))
	return writeFont(offTbl, tables)
}

func rebuildTTC(src []byte, fis []fontInfo, changed []bool, newNames [][]byte) []byte {
	num := binary.BigEndian.Uint32(src[8:12])
	// 生成各字体字节
	fontBytes := make([][]byte, len(fis))
	dirStart := 12 + int(num)*4
	cursor := dirStart
	offsets := make([]uint32, len(fis))
	for i := range fis {
		offTbl := append([]byte{}, src[fis[i].base:fis[i].base+12]...)
		tables := make([]table, 0, len(fis[i].tables))
		for _, t := range fis[i].tables {
			if changed[i] && t.tag == "name" {
				t = table{"name", newNames[i]}
			}
			tables = append(tables, t)
		}
		binary.BigEndian.PutUint16(offTbl[4:6], uint16(len(tables)))
		b := writeFont(offTbl, tables)
		offsets[i] = uint32(cursor)
		// 表offset需改为相对整个TTC文件的绝对偏移(fontTools语义), 而非相对字体block
		ntFont := int(binary.BigEndian.Uint16(b[4:6]))
		for t := 0; t < ntFont; t++ {
			d := 12 + t*16
			cur := binary.BigEndian.Uint32(b[d+8:])
			binary.BigEndian.PutUint32(b[d+8:], cur+offsets[i])
		}
		fontBytes[i] = b
		cursor += len(b)
	}
	out := make([]byte, cursor)
	copy(out, "ttcf")
	ver := binary.BigEndian.Uint32(src[4:8])
	binary.BigEndian.PutUint32(out[4:8], ver)
	binary.BigEndian.PutUint32(out[8:12], num)
	for i := range fis {
		binary.BigEndian.PutUint32(out[12+i*4:], offsets[i])
	}
	c := dirStart
	for i := range fis {
		copy(out[c:], fontBytes[i])
		c += len(fontBytes[i])
	}
	return out
}

// mfna — macOS Fonts Name Align tools
const progFull = "macOS Fonts Name Align tools"

func banner() {
	fmt.Println("mfna — " + progFull)
	fmt.Println("  把macOS读取的字体name信息对齐到Windows的值(Windows记录保持不改)")
	fmt.Println("  支持TTF / OTF / TTC; TTC默认处理全部字体, 可用 --font-index指定")
	fmt.Println()
	fmt.Println("用法:")
	fmt.Println("  mfna dump <font> [--font-index N]")
	fmt.Println("  mfna align <font> --out <out> [--lang en,zh] [--with-typo] [--font-index N]")
	fmt.Println("  mfna -v | --version显示版本与名称释义")
}

func main() {
	if len(os.Args) < 2 || os.Args[1] == "-h" || os.Args[1] == "--help" {
		banner()
		os.Exit(0)
	}
	if os.Args[1] == "-v" || os.Args[1] == "--version" {
		fmt.Printf("mfna %s (build for macOS/Linux)", progFull)
		return
	}
	switch os.Args[1] {
	case "dump":
		if len(os.Args) < 3 {
			usage()
		}
		idx := -1
		for i := 2; i < len(os.Args)-1; i++ {
			if os.Args[i] == "--font-index" && i+1 < len(os.Args) {
				fmt.Sscanf(os.Args[i+1], "%d", &idx)
			}
		}
		cmdDump(os.Args[2], idx)
	case "align":
		var out, lang string = "", "en,zh"
		fontIndex := -1
		withTypo := false
		var pos []string
		args := os.Args[2:]
		for i := 0; i < len(args); i++ {
			switch args[i] {
			case "--out":
				if i+1 < len(args) {
					out = args[i+1]
					i++
				}
			case "--lang":
				if i+1 < len(args) {
					lang = args[i+1]
					i++
				}
			case "-font-index", "--font-index":
				if i+1 < len(args) {
					fmt.Sscanf(args[i+1], "%d", &fontIndex)
					i++
				}
			case "--with-typo":
				withTypo = true
			default:
				pos = append(pos, args[i])
			}
		}
		if out == "" || len(pos) < 1 {
			usage()
		}
		langs := languages(lang)
		if len(langs) == 0 {
			fmt.Fprintln(os.Stderr, "--lang需包含en或zh")
			os.Exit(2)
		}
		cmdAlign(pos[0], out, langs, fontIndex, withTypo)
	default:
		usage()
	}
}

func languages(s string) []string {
	var out []string
	for _, x := range strings.Split(s, ",") {
		x = strings.TrimSpace(x)
		if x == "en" {
			out = append(out, "en")
		} else if x == "zh" {
			out = append(out, "zh")
		}
	}
	return out
}

func usage() {
	fmt.Fprintln(os.Stderr, "用法:\n  mfna dump <font> [--font-index N]\n  mfna align <font> --out out [-font-index N] [--lang en,zh] [--with-typo]\n运行mfna(无参数) 查看详细帮助")
	os.Exit(2)
}
  • Python实现:
  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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse, os, json, struct
from fontTools.ttLib import TTFont, TTCollection, TTLibError

MAC_SPECS = {"en": (1, 0, 0x0000), "zh": (1, 25, 0x0021)}
WIN_SPECS = {"en": (3, 1, 0x0409), "zh": (3, 1, 0x0804)}


def is_ttc(path):
    with open(path, "rb") as f:
        return f.read(4) == b"ttcf"


def load(path, font_index=None, force=False):
    """返回 (fonts_list, is_collection)"""
    if is_ttc(path):
        coll = TTCollection(path)
        return coll, True
    font = TTFont(path)
    if font_index is not None and font_index != 0:
        raise SystemExit("单字体文件只有索引0")
    return [font], False


def _get(name, nameID, specs):
    p, e, l = specs
    for r in name.names:
        if r.nameID == nameID and r.platformID == p and r.platEncID == e and r.langID == l:
            try:
                return r.toUnicode()
            except Exception:
                return None
    return None


def _first(name, nameID, platformID):
    for r in name.names:
        if r.nameID == nameID and r.platformID == platformID:
            try:
                return r.toUnicode()
            except Exception:
                return None
    return None


def dump_table(path, as_json=False, font_index=None):
    fonts, iscol = load(path, font_index)
    if font_index is None:
        idxs = range(len(fonts)) if iscol else [0]
    else:
        idxs = [font_index]
    for i in idxs:
        if i >= len(fonts):
            raise SystemExit(f"索引 {i} 超出范围(共 {len(fonts)} 个字体)")
        font = fonts[i]
        if "name" not in font:
            print(f"[字体#{i}] 无name表"); continue
        name = font["name"]
        rows = []
        for r in name.names:
            try:
                v = r.toUnicode()
            except Exception:
                v = "<无法解码>"
            rows.append((r.nameID, r.platformID, r.platEncID, r.langID, v))
        rows.sort(key=lambda x: (x[0], x[1], x[2], x[3]))
        if as_json:
            data = [{"nameID": x[0], "platformID": x[1], "encID": x[2],
                     "langID": hex(x[3]), "value": x[4]} for x in rows]
            print(f"[字体#{i}] " + json.dumps(data, ensure_ascii=False))
        else:
            print(f"== {path} :: 字体#{i} ({'TTC' if iscol else '单字体'}) name表 ==")
            tag = f"  [字体#{i}] " if iscol and font_index is None else "  "
            for x in rows:
                print(f"{tag}nameID={x[0]:2d} plat={x[1]} enc={x[2]} lang=0x{x[3]:04x}: {x[4]!r}")


def operate_font(font, langs, with_typo, force=False):
    """对单个TTFont应用对齐逻辑, 返回True表示执行了修改"""
    if "name" not in font:
        return False
    name = font["name"]
    base = {}
    for lang in langs:
        fam = _get(name, 1, WIN_SPECS[lang])
        sub = _get(name, 2, WIN_SPECS[lang])
        if fam is None:
            fam = _first(name, 1, 3)
        if sub is None:
            sub = _first(name, 2, 3) or "Regular"
        base[lang] = {"family": fam, "sub": sub}
        if fam is None:
            print(f"  [跳过] 未找到Windows平台family(lang={lang})")
            return False
    # 移除mac平台待重写1/2/4/16/17及各平台16/17; 保留platform 3
    name.names = [n for n in name.names
                  if not (n.platformID == 3 and False)     # platform 3永不删
                  and not (n.platformID == 1 and n.nameID in {1, 2, 4, 16, 17})
                  and n.nameID not in {16, 17}]
    for lang in langs:
        fam = base[lang]["family"] or base["en"]["family"]
        sub = base[lang]["sub"] or "Regular"
        full = fam if sub.lower() in ("regular", "normal", "") else f"{fam} {sub}"
        p, e, l = MAC_SPECS[lang]
        name.setName(fam, 1, p, e, l)
        name.setName(sub, 2, p, e, l)
        name.setName(full, 4, p, e, l)
        if with_typo:
            name.setName(fam, 16, p, e, l)
            name.setName(sub, 17, p, e, l)
    return True


def align_path(path, outpath, langs, with_typo, font_index, force):
    iscol = is_ttc(path)
    if iscol:
        coll = TTCollection(path)
        if font_index is None:
            idxs = range(len(coll.fonts))
        else:
            idxs = [font_index]
        done = 0
        for i in idxs:
            if i >= len(coll.fonts):
                raise SystemExit(f"索引 {i} 超出范围(共 {len(coll.fonts)} 个字体)")
            if operate_font(coll.fonts[i], langs, with_typo, force):
                done += 1
        coll.save(outpath)
        print(f"✅ 已写出TTC: {outpath} (处理 {done} 个字体 / 共 {len(coll.fonts)})")
    else:
        font = TTFont(path)
        if font_index is not None and font_index != 0:
            raise SystemExit("单字体文件无索引之分")
        if not operate_font(font, langs, with_typo, force):
            raise SystemExit("未对齐(缺Windows平台family)")
        font.save(outpath)
        print(f"✅ 已写出: {outpath}")


def main():
    ap = argparse.ArgumentParser(description="字体name表dump/对齐工具 (支持TTF/OTF/TTC)")
    sub = ap.add_subparsers(dest="cmd", required=True)

    d = sub.add_parser("dump", help="打印name表")
    d.add_argument("font"); d.add_argument("--json", action="store_true")
    d.add_argument("--font-index", type=int, default=None, help="TTC字体索引(0-based)")

    p = sub.add_parser("align", help="以Windows为基准对齐macOS")
    p.add_argument("font"); p.add_argument("--out", required=True)
    p.add_argument("--lang", default="en,zh")
    p.add_argument("--with-typo", action="store_true")
    p.add_argument("--font-index", type=int, default=None, help="TTC字体索引, 默认全部")
    p.add_argument("--force", action="store_true")

    args = ap.parse_args()
    if args.cmd == "dump":
        dump_table(args.font, args.json, args.font_index)
        return
    if args.cmd == "align":
        langs = []
        for x in args.lang.lower().replace("both", "en,zh").split(","):
            x = x.strip()
            if x == "en": langs.append("en")
            elif x == "zh": langs.append("zh")
        if not langs:
            raise SystemExit("--lang需包含en或zh")
        align_path(args.font, args.out, langs, args.with_typo, args.font_index, args.force)


if __name__ == "__main__":
    main()