diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md index 37567f19..f6e02ef6 100644 --- a/ACKNOWLEDGEMENTS.md +++ b/ACKNOWLEDGEMENTS.md @@ -15,3 +15,8 @@ The TerminusV proportional font is by ohnonot, derived from Terminus: https://framagit.org/ohnonot/terv-terc. It is also distributed under the SIL Open Font License; see app/fonts/terminusv/LICENSE. +The CJK font used for EvenHub compatibility is Source Han Sans SC Light by +Adobe: https://github.com/adobe-fonts/source-han-sans. It is distributed under +the SIL Open Font License, Version 1.1; see app/fonts/source-han-sans/LICENSE.txt. +Faceclaw includes the G2's serialized 20 px LVGL build of the font so phone-side +rendering matches the glasses. diff --git a/app/fonts/source-han-sans/LICENSE.txt b/app/fonts/source-han-sans/LICENSE.txt new file mode 100644 index 00000000..3ff0ccab --- /dev/null +++ b/app/fonts/source-han-sans/LICENSE.txt @@ -0,0 +1,96 @@ +Copyright 2014-2025 Adobe (http://www.adobe.com/), with Reserved Font +Name 'Source'. Source is a trademark of Adobe in the United States +and/or other countries. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin b/app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin new file mode 100644 index 00000000..ada45e43 Binary files /dev/null and b/app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin differ diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts index 495f1818..e7178142 100644 --- a/app/g2/firmware-builder.ts +++ b/app/g2/firmware-builder.ts @@ -1,17 +1,23 @@ /** * Builds the Faceclaw custom firmware on-device: downloads the stock Even * Realities G2 2.2.6.10 image from Even's CDN, verifies its SHA-256, applies - * the committed byte-patch set (cfw-patches.ts), verifies the patched SHA-256, - * and writes the result to app storage. + * the committed byte-patch set (cfw-patches.ts), extracts the stock EvenHub + * fonts for phone-side rendering, verifies the patched SHA-256, and writes the + * result to app storage. * * This mirrors g2flash/build_cfw.sh + patches/apply_patches.py exactly (same * URL, same pinned hashes, same offset/old/new patch semantics), so a * successful run reproduces the reviewed image byte-for-byte. It does NOT flash * anything — producing and verifying the image is the whole job here. */ -import { knownFolders } from "@nativescript/core"; +import { File, knownFolders } from "@nativescript/core"; import { CFW_PATCH_SET, FirmwarePatchOp } from "./firmware/cfw-patches"; +import { + EVENHUB_RUNTIME_FONT_FILENAME, + extractEvenHubFontAsset, + isEvenHubFontAsset, +} from "./firmware-fonts"; declare const com: any; @@ -22,6 +28,7 @@ const STOCK_OUTPUT_FILENAME = "g2_2.2.6.10.bin"; export type FirmwareProgress = | { phase: "downloading" } | { phase: "verifying-base" } + | { phase: "extracting-fonts" } | { phase: "patching"; applied: number; total: number } | { phase: "verifying-output" } | { phase: "writing" } @@ -35,6 +42,36 @@ export type BuiltFirmware = { export class FirmwareBuildError extends Error {} +/** True only when a complete, parseable runtime extraction is present. */ +export function hasExtractedEvenHubFonts(): boolean { + const path = `${knownFolders.documents().path}/${EVENHUB_RUNTIME_FONT_FILENAME}`; + if (!File.exists(path)) return false; + try { + return isEvenHubFontAsset(JSON.parse(File.fromPath(path).readTextSync())); + } catch { + return false; + } +} + +/** + * Download and verify the pinned stock image, then extract its EvenHub fonts. + * Used to repair an existing custom-firmware install without reflashing it. + */ +export async function downloadAndExtractEvenHubFonts( + onProgress?: (progress: FirmwareProgress) => void, +): Promise { + const report = (progress: FirmwareProgress) => { + try { + onProgress?.(progress); + } catch { + // progress reporting must never break extraction + } + }; + const base = await downloadAndVerifyBase(report); + report({ phase: "extracting-fonts" }); + persistEvenHubFonts(base); +} + /** * Download → verify → patch → verify → persist. Rejects with a * FirmwareBuildError carrying a human-readable message if any hash check or the @@ -53,6 +90,9 @@ export async function buildCustomFirmware( const base = await downloadAndVerifyBase(report); + report({ phase: "extracting-fonts" }); + persistEvenHubFonts(base); + const patched = applyPatches(new Uint8Array(base), CFW_PATCH_SET.patches, (applied, total) => report({ phase: "patching", applied, total }), ); @@ -127,6 +167,24 @@ async function downloadFirmware(): Promise { return response.arrayBuffer(); } +function persistEvenHubFonts(base: ArrayBuffer): void { + try { + const asset = extractEvenHubFontAsset(base); + let writeError: unknown; + knownFolders.documents().getFile(EVENHUB_RUNTIME_FONT_FILENAME).writeTextSync( + JSON.stringify(asset), + (error) => { + writeError = error; + }, + ); + if (writeError) throw writeError; + } catch (error) { + throw new FirmwareBuildError( + `The firmware was verified, but its EvenHub fonts could not be extracted: ${(error as Error)?.message ?? error}`, + ); + } +} + /** * Replay the committed patch set onto `base`, returning the patched bytes. Each * op writes `new` at `offset` after checking the bytes there equal `old`; an op diff --git a/app/g2/firmware-fonts.ts b/app/g2/firmware-fonts.ts new file mode 100644 index 00000000..5da89d1d --- /dev/null +++ b/app/g2/firmware-fonts.ts @@ -0,0 +1,304 @@ +/** + * Extract the G2's proprietary 20 px EvenHub fallback fonts from a verified + * stock EVENOTA image. The resulting compact JSON contains only glyph boxes + * and bitmap bytes; text advances and kerning continue to come from pretext. + * + * These fonts are deliberately generated at install time rather than bundled + * with Faceclaw because their redistribution terms are unclear. + */ + +export const EVENHUB_RUNTIME_FONT_FILENAME = "evenhub-firmware-20.json"; + +const MAIN_APP_NAME = "ota/s200_firmware_ota.bin"; +const MAIN_APP_LOAD_ADDRESS = 0x00438000; +const MAIN_APP_PREAMBLE_SIZE = 0x20; +const COMPONENT_HEADER_SIZE = 128; + +type FontSpec = { + descriptor: number; + lineHeight: number; + baseLine: number; +}; + +// Priority order is the stock EvenHub fallback chain (before the CJK font). +const FONT_SPECS: FontSpec[] = [ + { descriptor: 0x0077f414, lineHeight: 27, baseLine: 5 }, + { descriptor: 0x0077f428, lineHeight: 26, baseLine: 5 }, + { descriptor: 0x0077f374, lineHeight: 20, baseLine: 2 }, +]; + +type ExtractedGlyph = { + boxW: number; + boxH: number; + ofsX: number; + ofsY: number; + bytes: Uint8Array; +}; + +export type EvenHubFontAsset = { + lineHeight: number; + baseline: number; + glyphs: Record; + bitmapBase64: string; +}; + +/** Reject missing, truncated, or otherwise unusable persisted font assets. */ +export function isEvenHubFontAsset(value: unknown): value is EvenHubFontAsset { + const asset = value as Partial | null; + return !!asset && Number.isFinite(asset.lineHeight) && Number.isFinite(asset.baseline) && + !!asset.glyphs && typeof asset.glyphs === "object" && Object.keys(asset.glyphs).length >= 700 && + typeof asset.bitmapBase64 === "string" && asset.bitmapBase64.length > 0; +} + +/** Extract and serialize the fonts used for EvenHub background text. */ +export function extractEvenHubFontAsset(firmware: ArrayBuffer): EvenHubFontAsset { + const image = new FirmwareImage(firmware); + const mainApp = image.findComponent(MAIN_APP_NAME); + if (mainApp.payloadSize <= MAIN_APP_PREAMBLE_SIZE) { + throw new Error("the main firmware component is missing its application payload"); + } + + const app = new AddressedImage( + image, + mainApp.payloadOffset + MAIN_APP_PREAMBLE_SIZE, + mainApp.payloadSize - MAIN_APP_PREAMBLE_SIZE, + MAIN_APP_LOAD_ADDRESS, + ); + const merged = new Map(); + for (const spec of FONT_SPECS) extractFont(app, spec, merged); + + if (merged.size < 700) { + throw new Error(`firmware font extraction produced only ${merged.size} glyphs`); + } + + const records: EvenHubFontAsset["glyphs"] = {}; + const chunks: Uint8Array[] = []; + let bitmapSize = 0; + for (const [codePoint, glyph] of [...merged].sort((a, b) => a[0] - b[0])) { + records[String(codePoint)] = [ + glyph.boxW, + glyph.boxH, + glyph.ofsX, + glyph.ofsY, + bitmapSize, + glyph.bytes.length, + ]; + chunks.push(glyph.bytes); + bitmapSize += glyph.bytes.length; + } + + const bitmap = new Uint8Array(bitmapSize); + let offset = 0; + for (const chunk of chunks) { + bitmap.set(chunk, offset); + offset += chunk.length; + } + + const layout = FONT_SPECS[0]!; + return { + lineHeight: layout.lineHeight, + baseline: layout.lineHeight - layout.baseLine, + glyphs: records, + bitmapBase64: base64Encode(bitmap), + }; +} + +function extractFont(app: AddressedImage, spec: FontSpec, merged: Map): void { + const bitmapAddress = app.u32(spec.descriptor); + const glyphDescriptors = app.u32(spec.descriptor + 4); + const cmapAddress = app.u32(spec.descriptor + 8); + const packed = app.u16(spec.descriptor + 18); + const cmapCount = packed & 0x1ff; + const bitsPerPixel = (packed >> 9) & 0xf; + const bitmapFormat = (packed >> 14) & 0x3; + if (bitsPerPixel !== 4 || bitmapFormat !== 3 || cmapCount === 0) { + throw new Error( + `unsupported firmware font at 0x${spec.descriptor.toString(16)} ` + + `(bpp=${bitsPerPixel}, format=${bitmapFormat}, cmaps=${cmapCount})`, + ); + } + + const mapping = new Map(); + for (let index = 0; index < cmapCount; index++) { + resolveCmap(app, cmapAddress + index * 20, mapping); + } + + for (const [codePoint, glyphId] of mapping) { + if (glyphId <= 0 || merged.has(codePoint)) continue; + const descriptor = glyphDescriptors + glyphId * 16; + const bitmapIndex = app.u32(descriptor); + const boxW = app.u16(descriptor + 8); + const boxH = app.u16(descriptor + 10); + const ofsX = app.i16(descriptor + 12); + const ofsY = app.i16(descriptor + 14); + const length = boxW > 0 && boxH > 0 ? rowStride(boxW) * boxH : 0; + merged.set(codePoint, { + boxW, + boxH, + ofsX, + ofsY, + bytes: app.bytes(bitmapAddress + bitmapIndex, length), + }); + } +} + +function resolveCmap(app: AddressedImage, address: number, mapping: Map): void { + const rangeStart = app.u32(address); + const rangeLength = app.u16(address + 4); + const glyphIdStart = app.u16(address + 6); + const unicodeList = app.u32(address + 8); + const glyphIdOffsets = app.u32(address + 12); + const listLength = app.u16(address + 16); + const type = app.u8(address + 18); + + if (type === 2) { + for (let relative = 0; relative < rangeLength; relative++) { + mapping.set(rangeStart + relative, glyphIdStart + relative); + } + return; + } + + if (type === 0) { + for (let relative = 0; relative < rangeLength; relative++) { + const offset = app.u8(glyphIdOffsets + relative); + if (relative !== 0 && offset === 0) continue; + mapping.set(rangeStart + relative, glyphIdStart + offset); + } + return; + } + + if (type === 3 || type === 1) { + for (let index = 0; index < listLength; index++) { + const relative = app.u16(unicodeList + index * 2); + let offset = index; + if (glyphIdOffsets) { + offset = type === 1 ? app.u16(glyphIdOffsets + index * 2) : app.u8(glyphIdOffsets + index); + if (index !== 0 && offset === 0) continue; + } + mapping.set(rangeStart + relative, glyphIdStart + offset); + } + return; + } + + throw new Error(`unknown LVGL font cmap type ${type} at 0x${address.toString(16)}`); +} + +function rowStride(boxWidth: number): number { + // Even's LVGL pipeline aligns every row to a whole byte and adds a padding + // byte for even widths. + return Math.floor(boxWidth / 2) + 1; +} + +class FirmwareImage { + private readonly view: DataView; + private readonly data: Uint8Array; + + constructor(buffer: ArrayBuffer) { + this.view = new DataView(buffer); + this.data = new Uint8Array(buffer); + if (this.data.length < 0x40 || ascii(this.data, 0, 8) !== "EVENOTA\0") { + throw new Error("downloaded image is not an EVENOTA firmware container"); + } + } + + findComponent(name: string): { payloadOffset: number; payloadSize: number } { + const count = this.u32(8); + if (count <= 0 || count > 64) throw new Error(`invalid firmware component count ${count}`); + for (let index = 0; index < count; index++) { + const toc = 0x40 + index * 16; + const componentOffset = this.u32(toc + 4); + this.check(componentOffset, COMPONENT_HEADER_SIZE); + const payloadSize = this.u32(componentOffset + 8); + const filename = nulTerminatedAscii(this.data, componentOffset + 48, 80); + const payloadOffset = componentOffset + COMPONENT_HEADER_SIZE; + this.check(payloadOffset, payloadSize); + if (filename === name) return { payloadOffset, payloadSize }; + } + throw new Error(`firmware component ${name} was not found`); + } + + u32(offset: number): number { + this.check(offset, 4); + return this.view.getUint32(offset, true); + } + + bytes(offset: number, length: number): Uint8Array { + this.check(offset, length); + return this.data.slice(offset, offset + length); + } + + check(offset: number, length: number): void { + if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > this.data.length) { + throw new Error(`firmware range 0x${offset.toString(16)} + ${length} is out of bounds`); + } + } +} + +class AddressedImage { + constructor( + private readonly firmware: FirmwareImage, + private readonly fileOffset: number, + private readonly length: number, + private readonly loadAddress: number, + ) {} + + u8(address: number): number { + return this.bytes(address, 1)[0]!; + } + + u16(address: number): number { + const bytes = this.bytes(address, 2); + return bytes[0]! | (bytes[1]! << 8); + } + + i16(address: number): number { + const value = this.u16(address); + return value & 0x8000 ? value - 0x10000 : value; + } + + u32(address: number): number { + const bytes = this.bytes(address, 4); + return (bytes[0]! | (bytes[1]! << 8) | (bytes[2]! << 16) | (bytes[3]! << 24)) >>> 0; + } + + bytes(address: number, length: number): Uint8Array { + const relative = address - this.loadAddress; + if (relative < 0 || relative + length > this.length) { + throw new Error(`firmware address 0x${address.toString(16)} + ${length} is outside the main application`); + } + return this.firmware.bytes(this.fileOffset + relative, length); + } +} + +function ascii(bytes: Uint8Array, offset: number, length: number): string { + let value = ""; + for (let i = 0; i < length; i++) value += String.fromCharCode(bytes[offset + i] ?? 0); + return value; +} + +function nulTerminatedAscii(bytes: Uint8Array, offset: number, maxLength: number): string { + let value = ""; + for (let i = 0; i < maxLength; i++) { + const byte = bytes[offset + i] ?? 0; + if (byte === 0) break; + value += String.fromCharCode(byte); + } + return value; +} + +const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +function base64Encode(bytes: Uint8Array): string { + let result = ""; + for (let i = 0; i < bytes.length; i += 3) { + const a = bytes[i] ?? 0; + const b = bytes[i + 1] ?? 0; + const c = bytes[i + 2] ?? 0; + const packed = (a << 16) | (b << 8) | c; + result += BASE64_ALPHABET[(packed >> 18) & 63]; + result += BASE64_ALPHABET[(packed >> 12) & 63]; + result += i + 1 < bytes.length ? BASE64_ALPHABET[(packed >> 6) & 63] : "="; + result += i + 2 < bytes.length ? BASE64_ALPHABET[packed & 63] : "="; + } + return result; +} diff --git a/app/graphics/evenhub-font.ts b/app/graphics/evenhub-font.ts index 2046d4d7..e672a2e6 100644 --- a/app/graphics/evenhub-font.ts +++ b/app/graphics/evenhub-font.ts @@ -1,10 +1,12 @@ /** * Even's on-glasses 20px UI font, for the EvenHub compatibility layer. * - * Two halves, from two sources: - * - Glyph BITMAPS + boxes: preprocessed from the firmware's extracted LVGL - * fonts (latin + greek/cyrillic + emoji, merged in the EvenHub fallback - * order) into fonts/evenhub/evenhub-20.json by scripts/build-evenhub-font.mjs. + * Three pieces: + * - Latin + Greek/Cyrillic + emoji glyphs are extracted from the stock G2 + * firmware into app-private storage while Faceclaw prepares custom firmware. + * They are not distributed with Faceclaw. + * - The final fallback is the G2's serialized Source Han Sans SC Light font, + * which Faceclaw can bundle under the SIL Open Font License. * - Text SIZING / KERNING / WRAPPING: @evenrealities/pretext, whose advance * tables the bitmaps were validated against. Using pretext for measurement * means our line breaks match exactly where EvenHub apps (which measure @@ -15,11 +17,15 @@ * any anti-aliasing survives. Codepoints with no glyph are skipped silently, * matching stock firmware (no tofu boxes). */ -import { knownFolders } from "@nativescript/core"; +import { File, knownFolders } from "@nativescript/core"; import { getTextWidth } from "@evenrealities/pretext"; +import { EVENHUB_RUNTIME_FONT_FILENAME, isEvenHubFontAsset } from "../g2/firmware-fonts"; +import { toUint8Array } from "../util/array-util"; import { GrayImage } from "./image"; -const ASSET_PATH = "fonts/evenhub/evenhub-20.json"; +declare const com: any; + +const CJK_ASSET_PATH = "fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin"; /** [boxW, boxH, ofsX, ofsY, bitmapOffset, bitmapLen] */ type GlyphRecord = [number, number, number, number, number, number]; @@ -31,6 +37,11 @@ type FontAsset = { bitmapBase64: string; }; +type CjkGlyph = { + record: GlyphRecord; + bitmap: Uint8Array; +}; + const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64Decode(text: string): Uint8Array { @@ -55,6 +66,9 @@ export class EvenHubFont { readonly baseline: number; private readonly glyphs: Map; private readonly bitmap: Uint8Array; + private readonly cjkPath: string; + private readonly cjkBaseline: number; + private readonly cjkGlyphs = new Map(); private constructor(asset: FontAsset) { this.lineHeight = asset.lineHeight; @@ -64,20 +78,43 @@ export class EvenHubFont { for (const key of Object.keys(asset.glyphs)) { this.glyphs.set(Number(key), asset.glyphs[key]!); } + this.cjkPath = knownFolders.currentApp().getFile(CJK_ASSET_PATH).path; + const metrics = toUint8Array(com.faceclaw.app.LvglFontFile.getMetrics(this.cjkPath)); + if (metrics.length < 2) { + throw new Error("The bundled Source Han Sans font could not be loaded."); + } + this.cjkBaseline = metrics[1]!; } private static cached: EvenHubFont | null = null; static get(): EvenHubFont { if (!EvenHubFont.cached) { - const text = knownFolders.currentApp().getFile(ASSET_PATH).readTextSync(); - EvenHubFont.cached = new EvenHubFont(JSON.parse(text) as FontAsset); + const path = `${knownFolders.documents().path}/${EVENHUB_RUNTIME_FONT_FILENAME}`; + let asset: FontAsset | null = null; + if (File.exists(path)) { + try { + const parsed: unknown = JSON.parse(File.fromPath(path).readTextSync()); + if (!isEvenHubFontAsset(parsed)) throw new Error("invalid font asset structure"); + asset = parsed; + } catch (error) { + console.warn(`Could not load the extracted G2 fonts; using Source Han Sans only: ${error}`); + } + } else { + console.warn( + "The G2 fonts have not been extracted yet; using Source Han Sans only. " + + "Reinstall Faceclaw's custom firmware to prepare the exact fallback chain.", + ); + } + EvenHubFont.cached = new EvenHubFont( + asset ?? { lineHeight: 27, baseline: 22, glyphs: {}, bitmapBase64: "" }, + ); } return EvenHubFont.cached; } hasGlyph(codePoint: number): boolean { - return this.glyphs.has(codePoint); + return this.glyphs.has(codePoint) || this.getCjkGlyph(codePoint) !== null; } /** @@ -166,7 +203,12 @@ export class EvenHubFont { for (let i = 0; i < cps.length; i++) { const cp = cps[i]!; const glyph = this.glyphs.get(cp); - if (glyph) this.drawGlyph(image, glyph, penX, baselineY, value); + if (glyph) { + this.drawGlyph(image, glyph, this.bitmap, penX, baselineY, value); + } else { + const cjk = this.getCjkGlyph(cp); + if (cjk) this.drawGlyph(image, cjk.record, cjk.bitmap, penX, y + this.cjkBaseline, value); + } penX += this.advanceOf(cp, cps[i + 1] ?? 0); } } @@ -180,7 +222,36 @@ export class EvenHubFont { return lines.length; } - private drawGlyph(image: GrayImage, glyph: GlyphRecord, penX: number, baselineY: number, value: number): void { + private getCjkGlyph(codePoint: number): CjkGlyph | null { + const cached = this.cjkGlyphs.get(codePoint); + if (cached !== undefined) return cached; + const bytes = toUint8Array(com.faceclaw.app.LvglFontFile.getGlyph(this.cjkPath, codePoint)); + if (bytes.length < 8) { + this.cjkGlyphs.set(codePoint, null); + return null; + } + const u16 = (offset: number) => bytes[offset]! | (bytes[offset + 1]! << 8); + const i16 = (offset: number) => { + const value = u16(offset); + return value & 0x8000 ? value - 0x10000 : value; + }; + const bitmap = bytes.subarray(8); + const glyph: CjkGlyph = { + record: [u16(0), u16(2), i16(4), i16(6), 0, bitmap.length], + bitmap, + }; + this.cjkGlyphs.set(codePoint, glyph); + return glyph; + } + + private drawGlyph( + image: GrayImage, + glyph: GlyphRecord, + bitmap: Uint8Array, + penX: number, + baselineY: number, + value: number, + ): void { const [boxW, boxH, ofsX, ofsY, off, len] = glyph; if (boxW <= 0 || boxH <= 0 || len <= 0) return; const stride = Math.floor(boxW / 2) + 1; @@ -189,7 +260,7 @@ export class EvenHubFont { for (let row = 0; row < boxH; row++) { const rowStart = off + row * stride; for (let col = 0; col < boxW; col++) { - const byte = this.bitmap[rowStart + (col >> 1)] ?? 0; + const byte = bitmap[rowStart + (col >> 1)] ?? 0; const nibble = col % 2 === 0 ? byte >> 4 : byte & 0x0f; if (nibble === 0) continue; image.setPixel(left + col, top + row, Math.round((nibble / 15) * value)); diff --git a/app/phone-ui/onboarding-firmware-check-view-model.ts b/app/phone-ui/onboarding-firmware-check-view-model.ts index ee7f49a5..5bb4a580 100644 --- a/app/phone-ui/onboarding-firmware-check-view-model.ts +++ b/app/phone-ui/onboarding-firmware-check-view-model.ts @@ -2,11 +2,16 @@ import { Frame, Observable } from "@nativescript/core"; import { ensureBlePermissions } from "../g2/android-permissions"; import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses"; +import { + downloadAndExtractEvenHubFonts, + hasExtractedEvenHubFonts, + type FirmwareProgress, +} from "../g2/firmware-builder"; import { classifyOnboardingFirmware, FLASHABLE_STOCK_VERSION_TEXT } from "../g2/firmware-compat"; import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe"; import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state"; -type CheckPhase = "checking" | "custom" | "flashable" | "newer" | "error"; +type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer" | "error"; export class OnboardingFirmwareCheckViewModel extends Observable { private _phase: CheckPhase = "checking"; @@ -86,7 +91,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable { get secondaryVisibility(): "visible" | "collapse" { // Once the custom firmware is confirmed present, Finish is the only action. - return this._phase === "custom" ? "collapse" : "visible"; + return this._phase === "custom" || this._phase === "fonts" ? "collapse" : "visible"; } // --- button handlers ------------------------------------------------------- @@ -166,11 +171,11 @@ export class OnboardingFirmwareCheckViewModel extends Observable { this.busy = false; switch (kind) { case "custom": - this.setPhase("custom"); - this.headline = "Custom Firmware Detected"; - this.status = - `Your glasses already run Faceclaw's custom firmware${version ? ` (version ${version})` : ""}` + - `${capabilities ? `, extensions: ${capabilities}` : ""}. No flashing needed — you're all set.`; + if (!hasExtractedEvenHubFonts()) { + void this.extractFontsForCustomFirmware(version, capabilities); + break; + } + this.showCustomReady(version, capabilities, false); break; case "flashable": this.setPhase("flashable"); @@ -197,6 +202,52 @@ export class OnboardingFirmwareCheckViewModel extends Observable { } } + private async extractFontsForCustomFirmware(version: string, capabilities: string): Promise { + this.setPhase("fonts"); + this.headline = "Preparing G2 Fonts"; + this.busy = true; + this.status = + "Custom firmware is already installed, but its phone-side fonts are missing. " + + "Downloading the official firmware to extract them; your glasses will not be reflashed."; + try { + await downloadAndExtractEvenHubFonts((progress) => this.reportFontProgress(progress)); + this.showCustomReady(version, capabilities, true); + } catch (error) { + this.toError( + `Custom firmware is installed, but the G2 fonts could not be prepared: ${this.formatError(error)}`, + "Couldn't Prepare Fonts", + ); + } + } + + private reportFontProgress(progress: FirmwareProgress): void { + switch (progress.phase) { + case "downloading": + this.status = "Downloading the official firmware from Even's CDN..."; + break; + case "verifying-base": + this.status = "Verifying the downloaded firmware..."; + break; + case "extracting-fonts": + this.status = "Extracting the G2 fonts for EvenHub apps..."; + break; + default: + break; + } + } + + private showCustomReady(version: string, capabilities: string, extractedFonts: boolean): void { + this.busy = false; + this.setPhase("custom"); + this.headline = extractedFonts ? "Fonts Ready" : "Custom Firmware Detected"; + this.status = + `Your glasses already run Faceclaw's custom firmware${version ? ` (version ${version})` : ""}` + + `${capabilities ? `, extensions: ${capabilities}` : ""}. ` + + (extractedFonts + ? "The phone-side G2 fonts were extracted successfully. No flashing was needed — you're all set." + : "The phone-side G2 fonts are present. No flashing needed — you're all set."); + } + // --- terminal actions ------------------------------------------------------ private goToFlashing(): void { @@ -217,12 +268,12 @@ export class OnboardingFirmwareCheckViewModel extends Observable { }); } - private toError(message: string): void { + private toError(message: string, headline = "Couldn't Check Firmware"): void { this.disposeProbe(); this.busy = false; this.status = message; this.setPhase("error"); - this.headline = "Couldn't Check Firmware"; + this.headline = headline; } private setPhase(phase: CheckPhase): void { diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts index e49f56f7..81372657 100644 --- a/app/phone-ui/onboarding-flash-view-model.ts +++ b/app/phone-ui/onboarding-flash-view-model.ts @@ -351,6 +351,9 @@ export class OnboardingFlashViewModel extends Observable { case "verifying-base": this.status = "Verifying the downloaded firmware..."; break; + case "extracting-fonts": + this.status = "Extracting the glasses' fonts for EvenHub apps..."; + break; case "patching": this.status = `Applying patches (${progress.applied}/${progress.total})...`; break;