From 56b07076722326e18316230fd075a4f787396520 Mon Sep 17 00:00:00 2001 From: Brian Jr Date: Tue, 24 Nov 2026 22:29:36 -0500 Subject: [PATCH 1/2] feat(theme): share the current look's fonts (#89) --- .../system/SharedFontsContract.kt | 91 ++++++++ .../commandpannel/system/SharedLookFonts.kt | 112 ++++++++++ .../commandpannel/system/ThemeProvider.kt | 104 +++++++-- .../commandpannel/system/UserFontStore.kt | 45 +++- .../commandpannel/system/SharedFontsTest.kt | 211 ++++++++++++++++++ docs/SHARED_THEME.md | 71 +++++- scripts/verify-shared-fonts.sh | 108 +++++++++ 7 files changed, 713 insertions(+), 29 deletions(-) create mode 100644 app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt create mode 100644 app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt create mode 100644 app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt create mode 100755 scripts/verify-shared-fonts.sh diff --git a/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt b/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt new file mode 100644 index 0000000..64bc9cf --- /dev/null +++ b/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt @@ -0,0 +1,91 @@ +package jr.brian.commandpannel.system + +/** + * The shared fonts contract, version 2: which fonts the applied look uses, read from [ThemeProvider] next to the + * version 1 palette ([SharedThemeContract]). The full spec is `docs/SHARED_THEME.md` in the Command Panel repo. + * + * Constants only, with no Android or Command Panel imports, so a client can copy this file as is. Version 2 is frozen + * the same way version 1 is: any change to the row means a new [VERSION]. + */ +object SharedFontsContract { + + /** The contract version this file describes, also returned in [COLUMN_VERSION]. */ + const val VERSION = 2 + + /** The fonts row: `content://.theme/fonts`. Returns one row. */ + const val PATH = "fonts" + + /** An imported font's file: `content://.theme/fonts/`, opened read-only by a trusted app only. */ + const val FILE_PATH = "fonts" + + /** MIME type of an imported font file (TrueType or OpenType). */ + const val FILE_MIME_TYPE = "font/sfnt" + + // ---- columns ---- + + /** Integer, always [VERSION]. */ + const val COLUMN_VERSION = "version" + + /** The applied look: a built-in look's name (`TERMINAL`) or `custom:` for a saved look. */ + const val COLUMN_LOOK_ID = "look_id" + + /** Font for big numbers and titles, as a font value (see [PREFIX_BUNDLED] and [PREFIX_USER]), or null. */ + const val COLUMN_DISPLAY_FONT = "display_font" + + /** SHA-256 of the display font's file (lowercase hex) when it's a `user:` font, otherwise null. */ + const val COLUMN_DISPLAY_FONT_SHA256 = "display_font_sha256" + + /** Font for labels and body text, as a font value, or null. */ + const val COLUMN_LABEL_FONT = "label_font" + + /** SHA-256 of the label font's file (lowercase hex) when it's a `user:` font, otherwise null. */ + const val COLUMN_LABEL_FONT_SHA256 = "label_font_sha256" + + /** Every column, in the order a query without a projection returns them. */ + val COLUMNS = listOf( + COLUMN_VERSION, COLUMN_LOOK_ID, + COLUMN_DISPLAY_FONT, COLUMN_DISPLAY_FONT_SHA256, + COLUMN_LABEL_FONT, COLUMN_LABEL_FONT_SHA256, + ) + + // ---- font values ---- + + /** `bundled:`: one of the bundled families below. The client ships the same open font files. */ + const val PREFIX_BUNDLED = "bundled:" + + /** `user:`: a font the user imported, read from [FILE_PATH]`/`. */ + const val PREFIX_USER = "user:" + + /** Barlow Condensed SemiBold, Bold and ExtraBold. */ + const val BUNDLED_CONDENSED = "condensed" + + /** Barlow Condensed ExtraBold only, for big numbers. */ + const val BUNDLED_CONDENSED_DISPLAY = "condensed_display" + + /** JetBrains Mono Regular and Bold. */ + const val BUNDLED_MONO = "mono" + + /** DSEG7 Classic Bold, seven-segment digits. */ + const val BUNDLED_SEGMENT = "segment" + + /** Baloo 2 ExtraBold. */ + const val BUNDLED_ROUNDED = "rounded" + + /** Black Ops One. */ + const val BUNDLED_STENCIL = "stencil" + + /** Bangers. */ + const val BUNDLED_COMIC = "comic" + + /** Michroma. */ + const val BUNDLED_CHROME_WIDE = "chrome_wide" + + /** Literata Regular and Italic. */ + const val BUNDLED_SERIF = "serif" + + /** Every bundled key. A key is never renamed or reused; a new bundled family adds a key. */ + val BUNDLED_KEYS = listOf( + BUNDLED_CONDENSED, BUNDLED_CONDENSED_DISPLAY, BUNDLED_MONO, BUNDLED_SEGMENT, BUNDLED_ROUNDED, + BUNDLED_STENCIL, BUNDLED_COMIC, BUNDLED_CHROME_WIDE, BUNDLED_SERIF, + ) +} diff --git a/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt b/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt new file mode 100644 index 0000000..e06a5dd --- /dev/null +++ b/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt @@ -0,0 +1,112 @@ +package jr.brian.commandpannel.system + +import androidx.compose.ui.text.font.FontFamily +import jr.brian.commandpannel.plugin.PanelPluginTrust +import jr.brian.commandpannel.ui.theme.BundledFont +import jr.brian.commandpannel.ui.theme.FontRef +import jr.brian.commandpannel.ui.theme.TccUiLook +import jr.brian.commandpannel.ui.theme.specForLook + +/** The contract key for [font], or `null` for the system font. */ +internal fun sharedBundledKey(font: BundledFont): String? = when (font) { + BundledFont.DEFAULT -> null + BundledFont.CONDENSED -> SharedFontsContract.BUNDLED_CONDENSED + BundledFont.CONDENSED_DISPLAY -> SharedFontsContract.BUNDLED_CONDENSED_DISPLAY + BundledFont.MONO -> SharedFontsContract.BUNDLED_MONO + BundledFont.SEGMENT -> SharedFontsContract.BUNDLED_SEGMENT + BundledFont.ROUNDED -> SharedFontsContract.BUNDLED_ROUNDED + BundledFont.STENCIL -> SharedFontsContract.BUNDLED_STENCIL + BundledFont.COMIC -> SharedFontsContract.BUNDLED_COMIC + BundledFont.CHROME_WIDE -> SharedFontsContract.BUNDLED_CHROME_WIDE + BundledFont.SERIF -> SharedFontsContract.BUNDLED_SERIF +} + +/** A built-in look's family as a [FontRef], or `null` when it uses the system font. */ +private fun FontFamily?.asBundledRef(): FontRef? = + this?.let { family -> BundledFont.entries.firstOrNull { it.family == family } }?.let { FontRef.Bundled(it) } + +/** The look's label and display font choices before resolving, the way `CustomLook.toSpec` layers them. */ +private fun SharedLook.fontRefs(): Pair { + val base = specForLook(custom?.baseLook ?: builtIn ?: TccUiLook.DEFAULT).traits + val label = custom?.labelFont ?: base.labelFontFamily.asBundledRef() + val display = custom?.displayFont ?: base.displayFontFamily.asBundledRef() + return label to display +} + +/** One font role's published value and, for an imported font, its file's SHA-256. */ +private data class SharedFontValue(val value: String, val sha256: String?) + +/** `null` for the system font or an imported font whose file is gone, which the overlay also draws in the system font. */ +private fun FontRef?.toShared(userFontSha256: (String) -> String?): SharedFontValue? = when (this) { + null -> null + is FontRef.Bundled -> sharedBundledKey(font)?.let { SharedFontValue(SharedFontsContract.PREFIX_BUNDLED + it, null) } + is FontRef.User -> userFontSha256(id)?.let { SharedFontValue(SharedFontsContract.PREFIX_USER + id, it) } +} + +/** + * The fonts row for [look]. A role without its own font falls back to the label font, as the overlay's text styles do, + * so a client never has to know the fallback rule. [userFontSha256] gives an imported font's digest, or `null` when its + * file is gone. + */ +internal fun sharedFontsRow(look: SharedLook, userFontSha256: (String) -> String?): Map { + val (labelRef, displayRef) = look.fontRefs() + val label = labelRef.toShared(userFontSha256) + val display = displayRef.toShared(userFontSha256) ?: label + return mapOf( + SharedFontsContract.COLUMN_VERSION to SharedFontsContract.VERSION, + SharedFontsContract.COLUMN_LOOK_ID to look.id, + SharedFontsContract.COLUMN_DISPLAY_FONT to display?.value, + SharedFontsContract.COLUMN_DISPLAY_FONT_SHA256 to display?.sha256, + SharedFontsContract.COLUMN_LABEL_FONT to label?.value, + SharedFontsContract.COLUMN_LABEL_FONT_SHA256 to label?.sha256, + ) +} + +/** [row]'s values for [columns], in that order. Values may be null; an unknown column is the caller's error. */ +internal fun selectSharedColumns(row: Map, columns: Array): Array = + Array(columns.size) { i -> + val column = columns[i] + require(row.containsKey(column)) { "unknown column: $column" } + row[column] + } + +// UserFontStore names files by UUID; anything else (dots, slashes, encoded separators) is refused outright. +private val USER_FONT_ID = Regex("[0-9A-Fa-f-]{1,64}") + +/** The imported font id a `fonts/` path asks for, or `null` for any other path. */ +internal fun sharedFontFileId(pathSegments: List): String? = + pathSegments.takeIf { it.size == 2 && it[0] == SharedFontsContract.FILE_PATH } + ?.get(1)?.takeIf { USER_FONT_ID.matches(it) } + +/** + * The apps allowed to open imported font files, by package and pinned signing certificate (SHA-256, lowercase hex). + * Only Jarngreipr's release build in a release Command Panel; a debug Command Panel also serves Jarngreipr's debug build. + */ +internal object SharedFontReaders { + const val JARN_PACKAGE = "jr.brian.home" + const val JARN_DEBUG_PACKAGE = "jr.brian.home.debug" + + /** Jarngreipr's release key, from `apksigner verify --print-certs`. */ + const val JARN_RELEASE_CERT_SHA256 = "a9a6e4628ff67b218be69f39dd4c7843cdcbd565f76b31f93f0c90f3433d56db" + + /** Jarngreipr's committed `app/debug.keystore`. */ + const val JARN_DEBUG_CERT_SHA256 = "d954c2d6139facf3acf555a6e28664e15b0b8f8e93b5339ab8e1fc9c001419a6" + + private val RELEASE = mapOf(JARN_PACKAGE to JARN_RELEASE_CERT_SHA256) + private val DEBUG = RELEASE + (JARN_DEBUG_PACKAGE to JARN_DEBUG_CERT_SHA256) + + fun allowed(debugBuild: Boolean): Map = if (debugBuild) DEBUG else RELEASE + + /** + * True when one of the calling UID's packages is on [allowed] and every current signer of that package matches its + * pin. [signerDigests] reads a package's signers; an empty list (not installed, unreadable) is never trusted. + */ + fun isTrusted( + callerPackages: Collection, + allowed: Map, + signerDigests: (String) -> List, + ): Boolean = callerPackages.any { pkg -> + val pin = allowed[pkg] ?: return@any false + PanelPluginTrust.isTrusted(signerDigests(pkg), setOf(pin)) + } +} diff --git a/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt b/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt index f43c34a..8c3d87a 100644 --- a/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt +++ b/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt @@ -4,24 +4,31 @@ import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.content.SharedPreferences +import android.content.pm.PackageManager import android.content.res.Configuration import android.database.ContentObserver import android.database.Cursor import android.database.MatrixCursor import android.net.Uri +import android.os.Binder import android.os.Handler import android.os.Looper +import android.os.ParcelFileDescriptor import android.provider.Settings import android.util.Log import androidx.compose.ui.graphics.toArgb +import jr.brian.commandpannel.BuildConfig +import jr.brian.commandpannel.plugin.PanelPluginTrust import jr.brian.commandpannel.privileged.ThorRgbController import jr.brian.commandpannel.ui.settings.companionPaletteFrom +import jr.brian.commandpannel.ui.theme.CustomLook import jr.brian.commandpannel.ui.theme.CustomLookJson import jr.brian.commandpannel.ui.theme.LookRef import jr.brian.commandpannel.ui.theme.PinnedColors import jr.brian.commandpannel.ui.theme.TccColors import jr.brian.commandpannel.ui.theme.TccUiLook import jr.brian.commandpannel.ui.theme.resolveLookPalette +import java.io.FileNotFoundException import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit @@ -31,7 +38,10 @@ import java.util.concurrent.atomic.AtomicBoolean * Publishes the overlay's resolved colors, read-only, so another app (Jarn FE) can match them ([SharedThemeContract]). * It starts from the palette the companion gets when it follows the look, whether or not that setting is on, adds the * built-in look's colors ([publishedLookPalette]), and never uses Theme Studio's unsaved draft. Colors aren't secret, - * so the provider is open to any app. + * so the palette is open to any app. + * + * It also publishes the applied look's fonts ([SharedFontsContract]). The fonts row is open too, but an imported font's + * file is only opened for an app on [SharedFontReaders]. * * Android creates providers before `Application.onCreate`, so nothing is read until the first query or the posted * [watch]. @@ -48,6 +58,7 @@ class ThemeProvider : ContentProvider() { // Only touched on [worker]. private var published: Map? = null + private var publishedFonts: Map? = null private val observer = object : ContentObserver(main) { override fun onChange(selfChange: Boolean) = queueRefresh() @@ -72,6 +83,7 @@ class ThemeProvider : ContentProvider() { ctx.contentResolver.registerContentObserver(Settings.System.getUriFor(it), false, observer) } published = currentRow(ctx) + publishedFonts = currentFontsRow(ctx) }.onFailure { Log.w(TAG, "couldn't watch the theme", it) } } @@ -83,13 +95,21 @@ class ThemeProvider : ContentProvider() { } } - /** Tells clients only when the row really changed: most LED and pref changes don't touch the palette. */ + /** Tells clients only when a row really changed: most LED and pref changes touch neither the palette nor the fonts. */ private fun publishIfChanged() { val ctx = context ?: return - val row = runCatching { currentRow(ctx) }.getOrElse { Log.w(TAG, "couldn't read the theme", it); return } - if (row == published) return - published = row - ctx.contentResolver.notifyChange(uri(ctx), null) + runCatching { currentRow(ctx) }.onSuccess { row -> + if (row != published) { + published = row + ctx.contentResolver.notifyChange(uri(ctx, SharedThemeContract.PATH), null) + } + }.onFailure { Log.w(TAG, "couldn't read the theme", it) } + runCatching { currentFontsRow(ctx) }.onSuccess { row -> + if (row != publishedFonts) { + publishedFonts = row + ctx.contentResolver.notifyChange(uri(ctx, SharedFontsContract.PATH), null) + } + }.onFailure { Log.w(TAG, "couldn't read the fonts", it) } } // Follow-system theme mode changes with the night setting. @@ -104,15 +124,51 @@ class ThemeProvider : ContentProvider() { sortOrder: String?, ): Cursor? { val ctx = context ?: return null - if (uri.pathSegments != listOf(SharedThemeContract.PATH)) return null - val columns = projection ?: SharedThemeContract.COLUMNS.toTypedArray() - val row = runCatching { currentRow(ctx) }.getOrElse { Log.w(TAG, "couldn't read the theme", it); return null } - val values = selectSharedThemeColumns(row, columns) - return MatrixCursor(columns, 1).apply { addRow(values) } + return when (uri.pathSegments) { + listOf(SharedThemeContract.PATH) -> { + val columns = projection ?: SharedThemeContract.COLUMNS.toTypedArray() + val row = runCatching { currentRow(ctx) } + .getOrElse { Log.w(TAG, "couldn't read the theme", it); return null } + MatrixCursor(columns, 1).apply { addRow(selectSharedThemeColumns(row, columns)) } + } + listOf(SharedFontsContract.PATH) -> { + val columns = projection ?: SharedFontsContract.COLUMNS.toTypedArray() + val row = runCatching { currentFontsRow(ctx) } + .getOrElse { Log.w(TAG, "couldn't read the fonts", it); return null } + MatrixCursor(columns, 1).apply { addRow(selectSharedColumns(row, columns)) } + } + else -> null + } + } + + override fun getType(uri: Uri): String? = when { + uri.pathSegments == listOf(SharedThemeContract.PATH) -> MIME_TYPE + uri.pathSegments == listOf(SharedFontsContract.PATH) -> FONTS_MIME_TYPE + sharedFontFileId(uri.pathSegments) != null -> SharedFontsContract.FILE_MIME_TYPE + else -> null } - override fun getType(uri: Uri): String? = - if (uri.pathSegments == listOf(SharedThemeContract.PATH)) MIME_TYPE else null + /** + * An imported font's file, read-only, for a trusted caller only ([SharedFontReaders]). Bundled fonts aren't served: + * the client ships its own copies. + */ + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { + val ctx = context ?: throw FileNotFoundException(uri.toString()) + if (mode != "r") throw SecurityException(READ_ONLY) + val id = sharedFontFileId(uri.pathSegments) ?: throw FileNotFoundException(uri.toString()) + if (!isTrustedFontReader(ctx)) throw SecurityException("not allowed to read fonts") + val file = UserFontStore.sharedFile(ctx, id) ?: throw FileNotFoundException(uri.toString()) + return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + } + + private fun isTrustedFontReader(ctx: Context): Boolean { + val pm = ctx.packageManager + val packages = pm.getPackagesForUid(Binder.getCallingUid())?.toList().orEmpty() + return SharedFontReaders.isTrusted(packages, SharedFontReaders.allowed(BuildConfig.DEBUG)) { pkg -> + val info = runCatching { pm.getPackageInfo(pkg, PackageManager.GET_SIGNING_CERTIFICATES) }.getOrNull() + PanelPluginTrust.signerDigests(info) + } + } override fun insert(uri: Uri, values: ContentValues?): Uri? = throw UnsupportedOperationException(READ_ONLY) @@ -134,25 +190,35 @@ class ThemeProvider : ContentProvider() { return sharedThemeRow(publishedPalette(themeMode, night, accent, activeLook.of(prefs))) } + private fun currentFontsRow(ctx: Context): Map = + sharedFontsRow(activeLook.of(Prefs.of(ctx))) { UserFontStore.sha256(ctx, it) } + private companion object { const val TAG = "ThemeProvider" const val WORKER_IDLE_SECONDS = 30L const val READ_ONLY = "the shared theme is read-only" const val MIME_TYPE = "vnd.android.cursor.item/vnd.jr.brian.commandpanel.theme" + const val FONTS_MIME_TYPE = "vnd.android.cursor.item/vnd.jr.brian.commandpanel.fonts" const val ACCENT_SYNC_PREF = "rgb_accent_sync" - val WATCHED_PREFS = setOf(CustomLookStore.LOOK_KEY, CustomLookStore.KEY, ACCENT_SYNC_PREF) + val WATCHED_PREFS = setOf(CustomLookStore.LOOK_KEY, CustomLookStore.KEY, ACCENT_SYNC_PREF, UserFontStore.KEY) val WATCHED_SETTINGS = listOf(SystemSettings.Keys.THEME_MODE, ThorRgbController.PICKER_COLOR_KEY) - fun uri(ctx: Context): Uri = Uri.Builder() + fun uri(ctx: Context, path: String): Uri = Uri.Builder() .scheme("content") .authority(ctx.packageName + SharedThemeContract.AUTHORITY_SUFFIX) - .path(SharedThemeContract.PATH) + .path(path) .build() } } -/** What the applied look adds to the shared palette: a [builtIn] look's colors, or a saved look's [pinned] ones. */ -internal data class SharedLook(val builtIn: TccUiLook?, val pinned: PinnedColors?) +/** + * What the applied look adds to the shared theme: a [builtIn] look's colors, or a saved look's [pinned] ones. A saved + * look also keeps its [custom] definition, for its fonts. + */ +internal data class SharedLook(val builtIn: TccUiLook?, val pinned: PinnedColors?, val custom: CustomLook? = null) { + /** The contract's `look_id`: the built-in look's name or the saved look's `custom:` key. */ + val id: String get() = custom?.ref?.key ?: (builtIn ?: TccUiLook.DEFAULT).name +} /** * The applied look. Reads only the applied look and the saved looks, never Theme Studio's draft (`studio_draft`). @@ -171,7 +237,7 @@ internal class ActiveSharedLook { val look = when (val ref = LookRef.parse(lookKey)) { is LookRef.BuiltIn -> SharedLook(ref.look, null) is LookRef.Custom -> CustomLookJson.decodeList(looksJson).firstOrNull { it.id == ref.id } - ?.let { SharedLook(null, it.colors) } + ?.let { SharedLook(null, it.colors, it) } ?: SharedLook(TccUiLook.DEFAULT, null) } last = Decoded(lookKey, looksJson, look) diff --git a/app/src/main/java/jr/brian/commandpannel/system/UserFontStore.kt b/app/src/main/java/jr/brian/commandpannel/system/UserFontStore.kt index c43a8b7..7434af7 100644 --- a/app/src/main/java/jr/brian/commandpannel/system/UserFontStore.kt +++ b/app/src/main/java/jr/brian/commandpannel/system/UserFontStore.kt @@ -13,6 +13,7 @@ import org.json.JSONArray import org.json.JSONObject import java.io.File import java.io.InputStream +import java.security.MessageDigest import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -33,14 +34,19 @@ data class UserFont( class FontImportException(@StringRes val messageRes: Int) : Exception() /** - * User-imported TTF/OTF fonts. Files are copied into `filesDir/fonts/.ttf` (app-private, never exported or - * backed up) and indexed in the `user_fonts` pref. The overlay service runs in the same app, so both surfaces load - * them from the same files. A look whose font file is missing falls back to the default font. + * User-imported TTF/OTF fonts. Files are copied into `filesDir/fonts/.ttf` (app-private, never backed up) and + * indexed in the `user_fonts` pref. The overlay service runs in the same app, so both surfaces load them from the same + * files. A look whose font file is missing falls back to the default font. [ThemeProvider] serves these files + * read-only to the apps on [SharedFontReaders] (docs/SHARED_THEME.md), and to no one else. */ object UserFontStore { - private const val KEY = "user_fonts" + internal const val KEY = "user_fonts" private const val MAX_BYTES = 5L * 1024 * 1024 private val cache = ConcurrentHashMap() + private val digests = ConcurrentHashMap() + + /** A file's SHA-256, valid while its size and modified time stay the same. */ + private class FileDigest(val length: Long, val modified: Long, val sha256: String) private fun prefs(context: Context) = Prefs.of(context) private fun dir(context: Context) = File(context.filesDir, "fonts").apply { mkdirs() } @@ -107,8 +113,39 @@ object UserFontStore { /** The app-private file holding [id] (for copying fonts out into `TCP Themes/fonts`). */ fun fileOf(context: Context, id: String): File = file(context, id) + /** + * The file for imported font [id] when it's indexed and its file sits directly in the fonts folder, otherwise + * `null`. What the shared theme serves, so an id can never reach another file. + */ + fun sharedFile(context: Context, id: String): File? { + if (all(context).none { it.id == id }) return null + val folder = dir(context).canonicalFile + return file(context, id).canonicalFile.takeIf { it.parentFile == folder && it.isFile } + } + + /** SHA-256 of [id]'s file (lowercase hex), or `null` when it isn't an imported font any more. */ + fun sha256(context: Context, id: String): String? { + val f = sharedFile(context, id) ?: return null + val length = f.length() + val modified = f.lastModified() + digests[id]?.takeIf { it.length == length && it.modified == modified }?.let { return it.sha256 } + val digest = MessageDigest.getInstance("SHA-256") + f.inputStream().use { input -> + val buf = ByteArray(16 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + digest.update(buf, 0, n) + } + } + val hex = digest.digest().joinToString("") { "%02x".format(it) } + digests[id] = FileDigest(length, modified, hex) + return hex + } + fun delete(context: Context, id: String) { cache.remove(id) + digests.remove(id) file(context, id).delete() write(context, all(context).filterNot { it.id == id }) } diff --git a/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt b/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt new file mode 100644 index 0000000..6ec64e9 --- /dev/null +++ b/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt @@ -0,0 +1,211 @@ +package jr.brian.commandpannel.system + +import jr.brian.commandpannel.ui.theme.BundledFont +import jr.brian.commandpannel.ui.theme.CustomLook +import jr.brian.commandpannel.ui.theme.CustomLookJson +import jr.brian.commandpannel.ui.theme.FontRef +import jr.brian.commandpannel.ui.theme.LookRef +import jr.brian.commandpannel.ui.theme.TccUiLook +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.lang.reflect.Proxy + +class SharedFontsTest { + @Test + fun `the contract's values never change`() { + assertEquals(2, SharedFontsContract.VERSION) + assertEquals("fonts", SharedFontsContract.PATH) + assertEquals("fonts", SharedFontsContract.FILE_PATH) + assertEquals( + listOf("version", "look_id", "display_font", "display_font_sha256", "label_font", "label_font_sha256"), + SharedFontsContract.COLUMNS, + ) + assertEquals("bundled:", SharedFontsContract.PREFIX_BUNDLED) + assertEquals("user:", SharedFontsContract.PREFIX_USER) + assertEquals( + listOf("condensed", "condensed_display", "mono", "segment", "rounded", "stencil", "comic", "chrome_wide", "serif"), + SharedFontsContract.BUNDLED_KEYS, + ) + } + + @Test + fun `every bundled family has its own key`() { + val keys = BundledFont.entries.filter { it != BundledFont.DEFAULT }.map { sharedBundledKey(it) } + assertEquals(SharedFontsContract.BUNDLED_KEYS, keys) + assertNull(sharedBundledKey(BundledFont.DEFAULT)) + } + + @Test + fun `the row has exactly the contract's columns`() { + assertEquals(SharedFontsContract.COLUMNS.toSet(), rowFor(SharedLook(TccUiLook.TERMINAL, null)).keys) + } + + @Test + fun `a built-in look publishes its bundled fonts`() { + val row = rowFor(SharedLook(TccUiLook.SEGMENT_LCD, null)) + assertEquals(2, row[SharedFontsContract.COLUMN_VERSION]) + assertEquals("SEGMENT_LCD", row[SharedFontsContract.COLUMN_LOOK_ID]) + assertEquals("bundled:segment", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + assertEquals("bundled:mono", row[SharedFontsContract.COLUMN_LABEL_FONT]) + assertNull(row[SharedFontsContract.COLUMN_DISPLAY_FONT_SHA256]) + assertNull(row[SharedFontsContract.COLUMN_LABEL_FONT_SHA256]) + } + + @Test + fun `a look in the system font publishes null fonts`() { + val row = rowFor(SharedLook(TccUiLook.AURORA_GLASS, null)) + assertNull(row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + assertNull(row[SharedFontsContract.COLUMN_LABEL_FONT]) + } + + @Test + fun `a missing display font falls back to the label font`() { + val row = rowFor(SharedLook(TccUiLook.E_INK, null)) + assertEquals("bundled:serif", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + assertEquals("bundled:serif", row[SharedFontsContract.COLUMN_LABEL_FONT]) + } + + @Test + fun `a saved look's imported font is published with its digest`() { + val look = CustomLook(id = "mine", name = "mine", baseLook = TccUiLook.TERMINAL, labelFont = userFont(FONT_ID)) + val row = rowFor(SharedLook(null, look.colors, look)) + assertEquals("custom:mine", row[SharedFontsContract.COLUMN_LOOK_ID]) + assertEquals("user:$FONT_ID", row[SharedFontsContract.COLUMN_LABEL_FONT]) + assertEquals(FONT_SHA, row[SharedFontsContract.COLUMN_LABEL_FONT_SHA256]) + assertEquals("bundled:mono", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + } + + @Test + fun `an imported font whose file is gone publishes the fallback`() { + val look = CustomLook( + id = "mine", name = "mine", baseLook = TccUiLook.TERMINAL, + labelFont = userFont(FONT_ID), displayFont = userFont("00000000-dead"), + ) + val row = rowFor(SharedLook(null, look.colors, look)) + assertEquals("user:$FONT_ID", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + assertEquals(FONT_SHA, row[SharedFontsContract.COLUMN_DISPLAY_FONT_SHA256]) + } + + @Test + fun `a saved look can pick the system font over its base look's`() { + val look = CustomLook( + id = "plain", name = "plain", baseLook = TccUiLook.E_INK, labelFont = FontRef.Bundled(BundledFont.DEFAULT), + ) + val row = rowFor(SharedLook(null, look.colors, look)) + assertNull(row[SharedFontsContract.COLUMN_LABEL_FONT]) + assertEquals("bundled:serif", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) + } + + @Test + fun `the applied saved look is read from prefs`() { + val look = CustomLook(id = "mine", name = "mine", labelFont = userFont(FONT_ID)) + val prefs = prefsOf(CustomLookStore.LOOK_KEY to look.ref.key, CustomLookStore.KEY to CustomLookJson.encodeList(listOf(look))) + val row = rowFor(ActiveSharedLook().of(prefs)) + assertEquals("user:$FONT_ID", row[SharedFontsContract.COLUMN_LABEL_FONT]) + } + + @Test + fun `an unknown look id publishes the default look`() { + val prefs = prefsOf(CustomLookStore.LOOK_KEY to LookRef.Custom("gone").key) + val row = rowFor(ActiveSharedLook().of(prefs)) + assertEquals(TccUiLook.DEFAULT.name, row[SharedFontsContract.COLUMN_LOOK_ID]) + assertNull(row[SharedFontsContract.COLUMN_LABEL_FONT]) + } + + @Test + fun `a projection returns its columns in order, nulls included`() { + val row = rowFor(SharedLook(TccUiLook.AURORA_GLASS, null)) + val values = selectSharedColumns(row, arrayOf("label_font", "version")) + assertArrayEquals(arrayOf(null, 2), values) + } + + @Test(expected = IllegalArgumentException::class) + fun `an unknown column is refused`() { + selectSharedColumns(rowFor(SharedLook(TccUiLook.TERMINAL, null)), arrayOf("secret")) + } + + @Test + fun `a font file path names one imported font id`() { + assertEquals(FONT_ID, sharedFontFileId(listOf("fonts", FONT_ID))) + assertNull(sharedFontFileId(listOf("fonts"))) + assertNull(sharedFontFileId(listOf("palette", FONT_ID))) + } + + @Test + fun `path traversal is refused`() { + listOf( + listOf("fonts", ".."), + listOf("fonts", "../../shared_prefs/prefs.xml"), + listOf("fonts", "..%2F..%2Fshared_prefs"), + listOf("fonts", "$FONT_ID.ttf"), + listOf("fonts", "a/b"), + listOf("fonts", ""), + listOf("fonts", "..", FONT_ID), + listOf("fonts", FONT_ID, ".."), + ).forEach { assertNull(it.toString(), sharedFontFileId(it)) } + } + + @Test + fun `only Jarngreipr signed with its pinned key may read font files`() { + val release = SharedFontReaders.allowed(debugBuild = false) + val jarn = SharedFontReaders.JARN_PACKAGE + val pin = SharedFontReaders.JARN_RELEASE_CERT_SHA256 + assertTrue(SharedFontReaders.isTrusted(listOf(jarn), release) { listOf(pin) }) + assertTrue(SharedFontReaders.isTrusted(listOf("other", jarn), release) { if (it == jarn) listOf(pin) else emptyList() }) + } + + @Test + fun `an untrusted caller can't read font files`() { + val release = SharedFontReaders.allowed(debugBuild = false) + val jarn = SharedFontReaders.JARN_PACKAGE + val pin = SharedFontReaders.JARN_RELEASE_CERT_SHA256 + val other = "0".repeat(64) + assertFalse(SharedFontReaders.isTrusted(emptyList(), release) { listOf(pin) }) + assertFalse(SharedFontReaders.isTrusted(listOf("com.evil"), release) { listOf(pin) }) + assertFalse(SharedFontReaders.isTrusted(listOf(jarn), release) { listOf(other) }) + assertFalse(SharedFontReaders.isTrusted(listOf(jarn), release) { listOf(pin, other) }) + assertFalse(SharedFontReaders.isTrusted(listOf(jarn), release) { emptyList() }) + assertFalse( + SharedFontReaders.isTrusted(listOf(SharedFontReaders.JARN_DEBUG_PACKAGE), release) { + listOf(SharedFontReaders.JARN_DEBUG_CERT_SHA256) + }, + ) + } + + @Test + fun `a debug build also serves Jarngreipr's debug build`() { + val debug = SharedFontReaders.allowed(debugBuild = true) + assertTrue( + SharedFontReaders.isTrusted(listOf(SharedFontReaders.JARN_DEBUG_PACKAGE), debug) { + listOf(SharedFontReaders.JARN_DEBUG_CERT_SHA256) + }, + ) + assertFalse( + SharedFontReaders.isTrusted(listOf(SharedFontReaders.JARN_DEBUG_PACKAGE), debug) { + listOf(SharedFontReaders.JARN_RELEASE_CERT_SHA256) + }, + ) + } + + private fun rowFor(look: SharedLook) = sharedFontsRow(look) { id -> FONT_SHA.takeIf { id == FONT_ID } } + + private fun userFont(id: String) = FontRef.User(id, "Orbitron") + + private fun prefsOf(vararg values: Pair): android.content.SharedPreferences = + Proxy.newProxyInstance( + android.content.SharedPreferences::class.java.classLoader, + arrayOf(android.content.SharedPreferences::class.java), + ) { _, method, args -> + check(method.name == "getString") { "unexpected call: ${method.name}" } + values.toMap()[args[0] as String] ?: args[1] + } as android.content.SharedPreferences + + private companion object { + const val FONT_ID = "3f2b6c1e-8a4d-4e7a-9b1c-0d2e3f4a5b6c" + val FONT_SHA = "ab".repeat(32) + } +} diff --git a/docs/SHARED_THEME.md b/docs/SHARED_THEME.md index af549ea..4ef5c98 100644 --- a/docs/SHARED_THEME.md +++ b/docs/SHARED_THEME.md @@ -1,7 +1,8 @@ # Shared theme -Command Panel publishes its overlay's resolved colors so another app can match them. The contract is -`SharedThemeContract.kt`, a constants-only file a client can copy. +Command Panel publishes its overlay's resolved colors and the applied look's fonts so another app can match them. The +contracts are `SharedThemeContract.kt` (colors, version 1) and `SharedFontsContract.kt` (fonts, version 2), +constants-only files a client can copy. ## Reading the theme @@ -33,6 +34,60 @@ Theme Studio's unsaved draft is never published, and "Companion follows overlay `text_primary` and `text_secondary` meet 4.5:1 on `surface`. `text_tertiary`, `accent`, `danger` and `success` only meet 3:1, so a client with a stricter rule must clamp them. +## Reading the fonts + +``` +content://jr.brian.commandpannel.theme/fonts +``` + +A query returns one row (debug builds serve it on the debug authority, like the palette). Projections, errors, `null` +results and the refused writes work as for `/palette`. + +| Column | Value | +|---|---| +| `version` | Integer, contract version 2 | +| `look_id` | The applied look: a built-in look's name (`TERMINAL`) or `custom:` for a saved look | +| `display_font` | Font for big numbers and titles, or null | +| `display_font_sha256` | SHA-256 of the display font's file (lowercase hex) for a `user:` font, otherwise null | +| `label_font` | Font for labels and body text, or null | +| `label_font_sha256` | SHA-256 of the label font's file for a `user:` font, otherwise null | + +A font value is one of: + +- `bundled:`: an open font Command Panel bundles. The client ships its own copy of the same files + (`app/src/main/res/font/tcc_*.ttf`, licenses in `assets/THIRD_PARTY_NOTICES.txt`). +- `user:`: a font the user imported. Read its file from `fonts/` (below) and cache it by its SHA-256. + +| Key | Family | Files | +|---|---|---| +| `condensed` | Barlow Condensed | `tcc_condensed_semibold`, `tcc_condensed_bold`, `tcc_condensed_extrabold` | +| `condensed_display` | Barlow Condensed ExtraBold | `tcc_condensed_extrabold` | +| `mono` | JetBrains Mono | `tcc_mono_regular`, `tcc_mono_bold` | +| `segment` | DSEG7 Classic Bold | `tcc_segment_bold` | +| `rounded` | Baloo 2 ExtraBold | `tcc_rounded_bold` | +| `stencil` | Black Ops One | `tcc_stencil` | +| `comic` | Bangers | `tcc_comic` | +| `chrome_wide` | Michroma | `tcc_chrome_wide` | +| `serif` | Literata | `tcc_serif_regular`, `tcc_serif_italic` | + +The fonts are resolved the way the overlay draws them: a saved look's own fonts over its base look's, and a look with no +display font of its own publishes its label font as `display_font`. Null means the system font, which is also what an +imported font whose file is gone falls back to. Treat a `bundled:` key you don't know as null. Theme Studio's unsaved +draft is never published. + +### Imported font files + +``` +content://jr.brian.commandpannel.theme/fonts/ +``` + +`ContentResolver.openFileDescriptor(uri, "r")` returns the font file (`font/sfnt`, TrueType or OpenType). It's served +only to an allowlisted app: every current signer of the calling package must match the pin Command Panel holds for that +package. Today that's Jarngreipr (`jr.brian.home`) with its release key; a debug Command Panel also serves Jarngreipr's +debug build (`jr.brian.home.debug`). Any other caller gets a `SecurityException`, a write mode is refused, and an id that +isn't an imported font (including anything with `.` or `/`) gets a `FileNotFoundException`. Bundled fonts aren't +served. + ## Client rules 1. Declare the authority in ``. A release client declares the release authority only: @@ -51,14 +106,18 @@ meet 3:1, so a client with a stricter rule must clamp them. Without this, another app could claim the authority when Command Panel isn't installed. If either check fails, use your own theme. Check again whenever you re-read, since the package can be replaced while your app runs. 3. Ignore a row whose `version` you don't support, and fall back to your own theme. -4. Register a `ContentObserver` on the URI. Also re-read on resume and on configuration changes, because Command Panel - can only send a change while its process is running. +4. Register a `ContentObserver` on each URI you read (`/palette`, `/fonts`); each is notified only when its own row + changes. Also re-read on resume and on configuration changes, because Command Panel can only send a change while its + process is running. ## Compatibility Version 1 is frozen: one row, these 16 integer columns (`version`, `is_dark` and 14 color roles). Never add, remove, rename or reorder a column. Any change to the row means a new `VERSION`. Read columns by name. -Which colors a look resolves to can change without a new version. The roles and their meaning stay the same. +The fonts row is version 2 and frozen the same way: these 6 columns, in this order. A bundled key is never renamed or +reused; a new bundled family only adds a key, which older clients treat as null. + +Which colors and fonts a look resolves to can change without a new version. The roles and their meaning stay the same. -The first version shares colors only. Shapes, fonts and look renderers stay in Command Panel. +Shapes and look renderers stay in Command Panel. diff --git a/scripts/verify-shared-fonts.sh b/scripts/verify-shared-fonts.sh new file mode 100755 index 0000000..19b9be4 --- /dev/null +++ b/scripts/verify-shared-fonts.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Verifies the shared fonts row and the font file gate (#89). +# scripts/verify-shared-fonts.sh [--release] +# +# Default: the debug build (jr.brian.commandpannel.debug), which can switch looks through the DEBUG_BACKGROUND +# broadcast (`--es look`, system/BackgroundImageDebug.kt). --release only reads the release build's row and checks the +# gate, since a release build has no debug broadcast and its look is left alone. +# +# Checks: +# - /palette still answers with version 1 and its 16 columns; +# - /fonts answers with version 2 and the six contract columns; +# - switching looks changes the row: SEGMENT_LCD gives bundled:segment / bundled:mono, E_INK bundled:serif twice, +# AURORA_GLASS null fonts; +# - an applied saved look with an imported font shows user: and a 64-char sha256 (only if one is applied); +# - the shell (an untrusted caller) can't read an imported font file, and traversal paths are refused. +# Look switching needs AssistantService running (the script opens the companion if it isn't). The user's look comes +# back at the end. Whether Jarn FE draws the right font needs a person. +set -uo pipefail + +PKG="jr.brian.commandpannel.debug" +[ "${1:-}" = "--release" ] && PKG="jr.brian.commandpannel" +AUTH="$PKG.theme" +PREFS="/data/user_de/0/$PKG/shared_prefs/command_panel.xml" +ACTION="jr.brian.commandpannel.action.DEBUG_BACKGROUND" + +passes=0; fails=0; skips=0 +pass() { echo " PASS $*"; passes=$((passes + 1)); } +fail() { echo " FAIL $*"; fails=$((fails + 1)); } +skip() { echo " SKIP $*"; skips=$((skips + 1)); } +step() { echo; echo "== $*"; } + +sh_dev() { adb shell "$@" 2>&1 | tr -d '\r'; } +query() { sh_dev content query --uri "content://$AUTH/$1"; } +# The value of column $2 in `content query` output $1 ("Row: 0 a=1, b=NULL, ..."). +col() { echo "$1" | grep -oE "(^|, | )$2=[^,]*" | head -1 | sed -E "s/^(, | )?$2=//"; } +expect_col() { + local row="$1" name="$2" want="$3" got + got="$(col "$row" "$name")" + if [ "$got" = "$want" ]; then pass "$name=$want"; else fail "$name: want $want, got '${got}'"; fi +} +current_look() { sh_dev run-as "$PKG" cat "$PREFS" | grep 'name="overlay_look"' | sed -E 's/.*>([^<]*)<.*/\1/'; } +set_look() { sh_dev am broadcast -a "$ACTION" -p "$PKG" --es look "$1" >/dev/null; sleep 1.5; } + +[ "$(adb devices | grep -c 'device$')" -eq 1 ] || { echo "need exactly one adb device (set ANDROID_SERIAL)" >&2; exit 2; } +sh_dev pm path "$PKG" | grep -q package: || { echo "$PKG isn't installed" >&2; exit 2; } + +step "palette (version 1) is unchanged" +palette="$(query palette)" +expect_col "$palette" version 1 +cols="$(echo "$palette" | grep -oE '[a-z_]+=' | wc -l | tr -d ' ')" +[ "$cols" = 16 ] && pass "16 palette columns" || fail "palette has $cols columns" + +step "fonts row (version 2)" +fonts="$(query fonts)" +echo " info $fonts" +expect_col "$fonts" version 2 +for c in look_id display_font display_font_sha256 label_font label_font_sha256; do + echo "$fonts" | grep -qE "(^| )$c=" && pass "has $c" || fail "missing $c" +done + +look="$(col "$fonts" look_id)" +case "$(col "$fonts" label_font)" in + user:*) + sha="$(col "$fonts" label_font_sha256)" + [[ "$sha" =~ ^[0-9a-f]{64}$ ]] && pass "imported label font has a sha256" || fail "bad sha256 '$sha'" + id="$(col "$fonts" label_font)"; id="${id#user:}" + step "an untrusted caller can't read the font file" + out="$(sh_dev content read --uri "content://$AUTH/fonts/$id")" + echo "$out" | grep -qi "SecurityException\|not allowed" && pass "shell refused" || fail "shell read: ${out:0:120}" + ;; + *) skip "no imported label font applied (apply a saved look with an imported font to cover user: fonts)" ;; +esac + +step "traversal paths are refused" +for p in "fonts/..%2Fshared_prefs%2Fcommand_panel.xml" "fonts/../shared_prefs/command_panel.xml" "fonts/x.ttf"; do + out="$(sh_dev content read --uri "content://$AUTH/$p")" + echo "$out" | grep -qiE "FileNotFound|Exception|Error" && pass "refused $p" || fail "$p returned: ${out:0:120}" +done + +if [ "$PKG" = "jr.brian.commandpannel.debug" ]; then + step "switching looks changes the row" + # The debug broadcast is handled by AssistantService, so make sure it's up. + if ! sh_dev dumpsys activity services "$PKG" | grep -q AssistantService; then + sh_dev am start -W -n "$PKG/jr.brian.commandpannel.MainActivity" --display 0 >/dev/null; sleep 3 + fi + original="$(current_look)" + set_look SEGMENT_LCD + row="$(query fonts)" + expect_col "$row" look_id SEGMENT_LCD + expect_col "$row" display_font bundled:segment + expect_col "$row" label_font bundled:mono + set_look E_INK + row="$(query fonts)" + expect_col "$row" display_font bundled:serif + expect_col "$row" label_font bundled:serif + set_look AURORA_GLASS + row="$(query fonts)" + expect_col "$row" display_font NULL + expect_col "$row" label_font NULL + set_look "${original:-$look}" + [ "$(col "$(query fonts)" look_id)" = "$look" ] && pass "look restored ($look)" || fail "look not restored" +else + skip "look switching (release build has no debug broadcast)" +fi + +echo +echo "passed $passes, failed $fails, skipped $skips" +[ "$fails" -eq 0 ] From 73199bd041332a683a79cc7c97ea7dd24f9e2348 Mon Sep 17 00:00:00 2001 From: Brian Jr Date: Tue, 24 Nov 2026 23:41:40 -0500 Subject: [PATCH 2/2] feat(theme): name the look in the shared fonts row (#89) --- .../commandpannel/system/SharedFontsContract.kt | 5 ++++- .../jr/brian/commandpannel/system/SharedLookFonts.kt | 9 +++++++-- .../jr/brian/commandpannel/system/ThemeProvider.kt | 2 +- .../jr/brian/commandpannel/system/SharedFontsTest.kt | 12 +++++++++--- docs/SHARED_THEME.md | 3 ++- scripts/verify-shared-fonts.sh | 5 +++-- 6 files changed, 26 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt b/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt index 64bc9cf..ca69145 100644 --- a/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt +++ b/app/src/main/java/jr/brian/commandpannel/system/SharedFontsContract.kt @@ -29,6 +29,9 @@ object SharedFontsContract { /** The applied look: a built-in look's name (`TERMINAL`) or `custom:` for a saved look. */ const val COLUMN_LOOK_ID = "look_id" + /** The applied look's name as the user sees it: a saved look's own name, or a built-in look's display name. */ + const val COLUMN_LOOK_NAME = "look_name" + /** Font for big numbers and titles, as a font value (see [PREFIX_BUNDLED] and [PREFIX_USER]), or null. */ const val COLUMN_DISPLAY_FONT = "display_font" @@ -43,7 +46,7 @@ object SharedFontsContract { /** Every column, in the order a query without a projection returns them. */ val COLUMNS = listOf( - COLUMN_VERSION, COLUMN_LOOK_ID, + COLUMN_VERSION, COLUMN_LOOK_ID, COLUMN_LOOK_NAME, COLUMN_DISPLAY_FONT, COLUMN_DISPLAY_FONT_SHA256, COLUMN_LABEL_FONT, COLUMN_LABEL_FONT_SHA256, ) diff --git a/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt b/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt index e06a5dd..b291ace 100644 --- a/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt +++ b/app/src/main/java/jr/brian/commandpannel/system/SharedLookFonts.kt @@ -46,15 +46,20 @@ private fun FontRef?.toShared(userFontSha256: (String) -> String?): SharedFontVa /** * The fonts row for [look]. A role without its own font falls back to the label font, as the overlay's text styles do, * so a client never has to know the fallback rule. [userFontSha256] gives an imported font's digest, or `null` when its - * file is gone. + * file is gone. [builtInName] gives a built-in look's display name. */ -internal fun sharedFontsRow(look: SharedLook, userFontSha256: (String) -> String?): Map { +internal fun sharedFontsRow( + look: SharedLook, + builtInName: (TccUiLook) -> String, + userFontSha256: (String) -> String?, +): Map { val (labelRef, displayRef) = look.fontRefs() val label = labelRef.toShared(userFontSha256) val display = displayRef.toShared(userFontSha256) ?: label return mapOf( SharedFontsContract.COLUMN_VERSION to SharedFontsContract.VERSION, SharedFontsContract.COLUMN_LOOK_ID to look.id, + SharedFontsContract.COLUMN_LOOK_NAME to (look.custom?.name ?: builtInName(look.builtIn ?: TccUiLook.DEFAULT)), SharedFontsContract.COLUMN_DISPLAY_FONT to display?.value, SharedFontsContract.COLUMN_DISPLAY_FONT_SHA256 to display?.sha256, SharedFontsContract.COLUMN_LABEL_FONT to label?.value, diff --git a/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt b/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt index 8c3d87a..000f86a 100644 --- a/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt +++ b/app/src/main/java/jr/brian/commandpannel/system/ThemeProvider.kt @@ -191,7 +191,7 @@ class ThemeProvider : ContentProvider() { } private fun currentFontsRow(ctx: Context): Map = - sharedFontsRow(activeLook.of(Prefs.of(ctx))) { UserFontStore.sha256(ctx, it) } + sharedFontsRow(activeLook.of(Prefs.of(ctx)), { ctx.getString(it.labelRes) }) { UserFontStore.sha256(ctx, it) } private companion object { const val TAG = "ThemeProvider" diff --git a/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt b/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt index 6ec64e9..67d809d 100644 --- a/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt +++ b/app/src/test/java/jr/brian/commandpannel/system/SharedFontsTest.kt @@ -21,7 +21,9 @@ class SharedFontsTest { assertEquals("fonts", SharedFontsContract.PATH) assertEquals("fonts", SharedFontsContract.FILE_PATH) assertEquals( - listOf("version", "look_id", "display_font", "display_font_sha256", "label_font", "label_font_sha256"), + listOf( + "version", "look_id", "look_name", "display_font", "display_font_sha256", "label_font", "label_font_sha256", + ), SharedFontsContract.COLUMNS, ) assertEquals("bundled:", SharedFontsContract.PREFIX_BUNDLED) @@ -49,6 +51,7 @@ class SharedFontsTest { val row = rowFor(SharedLook(TccUiLook.SEGMENT_LCD, null)) assertEquals(2, row[SharedFontsContract.COLUMN_VERSION]) assertEquals("SEGMENT_LCD", row[SharedFontsContract.COLUMN_LOOK_ID]) + assertEquals("name of SEGMENT_LCD", row[SharedFontsContract.COLUMN_LOOK_NAME]) assertEquals("bundled:segment", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) assertEquals("bundled:mono", row[SharedFontsContract.COLUMN_LABEL_FONT]) assertNull(row[SharedFontsContract.COLUMN_DISPLAY_FONT_SHA256]) @@ -71,9 +74,10 @@ class SharedFontsTest { @Test fun `a saved look's imported font is published with its digest`() { - val look = CustomLook(id = "mine", name = "mine", baseLook = TccUiLook.TERMINAL, labelFont = userFont(FONT_ID)) + val look = CustomLook(id = "mine", name = "Mine", baseLook = TccUiLook.TERMINAL, labelFont = userFont(FONT_ID)) val row = rowFor(SharedLook(null, look.colors, look)) assertEquals("custom:mine", row[SharedFontsContract.COLUMN_LOOK_ID]) + assertEquals("Mine", row[SharedFontsContract.COLUMN_LOOK_NAME]) assertEquals("user:$FONT_ID", row[SharedFontsContract.COLUMN_LABEL_FONT]) assertEquals(FONT_SHA, row[SharedFontsContract.COLUMN_LABEL_FONT_SHA256]) assertEquals("bundled:mono", row[SharedFontsContract.COLUMN_DISPLAY_FONT]) @@ -113,6 +117,7 @@ class SharedFontsTest { val prefs = prefsOf(CustomLookStore.LOOK_KEY to LookRef.Custom("gone").key) val row = rowFor(ActiveSharedLook().of(prefs)) assertEquals(TccUiLook.DEFAULT.name, row[SharedFontsContract.COLUMN_LOOK_ID]) + assertEquals("name of ${TccUiLook.DEFAULT.name}", row[SharedFontsContract.COLUMN_LOOK_NAME]) assertNull(row[SharedFontsContract.COLUMN_LABEL_FONT]) } @@ -191,7 +196,8 @@ class SharedFontsTest { ) } - private fun rowFor(look: SharedLook) = sharedFontsRow(look) { id -> FONT_SHA.takeIf { id == FONT_ID } } + private fun rowFor(look: SharedLook) = + sharedFontsRow(look, { "name of ${it.name}" }) { id -> FONT_SHA.takeIf { id == FONT_ID } } private fun userFont(id: String) = FontRef.User(id, "Orbitron") diff --git a/docs/SHARED_THEME.md b/docs/SHARED_THEME.md index 4ef5c98..94d8853 100644 --- a/docs/SHARED_THEME.md +++ b/docs/SHARED_THEME.md @@ -47,6 +47,7 @@ results and the refused writes work as for `/palette`. |---|---| | `version` | Integer, contract version 2 | | `look_id` | The applied look: a built-in look's name (`TERMINAL`) or `custom:` for a saved look | +| `look_name` | The applied look's name as the user sees it: a saved look's own name, or a built-in look's display name in Command Panel's language | | `display_font` | Font for big numbers and titles, or null | | `display_font_sha256` | SHA-256 of the display font's file (lowercase hex) for a `user:` font, otherwise null | | `label_font` | Font for labels and body text, or null | @@ -115,7 +116,7 @@ served. Version 1 is frozen: one row, these 16 integer columns (`version`, `is_dark` and 14 color roles). Never add, remove, rename or reorder a column. Any change to the row means a new `VERSION`. Read columns by name. -The fonts row is version 2 and frozen the same way: these 6 columns, in this order. A bundled key is never renamed or +The fonts row is version 2 and frozen the same way: these 7 columns, in this order. A bundled key is never renamed or reused; a new bundled family only adds a key, which older clients treat as null. Which colors and fonts a look resolves to can change without a new version. The roles and their meaning stay the same. diff --git a/scripts/verify-shared-fonts.sh b/scripts/verify-shared-fonts.sh index 19b9be4..dc4580e 100755 --- a/scripts/verify-shared-fonts.sh +++ b/scripts/verify-shared-fonts.sh @@ -8,7 +8,7 @@ # # Checks: # - /palette still answers with version 1 and its 16 columns; -# - /fonts answers with version 2 and the six contract columns; +# - /fonts answers with version 2 and the seven contract columns, look_name included; # - switching looks changes the row: SEGMENT_LCD gives bundled:segment / bundled:mono, E_INK bundled:serif twice, # AURORA_GLASS null fonts; # - an applied saved look with an imported font shows user: and a 64-char sha256 (only if one is applied); @@ -54,7 +54,7 @@ step "fonts row (version 2)" fonts="$(query fonts)" echo " info $fonts" expect_col "$fonts" version 2 -for c in look_id display_font display_font_sha256 label_font label_font_sha256; do +for c in look_id look_name display_font display_font_sha256 label_font label_font_sha256; do echo "$fonts" | grep -qE "(^| )$c=" && pass "has $c" || fail "missing $c" done @@ -87,6 +87,7 @@ if [ "$PKG" = "jr.brian.commandpannel.debug" ]; then set_look SEGMENT_LCD row="$(query fonts)" expect_col "$row" look_id SEGMENT_LCD + expect_col "$row" look_name "Segment LCD" expect_col "$row" display_font bundled:segment expect_col "$row" label_font bundled:mono set_look E_INK