cjkFonts.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /**
  2. * 未嵌入 CJK 字体的字体链(纯函数部分;注册与加载见 cjkFontRuntime.ts,规格见
  3. * docs/plugins/2026-10-15-office-viewer-builtin-panels-spec.md §5)。
  4. *
  5. * pdf.js 对未嵌入字体只找同名系统字体,找不到就退回通用 serif / sans-serif:宋体被画成黑体,
  6. * GBK 等多字节字体名直接放弃替换。这里按字体名(含多字节解码)与 PDF 的 Serif 标志选出同类的
  7. * `zcode-cjk-<文种>-<字形>` 字体族,插进 pdf.js 字体链的通用族之前。
  8. */
  9. export type CjkScript = "sc" | "tc" | "jp" | "kr";
  10. export type CjkStyle = "serif" | "sans" | "kai" | "fang";
  11. export interface CjkProfile {
  12. script: CjkScript;
  13. /** null when the name says nothing about the style; the PDF's serif flag decides. */
  14. style: CjkStyle | null;
  15. }
  16. /** The parts of a pdf.js font object the chain needs. */
  17. export interface PdfFontLike {
  18. name?: string;
  19. fallbackName?: string;
  20. missingFile?: boolean;
  21. isType3Font?: boolean;
  22. }
  23. export const FALLBACK_FAMILY = "zcode-cjk-fallback";
  24. /** Manifest of the bundled fallback font, written by scripts/build.mjs for the pdf plugin. */
  25. export const FALLBACK_MANIFEST = "cjk-fallback.json";
  26. /** CJK characters and full-width punctuation only, so Latin text keeps its own fallback. */
  27. export const CJK_UNICODE_RANGE =
  28. "U+1100-11FF, U+2E80-2FDF, U+2FF0-303F, U+3040-30FF, U+3100-31FF, U+3200-33FF, U+3400-4DBF, " +
  29. "U+4E00-9FFF, U+A960-A97F, U+AC00-D7FF, U+F900-FAFF, U+FE10-FE1F, U+FE30-FE4F, U+FF00-FFEF, " +
  30. "U+20000-2FA1F";
  31. /**
  32. * local() candidates per face: macOS, Windows and Linux fonts, by full name and PostScript name.
  33. * The first installed one wins; a face with none installed is not registered.
  34. */
  35. export const LOCAL_FONTS = {
  36. "sc-serif": [
  37. "STSongti-SC-Regular",
  38. "Songti SC Regular",
  39. "STSong",
  40. "SimSun",
  41. "NSimSun",
  42. "Noto Serif CJK SC",
  43. "NotoSerifCJKsc-Regular",
  44. "Noto Serif SC",
  45. "NotoSerifSC-Regular",
  46. "Source Han Serif SC",
  47. "SourceHanSerifSC-Regular",
  48. "AR PL UMing CN",
  49. "AR PL SungtiL GB",
  50. ],
  51. "sc-sans": [
  52. "PingFangSC-Regular",
  53. "PingFang SC Regular",
  54. "HiraginoSansGB-W3",
  55. "Hiragino Sans GB W3",
  56. "STHeitiSC-Light",
  57. "Heiti SC Light",
  58. "Microsoft YaHei",
  59. "SimHei",
  60. "Noto Sans CJK SC",
  61. "NotoSansCJKsc-Regular",
  62. "Noto Sans SC",
  63. "NotoSansSC-Regular",
  64. "Source Han Sans SC",
  65. "SourceHanSansSC-Regular",
  66. "WenQuanYi Micro Hei",
  67. "WenQuanYi Zen Hei",
  68. ],
  69. "sc-kai": [
  70. "STKaitiSC-Regular",
  71. "Kaiti SC Regular",
  72. "STKaiti",
  73. "KaiTi",
  74. "KaiTi_GB2312",
  75. "AR PL UKai CN",
  76. "LXGW WenKai",
  77. "LXGWWenKai-Regular",
  78. ],
  79. "sc-fang": ["STFangsong", "FangSong", "FangSong_GB2312"],
  80. "tc-serif": [
  81. "STSongti-TC-Regular",
  82. "Songti TC Regular",
  83. "LiSongPro",
  84. "LiSong Pro",
  85. "PMingLiU",
  86. "MingLiU",
  87. "Noto Serif CJK TC",
  88. "NotoSerifCJKtc-Regular",
  89. "Noto Serif TC",
  90. "Source Han Serif TC",
  91. "SourceHanSerifTC-Regular",
  92. "AR PL UMing TW",
  93. ],
  94. "tc-sans": [
  95. "PingFangTC-Regular",
  96. "PingFang TC Regular",
  97. "STHeitiTC-Light",
  98. "Heiti TC Light",
  99. "Microsoft JhengHei",
  100. "Noto Sans CJK TC",
  101. "NotoSansCJKtc-Regular",
  102. "Noto Sans TC",
  103. "Source Han Sans TC",
  104. "SourceHanSansTC-Regular",
  105. "WenQuanYi Zen Hei",
  106. ],
  107. "tc-kai": [
  108. "STKaitiTC-Regular",
  109. "Kaiti TC Regular",
  110. "BiauKaiTC-Regular",
  111. "BiauKaiTC Regular",
  112. "DFKai-SB",
  113. "AR PL UKai TW",
  114. ],
  115. "jp-serif": [
  116. "HiraMinProN-W3",
  117. "Hiragino Mincho ProN W3",
  118. "Yu Mincho",
  119. "YuMincho-Regular",
  120. "MS Mincho",
  121. "MS PMincho",
  122. "Noto Serif CJK JP",
  123. "NotoSerifCJKjp-Regular",
  124. "Noto Serif JP",
  125. "Source Han Serif",
  126. "SourceHanSerif-Regular",
  127. "IPAexMincho",
  128. "IPAMincho",
  129. ],
  130. "jp-sans": [
  131. "HiraginoSans-W3",
  132. "Hiragino Sans W3",
  133. "HiraKakuProN-W3",
  134. "Hiragino Kaku Gothic ProN W3",
  135. "Yu Gothic",
  136. "YuGothic-Medium",
  137. "Meiryo",
  138. "MS Gothic",
  139. "MS PGothic",
  140. "Noto Sans CJK JP",
  141. "NotoSansCJKjp-Regular",
  142. "Noto Sans JP",
  143. "Source Han Sans",
  144. "SourceHanSans-Regular",
  145. "IPAexGothic",
  146. "IPAGothic",
  147. ],
  148. "kr-serif": [
  149. "AppleMyungjo",
  150. "AppleMyungjo Regular",
  151. "Batang",
  152. "Noto Serif CJK KR",
  153. "NotoSerifCJKkr-Regular",
  154. "Noto Serif KR",
  155. "Source Han Serif K",
  156. "SourceHanSerifK-Regular",
  157. "UnBatang",
  158. "NanumMyeongjo",
  159. ],
  160. "kr-sans": [
  161. "AppleSDGothicNeo-Regular",
  162. "Apple SD Gothic Neo Regular",
  163. "Malgun Gothic",
  164. "Gulim",
  165. "Dotum",
  166. "Noto Sans CJK KR",
  167. "NotoSansCJKkr-Regular",
  168. "Noto Sans KR",
  169. "Source Han Sans K",
  170. "SourceHanSansK-Regular",
  171. "NanumGothic",
  172. "UnDotum",
  173. ],
  174. } satisfies Partial<Record<`${CjkScript}-${CjkStyle}`, string[]>>;
  175. export type FaceKey = keyof typeof LOCAL_FONTS;
  176. export const familyOf = (key: FaceKey) => `zcode-cjk-${key}`;
  177. // 规则按顺序匹配小写、去空格与下划线的字体名。仿/楷 先于 宋(FangSong 含 song);
  178. // HeiseiMin 的 hei 不算黑体。
  179. const STYLE_RULES: [RegExp, CjkStyle][] = [
  180. [/fang|仿/, "fang"],
  181. [/kai|楷/, "kai"],
  182. [/hei(?!sei)|gothic|kakugo|kozgo|gulim|dotum|yuanti|ゴシック|黑|黒|굴림|돋움|고딕/, "sans"],
  183. [
  184. /song|sung|simsun|ming|mincho|kozmin|ryumin|heiseimin|batang|myeongjo|myungjo|宋|明|바탕|명조/,
  185. "serif",
  186. ],
  187. ];
  188. /** Style words that alone do not make a font CJK (Noto Sans, Source Han Serif need a script word). */
  189. const GENERIC_STYLE_RULES: [RegExp, CjkStyle][] = [
  190. [/sans/, "sans"],
  191. [/serif/, "serif"],
  192. ];
  193. const SCRIPT_RULES: [RegExp, CjkScript][] = [
  194. [
  195. /^hy|batang|gulim|dotum|malgun|myeongjo|myungjo|nanum|^un(batang|dotum)|applesdgothic|cjkkr|(kr|ko)\b|바탕|굴림|돋움|명조|고딕/,
  196. "kr",
  197. ],
  198. [/^msung|^mhei|mingliu|dfkai|biaukai|jhenghei|lisong|cjktc|(tc|tw|hk)\b|細明|標楷/, "tc"],
  199. [
  200. /heisei|mincho|kozmin|kozgo|ryumin|gothicbbb|hira(kaku|min|maru)|hiraginosans(?!gb)|yu(gothic|mincho)|meiryo|ms-?p?gothic|ipa(ex)?(mincho|gothic)|cjkjp|jp\b|明朝|ゴシック/,
  201. "jp",
  202. ],
  203. [
  204. /simsun|simhei|stsong|stheiti|stkaiti|stfangsong|yahei|^fz|songti|heiti|kaiti|fangsong|gb2312|cjksc|(sc|cn|gb)\b|宋|黑|楷|仿/,
  205. "sc",
  206. ],
  207. ];
  208. /** Decoders for font names stored as raw multi-byte strings, with the script each implies. */
  209. const NAME_ENCODINGS: [string, CjkScript | null][] = [
  210. ["utf-8", null],
  211. ["gbk", "sc"],
  212. ["big5", "tc"],
  213. ["shift_jis", "jp"],
  214. ["euc-kr", "kr"],
  215. ];
  216. /** Script and style words in a name; null when nothing in it is CJK-specific. */
  217. function classifyText(name: string): { script: CjkScript | null; style: CjkStyle | null } | null {
  218. const key = name.replace(/[\s_]+/g, "").toLowerCase();
  219. const cjkStyle = STYLE_RULES.find(([rule]) => rule.test(key))?.[1] ?? null;
  220. const script = SCRIPT_RULES.find(([rule]) => rule.test(key))?.[1] ?? null;
  221. if (!cjkStyle && !script) return null;
  222. const style = cjkStyle ?? GENERIC_STYLE_RULES.find(([rule]) => rule.test(key))?.[1] ?? null;
  223. return { script, style };
  224. }
  225. /**
  226. * What a font name says about its script and style, or null for a non-CJK name. pdf.js keeps the
  227. * raw bytes of a name as Latin-1 characters; multi-byte names are decoded before matching.
  228. */
  229. export function classifyFontName(name: string): CjkProfile | null {
  230. const raw = name.replace(/^[A-Z]{6}\+/, "");
  231. if (!/[\x80-\xff]/.test(raw) || /[\u0100-\uffff]/.test(raw)) {
  232. const found = classifyText(raw);
  233. return found && { script: found.script ?? "sc", style: found.style };
  234. }
  235. const bytes = Uint8Array.from(raw, (char) => char.charCodeAt(0));
  236. for (const [encoding, implied] of NAME_ENCODINGS) {
  237. let decoded: string;
  238. try {
  239. decoded = new TextDecoder(encoding, { fatal: true }).decode(bytes);
  240. } catch {
  241. continue;
  242. }
  243. // 只采信能认出字形或文种的解码:GBK 几乎总能解码成功,Big5 / Shift-JIS 名会被它误读。
  244. const found = classifyText(decoded);
  245. if (found) return { script: found.script ?? implied ?? "sc", style: found.style };
  246. }
  247. return null;
  248. }
  249. /**
  250. * The `zcode-cjk-*` families for a font pdf.js has no file for, best first; empty for embedded and
  251. * Type 3 fonts.
  252. */
  253. export function cjkFamilies(font: PdfFontLike, fallbackReady: boolean): string[] {
  254. if (!font.missingFile || font.isType3Font) return [];
  255. const profile = classifyFontName(font.name ?? "");
  256. const script = profile?.script ?? "sc";
  257. const style = profile?.style ?? (font.fallbackName === "serif" ? "serif" : "sans");
  258. const own = `${script}-${style}`;
  259. const serif: FaceKey = `${script}-serif`;
  260. const keys: FaceKey[] = own in LOCAL_FONTS ? [own as FaceKey] : [];
  261. // 楷体、仿宋缺失时退到同文种的宋体,而不是黑体;日韩没有这两类,直接用宋体。
  262. if (style !== "sans" && !keys.includes(serif)) keys.push(serif);
  263. return [...keys.map(familyOf), ...(fallbackReady ? [FALLBACK_FAMILY] : [])];
  264. }
  265. const GENERIC_FAMILIES = new Set([
  266. "serif",
  267. "sans-serif",
  268. "monospace",
  269. "cursive",
  270. "fantasy",
  271. "system-ui",
  272. ]);
  273. /** Insert `families` into a CSS font-family list, before its trailing generic family. */
  274. export function withCjkFamilies(css: string, families: string[]): string {
  275. if (!families.length) return css;
  276. const parts = css.split(",");
  277. const quoted = families.map((family) => `"${family}"`);
  278. const last = parts.at(-1)!.trim();
  279. if (!GENERIC_FAMILIES.has(last)) return [...parts, ...quoted].join(",");
  280. return [...parts.slice(0, -1), ...quoted, last].join(",");
  281. }