| 1 | import { readFileSync, statSync } from 'fs' |
| 2 | import path from 'path' |
| 3 | import log from 'electron-log/main.js' |
| 4 | import { decompress } from 'woff2-encoder' |
| 5 | import fonteditorCore, { createFont } from 'fonteditor-core' |
| 6 | import type { HtmlToPptxEmbeddedFont, HtmlToPptxSlide } from '@arcsin1/html2pptx' |
| 7 | |
| 8 | type EmbeddedFontStyle = HtmlToPptxEmbeddedFont['style'] |
| 9 | |
| 10 | // Container format written into ppt/fonts/fontN.fntdata. 'eot' is what Windows |
| 11 | // PowerPoint itself produces; some viewers (PowerPoint for Mac, WPS) are more |
| 12 | // reliable with a plain sfnt ('ttf') payload. |
| 13 | type EmbeddedPayloadFormat = 'eot' | 'ttf' |
| 14 | |
| 15 | type FontUsage = { |
| 16 | fontFace: string |
| 17 | style: EmbeddedFontStyle |
| 18 | characters: Set<string> |
| 19 | } |
| 20 | |
| 21 | type ProjectFontFace = { |
| 22 | fontFace: string |
| 23 | weight: number |
| 24 | style: 'normal' | 'italic' |
| 25 | fontPath: string |
| 26 | unicodeRange?: string |
| 27 | } |
| 28 | |
| 29 | const EOT_HEADER_SIZE = 82 |
| 30 | const RESTRICTED_EMBEDDING = 0x0002 |
| 31 | const BITMAP_ONLY_EMBEDDING = 0x0200 |
| 32 | |
| 33 | const normalizeFontFace = (value: string): string => value.replace(/\s+/g, ' ').trim() |
| 34 | |
| 35 | const fontStyleFor = (bold?: boolean, italic?: boolean): EmbeddedFontStyle => { |
| 36 | if (bold && italic) return 'boldItalic' |
| 37 | if (bold) return 'bold' |
| 38 | if (italic) return 'italic' |
| 39 | return 'regular' |
| 40 | } |
| 41 | |
| 42 | const usageKey = (fontFace: string, style: EmbeddedFontStyle): string => |
| 43 | `${normalizeFontFace(fontFace).toLocaleLowerCase()}::${style}` |
| 44 | |
| 45 | const addUsage = ( |
| 46 | usages: Map<string, FontUsage>, |
| 47 | fontFace: string | undefined, |
| 48 | text: string, |
| 49 | bold?: boolean, |
| 50 | italic?: boolean |
| 51 | ): void => { |
| 52 | const normalizedFace = normalizeFontFace(fontFace || '') |
| 53 | if (!normalizedFace) return |
| 54 | const style = fontStyleFor(bold, italic) |
| 55 | const key = usageKey(normalizedFace, style) |
| 56 | const usage = usages.get(key) || { |
| 57 | fontFace: normalizedFace, |
| 58 | style, |
| 59 | characters: new Set<string>() |
| 60 | } |
| 61 | for (const character of text) usage.characters.add(character) |
| 62 | usages.set(key, usage) |
| 63 | } |
| 64 | |
| 65 | // Text extraction is the authority for what becomes editable in the PPTX. |
| 66 | // Scanning every font on disk would embed unused families and miss the actual |
| 67 | // style used by rich-text runs. |
| 68 | const collectUsedFontUsages = (slides: HtmlToPptxSlide[]): FontUsage[] => { |
| 69 | const usages = new Map<string, FontUsage>() |
| 70 | for (const slide of slides) { |
| 71 | for (const text of slide.texts) { |
| 72 | if (text.runs?.length) { |
| 73 | for (const run of text.runs) { |
| 74 | addUsage( |
| 75 | usages, |
| 76 | run.fontFace || text.fontFace, |
| 77 | run.text, |
| 78 | run.bold ?? text.bold, |
| 79 | run.italic ?? text.italic |
| 80 | ) |
| 81 | } |
| 82 | } else { |
| 83 | addUsage(usages, text.fontFace, text.text, text.bold, text.italic) |
| 84 | } |
| 85 | } |
| 86 | for (const table of slide.tables || []) { |
| 87 | for (const row of table.rows) { |
| 88 | for (const cell of row) { |
| 89 | addUsage(usages, cell.fontFace, cell.text, cell.bold, cell.italic) |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | return [...usages.values()] |
| 95 | } |
| 96 | |
| 97 | const parseCssValue = (css: string, property: string): string => { |
| 98 | const escapedProperty = property.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 99 | return css.match(new RegExp(`(?:^|;)\\s*${escapedProperty}\\s*:\\s*([^;]+)`, 'i'))?.[1]?.trim() || '' |
| 100 | } |
| 101 | |
| 102 | const parseCssFontFamily = (value: string): string => |
| 103 | normalizeFontFace(value.split(',')[0]?.trim().replace(/^['"]|['"]$/g, '') || '') |
| 104 | |
| 105 | const parseCssFontWeight = (value: string): number => { |
| 106 | const normalized = value.trim().toLowerCase() |
| 107 | if (normalized === 'normal') return 400 |
| 108 | if (normalized === 'bold') return 700 |
| 109 | const match = normalized.match(/\d{1,4}/) |
| 110 | return match ? Math.max(1, Math.min(1000, Number.parseInt(match[0], 10))) : 400 |
| 111 | } |
| 112 | |
| 113 | const parseCssFontStyle = (value: string): 'normal' | 'italic' => |
| 114 | /italic|oblique/i.test(value) ? 'italic' : 'normal' |
| 115 | |
| 116 | const isProjectFontPath = (candidatePath: string, projectDir: string): boolean => { |
| 117 | const fontRoot = path.resolve(projectDir, 'assets', 'fonts') |
| 118 | const relative = path.relative(fontRoot, candidatePath) |
| 119 | return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative) |
| 120 | } |
| 121 | |
| 122 | const resolveFontUrl = (url: string, htmlPath: string, projectDir: string): string | null => { |
| 123 | const source = url.trim().replace(/^['"]|['"]$/g, '') |
| 124 | if (!source || /^(?:data:|https?:|local-asset:)/i.test(source)) return null |
| 125 | const pathname = source.split(/[?#]/, 1)[0] |
| 126 | const candidatePath = path.resolve(path.dirname(htmlPath), decodeURIComponent(pathname)) |
| 127 | if (!isProjectFontPath(candidatePath, projectDir)) return null |
| 128 | if (path.extname(candidatePath).toLowerCase() !== '.woff2') return null |
| 129 | try { |
| 130 | return statSync(candidatePath).isFile() ? candidatePath : null |
| 131 | } catch { |
| 132 | return null |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // Read the actual @font-face declarations injected into exported HTML. This |
| 137 | // covers both bundled Google files and user uploads without relying on either |
| 138 | // storage directory's name or global user-font registry state. |
| 139 | const collectProjectFontFaces = (projectDir: string, htmlPaths: string[]): ProjectFontFace[] => { |
| 140 | const faces = new Map<string, ProjectFontFace>() |
| 141 | for (const htmlPath of new Set(htmlPaths)) { |
| 142 | let html: string |
| 143 | try { |
| 144 | html = readFileSync(htmlPath, 'utf-8') |
| 145 | } catch { |
| 146 | continue |
| 147 | } |
| 148 | for (const match of html.matchAll(/@font-face\s*\{([\s\S]*?)\}/gi)) { |
| 149 | const block = match[1] || '' |
| 150 | const fontFace = parseCssFontFamily(parseCssValue(block, 'font-family')) |
| 151 | const src = parseCssValue(block, 'src') |
| 152 | if (!fontFace || !src) continue |
| 153 | const weight = parseCssFontWeight(parseCssValue(block, 'font-weight')) |
| 154 | const style = parseCssFontStyle(parseCssValue(block, 'font-style')) |
| 155 | const unicodeRange = parseCssValue(block, 'unicode-range') || undefined |
| 156 | for (const urlMatch of src.matchAll(/url\(\s*([^)]*?)\s*\)/gi)) { |
| 157 | const fontPath = resolveFontUrl(urlMatch[1] || '', htmlPath, projectDir) |
| 158 | if (!fontPath) continue |
| 159 | const key = `${normalizeFontFace(fontFace).toLocaleLowerCase()}::${weight}::${style}::${fontPath}::${unicodeRange || ''}` |
| 160 | faces.set(key, { fontFace, weight, style, fontPath, unicodeRange }) |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | return [...faces.values()] |
| 165 | } |
| 166 | |
| 167 | const unicodeRangeContains = (unicodeRange: string, codePoint: number): boolean => { |
| 168 | for (const token of unicodeRange.split(',')) { |
| 169 | const value = token.trim().replace(/^U\+/i, '') |
| 170 | if (!value) continue |
| 171 | const rangeMatch = value.match(/^([0-9a-f?]+)(?:-([0-9a-f]+))?$/i) |
| 172 | if (!rangeMatch) continue |
| 173 | const start = rangeMatch[1].replace(/\?/g, '0') |
| 174 | const end = rangeMatch[2] || rangeMatch[1].replace(/\?/g, 'f') |
| 175 | const lower = Number.parseInt(start, 16) |
| 176 | const upper = Number.parseInt(end, 16) |
| 177 | if (Number.isFinite(lower) && Number.isFinite(upper) && codePoint >= lower && codePoint <= upper) { |
| 178 | return true |
| 179 | } |
| 180 | } |
| 181 | return false |
| 182 | } |
| 183 | |
| 184 | const faceContainsUsage = (face: ProjectFontFace, usage: FontUsage): boolean => { |
| 185 | if (!face.unicodeRange || usage.characters.size === 0) return true |
| 186 | for (const character of usage.characters) { |
| 187 | if (unicodeRangeContains(face.unicodeRange, character.codePointAt(0) || 0)) return true |
| 188 | } |
| 189 | return false |
| 190 | } |
| 191 | |
| 192 | const expectedWeightFor = (style: EmbeddedFontStyle): number => |
| 193 | style === 'bold' || style === 'boldItalic' ? 700 : 400 |
| 194 | |
| 195 | const sourceStyleFor = (style: EmbeddedFontStyle): 'normal' | 'italic' => |
| 196 | style === 'italic' || style === 'boldItalic' ? 'italic' : 'normal' |
| 197 | |
| 198 | const resolveFontSources = ( |
| 199 | usage: FontUsage, |
| 200 | faces: ProjectFontFace[] |
| 201 | ): { weight: number; paths: string[] } | null => { |
| 202 | const normalizedFace = normalizeFontFace(usage.fontFace).toLocaleLowerCase() |
| 203 | const style = sourceStyleFor(usage.style) |
| 204 | const candidates = faces.filter( |
| 205 | (face) => |
| 206 | normalizeFontFace(face.fontFace).toLocaleLowerCase() === normalizedFace && |
| 207 | face.style === style |
| 208 | ) |
| 209 | if (candidates.length === 0) return null |
| 210 | |
| 211 | const expectedWeight = expectedWeightFor(usage.style) |
| 212 | const closestWeight = candidates.reduce( |
| 213 | (closest, face) => |
| 214 | Math.abs(face.weight - expectedWeight) < Math.abs(closest - expectedWeight) |
| 215 | ? face.weight |
| 216 | : closest, |
| 217 | candidates[0].weight |
| 218 | ) |
| 219 | const matchingFaces = candidates.filter((face) => face.weight === closestWeight) |
| 220 | const paths = matchingFaces |
| 221 | .filter((face) => faceContainsUsage(face, usage)) |
| 222 | .map((face) => face.fontPath) |
| 223 | |
| 224 | return paths.length > 0 ? { weight: closestWeight, paths: [...new Set(paths)].sort() } : null |
| 225 | } |
| 226 | |
| 227 | // ─── TTF merge ────────────────────────────────────────────────────── |
| 228 | |
| 229 | const uint8ToArrayBuffer = (buffer: Uint8Array): ArrayBuffer => { |
| 230 | const arrayBuffer = new ArrayBuffer(buffer.byteLength) |
| 231 | new Uint8Array(arrayBuffer).set(buffer) |
| 232 | return arrayBuffer |
| 233 | } |
| 234 | |
| 235 | const detectSfntType = (buffer: Uint8Array): 'ttf' | 'otf' => |
| 236 | buffer[0] === 0x4f && buffer[1] === 0x54 && buffer[2] === 0x54 && buffer[3] === 0x4f |
| 237 | ? 'otf' |
| 238 | : 'ttf' |
| 239 | |
| 240 | const readWoff2SubsetAsTtfObject = async (woff2Path: string): Promise<any> => { |
| 241 | const woff2Data = new Uint8Array(readFileSync(woff2Path)) |
| 242 | const sfntData = await decompress(woff2Data) |
| 243 | const font = createFont(uint8ToArrayBuffer(sfntData), { |
| 244 | type: detectSfntType(sfntData), |
| 245 | subset: [], |
| 246 | hinting: false, |
| 247 | compound2simple: true |
| 248 | }) |
| 249 | return font.get() |
| 250 | } |
| 251 | |
| 252 | const glyphUnicodeCodes = (glyph: any): number[] => |
| 253 | Array.isArray(glyph?.unicode) |
| 254 | ? Array.from( |
| 255 | new Set<number>( |
| 256 | glyph.unicode.filter((code: unknown): code is number => |
| 257 | typeof code === 'number' && Number.isFinite(code) |
| 258 | ) |
| 259 | ) |
| 260 | ) |
| 261 | : [] |
| 262 | |
| 263 | const glyphSortKey = (glyph: any): number => { |
| 264 | const codes = glyphUnicodeCodes(glyph) |
| 265 | return codes.length > 0 ? Math.min(...codes) : Number.MAX_SAFE_INTEGER |
| 266 | } |
| 267 | |
| 268 | const isEmbeddable = (ttf: any): boolean => { |
| 269 | const flags = Number(ttf?.['OS/2']?.fsType || 0) |
| 270 | return (flags & (RESTRICTED_EMBEDDING | BITMAP_ONLY_EMBEDDING)) === 0 |
| 271 | } |
| 272 | |
| 273 | const normalizeMergedFontMetadata = ( |
| 274 | ttf: any, |
| 275 | familyName: string, |
| 276 | styleName: string, |
| 277 | weight: number, |
| 278 | italic: boolean |
| 279 | ): void => { |
| 280 | const postScriptStyle = styleName.replace(/\s+/g, '') |
| 281 | ttf.name = { |
| 282 | ...(ttf.name || {}), |
| 283 | fontFamily: familyName, |
| 284 | fontSubFamily: styleName, |
| 285 | preferredFamily: familyName, |
| 286 | preferredSubFamily: styleName, |
| 287 | compatibleFull: `${familyName} ${styleName}`, |
| 288 | uniqueSubFamily: `${familyName}-${postScriptStyle}`, |
| 289 | fullName: `${familyName} ${styleName}`, |
| 290 | postScriptName: `${familyName.replace(/\s+/g, '')}-${postScriptStyle}` |
| 291 | } |
| 292 | if (ttf['OS/2']) { |
| 293 | ttf['OS/2'].usWeightClass = weight |
| 294 | const currentSelection = Number(ttf['OS/2'].fsSelection || 0) |
| 295 | ttf['OS/2'].fsSelection = |
| 296 | (currentSelection & ~(0x0001 | 0x0020)) | (italic ? 0x0001 : 0) | (weight >= 700 ? 0x0020 : 0) |
| 297 | const unicodes = ttf.glyf |
| 298 | .flatMap((glyph: any) => (Array.isArray(glyph.unicode) ? glyph.unicode : [])) |
| 299 | .filter((code: number) => Number.isFinite(code)) |
| 300 | if (unicodes.length > 0) { |
| 301 | ttf['OS/2'].usFirstCharIndex = Math.min(...unicodes) |
| 302 | ttf['OS/2'].usLastCharIndex = Math.max(...unicodes) |
| 303 | } |
| 304 | } |
| 305 | if (ttf.head) { |
| 306 | ttf.head.macStyle = (weight >= 700 ? 1 : 0) | (italic ? 2 : 0) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | const isCjkFontFace = (fontFace: string): boolean => |
| 311 | /(?:Noto Sans SC|Noto Serif SC|Ma Shan Zheng|Source Han|PingFang|Microsoft YaHei|SimHei|SimSun)/i.test(fontFace) |
| 312 | |
| 313 | const swapUtf16ByteOrder = (buffer: Uint8Array, start: number, byteLength: number): void => { |
| 314 | for (let index = start; index < start + byteLength; index += 2) { |
| 315 | const first = buffer[index] |
| 316 | buffer[index] = buffer[index + 1] |
| 317 | buffer[index + 1] = first |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | const readEotNames = (buffer: Uint8Array): string[] | null => { |
| 322 | if (buffer.byteLength < EOT_HEADER_SIZE) return null |
| 323 | const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) |
| 324 | if (view.getUint32(0, true) !== buffer.byteLength || view.getUint16(34, true) !== 0x504c) return null |
| 325 | let offset = EOT_HEADER_SIZE |
| 326 | const names: string[] = [] |
| 327 | for (let index = 0; index < 4; index += 1) { |
| 328 | if (offset + 4 > buffer.byteLength) return null |
| 329 | const byteLength = view.getUint16(offset, true) |
| 330 | const textStart = offset + 2 |
| 331 | const textEnd = textStart + byteLength |
| 332 | if (byteLength % 2 !== 0 || textEnd + 2 > buffer.byteLength) return null |
| 333 | names.push(new TextDecoder('utf-16le').decode(buffer.slice(textStart, textEnd))) |
| 334 | offset = textEnd + 2 |
| 335 | } |
| 336 | if (offset + 2 > buffer.byteLength) return null |
| 337 | const rootStringSize = view.getUint16(offset, true) |
| 338 | const fontOffset = offset + 2 + rootStringSize |
| 339 | const fontDataSize = view.getUint32(4, true) |
| 340 | if (fontOffset + fontDataSize !== buffer.byteLength) return null |
| 341 | return names |
| 342 | } |
| 343 | |
| 344 | const encodeUtf16Le = (value: string): Uint8Array => { |
| 345 | const output = new Uint8Array(value.length * 2) |
| 346 | for (let index = 0; index < value.length; index += 1) { |
| 347 | const codeUnit = value.charCodeAt(index) |
| 348 | output[index * 2] = codeUnit & 0xff |
| 349 | output[index * 2 + 1] = codeUnit >>> 8 |
| 350 | } |
| 351 | return output |
| 352 | } |
| 353 | |
| 354 | const readEotNameRanges = (buffer: Uint8Array): Array<{ start: number; byteLength: number }> | null => { |
| 355 | if (buffer.byteLength < EOT_HEADER_SIZE) return null |
| 356 | const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) |
| 357 | if (view.getUint32(0, true) !== buffer.byteLength || view.getUint16(34, true) !== 0x504c) return null |
| 358 | let offset = EOT_HEADER_SIZE |
| 359 | const ranges: Array<{ start: number; byteLength: number }> = [] |
| 360 | for (let index = 0; index < 4; index += 1) { |
| 361 | if (offset + 4 > buffer.byteLength) return null |
| 362 | const byteLength = view.getUint16(offset, true) |
| 363 | const start = offset + 2 |
| 364 | const end = start + byteLength |
| 365 | if (byteLength % 2 !== 0 || end + 2 > buffer.byteLength) return null |
| 366 | ranges.push({ start, byteLength }) |
| 367 | offset = end + 2 |
| 368 | } |
| 369 | return ranges |
| 370 | } |
| 371 | |
| 372 | const replaceEotStyleName = (eotBuffer: Uint8Array, styleName: string): Uint8Array | null => { |
| 373 | const nameRanges = readEotNameRanges(eotBuffer) |
| 374 | if (!nameRanges) return null |
| 375 | const styleRange = nameRanges[1] |
| 376 | const styleBytes = encodeUtf16Le(styleName) |
| 377 | if (styleRange.byteLength === styleBytes.byteLength) { |
| 378 | const normalized = new Uint8Array(eotBuffer) |
| 379 | normalized.set(styleBytes, styleRange.start) |
| 380 | return normalized |
| 381 | } |
| 382 | |
| 383 | // fonteditor-core serializes name ID 2 as fontSubFamily, but its EOT writer |
| 384 | // reads the non-existent fontStyle alias. Rebuild only that EOT field so the |
| 385 | // header's StyleName remains consistent with the embedded OpenType font. |
| 386 | const styleSizeOffset = styleRange.start - 2 |
| 387 | const sourceAfterStyle = styleRange.start + styleRange.byteLength |
| 388 | const resized = new Uint8Array(eotBuffer.byteLength - styleRange.byteLength + styleBytes.byteLength) |
| 389 | resized.set(eotBuffer.slice(0, styleSizeOffset), 0) |
| 390 | const view = new DataView(resized.buffer) |
| 391 | view.setUint16(styleSizeOffset, styleBytes.byteLength, true) |
| 392 | resized.set(styleBytes, styleSizeOffset + 2) |
| 393 | resized.set(eotBuffer.slice(sourceAfterStyle), styleSizeOffset + 2 + styleBytes.byteLength) |
| 394 | view.setUint32(0, resized.byteLength, true) |
| 395 | return resized |
| 396 | } |
| 397 | |
| 398 | const normalizeEotPayload = ( |
| 399 | eotBuffer: Uint8Array, |
| 400 | familyName: string, |
| 401 | styleName: string, |
| 402 | italic: boolean |
| 403 | ): Uint8Array | null => { |
| 404 | const normalized = new Uint8Array(eotBuffer) |
| 405 | if (normalized.byteLength < EOT_HEADER_SIZE) return null |
| 406 | const view = new DataView(normalized.buffer, normalized.byteOffset, normalized.byteLength) |
| 407 | if (view.getUint16(34, true) !== 0x504c) return null |
| 408 | |
| 409 | const nameRanges = readEotNameRanges(normalized) |
| 410 | if (!nameRanges) return null |
| 411 | for (const { start: textStart, byteLength } of nameRanges) { |
| 412 | // fonteditor-core writes EOT name strings as UTF-16BE. EOT requires |
| 413 | // UTF-16LE, which Office uses when matching the font reference. |
| 414 | swapUtf16ByteOrder(normalized, textStart, byteLength) |
| 415 | } |
| 416 | const withStyleName = replaceEotStyleName(normalized, styleName) |
| 417 | if (!withStyleName) return null |
| 418 | withStyleName[26] = isCjkFontFace(familyName) ? 0x86 : 0x01 |
| 419 | withStyleName[27] = italic ? 1 : 0 |
| 420 | const names = readEotNames(withStyleName) |
| 421 | return names && normalizeFontFace(names[0]) === normalizeFontFace(familyName) && names[1] === styleName |
| 422 | ? withStyleName |
| 423 | : null |
| 424 | } |
| 425 | |
| 426 | const mergeTtfObjects = ( |
| 427 | ttfObjects: any[], |
| 428 | familyName: string, |
| 429 | styleName: string, |
| 430 | weight: number, |
| 431 | italic: boolean, |
| 432 | payloadFormat: EmbeddedPayloadFormat |
| 433 | ): Uint8Array | null => { |
| 434 | const base = ttfObjects[0] |
| 435 | const notdef = base.glyf?.[0] || { name: '.notdef', unicode: [] } |
| 436 | const glyphs: any[] = [notdef] |
| 437 | const seenCodes = new Set<number>() |
| 438 | const seenNames = new Set<string>() |
| 439 | |
| 440 | for (const ttf of ttfObjects) { |
| 441 | for (const glyph of ttf.glyf || []) { |
| 442 | if (glyph.name === '.notdef' || glyph.name === '.null' || glyph.name === 'nonmarkingreturn') { |
| 443 | continue |
| 444 | } |
| 445 | const codes = glyphUnicodeCodes(glyph) |
| 446 | const name = String(glyph.name || '') |
| 447 | if (codes.length > 0) { |
| 448 | if (codes.some((code) => seenCodes.has(code))) continue |
| 449 | glyph.unicode = codes.sort((a, b) => a - b) |
| 450 | codes.forEach((code) => seenCodes.add(code)) |
| 451 | } else if (name) { |
| 452 | if (seenNames.has(name)) continue |
| 453 | seenNames.add(name) |
| 454 | } else { |
| 455 | continue |
| 456 | } |
| 457 | glyphs.push(glyph) |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | base.glyf = [glyphs[0], ...glyphs.slice(1).sort((a, b) => glyphSortKey(a) - glyphSortKey(b))] |
| 462 | normalizeMergedFontMetadata(base, familyName, styleName, weight, italic) |
| 463 | |
| 464 | const writer = new fonteditorCore.TTFWriter() |
| 465 | try { |
| 466 | const ttfBuffer = new Uint8Array(writer.write(base)) |
| 467 | if (payloadFormat === 'ttf') { |
| 468 | return ttfBuffer |
| 469 | } |
| 470 | const eotBuffer = new Uint8Array(fonteditorCore.ttf2eot(uint8ToArrayBuffer(ttfBuffer))) |
| 471 | const normalizedEot = normalizeEotPayload(eotBuffer, familyName, styleName, italic) |
| 472 | const eotNames = normalizedEot ? readEotNames(normalizedEot) : null |
| 473 | if (!normalizedEot || !eotNames || normalizeFontFace(eotNames[0]) !== normalizeFontFace(familyName)) { |
| 474 | return null |
| 475 | } |
| 476 | return normalizedEot |
| 477 | } finally { |
| 478 | writer.dispose() |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | export const collectEmbeddedFonts = async ( |
| 483 | projectDir: string, |
| 484 | slides: HtmlToPptxSlide[], |
| 485 | options: { |
| 486 | mode?: 'auto' | 'always' | 'never' |
| 487 | payloadFormat?: EmbeddedPayloadFormat |
| 488 | maxTotalBytes?: number |
| 489 | pageHtmlPaths?: string[] |
| 490 | } = {} |
| 491 | ): Promise<HtmlToPptxEmbeddedFont[]> => { |
| 492 | const mode = options.mode || 'auto' |
| 493 | // 默认裸 TTF(sfnt)载荷:实测 PowerPoint for Mac 16.78 在 fntdata 为 EOT 容器时 |
| 494 | // 会忽略 b="1"(加粗不渲染,暗像素仅 100%),去嵌入或换裸 TTF 后加粗恢复 |
| 495 | // (约 131%)。EOT 仅按需显式传入以兼容旧链路。 |
| 496 | const payloadFormat = options.payloadFormat || 'ttf' |
| 497 | if (mode === 'never') { |
| 498 | log.info('[font-embed] disabled by export option') |
| 499 | return [] |
| 500 | } |
| 501 | if (slides.length === 0) return [] |
| 502 | |
| 503 | const usages = collectUsedFontUsages(slides) |
| 504 | log.info('[font-embed] actual text font usages', { |
| 505 | usages: usages.map((usage) => ({ |
| 506 | fontFace: usage.fontFace, |
| 507 | style: usage.style, |
| 508 | characterCount: usage.characters.size |
| 509 | })) |
| 510 | }) |
| 511 | if (usages.length === 0) return [] |
| 512 | |
| 513 | const faces = collectProjectFontFaces(projectDir, options.pageHtmlPaths || []) |
| 514 | log.info('[font-embed] local @font-face declarations', { |
| 515 | count: faces.length, |
| 516 | families: [...new Set(faces.map((face) => face.fontFace))] |
| 517 | }) |
| 518 | if (faces.length === 0) return [] |
| 519 | |
| 520 | const embeddedFonts: HtmlToPptxEmbeddedFont[] = [] |
| 521 | for (const usage of usages) { |
| 522 | const source = resolveFontSources(usage, faces) |
| 523 | if (!source) { |
| 524 | log.info('[font-embed] skip (no matching local font face)', { |
| 525 | fontFace: usage.fontFace, |
| 526 | style: usage.style |
| 527 | }) |
| 528 | continue |
| 529 | } |
| 530 | |
| 531 | const ttfObjects: any[] = [] |
| 532 | for (const woff2Path of source.paths) { |
| 533 | try { |
| 534 | const ttf = await readWoff2SubsetAsTtfObject(woff2Path) |
| 535 | if (!isEmbeddable(ttf)) { |
| 536 | log.warn('[font-embed] skip font restricted by fsType', { |
| 537 | fontFace: usage.fontFace, |
| 538 | style: usage.style, |
| 539 | path: woff2Path |
| 540 | }) |
| 541 | continue |
| 542 | } |
| 543 | ttfObjects.push(ttf) |
| 544 | } catch (error) { |
| 545 | log.warn('[font-embed] failed to read woff2 source', { |
| 546 | path: woff2Path, |
| 547 | error: String(error) |
| 548 | }) |
| 549 | } |
| 550 | } |
| 551 | if (ttfObjects.length === 0) continue |
| 552 | |
| 553 | try { |
| 554 | const isBold = usage.style === 'bold' || usage.style === 'boldItalic' |
| 555 | const isItalic = usage.style === 'italic' || usage.style === 'boldItalic' |
| 556 | const payload = mergeTtfObjects( |
| 557 | ttfObjects, |
| 558 | usage.fontFace, |
| 559 | isBold ? (isItalic ? 'Bold Italic' : 'Bold') : isItalic ? 'Italic' : 'Regular', |
| 560 | source.weight, |
| 561 | isItalic, |
| 562 | payloadFormat |
| 563 | ) |
| 564 | if (!payload) { |
| 565 | log.warn('[font-embed] generated font payload failed structural validation', { |
| 566 | fontFace: usage.fontFace, |
| 567 | style: usage.style, |
| 568 | payloadFormat |
| 569 | }) |
| 570 | continue |
| 571 | } |
| 572 | embeddedFonts.push({ fontFace: usage.fontFace, style: usage.style, ttfBuffer: payload }) |
| 573 | log.info('[font-embed] embedded actual font usage', { |
| 574 | fontFace: usage.fontFace, |
| 575 | style: usage.style, |
| 576 | files: source.paths.length, |
| 577 | sizeKb: Math.round(payload.byteLength / 1024) |
| 578 | }) |
| 579 | } catch (error) { |
| 580 | log.warn('[font-embed] failed to merge font', { |
| 581 | fontFace: usage.fontFace, |
| 582 | style: usage.style, |
| 583 | error: String(error) |
| 584 | }) |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | if (mode === 'auto') { |
| 589 | const maxTotalBytes = options.maxTotalBytes ?? 20 * 1024 * 1024 |
| 590 | const totalBytes = embeddedFonts.reduce((sum, item) => sum + item.ttfBuffer.byteLength, 0) |
| 591 | if (totalBytes > maxTotalBytes) { |
| 592 | log.warn('[font-embed] skipped embedded fonts in auto mode because payload is too large', { |
| 593 | totalBytes, |
| 594 | maxTotalBytes, |
| 595 | count: embeddedFonts.length |
| 596 | }) |
| 597 | return [] |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | return embeddedFonts |
| 602 | } |
| 603 |