Use TTF fonts throughout the UI; also add some more functions to app extension API

This commit is contained in:
James Babcock committed 2026-08-19 19:35:24 -07:00
1 parent 5abbe2a405
commit 96842ceb23
82 files changed
+2666 -288

No files matched your search

+42 -45
View File
@@ -1,5 +1,5 @@
import { knownFolders } from "@nativescript/core";
import { getStringSetting, onSettingsStoreChanged } from "~/native/settings-store";
import type { GrayImage } from "./image";
export type Glyph = {
encoding: number;
@@ -9,17 +9,35 @@ export type Glyph = {
bbxX: number;
bbxY: number;
bitmapRows: number[];
/**
* Antialiased coverage, bbxWidth*bbxHeight 4bpp levels (0..15) row-major.
* When present the glyph is an AA raster (e.g. a TTF render; see
* ttf-font.ts) and bitmapRows is unused/empty; when absent the glyph is
* 1bpp via bitmapRows.
*/
coverage?: Uint8Array;
/** Exact (fractional) advance in pixels; dwidthX is its integer stand-in. */
advance?: number;
};
let nextFontFingerprintId = 1;
/**
* Allocate a process-local font fingerprint id. Shared by every font class
* that participates in PlacedGlyph fingerprints (BdfFont, TtfFont) so ids
* never collide across font kinds.
*/
export function allocateFontFingerprintId(): number {
return nextFontFingerprintId++;
}
export class BdfFont {
/**
* Process-local identity for content fingerprints (fonts are cached
* singletons, so two draws with the same id + encoding are the same glyph
* bitmap). Only meaningful within one JS context; never persist it.
*/
readonly fingerprintId = nextFontFingerprintId++;
readonly fingerprintId = allocateFontFingerprintId();
/**
* Stable cross-context identity for the on-glasses glyph atlas (the
* embedded font name). Worker threads and the main thread must agree on
@@ -165,6 +183,25 @@ export class BdfFont {
}
return width;
}
/**
* Draw text with integer advances, recording each glyph as a deferred draw
* on the image (UiFont contract; y is the top of the line).
*/
drawText(image: GrayImage, x: number, y: number, text: string, value: number): void {
let cursorX = x;
for (const char of text) {
if (char === "\n") {
cursorX = x;
y += this.lineHeight;
continue;
}
const glyph = this.getGlyph(char.codePointAt(0) ?? 32);
if (!glyph) continue;
image.drawGlyph(this, glyph, cursorX, y, value);
cursorX += glyph.dwidthX;
}
}
}
const embeddedFonts = {
@@ -211,46 +248,6 @@ export function getFont(font: EmbeddedFontName): BdfFont {
return loadEmbeddedFont(font);
}
// User-selectable UI typeface. Only the small (12px) font has an alternative,
// since TerminusV ships no larger sizes; medium/large stay Terminus. The
// storage key and values are re-used by the settings UI in dashboard-settings.
export const UI_FONT_SETTING_KEY = "display.uiFont";
export const UI_FONT_VALUES = ["terminus", "terminusv"] as const;
export type UiFontChoice = (typeof UI_FONT_VALUES)[number];
const SMALL_FONT_FOR_CHOICE: Record<UiFontChoice, EmbeddedFontName> = {
terminus: "terminus12",
terminusv: "terminusv12",
};
// Reading the setting hits a JNI bridge, and getDefaultSmallFont() is called
// once per menu item per paint, so cache the resolved choice and invalidate it
// when the setting changes (in any isolate).
let cachedSmallFontChoice: UiFontChoice | null = null;
let smallFontListenerInstalled = false;
function currentSmallFontName(): EmbeddedFontName {
if (!smallFontListenerInstalled) {
onSettingsStoreChanged((key) => {
if (key === UI_FONT_SETTING_KEY) cachedSmallFontChoice = null;
});
smallFontListenerInstalled = true;
}
if (cachedSmallFontChoice === null) {
const raw = getStringSetting(UI_FONT_SETTING_KEY, "terminus");
cachedSmallFontChoice = (UI_FONT_VALUES as readonly string[]).includes(raw)
? (raw as UiFontChoice)
: "terminus";
}
return SMALL_FONT_FOR_CHOICE[cachedSmallFontChoice];
}
export function getDefaultSmallFont(): BdfFont {
return getFont(currentSmallFontName());
}
export function getDefaultMediumFont(): BdfFont {
return getFont("terminus16");
}
export function getDefaultLargeFont(): BdfFont {
return getFont("terminus24");
}
// NOTE: the default UI font getters (getDefaultSmallFont & co.) live in
// ./ui-fonts, which resolves the user's font settings to a BdfFont or
// TtfFont. This module stays a pure BDF loader.
+2 -4
View File
@@ -21,7 +21,7 @@ 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, type FwTextFont, type PlacedFwText, type PlacedFwTextGlyph } from "./image";
import { GrayImage, grayToNibble, type FwTextFont, type PlacedFwText, type PlacedFwTextGlyph } from "./image";
declare const com: any;
@@ -83,9 +83,7 @@ function inMode15UncertainRange(cp: number): boolean {
}
/** The 4bpp level an 8-bit value packs to (BmpUtil's GRAY_TO_NIBBLE). */
function quantNibble(value: number): number {
return value <= 0 ? 0 : Math.min(15, (value + 8) >> 4);
}
const quantNibble = grayToNibble;
export class EvenHubFont implements FwTextFont {
/** One builtin firmware font today; see FwTextFont. */
+123 -42
View File
@@ -19,8 +19,8 @@
* their pixels are baked into the submitted frame either way, so exclusion
* only means "no wire savings for this draw".
*/
import { BdfFont, Glyph } from "./bdffont";
import { GrayImage, type DeferredDraw, type PlacedFwText, type PlacedImage } from "./image";
import { Glyph } from "./bdffont";
import { GrayImage, type DeferredDraw, type GlyphFont, type PlacedFwText, type PlacedImage } from "./image";
declare const com: any;
@@ -36,7 +36,7 @@ type FontWireState = {
registered: Set<number>;
};
const fontStates = new Map<BdfFont, FontWireState>();
const fontStates = new Map<GlyphFont, FontWireState>();
/**
* Java-side image id per source image object, or null for images that can't
@@ -46,7 +46,7 @@ const fontStates = new Map<BdfFont, FontWireState>();
*/
const imageIds = new WeakMap<GrayImage, number | null>();
function fontWireState(font: BdfFont): FontWireState | null {
function fontWireState(font: GlyphFont): FontWireState | null {
if (!global.isAndroid || !font.atlasKey) return null;
if (font.lineHeight <= 0 || font.lineHeight > 255) return null;
let state = fontStates.get(font);
@@ -67,7 +67,7 @@ function fontWireState(font: BdfFont): FontWireState | null {
* line cell (the cached image is bbxWidth x lineHeight with the ink placed at
* inkTop), and metrics that fit the wire fields.
*/
function representableGlyph(font: BdfFont, glyph: Glyph): boolean {
function representableGlyph(font: GlyphFont, glyph: Glyph): boolean {
if (glyph.encoding < 32 || glyph.encoding > 127) return false;
if (glyph.bbxWidth <= 0 || glyph.bbxWidth > 255) return false;
if (glyph.bbxHeight <= 0 || glyph.bbxHeight > 255) return false;
@@ -155,7 +155,7 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
if (!global.isAndroid || draws.length === 0) return null;
// Pass 1: resolve ids, register unseen rasters, size the buffer.
let registration: Map<FontWireState, { font: BdfFont; glyphs: Glyph[] }> | null = null;
let registration: Map<FontWireState, RegistrationGroup> | null = null;
const fwRunOk = new Map<PlacedFwText, boolean>();
let bytes = 0;
for (const placed of draws) {
@@ -169,10 +169,10 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
registration ??= new Map();
let group = registration.get(state);
if (!group) {
group = { font: placed.font, glyphs: [] };
group = { font: placed.font, glyphs: [], aaGlyphs: [] };
registration.set(state, group);
}
group.glyphs.push(placed.glyph);
(placed.glyph.coverage ? group.aaGlyphs : group.glyphs).push(placed.glyph);
} else if (placed.kind === "image") {
if (!inRange16(placed.x) || !inRange16(placed.y)) continue;
if (imageId(placed) !== null) bytes += IMAGE_RECORD_BYTES;
@@ -183,7 +183,10 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
}
}
if (registration) {
com.faceclaw.app.GlyphAtlas.register(buildRegistrationBuffer(registration));
const plainBuffer = buildRegistrationBuffer(registration);
if (plainBuffer) com.faceclaw.app.GlyphAtlas.register(plainBuffer);
const aaBuffer = buildAaRegistrationBuffer(registration);
if (aaBuffer) com.faceclaw.app.GlyphAtlas.registerAa(aaBuffer);
}
if (bytes === 0) return null;
@@ -230,51 +233,129 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
return out.buffer;
}
type RegistrationGroup = {
font: GlyphFont;
/** 1bpp (BDF) glyphs for GlyphAtlas.register. */
glyphs: Glyph[];
/** Antialiased (coverage) glyphs for GlyphAtlas.registerAa. */
aaGlyphs: Glyph[];
};
/**
* Registration buffer: per font group
* 1bpp registration buffer: per font group
* [keyLen u8][key utf8][cellHeight u8][count u16]
* then per glyph
* [encoding u32][bbxX s8][inkTop u8][width u8][inkHeight u8]
* [inkHeight x row u32] (bit (ceil(width/8)*8 - 1 - col) = ink)
* mirroring GlyphAtlas.register on the Java side.
* mirroring GlyphAtlas.register on the Java side. Null when the groups hold
* no 1bpp glyphs.
*/
function buildRegistrationBuffer(
registration: Map<FontWireState, { font: BdfFont; glyphs: Glyph[] }>,
): ArrayBuffer {
let total = 0;
const encodedKeys = new Map<FontWireState, Uint8Array>();
registration.forEach((group, state) => {
const keyBytes = utf8Encode(group.font.atlasKey ?? "");
encodedKeys.set(state, keyBytes);
total += 1 + keyBytes.length + 1 + 2;
for (const glyph of group.glyphs) {
total += 8 + 4 * glyph.bbxHeight;
}
});
const buffer = new ArrayBuffer(total);
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
let offset = 0;
registration.forEach((group, state) => {
const keyBytes = encodedKeys.get(state)!;
view.setUint8(offset, keyBytes.length);
bytes.set(keyBytes, offset + 1);
offset += 1 + keyBytes.length;
view.setUint8(offset, state.cellHeight);
view.setUint16(offset + 1, group.glyphs.length, true);
offset += 3;
for (const glyph of group.glyphs) {
const inkTop = group.font.ascent - (glyph.bbxHeight + glyph.bbxY);
view.setUint32(offset, glyph.encoding, true);
view.setInt8(offset + 4, glyph.bbxX);
view.setUint8(offset + 5, inkTop);
view.setUint8(offset + 6, glyph.bbxWidth);
view.setUint8(offset + 7, glyph.bbxHeight);
registration: Map<FontWireState, RegistrationGroup>,
): ArrayBuffer | null {
return buildGroupedBuffer(
registration,
(group) => group.glyphs,
(glyph) => 8 + 4 * glyph.bbxHeight,
(view, _bytes, offset, group, glyph) => {
writeGlyphHeader(view, offset, group, glyph);
offset += 8;
for (let row = 0; row < glyph.bbxHeight; row++) {
view.setUint32(offset, (glyph.bitmapRows[row] ?? 0) >>> 0, true);
offset += 4;
}
return offset;
},
);
}
/**
* AA registration buffer: same group framing, but each glyph record carries
* packed 4bpp coverage instead of 1bpp rows:
* [encoding u32][bbxX s8][inkTop u8][width u8][inkHeight u8]
* [inkHeight x ceil(width/2) packed bytes, high nibble = left pixel]
* mirroring GlyphAtlas.registerAa. Null when the groups hold no AA glyphs.
*/
function buildAaRegistrationBuffer(
registration: Map<FontWireState, RegistrationGroup>,
): ArrayBuffer | null {
return buildGroupedBuffer(
registration,
(group) => group.aaGlyphs,
(glyph) => 8 + ((glyph.bbxWidth + 1) >> 1) * glyph.bbxHeight,
(view, bytes, offset, group, glyph) => {
writeGlyphHeader(view, offset, group, glyph);
offset += 8;
const coverage = glyph.coverage!;
const stride = (glyph.bbxWidth + 1) >> 1;
for (let row = 0; row < glyph.bbxHeight; row++) {
const rowStart = row * glyph.bbxWidth;
for (let b = 0; b < stride; b++) {
const col = b * 2;
const high = coverage[rowStart + col]! & 0x0f;
const low = col + 1 < glyph.bbxWidth ? coverage[rowStart + col + 1]! & 0x0f : 0;
bytes[offset++] = (high << 4) | low;
}
}
return offset;
},
);
}
/** [encoding u32][bbxX s8][inkTop u8][width u8][inkHeight u8], shared by both formats. */
function writeGlyphHeader(view: DataView, offset: number, group: RegistrationGroup, glyph: Glyph): void {
const inkTop = group.font.ascent - (glyph.bbxHeight + glyph.bbxY);
view.setUint32(offset, glyph.encoding, true);
view.setInt8(offset + 4, glyph.bbxX);
view.setUint8(offset + 5, inkTop);
view.setUint8(offset + 6, glyph.bbxWidth);
view.setUint8(offset + 7, glyph.bbxHeight);
}
/** Shared group-framing walk for the two registration formats. */
function buildGroupedBuffer(
registration: Map<FontWireState, RegistrationGroup>,
glyphsOf: (group: RegistrationGroup) => Glyph[],
glyphBytes: (glyph: Glyph) => number,
writeGlyph: (
view: DataView,
bytes: Uint8Array,
offset: number,
group: RegistrationGroup,
glyph: Glyph,
) => number,
): ArrayBuffer | null {
let total = 0;
let glyphCount = 0;
const encodedKeys = new Map<FontWireState, Uint8Array>();
registration.forEach((group, state) => {
const glyphs = glyphsOf(group);
if (glyphs.length === 0) return;
const keyBytes = utf8Encode(group.font.atlasKey ?? "");
encodedKeys.set(state, keyBytes);
total += 1 + keyBytes.length + 1 + 2;
glyphCount += glyphs.length;
for (const glyph of glyphs) {
total += glyphBytes(glyph);
}
});
if (glyphCount === 0) return null;
const buffer = new ArrayBuffer(total);
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
let offset = 0;
registration.forEach((group, state) => {
const glyphs = glyphsOf(group);
if (glyphs.length === 0) return;
const keyBytes = encodedKeys.get(state)!;
view.setUint8(offset, keyBytes.length);
bytes.set(keyBytes, offset + 1);
offset += 1 + keyBytes.length;
view.setUint8(offset, state.cellHeight);
view.setUint16(offset + 1, glyphs.length, true);
offset += 3;
for (const glyph of glyphs) {
offset = writeGlyph(view, bytes, offset, group, glyph);
}
});
return buffer;
+65 -20
View File
@@ -1,4 +1,4 @@
import { BdfFont, Glyph } from "./bdffont";
import { Glyph } from "./bdffont";
import { wrapText } from "./textwrap";
export const G2_LENS_WIDTH = 640;
@@ -21,6 +21,35 @@ export function imageFromAsciiArt(lines: readonly string[], value = 255): GrayIm
return image;
}
/**
* The font behind a deferred glyph draw: what rasterizeGlyph and the wire
* encoder (glyph-wire.ts) need from it. BdfFont satisfies this directly;
* TtfFont (ttf-font.ts) implements it for antialiased glyphs. Structural so
* image.ts needs no imports beyond BdfFont's Glyph shape.
*/
export interface GlyphFont {
/** Process-local identity for content fingerprints (see BdfFont). */
readonly fingerprintId: number;
/** Stable cross-context identity for the on-glasses glyph atlas, or null. */
readonly atlasKey: string | null;
readonly ascent: number;
readonly lineHeight: number;
}
/**
* A general text-drawing font: what GrayImage.drawText and the shared list
* UI helpers need. BdfFont (bitmap) and TtfFont (antialiased) both implement
* it. The font owns text layout (drawText) because layout rules differ by
* kind — BDF advances are integers, TTF advances are fractional and kerned.
*/
export interface UiFont extends GlyphFont {
readonly descent: number;
measureText(text: string): number;
getGlyph(codePoint: number): Glyph | undefined;
hasGlyph(codePoint: number): boolean;
drawText(image: GrayImage, x: number, y: number, text: string, value: number): void;
}
/**
* One deferred glyph draw. Text drawn through drawGlyph/drawText/
* drawTextWrapped is retained here rather than baked into the pixel buffer,
@@ -30,7 +59,7 @@ export function imageFromAsciiArt(lines: readonly string[], value = 255): GrayIm
*/
export type PlacedGlyph = {
kind: "glyph";
font: BdfFont;
font: GlyphFont;
glyph: Glyph;
x: number;
y: number;
@@ -202,23 +231,12 @@ export class GrayImage {
}
}
drawText(font: BdfFont, x: number, y: number, text: string, value: number): void {
let cursorX = x;
for (const char of text) {
if (char === "\n") {
cursorX = x;
y += font.lineHeight;
continue;
}
const glyph = font.getGlyph(char.codePointAt(0) ?? 32);
if (!glyph) continue;
this.drawGlyph(font, glyph, cursorX, y, value);
cursorX += glyph.dwidthX;
}
drawText(font: UiFont, x: number, y: number, text: string, value: number): void {
font.drawText(this, x, y, text, value);
}
drawTextWrapped({font, x, y, width, text, value }: {
font: BdfFont;
font: UiFont;
x: number;
y: number;
width: number;
@@ -227,7 +245,7 @@ export class GrayImage {
}): void {
const lines = wrapText(font, text, width);
for (let i = 0; i < lines.length; i++) {
this.drawText(font, x, y + i * font.lineHeight, lines[i]!, value);
font.drawText(this, x, y + i * font.lineHeight, lines[i]!, value);
}
}
@@ -414,7 +432,7 @@ export class GrayImage {
* (rendered above all raster pixels) instead of being baked into the
* buffer.
*/
drawGlyph(font: BdfFont, glyph: Glyph, x: number, y: number, value: number): void {
drawGlyph(font: GlyphFont, glyph: Glyph, x: number, y: number, value: number): void {
this.drawList.push({ kind: "glyph", font, glyph, x, y, value: clampByte(value) });
}
@@ -492,10 +510,19 @@ export class GrayImage {
}
}
/** Bake one BDF glyph into an image's pixel buffer (y is the top of the line). */
/**
* The 4bpp level an 8-bit gray value packs to (BmpUtil's GRAY_TO_NIBBLE).
* Shared by every phone-side bake that must match the firmware's draw-time
* LUT math bit-for-bit (AA glyphs here, EvenHubFont's mode-15 bakes).
*/
export function grayToNibble(value: number): number {
return value <= 0 ? 0 : Math.min(15, (value + 8) >> 4);
}
/** Bake one glyph into an image's pixel buffer (y is the top of the line). */
function rasterizeGlyph(
target: GrayImage,
font: BdfFont,
font: GlyphFont,
glyph: Glyph,
x: number,
y: number,
@@ -504,6 +531,24 @@ function rasterizeGlyph(
const baselineY = y + font.ascent;
const top = baselineY - (glyph.bbxHeight + glyph.bbxY);
const left = x + glyph.bbxX;
if (glyph.coverage) {
// Firmware-exact AA shading (see EvenHubFont.drawGlyph): the CFW draws
// cached glyphs through a LUT mapping source nibble n to n*top/15
// (integer), skipping only n == 0. Writing 16*level makes the composite
// quantize (grayToNibble) back to exactly that level, so the
// texture-cache planner's pixel checks — and the shadow after an
// on-glasses mode-14 draw — match this bake bit-for-bit.
const top4 = grayToNibble(value);
for (let row = 0; row < glyph.bbxHeight; row++) {
const rowStart = row * glyph.bbxWidth;
for (let col = 0; col < glyph.bbxWidth; col++) {
const nibble = glyph.coverage[rowStart + col]!;
if (nibble === 0) continue;
target.setPixel(left + col, top + row, Math.floor((nibble * top4) / 15) * 16);
}
}
return;
}
const rowBitWidth = ((glyph.bbxWidth + 7) >> 3) << 3;
for (let row = 0; row < glyph.bbxHeight; row++) {
const bits = glyph.bitmapRows[row] ?? 0;
+227
View File
@@ -0,0 +1,227 @@
/**
* The app-internal installed-fonts directory: the set of TTF/OTF faces the
* font picker offers. Fonts arrive two ways — bundled faces copied out of the
* app assets on first listing (so the directory is the single source of
* truth), and user installs from the Files app ("Install" on a font file).
*
* Listing parses each file's name table for family/style (via the Java
* FontFileRenderer) and probes monospace-ness by comparing advances, both
* memoized per path for the session.
*/
import { File, Folder, knownFolders, path as nsPath } from "@nativescript/core";
import { canLoadFontFile, fontFileDisplayName, isFontFile } from "../native/font-files";
declare const com: any;
declare const java: any;
declare const global: any;
/** Bundled faces (under app assets fonts/ttf/) preinstalled on first listing. */
const PREINSTALLED_FONT_FILES = [
"Inter_18pt-Light.ttf",
"Inter_18pt-Regular.ttf",
"Inter_18pt-Bold.ttf",
"Montserrat-Light.ttf",
"Montserrat-Regular.ttf",
"Montserrat-Bold.ttf",
"Roboto-Light.ttf",
"Roboto-Regular.ttf",
"Roboto-Bold.ttf",
"RobotoMono-Light.ttf",
"RobotoMono-Regular.ttf",
"RobotoMono-Bold.ttf",
] as const;
export type InstalledFont = {
/** Absolute path, loadable by TtfFont / FontFileRenderer. */
path: string;
fileName: string;
/** Family name from the font's name table (filename stem as fallback). */
family: string;
/** Style name from the name table ("Light", "Bold", ... ; "" = regular). */
style: string;
/** Sort key for weight pickers (400 = regular; +1000 marks italics last). */
weightOrder: number;
monospace: boolean;
};
/** The app-internal fonts directory (created on first use). */
export function installedFontsDir(): string {
return knownFolders.documents().getFolder("fonts").path;
}
/** Absolute path of an installed font by filename (existence not checked). */
export function installedFontPath(fileName: string): string {
return nsPath.join(installedFontsDir(), fileName);
}
let preinstalledEnsured = false;
/**
* Copy any missing bundled faces into the installed-fonts directory. Cheap
* after the first run (existence checks only), so callers can invoke it
* before every listing.
*/
export function ensurePreinstalledFonts(): void {
if (preinstalledEnsured || !global.isAndroid) return;
const assetsDir = nsPath.join(knownFolders.currentApp().path, "fonts/ttf");
for (const fileName of PREINSTALLED_FONT_FILES) {
const target = installedFontPath(fileName);
if (File.exists(target)) continue;
const source = nsPath.join(assetsDir, fileName);
if (!File.exists(source)) continue;
try {
copyFileBytes(source, target);
} catch (error) {
console.warn(`Could not preinstall font ${fileName}: ${error}`);
}
}
preinstalledEnsured = true;
}
/**
* Install a font file into the installed-fonts directory (overwriting a
* same-named file). Returns an error message for the UI, or null on success.
*/
export function installFontFile(sourcePath: string): string | null {
if (!global.isAndroid) return "Not available on this platform.";
if (!isFontFile(sourcePath)) return "Not a font file.";
if (!canLoadFontFile(sourcePath)) return "This file could not be loaded as a font.";
const fileName = sourcePath.slice(sourcePath.lastIndexOf("/") + 1);
try {
copyFileBytes(sourcePath, installedFontPath(fileName));
metadataCache.delete(installedFontPath(fileName));
return null;
} catch (error) {
console.warn(`installFontFile failed for ${sourcePath}: ${error}`);
return "Could not copy the font file.";
}
}
/** Whether a same-named font is already installed. */
export function isFontInstalled(sourcePath: string): boolean {
const fileName = sourcePath.slice(sourcePath.lastIndexOf("/") + 1);
return File.exists(installedFontPath(fileName));
}
/**
* All installed fonts (preinstalling bundled faces first), sorted by family
* then weight. Unloadable files are skipped.
*/
export function listInstalledFonts(): InstalledFont[] {
if (!global.isAndroid) return [];
ensurePreinstalledFonts();
const fonts: InstalledFont[] = [];
try {
for (const entity of Folder.fromPath(installedFontsDir()).getEntitiesSync()) {
if (!isFontFile(entity.name)) continue;
const meta = fontMetadata(entity.path, entity.name);
if (meta) fonts.push(meta);
}
} catch (error) {
console.warn(`listInstalledFonts failed: ${error}`);
}
fonts.sort((a, b) =>
a.family.localeCompare(b.family) || a.weightOrder - b.weightOrder || a.style.localeCompare(b.style),
);
return fonts;
}
/** The installed font with this filename, or null. */
export function getInstalledFont(fileName: string): InstalledFont | null {
const path = installedFontPath(fileName);
if (!File.exists(path)) return null;
return fontMetadata(path, fileName);
}
const metadataCache = new Map<string, InstalledFont | null>();
function fontMetadata(path: string, fileName: string): InstalledFont | null {
const cached = metadataCache.get(path);
if (cached !== undefined) return cached;
let meta: InstalledFont | null = null;
if (canLoadFontFile(path)) {
const name = fontFileDisplayName(path);
const family = name?.family || fileName.replace(/\.[^.]+$/, "");
const style = normalizeStyle(name?.style ?? "");
meta = {
path,
fileName,
family,
style,
weightOrder: styleWeightOrder(style),
monospace: isMonospaceFont(path),
};
}
metadataCache.set(path, meta);
return meta;
}
function normalizeStyle(style: string): string {
const trimmed = style.trim();
return trimmed === "Regular" ? "" : trimmed;
}
/** OS/2-style weight for a style name; italics sort after all uprights. */
function styleWeightOrder(style: string): number {
const withoutItalic = style.replace(/\bitalic\b/i, "").trim().toLowerCase();
const weights: Record<string, number> = {
"thin": 100,
"extralight": 200,
"extra light": 200,
"ultralight": 200,
"light": 300,
"": 400,
"regular": 400,
"normal": 400,
"medium": 500,
"semibold": 600,
"semi bold": 600,
"demibold": 600,
"bold": 700,
"extrabold": 800,
"extra bold": 800,
"black": 900,
"heavy": 900,
};
const weight = weights[withoutItalic] ?? 400;
return /\bitalic\b/i.test(style) ? weight + 1000 : weight;
}
/**
* Whether the face is monospace: narrow, wide, and punctuation glyphs all
* measure the same advance. Measured at a large size so fractional advance
* differences show up clearly.
*/
function isMonospaceFont(path: string): boolean {
try {
const measure = (text: string) =>
Number(com.faceclaw.app.FontFileRenderer.measureTextExact(path, text, 48));
const narrow = measure("i");
if (!(narrow > 0)) return false;
return (
Math.abs(measure("W") - narrow) < 0.5 &&
Math.abs(measure("m") - narrow) < 0.5 &&
Math.abs(measure(".") - narrow) < 0.5
);
} catch {
return false;
}
}
// Plain stream/channel copy: java.nio.file.Paths.get is a varargs overload
// set that NativeScript's JNI overload resolution picks wrong (it tries the
// (URI) form for a JS string), so java.nio.file is avoided here.
function copyFileBytes(source: string, target: string): void {
const input = new java.io.FileInputStream(source);
try {
const output = new java.io.FileOutputStream(target);
try {
const inChannel = input.getChannel();
output.getChannel().transferFrom(inChannel, 0, inChannel.size());
} finally {
output.close();
}
} finally {
input.close();
}
}
+15 -6
View File
@@ -1,4 +1,13 @@
import { BdfFont } from "./bdffont";
/**
* What wrapping and truncation need from a font. BdfFont and TtfFont both
* satisfy it structurally: getGlyph feeds per-codepoint advances for wrap
* measurement (integer and kerning-free, so slightly conservative for kerned
* faces), measureText feeds truncation.
*/
export interface WrapFont {
measureText(text: string): number;
getGlyph(codePoint: number): { dwidthX: number } | undefined;
}
export type WrapTextOptions = {
preserveLeadingWhitespace?: boolean;
@@ -34,7 +43,7 @@ export function findWrapOpportunities(text: string): number[] {
return offsets;
}
export function wrapText(font: BdfFont, text: string, targetWidth: number, opts: WrapTextOptions = {}): string[] {
export function wrapText(font: WrapFont, text: string, targetWidth: number, opts: WrapTextOptions = {}): string[] {
if (targetWidth <= 0) {
return text.length ? text.split("\n") : [""];
}
@@ -47,7 +56,7 @@ export function wrapText(font: BdfFont, text: string, targetWidth: number, opts:
return lines.length ? lines : [""];
}
export function truncateText(font: BdfFont, text: string, maxWidth: number): string {
export function truncateText(font: WrapFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
@@ -56,7 +65,7 @@ export function truncateText(font: BdfFont, text: string, maxWidth: number): str
return `${out}...`;
}
export function truncateLeft(font: BdfFont, text: string, maxWidth: number): string {
export function truncateLeft(font: WrapFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`...${out}`) > maxWidth) {
@@ -65,7 +74,7 @@ export function truncateLeft(font: BdfFont, text: string, maxWidth: number): str
return `...${out}`;
}
function wrapParagraph(font: BdfFont, paragraph: string, targetWidth: number, opts: WrapTextOptions): string[] {
function wrapParagraph(font: WrapFont, paragraph: string, targetWidth: number, opts: WrapTextOptions): string[] {
if (paragraph.length === 0) {
return [""];
}
@@ -109,7 +118,7 @@ function wrapParagraph(font: BdfFont, paragraph: string, targetWidth: number, op
return lines.length ? lines : [""];
}
function measureOffsets(font: BdfFont, text: string): Map<number, number> {
function measureOffsets(font: WrapFont, text: string): Map<number, number> {
const widths = new Map<number, number>();
let total = 0;
widths.set(0, 0);
+285
View File
@@ -0,0 +1,285 @@
/**
* TTF/OTF fonts for on-glasses UI text, rendered per-codepoint through the
* Java FontFileRenderer (Android minikin/HarfBuzz: real shaping, kerning,
* antialiasing) and cached as 4bpp coverage rasters that ride the
* texture-cache glyph pipeline (CFW mode 14; see
* notes/texture-cache-display-list-design.md and graphics/glyph-wire.ts).
*
* Layout model: the font owns drawText (like EvenHubFont) because TTF
* advances are fractional and kerned, which GrayImage.drawText's integer
* cursor walk can't express. Each glyph is recorded as a deferred
* PlacedGlyph at an integer pen x, so the wire path and the phone-side bake
* (rasterizeGlyph's coverage branch, firmware-LUT-exact) see identical
* positions; the fractional pen accumulates across the line so rounding
* never drifts.
*
* Kerning uses memoized per-pair measurements (measure("ab") - a - b);
* ligatures are disabled Java-side so per-codepoint rasters plus pairwise
* kerning fully describe a line. Glyph rasters and advances come from one
* JNI render per (font, size, codepoint) per JS context, memoized forever.
*
* Cross-context determinism: worker threads and the main thread each build
* their own TtfFont, but the Java GlyphAtlas dedupes by atlasKey and treats
* rasters as immutable — safe because renderGlyphCell is deterministic for a
* given (path, size, gamma), all of which are baked into the atlasKey.
*/
import { knownFolders } from "@nativescript/core";
import { allocateFontFingerprintId, type Glyph } from "./bdffont";
import { GrayImage, grayToNibble, type GlyphFont } from "./image";
import { toUint8Array } from "../util/array-util";
declare const com: any;
declare const global: any;
/**
* Coverage-to-shade gamma (out = coverage^gamma). The G2 display response
* looks roughly linear, so 1.0; part of the atlas identity, so changing it
* per-font is safe but changing it per-draw is not possible.
*/
const DEFAULT_TTF_GAMMA = 1.0;
/** Fonts bundled as app assets (paths relative to the app folder). */
const BUNDLED_FONTS = {
"inter-light": "fonts/ttf/Inter_18pt-Light.ttf",
} as const;
export type BundledTtfName = keyof typeof BUNDLED_FONTS;
const loadedFonts = new Map<string, TtfFont | null>();
export class TtfFont implements GlyphFont {
readonly fingerprintId = allocateFontFingerprintId();
/** Stable cross-context atlas identity: face + size + gamma. */
readonly atlasKey: string;
readonly ascent: number;
readonly descent: number;
readonly lineHeight: number;
private readonly glyphCache = new Map<number, Glyph | null>();
private readonly kernCache = new Map<number, number>();
private constructor(
readonly path: string,
readonly sizePx: number,
readonly gamma: number,
ascent: number,
descent: number,
) {
this.ascent = ascent;
this.descent = descent;
this.lineHeight = ascent + descent;
const basename = path.slice(path.lastIndexOf("/") + 1).replace(/\.[^.]+$/, "");
this.atlasKey = `ttf:${basename}:${fnv32(path).toString(36)}@${sizePx}g${gamma}`;
}
/**
* Load (or return the memoized) font at a pixel size. Null when the font
* file is missing/unloadable or off-Android — callers fall back to a BDF
* face.
*/
static load(path: string, sizePx: number, gamma = DEFAULT_TTF_GAMMA): TtfFont | null {
const key = `${path}@${sizePx}g${gamma}`;
const cached = loadedFonts.get(key);
if (cached !== undefined) return cached;
let font: TtfFont | null = null;
if (global.isAndroid && sizePx > 0) {
try {
const raw = String(com.faceclaw.app.FontFileRenderer.getFontMetrics(path, sizePx) ?? "");
const parts = raw.split(" ").map((part) => parseInt(part, 10));
if (parts.length === 3 && parts.every((part) => Number.isFinite(part))) {
const [ascent, descent] = parts as [number, number, number];
if (ascent + descent > 0 && ascent + descent <= 255) {
font = new TtfFont(path, sizePx, gamma, ascent, descent);
}
}
} catch (error) {
console.warn(`TtfFont.load failed for ${path}: ${error}`);
}
}
loadedFonts.set(key, font);
return font;
}
/** A font bundled with the app, or null when it can't load. */
static bundled(name: BundledTtfName, sizePx: number, gamma = DEFAULT_TTF_GAMMA): TtfFont | null {
if (!global.isAndroid) return null;
return TtfFont.load(`${knownFolders.currentApp().path}/${BUNDLED_FONTS[name]}`, sizePx, gamma);
}
/**
* The codepoint's glyph (rendered and memoized on first use), or undefined
* when the render fails outright. Android renders SOMETHING for any
* codepoint the face covers or tofu otherwise, so undefined is rare.
* Ink-free glyphs (space) have bbxWidth 0 and no coverage.
*/
getGlyph(codePoint: number): Glyph | undefined {
let glyph = this.glyphCache.get(codePoint);
if (glyph === undefined) {
glyph = this.loadGlyph(codePoint);
this.glyphCache.set(codePoint, glyph);
}
return glyph ?? undefined;
}
hasGlyph(codePoint: number): boolean {
return this.getGlyph(codePoint) !== undefined;
}
/**
* Pixel width of the widest line in `text` (fractional; kerning included),
* for wrapping and truncation.
*/
measureText(text: string): number {
const cps = toCodePoints(text);
let width = 0;
let maxWidth = 0;
for (let i = 0; i < cps.length; i++) {
const cp = cps[i]!;
if (cp === 10) {
maxWidth = Math.max(maxWidth, width);
width = 0;
continue;
}
width += this.advanceOf(cp);
const next = cps[i + 1];
if (next !== undefined && next !== 10) {
width += this.kernBetween(cp, next);
}
}
return Math.max(maxWidth, width);
}
/**
* Draw text with the font's own (fractional, kerned) layout, recording
* each inked glyph as a deferred draw on the image. y is the top of the
* line (baseline at y + ascent), matching GrayImage.drawText.
*/
drawText(image: GrayImage, x: number, y: number, text: string, value: number): void {
const cps = toCodePoints(text);
let penX = x;
let lineY = y;
for (let i = 0; i < cps.length; i++) {
const cp = cps[i]!;
if (cp === 10) {
penX = x;
lineY += this.lineHeight;
continue;
}
const glyph = this.getGlyph(cp);
if (!glyph) continue;
if (glyph.coverage && glyph.bbxWidth > 0) {
image.drawGlyph(this, glyph, Math.round(penX), lineY, value);
}
penX += glyph.advance ?? glyph.dwidthX;
const next = cps[i + 1];
if (next !== undefined && next !== 10) {
penX += this.kernBetween(cp, next);
}
}
}
private advanceOf(codePoint: number): number {
const glyph = this.getGlyph(codePoint);
return glyph ? (glyph.advance ?? glyph.dwidthX) : 0;
}
/**
* Kerning between two adjacent codepoints: measure(ab) - a - b, memoized.
* One JNI measurement per distinct pair per JS context.
*/
private kernBetween(a: number, b: number): number {
const key = a * 0x200000 + b;
const cached = this.kernCache.get(key);
if (cached !== undefined) return cached;
let kern = 0;
try {
const pair = Number(
com.faceclaw.app.FontFileRenderer.measureTextExact(
this.path,
String.fromCodePoint(a) + String.fromCodePoint(b),
this.sizePx,
),
);
if (pair > 0) {
kern = pair - this.advanceOf(a) - this.advanceOf(b);
// A kern larger than the em size means the decomposition failed
// (e.g. the pair shaped into something we can't represent).
if (!Number.isFinite(kern) || Math.abs(kern) > this.sizePx) kern = 0;
}
} catch {
kern = 0;
}
this.kernCache.set(key, kern);
return kern;
}
/** Render + quantize one glyph via renderGlyphCell (see FontFileRenderer). */
private loadGlyph(codePoint: number): Glyph | null {
let bytes: Uint8Array;
try {
bytes = toUint8Array(
com.faceclaw.app.FontFileRenderer.renderGlyphCell(this.path, this.sizePx, codePoint, this.gamma),
);
} catch (error) {
console.warn(`renderGlyphCell failed for U+${codePoint.toString(16)}: ${error}`);
return null;
}
if (bytes.length < 10) return null;
const u16 = (offset: number) => bytes[offset]! | (bytes[offset + 1]! << 8);
const s16 = (offset: number) => {
const value = u16(offset);
return value & 0x8000 ? value - 0x10000 : value;
};
const advance = u16(0) / 64;
const bearingX = s16(2);
const inkTop = s16(4);
const width = u16(6);
const height = u16(8);
const base: Glyph = {
encoding: codePoint,
dwidthX: Math.round(advance),
bbxWidth: 0,
bbxHeight: 0,
bbxX: 0,
bbxY: 0,
bitmapRows: [],
advance,
};
if (width <= 0 || height <= 0 || bytes.length < 10 + width * height) {
return base; // ink-free (space) or malformed: advance-only
}
// Quantize 8-bit coverage to the 4bpp levels the composite packs to;
// faint fringe (< 8) quantizes to 0 = transparent.
const coverage = new Uint8Array(width * height);
let hasInk = false;
for (let i = 0; i < coverage.length; i++) {
const nibble = grayToNibble(bytes[10 + i]!);
coverage[i] = nibble;
if (nibble !== 0) hasInk = true;
}
if (!hasInk) return base;
return {
...base,
bbxWidth: width,
bbxHeight: height,
bbxX: bearingX,
bbxY: this.ascent - inkTop - height,
coverage,
};
}
}
function toCodePoints(text: string): number[] {
const cps: number[] = [];
for (const char of text) {
cps.push(char.codePointAt(0)!);
}
return cps;
}
function fnv32(text: string): number {
let hash = 2166136261;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
+192
View File
@@ -0,0 +1,192 @@
/**
* The user-selectable UI fonts: resolves the font settings (chosen in the
* Settings app's font picker) to concrete BdfFont/TtfFont instances for the
* three UI size roles, plus the terminal's separate monospace font.
*
* Selections are stored as one JSON value per setting so a font/size change
* is atomic. Resolution is cached per isolate and invalidated by the settings
* broadcast, matching the old getDefaultSmallFont pattern (these getters are
* called per menu row per paint).
*/
import { getFont, type BdfFont } from "./bdffont";
import type { UiFont } from "./image";
import { TtfFont } from "./ttf-font";
import { getInstalledFont, installedFontPath } from "./installed-fonts";
import { getStringSetting, onSettingsStoreChanged, setStringSetting } from "../native/settings-store";
export type BitmapFace = "terminus" | "terminusv";
export type UiFontSelection =
| { kind: "bitmap"; face: BitmapFace }
| { kind: "ttf"; file: string; size: number };
export const UI_FONT_SELECTION_KEY = "display.uiFont2";
export const TERMINAL_FONT_SELECTION_KEY = "terminal.font";
/** Pre-picker setting ("terminus" | "terminusv"), read as a migration default. */
const LEGACY_UI_FONT_KEY = "display.uiFont";
/** Line-height floors for the medium/large UI font roles (bitmap: 16/24px faces). */
const MEDIUM_MIN_LINE_HEIGHT = 20;
const LARGE_MIN_LINE_HEIGHT = 26;
/** How far size can grow hunting a line-height floor before giving up. */
const MAX_SIZE_GROWTH = 48;
export function parseFontSelection(raw: string): UiFontSelection | null {
try {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return null;
const sel = parsed as Record<string, unknown>;
if (sel.kind === "bitmap" && (sel.face === "terminus" || sel.face === "terminusv")) {
return { kind: "bitmap", face: sel.face };
}
if (
sel.kind === "ttf" &&
typeof sel.file === "string" && sel.file.length > 0 &&
typeof sel.size === "number" && Number.isFinite(sel.size) && sel.size >= 6 && sel.size <= 64
) {
return { kind: "ttf", file: sel.file, size: Math.round(sel.size) };
}
} catch {
// fall through
}
return null;
}
export function getUiFontSelection(): UiFontSelection {
const parsed = parseFontSelection(getStringSetting(UI_FONT_SELECTION_KEY, ""));
if (parsed) return parsed;
const legacy = getStringSetting(LEGACY_UI_FONT_KEY, "terminus");
return { kind: "bitmap", face: legacy === "terminusv" ? "terminusv" : "terminus" };
}
export function setUiFontSelection(selection: UiFontSelection): void {
setStringSetting(UI_FONT_SELECTION_KEY, JSON.stringify(selection));
}
export function getTerminalFontSelection(): UiFontSelection {
return parseFontSelection(getStringSetting(TERMINAL_FONT_SELECTION_KEY, "")) ?? { kind: "bitmap", face: "terminus" };
}
export function setTerminalFontSelection(selection: UiFontSelection): void {
setStringSetting(TERMINAL_FONT_SELECTION_KEY, JSON.stringify(selection));
}
/** Human label for a selection, e.g. "Inter Light 16" or "Terminus". */
export function fontSelectionLabel(selection: UiFontSelection): string {
if (selection.kind === "bitmap") {
return selection.face === "terminusv" ? "TerminusV" : "Terminus";
}
const installed = getInstalledFont(selection.file);
const face = installed ? `${installed.family}${installed.style ? ` ${installed.style}` : ""}` : selection.file;
return `${face} ${selection.size}`;
}
// --- Resolution, cached per isolate ---
const resolved = new Map<string, UiFont>();
let invalidationInstalled = false;
function cacheKey(role: string): string {
return role;
}
function installInvalidation(): void {
if (invalidationInstalled) return;
invalidationInstalled = true;
onSettingsStoreChanged((key) => {
if (key === UI_FONT_SELECTION_KEY || key === LEGACY_UI_FONT_KEY || key === TERMINAL_FONT_SELECTION_KEY) {
resolved.clear();
cachedTerminalConfig = null;
}
});
}
/**
* The selection's TTF at a size grown until lineHeight reaches minLineHeight
* (never shrunk below the picked size), or null when the file can't load.
*/
function resolveTtf(selection: UiFontSelection, minLineHeight = 0): TtfFont | null {
if (selection.kind !== "ttf") return null;
const path = installedFontPath(selection.file);
for (let size = selection.size; size <= selection.size + MAX_SIZE_GROWTH; size++) {
const font = TtfFont.load(path, size);
if (!font) return null;
if (font.lineHeight >= minLineHeight) return font;
}
return null;
}
function resolveRole(role: "small" | "medium" | "large"): UiFont {
installInvalidation();
const key = cacheKey(role);
const cached = resolved.get(key);
if (cached) return cached;
const selection = getUiFontSelection();
let font: UiFont | null = null;
if (selection.kind === "ttf") {
font =
role === "small"
? resolveTtf(selection)
: resolveTtf(selection, role === "medium" ? MEDIUM_MIN_LINE_HEIGHT : LARGE_MIN_LINE_HEIGHT);
}
if (!font) {
font = bitmapForRole(selection.kind === "bitmap" ? selection.face : "terminus", role);
}
resolved.set(key, font);
return font;
}
// Only the small (12px) bitmap font has a TerminusV alternative (it ships no
// larger sizes); bitmap medium/large stay Terminus, as before the picker.
function bitmapForRole(face: BitmapFace, role: "small" | "medium" | "large"): BdfFont {
if (role === "medium") return getFont("terminus16");
if (role === "large") return getFont("terminus24");
return getFont(face === "terminusv" ? "terminusv12" : "terminus12");
}
export function getDefaultSmallFont(): UiFont {
return resolveRole("small");
}
export function getDefaultMediumFont(): UiFont {
return resolveRole("medium");
}
export function getDefaultLargeFont(): UiFont {
return resolveRole("large");
}
// --- Terminal font ---
export type TerminalFontConfig = {
font: UiFont;
/** Integer cell pitch; TTF glyphs are drawn per-cell at col*cellWidth. */
cellWidth: number;
cellHeight: number;
};
let cachedTerminalConfig: TerminalFontConfig | null = null;
/**
* The terminal's font and cell geometry. Note grid dimensions are baked into
* each session's handshake, so callers capture this per window at open time;
* a settings change applies to windows opened afterwards.
*/
export function getTerminalFontConfig(): TerminalFontConfig {
installInvalidation();
if (cachedTerminalConfig) return cachedTerminalConfig;
const selection = getTerminalFontSelection();
let config: TerminalFontConfig | null = null;
if (selection.kind === "ttf") {
const font = resolveTtf(selection);
// Cell pitch from a digit's advance (all advances are equal in the
// monospace faces the picker offers), rounded to an integer grid.
const advance = font?.getGlyph(48)?.advance ?? 0;
if (font && advance > 0) {
config = { font, cellWidth: Math.max(1, Math.round(advance)), cellHeight: font.lineHeight };
}
}
if (!config) {
config = { font: getFont("terminus12"), cellWidth: 6, cellHeight: 12 };
}
cachedTerminalConfig = config;
return config;
}