Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Bundle the design fonts and take Bloom's colors from the wallpaper

Bee385c302059d4
diff --git a/Cargo.lock b/Cargo.lock
index cb1b701..40f4de0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -52,6 +52,19 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -1261,6 +1274,18 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -1270,7 +1295,7 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
+ "r-efi 6.0.0",
"rand_core",
"wasm-bindgen",
]
@@ -2134,6 +2159,17 @@ dependencies = [
"regex-automata",
]
+[[package]]
+name = "material-colors"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57a5bf6a9d1cf6319a36cebc589b9a681a6b1c699e162f27c020877783579cc7"
+dependencies = [
+ "ahash",
+ "indexmap",
+ "serde",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -2296,6 +2332,7 @@ dependencies = [
"cxx-qt-lib",
"dirs",
"hostname",
+ "material-colors",
"nectarlink-core",
"qrcode",
"serde",
@@ -3035,6 +3072,12 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "r-efi"
version = "6.0.0"
@@ -4382,6 +4425,15 @@ version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
@@ -4822,6 +4874,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
[[package]]
name = "wmi"
version = "0.18.4"
diff --git a/Cargo.toml b/Cargo.toml
index f8d90ee..0e6d957 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -34,6 +34,7 @@ hostname = "0.4"
hmac = "0.13"
iroh = "1.3"
iroh-mdns-address-lookup = "0.6"
+material-colors = { version = "0.5", default-features = false, features = ["std", "quantize"] }
n0-future = "0.3"
qrcode = { version = "0.14", default-features = false }
rand = "0.10"
diff --git a/README.md b/README.md
index f51acdb..662e4f7 100644
--- a/README.md
+++ b/README.md
@@ -73,9 +73,10 @@ place and tested; the user-facing features of Phase 1 come next.
- **Capability matrix**: both apps compute which features work for a pair of
devices and what would enable the rest, so the interface never offers
something that can't work.
-- **Windows app**: home and settings, two themes (Bloom and Graphite) in light
- and dark, Mica, a custom title bar with Snap Layouts, and a tray icon. In the
- background it uses about 10 MB of memory (as shown in Task Manager).
+- **Windows app**: home and settings, two themes in light and dark (Bloom,
+ which takes its colors from the desktop wallpaper, and Graphite), Mica, a
+ custom title bar with Snap Layouts, and a tray icon. In the background it
+ uses about 10 MB of memory (as shown in Task Manager).
- **Android app**: pairing, home and settings, Material You colors, a background
connection service, and an identity key protected by the Android Keystore.
- **Command-line client** for development and testing (`nectarlink`).
@@ -134,6 +135,7 @@ core/
nectarlink-cli/ Command-line client for development and testing (GPL)
desktop/app/ Windows app: Rust host, cxx-qt bridge, QML UI (GPL)
android/ Android app: Kotlin and Jetpack Compose (GPL)
+assets/fonts/ Fonts both apps ship with (OFL-1.1)
tools/xtask/ Code generation (theme tokens) and checks
spikes/ Technical experiments with their results
scripts/ Build and check scripts
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index d076164..45a3c2b 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -93,6 +93,26 @@ abstract class UniffiBindgen : DefaultTask() {
}
}
+// ---- Fonts ----
+//
+// The shared fonts in `assets/fonts` (with their licenses) are packaged as
+// app assets under `fonts/`.
+
+/** Copies the bundled fonts and their licenses into `<outputDir>/fonts`. */
+abstract class BundleFonts : DefaultTask() {
+ @get:Inject abstract val fs: FileSystemOperations
+ @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) abstract val fonts: DirectoryProperty
+ @get:OutputDirectory abstract val outputDir: DirectoryProperty
+
+ @TaskAction
+ fun copy() {
+ fs.sync {
+ from(fonts) { include("*.ttf", "OFL-*.txt") }
+ into(outputDir.dir("fonts"))
+ }
+ }
+}
+
val workspaceDir: Directory = rootProject.layout.projectDirectory.dir("..")
val rustAbis: List<String> =
(findProperty("nectarlink.abis") as String?)?.split(",")?.map(String::trim) ?: listOf("arm64-v8a", "x86_64")
@@ -113,8 +133,13 @@ androidComponents {
library.set(cargo.flatMap { it.outputDir.file("${rustAbis.first()}/libnectarlink_ffi.so") })
workspace.set(workspaceDir)
}
+ val fonts = tasks.register<BundleFonts>("bundleFonts$suffix") {
+ description = "Packages the shared fonts as assets."
+ this.fonts.set(workspaceDir.dir("assets/fonts"))
+ }
variant.sources.jniLibs?.addGeneratedSourceDirectory(cargo, CargoNdkBuild::outputDir)
variant.sources.java?.addGeneratedSourceDirectory(bindgen, UniffiBindgen::outputDir)
+ variant.sources.assets?.addGeneratedSourceDirectory(fonts, BundleFonts::outputDir)
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index c1228bc..3e8a276 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -29,7 +29,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.nectarlink.android.R
import app.nectarlink.android.core.CoreState
@@ -56,7 +55,6 @@ fun HomeScreen(
Text(
stringResource(R.string.home_title),
style = MaterialTheme.typography.headlineMedium,
- fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
)
}
@@ -105,7 +103,7 @@ private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {
Text(linkText(device.link), style = MaterialTheme.typography.labelLarge)
}
Spacer(Modifier.height(12.dp))
- Text(device.name, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.SemiBold)
+ Text(device.name, style = MaterialTheme.typography.headlineLarge)
device.model?.let {
Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 2.dp))
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt
index 761f6eb..9d879cd 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt
@@ -42,7 +42,6 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
-import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@@ -50,6 +49,7 @@ import androidx.compose.ui.unit.sp
import app.nectarlink.android.R
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.PairingState
+import app.nectarlink.android.ui.theme.LocalAppFonts
import app.nectarlink.core.DiscoveredDevice
import app.nectarlink.core.PairingFailure
import kotlinx.coroutines.delay
@@ -104,7 +104,6 @@ fun PairingScreen(
else -> if (nearby) stringResource(R.string.pair_nearby_title) else stringResource(R.string.pair_title)
},
style = MaterialTheme.typography.headlineMedium,
- fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(20.dp))
@@ -243,7 +242,7 @@ private fun CodeDigits(code: String) {
modifier = Modifier.size(width = 44.dp, height = 56.dp),
) {
Box(contentAlignment = Alignment.Center) {
- Text(digit.toString(), fontFamily = FontFamily.Monospace, fontSize = 26.sp, fontWeight = FontWeight.Bold)
+ Text(digit.toString(), fontFamily = LocalAppFonts.current.mono, fontSize = 26.sp, fontWeight = FontWeight.Bold)
}
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index ec16360..faaa590 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -34,8 +34,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
-import androidx.compose.ui.text.font.FontFamily
-import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.nectarlink.android.BuildConfig
import app.nectarlink.android.R
@@ -43,6 +41,7 @@ import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.CoreStatus
import app.nectarlink.android.core.Device
import app.nectarlink.android.ui.theme.Appearance
+import app.nectarlink.android.ui.theme.LocalAppFonts
import app.nectarlink.android.ui.theme.Tokens
@Composable
@@ -63,7 +62,6 @@ fun SettingsScreen(
Text(
stringResource(R.string.settings_title),
style = MaterialTheme.typography.headlineMedium,
- fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
)
@@ -141,7 +139,7 @@ fun SettingsScreen(
Text(
it.deviceId,
style = MaterialTheme.typography.bodySmall,
- fontFamily = FontFamily.Monospace,
+ fontFamily = LocalAppFonts.current.mono,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt
index 77d9ab8..978de20 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt
@@ -13,7 +13,9 @@ import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
+import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
@@ -108,5 +110,14 @@ fun NectarlinkTheme(appearance: Appearance = Appearance(), content: @Composable
}
}
}
- MaterialTheme(colorScheme = scheme, shapes = shapes(graphite), content = content)
+ val assets = LocalContext.current.assets
+ val fonts = remember(assets) { AppFonts(assets) }
+ CompositionLocalProvider(LocalAppFonts provides fonts) {
+ MaterialTheme(
+ colorScheme = scheme,
+ shapes = shapes(graphite),
+ typography = remember(fonts, graphite) { typography(fonts, graphite) },
+ content = content,
+ )
+ }
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Type.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Type.kt
new file mode 100644
index 0000000..fd8bf15
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Type.kt
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.ui.theme
+
+import android.content.res.AssetManager
+import androidx.compose.material3.Typography
+import androidx.compose.runtime.Immutable
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.Font
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontVariation
+import androidx.compose.ui.text.font.FontWeight
+
+/**
+ * The fonts bundled with the app (`assets/fonts` in the repository, packaged
+ * as assets under `fonts/`): Figtree for text, Instrument Serif for
+ * Graphite's headings, Space Mono for codes.
+ */
+@Immutable
+class AppFonts(assets: AssetManager) {
+ /** Figtree is a variable font: one file, every weight the app uses. */
+ val sans = FontFamily(
+ listOf(400, 500, 600, 650, 700).map { weight ->
+ Font(
+ "fonts/Figtree.ttf",
+ assets,
+ FontWeight(weight),
+ variationSettings = FontVariation.Settings(FontVariation.weight(weight)),
+ )
+ },
+ )
+ val serif = FontFamily(Font("fonts/InstrumentSerif-Regular.ttf", assets))
+ val mono = FontFamily(
+ Font("fonts/SpaceMono-Regular.ttf", assets),
+ Font("fonts/SpaceMono-Bold.ttf", assets, FontWeight.Bold),
+ )
+}
+
+val LocalAppFonts = staticCompositionLocalOf<AppFonts> { error("NectarlinkTheme provides the fonts") }
+
+/**
+ * Material's type scale (sizes and line heights suit a phone) in the bundled
+ * fonts, with the weights from docs/design/tokens.json: bold headings in
+ * Bloom, serif headings in Graphite.
+ */
+internal fun typography(fonts: AppFonts, graphite: Boolean): Typography {
+ val base = Typography()
+ fun TextStyle.text(weight: Int) = copy(fontFamily = fonts.sans, fontWeight = FontWeight(weight))
+ fun TextStyle.heading() =
+ if (graphite) copy(fontFamily = fonts.serif, fontWeight = FontWeight.Normal) else text(650)
+ return base.copy(
+ displayLarge = base.displayLarge.heading(),
+ displayMedium = base.displayMedium.heading(),
+ displaySmall = base.displaySmall.heading(),
+ headlineLarge = base.headlineLarge.heading(),
+ headlineMedium = base.headlineMedium.heading(),
+ headlineSmall = base.headlineSmall.heading(),
+ titleLarge = base.titleLarge.text(600),
+ titleMedium = base.titleMedium.text(600),
+ titleSmall = base.titleSmall.text(600),
+ bodyLarge = base.bodyLarge.text(400),
+ bodyMedium = base.bodyMedium.text(400),
+ bodySmall = base.bodySmall.text(400),
+ labelLarge = base.labelLarge.text(600),
+ labelMedium = base.labelMedium.text(600),
+ labelSmall = base.labelSmall.text(500),
+ )
+}
diff --git a/assets/fonts/Figtree.ttf b/assets/fonts/Figtree.ttf
new file mode 100644
index 0000000..579e2ab
Binary files /dev/null and b/assets/fonts/Figtree.ttf differ
diff --git a/assets/fonts/InstrumentSerif-Regular.ttf b/assets/fonts/InstrumentSerif-Regular.ttf
new file mode 100644
index 0000000..36fac00
Binary files /dev/null and b/assets/fonts/InstrumentSerif-Regular.ttf differ
diff --git a/assets/fonts/OFL-Figtree.txt b/assets/fonts/OFL-Figtree.txt
new file mode 100644
index 0000000..80b12bb
--- /dev/null
+++ b/assets/fonts/OFL-Figtree.txt
@@ -0,0 +1,93 @@
+Copyright 2022 The Figtree Project Authors (https://github.com/erikdkennedy/figtree)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/assets/fonts/OFL-InstrumentSerif.txt b/assets/fonts/OFL-InstrumentSerif.txt
new file mode 100644
index 0000000..669ce79
--- /dev/null
+++ b/assets/fonts/OFL-InstrumentSerif.txt
@@ -0,0 +1,93 @@
+Copyright 2022 The Instrument Serif Project Authors (https://github.com/Instrument/instrument-serif)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/assets/fonts/OFL-SpaceMono.txt b/assets/fonts/OFL-SpaceMono.txt
new file mode 100644
index 0000000..a72b0a7
--- /dev/null
+++ b/assets/fonts/OFL-SpaceMono.txt
@@ -0,0 +1,93 @@
+Copyright 2016 The Space Mono Project Authors (https://github.com/googlefonts/spacemono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/assets/fonts/README.md b/assets/fonts/README.md
new file mode 100644
index 0000000..e559a93
--- /dev/null
+++ b/assets/fonts/README.md
@@ -0,0 +1,18 @@
+# Fonts
+
+The typefaces both apps ship with, as named in `docs/design/tokens.json`.
+All are under the [SIL Open Font License 1.1](https://openfontlicense.org);
+each license sits next to its font and is packaged with it.
+
+| File | Family | Used for |
+|---|---|---|
+| `Figtree.ttf` | Figtree (variable, weights 300–900) | All text in Bloom; body text in Graphite |
+| `InstrumentSerif-Regular.ttf` | Instrument Serif | Graphite headings |
+| `SpaceMono-Regular.ttf`, `SpaceMono-Bold.ttf` | Space Mono | Codes, IDs and Graphite labels |
+
+Taken unmodified from [google/fonts](https://github.com/google/fonts) at
+commit `6e8069ff8ba3dab2a397fb30e7fbd243aba9b57a` (`ofl/figtree`,
+`ofl/instrumentserif`, `ofl/spacemono`).
+
+The Windows app compiles them into its resources (`desktop/app/build.rs`);
+the Android app packages this folder as assets (`android/app/build.gradle.kts`).
diff --git a/assets/fonts/SpaceMono-Bold.ttf b/assets/fonts/SpaceMono-Bold.ttf
new file mode 100644
index 0000000..2c4f268
Binary files /dev/null and b/assets/fonts/SpaceMono-Bold.ttf differ
diff --git a/assets/fonts/SpaceMono-Regular.ttf b/assets/fonts/SpaceMono-Regular.ttf
new file mode 100644
index 0000000..1cfa365
Binary files /dev/null and b/assets/fonts/SpaceMono-Regular.ttf differ
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index c6bcba9..ea396f6 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -3,7 +3,8 @@ name = "nectarlink-desktop"
description = "Nectarlink for Windows: the desktop app"
version.workspace = true
edition.workspace = true
-rust-version.workspace = true
+# Above the workspace minimum: material-colors needs Rust 1.97.
+rust-version = "1.97"
authors.workspace = true
repository.workspace = true
license = "GPL-3.0-or-later"
@@ -20,6 +21,7 @@ cxx-qt.workspace = true
cxx-qt-lib.workspace = true
dirs.workspace = true
hostname.workspace = true
+material-colors.workspace = true
nectarlink-core.workspace = true
qrcode.workspace = true
serde.workspace = true
@@ -33,8 +35,10 @@ windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
+ "Win32_Graphics_Imaging",
"Win32_System_LibraryLoader",
"Win32_Security",
+ "Win32_System_Com",
"Win32_System_Power",
"Win32_System_Registry",
"Win32_System_Threading",
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index fffddef..d56bb1c 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -1,6 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Builds the QML module `app.nectarlink` (QML files compiled ahead of time,
-//! Rust QObjects, C++ helpers) and links the Windows libraries C++ uses.
+//! Rust QObjects, C++ helpers), compiles in the bundled fonts and links the
+//! Windows libraries C++ uses.
+
+use std::{
+ fs,
+ path::{Path, PathBuf},
+};
use cxx_qt_build::{CxxQtBuilder, QmlFile, QmlModule};
@@ -36,6 +42,28 @@ const QML: &[&str] = &[
/// QML singletons.
const QML_SINGLETONS: &[&str] = &["qml/Tokens.qml", "qml/Theme.qml", "qml/Icons.qml"];
+/// Bundled fonts (in `assets/fonts`), compiled in under `:/fonts/`.
+const FONTS: &[&str] =
+ &["Figtree.ttf", "InstrumentSerif-Regular.ttf", "SpaceMono-Regular.ttf", "SpaceMono-Bold.ttf"];
+
+/// Writes a resource file listing the fonts (they live outside this crate,
+/// so each needs an alias) and returns its path.
+fn fonts_qrc() -> PathBuf {
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts");
+ let mut qrc = String::from("<RCC>\n <qresource prefix=\"/fonts\">\n");
+ for font in FONTS {
+ let path = dir.join(font).canonicalize().unwrap_or_else(|e| panic!("missing font {font}: {e}"));
+ println!("cargo::rerun-if-changed={}", path.display());
+ // rcc takes forward slashes; strip the verbatim prefix canonicalize adds.
+ let path = path.display().to_string().trim_start_matches(r"\\?\").replace('\\', "/");
+ qrc.push_str(&format!(" <file alias=\"{font}\">{path}</file>\n"));
+ }
+ qrc.push_str(" </qresource>\n</RCC>\n");
+ let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("fonts.qrc");
+ fs::write(&out, qrc).expect("write fonts.qrc");
+ out
+}
+
fn main() {
let module = QmlModule::new("app.nectarlink")
.qml_files(QML.iter().map(|f| QmlFile::from(*f)))
@@ -44,6 +72,7 @@ fn main() {
.qt_module("Quick")
.include_dir("cpp")
.cpp_files(["cpp/app_helpers.cpp", "cpp/native_window.h", "cpp/native_window.cpp"])
+ .qrc(fonts_qrc())
.files([
"src/bridge/native.rs",
"src/bridge/app.rs",
diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cpp
index cff5bc3..5b9d2f5 100644
--- a/desktop/app/cpp/app_helpers.cpp
+++ b/desktop/app/cpp/app_helpers.cpp
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "app_helpers.h"
+#include <QtCore/QDir>
#include <QtCore/QtEnvironmentVariables>
+#include <QtGui/QFontDatabase>
#include <QtGui/QGuiApplication>
#include <QtGui/QIcon>
#include <QtGui/QImage>
@@ -44,3 +46,14 @@ void keep_running_without_windows()
{
QGuiApplication::setQuitOnLastWindowClosed(false);
}
+
+int32_t load_bundled_fonts()
+{
+ int32_t loaded = 0;
+ const QDir dir(QStringLiteral(":/fonts"));
+ for (const QString &name : dir.entryList({QStringLiteral("*.ttf")}, QDir::Files)) {
+ if (QFontDatabase::addApplicationFont(dir.filePath(name)) >= 0)
+ ++loaded;
+ }
+ return loaded;
+}
diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.h
index afef0cd..1e05109 100644
--- a/desktop/app/cpp/app_helpers.h
+++ b/desktop/app/cpp/app_helpers.h
@@ -15,3 +15,7 @@ void apply_app_icon();
// Keeps the app running with no windows open (it lives in the tray).
void keep_running_without_windows();
+
+// Registers every font compiled in under :/fonts/ and returns how many
+// loaded. Call after QGuiApplication is created.
+int32_t load_bundled_fonts();
diff --git a/desktop/app/qml/Theme.qml b/desktop/app/qml/Theme.qml
index 5fe51ec..c09fb25 100644
--- a/desktop/app/qml/Theme.qml
+++ b/desktop/app/qml/Theme.qml
@@ -16,10 +16,19 @@ QtObject {
readonly property bool reduceMotion: AppController.reduceMotion
readonly property var bloomSeeds: Tokens.data.themes.bloom.seeds
- readonly property string seed: bloomSeeds[Preferences.seed] ? Preferences.seed : Tokens.data.themes.bloom.defaultSeed
+ // Colors made from the desktop wallpaper (or null until they're known),
+ // in the shape of a preset seed.
+ readonly property var wallpaperSeed: AppController.wallpaperColors !== ""
+ ? JSON.parse(AppController.wallpaperColors) : null
+ // "wallpaper" or a preset name; the wallpaper falls back to the default
+ // preset while its colors are being worked out.
+ readonly property string seed: Preferences.seed === "wallpaper"
+ ? (wallpaperSeed ? "wallpaper" : Tokens.data.themes.bloom.defaultSeed)
+ : (bloomSeeds[Preferences.seed] ? Preferences.seed : Tokens.data.themes.bloom.defaultSeed)
+ readonly property var seedColors: seed === "wallpaper" ? wallpaperSeed : bloomSeeds[seed]
readonly property var palette: graphite
? Tokens.data.themes.graphite.variants[dark ? "slate" : "paper"]
- : bloomSeeds[seed][dark ? "dark" : "light"]
+ : seedColors[dark ? "dark" : "light"]
readonly property var status: graphite ? palette : Tokens.data.themes.bloom.status[dark ? "dark" : "light"]
// ---- Color roles ----
@@ -68,11 +77,10 @@ QtObject {
function pill(height) { return graphite ? shape.full : height / 2 }
// ---- Type ----
- // Bundled fonts (Figtree, Instrument Serif, Space Mono, Caveat) replace
- // these system fallbacks once added to the build.
- readonly property string fontUi: "Segoe UI Variable Text"
- readonly property string fontDisplay: graphite ? "Georgia" : "Segoe UI Variable Display"
- readonly property string fontMono: "Cascadia Mono"
+ // Bundled with the app (assets/fonts).
+ readonly property string fontUi: "Figtree"
+ readonly property string fontDisplay: graphite ? "Instrument Serif" : "Figtree"
+ readonly property string fontMono: "Space Mono"
readonly property var typography: Tokens.data.typography
readonly property var labelStyle: graphite ? Tokens.data.themes.graphite.label : Tokens.data.themes.bloom.label
diff --git a/desktop/app/qml/components/Avatar.qml b/desktop/app/qml/components/Avatar.qml
index 2a1c14c..6a84067 100644
--- a/desktop/app/qml/components/Avatar.qml
+++ b/desktop/app/qml/components/Avatar.qml
@@ -30,7 +30,7 @@ Rectangle {
anchors.centerIn: parent
text: avatar.name.length > 0 ? avatar.name.charAt(0).toUpperCase() : ""
role: "label"
- font.weight: 700
+ weight: 700
color: avatar.ink
}
}
diff --git a/desktop/app/qml/components/NavItem.qml b/desktop/app/qml/components/NavItem.qml
index 41c560d..57b927a 100644
--- a/desktop/app/qml/components/NavItem.qml
+++ b/desktop/app/qml/components/NavItem.qml
@@ -47,7 +47,7 @@ FocusScope {
anchors.topMargin: 4
text: item.text
role: "caption"
- font.weight: Theme.graphite ? 400 : 600
+ weight: Theme.graphite ? 400 : 600
color: item.selected ? Theme.surfaceContent : Theme.surfaceContentVariant
}
Rectangle {
diff --git a/desktop/app/qml/components/Txt.qml b/desktop/app/qml/components/Txt.qml
index 8d91714..95975d6 100644
--- a/desktop/app/qml/components/Txt.qml
+++ b/desktop/app/qml/components/Txt.qml
@@ -18,11 +18,19 @@ Text {
// Pixel size; set this (not font.pixelSize) to resize, so the role's
// tracking scales with it.
property int size: Math.round(graphiteLabel ? Theme.labelStyle.size : spec.size)
+ // Set this (not font.weight) to change the weight: Figtree is a variable
+ // font, and its weight axis is set to match, so in-between weights such
+ // as 650 render exactly instead of snapping to a named style.
+ property int weight: graphiteLabel ? Theme.labelStyle.weight : (isDisplay && Theme.graphite ? 400 : spec.weight)
+
+ readonly property string family: role === "code" || graphiteLabel
+ ? Theme.fontMono : (isDisplay ? Theme.fontDisplay : Theme.fontUi)
color: muted ? Theme.surfaceContentVariant : Theme.surfaceContent
- font.family: role === "code" || graphiteLabel ? Theme.fontMono : (isDisplay ? Theme.fontDisplay : Theme.fontUi)
+ font.family: family
font.pixelSize: size
- font.weight: graphiteLabel ? Theme.labelStyle.weight : (isDisplay && Theme.graphite ? 400 : spec.weight)
+ font.weight: weight
+ font.variableAxes: family === Theme.fontUi ? { "wght": weight } : {}
font.letterSpacing: (graphiteLabel ? Theme.labelStyle.tracking : spec.tracking) * size
font.capitalization: graphiteLabel ? Font.AllUppercase : Font.MixedCase
// Token line heights are CSS-style (a multiple of the font size), not
diff --git a/desktop/app/qml/pages/PairingPanel.qml b/desktop/app/qml/pages/PairingPanel.qml
index 95ee842..6612fdd 100644
--- a/desktop/app/qml/pages/PairingPanel.qml
+++ b/desktop/app/qml/pages/PairingPanel.qml
@@ -101,7 +101,7 @@ Item {
color: Theme.graphite ? "transparent" : Theme.secondaryContainer
border.width: Theme.graphite ? 1 : 0
border.color: Theme.outlineVariant
- Txt { anchors.centerIn: parent; text: index + 1; role: "caption"; font.weight: 700 }
+ Txt { anchors.centerIn: parent; text: index + 1; role: "caption"; weight: 700 }
}
Txt { anchors.verticalCenter: parent.verticalCenter; text: modelData; role: "bodySmall"; muted: true }
}
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index fef622d..7b7f25f 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -79,22 +79,39 @@ Item {
visible: !Theme.graphite
iconPath: Icons.sparkle
title: qsTr("Color")
+ description: qsTr("Match your wallpaper, or pick a color.")
Row {
spacing: 10
Repeater {
- model: Object.keys(Tokens.data.themes.bloom.seeds)
+ model: ["wallpaper"].concat(Object.keys(Tokens.data.themes.bloom.seeds))
delegate: Rectangle {
id: swatch
required property string modelData
- readonly property bool selected: Theme.seed === modelData
+ readonly property bool wallpaper: modelData === "wallpaper"
+ readonly property bool selected: Preferences.seed === "wallpaper"
+ ? wallpaper : Theme.seed === modelData
+ // The wallpaper swatch shows the accent it gives, in the
+ // current mode, with a picture mark on it.
+ readonly property var wallpaperPalette: Theme.wallpaperSeed
+ ? Theme.wallpaperSeed[Theme.dark ? "dark" : "light"] : null
width: 26; height: 26; radius: 13
- color: Tokens.data.themes.bloom.seeds[modelData].seed
+ color: !wallpaper ? Tokens.data.themes.bloom.seeds[modelData].seed
+ : wallpaperPalette ? wallpaperPalette.primary : Theme.surfaceContainerHighest
border.width: selected ? 2 : 0
border.color: Theme.surfaceContent
Accessible.role: Accessible.RadioButton
- Accessible.name: modelData
+ Accessible.name: wallpaper ? qsTr("Wallpaper")
+ : modelData.charAt(0).toUpperCase() + modelData.slice(1)
Accessible.checked: selected
Accessible.onPressAction: Preferences.seed = modelData
+ Icon {
+ visible: swatch.wallpaper
+ anchors.centerIn: parent
+ width: 14; height: 14
+ stroke: 2
+ path: Icons.photo
+ color: swatch.wallpaperPalette ? swatch.wallpaperPalette.onPrimary : Theme.surfaceContent
+ }
HoverHandler { cursorShape: Qt.PointingHandCursor }
TapHandler { onTapped: Preferences.seed = swatch.modelData }
}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 0ffcc7d..6e3b072 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -4,7 +4,10 @@
use std::{
pin::Pin,
- sync::{Mutex, OnceLock},
+ sync::{
+ Mutex, OnceLock,
+ atomic::{AtomicU64, Ordering},
+ },
};
use cxx_qt::{CxxQtThread, CxxQtType, Threading};
@@ -51,6 +54,9 @@ pub mod qobject {
#[qproperty(QString, ringing_from)]
#[qproperty(bool, system_dark)]
#[qproperty(bool, reduce_motion)]
+ /// Bloom colors from the desktop wallpaper, as JSON in the shape of
+ /// a tokens.json seed (`{ seed, light, dark }`); "" until known.
+ #[qproperty(QString, wallpaper_colors)]
#[qproperty(QString, version)]
type AppController = super::AppControllerRust;
@@ -104,6 +110,7 @@ pub struct AppControllerRust {
ringing_from: QString,
system_dark: bool,
reduce_motion: bool,
+ wallpaper_colors: QString,
version: QString,
tray: Option<tray::Tray>,
}
@@ -199,6 +206,30 @@ fn on_tray_event(qt: &CxxQtThread<qobject::AppController>, event: tray::TrayEven
}
}
+/// Bumped per wallpaper refresh, so a slow, older one can't overwrite a
+/// newer result.
+static WALLPAPER_GENERATION: AtomicU64 = AtomicU64::new(0);
+
+/// Works out the wallpaper's colors on a worker thread (decoding a photo
+/// takes a moment) and hands them to QML.
+fn refresh_wallpaper_colors(qt: CxxQtThread<qobject::AppController>) {
+ let generation = WALLPAPER_GENERATION.fetch_add(1, Ordering::SeqCst) + 1;
+ let spawned = std::thread::Builder::new().name("wallpaper-colors".into()).spawn(move || {
+ let seed = win::wallpaper::seed();
+ tracing::debug!(seed = ?seed.map(|s| format!("#{:06X}", s.as_u32())), "wallpaper colors");
+ let json = seed.map(|seed| crate::palette::scheme_json(seed).to_string());
+ if WALLPAPER_GENERATION.load(Ordering::SeqCst) != generation {
+ return;
+ }
+ let _ = qt.queue(move |object| {
+ object.set_wallpaper_colors(QString::from(json.as_deref().unwrap_or_default()));
+ });
+ });
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "can't start reading the wallpaper's colors");
+ }
+}
+
fn ring_device(device: DeviceId, on: bool) {
let Some(node) = core_host::node() else { return };
core_host::spawn(async move {
@@ -246,6 +277,7 @@ impl qobject::AppController {
fn refresh_appearance(mut self: Pin<&mut Self>) {
self.as_mut().set_system_dark(win::system_dark());
self.as_mut().set_reduce_motion(win::reduce_motion());
+ refresh_wallpaper_colors(self.qt_thread());
}
pub fn ring(self: Pin<&mut Self>, device: &QString, on: bool) {
diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rs
index ed6d1b2..601304d 100644
--- a/desktop/app/src/bridge/native.rs
+++ b/desktop/app/src/bridge/native.rs
@@ -11,5 +11,8 @@ pub mod ffi {
fn add_app_icon_image(size: i32, rgba: &[u8]);
fn apply_app_icon();
fn keep_running_without_windows();
+ /// Registers the fonts compiled in under `:/fonts/`; returns how
+ /// many loaded.
+ fn load_bundled_fonts() -> i32;
}
}
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 003a86d..c227b04 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -25,7 +25,8 @@ pub mod qobject {
#[qml_singleton]
/// "bloom" or "graphite".
#[qproperty(QString, theme)]
- /// Bloom color preset: "honey", "sage", "lavender" or "ocean".
+ /// Bloom colors: "wallpaper", or a preset: "honey", "sage", "lavender"
+ /// or "ocean".
#[qproperty(QString, seed)]
/// "system", "light" or "dark".
#[qproperty(QString, color_mode)]
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 4583a94..a6c33c1 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -11,6 +11,7 @@
mod bridge;
mod core_host;
mod logging;
+mod palette;
mod qr;
mod settings;
mod state;
@@ -31,6 +32,9 @@ use nectarlink_core::Platform;
use crate::win::single_instance::{self, Instance};
+/// How many fonts `build.rs` compiles in.
+const BUNDLED_FONTS: i32 = 4;
+
/// Rings the PC when a phone asks ("find my PC").
#[derive(Debug)]
struct DesktopPlatform;
@@ -133,6 +137,11 @@ fn main() -> ExitCode {
app.as_mut().set_application_version(&QString::from(env!("CARGO_PKG_VERSION")));
}
bridge::native::ffi::keep_running_without_windows();
+ // Text falls back to system fonts if these are missing, so it's not fatal.
+ let fonts = bridge::native::ffi::load_bundled_fonts();
+ if fonts < BUNDLED_FONTS {
+ tracing::warn!(loaded = fonts, expected = BUNDLED_FONTS, "some bundled fonts didn't load");
+ }
for size in [16, 20, 24, 32, 40, 48, 64, 256] {
bridge::native::ffi::add_app_icon_image(size, &win::icon::render(size as usize));
}
diff --git a/desktop/app/src/palette.rs b/desktop/app/src/palette.rs
new file mode 100644
index 0000000..ad1a282
--- /dev/null
+++ b/desktop/app/src/palette.rs
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Bloom's colors from a seed color, built like Material You: the most
+//! suitable color in the wallpaper becomes the seed, and the seed spans
+//! tonal palettes that every color role takes a tone from, in a light and a
+//! dark version. The presets in docs/design/tokens.json are built the same
+//! way, so a wallpaper theme looks like one of them.
+
+use material_colors::{
+ color::Rgb,
+ hct::Hct,
+ palette::TonalPalette,
+ quantize::{Quantizer, QuantizerCelebi},
+ score::Score,
+};
+
+/// How many colors an image is reduced to before picking a seed (Android's
+/// value).
+const QUANTIZE_COLORS: usize = 128;
+
+/// The best seed color in an image, or `None` when it has no color worth
+/// building a theme on (black and white, grey, near-empty).
+pub fn seed_from_pixels(pixels: &[Rgb]) -> Option<Rgb> {
+ if pixels.is_empty() {
+ return None;
+ }
+ let quantized = QuantizerCelebi::quantize(pixels, QUANTIZE_COLORS);
+ // A sentinel fallback tells "nothing suitable" apart from a real pick:
+ // pure black has no chroma, so scoring can never choose it.
+ let sentinel = Rgb::new(0, 0, 0);
+ let ranked = Score::score(&quantized.color_to_count, Some(1), Some(sentinel), Some(true));
+ ranked.first().copied().filter(|&c| c != sentinel)
+}
+
+#[derive(Clone, Copy)]
+enum Key {
+ Primary,
+ Secondary,
+ Neutral,
+ NeutralVariant,
+}
+
+/// Bloom's color roles (names as in docs/design/tokens.json) and the tone
+/// each takes from its palette, in light and dark: the Material 3 baseline
+/// tones, except that Bloom's low surface sits at the bottom in dark mode,
+/// so the navigation rail recedes.
+const ROLES: [(&str, Key, i32, i32); 15] = [
+ ("primary", Key::Primary, 40, 80),
+ ("onPrimary", Key::Primary, 100, 20),
+ ("primaryContainer", Key::Primary, 90, 30),
+ ("onPrimaryContainer", Key::Primary, 10, 90),
+ ("secondaryContainer", Key::Secondary, 90, 30),
+ ("onSecondaryContainer", Key::Secondary, 10, 90),
+ ("surface", Key::Neutral, 98, 6),
+ ("surfaceContainerLow", Key::Neutral, 96, 4),
+ ("surfaceContainer", Key::Neutral, 94, 12),
+ ("surfaceContainerHigh", Key::Neutral, 92, 17),
+ ("surfaceContainerHighest", Key::Neutral, 90, 22),
+ ("onSurface", Key::Neutral, 10, 90),
+ ("onSurfaceVariant", Key::NeutralVariant, 30, 80),
+ ("outline", Key::NeutralVariant, 50, 60),
+ ("outlineVariant", Key::NeutralVariant, 80, 30),
+];
+
+/// One Bloom palette: role name to "#RRGGBB".
+pub type Palette = serde_json::Map<String, serde_json::Value>;
+
+/// The palettes a seed spans, with Android's Tonal Spot chromas: calm
+/// accents in the seed's hue, and surfaces and text barely tinted by it. A
+/// loud wallpaper never makes a loud app.
+fn tonal_palettes(seed: Rgb) -> [TonalPalette; 4] {
+ let hue = Hct::new(seed).get_hue();
+ [
+ TonalPalette::of(hue, 36.0),
+ TonalPalette::of(hue, 16.0),
+ TonalPalette::of(hue, 6.0),
+ TonalPalette::of(hue, 8.0),
+ ]
+}
+
+fn palette(palettes: &[TonalPalette; 4], dark: bool) -> Palette {
+ ROLES
+ .iter()
+ .map(|&(name, key, light_tone, dark_tone)| {
+ let color = palettes[key as usize].tone(if dark { dark_tone } else { light_tone });
+ (name.to_owned(), format!("#{:06X}", color.as_u32()).into())
+ })
+ .collect()
+}
+
+/// `{ "seed": "#RRGGBB", "light": {...}, "dark": {...} }`, the shape of a
+/// seed in docs/design/tokens.json.
+pub fn scheme_json(seed: Rgb) -> serde_json::Value {
+ let palettes = tonal_palettes(seed);
+ serde_json::json!({
+ "seed": format!("#{:06X}", seed.as_u32()),
+ "light": palette(&palettes, false),
+ "dark": palette(&palettes, true),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hex(value: &str) -> Rgb {
+ Rgb::from_u32(u32::from_str_radix(value.trim_start_matches('#'), 16).unwrap())
+ }
+
+ /// Hue distance in degrees.
+ fn hue_distance(a: f64, b: f64) -> f64 {
+ let d = (a - b).rem_euclid(360.0);
+ d.min(360.0 - d)
+ }
+
+ /// The presets were tuned by hand, so they aren't reproduced to the
+ /// last digit. What must match is their structure: every role at the
+ /// same tone (so contrast is the same), in the seed's hue.
+ #[test]
+ fn has_the_structure_of_the_token_presets() {
+ let tokens: serde_json::Value =
+ serde_json::from_str(include_str!("../../../docs/design/tokens.json")).unwrap();
+ let seeds = tokens["themes"]["bloom"]["seeds"].as_object().unwrap();
+ assert!(!seeds.is_empty());
+ let mut mismatches = Vec::new();
+ for (name, preset) in seeds {
+ let built = scheme_json(hex(preset["seed"].as_str().unwrap()));
+ for mode in ["light", "dark"] {
+ let roles = preset[mode].as_object().unwrap();
+ assert_eq!(roles.len(), ROLES.len(), "{name} {mode}: roles changed in the tokens");
+ for (role, value) in roles {
+ let ours = Hct::new(hex(built[mode][role].as_str().unwrap()));
+ let theirs = Hct::new(hex(value.as_str().unwrap()));
+ let tone = (ours.get_tone() - theirs.get_tone()).abs();
+ let chromatic = ours.get_chroma() > 10.0 && theirs.get_chroma() > 10.0;
+ let hue = if chromatic { hue_distance(ours.get_hue(), theirs.get_hue()) } else { 0.0 };
+ if tone > 2.0 || hue > 15.0 {
+ mismatches
+ .push(format!("{name} {mode} {role}: tone off by {tone:.1}, hue by {hue:.0}"));
+ }
+ }
+ }
+ }
+ assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
+ }
+
+ #[test]
+ fn json_has_every_role_in_both_modes() {
+ let scheme = scheme_json(Rgb::new(0x3D, 0x7D, 0xA8));
+ assert_eq!(scheme["seed"], "#3D7DA8");
+ for mode in ["light", "dark"] {
+ for (role, ..) in ROLES {
+ let value = scheme[mode][role].as_str().unwrap();
+ assert!(value.len() == 7 && value.starts_with('#'), "{mode} {role}: {value}");
+ }
+ }
+ }
+
+ #[test]
+ fn picks_the_dominant_color_of_an_image() {
+ // Mostly a deep blue, some orange: the seed is the blue.
+ let mut pixels = vec![Rgb::new(0x1E, 0x4F, 0xA8); 900];
+ pixels.extend(vec![Rgb::new(0xE8, 0x8A, 0x2A); 100]);
+ let seed = seed_from_pixels(&pixels).unwrap();
+ let hue = Hct::new(seed).get_hue();
+ assert!((240.0..290.0).contains(&hue), "hue {hue}");
+ }
+
+ #[test]
+ fn grey_images_have_no_seed() {
+ let mut pixels = vec![Rgb::new(0x80, 0x80, 0x80); 500];
+ pixels.extend(vec![Rgb::new(0x20, 0x20, 0x20); 500]);
+ assert_eq!(seed_from_pixels(&pixels), None);
+ assert_eq!(seed_from_pixels(&[]), None);
+ }
+}
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index e247388..5c6cd8a 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -33,7 +33,8 @@ pub enum ColorMode {
#[serde(default, rename_all = "camelCase")]
pub struct Settings {
pub theme: Theme,
- /// Bloom seed preset, e.g. "honey" (see docs/design/tokens.json).
+ /// Bloom colors: "wallpaper" (from the desktop wallpaper) or a preset,
+ /// e.g. "honey" (see docs/design/tokens.json).
pub seed: String,
pub color_mode: ColorMode,
/// Use the Windows 11 Mica backdrop.
@@ -46,7 +47,7 @@ impl Default for Settings {
fn default() -> Self {
Settings {
theme: Theme::default(),
- seed: "honey".into(),
+ seed: "wallpaper".into(),
color_mode: ColorMode::default(),
backdrop: true,
close_to_tray: true,
@@ -120,7 +121,7 @@ mod tests {
fs::write(dir.path().join(FILE_NAME), r#"{ "theme": "graphite" }"#).unwrap();
let loaded = Settings::load(dir.path());
assert_eq!(loaded.theme, Theme::Graphite);
- assert_eq!(loaded.seed, "honey");
+ assert_eq!(loaded.seed, "wallpaper");
fs::write(dir.path().join(FILE_NAME), "{ not json").unwrap();
assert_eq!(Settings::load(dir.path()), Settings::default());
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 7e7b574..762660f 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -10,6 +10,7 @@ pub mod net;
pub mod single_instance;
pub mod sound;
pub mod tray;
+pub mod wallpaper;
use windows::{
Win32::{
diff --git a/desktop/app/src/win/tray.rs b/desktop/app/src/win/tray.rs
index fd41079..a73b45e 100644
--- a/desktop/app/src/win/tray.rs
+++ b/desktop/app/src/win/tray.rs
@@ -42,7 +42,8 @@ pub enum TrayEvent {
Quit,
/// The PC woke from sleep.
Resumed,
- /// Dark mode or the animation setting changed.
+ /// Dark mode, the accent color, the wallpaper or the animation setting
+ /// changed.
AppearanceChanged,
}
@@ -63,6 +64,7 @@ const PBT_APMRESUMEAUTOMATIC: usize = 0x12;
/// NIN_SELECT | NINF_KEY (shellapi.h): the icon was activated with the keyboard.
const NIN_KEYSELECT: u32 = NIN_SELECT | 0x1;
const SPI_SETCLIENTAREAANIMATION: usize = 0x1043;
+const SPI_SETDESKWALLPAPER: usize = 0x0014;
type Handler = Box<dyn Fn(TrayEvent)>;
@@ -292,7 +294,10 @@ unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lpar
// null-terminated string for the duration of the message.
let area =
if lparam.0 == 0 { None } else { unsafe { PCWSTR(lparam.0 as *const u16).to_string().ok() } };
- if area.as_deref() == Some("ImmersiveColorSet") || wparam.0 == SPI_SETCLIENTAREAANIMATION {
+ if area.as_deref() == Some("ImmersiveColorSet")
+ || wparam.0 == SPI_SETCLIENTAREAANIMATION
+ || wparam.0 == SPI_SETDESKWALLPAPER
+ {
emit(TrayEvent::AppearanceChanged);
}
LRESULT(0)
diff --git a/desktop/app/src/win/wallpaper.rs b/desktop/app/src/win/wallpaper.rs
new file mode 100644
index 0000000..2a74fcc
--- /dev/null
+++ b/desktop/app/src/win/wallpaper.rs
@@ -0,0 +1,249 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The desktop wallpaper's seed color, for Bloom's wallpaper colors: the
+//! image is decoded and shrunk with WIC, and its colors are scored like
+//! Android scores a phone's wallpaper. A solid-color background is its own
+//! seed. When neither gives a usable color (a grey photo, an image Windows
+//! can't decode), the Windows accent color is used.
+
+use std::{
+ path::{Path, PathBuf},
+ sync::Mutex,
+ time::SystemTime,
+};
+
+use material_colors::color::Rgb;
+use windows::{
+ Win32::{
+ Foundation::GENERIC_READ,
+ Graphics::{
+ Gdi::{COLOR_DESKTOP, GetSysColor},
+ Imaging::{
+ CLSID_WICImagingFactory, GUID_WICPixelFormat32bppBGR, IWICImagingFactory,
+ WICBitmapDitherTypeNone, WICBitmapInterpolationModeFant, WICBitmapPaletteTypeCustom,
+ WICDecodeMetadataCacheOnDemand,
+ },
+ },
+ System::{
+ Com::{
+ CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
+ },
+ Registry::HKEY_CURRENT_USER,
+ },
+ UI::WindowsAndMessaging::{
+ SPI_GETDESKWALLPAPER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
+ },
+ },
+ core::HSTRING,
+};
+
+use crate::palette;
+
+/// Wallpapers are shrunk to fit this square before their colors are
+/// counted: plenty for picking a seed, and fast.
+const SAMPLE_SIZE: u32 = 128;
+
+/// Where the wallpaper came from, so an unchanged one isn't decoded again
+/// (Windows announces setting changes far more often than wallpapers
+/// change).
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Source {
+ Image { path: PathBuf, modified: Option<SystemTime>, len: u64 },
+ Solid(u32),
+}
+
+static LAST: Mutex<Option<(Source, Option<Rgb>)>> = Mutex::new(None);
+
+/// The seed for the current wallpaper. Decoding takes up to a few hundred
+/// milliseconds for a large photo, so call this off the UI thread.
+pub fn seed() -> Option<Rgb> {
+ let source = current_source();
+ let wallpaper = match &source {
+ Some(source) => {
+ let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
+ match last.as_ref() {
+ Some((previous, seed)) if previous == source => *seed,
+ _ => {
+ let seed = seed_of(source);
+ *last = Some((source.clone(), seed));
+ seed
+ }
+ }
+ }
+ None => None,
+ };
+ wallpaper.or_else(accent_color)
+}
+
+fn current_source() -> Option<Source> {
+ let path = wallpaper_path();
+ if path.as_os_str().is_empty() {
+ // No picture: a solid color. COLORREF is 0x00BBGGRR.
+ // SAFETY: GetSysColor has no preconditions.
+ return Some(Source::Solid(unsafe { GetSysColor(COLOR_DESKTOP) }));
+ }
+ // Windows keeps its own copy of the picture it shows, which outlives the
+ // original being moved or deleted.
+ let transcoded = dirs::config_dir().map(|d| d.join(r"Microsoft\Windows\Themes\TranscodedWallpaper"));
+ [Some(path), transcoded].into_iter().flatten().find_map(|path| {
+ let meta = std::fs::metadata(&path).ok().filter(std::fs::Metadata::is_file)?;
+ Some(Source::Image { path, modified: meta.modified().ok(), len: meta.len() })
+ })
+}
+
+fn seed_of(source: &Source) -> Option<Rgb> {
+ match source {
+ Source::Solid(colorref) => {
+ let [r, g, b, _] = colorref.to_le_bytes();
+ palette::seed_from_pixels(&[Rgb::new(r, g, b)])
+ }
+ Source::Image { path, .. } => match sample(path) {
+ Ok(pixels) => palette::seed_from_pixels(&pixels),
+ Err(e) => {
+ tracing::debug!(error = %e, path = %path.display(), "can't read the wallpaper");
+ None
+ }
+ },
+ }
+}
+
+fn wallpaper_path() -> PathBuf {
+ let mut buf = [0u16; 1024];
+ // SAFETY: SPI_GETDESKWALLPAPER writes at most `uiParam` UTF-16 units,
+ // including the terminator, to the buffer.
+ let ok = unsafe {
+ SystemParametersInfoW(
+ SPI_GETDESKWALLPAPER,
+ buf.len() as u32,
+ Some(buf.as_mut_ptr().cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ )
+ }
+ .is_ok();
+ if !ok {
+ return PathBuf::new();
+ }
+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
+ PathBuf::from(String::from_utf16_lossy(&buf[..len]))
+}
+
+/// The Windows accent color (Settings > Personalization > Colors), which
+/// Windows itself can pick from the wallpaper.
+fn accent_color() -> Option<Rgb> {
+ // 0xAABBGGRR.
+ let value = super::reg_dword(HKEY_CURRENT_USER, r"Software\Microsoft\Windows\DWM", "AccentColor")?;
+ let [r, g, b, _] = value.to_le_bytes();
+ Some(Rgb::new(r, g, b))
+}
+
+/// Initializes COM on this thread for as long as it lives.
+struct Com;
+
+impl Com {
+ fn init() -> windows::core::Result<Com> {
+ // SAFETY: balanced by CoUninitialize in Drop, on the same thread.
+ unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok()?;
+ Ok(Com)
+ }
+}
+
+impl Drop for Com {
+ fn drop(&mut self) {
+ // SAFETY: paired with the successful CoInitializeEx in `init`.
+ unsafe { CoUninitialize() };
+ }
+}
+
+/// Decodes the image and shrinks it to fit `SAMPLE_SIZE`, keeping its
+/// aspect ratio.
+fn sample(path: &Path) -> windows::core::Result<Vec<Rgb>> {
+ let _com = Com::init()?;
+ // SAFETY: plain WIC calls on live interfaces; the pixel buffer is sized
+ // for the width, height and stride passed to CopyPixels.
+ unsafe {
+ let factory: IWICImagingFactory =
+ CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
+ let decoder = factory.CreateDecoderFromFilename(
+ &HSTRING::from(path.as_os_str()),
+ None,
+ GENERIC_READ,
+ WICDecodeMetadataCacheOnDemand,
+ )?;
+ let frame = decoder.GetFrame(0)?;
+ let (mut width, mut height) = (0, 0);
+ frame.GetSize(&mut width, &mut height)?;
+ if width == 0 || height == 0 {
+ return Ok(Vec::new());
+ }
+ let scale = (f64::from(SAMPLE_SIZE) / f64::from(width.max(height))).min(1.0);
+ let (w, h) = (
+ ((f64::from(width) * scale).round() as u32).max(1),
+ ((f64::from(height) * scale).round() as u32).max(1),
+ );
+
+ let scaler = factory.CreateBitmapScaler()?;
+ scaler.Initialize(&frame, w, h, WICBitmapInterpolationModeFant)?;
+ let converter = factory.CreateFormatConverter()?;
+ converter.Initialize(
+ &scaler,
+ &GUID_WICPixelFormat32bppBGR,
+ WICBitmapDitherTypeNone,
+ None,
+ 0.0,
+ WICBitmapPaletteTypeCustom,
+ )?;
+ let stride = w * 4;
+ let mut bgrx = vec![0u8; (stride * h) as usize];
+ converter.CopyPixels(std::ptr::null(), stride, &mut bgrx)?;
+ Ok(bgrx.as_chunks::<4>().0.iter().map(|&[b, g, r, _]| Rgb::new(r, g, b)).collect())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Writes a 64x32 24-bit BMP: left half `left`, right half `right`.
+ fn write_bmp(path: &Path, left: [u8; 3], right: [u8; 3]) {
+ let (w, h) = (64u32, 32u32);
+ let row = w * 3; // already a multiple of 4
+ let mut data = Vec::new();
+ data.extend_from_slice(b"BM");
+ data.extend_from_slice(&(54 + row * h).to_le_bytes());
+ data.extend_from_slice(&[0; 4]);
+ data.extend_from_slice(&54u32.to_le_bytes());
+ data.extend_from_slice(&40u32.to_le_bytes());
+ data.extend_from_slice(&w.to_le_bytes());
+ data.extend_from_slice(&h.to_le_bytes());
+ data.extend_from_slice(&1u16.to_le_bytes());
+ data.extend_from_slice(&24u16.to_le_bytes());
+ data.extend_from_slice(&[0; 24]);
+ for _ in 0..h {
+ for x in 0..w {
+ let [r, g, b] = if x < w / 2 { left } else { right };
+ data.extend_from_slice(&[b, g, r]);
+ }
+ }
+ std::fs::write(path, data).unwrap();
+ }
+
+ #[test]
+ fn samples_an_image_with_wic() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("wall.bmp");
+ write_bmp(&path, [0xC0, 0x30, 0x30], [0x20, 0x40, 0xC0]);
+ let pixels = sample(&path).unwrap();
+ assert_eq!(pixels.len(), 64 * 32, "small images aren't scaled up");
+ assert_eq!(pixels[0], Rgb::new(0xC0, 0x30, 0x30), "channels come out in RGB order");
+ assert_eq!(pixels[63], Rgb::new(0x20, 0x40, 0xC0));
+ assert!(sample(&dir.path().join("missing.png")).is_err());
+ }
+
+ #[test]
+ fn a_solid_background_is_its_own_seed() {
+ // Windows' default "solid color" blue.
+ let colorref = u32::from_le_bytes([0x00, 0x78, 0xD4, 0]);
+ let seed = seed_of(&Source::Solid(colorref)).unwrap();
+ assert_eq!(seed, Rgb::new(0x00, 0x78, 0xD4));
+ assert_eq!(seed_of(&Source::Solid(0x0080_8080)), None, "grey has no seed");
+ }
+}
diff --git a/docs/screenshots/desktop-bloom-home.png b/docs/screenshots/desktop-bloom-home.png
index f88da7b..d3de1d1 100644
Binary files a/docs/screenshots/desktop-bloom-home.png and b/docs/screenshots/desktop-bloom-home.png differ
diff --git a/docs/screenshots/desktop-bloom-settings.png b/docs/screenshots/desktop-bloom-settings.png
index e1d69a9..6d073a8 100644
Binary files a/docs/screenshots/desktop-bloom-settings.png and b/docs/screenshots/desktop-bloom-settings.png differ
diff --git a/docs/screenshots/desktop-graphite-home.png b/docs/screenshots/desktop-graphite-home.png
index 41f035f..5e81d6e 100644
Binary files a/docs/screenshots/desktop-graphite-home.png and b/docs/screenshots/desktop-graphite-home.png differ
diff --git a/docs/screenshots/desktop-graphite-settings.png b/docs/screenshots/desktop-graphite-settings.png
index 80f8de9..ad9b0b2 100644
Binary files a/docs/screenshots/desktop-graphite-settings.png and b/docs/screenshots/desktop-graphite-settings.png differ
diff --git a/docs/screenshots/desktop-pairing.png b/docs/screenshots/desktop-pairing.png
index cc3f799..884ec9c 100644
Binary files a/docs/screenshots/desktop-pairing.png and b/docs/screenshots/desktop-pairing.png differ