| 1 | import { describe, expect, it, beforeAll, afterAll } from 'vitest' |
| 2 | import { copyFile, mkdir, mkdtemp, readFile, writeFile, rm } from 'fs/promises' |
| 3 | import { readFileSync, writeFileSync } from 'node:fs' |
| 4 | import { pathToFileURL } from 'node:url' |
| 5 | import os from 'os' |
| 6 | import path from 'path' |
| 7 | import { unzipSync, zipSync } from 'fflate' |
| 8 | import { collectEmbeddedFonts } from '../../../src/main/io/html-pptx/font-collect' |
| 9 | |
| 10 | type ExperimentRun = { |
| 11 | text: string |
| 12 | x: number |
| 13 | y: number |
| 14 | w: number |
| 15 | h: number |
| 16 | fontSize: number |
| 17 | fontFace: string |
| 18 | bold?: boolean |
| 19 | } |
| 20 | type WriteHtmlToPptx = ( |
| 21 | outputPath: string, |
| 22 | document: { title: string; slides: Array<{ texts: ExperimentRun[] }>; embeddedFonts?: unknown[] } |
| 23 | ) => void |
| 24 | |
| 25 | // vitest 把 '@arcsin1/html2pptx' 别名到作者本地的兄弟源码目录(本机不存在), |
| 26 | // 且该包的 CJS 入口在 "type": "module" 包内 require ESM 会直接报错; |
| 27 | // 因此用绝对路径动态导入 ESM 入口,绕开别名与坏掉的 CJS 入口。 |
| 28 | const html2pptxNode = (await import( |
| 29 | pathToFileURL(path.resolve('node_modules/@arcsin1/html2pptx/dist/node.js')).href |
| 30 | )) as { writeHtmlToPptx: WriteHtmlToPptx } |
| 31 | const writeHtmlToPptx = html2pptxNode.writeHtmlToPptx |
| 32 | |
| 33 | const OUTPUT_DIR = process.env.FONT_EXPERIMENT_DIR |
| 34 | const GOOGLE_FONTS_ROOT = path.resolve('resources/google-fonts') |
| 35 | |
| 36 | type FontFaceDecl = { file: string; unicodeRange?: string } |
| 37 | |
| 38 | const parseFacesCss = (css: string): FontFaceDecl[] => { |
| 39 | const faces: FontFaceDecl[] = [] |
| 40 | for (const match of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) { |
| 41 | const block = match[1] || '' |
| 42 | const rawUrl = block.match(/url\(\s*([^)]+?)\s*\)/)?.[1] || '' |
| 43 | const file = rawUrl.replace(/^['"]|['"]$/g, '').replace(/^\.\//, '') |
| 44 | if (!file || !file.endsWith('.woff2')) continue |
| 45 | const unicodeRange = block.match(/unicode-range\s*:\s*([^;}]+)/i)?.[1]?.trim() |
| 46 | faces.push({ file, unicodeRange: unicodeRange || undefined }) |
| 47 | } |
| 48 | return faces |
| 49 | } |
| 50 | |
| 51 | type FamilyFixture = { |
| 52 | projectDir: string |
| 53 | subsetHtmlPath: string |
| 54 | } |
| 55 | |
| 56 | // 搭建一个最小导出环境:把某字体族全部 woff2 拷入项目 assets/fonts, |
| 57 | // 并生成带真实 unicode-range 的 @font-face 页面 HTML(与生产导出一致)。 |
| 58 | const buildFamilyFixture = async ( |
| 59 | family: string, |
| 60 | familyDirName: string |
| 61 | ): Promise<FamilyFixture> => { |
| 62 | const projectDir = await mkdtemp(path.join(os.tmpdir(), 'oh-my-ppt-font-exp-')) |
| 63 | const fontDir = path.join(projectDir, 'assets', 'fonts', 'user-fonts', 'exp') |
| 64 | await mkdir(fontDir, { recursive: true }) |
| 65 | const sourceDir = path.join(GOOGLE_FONTS_ROOT, familyDirName) |
| 66 | const faces = parseFacesCss(await readFile(path.join(sourceDir, 'faces.css'), 'utf-8')) |
| 67 | expect(faces.length).toBeGreaterThan(0) |
| 68 | for (const face of faces) { |
| 69 | await copyFile(path.join(sourceDir, face.file), path.join(fontDir, face.file)) |
| 70 | } |
| 71 | const blocks = faces |
| 72 | .map( |
| 73 | (face) => |
| 74 | `@font-face{font-family:"${family}";src:url("./assets/fonts/user-fonts/exp/${face.file}") format("woff2");` + |
| 75 | `font-weight:400;font-style:normal;font-display:swap;${face.unicodeRange ? `unicode-range:${face.unicodeRange};` : ''}}` |
| 76 | ) |
| 77 | .join('\n') |
| 78 | const htmlPath = path.join(projectDir, 'page.html') |
| 79 | await writeFile( |
| 80 | htmlPath, |
| 81 | `<!doctype html><html><head><meta charset="utf-8"><style>${blocks}</style></head><body></body></html>`, |
| 82 | 'utf-8' |
| 83 | ) |
| 84 | return { projectDir, subsetHtmlPath: htmlPath } |
| 85 | } |
| 86 | |
| 87 | // EOT 头部布局(fonteditor-core EotHead):EOTSize@0, FontDataSize@4, Version@8, Flags@12 |
| 88 | const patchEotHeader = ( |
| 89 | buffer: Uint8Array, |
| 90 | patch: { version?: number; flags?: number } |
| 91 | ): Uint8Array => { |
| 92 | const copy = new Uint8Array(buffer) |
| 93 | const view = new DataView(copy.buffer) |
| 94 | if (patch.version !== undefined) view.setUint32(8, patch.version, true) |
| 95 | if (patch.flags !== undefined) view.setUint32(12, patch.flags, true) |
| 96 | return copy |
| 97 | } |
| 98 | |
| 99 | // app.xml 的 AppVersion 当前是 "00.09:0000"(含冒号,不符合 XX.YYYY 约定),改写为标准格式 |
| 100 | const rewriteAppVersion = (pptxPath: string): void => { |
| 101 | const zip = unzipSync(readFileSync(pptxPath)) |
| 102 | const appXml = Buffer.from(zip['docProps/app.xml']) |
| 103 | .toString('utf-8') |
| 104 | .replace(/<AppVersion>[^<]*<\/AppVersion>/, '<AppVersion>00.0000</AppVersion>') |
| 105 | zip['docProps/app.xml'] = new Uint8Array(Buffer.from(appXml, 'utf-8')) |
| 106 | writeFileSync(pptxPath, zipSync(zip)) |
| 107 | } |
| 108 | |
| 109 | const maShanZhengRun = (): ExperimentRun => ({ |
| 110 | text: '嵌字实验 ABC 123,永', |
| 111 | x: 0.5, |
| 112 | y: 0.5, |
| 113 | w: 9, |
| 114 | h: 1.2, |
| 115 | fontSize: 44, |
| 116 | fontFace: 'Ma Shan Zheng' |
| 117 | }) |
| 118 | |
| 119 | const assertPayloadMagic = (pptxPath: string, format: 'eot' | 'ttf'): void => { |
| 120 | const zip = unzipSync(readFileSync(pptxPath)) |
| 121 | const fontEntries = Object.keys(zip).filter((name) => name.startsWith('ppt/fonts/')) |
| 122 | expect(fontEntries.length).toBeGreaterThan(0) |
| 123 | for (const entry of fontEntries) { |
| 124 | const data = zip[entry] |
| 125 | if (format === 'eot') { |
| 126 | const view = new DataView(data.buffer, data.byteOffset, data.byteLength) |
| 127 | expect(view.byteLength).toBeGreaterThan(82) |
| 128 | expect(view.getUint16(34, true)).toBe(0x504c) |
| 129 | } else { |
| 130 | const isPlainTtf = |
| 131 | data[0] === 0x00 && data[1] === 0x01 && data[2] === 0x00 && data[3] === 0x00 |
| 132 | const isCff = data[0] === 0x4f && data[1] === 0x54 && data[2] === 0x54 && data[3] === 0x4f |
| 133 | expect(isPlainTtf || isCff).toBe(true) |
| 134 | } |
| 135 | } |
| 136 | const presentation = Buffer.from(zip['ppt/presentation.xml']).toString('utf-8') |
| 137 | expect(presentation).toContain('embedTrueTypeFonts="1"') |
| 138 | expect(presentation).toContain('<p:embeddedFontLst>') |
| 139 | } |
| 140 | |
| 141 | describe.skipIf(!OUTPUT_DIR)('PPTX font payload experiment', () => { |
| 142 | const tempDirectories: string[] = [] |
| 143 | const generatedFiles: string[] = [] |
| 144 | |
| 145 | const generate = async ( |
| 146 | fileName: string, |
| 147 | fixture: FamilyFixture, |
| 148 | runs: ExperimentRun[], |
| 149 | opts: { |
| 150 | payloadFormat: 'eot' | 'ttf' |
| 151 | eotPatch?: { version?: number; flags?: number } |
| 152 | omitFonts?: boolean |
| 153 | fixAppVersion?: boolean |
| 154 | } |
| 155 | ): Promise<void> => { |
| 156 | const outPath = path.join(OUTPUT_DIR as string, fileName) |
| 157 | const slides = [{ texts: runs }] |
| 158 | let embedded = opts.omitFonts |
| 159 | ? [] |
| 160 | : await collectEmbeddedFonts(fixture.projectDir, slides, { |
| 161 | mode: 'always', |
| 162 | payloadFormat: opts.payloadFormat, |
| 163 | pageHtmlPaths: [fixture.subsetHtmlPath] |
| 164 | }) |
| 165 | if (opts.eotPatch && embedded.length > 0) { |
| 166 | embedded = embedded.map((item) => ({ ...item, ttfBuffer: patchEotHeader(item.ttfBuffer, opts.eotPatch!) })) |
| 167 | } |
| 168 | writeHtmlToPptx(outPath, { |
| 169 | title: '字体嵌入实验', |
| 170 | slides, |
| 171 | embeddedFonts: embedded.length > 0 ? embedded : undefined |
| 172 | }) |
| 173 | if (opts.fixAppVersion) rewriteAppVersion(outPath) |
| 174 | if (!opts.omitFonts) assertPayloadMagic(outPath, opts.payloadFormat) |
| 175 | generatedFiles.push(fileName) |
| 176 | console.log( |
| 177 | `[experiment] ${fileName}: ${embedded |
| 178 | .map((item) => `${item.style}=${Math.round(item.ttfBuffer.byteLength / 1024)}KB`) |
| 179 | .join(', ') || 'no embedded fonts'}` |
| 180 | ) |
| 181 | } |
| 182 | |
| 183 | beforeAll(async () => { |
| 184 | await mkdir(OUTPUT_DIR as string, { recursive: true }) |
| 185 | }) |
| 186 | |
| 187 | it( |
| 188 | 'generates variant 6: EOT with TTEMBED_SUBSET flag', |
| 189 | async () => { |
| 190 | const fixture = await buildFamilyFixture('Ma Shan Zheng', 'Ma_Shan_Zheng') |
| 191 | tempDirectories.push(fixture.projectDir) |
| 192 | await generate( |
| 193 | '实验6-EOT子集标志.pptx', |
| 194 | fixture, |
| 195 | [maShanZhengRun()], |
| 196 | { payloadFormat: 'eot', eotPatch: { flags: 0x00000001 } } |
| 197 | ) |
| 198 | }, |
| 199 | 120_000 |
| 200 | ) |
| 201 | |
| 202 | it( |
| 203 | 'generates variant 7: EOT version 2.2 + TTEMBED_SUBSET flag', |
| 204 | async () => { |
| 205 | const fixture = await buildFamilyFixture('Ma Shan Zheng', 'Ma_Shan_Zheng') |
| 206 | tempDirectories.push(fixture.projectDir) |
| 207 | await generate( |
| 208 | '实验7-EOTv22子集标志.pptx', |
| 209 | fixture, |
| 210 | [maShanZhengRun()], |
| 211 | { payloadFormat: 'eot', eotPatch: { version: 0x00020002, flags: 0x00000001 } } |
| 212 | ) |
| 213 | }, |
| 214 | 120_000 |
| 215 | ) |
| 216 | |
| 217 | it( |
| 218 | 'generates variant 8: standard AppVersion (00.0000)', |
| 219 | async () => { |
| 220 | const fixture = await buildFamilyFixture('Ma Shan Zheng', 'Ma_Shan_Zheng') |
| 221 | tempDirectories.push(fixture.projectDir) |
| 222 | await generate( |
| 223 | '实验8-AppVersion标准.pptx', |
| 224 | fixture, |
| 225 | [maShanZhengRun()], |
| 226 | { payloadFormat: 'eot', fixAppVersion: true } |
| 227 | ) |
| 228 | }, |
| 229 | 120_000 |
| 230 | ) |
| 231 | |
| 232 | it( |
| 233 | 'generates variant 9: no embedded fonts (repair dialog control)', |
| 234 | async () => { |
| 235 | const fixture = await buildFamilyFixture('Ma Shan Zheng', 'Ma_Shan_Zheng') |
| 236 | tempDirectories.push(fixture.projectDir) |
| 237 | await generate( |
| 238 | '实验9-无嵌入字体.pptx', |
| 239 | fixture, |
| 240 | [maShanZhengRun()], |
| 241 | { payloadFormat: 'eot', omitFonts: true } |
| 242 | ) |
| 243 | }, |
| 244 | 120_000 |
| 245 | ) |
| 246 | |
| 247 | it('writes viewing instructions', async () => { |
| 248 | const instructions = [ |
| 249 | '第三轮实验:定位 PowerPoint「修复」对话框的触发点', |
| 250 | '', |
| 251 | '已知背景:实验1(EOT 子集)在 Mac PowerPoint 上弹修复框,但修复后书法体仍在;', |
| 252 | '真实导出文件同样弹框、字体也正常;WPS 里字体正常、只是排版不同。', |
| 253 | '', |
| 254 | '请用 Mac PowerPoint 依次打开以下文件,记录:是否弹修复框 + 是否显示毛笔书法体:', |
| 255 | '', |
| 256 | '6. 实验6-EOT子集标志.pptx — EOT Flags 补上 TTEMBED_SUBSET(0x1)(真机子集字体应有的标志)', |
| 257 | '7. 实验7-EOTv22子集标志.pptx — EOT Version 改为 0x00020002 + SUBSET 标志(贴近真机产物)', |
| 258 | '8. 实验8-AppVersion标准.pptx — 修正 app.xml 的 AppVersion 为标准格式(字体不动)', |
| 259 | '9. 实验9-无嵌入字体.pptx — 完全不嵌字体(判断弹框是否与字体无关)', |
| 260 | '', |
| 261 | '判读:', |
| 262 | '- 若 9 弹框 → 弹框与嵌入字体无关,重点看 8(AppVersion 修复是否解决)', |
| 263 | '- 若 9 不弹、6/7 有一个不弹 → EOT 头字段是触发点,按胜出格式修 font-collect', |
| 264 | '- 若 6/7/8/9 都弹 → 触发点在包的其他部分,需继续二分(theme/notes/rels 等)' |
| 265 | ].join('\n') |
| 266 | await writeFile(path.join(OUTPUT_DIR as string, '说明.txt'), instructions, 'utf-8') |
| 267 | }) |
| 268 | |
| 269 | afterAll(async () => { |
| 270 | await Promise.all(tempDirectories.map((directory) => rm(directory, { recursive: true, force: true }))) |
| 271 | }) |
| 272 | }) |
| 273 |