forked from Blendman974/faceclaw
Add font viewer
This commit is contained in:
1 parent
495cf0363a
commit
812c3f9b4a
7 files changed
+775
-1
No files matched your search
@@ -0,0 +1,411 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Rasterizes text using font files (TTF/OTF/TTC) via the Android text stack,
|
||||
* so shaping, kerning, and antialiasing are all delegated to
|
||||
* minikin/HarfBuzz. Output uses the same grayscale packet format as
|
||||
* ImageFileLoader ([widthLo, widthHi, heightLo, heightHi, pixels...], one
|
||||
* byte per pixel, row-major), which the TS side turns into a GrayImage and
|
||||
* the compositor later quantizes to the 4bpp the firmware wants.
|
||||
*
|
||||
* The gamma parameter maps antialiased coverage to output shade:
|
||||
* out = 255 * (coverage/255)^gamma. The G2 display response looks roughly
|
||||
* linear, so 1.0 is the expected default; the font previewer exposes it for
|
||||
* on-hardware comparison.
|
||||
*/
|
||||
public final class FontFileRenderer {
|
||||
private static final String TAG = "FontFileRenderer";
|
||||
private static final int TYPEFACE_CACHE_SIZE = 4;
|
||||
|
||||
/** Small LRU of loaded typefaces keyed by file path. */
|
||||
private static final Map<String, Typeface> typefaceCache =
|
||||
new LinkedHashMap<String, Typeface>(TYPEFACE_CACHE_SIZE, 0.75f, true) {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry<String, Typeface> eldest) {
|
||||
return size() > TYPEFACE_CACHE_SIZE;
|
||||
}
|
||||
};
|
||||
|
||||
private FontFileRenderer() {}
|
||||
|
||||
/**
|
||||
* Render one line of text with the given font file at the given pixel
|
||||
* size. The returned image is the font's full vertical extent (top to
|
||||
* bottom, taller than ascent+descent), plus any horizontal glyph
|
||||
* overhang beyond the advance width.
|
||||
*
|
||||
* Returns an empty array if the font cannot be loaded or the text
|
||||
* renders to nothing.
|
||||
*/
|
||||
public static byte[] renderText(String path, String text, float sizePx, double gamma) {
|
||||
if (path == null || text == null || sizePx <= 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
Typeface typeface = loadTypeface(path);
|
||||
if (typeface == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
try {
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
|
||||
paint.setTypeface(typeface);
|
||||
paint.setTextSize(sizePx);
|
||||
paint.setColor(Color.WHITE);
|
||||
|
||||
// top/bottom (the font's maximal extent) rather than
|
||||
// ascent/descent, so diacritics and swashes don't clip.
|
||||
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
|
||||
int ascent = -fm.top;
|
||||
int height = -fm.top + fm.bottom;
|
||||
// measureText gives advance width; italic/swash glyphs can paint
|
||||
// outside it, so pad by half an em on each side and trim after.
|
||||
int pad = (int) Math.ceil(sizePx / 2);
|
||||
int advance = (int) Math.ceil(paint.measureText(text));
|
||||
int width = advance + 2 * pad;
|
||||
if (width <= 0 || height <= 0 || width * height > 4_000_000) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
canvas.drawText(text, pad, ascent, paint);
|
||||
byte[] pixels = alpha8Pixels(bitmap, width, height);
|
||||
bitmap.recycle();
|
||||
|
||||
// Trim the horizontal padding down to the painted extent, but
|
||||
// keep at least the advance width so spacing stays truthful.
|
||||
int left = pad;
|
||||
int right = pad + advance;
|
||||
int[] painted = paintedColumnRange(pixels, width, height);
|
||||
if (painted != null) {
|
||||
left = Math.min(left, painted[0]);
|
||||
right = Math.max(right, painted[1] + 1);
|
||||
}
|
||||
int outWidth = Math.max(1, right - left);
|
||||
|
||||
byte[] lut = gammaLut(gamma);
|
||||
byte[] out = new byte[4 + outWidth * height];
|
||||
out[0] = (byte) (outWidth & 0xff);
|
||||
out[1] = (byte) ((outWidth >> 8) & 0xff);
|
||||
out[2] = (byte) (height & 0xff);
|
||||
out[3] = (byte) ((height >> 8) & 0xff);
|
||||
for (int y = 0; y < height; y++) {
|
||||
int srcRow = y * width;
|
||||
int dstRow = 4 + y * outWidth;
|
||||
for (int x = 0; x < outWidth; x++) {
|
||||
out[dstRow + x] = lut[pixels[srcRow + left + x] & 0xff];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch (Exception | OutOfMemoryError e) {
|
||||
Log.w(TAG, "text render failed: " + path, e);
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a multi-line block of text wrapped to maxWidth, with line
|
||||
* breaking delegated to StaticLayout (so it matches Android text
|
||||
* behavior, including breaking inside long words). Truncated with an
|
||||
* ellipsis past maxLines. Same packet format as renderText.
|
||||
*/
|
||||
public static byte[] renderWrapped(
|
||||
String path, String text, float sizePx, int maxWidth, double gamma, int maxLines) {
|
||||
if (path == null || text == null || sizePx <= 0 || maxWidth <= 0 || maxLines <= 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
Typeface typeface = loadTypeface(path);
|
||||
if (typeface == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
try {
|
||||
android.text.TextPaint paint =
|
||||
new android.text.TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
|
||||
paint.setTypeface(typeface);
|
||||
paint.setTextSize(sizePx);
|
||||
paint.setColor(Color.WHITE);
|
||||
paint.setHinting(Paint.HINTING_ON);
|
||||
|
||||
android.text.StaticLayout layout = android.text.StaticLayout.Builder
|
||||
.obtain(text, 0, text.length(), paint, maxWidth)
|
||||
.setAlignment(android.text.Layout.Alignment.ALIGN_NORMAL)
|
||||
.setIncludePad(false)
|
||||
.setMaxLines(maxLines)
|
||||
.setEllipsize(android.text.TextUtils.TruncateAt.END)
|
||||
.build();
|
||||
int height = Math.max(1, layout.getHeight());
|
||||
if ((long) maxWidth * height > 4_000_000L) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
Bitmap bitmap = Bitmap.createBitmap(maxWidth, height, Bitmap.Config.ALPHA_8);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
layout.draw(canvas);
|
||||
byte[] pixels = alpha8Pixels(bitmap, maxWidth, height);
|
||||
bitmap.recycle();
|
||||
|
||||
byte[] lut = gammaLut(gamma);
|
||||
byte[] out = new byte[4 + pixels.length];
|
||||
out[0] = (byte) (maxWidth & 0xff);
|
||||
out[1] = (byte) ((maxWidth >> 8) & 0xff);
|
||||
out[2] = (byte) (height & 0xff);
|
||||
out[3] = (byte) ((height >> 8) & 0xff);
|
||||
for (int i = 0; i < pixels.length; i++) {
|
||||
out[4 + i] = lut[pixels[i] & 0xff];
|
||||
}
|
||||
return out;
|
||||
} catch (Exception | OutOfMemoryError e) {
|
||||
Log.w(TAG, "wrapped render failed: " + path, e);
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Line metrics for a font at a pixel size, as "ascent descent lineGap"
|
||||
* (integers, pixels). Empty string if the font cannot be loaded.
|
||||
*/
|
||||
public static String getFontMetrics(String path, float sizePx) {
|
||||
Typeface typeface = loadTypeface(path);
|
||||
if (typeface == null || sizePx <= 0) {
|
||||
return "";
|
||||
}
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
paint.setTypeface(typeface);
|
||||
paint.setTextSize(sizePx);
|
||||
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
|
||||
int lineGap = fm.leading;
|
||||
return (-fm.ascent) + " " + fm.descent + " " + lineGap;
|
||||
}
|
||||
|
||||
/** Advance width in pixels of a line of text (rounded up). */
|
||||
public static int measureText(String path, String text, float sizePx) {
|
||||
Typeface typeface = loadTypeface(path);
|
||||
if (typeface == null || text == null || sizePx <= 0) {
|
||||
return 0;
|
||||
}
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
paint.setTypeface(typeface);
|
||||
paint.setTextSize(sizePx);
|
||||
return (int) Math.ceil(paint.measureText(text));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the font file loads at all (strictly validated on API 29+;
|
||||
* best-effort below that).
|
||||
*/
|
||||
public static boolean canLoadFont(String path) {
|
||||
return loadTypeface(path) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The font's family and style names from its 'name' table, as
|
||||
* "Family\nStyle" ("Style" may be empty). Falls back to "" when the
|
||||
* table cannot be parsed; callers should then use the filename.
|
||||
*/
|
||||
public static String getFontName(String path) {
|
||||
try {
|
||||
return parseNameTable(path);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "name table parse failed: " + path, e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized Typeface loadTypeface(String path) {
|
||||
if (path == null) {
|
||||
return null;
|
||||
}
|
||||
Typeface cached = typefaceCache.get(path);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
File file = new File(path);
|
||||
if (!file.isFile() || !file.canRead()) {
|
||||
return null;
|
||||
}
|
||||
Typeface typeface = null;
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
// Strict path: Font.Builder throws on files that are not
|
||||
// valid fonts, unlike createFromFile which silently falls
|
||||
// back to the default typeface.
|
||||
android.graphics.fonts.Font font =
|
||||
new android.graphics.fonts.Font.Builder(file).build();
|
||||
typeface = new Typeface.CustomFallbackBuilder(
|
||||
new android.graphics.fonts.FontFamily.Builder(font).build())
|
||||
.build();
|
||||
} else {
|
||||
typeface = Typeface.createFromFile(file);
|
||||
if (typeface == null || typeface.equals(Typeface.DEFAULT)) {
|
||||
typeface = null;
|
||||
}
|
||||
}
|
||||
} catch (Exception | LinkageError e) {
|
||||
Log.w(TAG, "font load failed: " + path + ": " + e);
|
||||
typeface = null;
|
||||
}
|
||||
if (typeface != null) {
|
||||
typefaceCache.put(path, typeface);
|
||||
}
|
||||
return typeface;
|
||||
}
|
||||
|
||||
/**
|
||||
* The coverage bytes of an ALPHA_8 bitmap as a tightly-packed
|
||||
* width*height array (copyPixelsToBuffer copies rowBytes*height, and the
|
||||
* row stride is not guaranteed to equal the width).
|
||||
*/
|
||||
private static byte[] alpha8Pixels(Bitmap bitmap, int width, int height) {
|
||||
int rowBytes = bitmap.getRowBytes();
|
||||
byte[] raw = new byte[rowBytes * height];
|
||||
bitmap.copyPixelsToBuffer(ByteBuffer.wrap(raw));
|
||||
if (rowBytes == width) {
|
||||
return raw;
|
||||
}
|
||||
byte[] pixels = new byte[width * height];
|
||||
for (int y = 0; y < height; y++) {
|
||||
System.arraycopy(raw, y * rowBytes, pixels, y * width, width);
|
||||
}
|
||||
return pixels;
|
||||
}
|
||||
|
||||
/** [first, last] painted (nonzero) column indexes, or null if blank. */
|
||||
private static int[] paintedColumnRange(byte[] pixels, int width, int height) {
|
||||
int first = width;
|
||||
int last = -1;
|
||||
for (int y = 0; y < height; y++) {
|
||||
int row = y * width;
|
||||
for (int x = 0; x < first; x++) {
|
||||
if (pixels[row + x] != 0) {
|
||||
first = x;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int x = width - 1; x > last; x--) {
|
||||
if (pixels[row + x] != 0) {
|
||||
last = x;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return last >= first ? new int[] { first, last } : null;
|
||||
}
|
||||
|
||||
private static byte[] gammaLut(double gamma) {
|
||||
byte[] lut = new byte[256];
|
||||
if (gamma <= 0) {
|
||||
gamma = 1.0;
|
||||
}
|
||||
for (int i = 0; i < 256; i++) {
|
||||
lut[i] = (byte) Math.max(0, Math.min(255,
|
||||
(int) Math.round(255.0 * Math.pow(i / 255.0, gamma))));
|
||||
}
|
||||
return lut;
|
||||
}
|
||||
|
||||
// --- Minimal 'name' table reader (TTF/OTF/TTC) for preview titles ---
|
||||
|
||||
private static String parseNameTable(String path) throws Exception {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(path, "r")) {
|
||||
long fileSize = raf.length();
|
||||
if (fileSize < 12) {
|
||||
return "";
|
||||
}
|
||||
long offset = 0;
|
||||
int tag = readU32(raf, 0);
|
||||
if (tag == 0x74746366) { // 'ttcf': use the first face
|
||||
if (readU32(raf, 8) < 1) {
|
||||
return "";
|
||||
}
|
||||
offset = readU32(raf, 12) & 0xffffffffL;
|
||||
}
|
||||
int numTables = readU16(raf, offset + 4);
|
||||
long nameOffset = -1;
|
||||
for (int i = 0; i < numTables; i++) {
|
||||
long rec = offset + 12 + i * 16L;
|
||||
if (rec + 16 > fileSize) {
|
||||
return "";
|
||||
}
|
||||
if (readU32(raf, rec) == 0x6e616d65) { // 'name'
|
||||
nameOffset = readU32(raf, rec + 8) & 0xffffffffL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (nameOffset < 0 || nameOffset + 6 > fileSize) {
|
||||
return "";
|
||||
}
|
||||
int count = readU16(raf, nameOffset + 2);
|
||||
long stringStorage = nameOffset + readU16(raf, nameOffset + 4);
|
||||
String family = null;
|
||||
String style = null;
|
||||
String preferredFamily = null;
|
||||
String preferredStyle = null;
|
||||
for (int i = 0; i < count; i++) {
|
||||
long rec = nameOffset + 6 + i * 12L;
|
||||
if (rec + 12 > fileSize) {
|
||||
break;
|
||||
}
|
||||
int platform = readU16(raf, rec);
|
||||
int nameId = readU16(raf, rec + 6);
|
||||
if (nameId != 1 && nameId != 2 && nameId != 16 && nameId != 17) {
|
||||
continue;
|
||||
}
|
||||
int length = readU16(raf, rec + 8);
|
||||
long strOffset = stringStorage + readU16(raf, rec + 10);
|
||||
if (strOffset + length > fileSize || length <= 0 || length > 512) {
|
||||
continue;
|
||||
}
|
||||
byte[] data = new byte[length];
|
||||
raf.seek(strOffset);
|
||||
raf.readFully(data);
|
||||
// Platform 0 (Unicode) and 3 (Windows) store UTF-16BE;
|
||||
// platform 1 (Mac) is close enough to Latin-1 for names.
|
||||
String value = platform == 1
|
||||
? new String(data, java.nio.charset.StandardCharsets.ISO_8859_1)
|
||||
: new String(data, java.nio.charset.StandardCharsets.UTF_16BE);
|
||||
value = value.trim();
|
||||
if (value.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (nameId == 1 && family == null) family = value;
|
||||
if (nameId == 2 && style == null) style = value;
|
||||
if (nameId == 16 && preferredFamily == null) preferredFamily = value;
|
||||
if (nameId == 17 && preferredStyle == null) preferredStyle = value;
|
||||
}
|
||||
String outFamily = preferredFamily != null ? preferredFamily : family;
|
||||
String outStyle = preferredStyle != null ? preferredStyle : style;
|
||||
if (outFamily == null) {
|
||||
return "";
|
||||
}
|
||||
return outFamily + "\n" + (outStyle == null ? "" : outStyle);
|
||||
}
|
||||
}
|
||||
|
||||
private static int readU16(RandomAccessFile raf, long offset) throws Exception {
|
||||
raf.seek(offset);
|
||||
byte[] b = new byte[2];
|
||||
raf.readFully(b);
|
||||
return ByteBuffer.wrap(b).order(ByteOrder.BIG_ENDIAN).getShort() & 0xffff;
|
||||
}
|
||||
|
||||
private static int readU32(RandomAccessFile raf, long offset) throws Exception {
|
||||
raf.seek(offset);
|
||||
byte[] b = new byte[4];
|
||||
raf.readFully(b);
|
||||
return ByteBuffer.wrap(b).order(ByteOrder.BIG_ENDIAN).getInt();
|
||||
}
|
||||
}
|
||||
@@ -65,12 +65,14 @@ const TEXT_EXT = /\.(txt|md|markdown|log|json|xml|csv|ini|conf|cfg|yaml|yml|ts|j
|
||||
const IMAGE_EXT = /\.(png|jpe?g|gif|bmp|webp|heic|heif|svg)$/i;
|
||||
const VIDEO_EXT = /\.(mp4|mkv|webm|avi|mov|3gp|m4v)$/i;
|
||||
const AUDIO_EXT = /\.(mp3|m4a|aac|ogg|oga|opus|flac|wav|mid)$/i;
|
||||
const FONT_EXT = /\.(ttf|otf|ttc|bdf|woff2?)$/i;
|
||||
|
||||
function fileIconName(name: string): IconName {
|
||||
if (TEXT_EXT.test(name)) return "file-text";
|
||||
if (IMAGE_EXT.test(name)) return "image";
|
||||
if (VIDEO_EXT.test(name)) return "film";
|
||||
if (AUDIO_EXT.test(name)) return "music";
|
||||
if (FONT_EXT.test(name)) return "type";
|
||||
return "file";
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { readTextFile, type DirectoryEntry } from "../../native/file-access";
|
||||
import { isFontFile } from "../../native/font-files";
|
||||
import { isDecodableImageFile } from "../../native/image-files";
|
||||
import { FileBrowserLayer } from "./file-browser";
|
||||
import { FileInfoDialogLayer, type FileInfoAction } from "./file-info-dialog";
|
||||
import { FontPreviewerLayer } from "./font-previewer";
|
||||
import { ImageViewerLayer } from "./image-viewer";
|
||||
import { TextViewerLayer } from "./text-viewer";
|
||||
import {
|
||||
@@ -22,6 +24,8 @@ export type FilesAppOptions = InProcessAppOptions & {
|
||||
openDocumentWindow: (title: string, text: string) => void;
|
||||
/** Open an image file as its own shell window. */
|
||||
openImageWindow: (title: string, path: string) => void;
|
||||
/** Open a font file's previewer as its own shell window. */
|
||||
openFontWindow: (title: string, path: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -32,7 +36,7 @@ export type FilesAppOptions = InProcessAppOptions & {
|
||||
export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow {
|
||||
let created: InProcessWindow | null = null;
|
||||
const browser = new FileBrowserLayer({
|
||||
isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name),
|
||||
isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name) || isFontFile(name),
|
||||
// The browser handles double-click itself (up a level), so it is not
|
||||
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
|
||||
onLeave: () => shell.yieldFocusToSidebar(),
|
||||
@@ -83,6 +87,29 @@ export function createTextDocumentWindow(
|
||||
});
|
||||
}
|
||||
|
||||
/** One opened font file's previewer as its own window. */
|
||||
export function createFontDocumentWindow(
|
||||
windowId: string,
|
||||
title: string,
|
||||
path: string,
|
||||
options: InProcessAppOptions,
|
||||
): InProcessWindow {
|
||||
return createInProcessWindow({
|
||||
appId: "files",
|
||||
windowId,
|
||||
title,
|
||||
iconLetter: "F",
|
||||
icon: "type",
|
||||
closeable: true,
|
||||
actions: options.actions,
|
||||
baseLayer: new YieldAtRootLayer(new FontPreviewerLayer(path, title)),
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: options.onClosed,
|
||||
});
|
||||
}
|
||||
|
||||
/** One opened image file as its own window. */
|
||||
export function createImageDocumentWindow(
|
||||
windowId: string,
|
||||
@@ -149,5 +176,23 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
|
||||
},
|
||||
];
|
||||
}
|
||||
if (isFontFile(entry.name)) {
|
||||
return [
|
||||
{
|
||||
label: "Preview here",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
ctx.stack.push(new FontPreviewerLayer(entry.path, entry.name));
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Open in new window",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
options.openFontWindow(entry.name, entry.path);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/bdffont";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
import {
|
||||
canLoadFontFile,
|
||||
fontFileDisplayName,
|
||||
fontFileMetrics,
|
||||
renderFontFileText,
|
||||
renderFontFileWrapped,
|
||||
} from "../../native/font-files";
|
||||
import {
|
||||
GESTURE_CLICK,
|
||||
GESTURE_DOUBLE_CLICK,
|
||||
GESTURE_SCROLL,
|
||||
gestureHints,
|
||||
} from "../../ui/gestures";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
|
||||
|
||||
const MARGIN_X = 18;
|
||||
const TITLE_Y = 8;
|
||||
const BODY_TOP = 26;
|
||||
const FOOTER_MARGIN = 20;
|
||||
const SAMPLE_GAP = 4;
|
||||
|
||||
const SIZES = [8,9,10,11, 12, 13, 14, 16, 18, 20, 24, 28, 32, 40, 48] as const;
|
||||
const DEFAULT_SIZE_INDEX = SIZES.indexOf(16);
|
||||
// 1.0 = linear coverage->shade mapping, which should match the G2's
|
||||
// roughly-linear display response; the darker/brighter options are for
|
||||
// on-hardware comparison. Cycled with click.
|
||||
const GAMMAS = [1.0, 1.3, 1.6, 0.7, 0.5] as const;
|
||||
|
||||
const PANGRAM = "The quick brown fox jumps over the lazy dog.";
|
||||
const CHARSET = "AaBbGgRr 0123456789 ?!&%().,;:'\"";
|
||||
const PARAGRAPH =
|
||||
"Weather for today: partly cloudy, high of 23°C with a light breeze. " +
|
||||
"Meeting with Sam moved to 14:30 — they asked if you can review the " +
|
||||
"draft first. Battery 78%.";
|
||||
|
||||
/**
|
||||
* Font previewer for a font file on disk (TTF/OTF/TTC), rendered through the
|
||||
* Android text stack: a single-line pangram, a character-set sample, and a
|
||||
* wrapped paragraph, all at an adjustable pixel size. Scroll changes size,
|
||||
* click cycles the coverage gamma (for judging antialiasing on the lens),
|
||||
* double-click closes. Sized to its hosting stack (a Files document window,
|
||||
* or pushed over the file browser for view-in-place).
|
||||
*/
|
||||
export class FontPreviewerLayer implements Layer {
|
||||
private sizeIndex = DEFAULT_SIZE_INDEX >= 0 ? DEFAULT_SIZE_INDEX : 2;
|
||||
private gammaIndex = 0;
|
||||
private loadable: boolean | null = null;
|
||||
private displayName: string | null = null;
|
||||
/** Rendered samples for the current size+gamma, keyed by sample id. */
|
||||
private readonly cache = new Map<string, GrayImage | null>();
|
||||
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
private readonly fileName: string,
|
||||
) {}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const out = new GrayImage(width, height, 0);
|
||||
const size = SIZES[this.sizeIndex]!;
|
||||
const gamma = GAMMAS[this.gammaIndex]!;
|
||||
|
||||
const status = `${size}px γ ${gamma.toFixed(1)}`;
|
||||
const statusWidth = font.measureText(status);
|
||||
const title = truncateText(font, this.getDisplayName(), width - 2 * MARGIN_X - statusWidth - 12);
|
||||
out.drawText(font, MARGIN_X, TITLE_Y, title, 220);
|
||||
out.drawText(font, width - MARGIN_X - statusWidth, TITLE_Y, status, 150);
|
||||
|
||||
if (this.loadable === null) {
|
||||
this.loadable = canLoadFontFile(this.path);
|
||||
}
|
||||
const footerY = height - FOOTER_MARGIN;
|
||||
if (!this.loadable) {
|
||||
out.drawText(font, MARGIN_X, BODY_TOP + 16, "(could not load font)", 160);
|
||||
out.drawText(font, MARGIN_X, footerY, gestureHints([[GESTURE_DOUBLE_CLICK, "back"]]), 110);
|
||||
return out;
|
||||
}
|
||||
|
||||
const bodyWidth = width - 2 * MARGIN_X;
|
||||
let y = BODY_TOP;
|
||||
for (const [id, text] of [
|
||||
["pangram", PANGRAM],
|
||||
["charset", CHARSET],
|
||||
] as const) {
|
||||
const line = this.getCached(id, () => renderFontFileText(this.path, text, size, gamma));
|
||||
if (!line) continue;
|
||||
out.bitBlt(line, MARGIN_X, y, { width: bodyWidth });
|
||||
y += line.height + SAMPLE_GAP;
|
||||
}
|
||||
|
||||
// Fill the rest with a wrapped paragraph, however many lines fit.
|
||||
const metrics = fontFileMetrics(this.path, size);
|
||||
const lineHeight = metrics ? metrics.ascent + metrics.descent + metrics.lineGap : size;
|
||||
const paragraphLines = Math.floor((footerY - SAMPLE_GAP - y) / Math.max(1, lineHeight));
|
||||
if (paragraphLines >= 1) {
|
||||
const paragraph = this.getCached(`para:${paragraphLines}:${bodyWidth}`, () =>
|
||||
renderFontFileWrapped({
|
||||
path: this.path,
|
||||
text: PARAGRAPH,
|
||||
sizePx: size,
|
||||
maxWidth: bodyWidth,
|
||||
maxLines: paragraphLines,
|
||||
gamma,
|
||||
}),
|
||||
);
|
||||
if (paragraph) {
|
||||
out.bitBlt(paragraph, MARGIN_X, y + SAMPLE_GAP);
|
||||
}
|
||||
}
|
||||
|
||||
out.drawText(
|
||||
font,
|
||||
MARGIN_X,
|
||||
footerY,
|
||||
gestureHints([
|
||||
[GESTURE_SCROLL, "size"],
|
||||
[GESTURE_CLICK, "gamma"],
|
||||
[GESTURE_DOUBLE_CLICK, "back"],
|
||||
]),
|
||||
110,
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.setSizeIndex(this.sizeIndex + 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.setSizeIndex(this.sizeIndex - 1);
|
||||
return;
|
||||
case "click":
|
||||
this.gammaIndex = (this.gammaIndex + 1) % GAMMAS.length;
|
||||
this.cache.clear();
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private setSizeIndex(index: number): void {
|
||||
const clamped = Math.max(0, Math.min(SIZES.length - 1, index));
|
||||
if (clamped !== this.sizeIndex) {
|
||||
this.sizeIndex = clamped;
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private getCached(key: string, render: () => GrayImage | null): GrayImage | null {
|
||||
if (!this.cache.has(key)) {
|
||||
this.cache.set(key, render());
|
||||
}
|
||||
return this.cache.get(key) ?? null;
|
||||
}
|
||||
|
||||
private getDisplayName(): string {
|
||||
if (this.displayName === null) {
|
||||
const name = fontFileDisplayName(this.path);
|
||||
this.displayName = name
|
||||
? name.style && !/^regular$/i.test(name.style)
|
||||
? `${name.family} ${name.style}`
|
||||
: name.family
|
||||
: this.fileName;
|
||||
}
|
||||
return this.displayName;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type AppContext, type AppDefinition } from "../app-definition";
|
||||
import {
|
||||
createFilesAppWindow,
|
||||
createFontDocumentWindow,
|
||||
createImageDocumentWindow,
|
||||
createTextDocumentWindow,
|
||||
FILES_SURFACE_ID,
|
||||
@@ -33,6 +34,17 @@ function openImageDocumentWindow(ctx: AppContext, title: string, path: string):
|
||||
});
|
||||
}
|
||||
|
||||
function openFontDocumentWindow(ctx: AppContext, title: string, path: string): void {
|
||||
const windowId = `files:doc:${nextDocumentSerial++}`;
|
||||
void ctx
|
||||
.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
|
||||
createFontDocumentWindow(windowId, title, path, options),
|
||||
)
|
||||
.catch((error) => {
|
||||
ctx.appendLog(`font preview window failed: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
const filesApp: AppDefinition = {
|
||||
appId: "files",
|
||||
title: "Files",
|
||||
@@ -43,6 +55,7 @@ const filesApp: AppDefinition = {
|
||||
...options,
|
||||
openDocumentWindow: (title, text) => openTextDocumentWindow(ctx, title, text),
|
||||
openImageWindow: (title, path) => openImageDocumentWindow(ctx, title, path),
|
||||
openFontWindow: (title, path) => openFontDocumentWindow(ctx, title, path),
|
||||
}),
|
||||
),
|
||||
// A document arriving via Android's Share intent opens as its own window.
|
||||
|
||||
@@ -48,6 +48,8 @@ export const ICON_SVGS = {
|
||||
'<svg viewBox="0 0 24 24" fill="none"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',
|
||||
film:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M7 3v18"/><path d="M3 7.5h4"/><path d="M3 12h18"/><path d="M3 16.5h4"/><path d="M17 3v18"/><path d="M21 7.5h-4"/><path d="M21 16.5h-4"/></svg>',
|
||||
type:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12 4v16"/><path d="M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2"/><path d="M9 20h6"/></svg>',
|
||||
"hard-drive":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/></svg>',
|
||||
music:
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Font-file text rendering for the on-glasses font previewer, backed by the
|
||||
* Java FontFileRenderer (Android Typeface/Paint, so shaping, kerning, and
|
||||
* line breaking come from minikin/HarfBuzz). Rendered text arrives as
|
||||
* antialiased 8bpp coverage, which the compositor quantizes to the display's
|
||||
* 16 shades.
|
||||
*/
|
||||
import { GrayImage } from "../graphics/image";
|
||||
import { grayImageFromPacket } from "./image-files";
|
||||
|
||||
declare const com: any;
|
||||
declare const global: any;
|
||||
|
||||
/** Font file formats Android's Typeface can load. */
|
||||
const FONT_FILE = /\.(ttf|otf|ttc)$/i;
|
||||
|
||||
export function isFontFile(name: string): boolean {
|
||||
return FONT_FILE.test(name);
|
||||
}
|
||||
|
||||
export type FontFileMetrics = {
|
||||
/** Pixels above the baseline. */
|
||||
ascent: number;
|
||||
/** Pixels below the baseline. */
|
||||
descent: number;
|
||||
/** Extra pixels between lines beyond ascent+descent. */
|
||||
lineGap: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gamma applied when mapping antialiased coverage to output shade
|
||||
* (out = coverage^gamma). The G2 display response looks roughly linear, so
|
||||
* 1.0 is the default; values below 1 brighten the AA fringe (as if the
|
||||
* display were sRGB-ish), values above darken it.
|
||||
*/
|
||||
export const DEFAULT_FONT_GAMMA = 1.0;
|
||||
|
||||
/** Whether the font file parses as a loadable font. */
|
||||
export function canLoadFontFile(path: string): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
try {
|
||||
return !!com.faceclaw.app.FontFileRenderer.canLoadFont(path);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The font's family/style names from its 'name' table; null when
|
||||
* unavailable (caller should fall back to the filename).
|
||||
*/
|
||||
export function fontFileDisplayName(path: string): { family: string; style: string } | null {
|
||||
if (!global.isAndroid) return null;
|
||||
try {
|
||||
const raw = String(com.faceclaw.app.FontFileRenderer.getFontName(path) ?? "");
|
||||
if (!raw) return null;
|
||||
const [family, style] = raw.split("\n");
|
||||
if (!family) return null;
|
||||
return { family, style: style ?? "" };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Line metrics at a pixel size; null when the font cannot be loaded. */
|
||||
export function fontFileMetrics(path: string, sizePx: number): FontFileMetrics | null {
|
||||
if (!global.isAndroid) return null;
|
||||
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.some((part) => !Number.isFinite(part))) return null;
|
||||
return { ascent: parts[0]!, descent: parts[1]!, lineGap: parts[2]! };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one line of text at a pixel size. The image is the full line box
|
||||
* (ascent+descent tall); null when the font cannot be loaded or the text
|
||||
* renders to nothing.
|
||||
*/
|
||||
export function renderFontFileText(
|
||||
path: string,
|
||||
text: string,
|
||||
sizePx: number,
|
||||
gamma = DEFAULT_FONT_GAMMA,
|
||||
): GrayImage | null {
|
||||
if (!global.isAndroid) return null;
|
||||
try {
|
||||
return grayImageFromPacket(com.faceclaw.app.FontFileRenderer.renderText(path, text, sizePx, gamma));
|
||||
} catch (error) {
|
||||
console.warn(`renderFontFileText failed for ${path}: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a paragraph wrapped to maxWidth (StaticLayout line breaking),
|
||||
* truncated with an ellipsis past maxLines.
|
||||
*/
|
||||
export function renderFontFileWrapped(opts: {
|
||||
path: string;
|
||||
text: string;
|
||||
sizePx: number;
|
||||
maxWidth: number;
|
||||
maxLines: number;
|
||||
gamma?: number;
|
||||
}): GrayImage | null {
|
||||
if (!global.isAndroid) return null;
|
||||
try {
|
||||
return grayImageFromPacket(
|
||||
com.faceclaw.app.FontFileRenderer.renderWrapped(
|
||||
opts.path,
|
||||
opts.text,
|
||||
opts.sizePx,
|
||||
Math.round(opts.maxWidth),
|
||||
opts.gamma ?? DEFAULT_FONT_GAMMA,
|
||||
Math.round(opts.maxLines),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(`renderFontFileWrapped failed for ${opts.path}: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user